@vleap/warps 0.12.0 → 0.13.1

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Transaction, TransactionOnNetwork } from '@multiversx/sdk-core';
2
- import { TypedValue, Type, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, TokenTransfer, Struct, CodeMetadataValue, NothingValue, Transaction as Transaction$1, Address } from '@multiversx/sdk-core/out';
2
+ import { TypedValue, Type, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, TokenTransfer, Struct, CodeMetadataValue, NothingValue, Transaction as Transaction$1, Address, ApiNetworkProvider } from '@multiversx/sdk-core/out';
3
3
  import QRCodeStyling from 'qr-code-styling';
4
4
 
5
5
  type ChainEnv = 'mainnet' | 'testnet' | 'devnet';
@@ -233,6 +233,8 @@ declare const WarpConstants: {
233
233
  IdentifierParamName: string;
234
234
  IdentifierParamSeparator: string;
235
235
  DefaultIdentifierType: string;
236
+ ArgParamsSeparator: string;
237
+ ArgCompositeSeparator: string;
236
238
  Egld: {
237
239
  Identifier: string;
238
240
  DisplayName: string;
@@ -242,6 +244,7 @@ declare const WarpConstants: {
242
244
 
243
245
  declare const getChainId: (env: ChainEnv) => string;
244
246
  declare const getLatestProtocolIdentifier: (name: string) => string;
247
+ declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
245
248
  declare const toTypedRegistryInfo: (registryInfo: any) => RegistryInfo;
246
249
  declare const shiftBigintBy: (value: bigint | string, decimals: number) => bigint;
247
250
  declare const toPreviewText: (text: string, maxChars?: number) => string;
@@ -271,17 +274,18 @@ declare class WarpActionExecutor {
271
274
  private serializer;
272
275
  private contractLoader;
273
276
  constructor(config: WarpConfig);
274
- createTransactionForExecute(action: WarpTransferAction | WarpContractAction, inputs: string[]): Transaction$1;
277
+ createTransactionForExecute(action: WarpTransferAction | WarpContractAction, inputs: string[]): Promise<Transaction$1>;
275
278
  executeQuery(action: WarpQueryAction, inputs: string[]): Promise<TypedValue>;
276
279
  executeCollect(action: WarpCollectAction, inputs: Record<string, any>, meta?: Record<string, any>): Promise<void>;
277
- getTxComponentsFromInputs(action: WarpTransferAction | WarpContractAction | WarpQueryAction, inputs: string[], sender?: Address): {
280
+ getTxComponentsFromInputs(action: WarpTransferAction | WarpContractAction | WarpQueryAction, inputs: string[], sender?: Address): Promise<{
278
281
  destination: Address;
279
282
  args: string[];
280
283
  value: bigint;
281
284
  transfers: TokenTransfer[];
282
- };
285
+ }>;
283
286
  private getModifiedInputs;
284
287
  private getResolvedInputs;
288
+ private preprocessInput;
285
289
  private getPreparedArgs;
286
290
  private getAbiForAction;
287
291
  private fetchAbi;
@@ -325,7 +329,6 @@ declare class WarpContractLoader {
325
329
  constructor(config: WarpConfig);
326
330
  getContract(address: string): Promise<WarpContract | null>;
327
331
  getVerificationInfo(address: string): Promise<WarpContractVerification | null>;
328
- private getConfiguredChainApi;
329
332
  }
330
333
 
331
334
  declare class WarpIndex {
@@ -396,6 +399,7 @@ declare class WarpUtils {
396
399
  id: string;
397
400
  } | null;
398
401
  static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
402
+ static getConfiguredChainApi(config: WarpConfig): ApiNetworkProvider;
399
403
  }
400
404
 
401
- export { type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, type ChainEnv, Config, type RegistryInfo, type TrustStatus, type Warp, type WarpAction, type WarpActionExecutionResult, WarpActionExecutor, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpArgSerializer, WarpBuilder, type WarpCacheConfig, type WarpCollectAction, type WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpIdType, WarpIndex, WarpLink, type WarpLinkAction, type WarpMeta, type WarpNativeValue, type WarpQueryAction, WarpRegistry, type WarpSearchHit, type WarpSearchResult, type WarpTransferAction, WarpUtils, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, esdt, getChainId, getLatestProtocolIdentifier, hex, list, nothing, option, optional, shiftBigintBy, string, toPreviewText, toTypedRegistryInfo, token, u16, u32, u64, u8, variadic };
405
+ export { type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, type ChainEnv, Config, type RegistryInfo, type TrustStatus, type Warp, type WarpAction, type WarpActionExecutionResult, WarpActionExecutor, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpArgSerializer, WarpBuilder, type WarpCacheConfig, type WarpCollectAction, type WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpIdType, WarpIndex, WarpLink, type WarpLinkAction, type WarpMeta, type WarpNativeValue, type WarpQueryAction, WarpRegistry, type WarpSearchHit, type WarpSearchResult, type WarpTransferAction, WarpUtils, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, esdt, getChainId, getLatestProtocolIdentifier, getWarpActionByIndex, hex, list, nothing, option, optional, shiftBigintBy, string, toPreviewText, toTypedRegistryInfo, token, u16, u32, u64, u8, variadic };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Transaction, TransactionOnNetwork } from '@multiversx/sdk-core';
2
- import { TypedValue, Type, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, TokenTransfer, Struct, CodeMetadataValue, NothingValue, Transaction as Transaction$1, Address } from '@multiversx/sdk-core/out';
2
+ import { TypedValue, Type, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, TokenTransfer, Struct, CodeMetadataValue, NothingValue, Transaction as Transaction$1, Address, ApiNetworkProvider } from '@multiversx/sdk-core/out';
3
3
  import QRCodeStyling from 'qr-code-styling';
4
4
 
5
5
  type ChainEnv = 'mainnet' | 'testnet' | 'devnet';
@@ -233,6 +233,8 @@ declare const WarpConstants: {
233
233
  IdentifierParamName: string;
234
234
  IdentifierParamSeparator: string;
235
235
  DefaultIdentifierType: string;
236
+ ArgParamsSeparator: string;
237
+ ArgCompositeSeparator: string;
236
238
  Egld: {
237
239
  Identifier: string;
238
240
  DisplayName: string;
@@ -242,6 +244,7 @@ declare const WarpConstants: {
242
244
 
243
245
  declare const getChainId: (env: ChainEnv) => string;
244
246
  declare const getLatestProtocolIdentifier: (name: string) => string;
247
+ declare const getWarpActionByIndex: (warp: Warp, index: number) => WarpAction;
245
248
  declare const toTypedRegistryInfo: (registryInfo: any) => RegistryInfo;
246
249
  declare const shiftBigintBy: (value: bigint | string, decimals: number) => bigint;
247
250
  declare const toPreviewText: (text: string, maxChars?: number) => string;
@@ -271,17 +274,18 @@ declare class WarpActionExecutor {
271
274
  private serializer;
272
275
  private contractLoader;
273
276
  constructor(config: WarpConfig);
274
- createTransactionForExecute(action: WarpTransferAction | WarpContractAction, inputs: string[]): Transaction$1;
277
+ createTransactionForExecute(action: WarpTransferAction | WarpContractAction, inputs: string[]): Promise<Transaction$1>;
275
278
  executeQuery(action: WarpQueryAction, inputs: string[]): Promise<TypedValue>;
276
279
  executeCollect(action: WarpCollectAction, inputs: Record<string, any>, meta?: Record<string, any>): Promise<void>;
277
- getTxComponentsFromInputs(action: WarpTransferAction | WarpContractAction | WarpQueryAction, inputs: string[], sender?: Address): {
280
+ getTxComponentsFromInputs(action: WarpTransferAction | WarpContractAction | WarpQueryAction, inputs: string[], sender?: Address): Promise<{
278
281
  destination: Address;
279
282
  args: string[];
280
283
  value: bigint;
281
284
  transfers: TokenTransfer[];
282
- };
285
+ }>;
283
286
  private getModifiedInputs;
284
287
  private getResolvedInputs;
288
+ private preprocessInput;
285
289
  private getPreparedArgs;
286
290
  private getAbiForAction;
287
291
  private fetchAbi;
@@ -325,7 +329,6 @@ declare class WarpContractLoader {
325
329
  constructor(config: WarpConfig);
326
330
  getContract(address: string): Promise<WarpContract | null>;
327
331
  getVerificationInfo(address: string): Promise<WarpContractVerification | null>;
328
- private getConfiguredChainApi;
329
332
  }
330
333
 
331
334
  declare class WarpIndex {
@@ -396,6 +399,7 @@ declare class WarpUtils {
396
399
  id: string;
397
400
  } | null;
398
401
  static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
402
+ static getConfiguredChainApi(config: WarpConfig): ApiNetworkProvider;
399
403
  }
400
404
 
401
- export { type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, type ChainEnv, Config, type RegistryInfo, type TrustStatus, type Warp, type WarpAction, type WarpActionExecutionResult, WarpActionExecutor, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpArgSerializer, WarpBuilder, type WarpCacheConfig, type WarpCollectAction, type WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpIdType, WarpIndex, WarpLink, type WarpLinkAction, type WarpMeta, type WarpNativeValue, type WarpQueryAction, WarpRegistry, type WarpSearchHit, type WarpSearchResult, type WarpTransferAction, WarpUtils, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, esdt, getChainId, getLatestProtocolIdentifier, hex, list, nothing, option, optional, shiftBigintBy, string, toPreviewText, toTypedRegistryInfo, token, u16, u32, u64, u8, variadic };
405
+ export { type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, type ChainEnv, Config, type RegistryInfo, type TrustStatus, type Warp, type WarpAction, type WarpActionExecutionResult, WarpActionExecutor, type WarpActionInput, type WarpActionInputModifier, type WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpArgSerializer, WarpBuilder, type WarpCacheConfig, type WarpCollectAction, type WarpConfig, WarpConstants, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpIdType, WarpIndex, WarpLink, type WarpLinkAction, type WarpMeta, type WarpNativeValue, type WarpQueryAction, WarpRegistry, type WarpSearchHit, type WarpSearchResult, type WarpTransferAction, WarpUtils, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, esdt, getChainId, getLatestProtocolIdentifier, getWarpActionByIndex, hex, list, nothing, option, optional, shiftBigintBy, string, toPreviewText, toTypedRegistryInfo, token, u16, u32, u64, u8, variadic };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var rt=Object.create;var $=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var ot=(a,t)=>{for(var e in t)$(a,e,{get:t[e],enumerable:!0})},z=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of it(t))!at.call(a,i)&&i!==e&&$(a,i,{get:()=>t[i],enumerable:!(r=nt(t,i))||r.enumerable});return a};var D=(a,t,e)=>(e=a!=null?rt(st(a)):{},z(t||!a||!a.__esModule?$(e,"default",{value:a,enumerable:!0}):e,a)),ct=a=>z($({},"__esModule",{value:!0}),a);var St={};ot(St,{BrandBuilder:()=>Q,Config:()=>m,WarpActionExecutor:()=>H,WarpArgSerializer:()=>S,WarpBuilder:()=>N,WarpConstants:()=>T,WarpContractLoader:()=>R,WarpIndex:()=>M,WarpLink:()=>U,WarpRegistry:()=>P,WarpUtils:()=>b,address:()=>Ct,biguint:()=>Tt,boolean:()=>Wt,codemeta:()=>Bt,composite:()=>gt,esdt:()=>bt,getChainId:()=>W,getLatestProtocolIdentifier:()=>x,hex:()=>At,list:()=>lt,nothing:()=>vt,option:()=>pt,optional:()=>ut,shiftBigintBy:()=>k,string:()=>ft,toPreviewText:()=>_,toTypedRegistryInfo:()=>V,token:()=>It,u16:()=>ht,u32:()=>yt,u64:()=>wt,u8:()=>mt,variadic:()=>dt});module.exports=ct(St);var C=require("@multiversx/sdk-core"),G=D(require("ajv"));var m={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.5.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.5.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 W=a=>a==="devnet"?"D":a==="testnet"?"T":"1",x=a=>`${a}:${m.LatestProtocolVersion}`,V=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}),k=(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 p=o.slice(0,-s)||"0";return BigInt(p)}else return BigInt(a)},_=(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 Q=class{constructor(t){this.pendingBrand={protocol:x(m.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new C.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new C.TransferTransactionsFactory({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:C.Address.newFromBech32(this.config.userAddress),receiver:C.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 C.ApiNetworkProvider(this.config.chainApiUrl||m.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||m.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new G.default,o=s.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};var T={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var c=require("@multiversx/sdk-core/out"),pt=(a,t)=>a?c.OptionValue.newProvided(a):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),ut=(a,t)=>a?new c.OptionalValue(a.getType(),a):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),lt=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)},dt=a=>c.VariadicValue.fromItems(...a),gt=a=>{let t=a.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),a)},ft=a=>c.StringValue.fromUTF8(a),mt=a=>new c.U8Value(a),ht=a=>new c.U16Value(a),yt=a=>new c.U32Value(a),wt=a=>new c.U64Value(a),Tt=a=>new c.BigUIntValue(BigInt(a)),Wt=a=>new c.BooleanValue(a),Ct=a=>new c.AddressValue(c.Address.newFromBech32(a)),It=a=>new c.TokenIdentifierValue(a),At=a=>c.BytesValue.fromHex(a),bt=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"))),vt=()=>new c.NothingValue;var f=require("@multiversx/sdk-core/out");var n=require("@multiversx/sdk-core/out"),y=":",I="|",J=new RegExp(`${y}(.*)`),S=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(p=>this.typedToString(p).split(y)[0]),i=e.map(p=>this.typedToString(p).split(y)[1]),s=r.join(I),o=i.join(I);return`composite(${s}):${o}`}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(n.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(n.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),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(I).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),p=s[s.length-1],l=(p?p.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),p=s[s.length-1],l=(p?p.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`variadic:${o}`,l]}else if(r.startsWith("composite")){let s=r.match(/\(([^)]+)\)/)?.[1]?.split(I),p=i.split(I).map((d,l)=>this.stringToNative(`${s[l]}:${d}`)[1]);return[r,p]}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,p]=i.split(I);return[r,new n.TokenTransfer({token:new n.Token({identifier:s,nonce:BigInt(o)}),amount:BigInt(p)})]}}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(J,2),p=s.split(",").map(d=>this.stringToTyped(`${i}:${d}`));return new n.List(this.nativeToType(i),p)}if(e==="variadic"){let[i,s]=r.split(J,2),p=s.split(",").map(d=>this.stringToTyped(`${i}:${d}`));return new n.VariadicValue(new n.VariadicType(this.nativeToType(i)),p)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],s=r.split(I),o=i.split(I),p=s.map((l,g)=>this.stringToTyped(`${o[g]}:${l}`)),d=p.map(l=>l.getType());return new n.CompositeValue(new n.CompositeType(...d),p)}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(I);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 K=require("@multiversx/sdk-core/out"),R=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 K.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4})}};var H=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 S,this.contractLoader=new R(t)}createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=f.Address.newFromBech32(this.config.userAddress),i=new f.TransactionsFactoryConfig({chainID:W(this.config.env)}),{destination:s,args:o,value:p,transfers:d}=this.getTxComponentsFromInputs(t,e,r),l=o.map(g=>this.serializer.stringToTyped(g));return s.isContractAddress()?new f.SmartContractTransactionsFactory({config:i}).createTransactionForExecute({sender:r,contract:s,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:l,tokenTransfers:d,nativeTransferAmount:p}):new f.TransferTransactionsFactory({config:i}).createTransactionForTransfer({sender:r,receiver:s,nativeAmount:p,tokenTransfers:d,data:l[0]?.hasExactClass(f.StringValue.ClassName)?l[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),p=o.map(w=>this.serializer.stringToTyped(w)),d=new f.SmartContractQueriesController({queryRunner:i,abi:s}),l=d.createQuery({contract:t.address,function:t.func,arguments:p}),g=await d.runQuery(l),h=new f.ResultsParser,O={returnCode:g.returnCode,returnMessage:g.returnMessage,getReturnDataParts:()=>g.returnDataParts.map(w=>Buffer.from(w))},L=g.function,q=s.getEndpoint(L),E=h.parseQueryResponse(O,q).firstValue;if(!E)throw new Error("WarpActionExecutor: Query result not found");return E}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=s.find(w=>w.input.position==="receiver")?.value,p="address"in t?t.address:null,d=o?.split(":")[1]||p||r?.toBech32();if(!d)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=f.Address.newFromBech32(d),g=this.getPreparedArgs(t,s),h=s.find(w=>w.input.position==="value")?.value||null,O="value"in t?t.value:null,L=BigInt(h?.split(":")[1]||O||0),q=s.filter(w=>w.input.position==="transfer"&&w.value).map(w=>w.value),E=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...q?.map(w=>this.serializer.stringToNative(w)[1])||[]];return{destination:l,args:g,value:L,transfers:E}}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 p=k(o,+s);return{...e,value:`${e.input.type}:${p}`}}else{let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=k(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 A=require("@multiversx/sdk-core");var v={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},B=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 Z=D(require("qr-code-styling"));var u=require("@multiversx/sdk-core/out");var j={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 P=class{constructor(t){this.cache=new B;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:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[u.BytesValue.fromHex(t),u.BytesValue.fromUTF8(e)]:[u.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[u.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:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[u.BytesValue.fromUTF8(t),u.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[u.BytesValue.fromHex(t),u.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:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[u.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[u.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[u.BytesValue.fromHex(t),u.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=v.RegistryInfo(t);if(e){let h=this.cache.get(r);if(h)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),h}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[u.BytesValue.fromUTF8(t)]}),p=await s.runQuery(o),[d]=s.parseQueryResponse(p),l=d?V(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=v.RegistryInfo(t);if(e){let h=this.cache.get(r);if(h)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),h}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByHash",arguments:[u.BytesValue.fromHex(t)]}),p=await s.runQuery(o),[d]=s.parseQueryResponse(p),l=d?V(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 u.AddressValue(new u.Address(e))]}),o=await i.runQuery(s),[p]=i.parseQueryResponse(o);return p.map(V)}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 u.AddressValue(new u.Address(e))]}),o=await i.runQuery(s),[p]=i.parseQueryResponse(o),d=p.map(h=>h.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(d.map(h=>this.fetchBrand(h,l)))).filter(h=>h!==null)}async fetchBrand(t,e){let r=v.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 u.ApiNetworkProvider(this.config.chainApiUrl||m.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||m.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 u.TransactionsFactoryConfig({chainID:W(this.config.env)}),e=u.AbiRegistry.create(j);return new u.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||m.Chain.ApiUrl(this.config.env),e=new u.ApiNetworkProvider(t,{timeout:3e4}),r=new u.QueryRunnerAdapter({networkProvider:e}),i=u.AbiRegistry.create(j);return new u.SmartContractQueriesController({queryRunner:r,abi:i})}};var U=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(T.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),p=o.length>0,d=o.map(l=>({url:l.url,warp:l.warp}));return{match:p,results:d}}async detect(t){let e=t.startsWith(T.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 N(this.config),o=new P(this.config),p=null,d=null,l=null;if(r==="hash"){p=await s.createFromTransactionHash(i);try{let{registryInfo:g,brand:h}=await o.getInfoByHash(i);d=g,l=h}catch{}}else if(r==="alias"){let{registryInfo:g,brand:h}=await o.getInfoByAlias(i);d=g,l=h,g&&(p=await s.createFromTransactionHash(g.hash))}return p?{match:!0,url:t,warp:p,registryInfo:d,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||m.DefaultClientUrl(this.config.env),i=t===T.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+T.IdentifierParamSeparator+e);return m.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${T.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",s="black",o="#23F7DD"){let p=this.build(t,e);return new Z.default({type:"svg",width:r,height:r,data:String(p),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=m.SuperClientUrls.includes(e.origin),i=e.searchParams.get(T.IdentifierParamName),s=r&&!i?e.pathname.split("/")[1]:i;if(!s)return null;let o=decodeURIComponent(s);return b.getInfoFromPrefixedIdentifier(o)}};var Vt="https://",X="query",Y="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(`${X}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=o.split(`${X}:`)[1],d=new URL(e.currentUrl).searchParams.get(p);d&&i(s,d)}else if(typeof o=="string"&&o.startsWith(`${Y}:`)){let p=o.split(`${Y}:`)[1],d=e.vars?.[p];d&&i(s,d)}else i(s,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(T.IdentifierParamSeparator)?e:`${T.DefaultIdentifierType}${T.IdentifierParamSeparator}${e}`,[i,s]=r.split(T.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 U(e),i=a.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}};var tt=D(require("ajv"));var F=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||m.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new tt.default,o=s.compile(i);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};var N=class{constructor(t){this.cache=new B;this.pendingWarp={protocol:x(m.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 A.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new A.TransferTransactionsFactory({config:e}),i=JSON.stringify(t),s=r.createTransactionForTransfer({sender:A.Address.newFromBech32(this.config.userAddress),receiver:A.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 new F(this.config).validate(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=v.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 A.ApiNetworkProvider(this.config.chainApiUrl||m.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 new F(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return _(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var M=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 et=Object.create;var k=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var at=(a,t)=>{for(var e in t)k(a,e,{get:t[e],enumerable:!0})},j=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of nt(t))!st.call(a,i)&&i!==e&&k(a,i,{get:()=>t[i],enumerable:!(r=rt(t,i))||r.enumerable});return a};var L=(a,t,e)=>(e=a!=null?et(it(a)):{},j(t||!a||!a.__esModule?k(e,"default",{value:a,enumerable:!0}):e,a)),ot=a=>j(k({},"__esModule",{value:!0}),a);var Pt={};at(Pt,{BrandBuilder:()=>_,Config:()=>y,WarpActionExecutor:()=>Q,WarpArgSerializer:()=>U,WarpBuilder:()=>V,WarpConstants:()=>g,WarpContractLoader:()=>F,WarpIndex:()=>H,WarpLink:()=>R,WarpRegistry:()=>P,WarpUtils:()=>w,address:()=>It,biguint:()=>Ct,boolean:()=>At,codemeta:()=>xt,composite:()=>mt,esdt:()=>vt,getChainId:()=>W,getLatestProtocolIdentifier:()=>B,getWarpActionByIndex:()=>ct,hex:()=>Bt,list:()=>gt,nothing:()=>St,option:()=>lt,optional:()=>dt,shiftBigintBy:()=>x,string:()=>ht,toPreviewText:()=>q,toTypedRegistryInfo:()=>v,token:()=>bt,u16:()=>wt,u32:()=>Tt,u64:()=>Wt,u8:()=>yt,variadic:()=>ft});module.exports=ot(Pt);var A=require("@multiversx/sdk-core"),Z=L(require("ajv"));var y={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.5.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.5.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 W=a=>a==="devnet"?"D":a==="testnet"?"T":"1",B=a=>`${a}:${y.LatestProtocolVersion}`,ct=(a,t)=>a?.actions[t-1],v=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}),x=(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 p=o.slice(0,-s)||"0";return BigInt(p)}else return BigInt(a)},q=(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 J=require("@multiversx/sdk-core/out");var g={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var z=L(require("qr-code-styling"));var C=require("@multiversx/sdk-core");var b={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},I=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 M=L(require("ajv"));var S=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||y.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new M.default,o=s.compile(i);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};var V=class{constructor(t){this.cache=new I;this.pendingWarp={protocol:B(y.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 C.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new C.TransferTransactionsFactory({config:e}),i=JSON.stringify(t),s=r.createTransactionForTransfer({sender:C.Address.newFromBech32(this.config.userAddress),receiver:C.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 new S(this.config).validate(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=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=w.getConfiguredChainApi(this.config);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 new S(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return q(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var d=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 P=class{constructor(t){this.cache=new I;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:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[d.BytesValue.fromHex(t),d.BytesValue.fromUTF8(e)]:[d.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[d.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:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromUTF8(t),d.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t),d.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:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t),d.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=b.RegistryInfo(t);if(e){let h=this.cache.get(r);if(h)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),h}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[d.BytesValue.fromUTF8(t)]}),p=await s.runQuery(o),[u]=s.parseQueryResponse(p),l=u?v(u):null,f=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:f},e.ttl),{registryInfo:l,brand:f}}async getInfoByHash(t,e){let r=b.RegistryInfo(t);if(e){let h=this.cache.get(r);if(h)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),h}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByHash",arguments:[d.BytesValue.fromHex(t)]}),p=await s.runQuery(o),[u]=s.parseQueryResponse(p),l=u?v(u):null,f=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:f},e.ttl),{registryInfo:l,brand:f}}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 d.AddressValue(new d.Address(e))]}),o=await i.runQuery(s),[p]=i.parseQueryResponse(o);return p.map(v)}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 d.AddressValue(new d.Address(e))]}),o=await i.runQuery(s),[p]=i.parseQueryResponse(o),u=p.map(h=>h.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(u.map(h=>this.fetchBrand(h,l)))).filter(h=>h!==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=w.getConfiguredChainApi(this.config);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||y.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 d.TransactionsFactoryConfig({chainID:W(this.config.env)}),e=d.AbiRegistry.create(D);return new d.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=w.getConfiguredChainApi(this.config),e=new d.QueryRunnerAdapter({networkProvider:t}),r=d.AbiRegistry.create(D);return new d.SmartContractQueriesController({queryRunner:e,abi:r})}};var R=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(g.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),p=o.length>0,u=o.map(l=>({url:l.url,warp:l.warp}));return{match:p,results:u}}async detect(t){let e=t.startsWith(g.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):w.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,s=new V(this.config),o=new P(this.config),p=null,u=null,l=null;if(r==="hash"){p=await s.createFromTransactionHash(i);try{let{registryInfo:f,brand:h}=await o.getInfoByHash(i);u=f,l=h}catch{}}else if(r==="alias"){let{registryInfo:f,brand:h}=await o.getInfoByAlias(i);u=f,l=h,f&&(p=await s.createFromTransactionHash(f.hash))}return p?{match:!0,url:t,warp:p,registryInfo:u,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||y.DefaultClientUrl(this.config.env),i=t===g.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+g.IdentifierParamSeparator+e);return y.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${g.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",s="black",o="#23F7DD"){let p=this.build(t,e);return new z.default({type:"svg",width:r,height:r,data:String(p),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=y.SuperClientUrls.includes(e.origin),i=e.searchParams.get(g.IdentifierParamName),s=r&&!i?e.pathname.split("/")[1]:i;if(!s)return null;let o=decodeURIComponent(s);return w.getInfoFromPrefixedIdentifier(o)}};var ut="https://",G="query",K="env",w=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(`${G}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=o.split(`${G}:`)[1],u=new URL(e.currentUrl).searchParams.get(p);u&&i(s,u)}else if(typeof o=="string"&&o.startsWith(`${K}:`)){let p=o.split(`${K}:`)[1],u=e.vars?.[p];u&&i(s,u)}else i(s,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(g.IdentifierParamSeparator)?e:`${g.DefaultIdentifierType}${g.IdentifierParamSeparator}${e}`,[i,s]=r.split(g.IdentifierParamSeparator);return{type:i,id:s}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(ut))return t.next;{let r=new R(e),i=a.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}static getConfiguredChainApi(t){let e=t.chainApiUrl||y.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new J.ApiNetworkProvider(e,{timeout:3e4,clientName:"warp-sdk"})}};var _=class{constructor(t){this.pendingBrand={protocol:B(y.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new A.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new A.TransferTransactionsFactory({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:A.Address.newFromBech32(this.config.userAddress),receiver:A.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=w.getConfiguredChainApi(this.config);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||y.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new Z.default,o=s.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};var c=require("@multiversx/sdk-core/out"),lt=(a,t)=>a?c.OptionValue.newProvided(a):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),dt=(a,t)=>a?new c.OptionalValue(a.getType(),a):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),gt=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)},ft=a=>c.VariadicValue.fromItems(...a),mt=a=>{let t=a.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),a)},ht=a=>c.StringValue.fromUTF8(a),yt=a=>new c.U8Value(a),wt=a=>new c.U16Value(a),Tt=a=>new c.U32Value(a),Wt=a=>new c.U64Value(a),Ct=a=>new c.BigUIntValue(BigInt(a)),At=a=>new c.BooleanValue(a),It=a=>new c.AddressValue(c.Address.newFromBech32(a)),bt=a=>new c.TokenIdentifierValue(a),Bt=a=>c.BytesValue.fromHex(a),vt=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")]),xt=a=>new c.CodeMetadataValue(c.CodeMetadata.fromBuffer(Buffer.from(a,"hex"))),St=()=>new c.NothingValue;var m=require("@multiversx/sdk-core/out");var Vt=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],X=a=>Vt.find(t=>t.id===a)||null;var n=require("@multiversx/sdk-core/out");var Y=new RegExp(`${g.ArgParamsSeparator}(.*)`),U=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(g.ArgParamsSeparator)[0])[0],s=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[1]);return`list:${i}:${s.join(",")}`}if(t.hasClassOrSuperclass(n.VariadicValue.ClassName)){let e=t.getItems(),i=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[0])[0],s=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[1]);return`variadic:${i}:${s.join(",")}`}if(t.hasClassOrSuperclass(n.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(p=>this.typedToString(p).split(g.ArgParamsSeparator)[0]),i=e.map(p=>this.typedToString(p).split(g.ArgParamsSeparator)[1]),s=r.join(g.ArgCompositeSeparator),o=i.join(g.ArgCompositeSeparator);return`composite(${s}):${o}`}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(n.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(n.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),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(g.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new n.StringType;if(t==="uint8")return new n.U8Type;if(t==="uint16")return new n.U16Type;if(t==="uint32")return new n.U32Type;if(t==="uint64")return new n.U64Type;if(t==="biguint")return new n.BigUIntType;if(t==="bool")return new n.BooleanType;if(t==="address")return new n.AddressType;if(t==="token")return new n.TokenIdentifierType;if(t==="hex")return new n.BytesType;if(t==="codemeta")return new n.CodeMetadataType;if(t==="esdt"||t==="nft")return new n.StructType("EsdtTokenPayment",[new n.FieldDefinition("token_identifier","",new n.TokenIdentifierType),new n.FieldDefinition("token_nonce","",new n.U64Type),new n.FieldDefinition("amount","",new n.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(g.ArgParamsSeparator),r=e[0],i=e.slice(1).join(g.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[s,o]=i.split(g.ArgParamsSeparator);return[`option:${s}`,o||null]}else if(r==="optional"){let[s,o]=i.split(g.ArgParamsSeparator);return[`optional:${s}`,o||null]}else if(r==="list"){let s=i.split(g.ArgParamsSeparator),o=s.slice(0,-1).join(g.ArgParamsSeparator),p=s[s.length-1],l=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`list:${o}`,l]}else if(r==="variadic"){let s=i.split(g.ArgParamsSeparator),o=s.slice(0,-1).join(g.ArgParamsSeparator),p=s[s.length-1],l=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`variadic:${o}`,l]}else if(r.startsWith("composite")){let s=r.match(/\(([^)]+)\)/)?.[1]?.split(g.ArgCompositeSeparator),p=i.split(g.ArgCompositeSeparator).map((u,l)=>this.stringToNative(`${s[l]}:${u}`)[1]);return[r,p]}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,p]=i.split(g.ArgCompositeSeparator);return[r,new n.TokenTransfer({token:new n.Token({identifier:s,nonce:BigInt(o)}),amount:BigInt(p)})]}}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(Y,2),p=s.split(",").map(u=>this.stringToTyped(`${i}:${u}`));return new n.List(this.nativeToType(i),p)}if(e==="variadic"){let[i,s]=r.split(Y,2),p=s.split(",").map(u=>this.stringToTyped(`${i}:${u}`));return new n.VariadicValue(new n.VariadicType(this.nativeToType(i)),p)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],s=r.split(g.ArgCompositeSeparator),o=i.split(g.ArgCompositeSeparator),p=s.map((l,f)=>this.stringToTyped(`${o[f]}:${l}`)),u=p.map(l=>l.getType());return new n.CompositeValue(new n.CompositeType(...u),p)}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(g.ArgCompositeSeparator);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 F=class{constructor(t){this.config=t}async getContract(t){try{let r=await w.getConfiguredChainApi(this.config).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 w.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};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 U,this.contractLoader=new F(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=m.Address.newFromBech32(this.config.userAddress),i=new m.TransactionsFactoryConfig({chainID:W(this.config.env)}),{destination:s,args:o,value:p,transfers:u}=await this.getTxComponentsFromInputs(t,e,r),l=o.map(f=>this.serializer.stringToTyped(f));return s.isContractAddress()?new m.SmartContractTransactionsFactory({config:i}).createTransactionForExecute({sender:r,contract:s,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:l,tokenTransfers:u,nativeTransferAmount:p}):new m.TransferTransactionsFactory({config:i}).createTransactionForTransfer({sender:r,receiver:s,nativeAmount:p,tokenTransfers:u,data:l[0]?.hasExactClass(m.StringValue.ClassName)?l[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=w.getConfiguredChainApi(this.config),i=new m.QueryRunnerAdapter({networkProvider:r}),s=await this.getAbiForAction(t),{args:o}=await this.getTxComponentsFromInputs(t,e),p=o.map(T=>this.serializer.stringToTyped(T)),u=new m.SmartContractQueriesController({queryRunner:i,abi:s}),l=u.createQuery({contract:t.address,function:t.func,arguments:p}),f=await u.runQuery(l),h=new m.ResultsParser,E={returnCode:f.returnCode,returnMessage:f.returnMessage,getReturnDataParts:()=>f.returnDataParts.map(T=>Buffer.from(T))},$=f.function,O=s.getEndpoint($),N=h.parseQueryResponse(E,O).firstValue;if(!N)throw new Error("WarpActionExecutor: Query result not found");return N}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})})}async getTxComponentsFromInputs(t,e,r){let i=await this.getResolvedInputs(t,e),s=this.getModifiedInputs(i),o=s.find(T=>T.input.position==="receiver")?.value,p="address"in t?t.address:null,u=o?.split(":")[1]||p||r?.toBech32();if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=m.Address.newFromBech32(u),f=this.getPreparedArgs(t,s),h=s.find(T=>T.input.position==="value")?.value||null,E="value"in t?t.value:null,$=BigInt(h?.split(":")[1]||E||0),O=s.filter(T=>T.input.position==="transfer"&&T.value).map(T=>T.value),N=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...O?.map(T=>this.serializer.stringToNative(T)[1])||[]];return{destination:l,args:f,value:$,transfers:N}}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(u=>u.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 p=x(o,+s);return{...e,value:`${e.input.type}:${p}`}}else{let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=x(s,+i);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async getResolvedInputs(t,e){let r=t.inputs||[],i=await Promise.all(e.map(o=>this.preprocessInput(o))),s=(o,p)=>o.source==="query"?this.serializer.nativeToString(o.type,this.url.searchParams.get(o.name)||""):i[p]||null;return r.map((o,p)=>({input:o,value:s(o,p)}))}async preprocessInput(t){try{let[e,r]=this.serializer.stringToNative(t);if(e==="esdt"){let[,,,i]=t.split(g.ArgCompositeSeparator);if(i)return t;let s=r;if(!new m.TokenComputer().isFungible(s.token))return t;let u=X(s.token.identifier)?.decimals;if(!u){let f=this.config.chainApiUrl||y.Chain.ApiUrl(this.config.env);u=(await(await fetch(`${f}/tokens/${s.token.identifier}`)).json()).decimals}if(!u)throw new Error(`WarpActionExecutor: Decimals not found for token ${s.token.identifier}`);let l=new m.TokenTransfer({token:s.token,amount:x(s.amount,u)});return this.serializer.nativeToString(e,l)+g.ArgCompositeSeparator+u}return t}catch{return t}}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 m.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 m.AbiRegistry.create(r)}toTypedTransfer(t){return new m.TokenTransfer({token:new m.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var H=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,getWarpActionByIndex,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 Y,ApiNetworkProvider as Ot,TransactionsFactoryConfig as Lt,TransferTransactionsFactory as qt}from"@multiversx/sdk-core";import Dt from"ajv";var d={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.5.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.5.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 W=a=>a==="devnet"?"D":a==="testnet"?"T":"1",v=a=>`${a}:${d.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}),$=(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)},X=(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 tt=class{constructor(t){this.pendingBrand={protocol:v(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 Lt({chainID:W(this.config.env)}),r=new qt({config:e}),n=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:Y.newFromBech32(this.config.userAddress),receiver:Y.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 Ot(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 Dt,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var w={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import{Address as _t,AddressValue as Qt,BigUIntType as Ht,BigUIntValue as et,BooleanValue as jt,BytesValue as Mt,CodeMetadata as zt,CodeMetadataValue as Gt,CompositeType as Jt,CompositeValue as Kt,Field as k,FieldDefinition as O,List as Zt,NothingValue as Xt,OptionalValue as L,OptionValue as q,StringValue as Yt,Struct as te,StructType as ee,TokenIdentifierType as re,TokenIdentifierValue as rt,U16Value as ne,U32Value as ie,U64Type as se,U64Value as nt,U8Value as ae,VariadicValue as oe}from"@multiversx/sdk-core/out";var Ke=(a,t)=>a?q.newProvided(a):t?q.newMissingTyped(t):q.newMissing(),Ze=(a,t)=>a?new L(a.getType(),a):t?new L(t):L.newMissing(),Xe=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new Zt(t,a)},Ye=a=>oe.fromItems(...a),tr=a=>{let t=a.map(e=>e.getType());return new Kt(new Jt(...t),a)},er=a=>Yt.fromUTF8(a),rr=a=>new ae(a),nr=a=>new ne(a),ir=a=>new ie(a),sr=a=>new nt(a),ar=a=>new et(BigInt(a)),or=a=>new jt(a),cr=a=>new Qt(_t.newFromBech32(a)),pr=a=>new rt(a),ur=a=>Mt.fromHex(a),lr=a=>new te(new ee("EsdtTokenPayment",[new O("token_identifier","",new re),new O("token_nonce","",new se),new O("amount","",new Ht)]),[new k(new rt(a.token.identifier),"token_identifier"),new k(new nt(BigInt(a.token.nonce)),"token_nonce"),new k(new et(BigInt(a.amount)),"amount")]),dr=a=>new Gt(zt.fromBuffer(Buffer.from(a,"hex"))),gr=()=>new Xt;import{AbiRegistry as xt,Address as Vt,ApiNetworkProvider as fe,QueryRunnerAdapter as me,ResultsParser as he,SmartContractQueriesController as ye,SmartContractTransactionsFactory as we,StringValue as Te,Token as We,TokenTransfer as Ce,TransactionsFactoryConfig as Ie,TransferTransactionsFactory as Ae}from"@multiversx/sdk-core/out";import{Address as ce,AddressType as it,AddressValue as st,BigUIntType as D,BigUIntValue as _,BooleanType as at,BooleanValue as ot,BytesType as ct,BytesValue as pt,CodeMetadata as pe,CodeMetadataType as ut,CodeMetadataValue as lt,CompositeType as dt,CompositeValue as gt,Field as Q,FieldDefinition as H,List as ft,NothingValue as y,OptionalValue as j,OptionValue as M,StringType as mt,StringValue as ht,Struct as ue,StructType as yt,Token as le,TokenIdentifierType as z,TokenIdentifierValue as G,TokenTransfer as wt,U16Type as Tt,U16Value as Wt,U32Type as Ct,U32Value as It,U64Type as J,U64Value as K,U8Type as At,U8Value as bt,VariadicType as de,VariadicValue as Bt}from"@multiversx/sdk-core/out";var f=":",T="|",vt=new RegExp(`${f}(.*)`),V=class{nativeToString(t,e){return t==="esdt"&&e instanceof wt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(M.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(j.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(ft.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(Bt.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(gt.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(T),s=n.join(T);return`composite(${i}):${s}`}if(t.hasClassOrSuperclass(_.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(bt.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Wt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(It.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(K.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(ht.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(ot.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(st.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(G.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(pt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(lt.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 dt(...e.split(T).map(r=>this.nativeToType(r)))}if(t==="string")return new mt;if(t==="uint8")return new At;if(t==="uint16")return new Tt;if(t==="uint32")return new Ct;if(t==="uint64")return new J;if(t==="biguint")return new D;if(t==="bool")return new at;if(t==="address")return new it;if(t==="token")return new z;if(t==="hex")return new ct;if(t==="codemeta")return new ut;if(t==="esdt"||t==="nft")return new yt("EsdtTokenPayment",[new H("token_identifier","",new z),new H("token_nonce","",new J),new H("amount","",new D)]);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(u=>this.stringToNative(`${s}:${u}`)[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(u=>this.stringToNative(`${s}:${u}`)[1]);return[`variadic:${s}`,c]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(T),o=n.split(T).map((p,c)=>this.stringToNative(`${i[c]}:${p}`)[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(T);return[r,new wt({token:new le({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 y;if(e==="option"){let n=this.stringToTyped(r);return n instanceof y?M.newMissingTyped(n.getType()):M.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof y?j.newMissing():new j(n.getType(),n)}if(e==="list"){let[n,i]=r.split(vt,2),o=i.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new ft(this.nativeToType(n),o)}if(e==="variadic"){let[n,i]=r.split(vt,2),o=i.split(",").map(p=>this.stringToTyped(`${n}:${p}`));return new Bt(new de(this.nativeToType(n)),o)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(T),s=n.split(T),o=i.map((c,u)=>this.stringToTyped(`${s[u]}:${c}`)),p=o.map(c=>c.getType());return new gt(new dt(...p),o)}if(e==="string")return r?ht.fromUTF8(r):new y;if(e==="uint8")return r?new bt(Number(r)):new y;if(e==="uint16")return r?new Wt(Number(r)):new y;if(e==="uint32")return r?new It(Number(r)):new y;if(e==="uint64")return r?new K(BigInt(r)):new y;if(e==="biguint")return r?new _(BigInt(r)):new y;if(e==="bool")return r?new ot(typeof r=="boolean"?r:r==="true"):new y;if(e==="address")return r?new st(ce.newFromBech32(r)):new y;if(e==="token")return r?new G(r):new y;if(e==="hex")return r?pt.fromHex(r):new y;if(e==="codemeta")return new lt(pe.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let n=r.split(T);return new ue(this.nativeToType("esdt"),[new Q(new G(n[0]),"token_identifier"),new Q(new K(BigInt(n[1])),"token_nonce"),new Q(new _(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof mt)return"string";if(t instanceof At)return"uint8";if(t instanceof Tt)return"uint16";if(t instanceof Ct)return"uint32";if(t instanceof J)return"uint64";if(t instanceof D)return"biguint";if(t instanceof at)return"bool";if(t instanceof it)return"address";if(t instanceof z)return"token";if(t instanceof ct)return"hex";if(t instanceof ut)return"codemeta";if(t instanceof yt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};import{ApiNetworkProvider as ge}from"@multiversx/sdk-core/out";var 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 ge(this.config.chainApiUrl,{timeout:3e4})}};var St=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){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=Vt.newFromBech32(this.config.userAddress),n=new Ie({chainID:W(this.config.env)}),{destination:i,args:s,value:o,transfers:p}=this.getTxComponentsFromInputs(t,e,r),c=s.map(u=>this.serializer.stringToTyped(u));return i.isContractAddress()?new we({config:n}).createTransactionForExecute({sender:r,contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:c,tokenTransfers:p,nativeTransferAmount:o}):new Ae({config:n}).createTransactionForTransfer({sender:r,receiver:i,nativeAmount:o,tokenTransfers:p,data:c[0]?.hasExactClass(Te.ClassName)?c[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 fe(this.config.chainApiUrl,{timeout:3e4}),n=new me({networkProvider:r}),i=await this.getAbiForAction(t),{args:s}=this.getTxComponentsFromInputs(t,e),o=s.map(m=>this.serializer.stringToTyped(m)),p=new ye({queryRunner:n,abi:i}),c=p.createQuery({contract:t.address,function:t.func,arguments:o}),u=await p.runQuery(c),l=new he,N={returnCode:u.returnCode,returnMessage:u.returnMessage,getReturnDataParts:()=>u.returnDataParts.map(m=>Buffer.from(m))},F=u.function,E=i.getEndpoint(F),B=l.parseQueryResponse(N,E).firstValue;if(!B)throw new Error("WarpActionExecutor: Query result not found");return B}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=i.find(m=>m.input.position==="receiver")?.value,o="address"in t?t.address:null,p=s?.split(":")[1]||o||r?.toBech32();if(!p)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let c=Vt.newFromBech32(p),u=this.getPreparedArgs(t,i),l=i.find(m=>m.input.position==="value")?.value||null,N="value"in t?t.value:null,F=BigInt(l?.split(":")[1]||N||0),E=i.filter(m=>m.input.position==="transfer"&&m.value).map(m=>m.value),B=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...E?.map(m=>this.serializer.stringToNative(m)[1])||[]];return{destination:c,args:u,value:F,transfers:B}}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(p=>p.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=$(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=$(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 xt.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 xt.create(r)}toTypedTransfer(t){return new Ce({token:new We({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Et,ApiNetworkProvider as Ue,TransactionsFactoryConfig as Ne,TransferTransactionsFactory as Fe}from"@multiversx/sdk-core";var A={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},I=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 Se from"qr-code-styling";import{AbiRegistry as Rt,Address as g,AddressValue as Pt,ApiNetworkProvider as Ut,BytesValue as h,QueryRunnerAdapter as Be,SmartContractQueriesController as ve,SmartContractTransactionsFactory as xe,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 R=class{constructor(t){this.cache=new I;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?[h.fromHex(t),h.fromUTF8(e)]:[h.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:[h.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:[h.fromUTF8(t),h.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:[h.fromHex(t),h.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:[h.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:[h.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:[h.fromHex(t),h.fromHex(e)]})}async getInfoByAlias(t,e){let r=A.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:[h.fromUTF8(t)]}),o=await i.runQuery(s),[p]=i.parseQueryResponse(o),c=p?x(p):null,u=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:u},e.ttl),{registryInfo:c,brand:u}}async getInfoByHash(t,e){let r=A.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:[h.fromHex(t)]}),o=await i.runQuery(s),[p]=i.parseQueryResponse(o),c=p?x(p):null,u=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:u},e.ttl),{registryInfo:c,brand:u}}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 Pt(new g(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s);return o.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(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new Pt(new g(e))]}),s=await n.runQuery(i),[o]=n.parseQueryResponse(s),p=o.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(p.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}async fetchBrand(t,e){let r=A.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 Ut(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:W(this.config.env)}),e=Rt.create(Z);return new xe({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env),e=new Ut(t,{timeout:3e4}),r=new Be({networkProvider:e}),n=Rt.create(Z);return new ve({queryRunner:r,abi:n})}};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 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,p=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t){let e=t.startsWith(w.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):C.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new U(this.config),s=new R(this.config),o=null,p=null,c=null;if(r==="hash"){o=await i.createFromTransactionHash(n);try{let{registryInfo:u,brand:l}=await s.getInfoByHash(n);p=u,c=l}catch{}}else if(r==="alias"){let{registryInfo:u,brand:l}=await s.getInfoByAlias(n);p=u,c=l,u&&(o=await i.createFromTransactionHash(u.hash))}return o?{match:!0,url:t,warp:o,registryInfo:p,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===w.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+w.IdentifierParamSeparator+e);return d.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${w.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",s="#23F7DD"){let o=this.build(t,e);return new Se({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(w.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let s=decodeURIComponent(i);return C.getInfoFromPrefixedIdentifier(s)}};var Re="https://",Nt="query",Ft="env",C=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(`${Nt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${Nt}:`)[1],p=new URL(e.currentUrl).searchParams.get(o);p&&n(i,p)}else if(typeof s=="string"&&s.startsWith(`${Ft}:`)){let o=s.split(`${Ft}:`)[1],p=e.vars?.[o];p&&n(i,p)}else n(i,s)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(w.IdentifierParamSeparator)?e:`${w.DefaultIdentifierType}${w.IdentifierParamSeparator}${e}`,[n,i]=r.split(w.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(Re))return t.next;{let r=new P(e),n=a.getInfoFromPrefixedIdentifier(t.next);return n?r.build(n.type,n.id):null}}};import Pe from"ajv";var b=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||d.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new Pe,s=i.compile(n);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};var U=class{constructor(t){this.cache=new I;this.pendingWarp={protocol:v(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 Ne({chainID:W(this.config.env)}),r=new Fe({config:e}),n=JSON.stringify(t),i=r.createTransactionForTransfer({sender:Et.newFromBech32(this.config.userAddress),receiver:Et.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 new b(this.config).validate(r),C.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=A.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 Ue(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 new b(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return X(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var $t=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{tt as BrandBuilder,d as Config,St as WarpActionExecutor,V as WarpArgSerializer,U as WarpBuilder,w as WarpConstants,S as WarpContractLoader,$t as WarpIndex,P as WarpLink,R as WarpRegistry,C as WarpUtils,cr as address,ar as biguint,or as boolean,dr as codemeta,tr as composite,lr as esdt,W as getChainId,v as getLatestProtocolIdentifier,ur as hex,Xe as list,gr as nothing,Ke as option,Ze as optional,$ as shiftBigintBy,er as string,X as toPreviewText,x as toTypedRegistryInfo,pr as token,nr as u16,ir as u32,sr as u64,rr as u8,Ye as variadic};
1
+ import{Address as rt,TransactionsFactoryConfig as Gt,TransferTransactionsFactory as Kt}from"@multiversx/sdk-core";import Jt from"ajv";var g={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.5.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.5.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}:${g.LatestProtocolVersion}`,Ee=(a,t)=>a?.actions[t-1],v=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}),x=(a,t)=>{let e=a.toString(),[r,i=""]=e.split("."),n=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(n,"0"));if(t<0){let s=r+i;if(n>=s.length)return 0n;let o=s.slice(0,-n)||"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};import{ApiNetworkProvider as Mt}from"@multiversx/sdk-core/out";var u={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import jt from"qr-code-styling";import{Address as Z,TransactionsFactoryConfig as Ot,TransferTransactionsFactory as Lt}from"@multiversx/sdk-core";var C={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},W=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()}};import $t from"ajv";var A=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||g.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),n=new $t,s=n.compile(i);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};var S=class{constructor(t){this.cache=new W;this.pendingWarp={protocol:B(g.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 Ot({chainID:T(this.config.env)}),r=new Lt({config:e}),i=JSON.stringify(t),n=r.createTransactionForTransfer({sender:Z.newFromBech32(this.config.userAddress),receiver:Z.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return n.gasLimit=n.gasLimit+BigInt(2e6),n}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new A(this.config).validate(r),f.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=C.Warp(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),n}let i=f.getConfiguredChainApi(this.config);try{let n=await i.getTransaction(t),s=await this.createFromTransaction(n);return e&&e.ttl&&s&&this.cache.set(r,s,e.ttl),s}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),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 new A(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return J(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};import{AbiRegistry as X,Address as m,AddressValue as Y,BytesValue as y,QueryRunnerAdapter as Dt,SmartContractQueriesController as _t,SmartContractTransactionsFactory as Qt,TransactionsFactoryConfig as Ht}from"@multiversx/sdk-core/out";var N={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 V=class{constructor(t){this.cache=new W;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:m.newFromBech32(this.config.userAddress),contract:m.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[y.fromHex(t),y.fromUTF8(e)]:[y.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:m.newFromBech32(this.config.userAddress),contract:m.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[y.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:m.newFromBech32(this.config.userAddress),contract:m.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromUTF8(t),y.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:m.newFromBech32(this.config.userAddress),contract:m.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.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:m.newFromBech32(this.config.userAddress),contract:m.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:m.newFromBech32(this.config.userAddress),contract:m.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:m.newFromBech32(this.config.userAddress),contract:m.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromHex(e)]})}async getInfoByAlias(t,e){let r=C.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),d}let i=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[y.fromUTF8(t)]}),o=await n.runQuery(s),[c]=n.parseQueryResponse(o),p=c?v(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}async getInfoByHash(t,e){let r=C.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let i=this.getRegistryContractAddress(),n=this.getController(),s=n.createQuery({contract:i,function:"getInfoByHash",arguments:[y.fromHex(t)]}),o=await n.runQuery(s),[c]=n.parseQueryResponse(o),p=c?v(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}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(),n=i.createQuery({contract:r,function:"getUserWarps",arguments:[new Y(new m(e))]}),s=await i.runQuery(n),[o]=i.parseQueryResponse(s);return o.map(v)}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(),n=i.createQuery({contract:r,function:"getUserBrands",arguments:[new Y(new m(e))]}),s=await i.runQuery(n),[o]=i.parseQueryResponse(s),c=o.map(d=>d.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(d=>this.fetchBrand(d,p)))).filter(d=>d!==null)}async fetchBrand(t,e){let r=C.Brand(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n}let i=f.getConfiguredChainApi(this.config);try{let n=await i.getTransaction(t),s=JSON.parse(n.data.toString());return s.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,s,e.ttl),s}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}getRegistryContractAddress(){return this.config.registryContract||g.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),[n]=e.parseQueryResponse(i),s=BigInt(n.toString());this.unitPrice=s}getFactory(){let t=new Ht({chainID:T(this.config.env)}),e=X.create(N);return new Qt({config:t,abi:e})}getController(){let t=f.getConfiguredChainApi(this.config),e=new Dt({networkProvider:t}),r=X.create(N);return new _t({queryRunner:e,abi:r})}};var P=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),s=(await Promise.all(i)).filter(p=>p.match),o=s.length>0,c=s.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t){let e=t.startsWith(u.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):f.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,n=new S(this.config),s=new V(this.config),o=null,c=null,p=null;if(r==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:l,brand:d}=await s.getInfoByHash(i);c=l,p=d}catch{}}else if(r==="alias"){let{registryInfo:l,brand:d}=await s.getInfoByAlias(i);c=l,p=d,l&&(o=await n.createFromTransactionHash(l.hash))}return o?{match:!0,url:t,warp:o,registryInfo:c,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||g.DefaultClientUrl(this.config.env),i=t===u.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+u.IdentifierParamSeparator+e);return g.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${u.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",n="black",s="#23F7DD"){let o=this.build(t,e);return new jt({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},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=g.SuperClientUrls.includes(e.origin),i=e.searchParams.get(u.IdentifierParamName),n=r&&!i?e.pathname.split("/")[1]:i;if(!n)return null;let s=decodeURIComponent(n);return f.getInfoFromPrefixedIdentifier(s)}};var zt="https://",tt="query",et="env",f=class a{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),i=(n,s)=>{r=r.replace(new RegExp(`{{${n.toUpperCase()}}}`,"g"),s.toString())};return Object.entries(t.vars).forEach(([n,s])=>{if(typeof s=="string"&&s.startsWith(`${tt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${tt}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&i(n,c)}else if(typeof s=="string"&&s.startsWith(`${et}:`)){let o=s.split(`${et}:`)[1],c=e.vars?.[o];c&&i(n,c)}else i(n,s)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(u.IdentifierParamSeparator)?e:`${u.DefaultIdentifierType}${u.IdentifierParamSeparator}${e}`,[i,n]=r.split(u.IdentifierParamSeparator);return{type:i,id:n}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(zt))return t.next;{let r=new P(e),i=a.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}static getConfiguredChainApi(t){let e=t.chainApiUrl||g.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new Mt(e,{timeout:3e4,clientName:"warp-sdk"})}};var nt=class{constructor(t){this.pendingBrand={protocol:B(g.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new Gt({chainID:T(this.config.env)}),r=new Kt({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:rt.newFromBech32(this.config.userAddress),receiver:rt.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=f.getConfiguredChainApi(this.config);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||g.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),n=new Jt,s=n.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import{Address as Zt,AddressValue as Xt,BigUIntType as Yt,BigUIntValue as it,BooleanValue as te,BytesValue as ee,CodeMetadata as re,CodeMetadataValue as ne,CompositeType as ie,CompositeValue as se,Field as k,FieldDefinition as $,List as ae,NothingValue as oe,OptionalValue as O,OptionValue as L,StringValue as ce,Struct as pe,StructType as ue,TokenIdentifierType as le,TokenIdentifierValue as st,U16Value as de,U32Value as ge,U64Type as fe,U64Value as at,U8Value as me,VariadicValue as he}from"@multiversx/sdk-core/out";var Vr=(a,t)=>a?L.newProvided(a):t?L.newMissingTyped(t):L.newMissing(),Pr=(a,t)=>a?new O(a.getType(),a):t?new O(t):O.newMissing(),Rr=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new ae(t,a)},Ur=a=>he.fromItems(...a),Fr=a=>{let t=a.map(e=>e.getType());return new se(new ie(...t),a)},Er=a=>ce.fromUTF8(a),Nr=a=>new me(a),kr=a=>new de(a),$r=a=>new ge(a),Or=a=>new at(a),Lr=a=>new it(BigInt(a)),qr=a=>new te(a),Dr=a=>new Xt(Zt.newFromBech32(a)),_r=a=>new st(a),Qr=a=>ee.fromHex(a),Hr=a=>new pe(new ue("EsdtTokenPayment",[new $("token_identifier","",new le),new $("token_nonce","",new fe),new $("amount","",new Yt)]),[new k(new st(a.token.identifier),"token_identifier"),new k(new at(BigInt(a.token.nonce)),"token_nonce"),new k(new it(BigInt(a.amount)),"amount")]),jr=a=>new ne(re.fromBuffer(Buffer.from(a,"hex"))),Mr=()=>new oe;import{AbiRegistry as Rt,Address as Ut,QueryRunnerAdapter as Ie,ResultsParser as be,SmartContractQueriesController as Be,SmartContractTransactionsFactory as ve,StringValue as xe,Token as Se,TokenComputer as Ve,TokenTransfer as Ft,TransactionsFactoryConfig as Pe,TransferTransactionsFactory as Re}from"@multiversx/sdk-core/out";var ye=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],ot=a=>ye.find(t=>t.id===a)||null;import{Address as we,AddressType as ct,AddressValue as pt,BigUIntType as q,BigUIntValue as D,BooleanType as ut,BooleanValue as lt,BytesType as dt,BytesValue as gt,CodeMetadata as Te,CodeMetadataType as ft,CodeMetadataValue as mt,CompositeType as ht,CompositeValue as yt,Field as _,FieldDefinition as Q,List as wt,NothingValue as w,OptionalValue as H,OptionValue as j,StringType as Tt,StringValue as Wt,Struct as We,StructType as Ct,Token as Ce,TokenIdentifierType as M,TokenIdentifierValue as z,TokenTransfer as At,U16Type as It,U16Value as bt,U32Type as Bt,U32Value as vt,U64Type as G,U64Value as K,U8Type as xt,U8Value as St,VariadicType as Ae,VariadicValue as Vt}from"@multiversx/sdk-core/out";var Pt=new RegExp(`${u.ArgParamsSeparator}(.*)`),R=class{nativeToString(t,e){return t==="esdt"&&e instanceof At?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(j.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(H.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(wt.ClassName)){let e=t.getItems(),i=e.map(s=>this.typedToString(s).split(u.ArgParamsSeparator)[0])[0],n=e.map(s=>this.typedToString(s).split(u.ArgParamsSeparator)[1]);return`list:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(Vt.ClassName)){let e=t.getItems(),i=e.map(s=>this.typedToString(s).split(u.ArgParamsSeparator)[0])[0],n=e.map(s=>this.typedToString(s).split(u.ArgParamsSeparator)[1]);return`variadic:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(yt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[0]),i=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[1]),n=r.join(u.ArgCompositeSeparator),s=i.join(u.ArgCompositeSeparator);return`composite(${n}):${s}`}if(t.hasClassOrSuperclass(D.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(St.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(bt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(vt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(K.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Wt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(lt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(pt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(z.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(gt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(mt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),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 ht(...e.split(u.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new Tt;if(t==="uint8")return new xt;if(t==="uint16")return new It;if(t==="uint32")return new Bt;if(t==="uint64")return new G;if(t==="biguint")return new q;if(t==="bool")return new ut;if(t==="address")return new ct;if(t==="token")return new M;if(t==="hex")return new dt;if(t==="codemeta")return new ft;if(t==="esdt"||t==="nft")return new Ct("EsdtTokenPayment",[new Q("token_identifier","",new M),new Q("token_nonce","",new G),new Q("amount","",new q)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(u.ArgParamsSeparator),r=e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[n,s]=i.split(u.ArgParamsSeparator);return[`option:${n}`,s||null]}else if(r==="optional"){let[n,s]=i.split(u.ArgParamsSeparator);return[`optional:${n}`,s||null]}else if(r==="list"){let n=i.split(u.ArgParamsSeparator),s=n.slice(0,-1).join(u.ArgParamsSeparator),o=n[n.length-1],p=(o?o.split(","):[]).map(l=>this.stringToNative(`${s}:${l}`)[1]);return[`list:${s}`,p]}else if(r==="variadic"){let n=i.split(u.ArgParamsSeparator),s=n.slice(0,-1).join(u.ArgParamsSeparator),o=n[n.length-1],p=(o?o.split(","):[]).map(l=>this.stringToNative(`${s}:${l}`)[1]);return[`variadic:${s}`,p]}else if(r.startsWith("composite")){let n=r.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),o=i.split(u.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${n[p]}:${c}`)[1]);return[r,o]}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[n,s,o]=i.split(u.ArgCompositeSeparator);return[r,new At({token:new Ce({identifier:n,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 w;if(e==="option"){let i=this.stringToTyped(r);return i instanceof w?j.newMissingTyped(i.getType()):j.newProvided(i)}if(e==="optional"){let i=this.stringToTyped(r);return i instanceof w?H.newMissing():new H(i.getType(),i)}if(e==="list"){let[i,n]=r.split(Pt,2),o=n.split(",").map(c=>this.stringToTyped(`${i}:${c}`));return new wt(this.nativeToType(i),o)}if(e==="variadic"){let[i,n]=r.split(Pt,2),o=n.split(",").map(c=>this.stringToTyped(`${i}:${c}`));return new Vt(new Ae(this.nativeToType(i)),o)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],n=r.split(u.ArgCompositeSeparator),s=i.split(u.ArgCompositeSeparator),o=n.map((p,l)=>this.stringToTyped(`${s[l]}:${p}`)),c=o.map(p=>p.getType());return new yt(new ht(...c),o)}if(e==="string")return r?Wt.fromUTF8(r):new w;if(e==="uint8")return r?new St(Number(r)):new w;if(e==="uint16")return r?new bt(Number(r)):new w;if(e==="uint32")return r?new vt(Number(r)):new w;if(e==="uint64")return r?new K(BigInt(r)):new w;if(e==="biguint")return r?new D(BigInt(r)):new w;if(e==="bool")return r?new lt(typeof r=="boolean"?r:r==="true"):new w;if(e==="address")return r?new pt(we.newFromBech32(r)):new w;if(e==="token")return r?new z(r):new w;if(e==="hex")return r?gt.fromHex(r):new w;if(e==="codemeta")return new mt(Te.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let i=r.split(u.ArgCompositeSeparator);return new We(this.nativeToType("esdt"),[new _(new z(i[0]),"token_identifier"),new _(new K(BigInt(i[1])),"token_nonce"),new _(new D(BigInt(i[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof Tt)return"string";if(t instanceof xt)return"uint8";if(t instanceof It)return"uint16";if(t instanceof Bt)return"uint32";if(t instanceof G)return"uint64";if(t instanceof q)return"biguint";if(t instanceof ut)return"bool";if(t instanceof ct)return"address";if(t instanceof M)return"token";if(t instanceof dt)return"hex";if(t instanceof ft)return"codemeta";if(t instanceof Ct&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var U=class{constructor(t){this.config=t}async getContract(t){try{let r=await f.getConfiguredChainApi(this.config).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 f.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var Et=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 R,this.contractLoader=new U(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=Ut.newFromBech32(this.config.userAddress),i=new Pe({chainID:T(this.config.env)}),{destination:n,args:s,value:o,transfers:c}=await this.getTxComponentsFromInputs(t,e,r),p=s.map(l=>this.serializer.stringToTyped(l));return n.isContractAddress()?new ve({config:i}).createTransactionForExecute({sender:r,contract:n,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:p,tokenTransfers:c,nativeTransferAmount:o}):new Re({config:i}).createTransactionForTransfer({sender:r,receiver:n,nativeAmount:o,tokenTransfers:c,data:p[0]?.hasExactClass(xe.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=f.getConfiguredChainApi(this.config),i=new Ie({networkProvider:r}),n=await this.getAbiForAction(t),{args:s}=await this.getTxComponentsFromInputs(t,e),o=s.map(h=>this.serializer.stringToTyped(h)),c=new Be({queryRunner:i,abi:n}),p=c.createQuery({contract:t.address,function:t.func,arguments:o}),l=await c.runQuery(p),d=new be,I={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(h=>Buffer.from(h))},F=l.function,E=n.getEndpoint(F),b=d.parseQueryResponse(I,E).firstValue;if(!b)throw new Error("WarpActionExecutor: Query result not found");return b}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(([n,s])=>{i.set(n,s)}),await fetch(t.destination.url,{method:t.destination.method,headers:i,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let i=await this.getResolvedInputs(t,e),n=this.getModifiedInputs(i),s=n.find(h=>h.input.position==="receiver")?.value,o="address"in t?t.address:null,c=s?.split(":")[1]||o||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=Ut.newFromBech32(c),l=this.getPreparedArgs(t,n),d=n.find(h=>h.input.position==="value")?.value||null,I="value"in t?t.value:null,F=BigInt(d?.split(":")[1]||I||0),E=n.filter(h=>h.input.position==="transfer"&&h.value).map(h=>h.value),b=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...E?.map(h=>this.serializer.stringToNative(h)[1])||[]];return{destination:p,args:l,value:F,transfers:b}}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,i]=e.input.modifier.split(":");if(isNaN(Number(i))){let n=Number(t.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!n)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let s=e.value?.split(":")[1];if(!s)throw new Error("WarpActionExecutor: Scalable value not found");let o=x(s,+n);return{...e,value:`${e.input.type}:${o}`}}else{let n=e.value?.split(":")[1];if(!n)throw new Error("WarpActionExecutor: Scalable value not found");let s=x(n,+i);return{...e,value:`${e.input.type}:${s}`}}}else return e})}async getResolvedInputs(t,e){let r=t.inputs||[],i=await Promise.all(e.map(s=>this.preprocessInput(s))),n=(s,o)=>s.source==="query"?this.serializer.nativeToString(s.type,this.url.searchParams.get(s.name)||""):i[o]||null;return r.map((s,o)=>({input:s,value:n(s,o)}))}async preprocessInput(t){try{let[e,r]=this.serializer.stringToNative(t);if(e==="esdt"){let[,,,i]=t.split(u.ArgCompositeSeparator);if(i)return t;let n=r;if(!new Ve().isFungible(n.token))return t;let c=ot(n.token.identifier)?.decimals;if(!c){let l=this.config.chainApiUrl||g.Chain.ApiUrl(this.config.env);c=(await(await fetch(`${l}/tokens/${n.token.identifier}`)).json()).decimals}if(!c)throw new Error(`WarpActionExecutor: Decimals not found for token ${n.token.identifier}`);let p=new Ft({token:n.token,amount:x(n.amount,c)});return this.serializer.nativeToString(e,p)+u.ArgCompositeSeparator+c}return t}catch{return t}}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:i,value:n})=>{if(!n||!i.position.startsWith("arg:"))return;let s=Number(i.position.split(":")[1])-1;r.splice(s,0,n)}),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 Rt.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 Rt.create(r)}toTypedTransfer(t){return new Ft({token:new Se({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var Nt=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{nt as BrandBuilder,g as Config,Et as WarpActionExecutor,R as WarpArgSerializer,S as WarpBuilder,u as WarpConstants,U as WarpContractLoader,Nt as WarpIndex,P as WarpLink,V as WarpRegistry,f as WarpUtils,Dr as address,Lr as biguint,qr as boolean,jr as codemeta,Fr as composite,Hr as esdt,T as getChainId,B as getLatestProtocolIdentifier,Ee as getWarpActionByIndex,Qr as hex,Rr as list,Mr as nothing,Vr as option,Pr as optional,x as shiftBigintBy,Er as string,J as toPreviewText,v as toTypedRegistryInfo,_r as token,kr as u16,$r as u32,Or as u64,Nr as u8,Ur as variadic};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "0.12.0",
3
+ "version": "0.13.1",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",