@vleap/warps-adapter-multiversx 0.2.0-alpha.6 → 0.2.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { WarpInitConfig, Adapter, WarpAbi, WarpCacheConfig, WarpContractAction, WarpQueryAction, WarpBrand, AdapterWarpBuilder, Warp, WarpChainInfo, WarpContract, WarpContractVerification, AdapterWarpExecutor, WarpExecutable, WarpExecution, WarpActionInputType, WarpChainEnv, AdapterWarpRegistry, WarpRegistryConfigInfo, WarpRegistryInfo, WarpChain, AdapterWarpResults,
|
|
1
|
+
import { WarpInitConfig, Adapter, WarpAbi, WarpCacheConfig, WarpContractAction, WarpQueryAction, WarpBrand, AdapterWarpBuilder, Warp, WarpChainInfo, WarpContract, WarpContractVerification, AdapterWarpExecutor, WarpExecutable, WarpExecution, WarpActionInputType, WarpChainEnv, AdapterWarpRegistry, WarpRegistryConfigInfo, WarpRegistryInfo, WarpChain, AdapterWarpResults, ResolvedInput, WarpExecutionResults, AdapterWarpSerializer, WarpSerializer, WarpNativeValue, BaseWarpActionInputType, WarpAdapterGenericType } from '@vleap/warps';
|
|
2
2
|
import { TypedValue, Type, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, TokenTransfer, Struct, CodeMetadataValue, NothingValue, TransactionOnNetwork, AbiRegistry, Transaction, NetworkEntrypoint, Address } from '@multiversx/sdk-core';
|
|
3
3
|
|
|
4
4
|
declare const WarpMultiversxConstants: {
|
|
@@ -125,8 +125,8 @@ declare class WarpMultiversxResults implements AdapterWarpResults {
|
|
|
125
125
|
private readonly serializer;
|
|
126
126
|
private readonly cache;
|
|
127
127
|
constructor(config: WarpInitConfig);
|
|
128
|
-
getTransactionExecutionResults(warp: Warp,
|
|
129
|
-
extractContractResults(warp: Warp,
|
|
128
|
+
getTransactionExecutionResults(warp: Warp, tx: TransactionOnNetwork): Promise<WarpExecution>;
|
|
129
|
+
extractContractResults(warp: Warp, tx: TransactionOnNetwork, inputs: ResolvedInput[]): Promise<{
|
|
130
130
|
values: any[];
|
|
131
131
|
results: WarpExecutionResults;
|
|
132
132
|
}>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { WarpInitConfig, Adapter, WarpAbi, WarpCacheConfig, WarpContractAction, WarpQueryAction, WarpBrand, AdapterWarpBuilder, Warp, WarpChainInfo, WarpContract, WarpContractVerification, AdapterWarpExecutor, WarpExecutable, WarpExecution, WarpActionInputType, WarpChainEnv, AdapterWarpRegistry, WarpRegistryConfigInfo, WarpRegistryInfo, WarpChain, AdapterWarpResults,
|
|
1
|
+
import { WarpInitConfig, Adapter, WarpAbi, WarpCacheConfig, WarpContractAction, WarpQueryAction, WarpBrand, AdapterWarpBuilder, Warp, WarpChainInfo, WarpContract, WarpContractVerification, AdapterWarpExecutor, WarpExecutable, WarpExecution, WarpActionInputType, WarpChainEnv, AdapterWarpRegistry, WarpRegistryConfigInfo, WarpRegistryInfo, WarpChain, AdapterWarpResults, ResolvedInput, WarpExecutionResults, AdapterWarpSerializer, WarpSerializer, WarpNativeValue, BaseWarpActionInputType, WarpAdapterGenericType } from '@vleap/warps';
|
|
2
2
|
import { TypedValue, Type, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, TokenTransfer, Struct, CodeMetadataValue, NothingValue, TransactionOnNetwork, AbiRegistry, Transaction, NetworkEntrypoint, Address } from '@multiversx/sdk-core';
|
|
3
3
|
|
|
4
4
|
declare const WarpMultiversxConstants: {
|
|
@@ -125,8 +125,8 @@ declare class WarpMultiversxResults implements AdapterWarpResults {
|
|
|
125
125
|
private readonly serializer;
|
|
126
126
|
private readonly cache;
|
|
127
127
|
constructor(config: WarpInitConfig);
|
|
128
|
-
getTransactionExecutionResults(warp: Warp,
|
|
129
|
-
extractContractResults(warp: Warp,
|
|
128
|
+
getTransactionExecutionResults(warp: Warp, tx: TransactionOnNetwork): Promise<WarpExecution>;
|
|
129
|
+
extractContractResults(warp: Warp, tx: TransactionOnNetwork, inputs: ResolvedInput[]): Promise<{
|
|
130
130
|
values: any[];
|
|
131
131
|
results: WarpExecutionResults;
|
|
132
132
|
}>;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var G=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var at=Object.prototype.hasOwnProperty;var it=(i,t)=>{for(var e in t)G(i,e,{get:t[e],enumerable:!0})},st=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of nt(t))!at.call(i,a)&&a!==e&&G(i,a,{get:()=>t[a],enumerable:!(r=rt(t,a))||r.enumerable});return i};var ot=i=>st(G({},"__esModule",{value:!0}),i);var Bt={};it(Bt,{WarpMultiversxAbi:()=>P,WarpMultiversxBrandBuilder:()=>Y,WarpMultiversxBuilder:()=>L,WarpMultiversxConstants:()=>ct,WarpMultiversxContractLoader:()=>M,WarpMultiversxExecutor:()=>W,WarpMultiversxRegistry:()=>Q,WarpMultiversxResults:()=>_,WarpMultiversxSerializer:()=>F,address_value:()=>Tt,biguint_value:()=>ht,boolean_value:()=>wt,codemeta_value:()=>bt,composite_value:()=>gt,esdt_value:()=>J,getMultiversxAdapter:()=>vt,hex_value:()=>Wt,list_value:()=>lt,nothing_value:()=>It,option_value:()=>ut,optional_value:()=>pt,string_value:()=>S,token_value:()=>Ct,u16_value:()=>yt,u32_value:()=>q,u64_value:()=>mt,u8_value:()=>dt,variadic_value:()=>ft});module.exports=ot(Bt);var ct={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var O=require("@multiversx/sdk-core"),V=require("@vleap/warps");var y=require("@multiversx/sdk-core"),v=require("@vleap/warps");var D=require("@multiversx/sdk-core"),B=require("@vleap/warps");var K=require("@vleap/warps");var M=class{constructor(t){this.config=t}async getContract(t,e){try{let o=await W.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:o.ownerAddress,verified:o.isVerified||!1}}catch(r){return K.WarpLogger.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let o=await W.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:o.codeHash,abi:o.source.abi}}catch(r){return K.WarpLogger.error("WarpContractLoader: getVerificationInfo error",r),null}}};var P=class{constructor(t){this.config=t;this.contractLoader=new M(this.config),this.cache=new B.WarpCache(this.config.cache?.type)}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=B.WarpCacheKey.WarpAbi(this.config.env,t);if(e){let s=this.cache.get(r);if(s)return B.WarpLogger.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),s}let a=(0,B.getMainChainInfo)(this.config),u=W.getChainEntrypoint(a,this.config.env).createNetworkProvider();try{let s=await u.getTransaction(t),f=await this.createFromTransaction(s);return e&&e.ttl&&f&&this.cache.set(r,f,e.ttl),f}catch(s){return B.WarpLogger.error("WarpAbiBuilder: Error creating from transaction hash",s),null}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);if(!t.address)throw new Error("WarpActionExecutor: Address not found");let e=(0,B.getMainChainInfo)(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return D.AbiRegistry.create(r.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(B.WarpConstants.IdentifierType.Hash)){let e=t.abi.split(B.WarpConstants.IdentifierParamSeparator)[1],r=await this.createFromTransactionHash(e);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return D.AbiRegistry.create(r.content)}else{let r=await(await fetch(t.abi)).json();return D.AbiRegistry.create(r)}}};var U=require("@multiversx/sdk-core"),w=require("@vleap/warps");var n=require("@multiversx/sdk-core"),b=require("@vleap/warps"),Z=new RegExp(`${b.WarpConstants.ArgParamsSeparator}(.*)`),F=class{constructor(){this.coreSerializer=new b.WarpSerializer}typedToString(t){if(t.hasClassOrSuperclass(n.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(n.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(n.List.ClassName)){let e=t.getItems(),a=e.map(u=>this.typedToString(u).split(b.WarpConstants.ArgParamsSeparator)[0])[0],o=e.map(u=>this.typedToString(u).split(b.WarpConstants.ArgParamsSeparator)[1]);return`list:${a}:${o.join(",")}`}if(t.hasClassOrSuperclass(n.VariadicValue.ClassName)){let e=t.getItems(),a=e.map(u=>this.typedToString(u).split(b.WarpConstants.ArgParamsSeparator)[0])[0],o=e.map(u=>this.typedToString(u).split(b.WarpConstants.ArgParamsSeparator)[1]);return`variadic:${a}:${o.join(",")}`}if(t.hasClassOrSuperclass(n.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(s=>this.typedToString(s).split(b.WarpConstants.ArgParamsSeparator)[0]),a=e.map(s=>this.typedToString(s).split(b.WarpConstants.ArgParamsSeparator)[1]),o=r.join(b.WarpConstants.ArgCompositeSeparator),u=a.join(b.WarpConstants.ArgCompositeSeparator);return`composite(${o}):${u}`}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(n.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(n.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),a=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${a}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.coreSerializer.stringToNative(e)}nativeToTyped(t,e){let r=this.coreSerializer.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new n.CompositeType(...e.split(b.WarpConstants.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new n.StringType;if(t==="uint8")return new n.U8Type;if(t==="uint16")return new n.U16Type;if(t==="uint32")return new n.U32Type;if(t==="uint64")return new n.U64Type;if(t==="biguint")return new n.BigUIntType;if(t==="bool")return new n.BooleanType;if(t==="address")return new n.AddressType;if(t==="token")return new n.TokenIdentifierType;if(t==="hex")return new n.BytesType;if(t==="codemeta")return new n.CodeMetadataType;if(t==="esdt"||t==="nft")return new n.StructType("EsdtTokenPayment",[new n.FieldDefinition("token_identifier","",new n.TokenIdentifierType),new n.FieldDefinition("token_nonce","",new n.U64Type),new n.FieldDefinition("amount","",new n.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new n.NothingValue;if(e==="option"){let a=this.stringToTyped(r);return a instanceof n.NothingValue?n.OptionValue.newMissingTyped(a.getType()):n.OptionValue.newProvided(a)}if(e==="optional"){let a=this.stringToTyped(r);return a instanceof n.NothingValue?n.OptionalValue.newMissing():new n.OptionalValue(a.getType(),a)}if(e==="list"){let[a,o]=r.split(Z,2),s=o.split(",").map(f=>this.stringToTyped(`${a}:${f}`));return new n.List(this.nativeToType(a),s)}if(e==="variadic"){let[a,o]=r.split(Z,2),s=o.split(",").map(f=>this.stringToTyped(`${a}:${f}`));return new n.VariadicValue(new n.VariadicType(this.nativeToType(a)),s)}if(e.startsWith("composite")){let a=e.match(/\(([^)]+)\)/)?.[1],o=r.split(b.WarpConstants.ArgCompositeSeparator),u=a.split(b.WarpConstants.ArgCompositeSeparator),s=o.map((p,g)=>this.stringToTyped(`${u[g]}:${p}`)),f=s.map(p=>p.getType());return new n.CompositeValue(new n.CompositeType(...f),s)}if(e==="string")return r?n.StringValue.fromUTF8(r):new n.NothingValue;if(e==="uint8")return r?new n.U8Value(Number(r)):new n.NothingValue;if(e==="uint16")return r?new n.U16Value(Number(r)):new n.NothingValue;if(e==="uint32")return r?new n.U32Value(Number(r)):new n.NothingValue;if(e==="uint64")return r?new n.U64Value(BigInt(r)):new n.NothingValue;if(e==="biguint")return r?new n.BigUIntValue(BigInt(r)):new n.NothingValue;if(e==="bool")return r?new n.BooleanValue(typeof r=="boolean"?r:r==="true"):new n.NothingValue;if(e==="address")return r?new n.AddressValue(n.Address.newFromBech32(r)):new n.NothingValue;if(e==="token")return r?new n.TokenIdentifierValue(r):new n.NothingValue;if(e==="hex")return r?n.BytesValue.fromHex(r):new n.NothingValue;if(e==="codemeta")return new n.CodeMetadataValue(n.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let a=r.split(b.WarpConstants.ArgCompositeSeparator);return new n.Struct(this.nativeToType("esdt"),[new n.Field(new n.TokenIdentifierValue(a[0]),"token_identifier"),new n.Field(new n.U64Value(BigInt(a[1])),"token_nonce"),new n.Field(new n.BigUIntValue(BigInt(a[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof n.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof n.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof n.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof n.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof n.StringType)return"string";if(t instanceof n.U8Type)return"uint8";if(t instanceof n.U16Type)return"uint16";if(t instanceof n.U32Type)return"uint32";if(t instanceof n.U64Type)return"uint64";if(t instanceof n.BigUIntType)return"biguint";if(t instanceof n.BooleanType)return"bool";if(t instanceof n.AddressType)return"address";if(t instanceof n.TokenIdentifierType)return"token";if(t instanceof n.BytesType)return"hex";if(t instanceof n.CodeMetadataType)return"codemeta";if(t instanceof n.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var _=class{constructor(t){this.config=t;this.abi=new P(t),this.serializer=new F,this.cache=new w.WarpCache(t.cache?.type)}async getTransactionExecutionResults(t,e,r){let a=this.cache.get(w.WarpCacheKey.WarpExecutable(this.config.env,t.meta?.hash||"",e))??[],o=await this.extractContractResults(t,e,r,a),u=(0,w.getNextInfo)(this.config,t,e,o),s=(0,w.applyResultsToMessages)(t,o.results);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:u,values:o.values,results:o.results,messages:s}}async extractContractResults(t,e,r,a){let o=(0,w.getWarpActionByIndex)(t,e),u=[],s={};if(!t.results||o.type!=="contract")return{values:u,results:s};if(!Object.values(t.results).some(I=>I.includes("out")||I.includes("event"))){for(let[I,m]of Object.entries(t.results))s[I]=m;return{values:u,results:await(0,w.evaluateResultsCommon)(t,s,e,a)}}let p=await this.abi.getAbiForAction(o),g=new U.TransactionEventsParser({abi:p}),T=new U.SmartContractTransactionsOutcomeParser({abi:p}).parseExecute({transactionOnNetwork:r,function:o.func||void 0});for(let[I,m]of Object.entries(t.results)){if(m.startsWith(w.WarpConstants.Transform.Prefix))continue;if(m.startsWith("input.")){s[I]=m;continue}let x=(0,w.parseResultsOutIndex)(m);if(x!==null&&x!==e){s[I]=null;continue}let[A,R,E]=m.split(".");if(A==="event"){if(!R||isNaN(Number(E)))continue;let z=Number(E),C=(0,U.findEventsByFirstTopic)(r,R),$=g.parseEvents({events:C})[0],H=Object.values($)[z]||null;u.push(H),s[I]=H&&H.valueOf()}else if(A==="out"||A.startsWith("out[")){if(!R)continue;let z=Number(R),C=T.values[z-1]||null;E&&(C=C[E]||null),C&&typeof C=="object"&&(C="toFixed"in C?C.toFixed():C.valueOf()),u.push(C),s[I]=C&&C.valueOf()}else s[I]=m}return{values:u,results:await(0,w.evaluateResultsCommon)(t,s,e,a)}}async extractQueryResults(t,e,r,a){let o=e.map(p=>this.serializer.typedToString(p)),u=e.map(p=>this.serializer.typedToNative(p)[1]),s={};if(!t.results)return{values:o,results:s};let f=p=>{let g=p.split(".").slice(1).map(T=>parseInt(T)-1);if(g.length===0)return;let d=u[g[0]];for(let T=1;T<g.length;T++){if(d==null)return;d=d[g[T]]}return d};for(let[p,g]of Object.entries(t.results)){if(g.startsWith(w.WarpConstants.Transform.Prefix))continue;let d=(0,w.parseResultsOutIndex)(g);if(d!==null&&d!==r){s[p]=null;continue}g.startsWith("out.")||g==="out"||g.startsWith("out[")?s[p]=f(g)||null:s[p]=g}return{values:o,results:await(0,w.evaluateResultsCommon)(t,s,r,a)}}async resolveWarpResultsRecursively(t){let e=t.warp,r=t.entryActionIndex,a=t.executor,o=t.inputs,u=t.meta,s=new Map,f=new Set,p=this;async function g(m,x=[]){if(s.has(m))return s.get(m);if(f.has(m))throw new Error(`Circular dependency detected at action ${m}`);f.add(m);let A=e.actions[m-1];if(!A)throw new Error(`Action ${m} not found`);let R;if(A.type==="query")R=await a.executeQuery(e,m,x);else if(A.type==="collect")R=await a.executeCollect(e,m,x,u);else throw new Error(`Unsupported or interactive action type: ${A.type}`);if(s.set(m,R),e.results)for(let E of Object.values(e.results)){let C=String(E).match(/^out\[(\d+)\]/);if(C){let $=parseInt(C[1],10);$!==m&&!s.has($)&&await g($)}}return f.delete(m),R}await g(r,o);let d={};for(let m of s.values())for(let[x,A]of Object.entries(m.results))A!==null?d[x]=A:x in d||(d[x]=null);let T=await(0,w.evaluateResultsCommon)(e,d,r,o);return{...s.get(r),action:r,results:T}}};var c=require("@multiversx/sdk-core"),ut=(i,t)=>i?c.OptionValue.newProvided(i):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),pt=(i,t)=>i?new c.OptionalValue(i.getType(),i):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),lt=i=>{if(i.length===0)throw new Error("Cannot create a list from an empty array");let t=i[0].getType();return new c.List(t,i)},ft=i=>c.VariadicValue.fromItems(...i),gt=i=>{let t=i.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),i)},S=i=>c.StringValue.fromUTF8(i),dt=i=>new c.U8Value(i),yt=i=>new c.U16Value(i),q=i=>new c.U32Value(i),mt=i=>new c.U64Value(i),ht=i=>new c.BigUIntValue(BigInt(i)),wt=i=>new c.BooleanValue(i),Tt=i=>new c.AddressValue(c.Address.newFromBech32(i)),Ct=i=>new c.TokenIdentifierValue(i),Wt=i=>c.BytesValue.fromHex(i),J=i=>new c.Struct(new c.StructType("EsdtTokenPayment",[new c.FieldDefinition("token_identifier","",new c.TokenIdentifierType),new c.FieldDefinition("token_nonce","",new c.U64Type),new c.FieldDefinition("amount","",new c.BigUIntType)]),[new c.Field(new c.TokenIdentifierValue(i.token.identifier),"token_identifier"),new c.Field(new c.U64Value(BigInt(i.token.nonce)),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(i.amount)),"amount")]),bt=i=>new c.CodeMetadataValue(c.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(i,"hex")))),It=()=>new c.NothingValue;var W=class i{constructor(t){this.config=t;this.serializer=new F,this.abi=new P(this.config),this.results=new _(this.config)}async createTransaction(t){let e=(0,v.getWarpActionByIndex)(t.warp,t.action),r=null;if(e.type==="transfer")r=await this.createTransferTransaction(t);else if(e.type==="contract")r=await this.createContractCallTransaction(t);else{if(e.type==="query")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(e.type==="collect")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!r)throw new Error(`WarpMultiversxExecutor: Invalid action type (${e.type})`);return r}async createTransferTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let e=y.Address.newFromBech32(this.config.user.wallet),r=new y.TransactionsFactoryConfig({chainID:t.chain.chainId}),a=t.data?Buffer.from(this.serializer.stringToTyped(t.data).valueOf()):null;return new y.TransferTransactionsFactory({config:r}).createTransactionForTransfer(e,{receiver:y.Address.newFromBech32(t.destination),nativeAmount:t.value,data:a?new Uint8Array(a):void 0})}async createContractCallTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let e=(0,v.getWarpActionByIndex)(t.warp,t.action),r=y.Address.newFromBech32(this.config.user.wallet),a=t.args.map(u=>this.serializer.stringToTyped(u)),o=new y.TransactionsFactoryConfig({chainID:t.chain.chainId});return new y.SmartContractTransactionsFactory({config:o}).createTransactionForExecute(r,{contract:y.Address.newFromBech32(t.destination),function:"func"in e&&e.func||"",gasLimit:"gasLimit"in e?BigInt(e.gasLimit||0):0n,arguments:a,nativeTransferAmount:t.value})}async executeQuery(t){let e=(0,v.getWarpActionByIndex)(t.warp,t.action);if(e.type!=="query")throw new Error(`WarpMultiversxExecutor: Invalid action type for executeQuery: ${e.type}`);let r=await this.abi.getAbiForAction(e),a=t.args.map(E=>this.serializer.stringToTyped(E)),o=i.getChainEntrypoint(t.chain,this.config.env),u=y.Address.newFromBech32(t.destination),s=o.createSmartContractController(r),f=s.createQuery({contract:u,function:e.func||"",arguments:a}),p=await s.runQuery(f),g=p.returnCode==="ok",d=new y.ArgSerializer,T=r.getEndpoint(p.function||e.func||""),I=(p.returnDataParts||[]).map(E=>Buffer.from(E)),m=d.buffersToValues(I,T.output),{values:x,results:A}=await this.results.extractQueryResults(t.warp,m,t.action,t.resolvedInputs),R=(0,v.getNextInfo)(this.config,t.warp,t.action,A);return{success:g,warp:t.warp,action:t.action,user:this.config.user?.wallet||null,txHash:null,next:R,values:x,results:A,messages:(0,v.applyResultsToMessages)(t.warp,A)}}async preprocessInput(t,e,r,a){if(r==="esdt"){let[o,u,s,f]=a.split(v.WarpConstants.ArgCompositeSeparator);if(f)return e;let p=new y.Token({identifier:o,nonce:BigInt(u)});if(!new y.TokenComputer().isFungible(p))return e;let T=(0,v.findKnownTokenById)(o)?.decimals;if(T||(T=(await(await fetch(`${t.apiUrl}/tokens/${o}`)).json()).decimals),!T)throw new Error(`WarpActionExecutor: Decimals not found for token ${o}`);let I=J(new y.TokenTransfer({token:p,amount:(0,v.shiftBigintBy)(s,T)}));return this.serializer.typedToString(I)+v.WarpConstants.ArgCompositeSeparator+T}return e}static getChainEntrypoint(t,e){let r="warp-sdk",a="api";return e==="devnet"?new y.DevnetEntrypoint(t.apiUrl,a,r):e==="testnet"?new y.TestnetEntrypoint(t.apiUrl,a,r):new y.MainnetEntrypoint(t.apiUrl,a,r)}};var L=class{constructor(t){this.config=t,this.cache=new V.WarpCache(t.cache?.type),this.core=new V.WarpBuilder(t)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=(0,V.getMainChainInfo)(this.config),r=new O.TransactionsFactoryConfig({chainID:e.chainId}),a=new O.TransferTransactionsFactory({config:r}),o=O.Address.newFromBech32(this.config.user.wallet),u=JSON.stringify(t),s=a.createTransactionForTransfer(o,{receiver:O.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(u))});return s.gasLimit=s.gasLimit+BigInt(2e6),s}async createFromTransaction(t,e=!1){let r=await this.core.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=V.WarpCacheKey.Warp(this.config.env,t);if(e){let s=this.cache.get(r);if(s)return V.WarpLogger.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),s}let a=(0,V.getMainChainInfo)(this.config),u=W.getChainEntrypoint(a,this.config.env).createNetworkProvider();try{let s=await u.getTransaction(t),f=await this.createFromTransaction(s);return e&&e.ttl&&f&&this.cache.set(r,f,e.ttl),f}catch(s){return V.WarpLogger.error("WarpBuilder: Error creating from transaction hash",s),null}}};var l=require("@multiversx/sdk-core"),h=require("@vleap/warps");var X={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 j=i=>({hash:i.hash.toString("hex"),alias:i.alias?.toString()||null,trust:i.trust.toString(),owner:i.owner.toString(),createdAt:i.created_at.toNumber(),upgradedAt:i.upgraded_at?.toNumber(),brand:i.brand?.toString("hex")||null,upgrade:i.upgrade?.toString("hex")||null}),tt=i=>({unitPrice:BigInt(i.unit_price.toString()),admins:i.admins.map(t=>t.toBech32())});var Q=class{constructor(t){this.config=t,this.cache=new h.WarpCache(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let a=l.Address.newFromBech32(this.config.user.wallet),o=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,u=()=>e&&r?[l.BytesValue.fromHex(t),l.BytesValue.fromUTF8(e),l.BytesValue.fromHex(r)]:e?[l.BytesValue.fromHex(t),l.BytesValue.fromUTF8(e)]:[l.BytesValue.fromHex(t)];return this.getFactory().createTransactionForExecute(a,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:o(),arguments:u()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[l.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[l.BytesValue.fromUTF8(t),l.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[l.BytesValue.fromHex(t),l.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[l.BytesValue.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[l.BytesValue.fromHex(t),new l.AddressValue(new l.Address(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[l.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[l.BytesValue.fromHex(t),l.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=h.WarpCacheKey.RegistryInfo(this.config.env,t),a=e?this.cache.get(r):null;if(a)return h.WarpLogger.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),a;let o=this.getRegistryContractAddress(),u=this.getController(),s=u.createQuery({contract:o,function:"getInfoByAlias",arguments:[l.BytesValue.fromUTF8(t)]}),f=await u.runQuery(s),[p]=u.parseQueryResponse(f),g=p?j(p):null,d=g?.brand?await this.fetchBrand(g.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:g,brand:d},e.ttl),{registryInfo:g,brand:d}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=h.WarpCacheKey.RegistryInfo(this.config.env,t);if(e){let d=this.cache.get(r);if(d)return h.WarpLogger.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let a=this.getRegistryContractAddress(),o=this.getController(),u=o.createQuery({contract:a,function:"getInfoByHash",arguments:[l.BytesValue.fromHex(t)]}),s=await o.runQuery(u),[f]=o.parseQueryResponse(s),p=f?j(f):null,g=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:g},e.ttl),{registryInfo:p,brand:g}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:r,function:"getUserWarps",arguments:[new l.AddressValue(new l.Address(e))]}),u=await a.runQuery(o),[s]=a.parseQueryResponse(u);return s.map(j)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:r,function:"getUserBrands",arguments:[new l.AddressValue(new l.Address(e))]}),u=await a.runQuery(o),[s]=a.parseQueryResponse(u),f=s.map(d=>d.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(f.map(d=>this.fetchBrand(d,p)))).filter(d=>d!==null)}catch{return[]}}async getChainInfos(t){let e=h.WarpCacheKey.ChainInfos(this.config.env);if(t&&t.ttl){let p=this.cache.get(e);if(p)return h.WarpLogger.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:r,function:"getChains",arguments:[]}),u=await a.runQuery(o),[s]=a.parseQueryResponse(u),f=s.map(h.toTypedChainInfo);if(t&&t.ttl){for(let p of f)this.cache.set(h.WarpCacheKey.ChainInfo(this.config.env,p.chain),p,t.ttl);this.cache.set(e,f,t.ttl)}return f}async getChainInfo(t,e){try{let r=h.WarpCacheKey.ChainInfo(this.config.env,t),a=e?this.cache.get(r):null;if(a)return h.WarpLogger.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),a;let o=this.getRegistryContractAddress(),u=this.getController(),s=u.createQuery({contract:o,function:"getChain",arguments:[l.BytesValue.fromUTF8(t)]}),f=await u.runQuery(s),[p]=u.parseQueryResponse(f),g=p?(0,h.toTypedChainInfo)(p):null;return e&&e.ttl&&g&&this.cache.set(r,g,e.ttl),g}catch{return null}}async setChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"setChain",gasLimit:BigInt(1e7),arguments:[S(t.name),S(t.displayName),S(t.chainId),q(t.blockTime),S(t.addressHrp),S(t.apiUrl),S(t.explorerUrl),S(t.nativeToken)]})}async removeChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"removeChain",gasLimit:BigInt(1e7),arguments:[S(t)]})}async fetchBrand(t,e){let r=h.WarpCacheKey.Brand(this.config.env,t),a=e?this.cache.get(r):null;if(a)return h.WarpLogger.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),a;let o=(0,h.getMainChainInfo)(this.config),s=W.getChainEntrypoint(o,this.config.env).createNetworkProvider();try{let f=await s.getTransaction(t),p=JSON.parse(f.data.toString());return p.meta={hash:f.hash,creator:f.sender.bech32(),createdAt:new Date(f.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,p,e.ttl),p}catch{return null}}getRegistryContractAddress(){return l.Address.newFromBech32(this.config.registry?.contract||h.WarpConfig.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),a=r?tt(r):null;this.registryConfig=a||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=(0,h.getMainChainInfo)(this.config),e=new l.TransactionsFactoryConfig({chainID:t.chainId}),r=l.AbiRegistry.create(X);return new l.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=(0,h.getMainChainInfo)(this.config),e=W.getChainEntrypoint(t,this.config.env),r=l.AbiRegistry.create(X);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var vt=i=>({chain:"multiversx",builder:new L(i),executor:new W(i),results:new _(i),serializer:new F,registry:new Q(i)});var k=require("@multiversx/sdk-core"),N=require("@vleap/warps"),et=require("buffer");var Y=class{constructor(t){this.config=t,this.core=new N.WarpBrandBuilder(t)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=(0,N.getMainChainInfo)(this.config),r=new k.TransactionsFactoryConfig({chainID:e.chainId}),a=new k.TransferTransactionsFactory({config:r}),o=k.Address.newFromBech32(this.config.user.wallet),u=JSON.stringify(t);return a.createTransactionForNativeTokenTransfer(o,{receiver:k.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(et.Buffer.from(u))})}async createFromTransaction(t,e=!1){return await this.core.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=(0,N.getMainChainInfo)(this.config),a=W.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t);return this.createFromTransaction(o)}catch(o){return N.WarpLogger.error("BrandBuilder: Error creating from transaction hash",o),null}}};0&&(module.exports={WarpMultiversxAbi,WarpMultiversxBrandBuilder,WarpMultiversxBuilder,WarpMultiversxConstants,WarpMultiversxContractLoader,WarpMultiversxExecutor,WarpMultiversxRegistry,WarpMultiversxResults,WarpMultiversxSerializer,address_value,biguint_value,boolean_value,codemeta_value,composite_value,esdt_value,getMultiversxAdapter,hex_value,list_value,nothing_value,option_value,optional_value,string_value,token_value,u16_value,u32_value,u64_value,u8_value,variadic_value});
|
|
1
|
+
"use strict";var G=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var at=Object.prototype.hasOwnProperty;var it=(i,t)=>{for(var e in t)G(i,e,{get:t[e],enumerable:!0})},st=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of nt(t))!at.call(i,a)&&a!==e&&G(i,a,{get:()=>t[a],enumerable:!(r=rt(t,a))||r.enumerable});return i};var ot=i=>st(G({},"__esModule",{value:!0}),i);var xt={};it(xt,{WarpMultiversxAbi:()=>P,WarpMultiversxBrandBuilder:()=>Y,WarpMultiversxBuilder:()=>L,WarpMultiversxConstants:()=>ct,WarpMultiversxContractLoader:()=>M,WarpMultiversxExecutor:()=>W,WarpMultiversxRegistry:()=>Q,WarpMultiversxResults:()=>_,WarpMultiversxSerializer:()=>F,address_value:()=>Tt,biguint_value:()=>ht,boolean_value:()=>wt,codemeta_value:()=>bt,composite_value:()=>gt,esdt_value:()=>J,getMultiversxAdapter:()=>vt,hex_value:()=>Wt,list_value:()=>lt,nothing_value:()=>It,option_value:()=>ut,optional_value:()=>pt,string_value:()=>S,token_value:()=>Ct,u16_value:()=>yt,u32_value:()=>q,u64_value:()=>mt,u8_value:()=>dt,variadic_value:()=>ft});module.exports=ot(xt);var ct={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};var O=require("@multiversx/sdk-core"),V=require("@vleap/warps");var y=require("@multiversx/sdk-core"),v=require("@vleap/warps");var D=require("@multiversx/sdk-core"),x=require("@vleap/warps");var K=require("@vleap/warps");var M=class{constructor(t){this.config=t}async getContract(t,e){try{let o=await W.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:o.ownerAddress,verified:o.isVerified||!1}}catch(r){return K.WarpLogger.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let o=await W.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:o.codeHash,abi:o.source.abi}}catch(r){return K.WarpLogger.error("WarpContractLoader: getVerificationInfo error",r),null}}};var P=class{constructor(t){this.config=t;this.contractLoader=new M(this.config),this.cache=new x.WarpCache(this.config.cache?.type)}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=x.WarpCacheKey.WarpAbi(this.config.env,t);if(e){let s=this.cache.get(r);if(s)return x.WarpLogger.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),s}let a=(0,x.getMainChainInfo)(this.config),u=W.getChainEntrypoint(a,this.config.env).createNetworkProvider();try{let s=await u.getTransaction(t),f=await this.createFromTransaction(s);return e&&e.ttl&&f&&this.cache.set(r,f,e.ttl),f}catch(s){return x.WarpLogger.error("WarpAbiBuilder: Error creating from transaction hash",s),null}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);if(!t.address)throw new Error("WarpActionExecutor: Address not found");let e=(0,x.getMainChainInfo)(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return D.AbiRegistry.create(r.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(x.WarpConstants.IdentifierType.Hash)){let e=t.abi.split(x.WarpConstants.IdentifierParamSeparator)[1],r=await this.createFromTransactionHash(e);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return D.AbiRegistry.create(r.content)}else{let r=await(await fetch(t.abi)).json();return D.AbiRegistry.create(r)}}};var U=require("@multiversx/sdk-core"),w=require("@vleap/warps");var n=require("@multiversx/sdk-core"),b=require("@vleap/warps"),Z=new RegExp(`${b.WarpConstants.ArgParamsSeparator}(.*)`),F=class{constructor(){this.coreSerializer=new b.WarpSerializer}typedToString(t){if(t.hasClassOrSuperclass(n.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(n.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(n.List.ClassName)){let e=t.getItems(),a=e.map(u=>this.typedToString(u).split(b.WarpConstants.ArgParamsSeparator)[0])[0],o=e.map(u=>this.typedToString(u).split(b.WarpConstants.ArgParamsSeparator)[1]);return`list:${a}:${o.join(",")}`}if(t.hasClassOrSuperclass(n.VariadicValue.ClassName)){let e=t.getItems(),a=e.map(u=>this.typedToString(u).split(b.WarpConstants.ArgParamsSeparator)[0])[0],o=e.map(u=>this.typedToString(u).split(b.WarpConstants.ArgParamsSeparator)[1]);return`variadic:${a}:${o.join(",")}`}if(t.hasClassOrSuperclass(n.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(s=>this.typedToString(s).split(b.WarpConstants.ArgParamsSeparator)[0]),a=e.map(s=>this.typedToString(s).split(b.WarpConstants.ArgParamsSeparator)[1]),o=r.join(b.WarpConstants.ArgCompositeSeparator),u=a.join(b.WarpConstants.ArgCompositeSeparator);return`composite(${o}):${u}`}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(n.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(n.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),a=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${a}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.coreSerializer.stringToNative(e)}nativeToTyped(t,e){let r=this.coreSerializer.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new n.CompositeType(...e.split(b.WarpConstants.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new n.StringType;if(t==="uint8")return new n.U8Type;if(t==="uint16")return new n.U16Type;if(t==="uint32")return new n.U32Type;if(t==="uint64")return new n.U64Type;if(t==="biguint")return new n.BigUIntType;if(t==="bool")return new n.BooleanType;if(t==="address")return new n.AddressType;if(t==="token")return new n.TokenIdentifierType;if(t==="hex")return new n.BytesType;if(t==="codemeta")return new n.CodeMetadataType;if(t==="esdt"||t==="nft")return new n.StructType("EsdtTokenPayment",[new n.FieldDefinition("token_identifier","",new n.TokenIdentifierType),new n.FieldDefinition("token_nonce","",new n.U64Type),new n.FieldDefinition("amount","",new n.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new n.NothingValue;if(e==="option"){let a=this.stringToTyped(r);return a instanceof n.NothingValue?n.OptionValue.newMissingTyped(a.getType()):n.OptionValue.newProvided(a)}if(e==="optional"){let a=this.stringToTyped(r);return a instanceof n.NothingValue?n.OptionalValue.newMissing():new n.OptionalValue(a.getType(),a)}if(e==="list"){let[a,o]=r.split(Z,2),s=o.split(",").map(f=>this.stringToTyped(`${a}:${f}`));return new n.List(this.nativeToType(a),s)}if(e==="variadic"){let[a,o]=r.split(Z,2),s=o.split(",").map(f=>this.stringToTyped(`${a}:${f}`));return new n.VariadicValue(new n.VariadicType(this.nativeToType(a)),s)}if(e.startsWith("composite")){let a=e.match(/\(([^)]+)\)/)?.[1],o=r.split(b.WarpConstants.ArgCompositeSeparator),u=a.split(b.WarpConstants.ArgCompositeSeparator),s=o.map((p,g)=>this.stringToTyped(`${u[g]}:${p}`)),f=s.map(p=>p.getType());return new n.CompositeValue(new n.CompositeType(...f),s)}if(e==="string")return r?n.StringValue.fromUTF8(r):new n.NothingValue;if(e==="uint8")return r?new n.U8Value(Number(r)):new n.NothingValue;if(e==="uint16")return r?new n.U16Value(Number(r)):new n.NothingValue;if(e==="uint32")return r?new n.U32Value(Number(r)):new n.NothingValue;if(e==="uint64")return r?new n.U64Value(BigInt(r)):new n.NothingValue;if(e==="biguint")return r?new n.BigUIntValue(BigInt(r)):new n.NothingValue;if(e==="bool")return r?new n.BooleanValue(typeof r=="boolean"?r:r==="true"):new n.NothingValue;if(e==="address")return r?new n.AddressValue(n.Address.newFromBech32(r)):new n.NothingValue;if(e==="token")return r?new n.TokenIdentifierValue(r):new n.NothingValue;if(e==="hex")return r?n.BytesValue.fromHex(r):new n.NothingValue;if(e==="codemeta")return new n.CodeMetadataValue(n.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let a=r.split(b.WarpConstants.ArgCompositeSeparator);return new n.Struct(this.nativeToType("esdt"),[new n.Field(new n.TokenIdentifierValue(a[0]),"token_identifier"),new n.Field(new n.U64Value(BigInt(a[1])),"token_nonce"),new n.Field(new n.BigUIntValue(BigInt(a[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof n.OptionType)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof n.OptionalType)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof n.ListType)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof n.VariadicType)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof n.StringType)return"string";if(t instanceof n.U8Type)return"uint8";if(t instanceof n.U16Type)return"uint16";if(t instanceof n.U32Type)return"uint32";if(t instanceof n.U64Type)return"uint64";if(t instanceof n.BigUIntType)return"biguint";if(t instanceof n.BooleanType)return"bool";if(t instanceof n.AddressType)return"address";if(t instanceof n.TokenIdentifierType)return"token";if(t instanceof n.BytesType)return"hex";if(t instanceof n.CodeMetadataType)return"codemeta";if(t instanceof n.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var _=class{constructor(t){this.config=t;this.abi=new P(t),this.serializer=new F,this.cache=new w.WarpCache(t.cache?.type)}async getTransactionExecutionResults(t,e){let[r,a]=(0,w.findWarpExecutableAction)(t),o=this.cache.get(w.WarpCacheKey.WarpExecutable(this.config.env,t.meta?.hash||"",a))??[],u=await this.extractContractResults(t,e,o),s=(0,w.getNextInfo)(this.config,t,a,u),f=(0,w.applyResultsToMessages)(t,u.results);return{success:e.status.isSuccessful(),warp:t,action:a,user:this.config.user?.wallet||null,txHash:e.hash,next:s,values:u.values,results:u.results,messages:f}}async extractContractResults(t,e,r){let[a,o]=(0,w.findWarpExecutableAction)(t),u=[],s={};if(!t.results||a.type!=="contract")return{values:u,results:s};if(!Object.values(t.results).some(I=>I.includes("out")||I.includes("event"))){for(let[I,m]of Object.entries(t.results))s[I]=m;return{values:u,results:await(0,w.evaluateResultsCommon)(t,s,o,r)}}let p=await this.abi.getAbiForAction(a),g=new U.TransactionEventsParser({abi:p}),T=new U.SmartContractTransactionsOutcomeParser({abi:p}).parseExecute({transactionOnNetwork:e,function:a.func||void 0});for(let[I,m]of Object.entries(t.results)){if(m.startsWith(w.WarpConstants.Transform.Prefix))continue;if(m.startsWith("input.")){s[I]=m;continue}let B=(0,w.parseResultsOutIndex)(m);if(B!==null&&B!==o){s[I]=null;continue}let[A,R,E]=m.split(".");if(A==="event"){if(!R||isNaN(Number(E)))continue;let z=Number(E),C=(0,U.findEventsByFirstTopic)(e,R),$=g.parseEvents({events:C})[0],H=Object.values($)[z]||null;u.push(H),s[I]=H&&H.valueOf()}else if(A==="out"||A.startsWith("out[")){if(!R)continue;let z=Number(R),C=T.values[z-1]||null;E&&(C=C[E]||null),C&&typeof C=="object"&&(C="toFixed"in C?C.toFixed():C.valueOf()),u.push(C),s[I]=C&&C.valueOf()}else s[I]=m}return{values:u,results:await(0,w.evaluateResultsCommon)(t,s,o,r)}}async extractQueryResults(t,e,r,a){let o=e.map(p=>this.serializer.typedToString(p)),u=e.map(p=>this.serializer.typedToNative(p)[1]),s={};if(!t.results)return{values:o,results:s};let f=p=>{let g=p.split(".").slice(1).map(T=>parseInt(T)-1);if(g.length===0)return;let d=u[g[0]];for(let T=1;T<g.length;T++){if(d==null)return;d=d[g[T]]}return d};for(let[p,g]of Object.entries(t.results)){if(g.startsWith(w.WarpConstants.Transform.Prefix))continue;let d=(0,w.parseResultsOutIndex)(g);if(d!==null&&d!==r){s[p]=null;continue}g.startsWith("out.")||g==="out"||g.startsWith("out[")?s[p]=f(g)||null:s[p]=g}return{values:o,results:await(0,w.evaluateResultsCommon)(t,s,r,a)}}async resolveWarpResultsRecursively(t){let e=t.warp,r=t.entryActionIndex,a=t.executor,o=t.inputs,u=t.meta,s=new Map,f=new Set,p=this;async function g(m,B=[]){if(s.has(m))return s.get(m);if(f.has(m))throw new Error(`Circular dependency detected at action ${m}`);f.add(m);let A=e.actions[m-1];if(!A)throw new Error(`Action ${m} not found`);let R;if(A.type==="query")R=await a.executeQuery(e,m,B);else if(A.type==="collect")R=await a.executeCollect(e,m,B,u);else throw new Error(`Unsupported or interactive action type: ${A.type}`);if(s.set(m,R),e.results)for(let E of Object.values(e.results)){let C=String(E).match(/^out\[(\d+)\]/);if(C){let $=parseInt(C[1],10);$!==m&&!s.has($)&&await g($)}}return f.delete(m),R}await g(r,o);let d={};for(let m of s.values())for(let[B,A]of Object.entries(m.results))A!==null?d[B]=A:B in d||(d[B]=null);let T=await(0,w.evaluateResultsCommon)(e,d,r,o);return{...s.get(r),action:r,results:T}}};var c=require("@multiversx/sdk-core"),ut=(i,t)=>i?c.OptionValue.newProvided(i):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),pt=(i,t)=>i?new c.OptionalValue(i.getType(),i):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),lt=i=>{if(i.length===0)throw new Error("Cannot create a list from an empty array");let t=i[0].getType();return new c.List(t,i)},ft=i=>c.VariadicValue.fromItems(...i),gt=i=>{let t=i.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),i)},S=i=>c.StringValue.fromUTF8(i),dt=i=>new c.U8Value(i),yt=i=>new c.U16Value(i),q=i=>new c.U32Value(i),mt=i=>new c.U64Value(i),ht=i=>new c.BigUIntValue(BigInt(i)),wt=i=>new c.BooleanValue(i),Tt=i=>new c.AddressValue(c.Address.newFromBech32(i)),Ct=i=>new c.TokenIdentifierValue(i),Wt=i=>c.BytesValue.fromHex(i),J=i=>new c.Struct(new c.StructType("EsdtTokenPayment",[new c.FieldDefinition("token_identifier","",new c.TokenIdentifierType),new c.FieldDefinition("token_nonce","",new c.U64Type),new c.FieldDefinition("amount","",new c.BigUIntType)]),[new c.Field(new c.TokenIdentifierValue(i.token.identifier),"token_identifier"),new c.Field(new c.U64Value(BigInt(i.token.nonce)),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(i.amount)),"amount")]),bt=i=>new c.CodeMetadataValue(c.CodeMetadata.newFromBytes(Uint8Array.from(Buffer.from(i,"hex")))),It=()=>new c.NothingValue;var W=class i{constructor(t){this.config=t;this.serializer=new F,this.abi=new P(this.config),this.results=new _(this.config)}async createTransaction(t){let e=(0,v.getWarpActionByIndex)(t.warp,t.action),r=null;if(e.type==="transfer")r=await this.createTransferTransaction(t);else if(e.type==="contract")r=await this.createContractCallTransaction(t);else{if(e.type==="query")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(e.type==="collect")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!r)throw new Error(`WarpMultiversxExecutor: Invalid action type (${e.type})`);return r}async createTransferTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let e=y.Address.newFromBech32(this.config.user.wallet),r=new y.TransactionsFactoryConfig({chainID:t.chain.chainId}),a=t.data?Buffer.from(this.serializer.stringToTyped(t.data).valueOf()):null;return new y.TransferTransactionsFactory({config:r}).createTransactionForTransfer(e,{receiver:y.Address.newFromBech32(t.destination),nativeAmount:t.value,data:a?new Uint8Array(a):void 0})}async createContractCallTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let e=(0,v.getWarpActionByIndex)(t.warp,t.action),r=y.Address.newFromBech32(this.config.user.wallet),a=t.args.map(u=>this.serializer.stringToTyped(u)),o=new y.TransactionsFactoryConfig({chainID:t.chain.chainId});return new y.SmartContractTransactionsFactory({config:o}).createTransactionForExecute(r,{contract:y.Address.newFromBech32(t.destination),function:"func"in e&&e.func||"",gasLimit:"gasLimit"in e?BigInt(e.gasLimit||0):0n,arguments:a,nativeTransferAmount:t.value})}async executeQuery(t){let e=(0,v.getWarpActionByIndex)(t.warp,t.action);if(e.type!=="query")throw new Error(`WarpMultiversxExecutor: Invalid action type for executeQuery: ${e.type}`);let r=await this.abi.getAbiForAction(e),a=t.args.map(E=>this.serializer.stringToTyped(E)),o=i.getChainEntrypoint(t.chain,this.config.env),u=y.Address.newFromBech32(t.destination),s=o.createSmartContractController(r),f=s.createQuery({contract:u,function:e.func||"",arguments:a}),p=await s.runQuery(f),g=p.returnCode==="ok",d=new y.ArgSerializer,T=r.getEndpoint(p.function||e.func||""),I=(p.returnDataParts||[]).map(E=>Buffer.from(E)),m=d.buffersToValues(I,T.output),{values:B,results:A}=await this.results.extractQueryResults(t.warp,m,t.action,t.resolvedInputs),R=(0,v.getNextInfo)(this.config,t.warp,t.action,A);return{success:g,warp:t.warp,action:t.action,user:this.config.user?.wallet||null,txHash:null,next:R,values:B,results:A,messages:(0,v.applyResultsToMessages)(t.warp,A)}}async preprocessInput(t,e,r,a){if(r==="esdt"){let[o,u,s,f]=a.split(v.WarpConstants.ArgCompositeSeparator);if(f)return e;let p=new y.Token({identifier:o,nonce:BigInt(u)});if(!new y.TokenComputer().isFungible(p))return e;let T=(0,v.findKnownTokenById)(o)?.decimals;if(T||(T=(await(await fetch(`${t.apiUrl}/tokens/${o}`)).json()).decimals),!T)throw new Error(`WarpActionExecutor: Decimals not found for token ${o}`);let I=J(new y.TokenTransfer({token:p,amount:(0,v.shiftBigintBy)(s,T)}));return this.serializer.typedToString(I)+v.WarpConstants.ArgCompositeSeparator+T}return e}static getChainEntrypoint(t,e){let r="warp-sdk",a="api";return e==="devnet"?new y.DevnetEntrypoint(t.apiUrl,a,r):e==="testnet"?new y.TestnetEntrypoint(t.apiUrl,a,r):new y.MainnetEntrypoint(t.apiUrl,a,r)}};var L=class{constructor(t){this.config=t,this.cache=new V.WarpCache(t.cache?.type),this.core=new V.WarpBuilder(t)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=(0,V.getMainChainInfo)(this.config),r=new O.TransactionsFactoryConfig({chainID:e.chainId}),a=new O.TransferTransactionsFactory({config:r}),o=O.Address.newFromBech32(this.config.user.wallet),u=JSON.stringify(t),s=a.createTransactionForTransfer(o,{receiver:O.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(u))});return s.gasLimit=s.gasLimit+BigInt(2e6),s}async createFromTransaction(t,e=!1){let r=await this.core.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=V.WarpCacheKey.Warp(this.config.env,t);if(e){let s=this.cache.get(r);if(s)return V.WarpLogger.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),s}let a=(0,V.getMainChainInfo)(this.config),u=W.getChainEntrypoint(a,this.config.env).createNetworkProvider();try{let s=await u.getTransaction(t),f=await this.createFromTransaction(s);return e&&e.ttl&&f&&this.cache.set(r,f,e.ttl),f}catch(s){return V.WarpLogger.error("WarpBuilder: Error creating from transaction hash",s),null}}};var l=require("@multiversx/sdk-core"),h=require("@vleap/warps");var X={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 j=i=>({hash:i.hash.toString("hex"),alias:i.alias?.toString()||null,trust:i.trust.toString(),owner:i.owner.toString(),createdAt:i.created_at.toNumber(),upgradedAt:i.upgraded_at?.toNumber(),brand:i.brand?.toString("hex")||null,upgrade:i.upgrade?.toString("hex")||null}),tt=i=>({unitPrice:BigInt(i.unit_price.toString()),admins:i.admins.map(t=>t.toBech32())});var Q=class{constructor(t){this.config=t,this.cache=new h.WarpCache(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let a=l.Address.newFromBech32(this.config.user.wallet),o=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,u=()=>e&&r?[l.BytesValue.fromHex(t),l.BytesValue.fromUTF8(e),l.BytesValue.fromHex(r)]:e?[l.BytesValue.fromHex(t),l.BytesValue.fromUTF8(e)]:[l.BytesValue.fromHex(t)];return this.getFactory().createTransactionForExecute(a,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:o(),arguments:u()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[l.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[l.BytesValue.fromUTF8(t),l.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[l.BytesValue.fromHex(t),l.BytesValue.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[l.BytesValue.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[l.BytesValue.fromHex(t),new l.AddressValue(new l.Address(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[l.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[l.BytesValue.fromHex(t),l.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=h.WarpCacheKey.RegistryInfo(this.config.env,t),a=e?this.cache.get(r):null;if(a)return h.WarpLogger.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),a;let o=this.getRegistryContractAddress(),u=this.getController(),s=u.createQuery({contract:o,function:"getInfoByAlias",arguments:[l.BytesValue.fromUTF8(t)]}),f=await u.runQuery(s),[p]=u.parseQueryResponse(f),g=p?j(p):null,d=g?.brand?await this.fetchBrand(g.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:g,brand:d},e.ttl),{registryInfo:g,brand:d}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=h.WarpCacheKey.RegistryInfo(this.config.env,t);if(e){let d=this.cache.get(r);if(d)return h.WarpLogger.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let a=this.getRegistryContractAddress(),o=this.getController(),u=o.createQuery({contract:a,function:"getInfoByHash",arguments:[l.BytesValue.fromHex(t)]}),s=await o.runQuery(u),[f]=o.parseQueryResponse(s),p=f?j(f):null,g=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:g},e.ttl),{registryInfo:p,brand:g}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:r,function:"getUserWarps",arguments:[new l.AddressValue(new l.Address(e))]}),u=await a.runQuery(o),[s]=a.parseQueryResponse(u);return s.map(j)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:r,function:"getUserBrands",arguments:[new l.AddressValue(new l.Address(e))]}),u=await a.runQuery(o),[s]=a.parseQueryResponse(u),f=s.map(d=>d.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(f.map(d=>this.fetchBrand(d,p)))).filter(d=>d!==null)}catch{return[]}}async getChainInfos(t){let e=h.WarpCacheKey.ChainInfos(this.config.env);if(t&&t.ttl){let p=this.cache.get(e);if(p)return h.WarpLogger.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),p}let r=this.getRegistryContractAddress(),a=this.getController(),o=a.createQuery({contract:r,function:"getChains",arguments:[]}),u=await a.runQuery(o),[s]=a.parseQueryResponse(u),f=s.map(h.toTypedChainInfo);if(t&&t.ttl){for(let p of f)this.cache.set(h.WarpCacheKey.ChainInfo(this.config.env,p.chain),p,t.ttl);this.cache.set(e,f,t.ttl)}return f}async getChainInfo(t,e){try{let r=h.WarpCacheKey.ChainInfo(this.config.env,t),a=e?this.cache.get(r):null;if(a)return h.WarpLogger.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),a;let o=this.getRegistryContractAddress(),u=this.getController(),s=u.createQuery({contract:o,function:"getChain",arguments:[l.BytesValue.fromUTF8(t)]}),f=await u.runQuery(s),[p]=u.parseQueryResponse(f),g=p?(0,h.toTypedChainInfo)(p):null;return e&&e.ttl&&g&&this.cache.set(r,g,e.ttl),g}catch{return null}}async setChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"setChain",gasLimit:BigInt(1e7),arguments:[S(t.name),S(t.displayName),S(t.chainId),q(t.blockTime),S(t.addressHrp),S(t.apiUrl),S(t.explorerUrl),S(t.nativeToken)]})}async removeChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=l.Address.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"removeChain",gasLimit:BigInt(1e7),arguments:[S(t)]})}async fetchBrand(t,e){let r=h.WarpCacheKey.Brand(this.config.env,t),a=e?this.cache.get(r):null;if(a)return h.WarpLogger.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),a;let o=(0,h.getMainChainInfo)(this.config),s=W.getChainEntrypoint(o,this.config.env).createNetworkProvider();try{let f=await s.getTransaction(t),p=JSON.parse(f.data.toString());return p.meta={hash:f.hash,creator:f.sender.bech32(),createdAt:new Date(f.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,p,e.ttl),p}catch{return null}}getRegistryContractAddress(){return l.Address.newFromBech32(this.config.registry?.contract||h.WarpConfig.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),a=r?tt(r):null;this.registryConfig=a||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=(0,h.getMainChainInfo)(this.config),e=new l.TransactionsFactoryConfig({chainID:t.chainId}),r=l.AbiRegistry.create(X);return new l.SmartContractTransactionsFactory({config:e,abi:r})}getController(){let t=(0,h.getMainChainInfo)(this.config),e=W.getChainEntrypoint(t,this.config.env),r=l.AbiRegistry.create(X);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var vt=i=>({chain:"multiversx",builder:new L(i),executor:new W(i),results:new _(i),serializer:new F,registry:new Q(i)});var k=require("@multiversx/sdk-core"),N=require("@vleap/warps"),et=require("buffer");var Y=class{constructor(t){this.config=t,this.core=new N.WarpBrandBuilder(t)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=(0,N.getMainChainInfo)(this.config),r=new k.TransactionsFactoryConfig({chainID:e.chainId}),a=new k.TransferTransactionsFactory({config:r}),o=k.Address.newFromBech32(this.config.user.wallet),u=JSON.stringify(t);return a.createTransactionForNativeTokenTransfer(o,{receiver:k.Address.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(et.Buffer.from(u))})}async createFromTransaction(t,e=!1){return await this.core.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=(0,N.getMainChainInfo)(this.config),a=W.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let o=await a.getTransaction(t);return this.createFromTransaction(o)}catch(o){return N.WarpLogger.error("BrandBuilder: Error creating from transaction hash",o),null}}};0&&(module.exports={WarpMultiversxAbi,WarpMultiversxBrandBuilder,WarpMultiversxBuilder,WarpMultiversxConstants,WarpMultiversxContractLoader,WarpMultiversxExecutor,WarpMultiversxRegistry,WarpMultiversxResults,WarpMultiversxSerializer,address_value,biguint_value,boolean_value,codemeta_value,composite_value,esdt_value,getMultiversxAdapter,hex_value,list_value,nothing_value,option_value,optional_value,string_value,token_value,u16_value,u32_value,u64_value,u8_value,variadic_value});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var or={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};import{Address as Lt,TransactionsFactoryConfig as je,TransferTransactionsFactory as Ge}from"@multiversx/sdk-core";import{getMainChainInfo as Qt,WarpBuilder as Ke,WarpCache as qe,WarpCacheKey as Je,WarpLogger as zt}from"@vleap/warps";import{Address as S,ArgSerializer as Pe,DevnetEntrypoint as _e,MainnetEntrypoint as Oe,SmartContractTransactionsFactory as ke,TestnetEntrypoint as Ne,Token as Ue,TokenComputer as $e,TokenTransfer as Me,TransactionsFactoryConfig as $t,TransferTransactionsFactory as Le}from"@multiversx/sdk-core";import{applyResultsToMessages as Qe,findKnownTokenById as ze,getNextInfo as He,getWarpActionByIndex as et,shiftBigintBy as De,WarpConstants as Mt}from"@vleap/warps";import{AbiRegistry as M}from"@multiversx/sdk-core";import{getMainChainInfo as st,WarpCache as Jt,WarpCacheKey as Xt,WarpConstants as ot,WarpLogger as ct}from"@vleap/warps";import{WarpLogger as it}from"@vleap/warps";var O=class{constructor(t){this.config=t}async getContract(t,e){try{let i=await m.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:i.ownerAddress,verified:i.isVerified||!1}}catch(r){return it.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let i=await m.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:i.codeHash,abi:i.source.abi}}catch(r){return it.error("WarpContractLoader: getVerificationInfo error",r),null}}};var x=class{constructor(t){this.config=t;this.contractLoader=new O(this.config),this.cache=new Jt(this.config.cache?.type)}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=Xt.WarpAbi(this.config.env,t);if(e){let a=this.cache.get(r);if(a)return ct.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),a}let n=st(this.config),o=m.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let a=await o.getTransaction(t),u=await this.createFromTransaction(a);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(a){return ct.error("WarpAbiBuilder: Error creating from transaction hash",a),null}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);if(!t.address)throw new Error("WarpActionExecutor: Address not found");let e=st(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return M.create(r.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(ot.IdentifierType.Hash)){let e=t.abi.split(ot.IdentifierParamSeparator)[1],r=await this.createFromTransactionHash(e);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return M.create(r.content)}else{let r=await(await fetch(t.abi)).json();return M.create(r)}}};import{findEventsByFirstTopic as ie,SmartContractTransactionsOutcomeParser as se,TransactionEventsParser as oe}from"@multiversx/sdk-core";import{applyResultsToMessages as ce,evaluateResultsCommon as k,getNextInfo as ue,getWarpActionByIndex as pe,parseResultsOutIndex as Ft,WarpCache as le,WarpCacheKey as fe,WarpConstants as Pt}from"@vleap/warps";import{Address as Yt,AddressType as ut,AddressValue as pt,BigUIntType as L,BigUIntValue as Q,BooleanType as lt,BooleanValue as ft,BytesType as gt,BytesValue as dt,CodeMetadata as Zt,CodeMetadataType as yt,CodeMetadataValue as mt,CompositeType as ht,CompositeValue as wt,Field as z,FieldDefinition as H,List as Tt,ListType as te,NothingValue as C,OptionalType as ee,OptionalValue as D,OptionType as re,OptionValue as j,StringType as Ct,StringValue as Wt,Struct as ne,StructType as bt,TokenIdentifierType as G,TokenIdentifierValue as K,U16Type as It,U16Value as At,U32Type as vt,U32Value as Bt,U64Type as q,U64Value as J,U8Type as xt,U8Value as Et,VariadicType as Vt,VariadicValue as Rt}from"@multiversx/sdk-core";import{WarpConstants as W,WarpSerializer as ae}from"@vleap/warps";var St=new RegExp(`${W.ArgParamsSeparator}(.*)`),B=class{constructor(){this.coreSerializer=new ae}typedToString(t){if(t.hasClassOrSuperclass(j.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(D.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Tt.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(W.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(W.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(Rt.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(W.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(W.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(wt.ClassName)){let e=t.getItems(),r=e.map(a=>this.typedToString(a).split(W.ArgParamsSeparator)[0]),n=e.map(a=>this.typedToString(a).split(W.ArgParamsSeparator)[1]),i=r.join(W.ArgCompositeSeparator),o=n.join(W.ArgCompositeSeparator);return`composite(${i}):${o}`}if(t.hasClassOrSuperclass(Q.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Et.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(At.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Bt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(J.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Wt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(ft.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(pt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(K.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(dt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(mt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.coreSerializer.stringToNative(e)}nativeToTyped(t,e){let r=this.coreSerializer.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new ht(...e.split(W.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Ct;if(t==="uint8")return new xt;if(t==="uint16")return new It;if(t==="uint32")return new vt;if(t==="uint64")return new q;if(t==="biguint")return new L;if(t==="bool")return new lt;if(t==="address")return new ut;if(t==="token")return new G;if(t==="hex")return new gt;if(t==="codemeta")return new yt;if(t==="esdt"||t==="nft")return new bt("EsdtTokenPayment",[new H("token_identifier","",new G),new H("token_nonce","",new q),new H("amount","",new L)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new C;if(e==="option"){let n=this.stringToTyped(r);return n instanceof C?j.newMissingTyped(n.getType()):j.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof C?D.newMissing():new D(n.getType(),n)}if(e==="list"){let[n,i]=r.split(St,2),a=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new Tt(this.nativeToType(n),a)}if(e==="variadic"){let[n,i]=r.split(St,2),a=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new Rt(new Vt(this.nativeToType(n)),a)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(W.ArgCompositeSeparator),o=n.split(W.ArgCompositeSeparator),a=i.map((c,p)=>this.stringToTyped(`${o[p]}:${c}`)),u=a.map(c=>c.getType());return new wt(new ht(...u),a)}if(e==="string")return r?Wt.fromUTF8(r):new C;if(e==="uint8")return r?new Et(Number(r)):new C;if(e==="uint16")return r?new At(Number(r)):new C;if(e==="uint32")return r?new Bt(Number(r)):new C;if(e==="uint64")return r?new J(BigInt(r)):new C;if(e==="biguint")return r?new Q(BigInt(r)):new C;if(e==="bool")return r?new ft(typeof r=="boolean"?r:r==="true"):new C;if(e==="address")return r?new pt(Yt.newFromBech32(r)):new C;if(e==="token")return r?new K(r):new C;if(e==="hex")return r?dt.fromHex(r):new C;if(e==="codemeta")return new mt(Zt.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(W.ArgCompositeSeparator);return new ne(this.nativeToType("esdt"),[new z(new K(n[0]),"token_identifier"),new z(new J(BigInt(n[1])),"token_nonce"),new z(new Q(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof re)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof ee)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof te)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Vt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ct)return"string";if(t instanceof xt)return"uint8";if(t instanceof It)return"uint16";if(t instanceof vt)return"uint32";if(t instanceof q)return"uint64";if(t instanceof L)return"biguint";if(t instanceof lt)return"bool";if(t instanceof ut)return"address";if(t instanceof G)return"token";if(t instanceof gt)return"hex";if(t instanceof yt)return"codemeta";if(t instanceof bt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var E=class{constructor(t){this.config=t;this.abi=new x(t),this.serializer=new B,this.cache=new le(t.cache?.type)}async getTransactionExecutionResults(t,e,r){let n=this.cache.get(fe.WarpExecutable(this.config.env,t.meta?.hash||"",e))??[],i=await this.extractContractResults(t,e,r,n),o=ue(this.config,t,e,i),a=ce(t,i.results);return{success:r.status.isSuccessful(),warp:t,action:e,user:this.config.user?.wallet||null,txHash:r.hash,next:o,values:i.values,results:i.results,messages:a}}async extractContractResults(t,e,r,n){let i=pe(t,e),o=[],a={};if(!t.results||i.type!=="contract")return{values:o,results:a};if(!Object.values(t.results).some(h=>h.includes("out")||h.includes("event"))){for(let[h,f]of Object.entries(t.results))a[h]=f;return{values:o,results:await k(t,a,e,n)}}let c=await this.abi.getAbiForAction(i),p=new oe({abi:c}),d=new se({abi:c}).parseExecute({transactionOnNetwork:r,function:i.func||void 0});for(let[h,f]of Object.entries(t.results)){if(f.startsWith(Pt.Transform.Prefix))continue;if(f.startsWith("input.")){a[h]=f;continue}let b=Ft(f);if(b!==null&&b!==e){a[h]=null;continue}let[w,A,I]=f.split(".");if(w==="event"){if(!A||isNaN(Number(I)))continue;let P=Number(I),y=ie(r,A),R=p.parseEvents({events:y})[0],_=Object.values(R)[P]||null;o.push(_),a[h]=_&&_.valueOf()}else if(w==="out"||w.startsWith("out[")){if(!A)continue;let P=Number(A),y=d.values[P-1]||null;I&&(y=y[I]||null),y&&typeof y=="object"&&(y="toFixed"in y?y.toFixed():y.valueOf()),o.push(y),a[h]=y&&y.valueOf()}else a[h]=f}return{values:o,results:await k(t,a,e,n)}}async extractQueryResults(t,e,r,n){let i=e.map(c=>this.serializer.typedToString(c)),o=e.map(c=>this.serializer.typedToNative(c)[1]),a={};if(!t.results)return{values:i,results:a};let u=c=>{let p=c.split(".").slice(1).map(d=>parseInt(d)-1);if(p.length===0)return;let l=o[p[0]];for(let d=1;d<p.length;d++){if(l==null)return;l=l[p[d]]}return l};for(let[c,p]of Object.entries(t.results)){if(p.startsWith(Pt.Transform.Prefix))continue;let l=Ft(p);if(l!==null&&l!==r){a[c]=null;continue}p.startsWith("out.")||p==="out"||p.startsWith("out[")?a[c]=u(p)||null:a[c]=p}return{values:i,results:await k(t,a,r,n)}}async resolveWarpResultsRecursively(t){let e=t.warp,r=t.entryActionIndex,n=t.executor,i=t.inputs,o=t.meta,a=new Map,u=new Set,c=this;async function p(f,b=[]){if(a.has(f))return a.get(f);if(u.has(f))throw new Error(`Circular dependency detected at action ${f}`);u.add(f);let w=e.actions[f-1];if(!w)throw new Error(`Action ${f} not found`);let A;if(w.type==="query")A=await n.executeQuery(e,f,b);else if(w.type==="collect")A=await n.executeCollect(e,f,b,o);else throw new Error(`Unsupported or interactive action type: ${w.type}`);if(a.set(f,A),e.results)for(let I of Object.values(e.results)){let y=String(I).match(/^out\[(\d+)\]/);if(y){let R=parseInt(y[1],10);R!==f&&!a.has(R)&&await p(R)}}return u.delete(f),A}await p(r,i);let l={};for(let f of a.values())for(let[b,w]of Object.entries(f.results))w!==null?l[b]=w:b in l||(l[b]=null);let d=await k(e,l,r,i);return{...a.get(r),action:r,results:d}}};import{Address as ge,AddressValue as de,BigUIntType as ye,BigUIntValue as _t,BooleanValue as me,BytesValue as he,CodeMetadata as we,CodeMetadataValue as Te,CompositeType as Ce,CompositeValue as We,Field as X,FieldDefinition as Y,List as be,NothingValue as Ie,OptionalValue as Z,OptionValue as tt,StringValue as Ae,Struct as ve,StructType as Be,TokenIdentifierType as xe,TokenIdentifierValue as Ot,U16Value as Ee,U32Value as Ve,U64Type as Re,U64Value as kt,U8Value as Se,VariadicValue as Fe}from"@multiversx/sdk-core";var rn=(s,t)=>s?tt.newProvided(s):t?tt.newMissingTyped(t):tt.newMissing(),nn=(s,t)=>s?new Z(s.getType(),s):t?new Z(t):Z.newMissing(),an=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new be(t,s)},sn=s=>Fe.fromItems(...s),on=s=>{let t=s.map(e=>e.getType());return new We(new Ce(...t),s)},v=s=>Ae.fromUTF8(s),cn=s=>new Se(s),un=s=>new Ee(s),Nt=s=>new Ve(s),pn=s=>new kt(s),ln=s=>new _t(BigInt(s)),fn=s=>new me(s),gn=s=>new de(ge.newFromBech32(s)),dn=s=>new Ot(s),yn=s=>he.fromHex(s),Ut=s=>new ve(new Be("EsdtTokenPayment",[new Y("token_identifier","",new xe),new Y("token_nonce","",new Re),new Y("amount","",new ye)]),[new X(new Ot(s.token.identifier),"token_identifier"),new X(new kt(BigInt(s.token.nonce)),"token_nonce"),new X(new _t(BigInt(s.amount)),"amount")]),mn=s=>new Te(we.newFromBytes(Uint8Array.from(Buffer.from(s,"hex")))),hn=()=>new Ie;var m=class s{constructor(t){this.config=t;this.serializer=new B,this.abi=new x(this.config),this.results=new E(this.config)}async createTransaction(t){let e=et(t.warp,t.action),r=null;if(e.type==="transfer")r=await this.createTransferTransaction(t);else if(e.type==="contract")r=await this.createContractCallTransaction(t);else{if(e.type==="query")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(e.type==="collect")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!r)throw new Error(`WarpMultiversxExecutor: Invalid action type (${e.type})`);return r}async createTransferTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let e=S.newFromBech32(this.config.user.wallet),r=new $t({chainID:t.chain.chainId}),n=t.data?Buffer.from(this.serializer.stringToTyped(t.data).valueOf()):null;return new Le({config:r}).createTransactionForTransfer(e,{receiver:S.newFromBech32(t.destination),nativeAmount:t.value,data:n?new Uint8Array(n):void 0})}async createContractCallTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let e=et(t.warp,t.action),r=S.newFromBech32(this.config.user.wallet),n=t.args.map(o=>this.serializer.stringToTyped(o)),i=new $t({chainID:t.chain.chainId});return new ke({config:i}).createTransactionForExecute(r,{contract:S.newFromBech32(t.destination),function:"func"in e&&e.func||"",gasLimit:"gasLimit"in e?BigInt(e.gasLimit||0):0n,arguments:n,nativeTransferAmount:t.value})}async executeQuery(t){let e=et(t.warp,t.action);if(e.type!=="query")throw new Error(`WarpMultiversxExecutor: Invalid action type for executeQuery: ${e.type}`);let r=await this.abi.getAbiForAction(e),n=t.args.map(I=>this.serializer.stringToTyped(I)),i=s.getChainEntrypoint(t.chain,this.config.env),o=S.newFromBech32(t.destination),a=i.createSmartContractController(r),u=a.createQuery({contract:o,function:e.func||"",arguments:n}),c=await a.runQuery(u),p=c.returnCode==="ok",l=new Pe,d=r.getEndpoint(c.function||e.func||""),h=(c.returnDataParts||[]).map(I=>Buffer.from(I)),f=l.buffersToValues(h,d.output),{values:b,results:w}=await this.results.extractQueryResults(t.warp,f,t.action,t.resolvedInputs),A=He(this.config,t.warp,t.action,w);return{success:p,warp:t.warp,action:t.action,user:this.config.user?.wallet||null,txHash:null,next:A,values:b,results:w,messages:Qe(t.warp,w)}}async preprocessInput(t,e,r,n){if(r==="esdt"){let[i,o,a,u]=n.split(Mt.ArgCompositeSeparator);if(u)return e;let c=new Ue({identifier:i,nonce:BigInt(o)});if(!new $e().isFungible(c))return e;let d=ze(i)?.decimals;if(d||(d=(await(await fetch(`${t.apiUrl}/tokens/${i}`)).json()).decimals),!d)throw new Error(`WarpActionExecutor: Decimals not found for token ${i}`);let h=Ut(new Me({token:c,amount:De(a,d)}));return this.serializer.typedToString(h)+Mt.ArgCompositeSeparator+d}return e}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new _e(t.apiUrl,n,r):e==="testnet"?new Ne(t.apiUrl,n,r):new Oe(t.apiUrl,n,r)}};var N=class{constructor(t){this.config=t,this.cache=new qe(t.cache?.type),this.core=new Ke(t)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=Qt(this.config),r=new je({chainID:e.chainId}),n=new Ge({config:r}),i=Lt.newFromBech32(this.config.user.wallet),o=JSON.stringify(t),a=n.createTransactionForTransfer(i,{receiver:Lt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return a.gasLimit=a.gasLimit+BigInt(2e6),a}async createFromTransaction(t,e=!1){let r=await this.core.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=Je.Warp(this.config.env,t);if(e){let a=this.cache.get(r);if(a)return zt.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),a}let n=Qt(this.config),o=m.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let a=await o.getTransaction(t),u=await this.createFromTransaction(a);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(a){return zt.error("WarpBuilder: Error creating from transaction hash",a),null}}};import{AbiRegistry as Dt,Address as T,AddressValue as nt,BytesValue as g,SmartContractTransactionsFactory as Ye,TransactionsFactoryConfig as Ze}from"@multiversx/sdk-core";import{getMainChainInfo as at,toTypedChainInfo as jt,WarpCache as tr,WarpCacheKey as V,WarpConfig as er,WarpLogger as F}from"@vleap/warps";var rt={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 U=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),owner:s.owner.toString(),createdAt:s.created_at.toNumber(),upgradedAt:s.upgraded_at?.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),Ht=s=>({unitPrice:BigInt(s.unit_price.toString()),admins:s.admins.map(t=>t.toBech32())});var $=class{constructor(t){this.config=t,this.cache=new tr(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let n=T.newFromBech32(this.config.user.wallet),i=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,o=()=>e&&r?[g.fromHex(t),g.fromUTF8(e),g.fromHex(r)]:e?[g.fromHex(t),g.fromUTF8(e)]:[g.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i(),arguments:o()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromUTF8(t),g.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(t),g.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[g.fromHex(t),new nt(new T(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(t),g.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=V.RegistryInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return F.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),o=this.getController(),a=o.createQuery({contract:i,function:"getInfoByAlias",arguments:[g.fromUTF8(t)]}),u=await o.runQuery(a),[c]=o.parseQueryResponse(u),p=c?U(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=V.RegistryInfo(this.config.env,t);if(e){let l=this.cache.get(r);if(l)return F.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let n=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[g.fromHex(t)]}),a=await i.runQuery(o),[u]=i.parseQueryResponse(a),c=u?U(u):null,p=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:p},e.ttl),{registryInfo:c,brand:p}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new nt(new T(e))]}),o=await n.runQuery(i),[a]=n.parseQueryResponse(o);return a.map(U)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new nt(new T(e))]}),o=await n.runQuery(i),[a]=n.parseQueryResponse(o),u=a.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(u.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}catch{return[]}}async getChainInfos(t){let e=V.ChainInfos(this.config.env);if(t&&t.ttl){let c=this.cache.get(e);if(c)return F.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),c}let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getChains",arguments:[]}),o=await n.runQuery(i),[a]=n.parseQueryResponse(o),u=a.map(jt);if(t&&t.ttl){for(let c of u)this.cache.set(V.ChainInfo(this.config.env,c.chain),c,t.ttl);this.cache.set(e,u,t.ttl)}return u}async getChainInfo(t,e){try{let r=V.ChainInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return F.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let i=this.getRegistryContractAddress(),o=this.getController(),a=o.createQuery({contract:i,function:"getChain",arguments:[g.fromUTF8(t)]}),u=await o.runQuery(a),[c]=o.parseQueryResponse(u),p=c?jt(c):null;return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch{return null}}async setChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"setChain",gasLimit:BigInt(1e7),arguments:[v(t.name),v(t.displayName),v(t.chainId),Nt(t.blockTime),v(t.addressHrp),v(t.apiUrl),v(t.explorerUrl),v(t.nativeToken)]})}async removeChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"removeChain",gasLimit:BigInt(1e7),arguments:[v(t)]})}async fetchBrand(t,e){let r=V.Brand(this.config.env,t),n=e?this.cache.get(r):null;if(n)return F.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let i=at(this.config),a=m.getChainEntrypoint(i,this.config.env).createNetworkProvider();try{let u=await a.getTransaction(t),c=JSON.parse(u.data.toString());return c.meta={hash:u.hash,creator:u.sender.bech32(),createdAt:new Date(u.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,c,e.ttl),c}catch{return null}}getRegistryContractAddress(){return T.newFromBech32(this.config.registry?.contract||er.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?Ht(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=at(this.config),e=new Ze({chainID:t.chainId}),r=Dt.create(rt);return new Ye({config:e,abi:r})}getController(){let t=at(this.config),e=m.getChainEntrypoint(t,this.config.env),r=Dt.create(rt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var ma=s=>({chain:"multiversx",builder:new N(s),executor:new m(s),results:new E(s),serializer:new B,registry:new $(s)});import{Address as Gt,TransactionsFactoryConfig as rr,TransferTransactionsFactory as nr}from"@multiversx/sdk-core";import{getMainChainInfo as Kt,WarpBrandBuilder as ar,WarpLogger as ir}from"@vleap/warps";import{Buffer as sr}from"buffer";var qt=class{constructor(t){this.config=t,this.core=new ar(t)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=Kt(this.config),r=new rr({chainID:e.chainId}),n=new nr({config:r}),i=Gt.newFromBech32(this.config.user.wallet),o=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(i,{receiver:Gt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(sr.from(o))})}async createFromTransaction(t,e=!1){return await this.core.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=Kt(this.config),n=m.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let i=await n.getTransaction(t);return this.createFromTransaction(i)}catch(i){return ir.error("BrandBuilder: Error creating from transaction hash",i),null}}};export{x as WarpMultiversxAbi,qt as WarpMultiversxBrandBuilder,N as WarpMultiversxBuilder,or as WarpMultiversxConstants,O as WarpMultiversxContractLoader,m as WarpMultiversxExecutor,$ as WarpMultiversxRegistry,E as WarpMultiversxResults,B as WarpMultiversxSerializer,gn as address_value,ln as biguint_value,fn as boolean_value,mn as codemeta_value,on as composite_value,Ut as esdt_value,ma as getMultiversxAdapter,yn as hex_value,an as list_value,hn as nothing_value,rn as option_value,nn as optional_value,v as string_value,dn as token_value,un as u16_value,Nt as u32_value,pn as u64_value,cn as u8_value,sn as variadic_value};
|
|
1
|
+
var or={Egld:{Identifier:"EGLD",EsdtIdentifier:"EGLD-000000",DisplayName:"eGold",Decimals:18}};import{Address as Qt,TransactionsFactoryConfig as je,TransferTransactionsFactory as Ge}from"@multiversx/sdk-core";import{getMainChainInfo as zt,WarpBuilder as Ke,WarpCache as qe,WarpCacheKey as Je,WarpLogger as Ht}from"@vleap/warps";import{Address as S,ArgSerializer as Pe,DevnetEntrypoint as _e,MainnetEntrypoint as Oe,SmartContractTransactionsFactory as ke,TestnetEntrypoint as Ne,Token as Ue,TokenComputer as $e,TokenTransfer as Me,TransactionsFactoryConfig as Mt,TransferTransactionsFactory as Le}from"@multiversx/sdk-core";import{applyResultsToMessages as Qe,findKnownTokenById as ze,getNextInfo as He,getWarpActionByIndex as et,shiftBigintBy as De,WarpConstants as Lt}from"@vleap/warps";import{AbiRegistry as M}from"@multiversx/sdk-core";import{getMainChainInfo as st,WarpCache as Xt,WarpCacheKey as Yt,WarpConstants as ot,WarpLogger as ct}from"@vleap/warps";import{WarpLogger as it}from"@vleap/warps";var O=class{constructor(t){this.config=t}async getContract(t,e){try{let s=await m.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}`);return{address:t,owner:s.ownerAddress,verified:s.isVerified||!1}}catch(r){return it.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t,e){try{let s=await m.getChainEntrypoint(e,this.config.env).createNetworkProvider().doGetGeneric(`accounts/${t}/verification`);return{codeHash:s.codeHash,abi:s.source.abi}}catch(r){return it.error("WarpContractLoader: getVerificationInfo error",r),null}}};var B=class{constructor(t){this.config=t;this.contractLoader=new O(this.config),this.cache=new Xt(this.config.cache?.type)}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=Yt.WarpAbi(this.config.env,t);if(e){let a=this.cache.get(r);if(a)return ct.info(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),a}let n=st(this.config),o=m.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let a=await o.getTransaction(t),u=await this.createFromTransaction(a);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(a){return ct.error("WarpAbiBuilder: Error creating from transaction hash",a),null}}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);if(!t.address)throw new Error("WarpActionExecutor: Address not found");let e=st(this.config),r=await this.contractLoader.getVerificationInfo(t.address,e);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return M.create(r.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(ot.IdentifierType.Hash)){let e=t.abi.split(ot.IdentifierParamSeparator)[1],r=await this.createFromTransactionHash(e);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return M.create(r.content)}else{let r=await(await fetch(t.abi)).json();return M.create(r)}}};import{findEventsByFirstTopic as se,SmartContractTransactionsOutcomeParser as oe,TransactionEventsParser as ce}from"@multiversx/sdk-core";import{applyResultsToMessages as ue,evaluateResultsCommon as k,findWarpExecutableAction as Ft,getNextInfo as pe,parseResultsOutIndex as Pt,WarpCache as le,WarpCacheKey as fe,WarpConstants as _t}from"@vleap/warps";import{Address as Zt,AddressType as ut,AddressValue as pt,BigUIntType as L,BigUIntValue as Q,BooleanType as lt,BooleanValue as ft,BytesType as gt,BytesValue as dt,CodeMetadata as te,CodeMetadataType as yt,CodeMetadataValue as mt,CompositeType as ht,CompositeValue as wt,Field as z,FieldDefinition as H,List as Tt,ListType as ee,NothingValue as C,OptionalType as re,OptionalValue as D,OptionType as ne,OptionValue as j,StringType as Ct,StringValue as Wt,Struct as ae,StructType as bt,TokenIdentifierType as G,TokenIdentifierValue as K,U16Type as It,U16Value as At,U32Type as vt,U32Value as xt,U64Type as q,U64Value as J,U8Type as Bt,U8Value as Et,VariadicType as Vt,VariadicValue as Rt}from"@multiversx/sdk-core";import{WarpConstants as W,WarpSerializer as ie}from"@vleap/warps";var St=new RegExp(`${W.ArgParamsSeparator}(.*)`),x=class{constructor(){this.coreSerializer=new ie}typedToString(t){if(t.hasClassOrSuperclass(j.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(D.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Tt.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(W.ArgParamsSeparator)[0])[0],s=e.map(o=>this.typedToString(o).split(W.ArgParamsSeparator)[1]);return`list:${n}:${s.join(",")}`}if(t.hasClassOrSuperclass(Rt.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(W.ArgParamsSeparator)[0])[0],s=e.map(o=>this.typedToString(o).split(W.ArgParamsSeparator)[1]);return`variadic:${n}:${s.join(",")}`}if(t.hasClassOrSuperclass(wt.ClassName)){let e=t.getItems(),r=e.map(a=>this.typedToString(a).split(W.ArgParamsSeparator)[0]),n=e.map(a=>this.typedToString(a).split(W.ArgParamsSeparator)[1]),s=r.join(W.ArgCompositeSeparator),o=n.join(W.ArgCompositeSeparator);return`composite(${s}):${o}`}if(t.hasClassOrSuperclass(Q.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Et.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(At.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(xt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(J.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Wt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(ft.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(pt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(K.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(dt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(mt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.coreSerializer.stringToNative(e)}nativeToTyped(t,e){let r=this.coreSerializer.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new ht(...e.split(W.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Ct;if(t==="uint8")return new Bt;if(t==="uint16")return new It;if(t==="uint32")return new vt;if(t==="uint64")return new q;if(t==="biguint")return new L;if(t==="bool")return new lt;if(t==="address")return new ut;if(t==="token")return new G;if(t==="hex")return new gt;if(t==="codemeta")return new yt;if(t==="esdt"||t==="nft")return new bt("EsdtTokenPayment",[new H("token_identifier","",new G),new H("token_nonce","",new q),new H("amount","",new L)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new C;if(e==="option"){let n=this.stringToTyped(r);return n instanceof C?j.newMissingTyped(n.getType()):j.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof C?D.newMissing():new D(n.getType(),n)}if(e==="list"){let[n,s]=r.split(St,2),a=s.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new Tt(this.nativeToType(n),a)}if(e==="variadic"){let[n,s]=r.split(St,2),a=s.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new Rt(new Vt(this.nativeToType(n)),a)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],s=r.split(W.ArgCompositeSeparator),o=n.split(W.ArgCompositeSeparator),a=s.map((c,p)=>this.stringToTyped(`${o[p]}:${c}`)),u=a.map(c=>c.getType());return new wt(new ht(...u),a)}if(e==="string")return r?Wt.fromUTF8(r):new C;if(e==="uint8")return r?new Et(Number(r)):new C;if(e==="uint16")return r?new At(Number(r)):new C;if(e==="uint32")return r?new xt(Number(r)):new C;if(e==="uint64")return r?new J(BigInt(r)):new C;if(e==="biguint")return r?new Q(BigInt(r)):new C;if(e==="bool")return r?new ft(typeof r=="boolean"?r:r==="true"):new C;if(e==="address")return r?new pt(Zt.newFromBech32(r)):new C;if(e==="token")return r?new K(r):new C;if(e==="hex")return r?dt.fromHex(r):new C;if(e==="codemeta")return new mt(te.newFromBytes(Uint8Array.from(Buffer.from(r,"hex"))));if(e==="esdt"){let n=r.split(W.ArgCompositeSeparator);return new ae(this.nativeToType("esdt"),[new z(new K(n[0]),"token_identifier"),new z(new J(BigInt(n[1])),"token_nonce"),new z(new Q(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToString(t){if(t instanceof ne)return"option:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof re)return"optional:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof ee)return"list:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Vt)return"variadic:"+this.typeToString(t.getFirstTypeParameter());if(t instanceof Ct)return"string";if(t instanceof Bt)return"uint8";if(t instanceof It)return"uint16";if(t instanceof vt)return"uint32";if(t instanceof q)return"uint64";if(t instanceof L)return"biguint";if(t instanceof lt)return"bool";if(t instanceof ut)return"address";if(t instanceof G)return"token";if(t instanceof gt)return"hex";if(t instanceof yt)return"codemeta";if(t instanceof bt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToString): Unsupported input type: ${t.getClassName()}`)}};var E=class{constructor(t){this.config=t;this.abi=new B(t),this.serializer=new x,this.cache=new le(t.cache?.type)}async getTransactionExecutionResults(t,e){let[r,n]=Ft(t),s=this.cache.get(fe.WarpExecutable(this.config.env,t.meta?.hash||"",n))??[],o=await this.extractContractResults(t,e,s),a=pe(this.config,t,n,o),u=ue(t,o.results);return{success:e.status.isSuccessful(),warp:t,action:n,user:this.config.user?.wallet||null,txHash:e.hash,next:a,values:o.values,results:o.results,messages:u}}async extractContractResults(t,e,r){let[n,s]=Ft(t),o=[],a={};if(!t.results||n.type!=="contract")return{values:o,results:a};if(!Object.values(t.results).some(h=>h.includes("out")||h.includes("event"))){for(let[h,f]of Object.entries(t.results))a[h]=f;return{values:o,results:await k(t,a,s,r)}}let c=await this.abi.getAbiForAction(n),p=new ce({abi:c}),d=new oe({abi:c}).parseExecute({transactionOnNetwork:e,function:n.func||void 0});for(let[h,f]of Object.entries(t.results)){if(f.startsWith(_t.Transform.Prefix))continue;if(f.startsWith("input.")){a[h]=f;continue}let b=Pt(f);if(b!==null&&b!==s){a[h]=null;continue}let[w,A,I]=f.split(".");if(w==="event"){if(!A||isNaN(Number(I)))continue;let P=Number(I),y=se(e,A),R=p.parseEvents({events:y})[0],_=Object.values(R)[P]||null;o.push(_),a[h]=_&&_.valueOf()}else if(w==="out"||w.startsWith("out[")){if(!A)continue;let P=Number(A),y=d.values[P-1]||null;I&&(y=y[I]||null),y&&typeof y=="object"&&(y="toFixed"in y?y.toFixed():y.valueOf()),o.push(y),a[h]=y&&y.valueOf()}else a[h]=f}return{values:o,results:await k(t,a,s,r)}}async extractQueryResults(t,e,r,n){let s=e.map(c=>this.serializer.typedToString(c)),o=e.map(c=>this.serializer.typedToNative(c)[1]),a={};if(!t.results)return{values:s,results:a};let u=c=>{let p=c.split(".").slice(1).map(d=>parseInt(d)-1);if(p.length===0)return;let l=o[p[0]];for(let d=1;d<p.length;d++){if(l==null)return;l=l[p[d]]}return l};for(let[c,p]of Object.entries(t.results)){if(p.startsWith(_t.Transform.Prefix))continue;let l=Pt(p);if(l!==null&&l!==r){a[c]=null;continue}p.startsWith("out.")||p==="out"||p.startsWith("out[")?a[c]=u(p)||null:a[c]=p}return{values:s,results:await k(t,a,r,n)}}async resolveWarpResultsRecursively(t){let e=t.warp,r=t.entryActionIndex,n=t.executor,s=t.inputs,o=t.meta,a=new Map,u=new Set,c=this;async function p(f,b=[]){if(a.has(f))return a.get(f);if(u.has(f))throw new Error(`Circular dependency detected at action ${f}`);u.add(f);let w=e.actions[f-1];if(!w)throw new Error(`Action ${f} not found`);let A;if(w.type==="query")A=await n.executeQuery(e,f,b);else if(w.type==="collect")A=await n.executeCollect(e,f,b,o);else throw new Error(`Unsupported or interactive action type: ${w.type}`);if(a.set(f,A),e.results)for(let I of Object.values(e.results)){let y=String(I).match(/^out\[(\d+)\]/);if(y){let R=parseInt(y[1],10);R!==f&&!a.has(R)&&await p(R)}}return u.delete(f),A}await p(r,s);let l={};for(let f of a.values())for(let[b,w]of Object.entries(f.results))w!==null?l[b]=w:b in l||(l[b]=null);let d=await k(e,l,r,s);return{...a.get(r),action:r,results:d}}};import{Address as ge,AddressValue as de,BigUIntType as ye,BigUIntValue as Ot,BooleanValue as me,BytesValue as he,CodeMetadata as we,CodeMetadataValue as Te,CompositeType as Ce,CompositeValue as We,Field as X,FieldDefinition as Y,List as be,NothingValue as Ie,OptionalValue as Z,OptionValue as tt,StringValue as Ae,Struct as ve,StructType as xe,TokenIdentifierType as Be,TokenIdentifierValue as kt,U16Value as Ee,U32Value as Ve,U64Type as Re,U64Value as Nt,U8Value as Se,VariadicValue as Fe}from"@multiversx/sdk-core";var rn=(i,t)=>i?tt.newProvided(i):t?tt.newMissingTyped(t):tt.newMissing(),nn=(i,t)=>i?new Z(i.getType(),i):t?new Z(t):Z.newMissing(),an=i=>{if(i.length===0)throw new Error("Cannot create a list from an empty array");let t=i[0].getType();return new be(t,i)},sn=i=>Fe.fromItems(...i),on=i=>{let t=i.map(e=>e.getType());return new We(new Ce(...t),i)},v=i=>Ae.fromUTF8(i),cn=i=>new Se(i),un=i=>new Ee(i),Ut=i=>new Ve(i),pn=i=>new Nt(i),ln=i=>new Ot(BigInt(i)),fn=i=>new me(i),gn=i=>new de(ge.newFromBech32(i)),dn=i=>new kt(i),yn=i=>he.fromHex(i),$t=i=>new ve(new xe("EsdtTokenPayment",[new Y("token_identifier","",new Be),new Y("token_nonce","",new Re),new Y("amount","",new ye)]),[new X(new kt(i.token.identifier),"token_identifier"),new X(new Nt(BigInt(i.token.nonce)),"token_nonce"),new X(new Ot(BigInt(i.amount)),"amount")]),mn=i=>new Te(we.newFromBytes(Uint8Array.from(Buffer.from(i,"hex")))),hn=()=>new Ie;var m=class i{constructor(t){this.config=t;this.serializer=new x,this.abi=new B(this.config),this.results=new E(this.config)}async createTransaction(t){let e=et(t.warp,t.action),r=null;if(e.type==="transfer")r=await this.createTransferTransaction(t);else if(e.type==="contract")r=await this.createContractCallTransaction(t);else{if(e.type==="query")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeQuery instead");if(e.type==="collect")throw new Error("WarpMultiversxExecutor: Invalid action type for createTransactionForExecute; Use executeCollect instead")}if(!r)throw new Error(`WarpMultiversxExecutor: Invalid action type (${e.type})`);return r}async createTransferTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpMultiversxExecutor: createTransfer - user address not set");let e=S.newFromBech32(this.config.user.wallet),r=new Mt({chainID:t.chain.chainId}),n=t.data?Buffer.from(this.serializer.stringToTyped(t.data).valueOf()):null;return new Le({config:r}).createTransactionForTransfer(e,{receiver:S.newFromBech32(t.destination),nativeAmount:t.value,data:n?new Uint8Array(n):void 0})}async createContractCallTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpMultiversxExecutor: createContractCall - user address not set");let e=et(t.warp,t.action),r=S.newFromBech32(this.config.user.wallet),n=t.args.map(o=>this.serializer.stringToTyped(o)),s=new Mt({chainID:t.chain.chainId});return new ke({config:s}).createTransactionForExecute(r,{contract:S.newFromBech32(t.destination),function:"func"in e&&e.func||"",gasLimit:"gasLimit"in e?BigInt(e.gasLimit||0):0n,arguments:n,nativeTransferAmount:t.value})}async executeQuery(t){let e=et(t.warp,t.action);if(e.type!=="query")throw new Error(`WarpMultiversxExecutor: Invalid action type for executeQuery: ${e.type}`);let r=await this.abi.getAbiForAction(e),n=t.args.map(I=>this.serializer.stringToTyped(I)),s=i.getChainEntrypoint(t.chain,this.config.env),o=S.newFromBech32(t.destination),a=s.createSmartContractController(r),u=a.createQuery({contract:o,function:e.func||"",arguments:n}),c=await a.runQuery(u),p=c.returnCode==="ok",l=new Pe,d=r.getEndpoint(c.function||e.func||""),h=(c.returnDataParts||[]).map(I=>Buffer.from(I)),f=l.buffersToValues(h,d.output),{values:b,results:w}=await this.results.extractQueryResults(t.warp,f,t.action,t.resolvedInputs),A=He(this.config,t.warp,t.action,w);return{success:p,warp:t.warp,action:t.action,user:this.config.user?.wallet||null,txHash:null,next:A,values:b,results:w,messages:Qe(t.warp,w)}}async preprocessInput(t,e,r,n){if(r==="esdt"){let[s,o,a,u]=n.split(Lt.ArgCompositeSeparator);if(u)return e;let c=new Ue({identifier:s,nonce:BigInt(o)});if(!new $e().isFungible(c))return e;let d=ze(s)?.decimals;if(d||(d=(await(await fetch(`${t.apiUrl}/tokens/${s}`)).json()).decimals),!d)throw new Error(`WarpActionExecutor: Decimals not found for token ${s}`);let h=$t(new Me({token:c,amount:De(a,d)}));return this.serializer.typedToString(h)+Lt.ArgCompositeSeparator+d}return e}static getChainEntrypoint(t,e){let r="warp-sdk",n="api";return e==="devnet"?new _e(t.apiUrl,n,r):e==="testnet"?new Ne(t.apiUrl,n,r):new Oe(t.apiUrl,n,r)}};var N=class{constructor(t){this.config=t,this.cache=new qe(t.cache?.type),this.core=new Ke(t)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpBuilder: user address not set");let e=zt(this.config),r=new je({chainID:e.chainId}),n=new Ge({config:r}),s=Qt.newFromBech32(this.config.user.wallet),o=JSON.stringify(t),a=n.createTransactionForTransfer(s,{receiver:Qt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(Buffer.from(o))});return a.gasLimit=a.gasLimit+BigInt(2e6),a}async createFromTransaction(t,e=!1){let r=await this.core.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.toBech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=Je.Warp(this.config.env,t);if(e){let a=this.cache.get(r);if(a)return Ht.info(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),a}let n=zt(this.config),o=m.getChainEntrypoint(n,this.config.env).createNetworkProvider();try{let a=await o.getTransaction(t),u=await this.createFromTransaction(a);return e&&e.ttl&&u&&this.cache.set(r,u,e.ttl),u}catch(a){return Ht.error("WarpBuilder: Error creating from transaction hash",a),null}}};import{AbiRegistry as jt,Address as T,AddressValue as nt,BytesValue as g,SmartContractTransactionsFactory as Ye,TransactionsFactoryConfig as Ze}from"@multiversx/sdk-core";import{getMainChainInfo as at,toTypedChainInfo as Gt,WarpCache as tr,WarpCacheKey as V,WarpConfig as er,WarpLogger as F}from"@vleap/warps";var rt={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 U=i=>({hash:i.hash.toString("hex"),alias:i.alias?.toString()||null,trust:i.trust.toString(),owner:i.owner.toString(),createdAt:i.created_at.toNumber(),upgradedAt:i.upgraded_at?.toNumber(),brand:i.brand?.toString("hex")||null,upgrade:i.upgrade?.toString("hex")||null}),Dt=i=>({unitPrice:BigInt(i.unit_price.toString()),admins:i.admins.map(t=>t.toBech32())});var $=class{constructor(t){this.config=t,this.cache=new tr(t.cache?.type),this.registryConfig={unitPrice:BigInt(0),admins:[]}}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e,r){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let n=T.newFromBech32(this.config.user.wallet),s=()=>this.isCurrentUserAdmin()?BigInt(0):e&&r?this.registryConfig.unitPrice*BigInt(3):e?this.registryConfig.unitPrice*BigInt(2):this.registryConfig.unitPrice,o=()=>e&&r?[g.fromHex(t),g.fromUTF8(e),g.fromHex(r)]:e?[g.fromHex(t),g.fromUTF8(e)]:[g.fromHex(t)];return this.getFactory().createTransactionForExecute(n,{contract:this.getRegistryContractAddress(),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:s(),arguments:o()})}createWarpUnregisterTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromUTF8(t),g.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(t),g.fromUTF8(e)]})}createWarpVerifyTransaction(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"verifyWarp",gasLimit:BigInt(1e7),arguments:[g.fromHex(t)]})}createWarpTransferOwnershipTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"transferOwnership",gasLimit:BigInt(1e7),arguments:[g.fromHex(t),new nt(new T(e))]})}createBrandRegisterTransaction(t){if(this.registryConfig.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let r=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(r,{contract:this.getRegistryContractAddress(),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.isCurrentUserAdmin()?void 0:this.registryConfig.unitPrice,arguments:[g.fromHex(t),g.fromHex(e)]})}async getInfoByAlias(t,e){try{let r=V.RegistryInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return F.info(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),n;let s=this.getRegistryContractAddress(),o=this.getController(),a=o.createQuery({contract:s,function:"getInfoByAlias",arguments:[g.fromUTF8(t)]}),u=await o.runQuery(a),[c]=o.parseQueryResponse(u),p=c?U(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}catch{return{registryInfo:null,brand:null}}}async getInfoByHash(t,e){try{let r=V.RegistryInfo(this.config.env,t);if(e){let l=this.cache.get(r);if(l)return F.info(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let n=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:n,function:"getInfoByHash",arguments:[g.fromHex(t)]}),a=await s.runQuery(o),[u]=s.parseQueryResponse(a),c=u?U(u):null,p=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:p},e.ttl),{registryInfo:c,brand:p}}catch{return{registryInfo:null,brand:null}}}async getUserWarpRegistryInfos(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getUserWarps",arguments:[new nt(new T(e))]}),o=await n.runQuery(s),[a]=n.parseQueryResponse(o);return a.map(U)}catch{return[]}}async getUserBrands(t){try{let e=t||this.config.user?.wallet;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getUserBrands",arguments:[new nt(new T(e))]}),o=await n.runQuery(s),[a]=n.parseQueryResponse(o),u=a.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(u.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}catch{return[]}}async getChainInfos(t){let e=V.ChainInfos(this.config.env);if(t&&t.ttl){let c=this.cache.get(e);if(c)return F.info("WarpRegistry (getChainInfos): ChainInfos found in cache"),c}let r=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:r,function:"getChains",arguments:[]}),o=await n.runQuery(s),[a]=n.parseQueryResponse(o),u=a.map(Gt);if(t&&t.ttl){for(let c of u)this.cache.set(V.ChainInfo(this.config.env,c.chain),c,t.ttl);this.cache.set(e,u,t.ttl)}return u}async getChainInfo(t,e){try{let r=V.ChainInfo(this.config.env,t),n=e?this.cache.get(r):null;if(n)return F.info(`WarpRegistry (getChainInfo): ChainInfo found in cache: ${t}`),n;let s=this.getRegistryContractAddress(),o=this.getController(),a=o.createQuery({contract:s,function:"getChain",arguments:[g.fromUTF8(t)]}),u=await o.runQuery(a),[c]=o.parseQueryResponse(u),p=c?Gt(c):null;return e&&e.ttl&&p&&this.cache.set(r,p,e.ttl),p}catch{return null}}async setChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"setChain",gasLimit:BigInt(1e7),arguments:[v(t.name),v(t.displayName),v(t.chainId),Ut(t.blockTime),v(t.addressHrp),v(t.apiUrl),v(t.explorerUrl),v(t.nativeToken)]})}async removeChain(t){if(!this.config.user?.wallet)throw new Error("WarpRegistry: user address not set");let e=T.newFromBech32(this.config.user.wallet);return this.getFactory().createTransactionForExecute(e,{contract:this.getRegistryContractAddress(),function:"removeChain",gasLimit:BigInt(1e7),arguments:[v(t)]})}async fetchBrand(t,e){let r=V.Brand(this.config.env,t),n=e?this.cache.get(r):null;if(n)return F.info(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n;let s=at(this.config),a=m.getChainEntrypoint(s,this.config.env).createNetworkProvider();try{let u=await a.getTransaction(t),c=JSON.parse(u.data.toString());return c.meta={hash:u.hash,creator:u.sender.bech32(),createdAt:new Date(u.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,c,e.ttl),c}catch{return null}}getRegistryContractAddress(){return T.newFromBech32(this.config.registry?.contract||er.Registry.Contract(this.config.env))}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),[r]=await e.query({contract:t,function:"getConfig",arguments:[]}),n=r?Dt(r):null;this.registryConfig=n||{unitPrice:BigInt(0),admins:[]}}getFactory(){let t=at(this.config),e=new Ze({chainID:t.chainId}),r=jt.create(rt);return new Ye({config:e,abi:r})}getController(){let t=at(this.config),e=m.getChainEntrypoint(t,this.config.env),r=jt.create(rt);return e.createSmartContractController(r)}isCurrentUserAdmin(){return!!this.config.user?.wallet&&this.registryConfig.admins.includes(this.config.user.wallet)}};var ma=i=>({chain:"multiversx",builder:new N(i),executor:new m(i),results:new E(i),serializer:new x,registry:new $(i)});import{Address as Kt,TransactionsFactoryConfig as rr,TransferTransactionsFactory as nr}from"@multiversx/sdk-core";import{getMainChainInfo as qt,WarpBrandBuilder as ar,WarpLogger as ir}from"@vleap/warps";import{Buffer as sr}from"buffer";var Jt=class{constructor(t){this.config=t,this.core=new ar(t)}createInscriptionTransaction(t){if(!this.config.user?.wallet)throw new Error("BrandBuilder: user address not set");let e=qt(this.config),r=new rr({chainID:e.chainId}),n=new nr({config:r}),s=Kt.newFromBech32(this.config.user.wallet),o=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer(s,{receiver:Kt.newFromBech32(this.config.user.wallet),nativeAmount:BigInt(0),data:Uint8Array.from(sr.from(o))})}async createFromTransaction(t,e=!1){return await this.core.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=qt(this.config),n=m.getChainEntrypoint(e,this.config.env).createNetworkProvider();try{let s=await n.getTransaction(t);return this.createFromTransaction(s)}catch(s){return ir.error("BrandBuilder: Error creating from transaction hash",s),null}}};export{B as WarpMultiversxAbi,Jt as WarpMultiversxBrandBuilder,N as WarpMultiversxBuilder,or as WarpMultiversxConstants,O as WarpMultiversxContractLoader,m as WarpMultiversxExecutor,$ as WarpMultiversxRegistry,E as WarpMultiversxResults,x as WarpMultiversxSerializer,gn as address_value,ln as biguint_value,fn as boolean_value,mn as codemeta_value,on as composite_value,$t as esdt_value,ma as getMultiversxAdapter,yn as hex_value,an as list_value,hn as nothing_value,rn as option_value,nn as optional_value,v as string_value,dn as token_value,un as u16_value,Ut as u32_value,pn as u64_value,cn as u8_value,sn 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.
|
|
3
|
+
"version": "0.2.0-alpha.8",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -31,6 +31,6 @@
|
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"@multiversx/sdk-core": "^14.2.1",
|
|
34
|
-
"@vleap/warps": "^3.0.0-alpha.
|
|
34
|
+
"@vleap/warps": "^3.0.0-alpha.44"
|
|
35
35
|
}
|
|
36
36
|
}
|