@vleap/warps 0.9.5 → 0.9.7
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 +2 -3
- package/dist/index.d.ts +2 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -294,8 +294,8 @@ declare class WarpBuilder {
|
|
|
294
294
|
private pendingWarp;
|
|
295
295
|
constructor(config: WarpConfig);
|
|
296
296
|
createInscriptionTransaction(warp: Warp): Transaction;
|
|
297
|
-
createFromRaw(encoded: string,
|
|
298
|
-
createFromTransaction(tx: TransactionOnNetwork,
|
|
297
|
+
createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
|
|
298
|
+
createFromTransaction(tx: TransactionOnNetwork, validate?: boolean): Promise<Warp>;
|
|
299
299
|
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
300
300
|
setName(name: string): WarpBuilder;
|
|
301
301
|
setTitle(title: string): WarpBuilder;
|
|
@@ -306,7 +306,6 @@ declare class WarpBuilder {
|
|
|
306
306
|
build(): Promise<Warp>;
|
|
307
307
|
getDescriptionPreview(description: string, maxChars?: number): string;
|
|
308
308
|
private ensure;
|
|
309
|
-
private ensureValidSchema;
|
|
310
309
|
}
|
|
311
310
|
|
|
312
311
|
declare class WarpContractLoader {
|
package/dist/index.d.ts
CHANGED
|
@@ -294,8 +294,8 @@ declare class WarpBuilder {
|
|
|
294
294
|
private pendingWarp;
|
|
295
295
|
constructor(config: WarpConfig);
|
|
296
296
|
createInscriptionTransaction(warp: Warp): Transaction;
|
|
297
|
-
createFromRaw(encoded: string,
|
|
298
|
-
createFromTransaction(tx: TransactionOnNetwork,
|
|
297
|
+
createFromRaw(encoded: string, validate?: boolean): Promise<Warp>;
|
|
298
|
+
createFromTransaction(tx: TransactionOnNetwork, validate?: boolean): Promise<Warp>;
|
|
299
299
|
createFromTransactionHash(hash: string, cache?: WarpCacheConfig): Promise<Warp | null>;
|
|
300
300
|
setName(name: string): WarpBuilder;
|
|
301
301
|
setTitle(title: string): WarpBuilder;
|
|
@@ -306,7 +306,6 @@ declare class WarpBuilder {
|
|
|
306
306
|
build(): Promise<Warp>;
|
|
307
307
|
getDescriptionPreview(description: string, maxChars?: number): string;
|
|
308
308
|
private ensure;
|
|
309
|
-
private ensureValidSchema;
|
|
310
309
|
}
|
|
311
310
|
|
|
312
311
|
declare class WarpContractLoader {
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var tt=Object.create;var F=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var nt=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var st=(a,t)=>{for(var e in t)F(a,e,{get:t[e],enumerable:!0})},H=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rt(t))!it.call(a,i)&&i!==e&&F(a,i,{get:()=>t[i],enumerable:!(r=et(t,i))||r.enumerable});return a};var k=(a,t,e)=>(e=a!=null?tt(nt(a)):{},H(t||!a||!a.__esModule?F(e,"default",{value:a,enumerable:!0}):e,a)),at=a=>H(F({},"__esModule",{value:!0}),a);var xt={};st(xt,{BrandBuilder:()=>L,Config:()=>h,WarpActionExecutor:()=>q,WarpArgSerializer:()=>V,WarpBuilder:()=>U,WarpConstants:()=>w,WarpContractLoader:()=>S,WarpIndex:()=>_,WarpLink:()=>P,WarpRegistry:()=>R,WarpUtils:()=>b,address:()=>Tt,biguint:()=>yt,boolean:()=>wt,codemeta:()=>bt,composite:()=>lt,esdt:()=>It,getChainId:()=>T,getLatestProtocolIdentifier:()=>v,hex:()=>Ct,list:()=>ut,nothing:()=>At,option:()=>ot,optional:()=>ct,shiftBigintBy:()=>N,string:()=>dt,toPreviewText:()=>O,toTypedRegistryInfo:()=>x,token:()=>Wt,u16:()=>ft,u32:()=>mt,u64:()=>ht,u8:()=>gt,variadic:()=>pt});module.exports=at(xt);var W=require("@multiversx/sdk-core"),j=k(require("ajv"));var h={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.4.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.4.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var T=a=>a==="devnet"?"D":a==="testnet"?"T":"1",v=a=>`${a}:${h.LatestProtocolVersion}`,x=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),creator:a.creator.toString(),createdAt:a.created_at.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),N=(a,t)=>{let e=a.toString(),[r,i=""]=e.split("."),s=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(s,"0"));if(t<0){let o=r+i;if(s>=o.length)return 0n;let u=o.slice(0,-s)||"0";return BigInt(u)}else return BigInt(a)},O=(a,t=100)=>{if(!a)return"";let e=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};var L=class{constructor(t){this.pendingBrand={protocol:v(h.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new W.TransactionsFactoryConfig({chainID:T(this.config.env)}),r=new W.TransferTransactionsFactory({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:W.Address.newFromBech32(this.config.userAddress),receiver:W.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=new W.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||h.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new j.default,o=s.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};var w={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var c=require("@multiversx/sdk-core/out"),ot=(a,t)=>a?c.OptionValue.newProvided(a):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),ct=(a,t)=>a?new c.OptionalValue(a.getType(),a):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),ut=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new c.List(t,a)},pt=a=>c.VariadicValue.fromItems(...a),lt=a=>{let t=a.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),a)},dt=a=>c.StringValue.fromUTF8(a),gt=a=>new c.U8Value(a),ft=a=>new c.U16Value(a),mt=a=>new c.U32Value(a),ht=a=>new c.U64Value(a),yt=a=>new c.BigUIntValue(BigInt(a)),wt=a=>new c.BooleanValue(a),Tt=a=>new c.AddressValue(c.Address.newFromBech32(a)),Wt=a=>new c.TokenIdentifierValue(a),Ct=a=>c.BytesValue.fromHex(a),It=a=>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(a.token.identifier),"token_identifier"),new c.Field(new c.U64Value(BigInt(a.token.nonce)),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(a.amount)),"amount")]),bt=a=>new c.CodeMetadataValue(c.CodeMetadata.fromBuffer(Buffer.from(a,"hex"))),At=()=>new c.NothingValue;var f=require("@multiversx/sdk-core/out");var n=require("@multiversx/sdk-core/out"),y=":",C="|",M=new RegExp(`${y}(.*)`),V=class{nativeToString(t,e){return t==="esdt"&&e instanceof n.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}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(),i=e.map(o=>this.typedToString(o).split(y)[0])[0],s=e.map(o=>this.typedToString(o).split(y)[1]);return`list:${i}:${s.join(",")}`}if(t.hasClassOrSuperclass(n.VariadicValue.ClassName)){let e=t.getItems(),i=e.map(o=>this.typedToString(o).split(y)[0])[0],s=e.map(o=>this.typedToString(o).split(y)[1]);return`variadic:${i}:${s.join(",")}`}if(t.hasClassOrSuperclass(n.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(u=>this.typedToString(u).split(y)[0]),i=e.map(u=>this.typedToString(u).split(y)[1]),s=r.join(C),o=i.join(C);return`composite(${s}):${o}`}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName))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(),i=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${i}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new n.CompositeType(...e.split(C).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}`)}stringToNative(t){let e=t.split(y),r=e[0],i=e.slice(1).join(y);if(r==="null")return[r,null];if(r==="option"){let[s,o]=i.split(y);return[`option:${s}`,o||null]}else if(r==="optional"){let[s,o]=i.split(y);return[`optional:${s}`,o||null]}else if(r==="list"){let s=i.split(y),o=s.slice(0,-1).join(y),u=s[s.length-1],l=(u?u.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`list:${o}`,l]}else if(r==="variadic"){let s=i.split(y),o=s.slice(0,-1).join(y),u=s[s.length-1],l=(u?u.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`variadic:${o}`,l]}else if(r.startsWith("composite")){let s=r.match(/\(([^)]+)\)/)?.[1]?.split(C),u=i.split(C).map((d,l)=>this.stringToNative(`${s[l]}:${d}`)[1]);return[r,u]}else{if(r==="string")return[r,i];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(i)];if(r==="uint64"||r==="biguint")return[r,BigInt(i||0)];if(r==="bool")return[r,i==="true"];if(r==="address")return[r,i];if(r==="token")return[r,i];if(r==="hex")return[r,i];if(r==="codemeta")return[r,i];if(r==="esdt"){let[s,o,u]=i.split(C);return[r,new n.TokenTransfer({token:new n.Token({identifier:s,nonce:BigInt(o)}),amount:BigInt(u)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new n.NothingValue;if(e==="option"){let i=this.stringToTyped(r);return i instanceof n.NothingValue?n.OptionValue.newMissingTyped(i.getType()):n.OptionValue.newProvided(i)}if(e==="optional"){let i=this.stringToTyped(r);return i instanceof n.NothingValue?n.OptionalValue.newMissing():new n.OptionalValue(i.getType(),i)}if(e==="list"){let[i,s]=r.split(M,2),u=s.split(",").map(d=>this.stringToTyped(`${i}:${d}`));return new n.List(this.nativeToType(i),u)}if(e==="variadic"){let[i,s]=r.split(M,2),u=s.split(",").map(d=>this.stringToTyped(`${i}:${d}`));return new n.VariadicValue(new n.VariadicType(this.nativeToType(i)),u)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],s=r.split(C),o=i.split(C),u=s.map((l,g)=>this.stringToTyped(`${o[g]}:${l}`)),d=u.map(l=>l.getType());return new n.CompositeValue(new n.CompositeType(...d),u)}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.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let i=r.split(C);return new n.Struct(this.nativeToType("esdt"),[new n.Field(new n.TokenIdentifierValue(i[0]),"token_identifier"),new n.Field(new n.U64Value(BigInt(i[1])),"token_nonce"),new n.Field(new n.BigUIntValue(BigInt(i[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){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 (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var z=require("@multiversx/sdk-core/out"),S=class{constructor(t){this.config=t}async getContract(t){try{let r=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}getConfiguredChainApi(){if(!this.config.chainApiUrl)throw new Error("WarpContract: Chain API URL not set");return new z.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4})}};var q=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new V,this.contractLoader=new S(t)}createTransactionForExecute(t,e,r){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=f.Address.newFromBech32(this.config.userAddress),s=f.Address.newFromBech32(t.address),o=new f.TransactionsFactoryConfig({chainID:T(this.config.env)}),{args:u,value:d,transfers:l}=this.getTxComponentsFromInputs(t,e,r),g=u.map(m=>this.serializer.stringToTyped(m));return s.isContractAddress()?new f.SmartContractTransactionsFactory({config:o}).createTransactionForExecute({sender:i,contract:s,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:g,tokenTransfers:l,nativeTransferAmount:d}):new f.TransferTransactionsFactory({config:o}).createTransactionForTransfer({sender:i,receiver:s,nativeAmount:d,tokenTransfers:l,data:g[0]?.hasExactClass(f.StringValue.ClassName)?g[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=new f.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4}),i=new f.QueryRunnerAdapter({networkProvider:r}),s=await this.getAbiForAction(t),{args:o}=this.getTxComponentsFromInputs(t,e,[]),u=o.map($=>this.serializer.stringToTyped($)),d=new f.SmartContractQueriesController({queryRunner:i,abi:s}),l=d.createQuery({contract:t.address,function:t.func,arguments:u}),g=await d.runQuery(l),m=new f.ResultsParser,E={returnCode:g.returnCode,returnMessage:g.returnMessage,getReturnDataParts:()=>g.returnDataParts.map($=>Buffer.from($))},X=g.function,Y=s.getEndpoint(X),Q=m.parseQueryResponse(E,Y).firstValue;if(!Q)throw new Error("WarpActionExecutor: Query result not found");return Q}async executeCollect(t,e,r){let i=new Headers;i.set("Content-Type","application/json"),i.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([s,o])=>{i.set(s,o)}),await fetch(t.destination.url,{method:t.destination.method,headers:i,body:JSON.stringify({inputs:e,meta:r})})}getTxComponentsFromInputs(t,e,r){let i=this.getResolvedInputs(t,e),s=this.getModifiedInputs(i),o=this.getPreparedArgs(t,s),u=s.find(E=>E.input.position==="value")?.value||null,d="value"in t?t.value:null,l=BigInt(u?.split(":")[1]||d||0),m=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...r];return{args:o,value:l,transfers:m}}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,i]=e.input.modifier.split(":");if(isNaN(Number(i))){let s=Number(t.find(d=>d.input.name===i)?.value?.split(":")[1]);if(!s)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let o=e.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let u=N(o,+s);return{...e,value:`${e.input.type}:${u}`}}else{let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=N(s,+i);return{...e,value:`${e.input.type}:${o}`}}}else return e})}getResolvedInputs(t,e){let r=t.inputs||[],i=(s,o)=>s.source==="query"?this.serializer.nativeToString(s.type,this.url.searchParams.get(s.name)||""):e[o]||null;return r.map((s,o)=>({input:s,value:i(s,o)}))}getPreparedArgs(t,e){let r="args"in t?t.args:[];return e.forEach(({input:i,value:s})=>{if(!s||!i.position.startsWith("arg:"))return;let o=Number(i.position.split(":")[1])-1;r.splice(o,0,s)}),r}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return f.AbiRegistry.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");let r=await(await fetch(t.abi)).json();return f.AbiRegistry.create(r)}toTypedTransfer(t){return new f.TokenTransfer({token:new f.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var I=require("@multiversx/sdk-core"),Z=k(require("ajv"));var B={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},A=class{constructor(){this.cache=new Map}set(t,e,r){let i=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:i})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};var G=k(require("qr-code-styling"));var p=require("@multiversx/sdk-core/out");var D={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},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:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],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:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var R=class{constructor(t){this.cache=new A;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:p.Address.newFromBech32(this.config.userAddress),contract:p.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[p.BytesValue.fromHex(t),p.BytesValue.fromUTF8(e)]:[p.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:p.Address.newFromBech32(this.config.userAddress),contract:p.Address.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[p.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:p.Address.newFromBech32(this.config.userAddress),contract:p.Address.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[p.BytesValue.fromUTF8(t),p.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:p.Address.newFromBech32(this.config.userAddress),contract:p.Address.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[p.BytesValue.fromHex(t),p.BytesValue.fromUTF8(e)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:p.Address.newFromBech32(this.config.userAddress),contract:p.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[p.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:p.Address.newFromBech32(this.config.userAddress),contract:p.Address.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[p.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:p.Address.newFromBech32(this.config.userAddress),contract:p.Address.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[p.BytesValue.fromHex(t),p.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=B.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),m}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[p.BytesValue.fromUTF8(t)]}),u=await s.runQuery(o),[d]=s.parseQueryResponse(u),l=d?x(d):null,g=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:g},e.ttl),{registryInfo:l,brand:g}}async getInfoByHash(t,e){let r=B.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),m}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByHash",arguments:[p.BytesValue.fromHex(t)]}),u=await s.runQuery(o),[d]=s.parseQueryResponse(u),l=d?x(d):null,g=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:g},e.ttl),{registryInfo:l,brand:g}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:r,function:"getUserWarps",arguments:[new p.AddressValue(new p.Address(e))]}),o=await i.runQuery(s),[u]=i.parseQueryResponse(o);return u.map(x)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:r,function:"getUserBrands",arguments:[new p.AddressValue(new p.Address(e))]}),o=await i.runQuery(s),[u]=i.parseQueryResponse(o),d=u.map(m=>m.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(d.map(m=>this.fetchBrand(m,l)))).filter(m=>m!==null)}async fetchBrand(t,e){let r=B.Brand(t);if(e){let s=this.cache.get(r);if(s)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),s}let i=new p.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let s=await i.getTransaction(t),o=JSON.parse(s.data.toString());return o.meta={hash:s.hash,creator:s.sender.bech32(),createdAt:new Date(s.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(s){return console.error("WarpRegistry: Error fetching brand from transaction hash",s),null}}getRegistryContractAddress(){return this.config.registryContract||h.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await e.runQuery(r),[s]=e.parseQueryResponse(i),o=BigInt(s.toString());this.unitPrice=o}getFactory(){let t=new p.TransactionsFactoryConfig({chainID:T(this.config.env)}),e=p.AbiRegistry.create(D);return new p.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env),e=new p.ApiNetworkProvider(t,{timeout:3e4}),r=new p.QueryRunnerAdapter({networkProvider:e}),i=p.AbiRegistry.create(D);return new p.SmartContractQueriesController({queryRunner:r,abi:i})}};var P=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(w.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),o=(await Promise.all(i)).filter(l=>l.match),u=o.length>0,d=o.map(l=>({url:l.url,warp:l.warp}));return{match:u,results:d}}async detect(t){let e=t.startsWith(w.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):b.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,s=new U(this.config),o=new R(this.config),u=null,d=null,l=null;if(r==="hash"){u=await s.createFromTransactionHash(i);try{let{registryInfo:g,brand:m}=await o.getInfoByHash(i);d=g,l=m}catch{}}else if(r==="alias"){let{registryInfo:g,brand:m}=await o.getInfoByAlias(i);d=g,l=m,g&&(u=await s.createFromTransactionHash(g.hash))}return u?{match:!0,url:t,warp:u,registryInfo:d,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||h.DefaultClientUrl(this.config.env),i=t===w.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+w.IdentifierParamSeparator+e);return h.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${w.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",s="black",o="#23F7DD"){let u=this.build(t,e);return new G.default({type:"svg",width:r,height:r,data:String(u),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=h.SuperClientUrls.includes(e.origin),i=e.searchParams.get(w.IdentifierParamName),s=r&&!i?e.pathname.split("/")[1]:i;if(!s)return null;let o=decodeURIComponent(s);return b.getInfoFromPrefixedIdentifier(o)}};var vt="https://",J="query",K="env",b=class a{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),i=(s,o)=>{r=r.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([s,o])=>{if(typeof o=="string"&&o.startsWith(`${J}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let u=o.split(`${J}:`)[1],d=new URL(e.currentUrl).searchParams.get(u);d&&i(s,d)}else if(typeof o=="string"&&o.startsWith(`${K}:`)){let u=o.split(`${K}:`)[1],d=e.vars?.[u];d&&i(s,d)}else i(s,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(w.IdentifierParamSeparator)?e:`${w.DefaultIdentifierType}${w.IdentifierParamSeparator}${e}`,[i,s]=r.split(w.IdentifierParamSeparator);return{type:i,id:s}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(vt))return t.next;{let r=new P(e),i=a.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}};var U=class{constructor(t){this.cache=new A;this.pendingWarp={protocol:v(h.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new I.TransactionsFactoryConfig({chainID:T(this.config.env)}),r=new I.TransferTransactionsFactory({config:e}),i=JSON.stringify(t),s=r.createTransactionForTransfer({sender:I.Address.newFromBech32(this.config.userAddress),receiver:I.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return s.gasLimit=s.gasLimit+BigInt(2e6),s}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),b.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=B.Warp(t);if(e){let s=this.cache.get(r);if(s)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),s}let i=new I.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let s=await i.getTransaction(t),o=await this.createFromTransaction(s);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(s){return console.error("WarpBuilder: Error creating from transaction hash",s),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return O(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||h.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new Z.default,o=s.compile(i);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};var _=class{constructor(t){this.config=t}async search(t){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let e=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t})});if(!e.ok)throw new Error(`WarpIndex: search failed with status ${e.status}`);return(await e.json()).hits}catch(e){throw console.error("WarpIndex: Error searching for warps: ",e),e}}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpConstants,WarpContractLoader,WarpIndex,WarpLink,WarpRegistry,WarpUtils,address,biguint,boolean,codemeta,composite,esdt,getChainId,getLatestProtocolIdentifier,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
|
|
1
|
+
"use strict";var tt=Object.create;var xe=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var at=(g,e)=>{for(var n in e)xe(g,n,{get:e[n],enumerable:!0})},He=(g,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of nt(e))!st.call(g,s)&&s!==n&&xe(g,s,{get:()=>e[s],enumerable:!(a=rt(e,s))||a.enumerable});return g};var Oe=(g,e,n)=>(n=g!=null?tt(it(g)):{},He(e||!g||!g.__esModule?xe(n,"default",{value:g,enumerable:!0}):n,g)),ot=g=>He(xe({},"__esModule",{value:!0}),g);var Nt={};at(Nt,{BrandBuilder:()=>Fe,Config:()=>$,WarpActionExecutor:()=>_e,WarpArgSerializer:()=>we,WarpBuilder:()=>Ce,WarpConstants:()=>Q,WarpContractLoader:()=>Te,WarpIndex:()=>qe,WarpLink:()=>Ie,WarpRegistry:()=>Ae,WarpUtils:()=>ue,address:()=>At,biguint:()=>wt,boolean:()=>Tt,codemeta:()=>Wt,composite:()=>ft,esdt:()=>Bt,getChainId:()=>ne,getLatestProtocolIdentifier:()=>me,hex:()=>Ct,list:()=>lt,nothing:()=>vt,option:()=>ct,optional:()=>ut,shiftBigintBy:()=>be,string:()=>gt,toPreviewText:()=>Ue,toTypedRegistryInfo:()=>ye,token:()=>It,u16:()=>ht,u32:()=>mt,u64:()=>yt,u8:()=>dt,variadic:()=>pt});module.exports=ot(Nt);var ie=require("@multiversx/sdk-core"),Qe=Oe(require("ajv"));var $={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.4.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.4.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:g=>g==="devnet"?"https://devnet.usewarp.to":g==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:g=>g==="devnet"?"https://devnet-api.multiversx.com":g==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:g=>g==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":g==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var ne=g=>g==="devnet"?"D":g==="testnet"?"T":"1",me=g=>`${g}:${$.LatestProtocolVersion}`,ye=g=>({hash:g.hash.toString("hex"),alias:g.alias?.toString()||null,trust:g.trust.toString(),creator:g.creator.toString(),createdAt:g.created_at.toNumber(),brand:g.brand?.toString("hex")||null,upgrade:g.upgrade?.toString("hex")||null}),be=(g,e)=>{let n=g.toString(),[a,s=""]=n.split("."),h=Math.abs(e);if(e>0)return BigInt(a+s.padEnd(h,"0"));if(e<0){let w=a+s;if(h>=w.length)return 0n;let I=w.slice(0,-h)||"0";return BigInt(I)}else return BigInt(g)},Ue=(g,e=100)=>{if(!g)return"";let n=g.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return n=n.startsWith("- ")?n.slice(2):n,n=n.length>e?n.substring(0,n.lastIndexOf(" ",e))+"...":n,n};var Fe=class{constructor(e){this.pendingBrand={protocol:me($.ProtocolNameBrand),name:"",description:"",logo:""};this.config=e}createInscriptionTransaction(e){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let n=new ie.TransactionsFactoryConfig({chainID:ne(this.config.env)}),a=new ie.TransferTransactionsFactory({config:n}),s=JSON.stringify(e);return a.createTransactionForNativeTokenTransfer({sender:ie.Address.newFromBech32(this.config.userAddress),receiver:ie.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(s).valueOf()})}async createFromRaw(e,n=!0){let a=JSON.parse(e);return n&&await this.ensureValidSchema(a),a}async createFromTransaction(e,n=!1){return await this.createFromRaw(e.data.toString(),n)}async createFromTransactionHash(e){let n=new ie.ApiNetworkProvider(this.config.chainApiUrl||$.Chain.ApiUrl(this.config.env));try{let a=await n.getTransaction(e);return this.createFromTransaction(a)}catch(a){return console.error("BrandBuilder: Error creating from transaction hash",a),null}}setName(e){return this.pendingBrand.name=e,this}setDescription(e){return this.pendingBrand.description=e,this}setLogo(e){return this.pendingBrand.logo=e,this}setUrls(e){return this.pendingBrand.urls=e,this}setColors(e){return this.pendingBrand.colors=e,this}setCta(e){return this.pendingBrand.cta=e,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(e,n){if(!e)throw new Error(`Warp: ${n}`)}async ensureValidSchema(e){let n=this.config.brandSchemaUrl||$.LatestBrandSchemaUrl,s=await(await fetch(n)).json(),h=new Qe.default,w=h.compile(s);if(!w(e))throw new Error(`BrandBuilder: schema validation failed: ${h.errorsText(w.errors)}`)}};var Q={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var C=require("@multiversx/sdk-core/out"),ct=(g,e)=>g?C.OptionValue.newProvided(g):e?C.OptionValue.newMissingTyped(e):C.OptionValue.newMissing(),ut=(g,e)=>g?new C.OptionalValue(g.getType(),g):e?new C.OptionalValue(e):C.OptionalValue.newMissing(),lt=g=>{if(g.length===0)throw new Error("Cannot create a list from an empty array");let e=g[0].getType();return new C.List(e,g)},pt=g=>C.VariadicValue.fromItems(...g),ft=g=>{let e=g.map(n=>n.getType());return new C.CompositeValue(new C.CompositeType(...e),g)},gt=g=>C.StringValue.fromUTF8(g),dt=g=>new C.U8Value(g),ht=g=>new C.U16Value(g),mt=g=>new C.U32Value(g),yt=g=>new C.U64Value(g),wt=g=>new C.BigUIntValue(BigInt(g)),Tt=g=>new C.BooleanValue(g),At=g=>new C.AddressValue(C.Address.newFromBech32(g)),It=g=>new C.TokenIdentifierValue(g),Ct=g=>C.BytesValue.fromHex(g),Bt=g=>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(g.token.identifier),"token_identifier"),new C.Field(new C.U64Value(BigInt(g.token.nonce)),"token_nonce"),new C.Field(new C.BigUIntValue(BigInt(g.amount)),"amount")]),Wt=g=>new C.CodeMetadataValue(C.CodeMetadata.fromBuffer(Buffer.from(g,"hex"))),vt=()=>new C.NothingValue;var O=require("@multiversx/sdk-core/out");var y=require("@multiversx/sdk-core/out");var xt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,ke=Math.ceil,J=Math.floor,H="[BigNumber Error] ",Ge=H+"Number primitive has more than 15 significant digits: ",Y=1e14,S=14,$e=9007199254740991,Le=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],ce=1e7,_=1e9;function ze(g){var e,n,a,s=A.prototype={constructor:A,toString:null,valueOf:null},h=new A(1),w=20,I=4,v=-7,B=21,N=-1e7,R=1e7,K=!1,le=1,Z=0,We={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},ee="0123456789abcdefghijklmnopqrstuvwxyz",pe=!0;function A(t,r){var i,f,c,l,m,o,u,d,p=this;if(!(p instanceof A))return new A(t,r);if(r==null){if(t&&t._isBigNumber===!0){p.s=t.s,!t.c||t.e>R?p.c=p.e=null:t.e<N?p.c=[p.e=0]:(p.e=t.e,p.c=t.c.slice());return}if((o=typeof t=="number")&&t*0==0){if(p.s=1/t<0?(t=-t,-1):1,t===~~t){for(l=0,m=t;m>=10;m/=10,l++);l>R?p.c=p.e=null:(p.e=l,p.c=[t]);return}d=String(t)}else{if(!xt.test(d=String(t)))return a(p,d,o);p.s=d.charCodeAt(0)==45?(d=d.slice(1),-1):1}(l=d.indexOf("."))>-1&&(d=d.replace(".","")),(m=d.search(/e/i))>0?(l<0&&(l=m),l+=+d.slice(m+1),d=d.substring(0,m)):l<0&&(l=d.length)}else{if(U(r,2,ee.length,"Base"),r==10&&pe)return p=new A(t),G(p,w+p.e+1,I);if(d=String(t),o=typeof t=="number"){if(t*0!=0)return a(p,d,o,r);if(p.s=1/t<0?(d=d.slice(1),-1):1,A.DEBUG&&d.replace(/^0\.0*|\./,"").length>15)throw Error(Ge+t)}else p.s=d.charCodeAt(0)===45?(d=d.slice(1),-1):1;for(i=ee.slice(0,r),l=m=0,u=d.length;m<u;m++)if(i.indexOf(f=d.charAt(m))<0){if(f=="."){if(m>l){l=u;continue}}else if(!c&&(d==d.toUpperCase()&&(d=d.toLowerCase())||d==d.toLowerCase()&&(d=d.toUpperCase()))){c=!0,m=-1,l=0;continue}return a(p,String(t),o,r)}o=!1,d=n(d,r,10,p.s),(l=d.indexOf("."))>-1?d=d.replace(".",""):l=d.length}for(m=0;d.charCodeAt(m)===48;m++);for(u=d.length;d.charCodeAt(--u)===48;);if(d=d.slice(m,++u)){if(u-=m,o&&A.DEBUG&&u>15&&(t>$e||t!==J(t)))throw Error(Ge+p.s*t);if((l=l-m-1)>R)p.c=p.e=null;else if(l<N)p.c=[p.e=0];else{if(p.e=l,p.c=[],m=(l+1)%S,l<0&&(m+=S),m<u){for(m&&p.c.push(+d.slice(0,m)),u-=S;m<u;)p.c.push(+d.slice(m,m+=S));m=S-(d=d.slice(m)).length}else m-=u;for(;m--;d+="0");p.c.push(+d)}}else p.c=[p.e=0]}A.clone=ze,A.ROUND_UP=0,A.ROUND_DOWN=1,A.ROUND_CEIL=2,A.ROUND_FLOOR=3,A.ROUND_HALF_UP=4,A.ROUND_HALF_DOWN=5,A.ROUND_HALF_EVEN=6,A.ROUND_HALF_CEIL=7,A.ROUND_HALF_FLOOR=8,A.EUCLID=9,A.config=A.set=function(t){var r,i;if(t!=null)if(typeof t=="object"){if(t.hasOwnProperty(r="DECIMAL_PLACES")&&(i=t[r],U(i,0,_,r),w=i),t.hasOwnProperty(r="ROUNDING_MODE")&&(i=t[r],U(i,0,8,r),I=i),t.hasOwnProperty(r="EXPONENTIAL_AT")&&(i=t[r],i&&i.pop?(U(i[0],-_,0,r),U(i[1],0,_,r),v=i[0],B=i[1]):(U(i,-_,_,r),v=-(B=i<0?-i:i))),t.hasOwnProperty(r="RANGE"))if(i=t[r],i&&i.pop)U(i[0],-_,-1,r),U(i[1],1,_,r),N=i[0],R=i[1];else if(U(i,-_,_,r),i)N=-(R=i<0?-i:i);else throw Error(H+r+" cannot be zero: "+i);if(t.hasOwnProperty(r="CRYPTO"))if(i=t[r],i===!!i)if(i)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))K=i;else throw K=!i,Error(H+"crypto unavailable");else K=i;else throw Error(H+r+" not true or false: "+i);if(t.hasOwnProperty(r="MODULO_MODE")&&(i=t[r],U(i,0,9,r),le=i),t.hasOwnProperty(r="POW_PRECISION")&&(i=t[r],U(i,0,_,r),Z=i),t.hasOwnProperty(r="FORMAT"))if(i=t[r],typeof i=="object")We=i;else throw Error(H+r+" not an object: "+i);if(t.hasOwnProperty(r="ALPHABET"))if(i=t[r],typeof i=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(i))pe=i.slice(0,10)=="0123456789",ee=i;else throw Error(H+r+" invalid: "+i)}else throw Error(H+"Object expected: "+t);return{DECIMAL_PLACES:w,ROUNDING_MODE:I,EXPONENTIAL_AT:[v,B],RANGE:[N,R],CRYPTO:K,MODULO_MODE:le,POW_PRECISION:Z,FORMAT:We,ALPHABET:ee}},A.isBigNumber=function(t){if(!t||t._isBigNumber!==!0)return!1;if(!A.DEBUG)return!0;var r,i,f=t.c,c=t.e,l=t.s;e:if({}.toString.call(f)=="[object Array]"){if((l===1||l===-1)&&c>=-_&&c<=_&&c===J(c)){if(f[0]===0){if(c===0&&f.length===1)return!0;break e}if(r=(c+1)%S,r<1&&(r+=S),String(f[0]).length==r){for(r=0;r<f.length;r++)if(i=f[r],i<0||i>=Y||i!==J(i))break e;if(i!==0)return!0}}}else if(f===null&&c===null&&(l===null||l===1||l===-1))return!0;throw Error(H+"Invalid BigNumber: "+t)},A.maximum=A.max=function(){return Me(arguments,-1)},A.minimum=A.min=function(){return Me(arguments,1)},A.random=function(){var t=9007199254740992,r=Math.random()*t&2097151?function(){return J(Math.random()*t)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(i){var f,c,l,m,o,u=0,d=[],p=new A(h);if(i==null?i=w:U(i,0,_),m=ke(i/S),K)if(crypto.getRandomValues){for(f=crypto.getRandomValues(new Uint32Array(m*=2));u<m;)o=f[u]*131072+(f[u+1]>>>11),o>=9e15?(c=crypto.getRandomValues(new Uint32Array(2)),f[u]=c[0],f[u+1]=c[1]):(d.push(o%1e14),u+=2);u=m/2}else if(crypto.randomBytes){for(f=crypto.randomBytes(m*=7);u<m;)o=(f[u]&31)*281474976710656+f[u+1]*1099511627776+f[u+2]*4294967296+f[u+3]*16777216+(f[u+4]<<16)+(f[u+5]<<8)+f[u+6],o>=9e15?crypto.randomBytes(7).copy(f,u):(d.push(o%1e14),u+=7);u=m/7}else throw K=!1,Error(H+"crypto unavailable");if(!K)for(;u<m;)o=r(),o<9e15&&(d[u++]=o%1e14);for(m=d[--u],i%=S,m&&i&&(o=Le[S-i],d[u]=J(m/o)*o);d[u]===0;d.pop(),u--);if(u<0)d=[l=0];else{for(l=-1;d[0]===0;d.splice(0,1),l-=S);for(u=1,o=d[0];o>=10;o/=10,u++);u<S&&(l-=S-u)}return p.e=l,p.c=d,p}}(),A.sum=function(){for(var t=1,r=arguments,i=new A(r[0]);t<r.length;)i=i.plus(r[t++]);return i},n=function(){var t="0123456789";function r(i,f,c,l){for(var m,o=[0],u,d=0,p=i.length;d<p;){for(u=o.length;u--;o[u]*=f);for(o[0]+=l.indexOf(i.charAt(d++)),m=0;m<o.length;m++)o[m]>c-1&&(o[m+1]==null&&(o[m+1]=0),o[m+1]+=o[m]/c|0,o[m]%=c)}return o.reverse()}return function(i,f,c,l,m){var o,u,d,p,T,W,x,V,F=i.indexOf("."),L=w,E=I;for(F>=0&&(p=Z,Z=0,i=i.replace(".",""),V=new A(f),W=V.pow(i.length-F),Z=p,V.c=r(se(j(W.c),W.e,"0"),10,c,t),V.e=V.c.length),x=r(i,f,c,m?(o=ee,t):(o=t,ee)),d=p=x.length;x[--p]==0;x.pop());if(!x[0])return o.charAt(0);if(F<0?--d:(W.c=x,W.e=d,W.s=l,W=e(W,V,L,E,c),x=W.c,T=W.r,d=W.e),u=d+L+1,F=x[u],p=c/2,T=T||u<0||x[u+1]!=null,T=E<4?(F!=null||T)&&(E==0||E==(W.s<0?3:2)):F>p||F==p&&(E==4||T||E==6&&x[u-1]&1||E==(W.s<0?8:7)),u<1||!x[0])i=T?se(o.charAt(1),-L,o.charAt(0)):o.charAt(0);else{if(x.length=u,T)for(--c;++x[--u]>c;)x[u]=0,u||(++d,x=[1].concat(x));for(p=x.length;!x[--p];);for(F=0,i="";F<=p;i+=o.charAt(x[F++]));i=se(i,d,o.charAt(0))}return i}}(),e=function(){function t(f,c,l){var m,o,u,d,p=0,T=f.length,W=c%ce,x=c/ce|0;for(f=f.slice();T--;)u=f[T]%ce,d=f[T]/ce|0,m=x*u+d*W,o=W*u+m%ce*ce+p,p=(o/l|0)+(m/ce|0)+x*d,f[T]=o%l;return p&&(f=[p].concat(f)),f}function r(f,c,l,m){var o,u;if(l!=m)u=l>m?1:-1;else for(o=u=0;o<l;o++)if(f[o]!=c[o]){u=f[o]>c[o]?1:-1;break}return u}function i(f,c,l,m){for(var o=0;l--;)f[l]-=o,o=f[l]<c[l]?1:0,f[l]=o*m+f[l]-c[l];for(;!f[0]&&f.length>1;f.splice(0,1));}return function(f,c,l,m,o){var u,d,p,T,W,x,V,F,L,E,P,D,ve,Ve,Pe,te,he,z=f.s==c.s?1:-1,q=f.c,k=c.c;if(!q||!q[0]||!k||!k[0])return new A(!f.s||!c.s||(q?k&&q[0]==k[0]:!k)?NaN:q&&q[0]==0||!k?z*0:z/0);for(F=new A(z),L=F.c=[],d=f.e-c.e,z=l+d+1,o||(o=Y,d=X(f.e/S)-X(c.e/S),z=z/S|0),p=0;k[p]==(q[p]||0);p++);if(k[p]>(q[p]||0)&&d--,z<0)L.push(1),T=!0;else{for(Ve=q.length,te=k.length,p=0,z+=2,W=J(o/(k[0]+1)),W>1&&(k=t(k,W,o),q=t(q,W,o),te=k.length,Ve=q.length),ve=te,E=q.slice(0,te),P=E.length;P<te;E[P++]=0);he=k.slice(),he=[0].concat(he),Pe=k[0],k[1]>=o/2&&Pe++;do{if(W=0,u=r(k,E,te,P),u<0){if(D=E[0],te!=P&&(D=D*o+(E[1]||0)),W=J(D/Pe),W>1)for(W>=o&&(W=o-1),x=t(k,W,o),V=x.length,P=E.length;r(x,E,V,P)==1;)W--,i(x,te<V?he:k,V,o),V=x.length,u=1;else W==0&&(u=W=1),x=k.slice(),V=x.length;if(V<P&&(x=[0].concat(x)),i(E,x,P,o),P=E.length,u==-1)for(;r(k,E,te,P)<1;)W++,i(E,te<P?he:k,P,o),P=E.length}else u===0&&(W++,E=[0]);L[p++]=W,E[0]?E[P++]=q[ve]||0:(E=[q[ve]],P=1)}while((ve++<Ve||E[0]!=null)&&z--);T=E[0]!=null,L[0]||L.splice(0,1)}if(o==Y){for(p=1,z=L[0];z>=10;z/=10,p++);G(F,l+(F.e=p+d*S-1)+1,m,T)}else F.e=d,F.r=+T;return F}}();function Re(t,r,i,f){var c,l,m,o,u;if(i==null?i=I:U(i,0,8),!t.c)return t.toString();if(c=t.c[0],m=t.e,r==null)u=j(t.c),u=f==1||f==2&&(m<=v||m>=B)?Ne(u,m):se(u,m,"0");else if(t=G(new A(t),r,i),l=t.e,u=j(t.c),o=u.length,f==1||f==2&&(r<=l||l<=v)){for(;o<r;u+="0",o++);u=Ne(u,l)}else if(r-=m,u=se(u,l,"0"),l+1>o){if(--r>0)for(u+=".";r--;u+="0");}else if(r+=l-o,r>0)for(l+1==o&&(u+=".");r--;u+="0");return t.s<0&&c?"-"+u:u}function Me(t,r){for(var i,f,c=1,l=new A(t[0]);c<t.length;c++)f=new A(t[c]),(!f.s||(i=fe(l,f))===r||i===0&&l.s===r)&&(l=f);return l}function Ee(t,r,i){for(var f=1,c=r.length;!r[--c];r.pop());for(c=r[0];c>=10;c/=10,f++);return(i=f+i*S-1)>R?t.c=t.e=null:i<N?t.c=[t.e=0]:(t.e=i,t.c=r),t}a=function(){var t=/^(-?)0([xbo])(?=\w[\w.]*$)/i,r=/^([^.]+)\.$/,i=/^\.([^.]+)$/,f=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(l,m,o,u){var d,p=o?m:m.replace(c,"");if(f.test(p))l.s=isNaN(p)?null:p<0?-1:1;else{if(!o&&(p=p.replace(t,function(T,W,x){return d=(x=x.toLowerCase())=="x"?16:x=="b"?2:8,!u||u==d?W:T}),u&&(d=u,p=p.replace(r,"$1").replace(i,"0.$1")),m!=p))return new A(p,d);if(A.DEBUG)throw Error(H+"Not a"+(u?" base "+u:"")+" number: "+m);l.s=null}l.c=l.e=null}}();function G(t,r,i,f){var c,l,m,o,u,d,p,T=t.c,W=Le;if(T){e:{for(c=1,o=T[0];o>=10;o/=10,c++);if(l=r-c,l<0)l+=S,m=r,u=T[d=0],p=J(u/W[c-m-1]%10);else if(d=ke((l+1)/S),d>=T.length)if(f){for(;T.length<=d;T.push(0));u=p=0,c=1,l%=S,m=l-S+1}else break e;else{for(u=o=T[d],c=1;o>=10;o/=10,c++);l%=S,m=l-S+c,p=m<0?0:J(u/W[c-m-1]%10)}if(f=f||r<0||T[d+1]!=null||(m<0?u:u%W[c-m-1]),f=i<4?(p||f)&&(i==0||i==(t.s<0?3:2)):p>5||p==5&&(i==4||f||i==6&&(l>0?m>0?u/W[c-m]:0:T[d-1])%10&1||i==(t.s<0?8:7)),r<1||!T[0])return T.length=0,f?(r-=t.e+1,T[0]=W[(S-r%S)%S],t.e=-r||0):T[0]=t.e=0,t;if(l==0?(T.length=d,o=1,d--):(T.length=d+1,o=W[S-l],T[d]=m>0?J(u/W[c-m]%W[m])*o:0),f)for(;;)if(d==0){for(l=1,m=T[0];m>=10;m/=10,l++);for(m=T[0]+=o,o=1;m>=10;m/=10,o++);l!=o&&(t.e++,T[0]==Y&&(T[0]=1));break}else{if(T[d]+=o,T[d]!=Y)break;T[d--]=0,o=1}for(l=T.length;T[--l]===0;T.pop());}t.e>R?t.c=t.e=null:t.e<N&&(t.c=[t.e=0])}return t}function re(t){var r,i=t.e;return i===null?t.toString():(r=j(t.c),r=i<=v||i>=B?Ne(r,i):se(r,i,"0"),t.s<0?"-"+r:r)}return s.absoluteValue=s.abs=function(){var t=new A(this);return t.s<0&&(t.s=1),t},s.comparedTo=function(t,r){return fe(this,new A(t,r))},s.decimalPlaces=s.dp=function(t,r){var i,f,c,l=this;if(t!=null)return U(t,0,_),r==null?r=I:U(r,0,8),G(new A(l),t+l.e+1,r);if(!(i=l.c))return null;if(f=((c=i.length-1)-X(this.e/S))*S,c=i[c])for(;c%10==0;c/=10,f--);return f<0&&(f=0),f},s.dividedBy=s.div=function(t,r){return e(this,new A(t,r),w,I)},s.dividedToIntegerBy=s.idiv=function(t,r){return e(this,new A(t,r),0,1)},s.exponentiatedBy=s.pow=function(t,r){var i,f,c,l,m,o,u,d,p,T=this;if(t=new A(t),t.c&&!t.isInteger())throw Error(H+"Exponent not an integer: "+re(t));if(r!=null&&(r=new A(r)),o=t.e>14,!T.c||!T.c[0]||T.c[0]==1&&!T.e&&T.c.length==1||!t.c||!t.c[0])return p=new A(Math.pow(+re(T),o?t.s*(2-Se(t)):+re(t))),r?p.mod(r):p;if(u=t.s<0,r){if(r.c?!r.c[0]:!r.s)return new A(NaN);f=!u&&T.isInteger()&&r.isInteger(),f&&(T=T.mod(r))}else{if(t.e>9&&(T.e>0||T.e<-1||(T.e==0?T.c[0]>1||o&&T.c[1]>=24e7:T.c[0]<8e13||o&&T.c[0]<=9999975e7)))return l=T.s<0&&Se(t)?-0:0,T.e>-1&&(l=1/l),new A(u?1/l:l);Z&&(l=ke(Z/S+2))}for(o?(i=new A(.5),u&&(t.s=1),d=Se(t)):(c=Math.abs(+re(t)),d=c%2),p=new A(h);;){if(d){if(p=p.times(T),!p.c)break;l?p.c.length>l&&(p.c.length=l):f&&(p=p.mod(r))}if(c){if(c=J(c/2),c===0)break;d=c%2}else if(t=t.times(i),G(t,t.e+1,1),t.e>14)d=Se(t);else{if(c=+re(t),c===0)break;d=c%2}T=T.times(T),l?T.c&&T.c.length>l&&(T.c.length=l):f&&(T=T.mod(r))}return f?p:(u&&(p=h.div(p)),r?p.mod(r):l?G(p,Z,I,m):p)},s.integerValue=function(t){var r=new A(this);return t==null?t=I:U(t,0,8),G(r,r.e+1,t)},s.isEqualTo=s.eq=function(t,r){return fe(this,new A(t,r))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(t,r){return fe(this,new A(t,r))>0},s.isGreaterThanOrEqualTo=s.gte=function(t,r){return(r=fe(this,new A(t,r)))===1||r===0},s.isInteger=function(){return!!this.c&&X(this.e/S)>this.c.length-2},s.isLessThan=s.lt=function(t,r){return fe(this,new A(t,r))<0},s.isLessThanOrEqualTo=s.lte=function(t,r){return(r=fe(this,new A(t,r)))===-1||r===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(t,r){var i,f,c,l,m=this,o=m.s;if(t=new A(t,r),r=t.s,!o||!r)return new A(NaN);if(o!=r)return t.s=-r,m.plus(t);var u=m.e/S,d=t.e/S,p=m.c,T=t.c;if(!u||!d){if(!p||!T)return p?(t.s=-r,t):new A(T?m:NaN);if(!p[0]||!T[0])return T[0]?(t.s=-r,t):new A(p[0]?m:I==3?-0:0)}if(u=X(u),d=X(d),p=p.slice(),o=u-d){for((l=o<0)?(o=-o,c=p):(d=u,c=T),c.reverse(),r=o;r--;c.push(0));c.reverse()}else for(f=(l=(o=p.length)<(r=T.length))?o:r,o=r=0;r<f;r++)if(p[r]!=T[r]){l=p[r]<T[r];break}if(l&&(c=p,p=T,T=c,t.s=-t.s),r=(f=T.length)-(i=p.length),r>0)for(;r--;p[i++]=0);for(r=Y-1;f>o;){if(p[--f]<T[f]){for(i=f;i&&!p[--i];p[i]=r);--p[i],p[f]+=Y}p[f]-=T[f]}for(;p[0]==0;p.splice(0,1),--d);return p[0]?Ee(t,p,d):(t.s=I==3?-1:1,t.c=[t.e=0],t)},s.modulo=s.mod=function(t,r){var i,f,c=this;return t=new A(t,r),!c.c||!t.s||t.c&&!t.c[0]?new A(NaN):!t.c||c.c&&!c.c[0]?new A(c):(le==9?(f=t.s,t.s=1,i=e(c,t,0,3),t.s=f,i.s*=f):i=e(c,t,0,le),t=c.minus(i.times(t)),!t.c[0]&&le==1&&(t.s=c.s),t)},s.multipliedBy=s.times=function(t,r){var i,f,c,l,m,o,u,d,p,T,W,x,V,F,L,E=this,P=E.c,D=(t=new A(t,r)).c;if(!P||!D||!P[0]||!D[0])return!E.s||!t.s||P&&!P[0]&&!D||D&&!D[0]&&!P?t.c=t.e=t.s=null:(t.s*=E.s,!P||!D?t.c=t.e=null:(t.c=[0],t.e=0)),t;for(f=X(E.e/S)+X(t.e/S),t.s*=E.s,u=P.length,T=D.length,u<T&&(V=P,P=D,D=V,c=u,u=T,T=c),c=u+T,V=[];c--;V.push(0));for(F=Y,L=ce,c=T;--c>=0;){for(i=0,W=D[c]%L,x=D[c]/L|0,m=u,l=c+m;l>c;)d=P[--m]%L,p=P[m]/L|0,o=x*d+p*W,d=W*d+o%L*L+V[l]+i,i=(d/F|0)+(o/L|0)+x*p,V[l--]=d%F;V[l]=i}return i?++f:V.splice(0,1),Ee(t,V,f)},s.negated=function(){var t=new A(this);return t.s=-t.s||null,t},s.plus=function(t,r){var i,f=this,c=f.s;if(t=new A(t,r),r=t.s,!c||!r)return new A(NaN);if(c!=r)return t.s=-r,f.minus(t);var l=f.e/S,m=t.e/S,o=f.c,u=t.c;if(!l||!m){if(!o||!u)return new A(c/0);if(!o[0]||!u[0])return u[0]?t:new A(o[0]?f:c*0)}if(l=X(l),m=X(m),o=o.slice(),c=l-m){for(c>0?(m=l,i=u):(c=-c,i=o),i.reverse();c--;i.push(0));i.reverse()}for(c=o.length,r=u.length,c-r<0&&(i=u,u=o,o=i,r=c),c=0;r;)c=(o[--r]=o[r]+u[r]+c)/Y|0,o[r]=Y===o[r]?0:o[r]%Y;return c&&(o=[c].concat(o),++m),Ee(t,o,m)},s.precision=s.sd=function(t,r){var i,f,c,l=this;if(t!=null&&t!==!!t)return U(t,1,_),r==null?r=I:U(r,0,8),G(new A(l),t,r);if(!(i=l.c))return null;if(c=i.length-1,f=c*S+1,c=i[c]){for(;c%10==0;c/=10,f--);for(c=i[0];c>=10;c/=10,f++);}return t&&l.e+1>f&&(f=l.e+1),f},s.shiftedBy=function(t){return U(t,-$e,$e),this.times("1e"+t)},s.squareRoot=s.sqrt=function(){var t,r,i,f,c,l=this,m=l.c,o=l.s,u=l.e,d=w+4,p=new A("0.5");if(o!==1||!m||!m[0])return new A(!o||o<0&&(!m||m[0])?NaN:m?l:1/0);if(o=Math.sqrt(+re(l)),o==0||o==1/0?(r=j(m),(r.length+u)%2==0&&(r+="0"),o=Math.sqrt(+r),u=X((u+1)/2)-(u<0||u%2),o==1/0?r="5e"+u:(r=o.toExponential(),r=r.slice(0,r.indexOf("e")+1)+u),i=new A(r)):i=new A(o+""),i.c[0]){for(u=i.e,o=u+d,o<3&&(o=0);;)if(c=i,i=p.times(c.plus(e(l,c,d,1))),j(c.c).slice(0,o)===(r=j(i.c)).slice(0,o))if(i.e<u&&--o,r=r.slice(o-3,o+1),r=="9999"||!f&&r=="4999"){if(!f&&(G(c,c.e+w+2,0),c.times(c).eq(l))){i=c;break}d+=4,o+=4,f=1}else{(!+r||!+r.slice(1)&&r.charAt(0)=="5")&&(G(i,i.e+w+2,1),t=!i.times(i).eq(l));break}}return G(i,i.e+w+1,I,t)},s.toExponential=function(t,r){return t!=null&&(U(t,0,_),t++),Re(this,t,r,1)},s.toFixed=function(t,r){return t!=null&&(U(t,0,_),t=t+this.e+1),Re(this,t,r)},s.toFormat=function(t,r,i){var f,c=this;if(i==null)t!=null&&r&&typeof r=="object"?(i=r,r=null):t&&typeof t=="object"?(i=t,t=r=null):i=We;else if(typeof i!="object")throw Error(H+"Argument not an object: "+i);if(f=c.toFixed(t,r),c.c){var l,m=f.split("."),o=+i.groupSize,u=+i.secondaryGroupSize,d=i.groupSeparator||"",p=m[0],T=m[1],W=c.s<0,x=W?p.slice(1):p,V=x.length;if(u&&(l=o,o=u,u=l,V-=l),o>0&&V>0){for(l=V%o||o,p=x.substr(0,l);l<V;l+=o)p+=d+x.substr(l,o);u>0&&(p+=d+x.slice(l)),W&&(p="-"+p)}f=T?p+(i.decimalSeparator||"")+((u=+i.fractionGroupSize)?T.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(i.fractionGroupSeparator||"")):T):p}return(i.prefix||"")+f+(i.suffix||"")},s.toFraction=function(t){var r,i,f,c,l,m,o,u,d,p,T,W,x=this,V=x.c;if(t!=null&&(o=new A(t),!o.isInteger()&&(o.c||o.s!==1)||o.lt(h)))throw Error(H+"Argument "+(o.isInteger()?"out of range: ":"not an integer: ")+re(o));if(!V)return new A(x);for(r=new A(h),d=i=new A(h),f=u=new A(h),W=j(V),l=r.e=W.length-x.e-1,r.c[0]=Le[(m=l%S)<0?S+m:m],t=!t||o.comparedTo(r)>0?l>0?r:d:o,m=R,R=1/0,o=new A(W),u.c[0]=0;p=e(o,r,0,1),c=i.plus(p.times(f)),c.comparedTo(t)!=1;)i=f,f=c,d=u.plus(p.times(c=d)),u=c,r=o.minus(p.times(c=r)),o=c;return c=e(t.minus(i),f,0,1),u=u.plus(c.times(d)),i=i.plus(c.times(f)),u.s=d.s=x.s,l=l*2,T=e(d,f,l,I).minus(x).abs().comparedTo(e(u,i,l,I).minus(x).abs())<1?[d,f]:[u,i],R=m,T},s.toNumber=function(){return+re(this)},s.toPrecision=function(t,r){return t!=null&&U(t,1,_),Re(this,t,r,2)},s.toString=function(t){var r,i=this,f=i.s,c=i.e;return c===null?f?(r="Infinity",f<0&&(r="-"+r)):r="NaN":(t==null?r=c<=v||c>=B?Ne(j(i.c),c):se(j(i.c),c,"0"):t===10&&pe?(i=G(new A(i),w+c+1,I),r=se(j(i.c),i.e,"0")):(U(t,2,ee.length,"Base"),r=n(se(j(i.c),c,"0"),10,t,f,!0)),f<0&&i.c[0]&&(r="-"+r)),r},s.valueOf=s.toJSON=function(){return re(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,g!=null&&A.set(g),A}function X(g){var e=g|0;return g>0||g===e?e:e-1}function j(g){for(var e,n,a=1,s=g.length,h=g[0]+"";a<s;){for(e=g[a++]+"",n=S-e.length;n--;e="0"+e);h+=e}for(s=h.length;h.charCodeAt(--s)===48;);return h.slice(0,s+1||1)}function fe(g,e){var n,a,s=g.c,h=e.c,w=g.s,I=e.s,v=g.e,B=e.e;if(!w||!I)return null;if(n=s&&!s[0],a=h&&!h[0],n||a)return n?a?0:-I:w;if(w!=I)return w;if(n=w<0,a=v==B,!s||!h)return a?0:!s^n?1:-1;if(!a)return v>B^n?1:-1;for(I=(v=s.length)<(B=h.length)?v:B,w=0;w<I;w++)if(s[w]!=h[w])return s[w]>h[w]^n?1:-1;return v==B?0:v>B^n?1:-1}function U(g,e,n,a){if(g<e||g>n||g!==J(g))throw Error(H+(a||"Argument")+(typeof g=="number"?g<e||g>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(g))}function Se(g){var e=g.c.length-1;return X(g.e/S)==e&&g.c[e]%2!=0}function Ne(g,e){return(g.length>1?g.charAt(0)+"."+g.slice(1):g)+(e<0?"e":"e+")+e}function se(g,e,n){var a,s;if(e<0){for(s=n+".";++e;s+=n);g=s+g}else if(a=g.length,++e>a){for(s=n,e-=a;--e;s+=n);g+=s}else e<a&&(g=g.slice(0,e)+"."+g.slice(e));return g}var je=ze();var M=":",ae="|",Je=new RegExp(`${M}(.*)`),we=class{nativeToString(e,n){return e==="esdt"&&n instanceof y.TokenTransfer?`esdt:${n.token.identifier}|${n.token.nonce.toString()}|${n.amount.toString()}`:`${e}:${n?.toString()??""}`}typedToString(e){if(e.hasClassOrSuperclass(y.OptionValue.ClassName))return e.isSet()?`option:${this.typedToString(e.getTypedValue())}`:"option:null";if(e.hasClassOrSuperclass(y.OptionalValue.ClassName))return e.isSet()?`optional:${this.typedToString(e.getTypedValue())}`:"optional:null";if(e.hasClassOrSuperclass(y.List.ClassName)){let n=e.getItems(),s=n.map(w=>this.typedToString(w).split(M)[0])[0],h=n.map(w=>this.typedToString(w).split(M)[1]);return`list:${s}:${h.join(",")}`}if(e.hasClassOrSuperclass(y.VariadicValue.ClassName)){let n=e.getItems(),s=n.map(w=>this.typedToString(w).split(M)[0])[0],h=n.map(w=>this.typedToString(w).split(M)[1]);return`variadic:${s}:${h.join(",")}`}if(e.hasClassOrSuperclass(y.CompositeValue.ClassName)){let n=e.getItems(),a=n.map(I=>this.typedToString(I).split(M)[0]),s=n.map(I=>this.typedToString(I).split(M)[1]),h=a.join(ae),w=s.join(ae);return`composite(${h}):${w}`}if(e.hasClassOrSuperclass(y.BigUIntValue.ClassName)||je.isBigNumber(e))return`biguint:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(y.U8Value.ClassName))return`uint8:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(y.U16Value.ClassName))return`uint16:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(y.U32Value.ClassName))return`uint32:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(y.U64Value.ClassName))return`uint64:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(y.StringValue.ClassName))return`string:${e.valueOf()}`;if(e.hasClassOrSuperclass(y.BooleanValue.ClassName))return`bool:${e.valueOf()}`;if(e.hasClassOrSuperclass(y.AddressValue.ClassName))return`address:${e.valueOf().bech32()}`;if(e.hasClassOrSuperclass(y.TokenIdentifierValue.ClassName))return`token:${e.valueOf()}`;if(e.hasClassOrSuperclass(y.BytesValue.ClassName))return`hex:${e.valueOf().toString("hex")}`;if(e.hasClassOrSuperclass(y.CodeMetadataValue.ClassName))return`codemeta:${e.valueOf().toBuffer().toString("hex")}`;if(e.getType().getName()==="EsdtTokenPayment"){let n=e.getFieldValue("token_identifier").valueOf(),a=e.getFieldValue("token_nonce").valueOf(),s=e.getFieldValue("amount").valueOf();return`esdt:${n}|${a}|${s}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${e.getClassName()}`)}typedToNative(e){let n=this.typedToString(e);return this.stringToNative(n)}nativeToTyped(e,n){let a=this.nativeToString(e,n);return this.stringToTyped(a)}nativeToType(e){if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1];return new y.CompositeType(...n.split(ae).map(a=>this.nativeToType(a)))}if(e==="string")return new y.StringType;if(e==="uint8")return new y.U8Type;if(e==="uint16")return new y.U16Type;if(e==="uint32")return new y.U32Type;if(e==="uint64")return new y.U64Type;if(e==="biguint")return new y.BigUIntType;if(e==="bool")return new y.BooleanType;if(e==="address")return new y.AddressType;if(e==="token")return new y.TokenIdentifierType;if(e==="hex")return new y.BytesType;if(e==="codemeta")return new y.CodeMetadataType;if(e==="esdt"||e==="nft")return new y.StructType("EsdtTokenPayment",[new y.FieldDefinition("token_identifier","",new y.TokenIdentifierType),new y.FieldDefinition("token_nonce","",new y.U64Type),new y.FieldDefinition("amount","",new y.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${e}`)}stringToNative(e){let n=e.split(M),a=n[0],s=n.slice(1).join(M);if(a==="null")return[a,null];if(a==="option"){let[h,w]=s.split(M);return[`option:${h}`,w||null]}else if(a==="optional"){let[h,w]=s.split(M);return[`optional:${h}`,w||null]}else if(a==="list"){let h=s.split(M),w=h.slice(0,-1).join(M),I=h[h.length-1],B=(I?I.split(","):[]).map(N=>this.stringToNative(`${w}:${N}`)[1]);return[`list:${w}`,B]}else if(a==="variadic"){let h=s.split(M),w=h.slice(0,-1).join(M),I=h[h.length-1],B=(I?I.split(","):[]).map(N=>this.stringToNative(`${w}:${N}`)[1]);return[`variadic:${w}`,B]}else if(a.startsWith("composite")){let h=a.match(/\(([^)]+)\)/)?.[1]?.split(ae),I=s.split(ae).map((v,B)=>this.stringToNative(`${h[B]}:${v}`)[1]);return[a,I]}else{if(a==="string")return[a,s];if(a==="uint8"||a==="uint16"||a==="uint32")return[a,Number(s)];if(a==="uint64"||a==="biguint")return[a,BigInt(s||0)];if(a==="bool")return[a,s==="true"];if(a==="address")return[a,s];if(a==="token")return[a,s];if(a==="hex")return[a,s];if(a==="codemeta")return[a,s];if(a==="esdt"){let[h,w,I]=s.split(ae);return[a,new y.TokenTransfer({token:new y.Token({identifier:h,nonce:BigInt(w)}),amount:BigInt(I)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${a}`)}stringToTyped(e){let[n,a]=e.split(/:(.*)/,2);if(n==="null"||n===null)return new y.NothingValue;if(n==="option"){let s=this.stringToTyped(a);return s instanceof y.NothingValue?y.OptionValue.newMissingTyped(s.getType()):y.OptionValue.newProvided(s)}if(n==="optional"){let s=this.stringToTyped(a);return s instanceof y.NothingValue?y.OptionalValue.newMissing():new y.OptionalValue(s.getType(),s)}if(n==="list"){let[s,h]=a.split(Je,2),I=h.split(",").map(v=>this.stringToTyped(`${s}:${v}`));return new y.List(this.nativeToType(s),I)}if(n==="variadic"){let[s,h]=a.split(Je,2),I=h.split(",").map(v=>this.stringToTyped(`${s}:${v}`));return new y.VariadicValue(new y.VariadicType(this.nativeToType(s)),I)}if(n.startsWith("composite")){let s=n.match(/\(([^)]+)\)/)?.[1],h=a.split(ae),w=s.split(ae),I=h.map((B,N)=>this.stringToTyped(`${w[N]}:${B}`)),v=I.map(B=>B.getType());return new y.CompositeValue(new y.CompositeType(...v),I)}if(n==="string")return a?y.StringValue.fromUTF8(a):new y.NothingValue;if(n==="uint8")return a?new y.U8Value(Number(a)):new y.NothingValue;if(n==="uint16")return a?new y.U16Value(Number(a)):new y.NothingValue;if(n==="uint32")return a?new y.U32Value(Number(a)):new y.NothingValue;if(n==="uint64")return a?new y.U64Value(BigInt(a)):new y.NothingValue;if(n==="biguint")return a?new y.BigUIntValue(BigInt(a)):new y.NothingValue;if(n==="bool")return a?new y.BooleanValue(typeof a=="boolean"?a:a==="true"):new y.NothingValue;if(n==="address")return a?new y.AddressValue(y.Address.newFromBech32(a)):new y.NothingValue;if(n==="token")return a?new y.TokenIdentifierValue(a):new y.NothingValue;if(n==="hex")return a?y.BytesValue.fromHex(a):new y.NothingValue;if(n==="codemeta")return new y.CodeMetadataValue(y.CodeMetadata.fromBuffer(Buffer.from(a,"hex")));if(n==="esdt"){let s=a.split(ae);return new y.Struct(this.nativeToType("esdt"),[new y.Field(new y.TokenIdentifierValue(s[0]),"token_identifier"),new y.Field(new y.U64Value(BigInt(s[1])),"token_nonce"),new y.Field(new y.BigUIntValue(BigInt(s[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${n}`)}typeToNative(e){if(e instanceof y.StringType)return"string";if(e instanceof y.U8Type)return"uint8";if(e instanceof y.U16Type)return"uint16";if(e instanceof y.U32Type)return"uint32";if(e instanceof y.U64Type)return"uint64";if(e instanceof y.BigUIntType)return"biguint";if(e instanceof y.BooleanType)return"bool";if(e instanceof y.AddressType)return"address";if(e instanceof y.TokenIdentifierType)return"token";if(e instanceof y.BytesType)return"hex";if(e instanceof y.CodeMetadataType)return"codemeta";if(e instanceof y.StructType&&e.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${e.getClassName()}`)}};var Xe=require("@multiversx/sdk-core/out"),Te=class{constructor(e){this.config=e}async getContract(e){try{let a=await this.getConfiguredChainApi().doGetGeneric(`accounts/${e}/verification`);return{address:e,owner:a.ownerAddress,verified:a.isVerified}}catch(n){return console.error("WarpContractLoader: getContract error",n),null}}async getVerificationInfo(e){try{let a=await this.getConfiguredChainApi().doGetGeneric(`accounts/${e}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(n){return console.error("WarpContractLoader: getVerificationInfo error",n),null}}getConfiguredChainApi(){if(!this.config.chainApiUrl)throw new Error("WarpContract: Chain API URL not set");return new Xe.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4})}};var _e=class{constructor(e){if(!e.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=e,this.url=new URL(e.currentUrl),this.serializer=new we,this.contractLoader=new Te(e)}createTransactionForExecute(e,n,a){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let s=O.Address.newFromBech32(this.config.userAddress),h=O.Address.newFromBech32(e.address),w=new O.TransactionsFactoryConfig({chainID:ne(this.config.env)}),{args:I,value:v,transfers:B}=this.getTxComponentsFromInputs(e,n,a),N=I.map(R=>this.serializer.stringToTyped(R));return h.isContractAddress()?new O.SmartContractTransactionsFactory({config:w}).createTransactionForExecute({sender:s,contract:h,function:e.func||"",gasLimit:BigInt(e.gasLimit),arguments:N,tokenTransfers:B,nativeTransferAmount:v}):new O.TransferTransactionsFactory({config:w}).createTransactionForTransfer({sender:s,receiver:h,nativeAmount:v,tokenTransfers:B,data:N[0]?.hasExactClass(O.StringValue.ClassName)?N[0].valueOf():void 0})}async executeQuery(e,n){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!e.func)throw new Error("WarpActionExecutor: Function not found");let a=new O.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4}),s=new O.QueryRunnerAdapter({networkProvider:a}),h=await this.getAbiForAction(e),{args:w}=this.getTxComponentsFromInputs(e,n,[]),I=w.map(pe=>this.serializer.stringToTyped(pe)),v=new O.SmartContractQueriesController({queryRunner:s,abi:h}),B=v.createQuery({contract:e.address,function:e.func,arguments:I}),N=await v.runQuery(B),R=new O.ResultsParser,K={returnCode:N.returnCode,returnMessage:N.returnMessage,getReturnDataParts:()=>N.returnDataParts.map(pe=>Buffer.from(pe))},le=N.function,Z=h.getEndpoint(le),ee=R.parseQueryResponse(K,Z).firstValue;if(!ee)throw new Error("WarpActionExecutor: Query result not found");return ee}async executeCollect(e,n,a){let s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(e.destination.headers).forEach(([h,w])=>{s.set(h,w)}),await fetch(e.destination.url,{method:e.destination.method,headers:s,body:JSON.stringify({inputs:n,meta:a})})}getTxComponentsFromInputs(e,n,a){let s=this.getResolvedInputs(e,n),h=this.getModifiedInputs(s),w=this.getPreparedArgs(e,h),I=h.find(K=>K.input.position==="value")?.value||null,v="value"in e?e.value:null,B=BigInt(I?.split(":")[1]||v||0),R=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...a];return{args:w,value:B,transfers:R}}getModifiedInputs(e){return e.map((n,a)=>{if(n.input.modifier?.startsWith("scale:")){let[,s]=n.input.modifier.split(":");if(isNaN(Number(s))){let h=Number(e.find(v=>v.input.name===s)?.value?.split(":")[1]);if(!h)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let w=n.value?.split(":")[1];if(!w)throw new Error("WarpActionExecutor: Scalable value not found");let I=be(w,+h);return{...n,value:`${n.input.type}:${I}`}}else{let h=n.value?.split(":")[1];if(!h)throw new Error("WarpActionExecutor: Scalable value not found");let w=be(h,+s);return{...n,value:`${n.input.type}:${w}`}}}else return n})}getResolvedInputs(e,n){let a=e.inputs||[],s=(h,w)=>h.source==="query"?this.serializer.nativeToString(h.type,this.url.searchParams.get(h.name)||""):n[w]||null;return a.map((h,w)=>({input:h,value:s(h,w)}))}getPreparedArgs(e,n){let a="args"in e?e.args:[];return n.forEach(({input:s,value:h})=>{if(!h||!s.position.startsWith("arg:"))return;let w=Number(s.position.split(":")[1])-1;a.splice(w,0,h)}),a}async getAbiForAction(e){if(e.abi)return await this.fetchAbi(e);let n=await this.contractLoader.getVerificationInfo(e.address);if(!n)throw new Error("WarpActionExecutor: Verification info not found");return O.AbiRegistry.create(n.abi)}async fetchAbi(e){if(!e.abi)throw new Error("WarpActionExecutor: ABI not found");let a=await(await fetch(e.abi)).json();return O.AbiRegistry.create(a)}toTypedTransfer(e){return new O.TokenTransfer({token:new O.Token({identifier:e.token,nonce:BigInt(e.nonce||0)}),amount:BigInt(e.amount||0)})}};var oe=require("@multiversx/sdk-core");var de={Warp:g=>`warp:${g}`,RegistryInfo:g=>`registry-info:${g}`,Brand:g=>`brand:${g}`},ge=class{constructor(){this.cache=new Map}set(e,n,a){let s=Date.now()+a*1e3;this.cache.set(e,{value:n,expiresAt:s})}get(e){let n=this.cache.get(e);return n?Date.now()>n.expiresAt?(this.cache.delete(e),null):n.value:null}clear(){this.cache.clear()}};var Ke=Oe(require("qr-code-styling"));var b=require("@multiversx/sdk-core/out");var De={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},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:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],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:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var Ae=class{constructor(e){this.cache=new ge;this.config=e,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(e,n){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let a=n?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:b.Address.newFromBech32(this.config.userAddress),contract:b.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a,arguments:n?[b.BytesValue.fromHex(e),b.BytesValue.fromUTF8(n)]:[b.BytesValue.fromHex(e)]})}createWarpUnregisterTransaction(e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:b.Address.newFromBech32(this.config.userAddress),contract:b.Address.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[b.BytesValue.fromHex(e)]})}createWarpUpgradeTransaction(e,n){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:b.Address.newFromBech32(this.config.userAddress),contract:b.Address.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[b.BytesValue.fromUTF8(e),b.BytesValue.fromHex(n)]})}createWarpAliasSetTransaction(e,n){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:b.Address.newFromBech32(this.config.userAddress),contract:b.Address.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[b.BytesValue.fromHex(e),b.BytesValue.fromUTF8(n)]})}createBrandRegisterTransaction(e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:b.Address.newFromBech32(this.config.userAddress),contract:b.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[b.BytesValue.fromHex(e)]})}createWarpPublishTransaction(e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:b.Address.newFromBech32(this.config.userAddress),contract:b.Address.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[b.BytesValue.fromHex(e)]})}createWarpBrandingTransaction(e,n){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:b.Address.newFromBech32(this.config.userAddress),contract:b.Address.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[b.BytesValue.fromHex(e),b.BytesValue.fromHex(n)]})}async getInfoByAlias(e,n){let a=de.RegistryInfo(e);if(n){let R=this.cache.get(a);if(R)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${e}`),R}let s=this.getRegistryContractAddress(),h=this.getController(),w=h.createQuery({contract:s,function:"getInfoByAlias",arguments:[b.BytesValue.fromUTF8(e)]}),I=await h.runQuery(w),[v]=h.parseQueryResponse(I),B=v?ye(v):null,N=B?.brand?await this.fetchBrand(B.brand):null;return n&&n.ttl&&this.cache.set(a,{registryInfo:B,brand:N},n.ttl),{registryInfo:B,brand:N}}async getInfoByHash(e,n){let a=de.RegistryInfo(e);if(n){let R=this.cache.get(a);if(R)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${e}`),R}let s=this.getRegistryContractAddress(),h=this.getController(),w=h.createQuery({contract:s,function:"getInfoByHash",arguments:[b.BytesValue.fromHex(e)]}),I=await h.runQuery(w),[v]=h.parseQueryResponse(I),B=v?ye(v):null,N=B?.brand?await this.fetchBrand(B.brand):null;return n&&n.ttl&&this.cache.set(a,{registryInfo:B,brand:N},n.ttl),{registryInfo:B,brand:N}}async getUserWarpRegistryInfos(e){let n=e||this.config.userAddress;if(!n)throw new Error("WarpRegistry: user address not set");let a=this.getRegistryContractAddress(),s=this.getController(),h=s.createQuery({contract:a,function:"getUserWarps",arguments:[new b.AddressValue(new b.Address(n))]}),w=await s.runQuery(h),[I]=s.parseQueryResponse(w);return I.map(ye)}async getUserBrands(e){let n=e||this.config.userAddress;if(!n)throw new Error("WarpRegistry: user address not set");let a=this.getRegistryContractAddress(),s=this.getController(),h=s.createQuery({contract:a,function:"getUserBrands",arguments:[new b.AddressValue(new b.Address(n))]}),w=await s.runQuery(h),[I]=s.parseQueryResponse(w),v=I.map(R=>R.toString("hex")),B={ttl:365*24*60*60};return(await Promise.all(v.map(R=>this.fetchBrand(R,B)))).filter(R=>R!==null)}async fetchBrand(e,n){let a=de.Brand(e);if(n){let h=this.cache.get(a);if(h)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${e}`),h}let s=new b.ApiNetworkProvider(this.config.chainApiUrl||$.Chain.ApiUrl(this.config.env));try{let h=await s.getTransaction(e),w=JSON.parse(h.data.toString());return w.meta={hash:h.hash,creator:h.sender.bech32(),createdAt:new Date(h.timestamp*1e3).toISOString()},n&&n.ttl&&this.cache.set(a,w,n.ttl),w}catch(h){return console.error("WarpRegistry: Error fetching brand from transaction hash",h),null}}getRegistryContractAddress(){return this.config.registryContract||$.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let e=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:e,function:"getConfig",arguments:[]}),s=await n.runQuery(a),[h]=n.parseQueryResponse(s),w=BigInt(h.toString());this.unitPrice=w}getFactory(){let e=new b.TransactionsFactoryConfig({chainID:ne(this.config.env)}),n=b.AbiRegistry.create(De);return new b.SmartContractTransactionsFactory({config:e,abi:n})}getController(){let e=this.config.chainApiUrl||$.Chain.ApiUrl(this.config.env),n=new b.ApiNetworkProvider(e,{timeout:3e4}),a=new b.QueryRunnerAdapter({networkProvider:n}),s=b.AbiRegistry.create(De);return new b.SmartContractQueriesController({queryRunner:a,abi:s})}};var Ie=class{constructor(e){this.config=e;this.config=e}isValid(e){return e.startsWith(Q.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(e):!1}async detectFromHtml(e){if(!e.length)return{match:!1,results:[]};let s=[...e.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(B=>B[0]).filter(B=>this.isValid(B)).map(B=>this.detect(B)),w=(await Promise.all(s)).filter(B=>B.match),I=w.length>0,v=w.map(B=>({url:B.url,warp:B.warp}));return{match:I,results:v}}async detect(e){let n=e.startsWith(Q.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(e):ue.getInfoFromPrefixedIdentifier(e);if(!n)return{match:!1,url:e,warp:null,registryInfo:null,brand:null};let{type:a,id:s}=n,h=new Ce(this.config),w=new Ae(this.config),I=null,v=null,B=null;if(a==="hash"){I=await h.createFromTransactionHash(s);try{let{registryInfo:N,brand:R}=await w.getInfoByHash(s);v=N,B=R}catch{}}else if(a==="alias"){let{registryInfo:N,brand:R}=await w.getInfoByAlias(s);v=N,B=R,N&&(I=await h.createFromTransactionHash(N.hash))}return I?{match:!0,url:e,warp:I,registryInfo:v,brand:B}:{match:!1,url:e,warp:null,registryInfo:null,brand:null}}build(e,n){let a=this.config.clientUrl||$.DefaultClientUrl(this.config.env),s=e===Q.DefaultIdentifierType?encodeURIComponent(n):encodeURIComponent(e+Q.IdentifierParamSeparator+n);return $.SuperClientUrls.includes(a)?`${a}/${s}`:`${a}?${Q.IdentifierParamName}=${s}`}generateQrCode(e,n,a=512,s="white",h="black",w="#23F7DD"){let I=this.build(e,n);return new Ke.default({type:"svg",width:a,height:a,data:String(I),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:h},cornersSquareOptions:{type:"extra-rounded",color:h},cornersDotOptions:{type:"square",color:h},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(w)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(e){let n=new URL(e),a=$.SuperClientUrls.includes(n.origin),s=n.searchParams.get(Q.IdentifierParamName),h=a&&!s?n.pathname.split("/")[1]:s;if(!h)return null;let w=decodeURIComponent(h);return ue.getInfoFromPrefixedIdentifier(w)}};var St="https://",Ye="query",Ze="env",ue=class g{static prepareVars(e,n){if(!e?.vars)return e;let a=JSON.stringify(e),s=(h,w)=>{a=a.replace(new RegExp(`{{${h.toUpperCase()}}}`,"g"),w.toString())};return Object.entries(e.vars).forEach(([h,w])=>{if(typeof w=="string"&&w.startsWith(`${Ye}:`)){if(!n.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let I=w.split(`${Ye}:`)[1],v=new URL(n.currentUrl).searchParams.get(I);v&&s(h,v)}else if(typeof w=="string"&&w.startsWith(`${Ze}:`)){let I=w.split(`${Ze}:`)[1],v=n.vars?.[I];v&&s(h,v)}else s(h,w)}),JSON.parse(a)}static getInfoFromPrefixedIdentifier(e){let n=decodeURIComponent(e),a=n.includes(Q.IdentifierParamSeparator)?n:`${Q.DefaultIdentifierType}${Q.IdentifierParamSeparator}${n}`,[s,h]=a.split(Q.IdentifierParamSeparator);return{type:s,id:h}}static getNextStepUrl(e,n){if(!e?.next)return null;if(e.next.startsWith(St))return e.next;{let a=new Ie(n),s=g.getInfoFromPrefixedIdentifier(e.next);return s?a.build(s.type,s.id):null}}};var et=Oe(require("ajv"));var Be=class{constructor(e){this.config=e;this.config=e}async validate(e){this.ensureMaxOneValuePosition(e),await this.ensureValidSchema(e)}ensureMaxOneValuePosition(e){if(e.actions.filter(a=>"position"in a?a.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(e){let n=this.config.warpSchemaUrl||$.LatestWarpSchemaUrl,s=await(await fetch(n)).json(),h=new et.default,w=h.compile(s);if(!w(e))throw new Error(`WarpBuilder: schema validation failed: ${h.errorsText(w.errors)}`)}};var Ce=class{constructor(e){this.cache=new ge;this.pendingWarp={protocol:me($.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=e}createInscriptionTransaction(e){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let n=new oe.TransactionsFactoryConfig({chainID:ne(this.config.env)}),a=new oe.TransferTransactionsFactory({config:n}),s=JSON.stringify(e),h=a.createTransactionForTransfer({sender:oe.Address.newFromBech32(this.config.userAddress),receiver:oe.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(s).valueOf()});return h.gasLimit=h.gasLimit+BigInt(2e6),h}async createFromRaw(e,n=!0){let a=JSON.parse(e);return n&&await new Be(this.config).validate(a),ue.prepareVars(a,this.config)}async createFromTransaction(e,n=!1){let a=await this.createFromRaw(e.data.toString(),n);return a.meta={hash:e.hash,creator:e.sender.bech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},a}async createFromTransactionHash(e,n){let a=de.Warp(e);if(n){let h=this.cache.get(a);if(h)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${e}`),h}let s=new oe.ApiNetworkProvider(this.config.chainApiUrl||$.Chain.ApiUrl(this.config.env));try{let h=await s.getTransaction(e),w=await this.createFromTransaction(h);return n&&n.ttl&&w&&this.cache.set(a,w,n.ttl),w}catch(h){return console.error("WarpBuilder: Error creating from transaction hash",h),null}}setName(e){return this.pendingWarp.name=e,this}setTitle(e){return this.pendingWarp.title=e,this}setDescription(e){return this.pendingWarp.description=e,this}setPreview(e){return this.pendingWarp.preview=e,this}setActions(e){return this.pendingWarp.actions=e,this}addAction(e){return this.pendingWarp.actions.push(e),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await new Be(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(e,n=100){return Ue(e,n)}ensure(e,n){if(!e)throw new Error(`WarpBuilder: ${n}`)}};var qe=class{constructor(e){this.config=e}async search(e){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw console.error("WarpIndex: Error searching for warps: ",n),n}}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpConstants,WarpContractLoader,WarpIndex,WarpLink,WarpRegistry,WarpUtils,address,biguint,boolean,codemeta,composite,esdt,getChainId,getLatestProtocolIdentifier,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Address as K,ApiNetworkProvider as $t,TransactionsFactoryConfig as kt,TransferTransactionsFactory as Ot}from"@multiversx/sdk-core";import Lt from"ajv";var d={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.4.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.4.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var T=a=>a==="devnet"?"D":a==="testnet"?"T":"1",b=a=>`${a}:${d.LatestProtocolVersion}`,A=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),creator:a.creator.toString(),createdAt:a.created_at.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),U=(a,t)=>{let e=a.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let s=r+n;if(i>=s.length)return 0n;let o=s.slice(0,-i)||"0";return BigInt(o)}else return BigInt(a)},J=(a,t=100)=>{if(!a)return"";let e=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};var Z=class{constructor(t){this.pendingBrand={protocol:b(d.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new kt({chainID:T(this.config.env)}),r=new Ot({config:e}),n=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:K.newFromBech32(this.config.userAddress),receiver:K.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=new $t(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||d.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new Lt,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var y={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import{Address as qt,AddressValue as Dt,BigUIntType as _t,BigUIntValue as X,BooleanValue as Qt,BytesValue as Ht,CodeMetadata as jt,CodeMetadataValue as Mt,CompositeType as zt,CompositeValue as Gt,Field as F,FieldDefinition as N,List as Jt,NothingValue as Kt,OptionalValue as E,OptionValue as $,StringValue as Zt,Struct as Xt,StructType as Yt,TokenIdentifierType as te,TokenIdentifierValue as Y,U16Value as ee,U32Value as re,U64Type as ne,U64Value as tt,U8Value as ie,VariadicValue as se}from"@multiversx/sdk-core/out";var Je=(a,t)=>a?$.newProvided(a):t?$.newMissingTyped(t):$.newMissing(),Ke=(a,t)=>a?new E(a.getType(),a):t?new E(t):E.newMissing(),Ze=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new Jt(t,a)},Xe=a=>se.fromItems(...a),Ye=a=>{let t=a.map(e=>e.getType());return new Gt(new zt(...t),a)},tr=a=>Zt.fromUTF8(a),er=a=>new ie(a),rr=a=>new ee(a),nr=a=>new re(a),ir=a=>new tt(a),sr=a=>new X(BigInt(a)),ar=a=>new Qt(a),or=a=>new Dt(qt.newFromBech32(a)),cr=a=>new Y(a),ur=a=>Ht.fromHex(a),pr=a=>new Xt(new Yt("EsdtTokenPayment",[new N("token_identifier","",new te),new N("token_nonce","",new ne),new N("amount","",new _t)]),[new F(new Y(a.token.identifier),"token_identifier"),new F(new tt(BigInt(a.token.nonce)),"token_nonce"),new F(new X(BigInt(a.amount)),"amount")]),lr=a=>new Mt(jt.fromBuffer(Buffer.from(a,"hex"))),dr=()=>new Kt;import{AbiRegistry as At,Address as Bt,ApiNetworkProvider as de,QueryRunnerAdapter as ge,ResultsParser as fe,SmartContractQueriesController as me,SmartContractTransactionsFactory as he,StringValue as ye,Token as we,TokenTransfer as Te,TransactionsFactoryConfig as We,TransferTransactionsFactory as Ce}from"@multiversx/sdk-core/out";import{Address as ae,AddressType as et,AddressValue as rt,BigUIntType as k,BigUIntValue as O,BooleanType as nt,BooleanValue as it,BytesType as st,BytesValue as at,CodeMetadata as oe,CodeMetadataType as ot,CodeMetadataValue as ct,CompositeType as ut,CompositeValue as pt,Field as L,FieldDefinition as q,List as lt,NothingValue as h,OptionalValue as D,OptionValue as _,StringType as dt,StringValue as gt,Struct as ce,StructType as ft,Token as ue,TokenIdentifierType as Q,TokenIdentifierValue as H,TokenTransfer as mt,U16Type as ht,U16Value as yt,U32Type as wt,U32Value as Tt,U64Type as j,U64Value as M,U8Type as Wt,U8Value as Ct,VariadicType as pe,VariadicValue as It}from"@multiversx/sdk-core/out";var f=":",w="|",bt=new RegExp(`${f}(.*)`),B=class{nativeToString(t,e){return t==="esdt"&&e instanceof mt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(_.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(lt.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f)[0])[0],i=e.map(s=>this.typedToString(s).split(f)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(It.ClassName)){let e=t.getItems(),n=e.map(s=>this.typedToString(s).split(f)[0])[0],i=e.map(s=>this.typedToString(s).split(f)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(pt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(f)[0]),n=e.map(o=>this.typedToString(o).split(f)[1]),i=r.join(w),s=n.join(w);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(O.ClassName))return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Ct.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(yt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Tt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(M.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(gt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(it.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(rt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(H.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(at.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(ct.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new ut(...e.split(w).map(r=>this.nativeToType(r)))}if(t==="string")return new dt;if(t==="uint8")return new Wt;if(t==="uint16")return new ht;if(t==="uint32")return new wt;if(t==="uint64")return new j;if(t==="biguint")return new k;if(t==="bool")return new nt;if(t==="address")return new et;if(t==="token")return new Q;if(t==="hex")return new st;if(t==="codemeta")return new ot;if(t==="esdt"||t==="nft")return new ft("EsdtTokenPayment",[new q("token_identifier","",new Q),new q("token_nonce","",new j),new q("amount","",new k)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f),r=e[0],n=e.slice(1).join(f);if(r==="null")return[r,null];if(r==="option"){let[i,s]=n.split(f);return[`option:${i}`,s||null]}else if(r==="optional"){let[i,s]=n.split(f);return[`optional:${i}`,s||null]}else if(r==="list"){let i=n.split(f),s=i.slice(0,-1).join(f),o=i[i.length-1],c=(o?o.split(","):[]).map(p=>this.stringToNative(`${s}:${p}`)[1]);return[`list:${s}`,c]}else if(r==="variadic"){let i=n.split(f),s=i.slice(0,-1).join(f),o=i[i.length-1],c=(o?o.split(","):[]).map(p=>this.stringToNative(`${s}:${p}`)[1]);return[`variadic:${s}`,c]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(w),o=n.split(w).map((u,c)=>this.stringToNative(`${i[c]}:${u}`)[1]);return[r,o]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,s,o]=n.split(w);return[r,new mt({token:new ue({identifier:i,nonce:BigInt(s)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new h;if(e==="option"){let n=this.stringToTyped(r);return n instanceof h?_.newMissingTyped(n.getType()):_.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof h?D.newMissing():new D(n.getType(),n)}if(e==="list"){let[n,i]=r.split(bt,2),o=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new lt(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(bt,2),o=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new It(new pe(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(w),s=n.split(w),o=i.map((c,p)=>this.stringToTyped(`${s[p]}:${c}`)),u=o.map(c=>c.getType());return new pt(new ut(...u),o)}if(e==="string")return r?gt.fromUTF8(r):new h;if(e==="uint8")return r?new Ct(Number(r)):new h;if(e==="uint16")return r?new yt(Number(r)):new h;if(e==="uint32")return r?new Tt(Number(r)):new h;if(e==="uint64")return r?new M(BigInt(r)):new h;if(e==="biguint")return r?new O(BigInt(r)):new h;if(e==="bool")return r?new it(typeof r=="boolean"?r:r==="true"):new h;if(e==="address")return r?new rt(ae.newFromBech32(r)):new h;if(e==="token")return r?new H(r):new h;if(e==="hex")return r?at.fromHex(r):new h;if(e==="codemeta")return new ct(oe.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let n=r.split(w);return new ce(this.nativeToType("esdt"),[new L(new H(n[0]),"token_identifier"),new L(new M(BigInt(n[1])),"token_nonce"),new L(new O(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof dt)return"string";if(t instanceof Wt)return"uint8";if(t instanceof ht)return"uint16";if(t instanceof wt)return"uint32";if(t instanceof j)return"uint64";if(t instanceof k)return"biguint";if(t instanceof nt)return"bool";if(t instanceof et)return"address";if(t instanceof Q)return"token";if(t instanceof st)return"hex";if(t instanceof ot)return"codemeta";if(t instanceof ft&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};import{ApiNetworkProvider as le}from"@multiversx/sdk-core/out";var v=class{constructor(t){this.config=t}async getContract(t){try{let r=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}getConfiguredChainApi(){if(!this.config.chainApiUrl)throw new Error("WarpContract: Chain API URL not set");return new le(this.config.chainApiUrl,{timeout:3e4})}};var vt=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new B,this.contractLoader=new v(t)}createTransactionForExecute(t,e,r){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=Bt.newFromBech32(this.config.userAddress),i=Bt.newFromBech32(t.address),s=new We({chainID:T(this.config.env)}),{args:o,value:u,transfers:c}=this.getTxComponentsFromInputs(t,e,r),p=o.map(l=>this.serializer.stringToTyped(l));return i.isContractAddress()?new he({config:s}).createTransactionForExecute({sender:n,contract:i,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:p,tokenTransfers:c,nativeTransferAmount:u}):new Ce({config:s}).createTransactionForTransfer({sender:n,receiver:i,nativeAmount:u,tokenTransfers:c,data:p[0]?.hasExactClass(ye.ClassName)?p[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=new de(this.config.chainApiUrl,{timeout:3e4}),n=new ge({networkProvider:r}),i=await this.getAbiForAction(t),{args:s}=this.getTxComponentsFromInputs(t,e,[]),o=s.map(P=>this.serializer.stringToTyped(P)),u=new me({queryRunner:n,abi:i}),c=u.createQuery({contract:t.address,function:t.func,arguments:o}),p=await u.runQuery(c),l=new fe,R={returnCode:p.returnCode,returnMessage:p.returnMessage,getReturnDataParts:()=>p.returnDataParts.map(P=>Buffer.from(P))},Nt=p.function,Et=i.getEndpoint(Nt),G=l.parseQueryResponse(R,Et).firstValue;if(!G)throw new Error("WarpActionExecutor: Query result not found");return G}async executeCollect(t,e,r){let n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([i,s])=>{n.set(i,s)}),await fetch(t.destination.url,{method:t.destination.method,headers:n,body:JSON.stringify({inputs:e,meta:r})})}getTxComponentsFromInputs(t,e,r){let n=this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),s=this.getPreparedArgs(t,i),o=i.find(R=>R.input.position==="value")?.value||null,u="value"in t?t.value:null,c=BigInt(o?.split(":")[1]||u||0),l=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...r];return{args:s,value:c,transfers:l}}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(u=>u.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=U(s,+i);return{...e,value:`${e.input.type}:${o}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let s=U(i,+n);return{...e,value:`${e.input.type}:${s}`}}}else return e})}getResolvedInputs(t,e){let r=t.inputs||[],n=(i,s)=>i.source==="query"?this.serializer.nativeToString(i.type,this.url.searchParams.get(i.name)||""):e[s]||null;return r.map((i,s)=>({input:i,value:n(i,s)}))}getPreparedArgs(t,e){let r="args"in t?t.args:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position.startsWith("arg:"))return;let s=Number(n.position.split(":")[1])-1;r.splice(s,0,i)}),r}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return At.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");let r=await(await fetch(t.abi)).json();return At.create(r)}toTypedTransfer(t){return new Te({token:new we({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Ut,ApiNetworkProvider as Se,TransactionsFactoryConfig as Re,TransferTransactionsFactory as Pe}from"@multiversx/sdk-core";import Ue from"ajv";var I={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},C=class{constructor(){this.cache=new Map}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};import xe from"qr-code-styling";import{AbiRegistry as xt,Address as g,AddressValue as Vt,ApiNetworkProvider as St,BytesValue as m,QueryRunnerAdapter as be,SmartContractQueriesController as Ae,SmartContractTransactionsFactory as Be,TransactionsFactoryConfig as ve}from"@multiversx/sdk-core/out";var z={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},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:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],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:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var x=class{constructor(t){this.cache=new C;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[m.fromHex(t),m.fromUTF8(e)]:[m.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromUTF8(t),m.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromUTF8(e)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromHex(e)]})}async getInfoByAlias(t,e){let r=I.RegistryInfo(t);if(e){let l=this.cache.get(r);if(l)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),l}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[m.fromUTF8(t)]}),o=await i.runQuery(s),[u]=i.parseQueryResponse(o),c=u?A(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}}async getInfoByHash(t,e){let r=I.RegistryInfo(t);if(e){let l=this.cache.get(r);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let n=this.getRegistryContractAddress(),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[m.fromHex(t)]}),o=await i.runQuery(s),[u]=i.parseQueryResponse(o),c=u?A(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}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;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 Vt(new g(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s);return o.map(A)}async getUserBrands(t){let e=t||this.config.userAddress;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 Vt(new g(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),u=o.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)}async fetchBrand(t,e){let r=I.Brand(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=new St(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),s=JSON.parse(i.data.toString());return s.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,s,e.ttl),s}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}getRegistryContractAddress(){return this.config.registryContract||d.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),n=await e.runQuery(r),[i]=e.parseQueryResponse(n),s=BigInt(i.toString());this.unitPrice=s}getFactory(){let t=new ve({chainID:T(this.config.env)}),e=xt.create(z);return new Be({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env),e=new St(t,{timeout:3e4}),r=new be({networkProvider:e}),n=xt.create(z);return new Ae({queryRunner:r,abi:n})}};var V=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(y.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),s=(await Promise.all(n)).filter(c=>c.match),o=s.length>0,u=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:u}}async detect(t){let e=t.startsWith(y.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):W.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new S(this.config),s=new x(this.config),o=null,u=null,c=null;if(r==="hash"){o=await i.createFromTransactionHash(n);try{let{registryInfo:p,brand:l}=await s.getInfoByHash(n);u=p,c=l}catch{}}else if(r==="alias"){let{registryInfo:p,brand:l}=await s.getInfoByAlias(n);u=p,c=l,p&&(o=await i.createFromTransactionHash(p.hash))}return o?{match:!0,url:t,warp:o,registryInfo:u,brand:c}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||d.DefaultClientUrl(this.config.env),n=t===y.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+y.IdentifierParamSeparator+e);return d.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${y.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new xe({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=d.SuperClientUrls.includes(e.origin),n=e.searchParams.get(y.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return W.getInfoFromPrefixedIdentifier(s)}};var Ve="https://",Rt="query",Pt="env",W=class a{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,s)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(t.vars).forEach(([i,s])=>{if(typeof s=="string"&&s.startsWith(`${Rt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${Rt}:`)[1],u=new URL(e.currentUrl).searchParams.get(o);u&&n(i,u)}else if(typeof s=="string"&&s.startsWith(`${Pt}:`)){let o=s.split(`${Pt}:`)[1],u=e.vars?.[o];u&&n(i,u)}else n(i,s)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(y.IdentifierParamSeparator)?e:`${y.DefaultIdentifierType}${y.IdentifierParamSeparator}${e}`,[n,i]=r.split(y.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(Ve))return t.next;{let r=new V(e),n=a.getInfoFromPrefixedIdentifier(t.next);return n?r.build(n.type,n.id):null}}};var S=class{constructor(t){this.cache=new C;this.pendingWarp={protocol:b(d.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Re({chainID:T(this.config.env)}),r=new Pe({config:e}),n=JSON.stringify(t),i=r.createTransactionForTransfer({sender:Ut.newFromBech32(this.config.userAddress),receiver:Ut.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()});return i.gasLimit=i.gasLimit+BigInt(2e6),i}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),W.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=I.Warp(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=new Se(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),s=await this.createFromTransaction(i);return e&&e.ttl&&s&&this.cache.set(r,s,e.ttl),s}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return J(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||d.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new Ue,s=i.compile(n);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var Ft=class{constructor(t){this.config=t}async search(t){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let e=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t})});if(!e.ok)throw new Error(`WarpIndex: search failed with status ${e.status}`);return(await e.json()).hits}catch(e){throw console.error("WarpIndex: Error searching for warps: ",e),e}}};export{Z as BrandBuilder,d as Config,vt as WarpActionExecutor,B as WarpArgSerializer,S as WarpBuilder,y as WarpConstants,v as WarpContractLoader,Ft as WarpIndex,V as WarpLink,x as WarpRegistry,W as WarpUtils,or as address,sr as biguint,ar as boolean,lr as codemeta,Ye as composite,pr as esdt,T as getChainId,b as getLatestProtocolIdentifier,ur as hex,Ze as list,dr as nothing,Je as option,Ke as optional,U as shiftBigintBy,tr as string,J as toPreviewText,A as toTypedRegistryInfo,cr as token,rr as u16,nr as u32,ir as u64,er as u8,Xe as variadic};
|
|
1
|
+
import{Address as Xe,ApiNetworkProvider as kt,TransactionsFactoryConfig as $t,TransferTransactionsFactory as Lt}from"@multiversx/sdk-core";import _t from"ajv";var U={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.4.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.4.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:m=>m==="devnet"?"https://devnet.usewarp.to":m==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:m=>m==="devnet"?"https://devnet-api.multiversx.com":m==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:m=>m==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":m==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var ie=m=>m==="devnet"?"D":m==="testnet"?"T":"1",me=m=>`${m}:${U.LatestProtocolVersion}`,ye=m=>({hash:m.hash.toString("hex"),alias:m.alias?.toString()||null,trust:m.trust.toString(),creator:m.creator.toString(),createdAt:m.created_at.toNumber(),brand:m.brand?.toString("hex")||null,upgrade:m.upgrade?.toString("hex")||null}),Ne=(m,e)=>{let n=m.toString(),[a,s=""]=n.split("."),d=Math.abs(e);if(e>0)return BigInt(a+s.padEnd(d,"0"));if(e<0){let y=a+s;if(d>=y.length)return 0n;let A=y.slice(0,-d)||"0";return BigInt(A)}else return BigInt(m)},Je=(m,e=100)=>{if(!m)return"";let n=m.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return n=n.startsWith("- ")?n.slice(2):n,n=n.length>e?n.substring(0,n.lastIndexOf(" ",e))+"...":n,n};var Ke=class{constructor(e){this.pendingBrand={protocol:me(U.ProtocolNameBrand),name:"",description:"",logo:""};this.config=e}createInscriptionTransaction(e){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let n=new $t({chainID:ie(this.config.env)}),a=new Lt({config:n}),s=JSON.stringify(e);return a.createTransactionForNativeTokenTransfer({sender:Xe.newFromBech32(this.config.userAddress),receiver:Xe.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(s).valueOf()})}async createFromRaw(e,n=!0){let a=JSON.parse(e);return n&&await this.ensureValidSchema(a),a}async createFromTransaction(e,n=!1){return await this.createFromRaw(e.data.toString(),n)}async createFromTransactionHash(e){let n=new kt(this.config.chainApiUrl||U.Chain.ApiUrl(this.config.env));try{let a=await n.getTransaction(e);return this.createFromTransaction(a)}catch(a){return console.error("BrandBuilder: Error creating from transaction hash",a),null}}setName(e){return this.pendingBrand.name=e,this}setDescription(e){return this.pendingBrand.description=e,this}setLogo(e){return this.pendingBrand.logo=e,this}setUrls(e){return this.pendingBrand.urls=e,this}setColors(e){return this.pendingBrand.colors=e,this}setCta(e){return this.pendingBrand.cta=e,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(e,n){if(!e)throw new Error(`Warp: ${n}`)}async ensureValidSchema(e){let n=this.config.brandSchemaUrl||U.LatestBrandSchemaUrl,s=await(await fetch(n)).json(),d=new _t,y=d.compile(s);if(!y(e))throw new Error(`BrandBuilder: schema validation failed: ${d.errorsText(y.errors)}`)}};var G={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import{Address as Dt,AddressValue as qt,BigUIntType as Mt,BigUIntValue as Ye,BooleanValue as Ht,BytesValue as Qt,CodeMetadata as Gt,CodeMetadataValue as zt,CompositeType as jt,CompositeValue as Jt,Field as Re,FieldDefinition as Ee,List as Xt,NothingValue as Kt,OptionalValue as Ve,OptionValue as Pe,StringValue as Yt,Struct as Zt,StructType as er,TokenIdentifierType as tr,TokenIdentifierValue as Ze,U16Value as rr,U32Value as nr,U64Type as ir,U64Value as et,U8Value as sr,VariadicValue as ar}from"@multiversx/sdk-core/out";var Xr=(m,e)=>m?Pe.newProvided(m):e?Pe.newMissingTyped(e):Pe.newMissing(),Kr=(m,e)=>m?new Ve(m.getType(),m):e?new Ve(e):Ve.newMissing(),Yr=m=>{if(m.length===0)throw new Error("Cannot create a list from an empty array");let e=m[0].getType();return new Xt(e,m)},Zr=m=>ar.fromItems(...m),en=m=>{let e=m.map(n=>n.getType());return new Jt(new jt(...e),m)},tn=m=>Yt.fromUTF8(m),rn=m=>new sr(m),nn=m=>new rr(m),sn=m=>new nr(m),an=m=>new et(m),on=m=>new Ye(BigInt(m)),cn=m=>new Ht(m),un=m=>new qt(Dt.newFromBech32(m)),ln=m=>new Ze(m),pn=m=>Qt.fromHex(m),fn=m=>new Zt(new er("EsdtTokenPayment",[new Ee("token_identifier","",new tr),new Ee("token_nonce","",new ir),new Ee("amount","",new Mt)]),[new Re(new Ze(m.token.identifier),"token_identifier"),new Re(new et(BigInt(m.token.nonce)),"token_nonce"),new Re(new Ye(BigInt(m.amount)),"amount")]),gn=m=>new zt(Gt.fromBuffer(Buffer.from(m,"hex"))),dn=()=>new Kt;import{AbiRegistry as bt,Address as St,ApiNetworkProvider as dr,QueryRunnerAdapter as hr,ResultsParser as mr,SmartContractQueriesController as yr,SmartContractTransactionsFactory as wr,StringValue as Tr,Token as Ar,TokenTransfer as Ir,TransactionsFactoryConfig as Cr,TransferTransactionsFactory as Br}from"@multiversx/sdk-core/out";import{Address as cr,AddressType as it,AddressValue as st,BigUIntType as ke,BigUIntValue as $e,BooleanType as at,BooleanValue as ot,BytesType as ct,BytesValue as ut,CodeMetadata as ur,CodeMetadataType as lt,CodeMetadataValue as pt,CompositeType as ft,CompositeValue as gt,Field as Le,FieldDefinition as _e,List as dt,NothingValue as M,OptionalValue as De,OptionValue as qe,StringType as ht,StringValue as mt,Struct as lr,StructType as yt,Token as pr,TokenIdentifierType as Me,TokenIdentifierValue as He,TokenTransfer as wt,U16Type as Tt,U16Value as At,U32Type as It,U32Value as Ct,U64Type as Qe,U64Value as Ge,U8Type as Bt,U8Value as Wt,VariadicType as fr,VariadicValue as vt}from"@multiversx/sdk-core/out";var or=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Oe=Math.ceil,j=Math.floor,D="[BigNumber Error] ",tt=D+"Number primitive has more than 15 significant digits: ",K=1e14,v=14,Ue=9007199254740991,Fe=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],se=1e7,F=1e9;function rt(m){var e,n,a,s=T.prototype={constructor:T,toString:null,valueOf:null},d=new T(1),y=20,A=4,B=-7,I=21,x=-1e7,b=1e7,X=!1,ae=1,Y=0,de={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Z="0123456789abcdefghijklmnopqrstuvwxyz",oe=!0;function T(t,r){var i,f,c,l,h,o,u,g,p=this;if(!(p instanceof T))return new T(t,r);if(r==null){if(t&&t._isBigNumber===!0){p.s=t.s,!t.c||t.e>b?p.c=p.e=null:t.e<x?p.c=[p.e=0]:(p.e=t.e,p.c=t.c.slice());return}if((o=typeof t=="number")&&t*0==0){if(p.s=1/t<0?(t=-t,-1):1,t===~~t){for(l=0,h=t;h>=10;h/=10,l++);l>b?p.c=p.e=null:(p.e=l,p.c=[t]);return}g=String(t)}else{if(!or.test(g=String(t)))return a(p,g,o);p.s=g.charCodeAt(0)==45?(g=g.slice(1),-1):1}(l=g.indexOf("."))>-1&&(g=g.replace(".","")),(h=g.search(/e/i))>0?(l<0&&(l=h),l+=+g.slice(h+1),g=g.substring(0,h)):l<0&&(l=g.length)}else{if(E(r,2,Z.length,"Base"),r==10&&oe)return p=new T(t),H(p,y+p.e+1,A);if(g=String(t),o=typeof t=="number"){if(t*0!=0)return a(p,g,o,r);if(p.s=1/t<0?(g=g.slice(1),-1):1,T.DEBUG&&g.replace(/^0\.0*|\./,"").length>15)throw Error(tt+t)}else p.s=g.charCodeAt(0)===45?(g=g.slice(1),-1):1;for(i=Z.slice(0,r),l=h=0,u=g.length;h<u;h++)if(i.indexOf(f=g.charAt(h))<0){if(f=="."){if(h>l){l=u;continue}}else if(!c&&(g==g.toUpperCase()&&(g=g.toLowerCase())||g==g.toLowerCase()&&(g=g.toUpperCase()))){c=!0,h=-1,l=0;continue}return a(p,String(t),o,r)}o=!1,g=n(g,r,10,p.s),(l=g.indexOf("."))>-1?g=g.replace(".",""):l=g.length}for(h=0;g.charCodeAt(h)===48;h++);for(u=g.length;g.charCodeAt(--u)===48;);if(g=g.slice(h,++u)){if(u-=h,o&&T.DEBUG&&u>15&&(t>Ue||t!==j(t)))throw Error(tt+p.s*t);if((l=l-h-1)>b)p.c=p.e=null;else if(l<x)p.c=[p.e=0];else{if(p.e=l,p.c=[],h=(l+1)%v,l<0&&(h+=v),h<u){for(h&&p.c.push(+g.slice(0,h)),u-=v;h<u;)p.c.push(+g.slice(h,h+=v));h=v-(g=g.slice(h)).length}else h-=u;for(;h--;g+="0");p.c.push(+g)}}else p.c=[p.e=0]}T.clone=rt,T.ROUND_UP=0,T.ROUND_DOWN=1,T.ROUND_CEIL=2,T.ROUND_FLOOR=3,T.ROUND_HALF_UP=4,T.ROUND_HALF_DOWN=5,T.ROUND_HALF_EVEN=6,T.ROUND_HALF_CEIL=7,T.ROUND_HALF_FLOOR=8,T.EUCLID=9,T.config=T.set=function(t){var r,i;if(t!=null)if(typeof t=="object"){if(t.hasOwnProperty(r="DECIMAL_PLACES")&&(i=t[r],E(i,0,F,r),y=i),t.hasOwnProperty(r="ROUNDING_MODE")&&(i=t[r],E(i,0,8,r),A=i),t.hasOwnProperty(r="EXPONENTIAL_AT")&&(i=t[r],i&&i.pop?(E(i[0],-F,0,r),E(i[1],0,F,r),B=i[0],I=i[1]):(E(i,-F,F,r),B=-(I=i<0?-i:i))),t.hasOwnProperty(r="RANGE"))if(i=t[r],i&&i.pop)E(i[0],-F,-1,r),E(i[1],1,F,r),x=i[0],b=i[1];else if(E(i,-F,F,r),i)x=-(b=i<0?-i:i);else throw Error(D+r+" cannot be zero: "+i);if(t.hasOwnProperty(r="CRYPTO"))if(i=t[r],i===!!i)if(i)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))X=i;else throw X=!i,Error(D+"crypto unavailable");else X=i;else throw Error(D+r+" not true or false: "+i);if(t.hasOwnProperty(r="MODULO_MODE")&&(i=t[r],E(i,0,9,r),ae=i),t.hasOwnProperty(r="POW_PRECISION")&&(i=t[r],E(i,0,F,r),Y=i),t.hasOwnProperty(r="FORMAT"))if(i=t[r],typeof i=="object")de=i;else throw Error(D+r+" not an object: "+i);if(t.hasOwnProperty(r="ALPHABET"))if(i=t[r],typeof i=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(i))oe=i.slice(0,10)=="0123456789",Z=i;else throw Error(D+r+" invalid: "+i)}else throw Error(D+"Object expected: "+t);return{DECIMAL_PLACES:y,ROUNDING_MODE:A,EXPONENTIAL_AT:[B,I],RANGE:[x,b],CRYPTO:X,MODULO_MODE:ae,POW_PRECISION:Y,FORMAT:de,ALPHABET:Z}},T.isBigNumber=function(t){if(!t||t._isBigNumber!==!0)return!1;if(!T.DEBUG)return!0;var r,i,f=t.c,c=t.e,l=t.s;e:if({}.toString.call(f)=="[object Array]"){if((l===1||l===-1)&&c>=-F&&c<=F&&c===j(c)){if(f[0]===0){if(c===0&&f.length===1)return!0;break e}if(r=(c+1)%v,r<1&&(r+=v),String(f[0]).length==r){for(r=0;r<f.length;r++)if(i=f[r],i<0||i>=K||i!==j(i))break e;if(i!==0)return!0}}}else if(f===null&&c===null&&(l===null||l===1||l===-1))return!0;throw Error(D+"Invalid BigNumber: "+t)},T.maximum=T.max=function(){return je(arguments,-1)},T.minimum=T.min=function(){return je(arguments,1)},T.random=function(){var t=9007199254740992,r=Math.random()*t&2097151?function(){return j(Math.random()*t)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(i){var f,c,l,h,o,u=0,g=[],p=new T(d);if(i==null?i=y:E(i,0,F),h=Oe(i/v),X)if(crypto.getRandomValues){for(f=crypto.getRandomValues(new Uint32Array(h*=2));u<h;)o=f[u]*131072+(f[u+1]>>>11),o>=9e15?(c=crypto.getRandomValues(new Uint32Array(2)),f[u]=c[0],f[u+1]=c[1]):(g.push(o%1e14),u+=2);u=h/2}else if(crypto.randomBytes){for(f=crypto.randomBytes(h*=7);u<h;)o=(f[u]&31)*281474976710656+f[u+1]*1099511627776+f[u+2]*4294967296+f[u+3]*16777216+(f[u+4]<<16)+(f[u+5]<<8)+f[u+6],o>=9e15?crypto.randomBytes(7).copy(f,u):(g.push(o%1e14),u+=7);u=h/7}else throw X=!1,Error(D+"crypto unavailable");if(!X)for(;u<h;)o=r(),o<9e15&&(g[u++]=o%1e14);for(h=g[--u],i%=v,h&&i&&(o=Fe[v-i],g[u]=j(h/o)*o);g[u]===0;g.pop(),u--);if(u<0)g=[l=0];else{for(l=-1;g[0]===0;g.splice(0,1),l-=v);for(u=1,o=g[0];o>=10;o/=10,u++);u<v&&(l-=v-u)}return p.e=l,p.c=g,p}}(),T.sum=function(){for(var t=1,r=arguments,i=new T(r[0]);t<r.length;)i=i.plus(r[t++]);return i},n=function(){var t="0123456789";function r(i,f,c,l){for(var h,o=[0],u,g=0,p=i.length;g<p;){for(u=o.length;u--;o[u]*=f);for(o[0]+=l.indexOf(i.charAt(g++)),h=0;h<o.length;h++)o[h]>c-1&&(o[h+1]==null&&(o[h+1]=0),o[h+1]+=o[h]/c|0,o[h]%=c)}return o.reverse()}return function(i,f,c,l,h){var o,u,g,p,w,C,W,N,V=i.indexOf("."),O=y,S=A;for(V>=0&&(p=Y,Y=0,i=i.replace(".",""),N=new T(f),C=N.pow(i.length-V),Y=p,N.c=r(re(z(C.c),C.e,"0"),10,c,t),N.e=N.c.length),W=r(i,f,c,h?(o=Z,t):(o=t,Z)),g=p=W.length;W[--p]==0;W.pop());if(!W[0])return o.charAt(0);if(V<0?--g:(C.c=W,C.e=g,C.s=l,C=e(C,N,O,S,c),W=C.c,w=C.r,g=C.e),u=g+O+1,V=W[u],p=c/2,w=w||u<0||W[u+1]!=null,w=S<4?(V!=null||w)&&(S==0||S==(C.s<0?3:2)):V>p||V==p&&(S==4||w||S==6&&W[u-1]&1||S==(C.s<0?8:7)),u<1||!W[0])i=w?re(o.charAt(1),-O,o.charAt(0)):o.charAt(0);else{if(W.length=u,w)for(--c;++W[--u]>c;)W[u]=0,u||(++g,W=[1].concat(W));for(p=W.length;!W[--p];);for(V=0,i="";V<=p;i+=o.charAt(W[V++]));i=re(i,g,o.charAt(0))}return i}}(),e=function(){function t(f,c,l){var h,o,u,g,p=0,w=f.length,C=c%se,W=c/se|0;for(f=f.slice();w--;)u=f[w]%se,g=f[w]/se|0,h=W*u+g*C,o=C*u+h%se*se+p,p=(o/l|0)+(h/se|0)+W*g,f[w]=o%l;return p&&(f=[p].concat(f)),f}function r(f,c,l,h){var o,u;if(l!=h)u=l>h?1:-1;else for(o=u=0;o<l;o++)if(f[o]!=c[o]){u=f[o]>c[o]?1:-1;break}return u}function i(f,c,l,h){for(var o=0;l--;)f[l]-=o,o=f[l]<c[l]?1:0,f[l]=o*h+f[l]-c[l];for(;!f[0]&&f.length>1;f.splice(0,1));}return function(f,c,l,h,o){var u,g,p,w,C,W,N,V,O,S,R,k,he,be,Se,ee,fe,Q=f.s==c.s?1:-1,L=f.c,P=c.c;if(!L||!L[0]||!P||!P[0])return new T(!f.s||!c.s||(L?P&&L[0]==P[0]:!P)?NaN:L&&L[0]==0||!P?Q*0:Q/0);for(V=new T(Q),O=V.c=[],g=f.e-c.e,Q=l+g+1,o||(o=K,g=J(f.e/v)-J(c.e/v),Q=Q/v|0),p=0;P[p]==(L[p]||0);p++);if(P[p]>(L[p]||0)&&g--,Q<0)O.push(1),w=!0;else{for(be=L.length,ee=P.length,p=0,Q+=2,C=j(o/(P[0]+1)),C>1&&(P=t(P,C,o),L=t(L,C,o),ee=P.length,be=L.length),he=ee,S=L.slice(0,ee),R=S.length;R<ee;S[R++]=0);fe=P.slice(),fe=[0].concat(fe),Se=P[0],P[1]>=o/2&&Se++;do{if(C=0,u=r(P,S,ee,R),u<0){if(k=S[0],ee!=R&&(k=k*o+(S[1]||0)),C=j(k/Se),C>1)for(C>=o&&(C=o-1),W=t(P,C,o),N=W.length,R=S.length;r(W,S,N,R)==1;)C--,i(W,ee<N?fe:P,N,o),N=W.length,u=1;else C==0&&(u=C=1),W=P.slice(),N=W.length;if(N<R&&(W=[0].concat(W)),i(S,W,R,o),R=S.length,u==-1)for(;r(P,S,ee,R)<1;)C++,i(S,ee<R?fe:P,R,o),R=S.length}else u===0&&(C++,S=[0]);O[p++]=C,S[0]?S[R++]=L[he]||0:(S=[L[he]],R=1)}while((he++<be||S[0]!=null)&&Q--);w=S[0]!=null,O[0]||O.splice(0,1)}if(o==K){for(p=1,Q=O[0];Q>=10;Q/=10,p++);H(V,l+(V.e=p+g*v-1)+1,h,w)}else V.e=g,V.r=+w;return V}}();function ve(t,r,i,f){var c,l,h,o,u;if(i==null?i=A:E(i,0,8),!t.c)return t.toString();if(c=t.c[0],h=t.e,r==null)u=z(t.c),u=f==1||f==2&&(h<=B||h>=I)?Te(u,h):re(u,h,"0");else if(t=H(new T(t),r,i),l=t.e,u=z(t.c),o=u.length,f==1||f==2&&(r<=l||l<=B)){for(;o<r;u+="0",o++);u=Te(u,l)}else if(r-=h,u=re(u,l,"0"),l+1>o){if(--r>0)for(u+=".";r--;u+="0");}else if(r+=l-o,r>0)for(l+1==o&&(u+=".");r--;u+="0");return t.s<0&&c?"-"+u:u}function je(t,r){for(var i,f,c=1,l=new T(t[0]);c<t.length;c++)f=new T(t[c]),(!f.s||(i=ce(l,f))===r||i===0&&l.s===r)&&(l=f);return l}function xe(t,r,i){for(var f=1,c=r.length;!r[--c];r.pop());for(c=r[0];c>=10;c/=10,f++);return(i=f+i*v-1)>b?t.c=t.e=null:i<x?t.c=[t.e=0]:(t.e=i,t.c=r),t}a=function(){var t=/^(-?)0([xbo])(?=\w[\w.]*$)/i,r=/^([^.]+)\.$/,i=/^\.([^.]+)$/,f=/^-?(Infinity|NaN)$/,c=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(l,h,o,u){var g,p=o?h:h.replace(c,"");if(f.test(p))l.s=isNaN(p)?null:p<0?-1:1;else{if(!o&&(p=p.replace(t,function(w,C,W){return g=(W=W.toLowerCase())=="x"?16:W=="b"?2:8,!u||u==g?C:w}),u&&(g=u,p=p.replace(r,"$1").replace(i,"0.$1")),h!=p))return new T(p,g);if(T.DEBUG)throw Error(D+"Not a"+(u?" base "+u:"")+" number: "+h);l.s=null}l.c=l.e=null}}();function H(t,r,i,f){var c,l,h,o,u,g,p,w=t.c,C=Fe;if(w){e:{for(c=1,o=w[0];o>=10;o/=10,c++);if(l=r-c,l<0)l+=v,h=r,u=w[g=0],p=j(u/C[c-h-1]%10);else if(g=Oe((l+1)/v),g>=w.length)if(f){for(;w.length<=g;w.push(0));u=p=0,c=1,l%=v,h=l-v+1}else break e;else{for(u=o=w[g],c=1;o>=10;o/=10,c++);l%=v,h=l-v+c,p=h<0?0:j(u/C[c-h-1]%10)}if(f=f||r<0||w[g+1]!=null||(h<0?u:u%C[c-h-1]),f=i<4?(p||f)&&(i==0||i==(t.s<0?3:2)):p>5||p==5&&(i==4||f||i==6&&(l>0?h>0?u/C[c-h]:0:w[g-1])%10&1||i==(t.s<0?8:7)),r<1||!w[0])return w.length=0,f?(r-=t.e+1,w[0]=C[(v-r%v)%v],t.e=-r||0):w[0]=t.e=0,t;if(l==0?(w.length=g,o=1,g--):(w.length=g+1,o=C[v-l],w[g]=h>0?j(u/C[c-h]%C[h])*o:0),f)for(;;)if(g==0){for(l=1,h=w[0];h>=10;h/=10,l++);for(h=w[0]+=o,o=1;h>=10;h/=10,o++);l!=o&&(t.e++,w[0]==K&&(w[0]=1));break}else{if(w[g]+=o,w[g]!=K)break;w[g--]=0,o=1}for(l=w.length;w[--l]===0;w.pop());}t.e>b?t.c=t.e=null:t.e<x&&(t.c=[t.e=0])}return t}function te(t){var r,i=t.e;return i===null?t.toString():(r=z(t.c),r=i<=B||i>=I?Te(r,i):re(r,i,"0"),t.s<0?"-"+r:r)}return s.absoluteValue=s.abs=function(){var t=new T(this);return t.s<0&&(t.s=1),t},s.comparedTo=function(t,r){return ce(this,new T(t,r))},s.decimalPlaces=s.dp=function(t,r){var i,f,c,l=this;if(t!=null)return E(t,0,F),r==null?r=A:E(r,0,8),H(new T(l),t+l.e+1,r);if(!(i=l.c))return null;if(f=((c=i.length-1)-J(this.e/v))*v,c=i[c])for(;c%10==0;c/=10,f--);return f<0&&(f=0),f},s.dividedBy=s.div=function(t,r){return e(this,new T(t,r),y,A)},s.dividedToIntegerBy=s.idiv=function(t,r){return e(this,new T(t,r),0,1)},s.exponentiatedBy=s.pow=function(t,r){var i,f,c,l,h,o,u,g,p,w=this;if(t=new T(t),t.c&&!t.isInteger())throw Error(D+"Exponent not an integer: "+te(t));if(r!=null&&(r=new T(r)),o=t.e>14,!w.c||!w.c[0]||w.c[0]==1&&!w.e&&w.c.length==1||!t.c||!t.c[0])return p=new T(Math.pow(+te(w),o?t.s*(2-we(t)):+te(t))),r?p.mod(r):p;if(u=t.s<0,r){if(r.c?!r.c[0]:!r.s)return new T(NaN);f=!u&&w.isInteger()&&r.isInteger(),f&&(w=w.mod(r))}else{if(t.e>9&&(w.e>0||w.e<-1||(w.e==0?w.c[0]>1||o&&w.c[1]>=24e7:w.c[0]<8e13||o&&w.c[0]<=9999975e7)))return l=w.s<0&&we(t)?-0:0,w.e>-1&&(l=1/l),new T(u?1/l:l);Y&&(l=Oe(Y/v+2))}for(o?(i=new T(.5),u&&(t.s=1),g=we(t)):(c=Math.abs(+te(t)),g=c%2),p=new T(d);;){if(g){if(p=p.times(w),!p.c)break;l?p.c.length>l&&(p.c.length=l):f&&(p=p.mod(r))}if(c){if(c=j(c/2),c===0)break;g=c%2}else if(t=t.times(i),H(t,t.e+1,1),t.e>14)g=we(t);else{if(c=+te(t),c===0)break;g=c%2}w=w.times(w),l?w.c&&w.c.length>l&&(w.c.length=l):f&&(w=w.mod(r))}return f?p:(u&&(p=d.div(p)),r?p.mod(r):l?H(p,Y,A,h):p)},s.integerValue=function(t){var r=new T(this);return t==null?t=A:E(t,0,8),H(r,r.e+1,t)},s.isEqualTo=s.eq=function(t,r){return ce(this,new T(t,r))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(t,r){return ce(this,new T(t,r))>0},s.isGreaterThanOrEqualTo=s.gte=function(t,r){return(r=ce(this,new T(t,r)))===1||r===0},s.isInteger=function(){return!!this.c&&J(this.e/v)>this.c.length-2},s.isLessThan=s.lt=function(t,r){return ce(this,new T(t,r))<0},s.isLessThanOrEqualTo=s.lte=function(t,r){return(r=ce(this,new T(t,r)))===-1||r===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(t,r){var i,f,c,l,h=this,o=h.s;if(t=new T(t,r),r=t.s,!o||!r)return new T(NaN);if(o!=r)return t.s=-r,h.plus(t);var u=h.e/v,g=t.e/v,p=h.c,w=t.c;if(!u||!g){if(!p||!w)return p?(t.s=-r,t):new T(w?h:NaN);if(!p[0]||!w[0])return w[0]?(t.s=-r,t):new T(p[0]?h:A==3?-0:0)}if(u=J(u),g=J(g),p=p.slice(),o=u-g){for((l=o<0)?(o=-o,c=p):(g=u,c=w),c.reverse(),r=o;r--;c.push(0));c.reverse()}else for(f=(l=(o=p.length)<(r=w.length))?o:r,o=r=0;r<f;r++)if(p[r]!=w[r]){l=p[r]<w[r];break}if(l&&(c=p,p=w,w=c,t.s=-t.s),r=(f=w.length)-(i=p.length),r>0)for(;r--;p[i++]=0);for(r=K-1;f>o;){if(p[--f]<w[f]){for(i=f;i&&!p[--i];p[i]=r);--p[i],p[f]+=K}p[f]-=w[f]}for(;p[0]==0;p.splice(0,1),--g);return p[0]?xe(t,p,g):(t.s=A==3?-1:1,t.c=[t.e=0],t)},s.modulo=s.mod=function(t,r){var i,f,c=this;return t=new T(t,r),!c.c||!t.s||t.c&&!t.c[0]?new T(NaN):!t.c||c.c&&!c.c[0]?new T(c):(ae==9?(f=t.s,t.s=1,i=e(c,t,0,3),t.s=f,i.s*=f):i=e(c,t,0,ae),t=c.minus(i.times(t)),!t.c[0]&&ae==1&&(t.s=c.s),t)},s.multipliedBy=s.times=function(t,r){var i,f,c,l,h,o,u,g,p,w,C,W,N,V,O,S=this,R=S.c,k=(t=new T(t,r)).c;if(!R||!k||!R[0]||!k[0])return!S.s||!t.s||R&&!R[0]&&!k||k&&!k[0]&&!R?t.c=t.e=t.s=null:(t.s*=S.s,!R||!k?t.c=t.e=null:(t.c=[0],t.e=0)),t;for(f=J(S.e/v)+J(t.e/v),t.s*=S.s,u=R.length,w=k.length,u<w&&(N=R,R=k,k=N,c=u,u=w,w=c),c=u+w,N=[];c--;N.push(0));for(V=K,O=se,c=w;--c>=0;){for(i=0,C=k[c]%O,W=k[c]/O|0,h=u,l=c+h;l>c;)g=R[--h]%O,p=R[h]/O|0,o=W*g+p*C,g=C*g+o%O*O+N[l]+i,i=(g/V|0)+(o/O|0)+W*p,N[l--]=g%V;N[l]=i}return i?++f:N.splice(0,1),xe(t,N,f)},s.negated=function(){var t=new T(this);return t.s=-t.s||null,t},s.plus=function(t,r){var i,f=this,c=f.s;if(t=new T(t,r),r=t.s,!c||!r)return new T(NaN);if(c!=r)return t.s=-r,f.minus(t);var l=f.e/v,h=t.e/v,o=f.c,u=t.c;if(!l||!h){if(!o||!u)return new T(c/0);if(!o[0]||!u[0])return u[0]?t:new T(o[0]?f:c*0)}if(l=J(l),h=J(h),o=o.slice(),c=l-h){for(c>0?(h=l,i=u):(c=-c,i=o),i.reverse();c--;i.push(0));i.reverse()}for(c=o.length,r=u.length,c-r<0&&(i=u,u=o,o=i,r=c),c=0;r;)c=(o[--r]=o[r]+u[r]+c)/K|0,o[r]=K===o[r]?0:o[r]%K;return c&&(o=[c].concat(o),++h),xe(t,o,h)},s.precision=s.sd=function(t,r){var i,f,c,l=this;if(t!=null&&t!==!!t)return E(t,1,F),r==null?r=A:E(r,0,8),H(new T(l),t,r);if(!(i=l.c))return null;if(c=i.length-1,f=c*v+1,c=i[c]){for(;c%10==0;c/=10,f--);for(c=i[0];c>=10;c/=10,f++);}return t&&l.e+1>f&&(f=l.e+1),f},s.shiftedBy=function(t){return E(t,-Ue,Ue),this.times("1e"+t)},s.squareRoot=s.sqrt=function(){var t,r,i,f,c,l=this,h=l.c,o=l.s,u=l.e,g=y+4,p=new T("0.5");if(o!==1||!h||!h[0])return new T(!o||o<0&&(!h||h[0])?NaN:h?l:1/0);if(o=Math.sqrt(+te(l)),o==0||o==1/0?(r=z(h),(r.length+u)%2==0&&(r+="0"),o=Math.sqrt(+r),u=J((u+1)/2)-(u<0||u%2),o==1/0?r="5e"+u:(r=o.toExponential(),r=r.slice(0,r.indexOf("e")+1)+u),i=new T(r)):i=new T(o+""),i.c[0]){for(u=i.e,o=u+g,o<3&&(o=0);;)if(c=i,i=p.times(c.plus(e(l,c,g,1))),z(c.c).slice(0,o)===(r=z(i.c)).slice(0,o))if(i.e<u&&--o,r=r.slice(o-3,o+1),r=="9999"||!f&&r=="4999"){if(!f&&(H(c,c.e+y+2,0),c.times(c).eq(l))){i=c;break}g+=4,o+=4,f=1}else{(!+r||!+r.slice(1)&&r.charAt(0)=="5")&&(H(i,i.e+y+2,1),t=!i.times(i).eq(l));break}}return H(i,i.e+y+1,A,t)},s.toExponential=function(t,r){return t!=null&&(E(t,0,F),t++),ve(this,t,r,1)},s.toFixed=function(t,r){return t!=null&&(E(t,0,F),t=t+this.e+1),ve(this,t,r)},s.toFormat=function(t,r,i){var f,c=this;if(i==null)t!=null&&r&&typeof r=="object"?(i=r,r=null):t&&typeof t=="object"?(i=t,t=r=null):i=de;else if(typeof i!="object")throw Error(D+"Argument not an object: "+i);if(f=c.toFixed(t,r),c.c){var l,h=f.split("."),o=+i.groupSize,u=+i.secondaryGroupSize,g=i.groupSeparator||"",p=h[0],w=h[1],C=c.s<0,W=C?p.slice(1):p,N=W.length;if(u&&(l=o,o=u,u=l,N-=l),o>0&&N>0){for(l=N%o||o,p=W.substr(0,l);l<N;l+=o)p+=g+W.substr(l,o);u>0&&(p+=g+W.slice(l)),C&&(p="-"+p)}f=w?p+(i.decimalSeparator||"")+((u=+i.fractionGroupSize)?w.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(i.fractionGroupSeparator||"")):w):p}return(i.prefix||"")+f+(i.suffix||"")},s.toFraction=function(t){var r,i,f,c,l,h,o,u,g,p,w,C,W=this,N=W.c;if(t!=null&&(o=new T(t),!o.isInteger()&&(o.c||o.s!==1)||o.lt(d)))throw Error(D+"Argument "+(o.isInteger()?"out of range: ":"not an integer: ")+te(o));if(!N)return new T(W);for(r=new T(d),g=i=new T(d),f=u=new T(d),C=z(N),l=r.e=C.length-W.e-1,r.c[0]=Fe[(h=l%v)<0?v+h:h],t=!t||o.comparedTo(r)>0?l>0?r:g:o,h=b,b=1/0,o=new T(C),u.c[0]=0;p=e(o,r,0,1),c=i.plus(p.times(f)),c.comparedTo(t)!=1;)i=f,f=c,g=u.plus(p.times(c=g)),u=c,r=o.minus(p.times(c=r)),o=c;return c=e(t.minus(i),f,0,1),u=u.plus(c.times(g)),i=i.plus(c.times(f)),u.s=g.s=W.s,l=l*2,w=e(g,f,l,A).minus(W).abs().comparedTo(e(u,i,l,A).minus(W).abs())<1?[g,f]:[u,i],b=h,w},s.toNumber=function(){return+te(this)},s.toPrecision=function(t,r){return t!=null&&E(t,1,F),ve(this,t,r,2)},s.toString=function(t){var r,i=this,f=i.s,c=i.e;return c===null?f?(r="Infinity",f<0&&(r="-"+r)):r="NaN":(t==null?r=c<=B||c>=I?Te(z(i.c),c):re(z(i.c),c,"0"):t===10&&oe?(i=H(new T(i),y+c+1,A),r=re(z(i.c),i.e,"0")):(E(t,2,Z.length,"Base"),r=n(re(z(i.c),c,"0"),10,t,f,!0)),f<0&&i.c[0]&&(r="-"+r)),r},s.valueOf=s.toJSON=function(){return te(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,m!=null&&T.set(m),T}function J(m){var e=m|0;return m>0||m===e?e:e-1}function z(m){for(var e,n,a=1,s=m.length,d=m[0]+"";a<s;){for(e=m[a++]+"",n=v-e.length;n--;e="0"+e);d+=e}for(s=d.length;d.charCodeAt(--s)===48;);return d.slice(0,s+1||1)}function ce(m,e){var n,a,s=m.c,d=e.c,y=m.s,A=e.s,B=m.e,I=e.e;if(!y||!A)return null;if(n=s&&!s[0],a=d&&!d[0],n||a)return n?a?0:-A:y;if(y!=A)return y;if(n=y<0,a=B==I,!s||!d)return a?0:!s^n?1:-1;if(!a)return B>I^n?1:-1;for(A=(B=s.length)<(I=d.length)?B:I,y=0;y<A;y++)if(s[y]!=d[y])return s[y]>d[y]^n?1:-1;return B==I?0:B>I^n?1:-1}function E(m,e,n,a){if(m<e||m>n||m!==j(m))throw Error(D+(a||"Argument")+(typeof m=="number"?m<e||m>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function we(m){var e=m.c.length-1;return J(m.e/v)==e&&m.c[e]%2!=0}function Te(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function re(m,e,n){var a,s;if(e<0){for(s=n+".";++e;s+=n);m=s+m}else if(a=m.length,++e>a){for(s=n,e-=a;--e;s+=n);m+=s}else e<a&&(m=m.slice(0,e)+"."+m.slice(e));return m}var nt=rt();var _=":",ne="|",xt=new RegExp(`${_}(.*)`),Ae=class{nativeToString(e,n){return e==="esdt"&&n instanceof wt?`esdt:${n.token.identifier}|${n.token.nonce.toString()}|${n.amount.toString()}`:`${e}:${n?.toString()??""}`}typedToString(e){if(e.hasClassOrSuperclass(qe.ClassName))return e.isSet()?`option:${this.typedToString(e.getTypedValue())}`:"option:null";if(e.hasClassOrSuperclass(De.ClassName))return e.isSet()?`optional:${this.typedToString(e.getTypedValue())}`:"optional:null";if(e.hasClassOrSuperclass(dt.ClassName)){let n=e.getItems(),s=n.map(y=>this.typedToString(y).split(_)[0])[0],d=n.map(y=>this.typedToString(y).split(_)[1]);return`list:${s}:${d.join(",")}`}if(e.hasClassOrSuperclass(vt.ClassName)){let n=e.getItems(),s=n.map(y=>this.typedToString(y).split(_)[0])[0],d=n.map(y=>this.typedToString(y).split(_)[1]);return`variadic:${s}:${d.join(",")}`}if(e.hasClassOrSuperclass(gt.ClassName)){let n=e.getItems(),a=n.map(A=>this.typedToString(A).split(_)[0]),s=n.map(A=>this.typedToString(A).split(_)[1]),d=a.join(ne),y=s.join(ne);return`composite(${d}):${y}`}if(e.hasClassOrSuperclass($e.ClassName)||nt.isBigNumber(e))return`biguint:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(Wt.ClassName))return`uint8:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(At.ClassName))return`uint16:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Ct.ClassName))return`uint32:${e.valueOf().toNumber()}`;if(e.hasClassOrSuperclass(Ge.ClassName))return`uint64:${BigInt(e.valueOf().toFixed())}`;if(e.hasClassOrSuperclass(mt.ClassName))return`string:${e.valueOf()}`;if(e.hasClassOrSuperclass(ot.ClassName))return`bool:${e.valueOf()}`;if(e.hasClassOrSuperclass(st.ClassName))return`address:${e.valueOf().bech32()}`;if(e.hasClassOrSuperclass(He.ClassName))return`token:${e.valueOf()}`;if(e.hasClassOrSuperclass(ut.ClassName))return`hex:${e.valueOf().toString("hex")}`;if(e.hasClassOrSuperclass(pt.ClassName))return`codemeta:${e.valueOf().toBuffer().toString("hex")}`;if(e.getType().getName()==="EsdtTokenPayment"){let n=e.getFieldValue("token_identifier").valueOf(),a=e.getFieldValue("token_nonce").valueOf(),s=e.getFieldValue("amount").valueOf();return`esdt:${n}|${a}|${s}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${e.getClassName()}`)}typedToNative(e){let n=this.typedToString(e);return this.stringToNative(n)}nativeToTyped(e,n){let a=this.nativeToString(e,n);return this.stringToTyped(a)}nativeToType(e){if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1];return new ft(...n.split(ne).map(a=>this.nativeToType(a)))}if(e==="string")return new ht;if(e==="uint8")return new Bt;if(e==="uint16")return new Tt;if(e==="uint32")return new It;if(e==="uint64")return new Qe;if(e==="biguint")return new ke;if(e==="bool")return new at;if(e==="address")return new it;if(e==="token")return new Me;if(e==="hex")return new ct;if(e==="codemeta")return new lt;if(e==="esdt"||e==="nft")return new yt("EsdtTokenPayment",[new _e("token_identifier","",new Me),new _e("token_nonce","",new Qe),new _e("amount","",new ke)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${e}`)}stringToNative(e){let n=e.split(_),a=n[0],s=n.slice(1).join(_);if(a==="null")return[a,null];if(a==="option"){let[d,y]=s.split(_);return[`option:${d}`,y||null]}else if(a==="optional"){let[d,y]=s.split(_);return[`optional:${d}`,y||null]}else if(a==="list"){let d=s.split(_),y=d.slice(0,-1).join(_),A=d[d.length-1],I=(A?A.split(","):[]).map(x=>this.stringToNative(`${y}:${x}`)[1]);return[`list:${y}`,I]}else if(a==="variadic"){let d=s.split(_),y=d.slice(0,-1).join(_),A=d[d.length-1],I=(A?A.split(","):[]).map(x=>this.stringToNative(`${y}:${x}`)[1]);return[`variadic:${y}`,I]}else if(a.startsWith("composite")){let d=a.match(/\(([^)]+)\)/)?.[1]?.split(ne),A=s.split(ne).map((B,I)=>this.stringToNative(`${d[I]}:${B}`)[1]);return[a,A]}else{if(a==="string")return[a,s];if(a==="uint8"||a==="uint16"||a==="uint32")return[a,Number(s)];if(a==="uint64"||a==="biguint")return[a,BigInt(s||0)];if(a==="bool")return[a,s==="true"];if(a==="address")return[a,s];if(a==="token")return[a,s];if(a==="hex")return[a,s];if(a==="codemeta")return[a,s];if(a==="esdt"){let[d,y,A]=s.split(ne);return[a,new wt({token:new pr({identifier:d,nonce:BigInt(y)}),amount:BigInt(A)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${a}`)}stringToTyped(e){let[n,a]=e.split(/:(.*)/,2);if(n==="null"||n===null)return new M;if(n==="option"){let s=this.stringToTyped(a);return s instanceof M?qe.newMissingTyped(s.getType()):qe.newProvided(s)}if(n==="optional"){let s=this.stringToTyped(a);return s instanceof M?De.newMissing():new De(s.getType(),s)}if(n==="list"){let[s,d]=a.split(xt,2),A=d.split(",").map(B=>this.stringToTyped(`${s}:${B}`));return new dt(this.nativeToType(s),A)}if(n==="variadic"){let[s,d]=a.split(xt,2),A=d.split(",").map(B=>this.stringToTyped(`${s}:${B}`));return new vt(new fr(this.nativeToType(s)),A)}if(n.startsWith("composite")){let s=n.match(/\(([^)]+)\)/)?.[1],d=a.split(ne),y=s.split(ne),A=d.map((I,x)=>this.stringToTyped(`${y[x]}:${I}`)),B=A.map(I=>I.getType());return new gt(new ft(...B),A)}if(n==="string")return a?mt.fromUTF8(a):new M;if(n==="uint8")return a?new Wt(Number(a)):new M;if(n==="uint16")return a?new At(Number(a)):new M;if(n==="uint32")return a?new Ct(Number(a)):new M;if(n==="uint64")return a?new Ge(BigInt(a)):new M;if(n==="biguint")return a?new $e(BigInt(a)):new M;if(n==="bool")return a?new ot(typeof a=="boolean"?a:a==="true"):new M;if(n==="address")return a?new st(cr.newFromBech32(a)):new M;if(n==="token")return a?new He(a):new M;if(n==="hex")return a?ut.fromHex(a):new M;if(n==="codemeta")return new pt(ur.fromBuffer(Buffer.from(a,"hex")));if(n==="esdt"){let s=a.split(ne);return new lr(this.nativeToType("esdt"),[new Le(new He(s[0]),"token_identifier"),new Le(new Ge(BigInt(s[1])),"token_nonce"),new Le(new $e(BigInt(s[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${n}`)}typeToNative(e){if(e instanceof ht)return"string";if(e instanceof Bt)return"uint8";if(e instanceof Tt)return"uint16";if(e instanceof It)return"uint32";if(e instanceof Qe)return"uint64";if(e instanceof ke)return"biguint";if(e instanceof at)return"bool";if(e instanceof it)return"address";if(e instanceof Me)return"token";if(e instanceof ct)return"hex";if(e instanceof lt)return"codemeta";if(e instanceof yt&&e.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${e.getClassName()}`)}};import{ApiNetworkProvider as gr}from"@multiversx/sdk-core/out";var Ie=class{constructor(e){this.config=e}async getContract(e){try{let a=await this.getConfiguredChainApi().doGetGeneric(`accounts/${e}/verification`);return{address:e,owner:a.ownerAddress,verified:a.isVerified}}catch(n){return console.error("WarpContractLoader: getContract error",n),null}}async getVerificationInfo(e){try{let a=await this.getConfiguredChainApi().doGetGeneric(`accounts/${e}/verification`);return{codeHash:a.codeHash,abi:a.source.abi}}catch(n){return console.error("WarpContractLoader: getVerificationInfo error",n),null}}getConfiguredChainApi(){if(!this.config.chainApiUrl)throw new Error("WarpContract: Chain API URL not set");return new gr(this.config.chainApiUrl,{timeout:3e4})}};var Nt=class{constructor(e){if(!e.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=e,this.url=new URL(e.currentUrl),this.serializer=new Ae,this.contractLoader=new Ie(e)}createTransactionForExecute(e,n,a){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let s=St.newFromBech32(this.config.userAddress),d=St.newFromBech32(e.address),y=new Cr({chainID:ie(this.config.env)}),{args:A,value:B,transfers:I}=this.getTxComponentsFromInputs(e,n,a),x=A.map(b=>this.serializer.stringToTyped(b));return d.isContractAddress()?new wr({config:y}).createTransactionForExecute({sender:s,contract:d,function:e.func||"",gasLimit:BigInt(e.gasLimit),arguments:x,tokenTransfers:I,nativeTransferAmount:B}):new Br({config:y}).createTransactionForTransfer({sender:s,receiver:d,nativeAmount:B,tokenTransfers:I,data:x[0]?.hasExactClass(Tr.ClassName)?x[0].valueOf():void 0})}async executeQuery(e,n){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!e.func)throw new Error("WarpActionExecutor: Function not found");let a=new dr(this.config.chainApiUrl,{timeout:3e4}),s=new hr({networkProvider:a}),d=await this.getAbiForAction(e),{args:y}=this.getTxComponentsFromInputs(e,n,[]),A=y.map(oe=>this.serializer.stringToTyped(oe)),B=new yr({queryRunner:s,abi:d}),I=B.createQuery({contract:e.address,function:e.func,arguments:A}),x=await B.runQuery(I),b=new mr,X={returnCode:x.returnCode,returnMessage:x.returnMessage,getReturnDataParts:()=>x.returnDataParts.map(oe=>Buffer.from(oe))},ae=x.function,Y=d.getEndpoint(ae),Z=b.parseQueryResponse(X,Y).firstValue;if(!Z)throw new Error("WarpActionExecutor: Query result not found");return Z}async executeCollect(e,n,a){let s=new Headers;s.set("Content-Type","application/json"),s.set("Accept","application/json"),Object.entries(e.destination.headers).forEach(([d,y])=>{s.set(d,y)}),await fetch(e.destination.url,{method:e.destination.method,headers:s,body:JSON.stringify({inputs:n,meta:a})})}getTxComponentsFromInputs(e,n,a){let s=this.getResolvedInputs(e,n),d=this.getModifiedInputs(s),y=this.getPreparedArgs(e,d),A=d.find(X=>X.input.position==="value")?.value||null,B="value"in e?e.value:null,I=BigInt(A?.split(":")[1]||B||0),b=[...("transfers"in e?e.transfers:[])?.map(this.toTypedTransfer)||[],...a];return{args:y,value:I,transfers:b}}getModifiedInputs(e){return e.map((n,a)=>{if(n.input.modifier?.startsWith("scale:")){let[,s]=n.input.modifier.split(":");if(isNaN(Number(s))){let d=Number(e.find(B=>B.input.name===s)?.value?.split(":")[1]);if(!d)throw new Error(`WarpActionExecutor: Exponent value not found for input ${s}`);let y=n.value?.split(":")[1];if(!y)throw new Error("WarpActionExecutor: Scalable value not found");let A=Ne(y,+d);return{...n,value:`${n.input.type}:${A}`}}else{let d=n.value?.split(":")[1];if(!d)throw new Error("WarpActionExecutor: Scalable value not found");let y=Ne(d,+s);return{...n,value:`${n.input.type}:${y}`}}}else return n})}getResolvedInputs(e,n){let a=e.inputs||[],s=(d,y)=>d.source==="query"?this.serializer.nativeToString(d.type,this.url.searchParams.get(d.name)||""):n[y]||null;return a.map((d,y)=>({input:d,value:s(d,y)}))}getPreparedArgs(e,n){let a="args"in e?e.args:[];return n.forEach(({input:s,value:d})=>{if(!d||!s.position.startsWith("arg:"))return;let y=Number(s.position.split(":")[1])-1;a.splice(y,0,d)}),a}async getAbiForAction(e){if(e.abi)return await this.fetchAbi(e);let n=await this.contractLoader.getVerificationInfo(e.address);if(!n)throw new Error("WarpActionExecutor: Verification info not found");return bt.create(n.abi)}async fetchAbi(e){if(!e.abi)throw new Error("WarpActionExecutor: ABI not found");let a=await(await fetch(e.abi)).json();return bt.create(a)}toTypedTransfer(e){return new Ir({token:new Ar({identifier:e.token,nonce:BigInt(e.nonce||0)}),amount:BigInt(e.amount||0)})}};import{Address as Ut,ApiNetworkProvider as Vr,TransactionsFactoryConfig as Pr,TransferTransactionsFactory as Or}from"@multiversx/sdk-core";var pe={Warp:m=>`warp:${m}`,RegistryInfo:m=>`registry-info:${m}`,Brand:m=>`brand:${m}`},le=class{constructor(){this.cache=new Map}set(e,n,a){let s=Date.now()+a*1e3;this.cache.set(e,{value:n,expiresAt:s})}get(e){let n=this.cache.get(e);return n?Date.now()>n.expiresAt?(this.cache.delete(e),null):n.value:null}clear(){this.cache.clear()}};import Nr from"qr-code-styling";import{AbiRegistry as Rt,Address as $,AddressValue as Et,ApiNetworkProvider as Vt,BytesValue as q,QueryRunnerAdapter as vr,SmartContractQueriesController as xr,SmartContractTransactionsFactory as br,TransactionsFactoryConfig as Sr}from"@multiversx/sdk-core/out";var ze={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},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:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],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:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var Ce=class{constructor(e){this.cache=new le;this.config=e,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(e,n){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let a=n?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:$.newFromBech32(this.config.userAddress),contract:$.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:a,arguments:n?[q.fromHex(e),q.fromUTF8(n)]:[q.fromHex(e)]})}createWarpUnregisterTransaction(e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:$.newFromBech32(this.config.userAddress),contract:$.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[q.fromHex(e)]})}createWarpUpgradeTransaction(e,n){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:$.newFromBech32(this.config.userAddress),contract:$.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[q.fromUTF8(e),q.fromHex(n)]})}createWarpAliasSetTransaction(e,n){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:$.newFromBech32(this.config.userAddress),contract:$.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[q.fromHex(e),q.fromUTF8(n)]})}createBrandRegisterTransaction(e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:$.newFromBech32(this.config.userAddress),contract:$.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[q.fromHex(e)]})}createWarpPublishTransaction(e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:$.newFromBech32(this.config.userAddress),contract:$.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[q.fromHex(e)]})}createWarpBrandingTransaction(e,n){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:$.newFromBech32(this.config.userAddress),contract:$.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[q.fromHex(e),q.fromHex(n)]})}async getInfoByAlias(e,n){let a=pe.RegistryInfo(e);if(n){let b=this.cache.get(a);if(b)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${e}`),b}let s=this.getRegistryContractAddress(),d=this.getController(),y=d.createQuery({contract:s,function:"getInfoByAlias",arguments:[q.fromUTF8(e)]}),A=await d.runQuery(y),[B]=d.parseQueryResponse(A),I=B?ye(B):null,x=I?.brand?await this.fetchBrand(I.brand):null;return n&&n.ttl&&this.cache.set(a,{registryInfo:I,brand:x},n.ttl),{registryInfo:I,brand:x}}async getInfoByHash(e,n){let a=pe.RegistryInfo(e);if(n){let b=this.cache.get(a);if(b)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${e}`),b}let s=this.getRegistryContractAddress(),d=this.getController(),y=d.createQuery({contract:s,function:"getInfoByHash",arguments:[q.fromHex(e)]}),A=await d.runQuery(y),[B]=d.parseQueryResponse(A),I=B?ye(B):null,x=I?.brand?await this.fetchBrand(I.brand):null;return n&&n.ttl&&this.cache.set(a,{registryInfo:I,brand:x},n.ttl),{registryInfo:I,brand:x}}async getUserWarpRegistryInfos(e){let n=e||this.config.userAddress;if(!n)throw new Error("WarpRegistry: user address not set");let a=this.getRegistryContractAddress(),s=this.getController(),d=s.createQuery({contract:a,function:"getUserWarps",arguments:[new Et(new $(n))]}),y=await s.runQuery(d),[A]=s.parseQueryResponse(y);return A.map(ye)}async getUserBrands(e){let n=e||this.config.userAddress;if(!n)throw new Error("WarpRegistry: user address not set");let a=this.getRegistryContractAddress(),s=this.getController(),d=s.createQuery({contract:a,function:"getUserBrands",arguments:[new Et(new $(n))]}),y=await s.runQuery(d),[A]=s.parseQueryResponse(y),B=A.map(b=>b.toString("hex")),I={ttl:365*24*60*60};return(await Promise.all(B.map(b=>this.fetchBrand(b,I)))).filter(b=>b!==null)}async fetchBrand(e,n){let a=pe.Brand(e);if(n){let d=this.cache.get(a);if(d)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${e}`),d}let s=new Vt(this.config.chainApiUrl||U.Chain.ApiUrl(this.config.env));try{let d=await s.getTransaction(e),y=JSON.parse(d.data.toString());return y.meta={hash:d.hash,creator:d.sender.bech32(),createdAt:new Date(d.timestamp*1e3).toISOString()},n&&n.ttl&&this.cache.set(a,y,n.ttl),y}catch(d){return console.error("WarpRegistry: Error fetching brand from transaction hash",d),null}}getRegistryContractAddress(){return this.config.registryContract||U.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let e=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:e,function:"getConfig",arguments:[]}),s=await n.runQuery(a),[d]=n.parseQueryResponse(s),y=BigInt(d.toString());this.unitPrice=y}getFactory(){let e=new Sr({chainID:ie(this.config.env)}),n=Rt.create(ze);return new br({config:e,abi:n})}getController(){let e=this.config.chainApiUrl||U.Chain.ApiUrl(this.config.env),n=new Vt(e,{timeout:3e4}),a=new vr({networkProvider:n}),s=Rt.create(ze);return new xr({queryRunner:a,abi:s})}};var Be=class{constructor(e){this.config=e;this.config=e}isValid(e){return e.startsWith(G.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(e):!1}async detectFromHtml(e){if(!e.length)return{match:!1,results:[]};let s=[...e.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(I=>I[0]).filter(I=>this.isValid(I)).map(I=>this.detect(I)),y=(await Promise.all(s)).filter(I=>I.match),A=y.length>0,B=y.map(I=>({url:I.url,warp:I.warp}));return{match:A,results:B}}async detect(e){let n=e.startsWith(G.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(e):ue.getInfoFromPrefixedIdentifier(e);if(!n)return{match:!1,url:e,warp:null,registryInfo:null,brand:null};let{type:a,id:s}=n,d=new We(this.config),y=new Ce(this.config),A=null,B=null,I=null;if(a==="hash"){A=await d.createFromTransactionHash(s);try{let{registryInfo:x,brand:b}=await y.getInfoByHash(s);B=x,I=b}catch{}}else if(a==="alias"){let{registryInfo:x,brand:b}=await y.getInfoByAlias(s);B=x,I=b,x&&(A=await d.createFromTransactionHash(x.hash))}return A?{match:!0,url:e,warp:A,registryInfo:B,brand:I}:{match:!1,url:e,warp:null,registryInfo:null,brand:null}}build(e,n){let a=this.config.clientUrl||U.DefaultClientUrl(this.config.env),s=e===G.DefaultIdentifierType?encodeURIComponent(n):encodeURIComponent(e+G.IdentifierParamSeparator+n);return U.SuperClientUrls.includes(a)?`${a}/${s}`:`${a}?${G.IdentifierParamName}=${s}`}generateQrCode(e,n,a=512,s="white",d="black",y="#23F7DD"){let A=this.build(e,n);return new Nr({type:"svg",width:a,height:a,data:String(A),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:s},dotsOptions:{type:"extra-rounded",color:d},cornersSquareOptions:{type:"extra-rounded",color:d},cornersDotOptions:{type:"square",color:d},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(y)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(e){let n=new URL(e),a=U.SuperClientUrls.includes(n.origin),s=n.searchParams.get(G.IdentifierParamName),d=a&&!s?n.pathname.split("/")[1]:s;if(!d)return null;let y=decodeURIComponent(d);return ue.getInfoFromPrefixedIdentifier(y)}};var Rr="https://",Pt="query",Ot="env",ue=class m{static prepareVars(e,n){if(!e?.vars)return e;let a=JSON.stringify(e),s=(d,y)=>{a=a.replace(new RegExp(`{{${d.toUpperCase()}}}`,"g"),y.toString())};return Object.entries(e.vars).forEach(([d,y])=>{if(typeof y=="string"&&y.startsWith(`${Pt}:`)){if(!n.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let A=y.split(`${Pt}:`)[1],B=new URL(n.currentUrl).searchParams.get(A);B&&s(d,B)}else if(typeof y=="string"&&y.startsWith(`${Ot}:`)){let A=y.split(`${Ot}:`)[1],B=n.vars?.[A];B&&s(d,B)}else s(d,y)}),JSON.parse(a)}static getInfoFromPrefixedIdentifier(e){let n=decodeURIComponent(e),a=n.includes(G.IdentifierParamSeparator)?n:`${G.DefaultIdentifierType}${G.IdentifierParamSeparator}${n}`,[s,d]=a.split(G.IdentifierParamSeparator);return{type:s,id:d}}static getNextStepUrl(e,n){if(!e?.next)return null;if(e.next.startsWith(Rr))return e.next;{let a=new Be(n),s=m.getInfoFromPrefixedIdentifier(e.next);return s?a.build(s.type,s.id):null}}};import Er from"ajv";var ge=class{constructor(e){this.config=e;this.config=e}async validate(e){this.ensureMaxOneValuePosition(e),await this.ensureValidSchema(e)}ensureMaxOneValuePosition(e){if(e.actions.filter(a=>"position"in a?a.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(e){let n=this.config.warpSchemaUrl||U.LatestWarpSchemaUrl,s=await(await fetch(n)).json(),d=new Er,y=d.compile(s);if(!y(e))throw new Error(`WarpBuilder: schema validation failed: ${d.errorsText(y.errors)}`)}};var We=class{constructor(e){this.cache=new le;this.pendingWarp={protocol:me(U.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=e}createInscriptionTransaction(e){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let n=new Pr({chainID:ie(this.config.env)}),a=new Or({config:n}),s=JSON.stringify(e),d=a.createTransactionForTransfer({sender:Ut.newFromBech32(this.config.userAddress),receiver:Ut.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(s).valueOf()});return d.gasLimit=d.gasLimit+BigInt(2e6),d}async createFromRaw(e,n=!0){let a=JSON.parse(e);return n&&await new ge(this.config).validate(a),ue.prepareVars(a,this.config)}async createFromTransaction(e,n=!1){let a=await this.createFromRaw(e.data.toString(),n);return a.meta={hash:e.hash,creator:e.sender.bech32(),createdAt:new Date(e.timestamp*1e3).toISOString()},a}async createFromTransactionHash(e,n){let a=pe.Warp(e);if(n){let d=this.cache.get(a);if(d)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${e}`),d}let s=new Vr(this.config.chainApiUrl||U.Chain.ApiUrl(this.config.env));try{let d=await s.getTransaction(e),y=await this.createFromTransaction(d);return n&&n.ttl&&y&&this.cache.set(a,y,n.ttl),y}catch(d){return console.error("WarpBuilder: Error creating from transaction hash",d),null}}setName(e){return this.pendingWarp.name=e,this}setTitle(e){return this.pendingWarp.title=e,this}setDescription(e){return this.pendingWarp.description=e,this}setPreview(e){return this.pendingWarp.preview=e,this}setActions(e){return this.pendingWarp.actions=e,this}addAction(e){return this.pendingWarp.actions.push(e),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await new ge(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(e,n=100){return Je(e,n)}ensure(e,n){if(!e)throw new Error(`WarpBuilder: ${n}`)}};var Ft=class{constructor(e){this.config=e}async search(e){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let n=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:e})});if(!n.ok)throw new Error(`WarpIndex: search failed with status ${n.status}`);return(await n.json()).hits}catch(n){throw console.error("WarpIndex: Error searching for warps: ",n),n}}};export{Ke as BrandBuilder,U as Config,Nt as WarpActionExecutor,Ae as WarpArgSerializer,We as WarpBuilder,G as WarpConstants,Ie as WarpContractLoader,Ft as WarpIndex,Be as WarpLink,Ce as WarpRegistry,ue as WarpUtils,un as address,on as biguint,cn as boolean,gn as codemeta,en as composite,fn as esdt,ie as getChainId,me as getLatestProtocolIdentifier,pn as hex,Yr as list,dn as nothing,Xr as option,Kr as optional,Ne as shiftBigintBy,tn as string,Je as toPreviewText,ye as toTypedRegistryInfo,ln as token,nn as u16,sn as u32,an as u64,rn as u8,Zr as variadic};
|