@vleap/warps 0.8.0 → 0.9.0

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
@@ -16,6 +16,7 @@ type WarpConfig = {
16
16
  indexUrl?: string;
17
17
  indexApiKey?: string;
18
18
  indexSearchParamName?: string;
19
+ vars?: Record<string, string | number>;
19
20
  };
20
21
  type WarpCacheConfig = {
21
22
  ttl?: number;
@@ -37,6 +38,7 @@ type Warp = {
37
38
  name: string;
38
39
  title: string;
39
40
  description: string | null;
41
+ bot?: string;
40
42
  preview: string;
41
43
  vars?: Record<WarpVarPlaceholder, string>;
42
44
  actions: WarpAction[];
@@ -49,7 +51,7 @@ type WarpMeta = {
49
51
  createdAt: string;
50
52
  };
51
53
  type WarpAction = WarpContractAction | WarpQueryAction | WarpLinkAction;
52
- type WarpActionType = 'contract' | 'query' | 'link';
54
+ type WarpActionType = 'contract' | 'query' | 'collect' | 'link';
53
55
  type WarpContractAction = {
54
56
  type: WarpActionType;
55
57
  label: string;
@@ -85,6 +87,16 @@ type WarpQueryAction = {
85
87
  abi?: string;
86
88
  inputs?: WarpActionInput[];
87
89
  };
90
+ type WarpCollectAction = {
91
+ type: WarpActionType;
92
+ label: string;
93
+ description?: string | null;
94
+ destination: {
95
+ url: string;
96
+ method: 'GET' | 'POST';
97
+ headers: Record<string, string>;
98
+ };
99
+ };
88
100
  type WarpActionInputSource = 'field' | 'query';
89
101
  type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'biguint' | 'bool' | 'address' | 'token' | 'codemeta' | 'hex' | 'esdt' | 'nft';
90
102
  type WarpActionInputType = string;
@@ -92,7 +104,9 @@ type WarpActionInputPosition = 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 |
92
104
  type WarpActionInputModifier = 'scale';
93
105
  type WarpActionInput = {
94
106
  name: string;
107
+ as?: string;
95
108
  description?: string | null;
109
+ bot?: string;
96
110
  type: WarpActionInputType;
97
111
  position: WarpActionInputPosition;
98
112
  source: WarpActionInputSource;
@@ -246,6 +260,7 @@ declare class WarpActionExecutor {
246
260
  constructor(config: WarpConfig, url: string);
247
261
  createTransactionForExecute(action: WarpContractAction, inputs: string[], inputTransfers: TokenTransfer[]): Transaction$1;
248
262
  executeQuery(action: WarpQueryAction, inputs: string[]): Promise<TypedValue>;
263
+ executeCollect(action: WarpCollectAction, inputs: string[]): Promise<void>;
249
264
  getArgumentsForInputs(action: WarpAction, inputs: string[]): string[];
250
265
  getNativeValueFromField(action: WarpAction, inputs: string[]): string | null;
251
266
  getNativeValueFromUrl(action: WarpAction): string | null;
@@ -368,4 +383,4 @@ declare class WarpUtils {
368
383
  static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
369
384
  }
370
385
 
371
- 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 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, 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 };
386
+ 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, 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 };
package/dist/index.d.ts CHANGED
@@ -16,6 +16,7 @@ type WarpConfig = {
16
16
  indexUrl?: string;
17
17
  indexApiKey?: string;
18
18
  indexSearchParamName?: string;
19
+ vars?: Record<string, string | number>;
19
20
  };
20
21
  type WarpCacheConfig = {
21
22
  ttl?: number;
@@ -37,6 +38,7 @@ type Warp = {
37
38
  name: string;
38
39
  title: string;
39
40
  description: string | null;
41
+ bot?: string;
40
42
  preview: string;
41
43
  vars?: Record<WarpVarPlaceholder, string>;
42
44
  actions: WarpAction[];
@@ -49,7 +51,7 @@ type WarpMeta = {
49
51
  createdAt: string;
50
52
  };
51
53
  type WarpAction = WarpContractAction | WarpQueryAction | WarpLinkAction;
52
- type WarpActionType = 'contract' | 'query' | 'link';
54
+ type WarpActionType = 'contract' | 'query' | 'collect' | 'link';
53
55
  type WarpContractAction = {
54
56
  type: WarpActionType;
55
57
  label: string;
@@ -85,6 +87,16 @@ type WarpQueryAction = {
85
87
  abi?: string;
86
88
  inputs?: WarpActionInput[];
87
89
  };
90
+ type WarpCollectAction = {
91
+ type: WarpActionType;
92
+ label: string;
93
+ description?: string | null;
94
+ destination: {
95
+ url: string;
96
+ method: 'GET' | 'POST';
97
+ headers: Record<string, string>;
98
+ };
99
+ };
88
100
  type WarpActionInputSource = 'field' | 'query';
89
101
  type BaseWarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'biguint' | 'bool' | 'address' | 'token' | 'codemeta' | 'hex' | 'esdt' | 'nft';
90
102
  type WarpActionInputType = string;
@@ -92,7 +104,9 @@ type WarpActionInputPosition = 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 |
92
104
  type WarpActionInputModifier = 'scale';
93
105
  type WarpActionInput = {
94
106
  name: string;
107
+ as?: string;
95
108
  description?: string | null;
109
+ bot?: string;
96
110
  type: WarpActionInputType;
97
111
  position: WarpActionInputPosition;
98
112
  source: WarpActionInputSource;
@@ -246,6 +260,7 @@ declare class WarpActionExecutor {
246
260
  constructor(config: WarpConfig, url: string);
247
261
  createTransactionForExecute(action: WarpContractAction, inputs: string[], inputTransfers: TokenTransfer[]): Transaction$1;
248
262
  executeQuery(action: WarpQueryAction, inputs: string[]): Promise<TypedValue>;
263
+ executeCollect(action: WarpCollectAction, inputs: string[]): Promise<void>;
249
264
  getArgumentsForInputs(action: WarpAction, inputs: string[]): string[];
250
265
  getNativeValueFromField(action: WarpAction, inputs: string[]): string | null;
251
266
  getNativeValueFromUrl(action: WarpAction): string | null;
@@ -368,4 +383,4 @@ declare class WarpUtils {
368
383
  static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
369
384
  }
370
385
 
371
- 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 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, 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 };
386
+ 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, 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 };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var tt=Object.create;var E=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var nt=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var st=(a,t)=>{for(var e in t)E(a,e,{get:t[e],enumerable:!0})},M=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rt(t))!it.call(a,i)&&i!==e&&E(a,i,{get:()=>t[i],enumerable:!(r=et(t,i))||r.enumerable});return a};var L=(a,t,e)=>(e=a!=null?tt(nt(a)):{},M(t||!a||!a.__esModule?E(e,"default",{value:a,enumerable:!0}):e,a)),at=a=>M(E({},"__esModule",{value:!0}),a);var Vt={};st(Vt,{BrandBuilder:()=>D,Config:()=>h,WarpActionExecutor:()=>_,WarpArgSerializer:()=>R,WarpBuilder:()=>k,WarpConstants:()=>w,WarpContractLoader:()=>U,WarpIndex:()=>H,WarpLink:()=>N,WarpRegistry:()=>F,WarpUtils:()=>I,address:()=>Tt,biguint:()=>yt,boolean:()=>wt,codemeta:()=>It,composite:()=>lt,esdt:()=>Ct,getChainId:()=>T,getLatestProtocolIdentifier:()=>S,hex:()=>bt,list:()=>ut,nothing:()=>At,option:()=>ot,optional:()=>ct,shiftBigintBy:()=>$,string:()=>dt,toPreviewText:()=>q,toTypedRegistryInfo:()=>P,token:()=>Wt,u16:()=>ft,u32:()=>mt,u64:()=>ht,u8:()=>gt,variadic:()=>pt});module.exports=at(Vt);var W=require("@multiversx/sdk-core"),z=L(require("ajv"));var h={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.4.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.4.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var T=a=>a==="devnet"?"D":a==="testnet"?"T":"1",S=a=>`${a}:${h.LatestProtocolVersion}`,P=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,i=""]=e.split("."),s=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(s,"0"));if(t<0){let o=r+i;if(s>=o.length)return 0n;let u=o.slice(0,-s)||"0";return BigInt(u)}else return BigInt(a)},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 D=class{constructor(t){this.pendingBrand={protocol:S(h.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new W.TransactionsFactoryConfig({chainID:T(this.config.env)}),r=new W.TransferTransactionsFactory({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:W.Address.newFromBech32(this.config.userAddress),receiver:W.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=new W.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||h.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new z.default,o=s.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};var w={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var c=require("@multiversx/sdk-core/out"),ot=(a,t)=>a?c.OptionValue.newProvided(a):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),ct=(a,t)=>a?new c.OptionalValue(a.getType(),a):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),ut=a=>{if(a.length===0)throw new Error("Cannot create a list from an empty array");let t=a[0].getType();return new c.List(t,a)},pt=a=>c.VariadicValue.fromItems(...a),lt=a=>{let t=a.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),a)},dt=a=>c.StringValue.fromUTF8(a),gt=a=>new c.U8Value(a),ft=a=>new c.U16Value(a),mt=a=>new c.U32Value(a),ht=a=>new c.U64Value(a),yt=a=>new c.BigUIntValue(BigInt(a)),wt=a=>new c.BooleanValue(a),Tt=a=>new c.AddressValue(c.Address.newFromBech32(a)),Wt=a=>new c.TokenIdentifierValue(a),bt=a=>c.BytesValue.fromHex(a),Ct=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")]),It=a=>new c.CodeMetadataValue(c.CodeMetadata.fromBuffer(Buffer.from(a,"hex"))),At=()=>new c.NothingValue;var f=require("@multiversx/sdk-core/out");var n=require("@multiversx/sdk-core/out"),y=":",b="|",G=new RegExp(`${y}(.*)`),R=class{nativeToString(t,e){return t==="esdt"&&e instanceof n.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(n.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(n.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(n.List.ClassName)){let e=t.getItems(),i=e.map(o=>this.typedToString(o).split(y)[0])[0],s=e.map(o=>this.typedToString(o).split(y)[1]);return`list:${i}:${s.join(",")}`}if(t.hasClassOrSuperclass(n.VariadicValue.ClassName)){let e=t.getItems(),i=e.map(o=>this.typedToString(o).split(y)[0])[0],s=e.map(o=>this.typedToString(o).split(y)[1]);return`variadic:${i}:${s.join(",")}`}if(t.hasClassOrSuperclass(n.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(u=>this.typedToString(u).split(y)[0]),i=e.map(u=>this.typedToString(u).split(y)[1]),s=r.join(b),o=i.join(b);return`composite(${s}):${o}`}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName))return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(n.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(n.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),i=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${i}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new n.CompositeType(...e.split(b).map(r=>this.nativeToType(r)))}if(t==="string")return new n.StringType;if(t==="uint8")return new n.U8Type;if(t==="uint16")return new n.U16Type;if(t==="uint32")return new n.U32Type;if(t==="uint64")return new n.U64Type;if(t==="biguint")return new n.BigUIntType;if(t==="bool")return new n.BooleanType;if(t==="address")return new n.AddressType;if(t==="token")return new n.TokenIdentifierType;if(t==="hex")return new n.BytesType;if(t==="codemeta")return new n.CodeMetadataType;if(t==="esdt"||t==="nft")return new n.StructType("EsdtTokenPayment",[new n.FieldDefinition("token_identifier","",new n.TokenIdentifierType),new n.FieldDefinition("token_nonce","",new n.U64Type),new n.FieldDefinition("amount","",new n.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(y),r=e[0],i=e.slice(1).join(y);if(r==="null")return[r,null];if(r==="option"){let[s,o]=i.split(y);return[`option:${s}`,o||null]}else if(r==="optional"){let[s,o]=i.split(y);return[`optional:${s}`,o||null]}else if(r==="list"){let s=i.split(y),o=s.slice(0,-1).join(y),u=s[s.length-1],p=(u?u.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`list:${o}`,p]}else if(r==="variadic"){let s=i.split(y),o=s.slice(0,-1).join(y),u=s[s.length-1],p=(u?u.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`variadic:${o}`,p]}else if(r.startsWith("composite")){let s=r.match(/\(([^)]+)\)/)?.[1]?.split(b),u=i.split(b).map((d,p)=>this.stringToNative(`${s[p]}:${d}`)[1]);return[r,u]}else{if(r==="string")return[r,i];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(i)];if(r==="uint64"||r==="biguint")return[r,BigInt(i||0)];if(r==="bool")return[r,i==="true"];if(r==="address")return[r,i];if(r==="token")return[r,i];if(r==="hex")return[r,i];if(r==="codemeta")return[r,i];if(r==="esdt"){let[s,o,u]=i.split(b);return[r,new n.TokenTransfer({token:new n.Token({identifier:s,nonce:BigInt(o)}),amount:BigInt(u)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new n.NothingValue;if(e==="option"){let i=this.stringToTyped(r);return i instanceof n.NothingValue?n.OptionValue.newMissingTyped(i.getType()):n.OptionValue.newProvided(i)}if(e==="optional"){let i=this.stringToTyped(r);return i instanceof n.NothingValue?n.OptionalValue.newMissing():new n.OptionalValue(i.getType(),i)}if(e==="list"){let[i,s]=r.split(G,2),u=s.split(",").map(d=>this.stringToTyped(`${i}:${d}`));return new n.List(this.nativeToType(i),u)}if(e==="variadic"){let[i,s]=r.split(G,2),u=s.split(",").map(d=>this.stringToTyped(`${i}:${d}`));return new n.VariadicValue(new n.VariadicType(this.nativeToType(i)),u)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],s=r.split(b),o=i.split(b),u=s.map((p,g)=>this.stringToTyped(`${o[g]}:${p}`)),d=u.map(p=>p.getType());return new n.CompositeValue(new n.CompositeType(...d),u)}if(e==="string")return r?n.StringValue.fromUTF8(r):new n.NothingValue;if(e==="uint8")return r?new n.U8Value(Number(r)):new n.NothingValue;if(e==="uint16")return r?new n.U16Value(Number(r)):new n.NothingValue;if(e==="uint32")return r?new n.U32Value(Number(r)):new n.NothingValue;if(e==="uint64")return r?new n.U64Value(BigInt(r)):new n.NothingValue;if(e==="biguint")return r?new n.BigUIntValue(BigInt(r)):new n.NothingValue;if(e==="bool")return r?new n.BooleanValue(typeof r=="boolean"?r:r==="true"):new n.NothingValue;if(e==="address")return r?new n.AddressValue(n.Address.newFromBech32(r)):new n.NothingValue;if(e==="token")return r?new n.TokenIdentifierValue(r):new n.NothingValue;if(e==="hex")return r?n.BytesValue.fromHex(r):new n.NothingValue;if(e==="codemeta")return new n.CodeMetadataValue(n.CodeMetadata.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let i=r.split(b);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 J=require("@multiversx/sdk-core/out"),U=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 J.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4})}};var _=class{constructor(t,e){this.config=t,this.url=new URL(e),this.serializer=new R,this.contractLoader=new U(t)}createTransactionForExecute(t,e,r){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=f.Address.newFromBech32(this.config.userAddress),s=f.Address.newFromBech32(t.address),o=new f.TransactionsFactoryConfig({chainID:T(this.config.env)}),u=this.getCombinedInputs(t,e),p=this.getModifiedInputs(t,u).map(x=>this.serializer.stringToTyped(x)),g=this.getNativeValueFromField(t,e),m=this.getNativeValueFromUrl(t),A=BigInt(g||m||t.value||0),B=this.getCombinedTokenTransfers(t,r);return s.isContractAddress()?new f.SmartContractTransactionsFactory({config:o}).createTransactionForExecute({sender:i,contract:s,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:p,tokenTransfers:B,nativeTransferAmount:A}):new f.TransferTransactionsFactory({config:o}).createTransactionForTransfer({sender:i,receiver:s,nativeAmount:A,tokenTransfers:B,data:p[0]?.hasExactClass(f.StringValue.ClassName)?p[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=new f.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4}),i=new f.QueryRunnerAdapter({networkProvider:r}),s=await this.getAbiForAction(t),o=this.getModifiedInputs(t,e),d=this.getCombinedInputs(t,o).map(O=>this.serializer.stringToTyped(O)),p=new f.SmartContractQueriesController({queryRunner:i,abi:s}),g=p.createQuery({contract:t.address,function:t.func,arguments:d}),m=await p.runQuery(g),A=new f.ResultsParser,B={returnCode:m.returnCode,returnMessage:m.returnMessage,getReturnDataParts:()=>m.returnDataParts.map(O=>Buffer.from(O))},x=m.function,Y=s.getEndpoint(x),j=A.parseQueryResponse(B,Y).firstValue;if(!j)throw new Error("WarpActionExecutor: Query result not found");return j}getArgumentsForInputs(t,e){let r=this.getModifiedInputs(t,e);return this.getCombinedInputs(t,r)}getNativeValueFromField(t,e){let r=(t.inputs||[]).findIndex(s=>s.source==="field"&&s.position==="value"),i=r!==-1?e[r]:null;return i?i.split(":")[1]:null}getNativeValueFromUrl(t){let e=new URLSearchParams(this.url.search),i=t.inputs?.filter(s=>s.source==="query")?.find(s=>s.position==="value")?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,e){return[...t.transfers?.map(this.toTypedTransfer)||[],...e]}getModifiedInputs(t,e){let r=Object.fromEntries(e.entries());return(t.inputs?.filter(s=>!!s.modifier)||[]).forEach((s,o)=>{if(s.modifier?.startsWith("scale:")){let[,u]=s.modifier.split(":");if(isNaN(Number(u))){let d=s.position.startsWith("arg:")?Number(s.position.split(":")[1])-1:o,p=t.inputs?.find(x=>x.name===u);if(!p)throw new Error(`WarpActionExecutor: Scalable input ${u} not found`);let g=Number(p.position.split(":")[1])-1,m=r[g].split(":")[1],A=r[d].split(":")[1],B=$(A,+m);r[d]=`${s.type}:${B}`}else{let d=s.position.startsWith("arg:")?Number(s.position.split(":")[1])-1:o,p=r[d].split(":")[1],g=$(p,+u);r[d]=`${s.type}:${g}`}}}),Object.values(r)}getCombinedInputs(t,e){let r=t.inputs?.filter(u=>u.position.startsWith("arg:"))||[],i=(u,d)=>u.source==="query"?this.serializer.nativeToString(u.type,this.url.searchParams.get(u.name)||""):e[d],s=r.map((u,d)=>({input:u,value:i(u,d)})),o="args"in t?t.args:[];return s.forEach(({input:u,value:d})=>{let p=Number(u.position.split(":")[1])-1;o.splice(p,0,d)}),o}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 C=require("@multiversx/sdk-core"),X=L(require("ajv"));var V={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},v=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 K=L(require("qr-code-styling"));var l=require("@multiversx/sdk-core/out");var Q={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 F=class{constructor(t){this.cache=new v;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:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[l.BytesValue.fromHex(t),l.BytesValue.fromUTF8(e)]:[l.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[l.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:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromUTF8(t),l.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromHex(t),l.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:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromHex(t),l.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=V.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),m}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[l.BytesValue.fromUTF8(t)]}),u=await s.runQuery(o),[d]=s.parseQueryResponse(u),p=d?P(d):null,g=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:g},e.ttl),{registryInfo:p,brand:g}}async getInfoByHash(t,e){let r=V.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),m}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByHash",arguments:[l.BytesValue.fromHex(t)]}),u=await s.runQuery(o),[d]=s.parseQueryResponse(u),p=d?P(d):null,g=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:g},e.ttl),{registryInfo:p,brand:g}}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 l.AddressValue(new l.Address(e))]}),o=await i.runQuery(s),[u]=i.parseQueryResponse(o);return u.map(P)}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 l.AddressValue(new l.Address(e))]}),o=await i.runQuery(s),[u]=i.parseQueryResponse(o),d=u.map(m=>m.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(d.map(m=>this.fetchBrand(m,p)))).filter(m=>m!==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 l.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let s=await i.getTransaction(t),o=JSON.parse(s.data.toString());return o.meta={hash:s.hash,creator:s.sender.bech32(),createdAt:new Date(s.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(s){return console.error("WarpRegistry: Error fetching brand from transaction hash",s),null}}getRegistryContractAddress(){return this.config.registryContract||h.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await e.runQuery(r),[s]=e.parseQueryResponse(i),o=BigInt(s.toString());this.unitPrice=o}getFactory(){let t=new l.TransactionsFactoryConfig({chainID:T(this.config.env)}),e=l.AbiRegistry.create(Q);return new l.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env),e=new l.ApiNetworkProvider(t,{timeout:3e4}),r=new l.QueryRunnerAdapter({networkProvider:e}),i=l.AbiRegistry.create(Q);return new l.SmartContractQueriesController({queryRunner:r,abi:i})}};var N=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(w.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(i)).filter(p=>p.match),u=o.length>0,d=o.map(p=>({url:p.url,warp:p.warp}));return{match:u,results:d}}async detect(t){let e=t.startsWith(w.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):I.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,s=new k(this.config),o=new F(this.config),u=null,d=null,p=null;if(r==="hash"){u=await s.createFromTransactionHash(i);try{let{registryInfo:g,brand:m}=await o.getInfoByHash(i);d=g,p=m}catch{}}else if(r==="alias"){let{registryInfo:g,brand:m}=await o.getInfoByAlias(i);d=g,p=m,g&&(u=await s.createFromTransactionHash(g.hash))}return u?{match:!0,url:t,warp:u,registryInfo:d,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||h.DefaultClientUrl(this.config.env),i=t===w.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+w.IdentifierParamSeparator+e);return h.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${w.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",s="black",o="#23F7DD"){let u=this.build(t,e);return new K.default({type:"svg",width:r,height:r,data:String(u),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=h.SuperClientUrls.includes(e.origin),i=e.searchParams.get(w.IdentifierParamName),s=r&&!i?e.pathname.split("/")[1]:i;if(!s)return null;let o=decodeURIComponent(s);return I.getInfoFromPrefixedIdentifier(o)}};var vt="https://",Z="query",I=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)};return Object.entries(t.vars).forEach(([s,o])=>{if(typeof o=="string"&&o.startsWith(`${Z}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let u=o.split(`${Z}:`)[1],d=new URL(e.currentUrl).searchParams.get(u);d&&i(s,d)}else i(s,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(w.IdentifierParamSeparator)?e:`${w.DefaultIdentifierType}${w.IdentifierParamSeparator}${e}`,[i,s]=r.split(w.IdentifierParamSeparator);return{type:i,id:s}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(vt))return t.next;{let r=new N(e),i=a.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}};var k=class{constructor(t){this.cache=new v;this.pendingWarp={protocol:S(h.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new C.TransactionsFactoryConfig({chainID:T(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 this.ensureValidSchema(r),I.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 C.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let s=await i.getTransaction(t),o=await this.createFromTransaction(s);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(s){return console.error("WarpBuilder: Error creating from transaction hash",s),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return q(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||h.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new X.default,o=s.compile(i);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};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,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
1
+ "use strict";var et=Object.create;var $=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)$(a,e,{get:t[e],enumerable:!0})},M=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of nt(t))!st.call(a,i)&&i!==e&&$(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)):{},M(t||!a||!a.__esModule?$(e,"default",{value:a,enumerable:!0}):e,a)),ot=a=>M($({},"__esModule",{value:!0}),a);var xt={};at(xt,{BrandBuilder:()=>D,Config:()=>h,WarpActionExecutor:()=>_,WarpArgSerializer:()=>R,WarpBuilder:()=>E,WarpConstants:()=>w,WarpContractLoader:()=>U,WarpIndex:()=>H,WarpLink:()=>N,WarpRegistry:()=>F,WarpUtils:()=>I,address:()=>Wt,biguint:()=>wt,boolean:()=>Tt,codemeta:()=>At,composite:()=>dt,esdt:()=>It,getChainId:()=>T,getLatestProtocolIdentifier:()=>S,hex:()=>Ct,list:()=>pt,nothing:()=>Bt,option:()=>ct,optional:()=>ut,shiftBigintBy:()=>k,string:()=>gt,toPreviewText:()=>q,toTypedRegistryInfo:()=>P,token:()=>bt,u16:()=>mt,u32:()=>ht,u64:()=>yt,u8:()=>ft,variadic:()=>lt});module.exports=ot(xt);var W=require("@multiversx/sdk-core"),z=L(require("ajv"));var h={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.4.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.4.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var T=a=>a==="devnet"?"D":a==="testnet"?"T":"1",S=a=>`${a}:${h.LatestProtocolVersion}`,P=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 u=o.slice(0,-s)||"0";return BigInt(u)}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 D=class{constructor(t){this.pendingBrand={protocol:S(h.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new W.TransactionsFactoryConfig({chainID:T(this.config.env)}),r=new W.TransferTransactionsFactory({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:W.Address.newFromBech32(this.config.userAddress),receiver:W.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=new W.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||h.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),s=new z.default,o=s.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};var w={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var c=require("@multiversx/sdk-core/out"),ct=(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(),pt=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)},lt=a=>c.VariadicValue.fromItems(...a),dt=a=>{let t=a.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),a)},gt=a=>c.StringValue.fromUTF8(a),ft=a=>new c.U8Value(a),mt=a=>new c.U16Value(a),ht=a=>new c.U32Value(a),yt=a=>new c.U64Value(a),wt=a=>new c.BigUIntValue(BigInt(a)),Tt=a=>new c.BooleanValue(a),Wt=a=>new c.AddressValue(c.Address.newFromBech32(a)),bt=a=>new c.TokenIdentifierValue(a),Ct=a=>c.BytesValue.fromHex(a),It=a=>new c.Struct(new c.StructType("EsdtTokenPayment",[new c.FieldDefinition("token_identifier","",new c.TokenIdentifierType),new c.FieldDefinition("token_nonce","",new c.U64Type),new c.FieldDefinition("amount","",new c.BigUIntType)]),[new c.Field(new c.TokenIdentifierValue(a.token.identifier),"token_identifier"),new c.Field(new c.U64Value(BigInt(a.token.nonce)),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(a.amount)),"amount")]),At=a=>new c.CodeMetadataValue(c.CodeMetadata.fromBuffer(Buffer.from(a,"hex"))),Bt=()=>new c.NothingValue;var f=require("@multiversx/sdk-core/out");var n=require("@multiversx/sdk-core/out"),y=":",b="|",G=new RegExp(`${y}(.*)`),R=class{nativeToString(t,e){return t==="esdt"&&e instanceof n.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(n.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(n.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(n.List.ClassName)){let e=t.getItems(),i=e.map(o=>this.typedToString(o).split(y)[0])[0],s=e.map(o=>this.typedToString(o).split(y)[1]);return`list:${i}:${s.join(",")}`}if(t.hasClassOrSuperclass(n.VariadicValue.ClassName)){let e=t.getItems(),i=e.map(o=>this.typedToString(o).split(y)[0])[0],s=e.map(o=>this.typedToString(o).split(y)[1]);return`variadic:${i}:${s.join(",")}`}if(t.hasClassOrSuperclass(n.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(u=>this.typedToString(u).split(y)[0]),i=e.map(u=>this.typedToString(u).split(y)[1]),s=r.join(b),o=i.join(b);return`composite(${s}):${o}`}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName))return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(n.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(n.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(n.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(n.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(n.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),i=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${i}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new n.CompositeType(...e.split(b).map(r=>this.nativeToType(r)))}if(t==="string")return new n.StringType;if(t==="uint8")return new n.U8Type;if(t==="uint16")return new n.U16Type;if(t==="uint32")return new n.U32Type;if(t==="uint64")return new n.U64Type;if(t==="biguint")return new n.BigUIntType;if(t==="bool")return new n.BooleanType;if(t==="address")return new n.AddressType;if(t==="token")return new n.TokenIdentifierType;if(t==="hex")return new n.BytesType;if(t==="codemeta")return new n.CodeMetadataType;if(t==="esdt"||t==="nft")return new n.StructType("EsdtTokenPayment",[new n.FieldDefinition("token_identifier","",new n.TokenIdentifierType),new n.FieldDefinition("token_nonce","",new n.U64Type),new n.FieldDefinition("amount","",new n.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(y),r=e[0],i=e.slice(1).join(y);if(r==="null")return[r,null];if(r==="option"){let[s,o]=i.split(y);return[`option:${s}`,o||null]}else if(r==="optional"){let[s,o]=i.split(y);return[`optional:${s}`,o||null]}else if(r==="list"){let s=i.split(y),o=s.slice(0,-1).join(y),u=s[s.length-1],p=(u?u.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`list:${o}`,p]}else if(r==="variadic"){let s=i.split(y),o=s.slice(0,-1).join(y),u=s[s.length-1],p=(u?u.split(","):[]).map(g=>this.stringToNative(`${o}:${g}`)[1]);return[`variadic:${o}`,p]}else if(r.startsWith("composite")){let s=r.match(/\(([^)]+)\)/)?.[1]?.split(b),u=i.split(b).map((d,p)=>this.stringToNative(`${s[p]}:${d}`)[1]);return[r,u]}else{if(r==="string")return[r,i];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(i)];if(r==="uint64"||r==="biguint")return[r,BigInt(i||0)];if(r==="bool")return[r,i==="true"];if(r==="address")return[r,i];if(r==="token")return[r,i];if(r==="hex")return[r,i];if(r==="codemeta")return[r,i];if(r==="esdt"){let[s,o,u]=i.split(b);return[r,new n.TokenTransfer({token:new n.Token({identifier:s,nonce:BigInt(o)}),amount:BigInt(u)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new n.NothingValue;if(e==="option"){let i=this.stringToTyped(r);return i instanceof n.NothingValue?n.OptionValue.newMissingTyped(i.getType()):n.OptionValue.newProvided(i)}if(e==="optional"){let i=this.stringToTyped(r);return i instanceof n.NothingValue?n.OptionalValue.newMissing():new n.OptionalValue(i.getType(),i)}if(e==="list"){let[i,s]=r.split(G,2),u=s.split(",").map(d=>this.stringToTyped(`${i}:${d}`));return new n.List(this.nativeToType(i),u)}if(e==="variadic"){let[i,s]=r.split(G,2),u=s.split(",").map(d=>this.stringToTyped(`${i}:${d}`));return new n.VariadicValue(new n.VariadicType(this.nativeToType(i)),u)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],s=r.split(b),o=i.split(b),u=s.map((p,g)=>this.stringToTyped(`${o[g]}:${p}`)),d=u.map(p=>p.getType());return new n.CompositeValue(new n.CompositeType(...d),u)}if(e==="string")return r?n.StringValue.fromUTF8(r):new n.NothingValue;if(e==="uint8")return r?new n.U8Value(Number(r)):new n.NothingValue;if(e==="uint16")return r?new n.U16Value(Number(r)):new n.NothingValue;if(e==="uint32")return r?new n.U32Value(Number(r)):new n.NothingValue;if(e==="uint64")return r?new n.U64Value(BigInt(r)):new n.NothingValue;if(e==="biguint")return r?new n.BigUIntValue(BigInt(r)):new n.NothingValue;if(e==="bool")return r?new n.BooleanValue(typeof r=="boolean"?r:r==="true"):new n.NothingValue;if(e==="address")return r?new n.AddressValue(n.Address.newFromBech32(r)):new n.NothingValue;if(e==="token")return r?new n.TokenIdentifierValue(r):new n.NothingValue;if(e==="hex")return r?n.BytesValue.fromHex(r):new n.NothingValue;if(e==="codemeta")return new n.CodeMetadataValue(n.CodeMetadata.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let i=r.split(b);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 J=require("@multiversx/sdk-core/out"),U=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 J.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4})}};var _=class{constructor(t,e){this.config=t,this.url=new URL(e),this.serializer=new R,this.contractLoader=new U(t)}createTransactionForExecute(t,e,r){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=f.Address.newFromBech32(this.config.userAddress),s=f.Address.newFromBech32(t.address),o=new f.TransactionsFactoryConfig({chainID:T(this.config.env)}),u=this.getCombinedInputs(t,e),p=this.getModifiedInputs(t,u).map(x=>this.serializer.stringToTyped(x)),g=this.getNativeValueFromField(t,e),m=this.getNativeValueFromUrl(t),A=BigInt(g||m||t.value||0),B=this.getCombinedTokenTransfers(t,r);return s.isContractAddress()?new f.SmartContractTransactionsFactory({config:o}).createTransactionForExecute({sender:i,contract:s,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:p,tokenTransfers:B,nativeTransferAmount:A}):new f.TransferTransactionsFactory({config:o}).createTransactionForTransfer({sender:i,receiver:s,nativeAmount:A,tokenTransfers:B,data:p[0]?.hasExactClass(f.StringValue.ClassName)?p[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=new f.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4}),i=new f.QueryRunnerAdapter({networkProvider:r}),s=await this.getAbiForAction(t),o=this.getModifiedInputs(t,e),d=this.getCombinedInputs(t,o).map(O=>this.serializer.stringToTyped(O)),p=new f.SmartContractQueriesController({queryRunner:i,abi:s}),g=p.createQuery({contract:t.address,function:t.func,arguments:d}),m=await p.runQuery(g),A=new f.ResultsParser,B={returnCode:m.returnCode,returnMessage:m.returnMessage,getReturnDataParts:()=>m.returnDataParts.map(O=>Buffer.from(O))},x=m.function,tt=s.getEndpoint(x),j=A.parseQueryResponse(B,tt).firstValue;if(!j)throw new Error("WarpActionExecutor: Query result not found");return j}async executeCollect(t,e){let r=new URL(t.destination.url),i=new Headers;return Object.entries(t.destination.headers).forEach(([u,d])=>{i.set(u,d)}),await(await fetch(r,{method:t.destination.method,headers:i,body:JSON.stringify({inputs:e})})).json()}getArgumentsForInputs(t,e){let r=this.getModifiedInputs(t,e);return this.getCombinedInputs(t,r)}getNativeValueFromField(t,e){let r=(t.inputs||[]).findIndex(s=>s.source==="field"&&s.position==="value"),i=r!==-1?e[r]:null;return i?i.split(":")[1]:null}getNativeValueFromUrl(t){let e=new URLSearchParams(this.url.search),i=t.inputs?.filter(s=>s.source==="query")?.find(s=>s.position==="value")?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,e){return[...t.transfers?.map(this.toTypedTransfer)||[],...e]}getModifiedInputs(t,e){let r=Object.fromEntries(e.entries());return(t.inputs?.filter(s=>!!s.modifier)||[]).forEach((s,o)=>{if(s.modifier?.startsWith("scale:")){let[,u]=s.modifier.split(":");if(isNaN(Number(u))){let d=s.position.startsWith("arg:")?Number(s.position.split(":")[1])-1:o,p=t.inputs?.find(x=>x.name===u);if(!p)throw new Error(`WarpActionExecutor: Scalable input ${u} not found`);let g=Number(p.position.split(":")[1])-1,m=r[g].split(":")[1],A=r[d].split(":")[1],B=k(A,+m);r[d]=`${s.type}:${B}`}else{let d=s.position.startsWith("arg:")?Number(s.position.split(":")[1])-1:o,p=r[d].split(":")[1],g=k(p,+u);r[d]=`${s.type}:${g}`}}}),Object.values(r)}getCombinedInputs(t,e){let r=t.inputs?.filter(u=>u.position.startsWith("arg:"))||[],i=(u,d)=>u.source==="query"?this.serializer.nativeToString(u.type,this.url.searchParams.get(u.name)||""):e[d],s=r.map((u,d)=>({input:u,value:i(u,d)})),o="args"in t?t.args:[];return s.forEach(({input:u,value:d})=>{let p=Number(u.position.split(":")[1])-1;o.splice(p,0,d)}),o}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 C=require("@multiversx/sdk-core"),Y=L(require("ajv"));var V={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},v=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 K=L(require("qr-code-styling"));var l=require("@multiversx/sdk-core/out");var Q={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 F=class{constructor(t){this.cache=new v;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:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[l.BytesValue.fromHex(t),l.BytesValue.fromUTF8(e)]:[l.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[l.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:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromUTF8(t),l.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromHex(t),l.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:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:l.Address.newFromBech32(this.config.userAddress),contract:l.Address.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.BytesValue.fromHex(t),l.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=V.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),m}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[l.BytesValue.fromUTF8(t)]}),u=await s.runQuery(o),[d]=s.parseQueryResponse(u),p=d?P(d):null,g=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:g},e.ttl),{registryInfo:p,brand:g}}async getInfoByHash(t,e){let r=V.RegistryInfo(t);if(e){let m=this.cache.get(r);if(m)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),m}let i=this.getRegistryContractAddress(),s=this.getController(),o=s.createQuery({contract:i,function:"getInfoByHash",arguments:[l.BytesValue.fromHex(t)]}),u=await s.runQuery(o),[d]=s.parseQueryResponse(u),p=d?P(d):null,g=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:g},e.ttl),{registryInfo:p,brand:g}}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 l.AddressValue(new l.Address(e))]}),o=await i.runQuery(s),[u]=i.parseQueryResponse(o);return u.map(P)}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 l.AddressValue(new l.Address(e))]}),o=await i.runQuery(s),[u]=i.parseQueryResponse(o),d=u.map(m=>m.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(d.map(m=>this.fetchBrand(m,p)))).filter(m=>m!==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 l.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let s=await i.getTransaction(t),o=JSON.parse(s.data.toString());return o.meta={hash:s.hash,creator:s.sender.bech32(),createdAt:new Date(s.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(s){return console.error("WarpRegistry: Error fetching brand from transaction hash",s),null}}getRegistryContractAddress(){return this.config.registryContract||h.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await e.runQuery(r),[s]=e.parseQueryResponse(i),o=BigInt(s.toString());this.unitPrice=o}getFactory(){let t=new l.TransactionsFactoryConfig({chainID:T(this.config.env)}),e=l.AbiRegistry.create(Q);return new l.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env),e=new l.ApiNetworkProvider(t,{timeout:3e4}),r=new l.QueryRunnerAdapter({networkProvider:e}),i=l.AbiRegistry.create(Q);return new l.SmartContractQueriesController({queryRunner:r,abi:i})}};var N=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(w.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),o=(await Promise.all(i)).filter(p=>p.match),u=o.length>0,d=o.map(p=>({url:p.url,warp:p.warp}));return{match:u,results:d}}async detect(t){let e=t.startsWith(w.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):I.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,s=new E(this.config),o=new F(this.config),u=null,d=null,p=null;if(r==="hash"){u=await s.createFromTransactionHash(i);try{let{registryInfo:g,brand:m}=await o.getInfoByHash(i);d=g,p=m}catch{}}else if(r==="alias"){let{registryInfo:g,brand:m}=await o.getInfoByAlias(i);d=g,p=m,g&&(u=await s.createFromTransactionHash(g.hash))}return u?{match:!0,url:t,warp:u,registryInfo:d,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||h.DefaultClientUrl(this.config.env),i=t===w.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+w.IdentifierParamSeparator+e);return h.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${w.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",s="black",o="#23F7DD"){let u=this.build(t,e);return new K.default({type:"svg",width:r,height:r,data:String(u),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=h.SuperClientUrls.includes(e.origin),i=e.searchParams.get(w.IdentifierParamName),s=r&&!i?e.pathname.split("/")[1]:i;if(!s)return null;let o=decodeURIComponent(s);return I.getInfoFromPrefixedIdentifier(o)}};var Vt="https://",Z="query",X="env",I=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(`${Z}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let u=o.split(`${Z}:`)[1],d=new URL(e.currentUrl).searchParams.get(u);d&&i(s,d)}else if(typeof o=="string"&&o.startsWith(`${X}:`)){let u=o.split(`${X}:`)[1],d=e.vars?.[u];d&&i(s,d)}else i(s,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(w.IdentifierParamSeparator)?e:`${w.DefaultIdentifierType}${w.IdentifierParamSeparator}${e}`,[i,s]=r.split(w.IdentifierParamSeparator);return{type:i,id:s}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(Vt))return t.next;{let r=new N(e),i=a.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}};var E=class{constructor(t){this.cache=new v;this.pendingWarp={protocol:S(h.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new C.TransactionsFactoryConfig({chainID:T(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 this.ensureValidSchema(r),I.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 C.ApiNetworkProvider(this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env));try{let s=await i.getTransaction(t),o=await this.createFromTransaction(s);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(s){return console.error("WarpBuilder: Error creating from transaction hash",s),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return q(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||h.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),s=new Y.default,o=s.compile(i);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${s.errorsText(o.errors)}`)}};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,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 X,ApiNetworkProvider as Et,TransactionsFactoryConfig as $t,TransferTransactionsFactory as Ot}from"@multiversx/sdk-core";import Lt from"ajv";var d={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.4.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.4.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="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=s=>s==="devnet"?"D":s==="testnet"?"T":"1",v=s=>`${s}:${d.LatestProtocolVersion}`,V=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),N=(s,t)=>{let e=s.toString(),[r,i=""]=e.split("."),n=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(n,"0"));if(t<0){let a=r+i;if(n>=a.length)return 0n;let o=a.slice(0,-n)||"0";return BigInt(o)}else return BigInt(s)},Z=(s,t=100)=>{if(!s)return"";let e=s.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 Y=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 $t({chainID:T(this.config.env)}),r=new Ot({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:X.newFromBech32(this.config.userAddress),receiver:X.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 Et(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,i=await(await fetch(e)).json(),n=new Lt,a=n.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};var y={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import{Address as qt,AddressValue as Dt,BigUIntType as _t,BigUIntValue as tt,BooleanValue as Qt,BytesValue as Ht,CodeMetadata as jt,CodeMetadataValue as Mt,CompositeType as zt,CompositeValue as Gt,Field as k,FieldDefinition as E,List as Jt,NothingValue as Kt,OptionalValue as $,OptionValue as O,StringValue as Zt,Struct as Xt,StructType as Yt,TokenIdentifierType as te,TokenIdentifierValue as et,U16Value as ee,U32Value as re,U64Type as ne,U64Value as rt,U8Value as ie,VariadicValue as se}from"@multiversx/sdk-core/out";var Je=(s,t)=>s?O.newProvided(s):t?O.newMissingTyped(t):O.newMissing(),Ke=(s,t)=>s?new $(s.getType(),s):t?new $(t):$.newMissing(),Ze=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new Jt(t,s)},Xe=s=>se.fromItems(...s),Ye=s=>{let t=s.map(e=>e.getType());return new Gt(new zt(...t),s)},tr=s=>Zt.fromUTF8(s),er=s=>new ie(s),rr=s=>new ee(s),nr=s=>new re(s),ir=s=>new rt(s),sr=s=>new tt(BigInt(s)),ar=s=>new Qt(s),or=s=>new Dt(qt.newFromBech32(s)),cr=s=>new et(s),ur=s=>Ht.fromHex(s),pr=s=>new Xt(new Yt("EsdtTokenPayment",[new E("token_identifier","",new te),new E("token_nonce","",new ne),new E("amount","",new _t)]),[new k(new et(s.token.identifier),"token_identifier"),new k(new rt(BigInt(s.token.nonce)),"token_nonce"),new k(new tt(BigInt(s.amount)),"amount")]),lr=s=>new Mt(jt.fromBuffer(Buffer.from(s,"hex"))),dr=()=>new Kt;import{AbiRegistry as vt,Address as Vt,ApiNetworkProvider as de,QueryRunnerAdapter as ge,ResultsParser as fe,SmartContractQueriesController as me,SmartContractTransactionsFactory as he,StringValue as ye,Token as we,TokenTransfer as Te,TransactionsFactoryConfig as We,TransferTransactionsFactory as be}from"@multiversx/sdk-core/out";import{Address as ae,AddressType as nt,AddressValue as it,BigUIntType as L,BigUIntValue as q,BooleanType as st,BooleanValue as at,BytesType as ot,BytesValue as ct,CodeMetadata as oe,CodeMetadataType as ut,CodeMetadataValue as pt,CompositeType as lt,CompositeValue as dt,Field as D,FieldDefinition as _,List as gt,NothingValue as h,OptionalValue as Q,OptionValue as H,StringType as ft,StringValue as mt,Struct as ce,StructType as ht,Token as ue,TokenIdentifierType as j,TokenIdentifierValue as M,TokenTransfer as yt,U16Type as wt,U16Value as Tt,U32Type as Wt,U32Value as bt,U64Type as z,U64Value as G,U8Type as Ct,U8Value as It,VariadicType as pe,VariadicValue as At}from"@multiversx/sdk-core/out";var f=":",w="|",Bt=new RegExp(`${f}(.*)`),x=class{nativeToString(t,e){return t==="esdt"&&e instanceof yt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(H.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(Q.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(gt.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToString(a).split(f)[0])[0],n=e.map(a=>this.typedToString(a).split(f)[1]);return`list:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(At.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToString(a).split(f)[0])[0],n=e.map(a=>this.typedToString(a).split(f)[1]);return`variadic:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(dt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(f)[0]),i=e.map(o=>this.typedToString(o).split(f)[1]),n=r.join(w),a=i.join(w);return`composite(${n}):${a}`}if(t.hasClassOrSuperclass(q.ClassName))return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(It.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Tt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(bt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(G.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(mt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(at.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(it.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(M.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(ct.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(pt.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 lt(...e.split(w).map(r=>this.nativeToType(r)))}if(t==="string")return new ft;if(t==="uint8")return new Ct;if(t==="uint16")return new wt;if(t==="uint32")return new Wt;if(t==="uint64")return new z;if(t==="biguint")return new L;if(t==="bool")return new st;if(t==="address")return new nt;if(t==="token")return new j;if(t==="hex")return new ot;if(t==="codemeta")return new ut;if(t==="esdt"||t==="nft")return new ht("EsdtTokenPayment",[new _("token_identifier","",new j),new _("token_nonce","",new z),new _("amount","",new L)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f),r=e[0],i=e.slice(1).join(f);if(r==="null")return[r,null];if(r==="option"){let[n,a]=i.split(f);return[`option:${n}`,a||null]}else if(r==="optional"){let[n,a]=i.split(f);return[`optional:${n}`,a||null]}else if(r==="list"){let n=i.split(f),a=n.slice(0,-1).join(f),o=n[n.length-1],c=(o?o.split(","):[]).map(p=>this.stringToNative(`${a}:${p}`)[1]);return[`list:${a}`,c]}else if(r==="variadic"){let n=i.split(f),a=n.slice(0,-1).join(f),o=n[n.length-1],c=(o?o.split(","):[]).map(p=>this.stringToNative(`${a}:${p}`)[1]);return[`variadic:${a}`,c]}else if(r.startsWith("composite")){let n=r.match(/\(([^)]+)\)/)?.[1]?.split(w),o=i.split(w).map((u,c)=>this.stringToNative(`${n[c]}:${u}`)[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,a,o]=i.split(w);return[r,new yt({token:new ue({identifier:n,nonce:BigInt(a)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new h;if(e==="option"){let i=this.stringToTyped(r);return i instanceof h?H.newMissingTyped(i.getType()):H.newProvided(i)}if(e==="optional"){let i=this.stringToTyped(r);return i instanceof h?Q.newMissing():new Q(i.getType(),i)}if(e==="list"){let[i,n]=r.split(Bt,2),o=n.split(",").map(u=>this.stringToTyped(`${i}:${u}`));return new gt(this.nativeToType(i),o)}if(e==="variadic"){let[i,n]=r.split(Bt,2),o=n.split(",").map(u=>this.stringToTyped(`${i}:${u}`));return new At(new pe(this.nativeToType(i)),o)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],n=r.split(w),a=i.split(w),o=n.map((c,p)=>this.stringToTyped(`${a[p]}:${c}`)),u=o.map(c=>c.getType());return new dt(new lt(...u),o)}if(e==="string")return r?mt.fromUTF8(r):new h;if(e==="uint8")return r?new It(Number(r)):new h;if(e==="uint16")return r?new Tt(Number(r)):new h;if(e==="uint32")return r?new bt(Number(r)):new h;if(e==="uint64")return r?new G(BigInt(r)):new h;if(e==="biguint")return r?new q(BigInt(r)):new h;if(e==="bool")return r?new at(typeof r=="boolean"?r:r==="true"):new h;if(e==="address")return r?new it(ae.newFromBech32(r)):new h;if(e==="token")return r?new M(r):new h;if(e==="hex")return r?ct.fromHex(r):new h;if(e==="codemeta")return new pt(oe.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let i=r.split(w);return new ce(this.nativeToType("esdt"),[new D(new M(i[0]),"token_identifier"),new D(new G(BigInt(i[1])),"token_nonce"),new D(new q(BigInt(i[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof ft)return"string";if(t instanceof Ct)return"uint8";if(t instanceof wt)return"uint16";if(t instanceof Wt)return"uint32";if(t instanceof z)return"uint64";if(t instanceof L)return"biguint";if(t instanceof st)return"bool";if(t instanceof nt)return"address";if(t instanceof j)return"token";if(t instanceof ot)return"hex";if(t instanceof ut)return"codemeta";if(t instanceof ht&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};import{ApiNetworkProvider as le}from"@multiversx/sdk-core/out";var 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 le(this.config.chainApiUrl,{timeout:3e4})}};var xt=class{constructor(t,e){this.config=t,this.url=new URL(e),this.serializer=new x,this.contractLoader=new S(t)}createTransactionForExecute(t,e,r){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=Vt.newFromBech32(this.config.userAddress),n=Vt.newFromBech32(t.address),a=new We({chainID:T(this.config.env)}),o=this.getCombinedInputs(t,e),c=this.getModifiedInputs(t,o).map(B=>this.serializer.stringToTyped(B)),p=this.getNativeValueFromField(t,e),l=this.getNativeValueFromUrl(t),b=BigInt(p||l||t.value||0),C=this.getCombinedTokenTransfers(t,r);return n.isContractAddress()?new he({config:a}).createTransactionForExecute({sender:i,contract:n,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:C,nativeTransferAmount:b}):new be({config:a}).createTransactionForTransfer({sender:i,receiver:n,nativeAmount:b,tokenTransfers:C,data:c[0]?.hasExactClass(ye.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 de(this.config.chainApiUrl,{timeout:3e4}),i=new ge({networkProvider:r}),n=await this.getAbiForAction(t),a=this.getModifiedInputs(t,e),u=this.getCombinedInputs(t,a).map(F=>this.serializer.stringToTyped(F)),c=new me({queryRunner:i,abi:n}),p=c.createQuery({contract:t.address,function:t.func,arguments:u}),l=await c.runQuery(p),b=new fe,C={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(F=>Buffer.from(F))},B=l.function,kt=n.getEndpoint(B),K=b.parseQueryResponse(C,kt).firstValue;if(!K)throw new Error("WarpActionExecutor: Query result not found");return K}getArgumentsForInputs(t,e){let r=this.getModifiedInputs(t,e);return this.getCombinedInputs(t,r)}getNativeValueFromField(t,e){let r=(t.inputs||[]).findIndex(n=>n.source==="field"&&n.position==="value"),i=r!==-1?e[r]:null;return i?i.split(":")[1]:null}getNativeValueFromUrl(t){let e=new URLSearchParams(this.url.search),i=t.inputs?.filter(n=>n.source==="query")?.find(n=>n.position==="value")?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,e){return[...t.transfers?.map(this.toTypedTransfer)||[],...e]}getModifiedInputs(t,e){let r=Object.fromEntries(e.entries());return(t.inputs?.filter(n=>!!n.modifier)||[]).forEach((n,a)=>{if(n.modifier?.startsWith("scale:")){let[,o]=n.modifier.split(":");if(isNaN(Number(o))){let u=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:a,c=t.inputs?.find(B=>B.name===o);if(!c)throw new Error(`WarpActionExecutor: Scalable input ${o} not found`);let p=Number(c.position.split(":")[1])-1,l=r[p].split(":")[1],b=r[u].split(":")[1],C=N(b,+l);r[u]=`${n.type}:${C}`}else{let u=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:a,c=r[u].split(":")[1],p=N(c,+o);r[u]=`${n.type}:${p}`}}}),Object.values(r)}getCombinedInputs(t,e){let r=t.inputs?.filter(o=>o.position.startsWith("arg:"))||[],i=(o,u)=>o.source==="query"?this.serializer.nativeToString(o.type,this.url.searchParams.get(o.name)||""):e[u],n=r.map((o,u)=>({input:o,value:i(o,u)})),a="args"in t?t.args:[];return n.forEach(({input:o,value:u})=>{let c=Number(o.position.split(":")[1])-1;a.splice(c,0,u)}),a}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 vt.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 vt.create(r)}toTypedTransfer(t){return new Te({token:new we({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Ft,ApiNetworkProvider as Se,TransactionsFactoryConfig as Pe,TransferTransactionsFactory as Re}from"@multiversx/sdk-core";import Ue from"ajv";var A={Warp:s=>`warp:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},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()}};import Ve from"qr-code-styling";import{AbiRegistry as St,Address as g,AddressValue as Pt,ApiNetworkProvider as Rt,BytesValue as m,QueryRunnerAdapter as Ie,SmartContractQueriesController as Ae,SmartContractTransactionsFactory as Be,TransactionsFactoryConfig as ve}from"@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 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?[m.fromHex(t),m.fromUTF8(e)]:[m.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromUTF8(t),m.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromUTF8(e)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromHex(e)]})}async getInfoByAlias(t,e){let r=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 i=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.fromUTF8(t)]}),o=await n.runQuery(a),[u]=n.parseQueryResponse(o),c=u?V(u):null,p=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:p},e.ttl),{registryInfo:c,brand:p}}async getInfoByHash(t,e){let r=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 i=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByHash",arguments:[m.fromHex(t)]}),o=await n.runQuery(a),[u]=n.parseQueryResponse(o),c=u?V(u):null,p=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:p},e.ttl),{registryInfo:c,brand:p}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),i=this.getController(),n=i.createQuery({contract:r,function:"getUserWarps",arguments:[new Pt(new g(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a);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 Pt(new g(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a),u=o.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(u.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}async fetchBrand(t,e){let r=A.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=new Rt(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(t),a=JSON.parse(n.data.toString());return a.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,a,e.ttl),a}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),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:[]}),i=await e.runQuery(r),[n]=e.parseQueryResponse(i),a=BigInt(n.toString());this.unitPrice=a}getFactory(){let t=new ve({chainID:T(this.config.env)}),e=St.create(J);return new Be({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env),e=new Rt(t,{timeout:3e4}),r=new Ie({networkProvider:e}),i=St.create(J);return new Ae({queryRunner:r,abi:i})}};var R=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(y.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),o=a.length>0,u=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:u}}async detect(t){let e=t.startsWith(y.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):W.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,n=new U(this.config),a=new P(this.config),o=null,u=null,c=null;if(r==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:p,brand:l}=await a.getInfoByHash(i);u=p,c=l}catch{}}else if(r==="alias"){let{registryInfo:p,brand:l}=await a.getInfoByAlias(i);u=p,c=l,p&&(o=await n.createFromTransactionHash(p.hash))}return o?{match:!0,url:t,warp:o,registryInfo:u,brand:c}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||d.DefaultClientUrl(this.config.env),i=t===y.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+y.IdentifierParamSeparator+e);return d.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${y.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",n="black",a="#23F7DD"){let o=this.build(t,e);return new Ve({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(a)}" 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),i=e.searchParams.get(y.IdentifierParamName),n=r&&!i?e.pathname.split("/")[1]:i;if(!n)return null;let a=decodeURIComponent(n);return W.getInfoFromPrefixedIdentifier(a)}};var xe="https://",Ut="query",W=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),i=(n,a)=>{r=r.replace(new RegExp(`{{${n.toUpperCase()}}}`,"g"),a)};return Object.entries(t.vars).forEach(([n,a])=>{if(typeof a=="string"&&a.startsWith(`${Ut}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${Ut}:`)[1],u=new URL(e.currentUrl).searchParams.get(o);u&&i(n,u)}else i(n,a)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(y.IdentifierParamSeparator)?e:`${y.DefaultIdentifierType}${y.IdentifierParamSeparator}${e}`,[i,n]=r.split(y.IdentifierParamSeparator);return{type:i,id:n}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(xe))return t.next;{let r=new R(e),i=s.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}};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 Pe({chainID:T(this.config.env)}),r=new Re({config:e}),i=JSON.stringify(t),n=r.createTransactionForTransfer({sender:Ft.newFromBech32(this.config.userAddress),receiver:Ft.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 this.ensureValidSchema(r),W.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=A.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=new Se(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(t),a=await this.createFromTransaction(n);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}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 this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Z(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||d.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),n=new Ue,a=n.compile(i);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};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{Y as BrandBuilder,d as Config,xt as WarpActionExecutor,x as WarpArgSerializer,U as WarpBuilder,y as WarpConstants,S as WarpContractLoader,Nt as WarpIndex,R as WarpLink,P as WarpRegistry,W as WarpUtils,or as address,sr as biguint,ar as boolean,lr as codemeta,Ye as composite,pr as esdt,T as getChainId,v as getLatestProtocolIdentifier,ur as hex,Ze as list,dr as nothing,Je as option,Ke as optional,N as shiftBigintBy,tr as string,Z as toPreviewText,V as toTypedRegistryInfo,cr as token,rr as u16,nr as u32,ir as u64,er as u8,Xe as variadic};
1
+ import{Address as X,ApiNetworkProvider as kt,TransactionsFactoryConfig as Ot,TransferTransactionsFactory as Lt}from"@multiversx/sdk-core";import qt from"ajv";var d={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.4.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.4.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="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=s=>s==="devnet"?"D":s==="testnet"?"T":"1",v=s=>`${s}:${d.LatestProtocolVersion}`,V=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),N=(s,t)=>{let e=s.toString(),[r,i=""]=e.split("."),n=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(n,"0"));if(t<0){let a=r+i;if(n>=a.length)return 0n;let o=a.slice(0,-n)||"0";return BigInt(o)}else return BigInt(s)},Z=(s,t=100)=>{if(!s)return"";let e=s.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 Y=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 Ot({chainID:T(this.config.env)}),r=new Lt({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:X.newFromBech32(this.config.userAddress),receiver:X.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 kt(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,i=await(await fetch(e)).json(),n=new qt,a=n.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};var y={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",DefaultIdentifierType:"alias",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import{Address as Dt,AddressValue as _t,BigUIntType as Qt,BigUIntValue as tt,BooleanValue as Ht,BytesValue as jt,CodeMetadata as Mt,CodeMetadataValue as zt,CompositeType as Gt,CompositeValue as Jt,Field as E,FieldDefinition as $,List as Kt,NothingValue as Zt,OptionalValue as k,OptionValue as O,StringValue as Xt,Struct as Yt,StructType as te,TokenIdentifierType as ee,TokenIdentifierValue as et,U16Value as re,U32Value as ne,U64Type as ie,U64Value as rt,U8Value as se,VariadicValue as ae}from"@multiversx/sdk-core/out";var Ke=(s,t)=>s?O.newProvided(s):t?O.newMissingTyped(t):O.newMissing(),Ze=(s,t)=>s?new k(s.getType(),s):t?new k(t):k.newMissing(),Xe=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new Kt(t,s)},Ye=s=>ae.fromItems(...s),tr=s=>{let t=s.map(e=>e.getType());return new Jt(new Gt(...t),s)},er=s=>Xt.fromUTF8(s),rr=s=>new se(s),nr=s=>new re(s),ir=s=>new ne(s),sr=s=>new rt(s),ar=s=>new tt(BigInt(s)),or=s=>new Ht(s),cr=s=>new _t(Dt.newFromBech32(s)),ur=s=>new et(s),pr=s=>jt.fromHex(s),lr=s=>new Yt(new te("EsdtTokenPayment",[new $("token_identifier","",new ee),new $("token_nonce","",new ie),new $("amount","",new Qt)]),[new E(new et(s.token.identifier),"token_identifier"),new E(new rt(BigInt(s.token.nonce)),"token_nonce"),new E(new tt(BigInt(s.amount)),"amount")]),dr=s=>new zt(Mt.fromBuffer(Buffer.from(s,"hex"))),gr=()=>new Zt;import{AbiRegistry as vt,Address as Vt,ApiNetworkProvider as ge,QueryRunnerAdapter as fe,ResultsParser as me,SmartContractQueriesController as he,SmartContractTransactionsFactory as ye,StringValue as we,Token as Te,TokenTransfer as We,TransactionsFactoryConfig as be,TransferTransactionsFactory as Ce}from"@multiversx/sdk-core/out";import{Address as oe,AddressType as nt,AddressValue as it,BigUIntType as L,BigUIntValue as q,BooleanType as st,BooleanValue as at,BytesType as ot,BytesValue as ct,CodeMetadata as ce,CodeMetadataType as ut,CodeMetadataValue as pt,CompositeType as lt,CompositeValue as dt,Field as D,FieldDefinition as _,List as gt,NothingValue as h,OptionalValue as Q,OptionValue as H,StringType as ft,StringValue as mt,Struct as ue,StructType as ht,Token as pe,TokenIdentifierType as j,TokenIdentifierValue as M,TokenTransfer as yt,U16Type as wt,U16Value as Tt,U32Type as Wt,U32Value as bt,U64Type as z,U64Value as G,U8Type as Ct,U8Value as It,VariadicType as le,VariadicValue as At}from"@multiversx/sdk-core/out";var f=":",w="|",Bt=new RegExp(`${f}(.*)`),x=class{nativeToString(t,e){return t==="esdt"&&e instanceof yt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(H.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(Q.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(gt.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToString(a).split(f)[0])[0],n=e.map(a=>this.typedToString(a).split(f)[1]);return`list:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(At.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToString(a).split(f)[0])[0],n=e.map(a=>this.typedToString(a).split(f)[1]);return`variadic:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(dt.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(f)[0]),i=e.map(o=>this.typedToString(o).split(f)[1]),n=r.join(w),a=i.join(w);return`composite(${n}):${a}`}if(t.hasClassOrSuperclass(q.ClassName))return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(It.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Tt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(bt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(G.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(mt.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(at.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(it.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(M.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(ct.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(pt.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 lt(...e.split(w).map(r=>this.nativeToType(r)))}if(t==="string")return new ft;if(t==="uint8")return new Ct;if(t==="uint16")return new wt;if(t==="uint32")return new Wt;if(t==="uint64")return new z;if(t==="biguint")return new L;if(t==="bool")return new st;if(t==="address")return new nt;if(t==="token")return new j;if(t==="hex")return new ot;if(t==="codemeta")return new ut;if(t==="esdt"||t==="nft")return new ht("EsdtTokenPayment",[new _("token_identifier","",new j),new _("token_nonce","",new z),new _("amount","",new L)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(f),r=e[0],i=e.slice(1).join(f);if(r==="null")return[r,null];if(r==="option"){let[n,a]=i.split(f);return[`option:${n}`,a||null]}else if(r==="optional"){let[n,a]=i.split(f);return[`optional:${n}`,a||null]}else if(r==="list"){let n=i.split(f),a=n.slice(0,-1).join(f),o=n[n.length-1],c=(o?o.split(","):[]).map(p=>this.stringToNative(`${a}:${p}`)[1]);return[`list:${a}`,c]}else if(r==="variadic"){let n=i.split(f),a=n.slice(0,-1).join(f),o=n[n.length-1],c=(o?o.split(","):[]).map(p=>this.stringToNative(`${a}:${p}`)[1]);return[`variadic:${a}`,c]}else if(r.startsWith("composite")){let n=r.match(/\(([^)]+)\)/)?.[1]?.split(w),o=i.split(w).map((u,c)=>this.stringToNative(`${n[c]}:${u}`)[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,a,o]=i.split(w);return[r,new yt({token:new pe({identifier:n,nonce:BigInt(a)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new h;if(e==="option"){let i=this.stringToTyped(r);return i instanceof h?H.newMissingTyped(i.getType()):H.newProvided(i)}if(e==="optional"){let i=this.stringToTyped(r);return i instanceof h?Q.newMissing():new Q(i.getType(),i)}if(e==="list"){let[i,n]=r.split(Bt,2),o=n.split(",").map(u=>this.stringToTyped(`${i}:${u}`));return new gt(this.nativeToType(i),o)}if(e==="variadic"){let[i,n]=r.split(Bt,2),o=n.split(",").map(u=>this.stringToTyped(`${i}:${u}`));return new At(new le(this.nativeToType(i)),o)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],n=r.split(w),a=i.split(w),o=n.map((c,p)=>this.stringToTyped(`${a[p]}:${c}`)),u=o.map(c=>c.getType());return new dt(new lt(...u),o)}if(e==="string")return r?mt.fromUTF8(r):new h;if(e==="uint8")return r?new It(Number(r)):new h;if(e==="uint16")return r?new Tt(Number(r)):new h;if(e==="uint32")return r?new bt(Number(r)):new h;if(e==="uint64")return r?new G(BigInt(r)):new h;if(e==="biguint")return r?new q(BigInt(r)):new h;if(e==="bool")return r?new at(typeof r=="boolean"?r:r==="true"):new h;if(e==="address")return r?new it(oe.newFromBech32(r)):new h;if(e==="token")return r?new M(r):new h;if(e==="hex")return r?ct.fromHex(r):new h;if(e==="codemeta")return new pt(ce.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let i=r.split(w);return new ue(this.nativeToType("esdt"),[new D(new M(i[0]),"token_identifier"),new D(new G(BigInt(i[1])),"token_nonce"),new D(new q(BigInt(i[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof ft)return"string";if(t instanceof Ct)return"uint8";if(t instanceof wt)return"uint16";if(t instanceof Wt)return"uint32";if(t instanceof z)return"uint64";if(t instanceof L)return"biguint";if(t instanceof st)return"bool";if(t instanceof nt)return"address";if(t instanceof j)return"token";if(t instanceof ot)return"hex";if(t instanceof ut)return"codemeta";if(t instanceof ht&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};import{ApiNetworkProvider as de}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 de(this.config.chainApiUrl,{timeout:3e4})}};var xt=class{constructor(t,e){this.config=t,this.url=new URL(e),this.serializer=new x,this.contractLoader=new S(t)}createTransactionForExecute(t,e,r){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=Vt.newFromBech32(this.config.userAddress),n=Vt.newFromBech32(t.address),a=new be({chainID:T(this.config.env)}),o=this.getCombinedInputs(t,e),c=this.getModifiedInputs(t,o).map(B=>this.serializer.stringToTyped(B)),p=this.getNativeValueFromField(t,e),l=this.getNativeValueFromUrl(t),b=BigInt(p||l||t.value||0),C=this.getCombinedTokenTransfers(t,r);return n.isContractAddress()?new ye({config:a}).createTransactionForExecute({sender:i,contract:n,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:C,nativeTransferAmount:b}):new Ce({config:a}).createTransactionForTransfer({sender:i,receiver:n,nativeAmount:b,tokenTransfers:C,data:c[0]?.hasExactClass(we.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 ge(this.config.chainApiUrl,{timeout:3e4}),i=new fe({networkProvider:r}),n=await this.getAbiForAction(t),a=this.getModifiedInputs(t,e),u=this.getCombinedInputs(t,a).map(F=>this.serializer.stringToTyped(F)),c=new he({queryRunner:i,abi:n}),p=c.createQuery({contract:t.address,function:t.func,arguments:u}),l=await c.runQuery(p),b=new me,C={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(F=>Buffer.from(F))},B=l.function,$t=n.getEndpoint(B),K=b.parseQueryResponse(C,$t).firstValue;if(!K)throw new Error("WarpActionExecutor: Query result not found");return K}async executeCollect(t,e){let r=new URL(t.destination.url),i=new Headers;return Object.entries(t.destination.headers).forEach(([o,u])=>{i.set(o,u)}),await(await fetch(r,{method:t.destination.method,headers:i,body:JSON.stringify({inputs:e})})).json()}getArgumentsForInputs(t,e){let r=this.getModifiedInputs(t,e);return this.getCombinedInputs(t,r)}getNativeValueFromField(t,e){let r=(t.inputs||[]).findIndex(n=>n.source==="field"&&n.position==="value"),i=r!==-1?e[r]:null;return i?i.split(":")[1]:null}getNativeValueFromUrl(t){let e=new URLSearchParams(this.url.search),i=t.inputs?.filter(n=>n.source==="query")?.find(n=>n.position==="value")?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,e){return[...t.transfers?.map(this.toTypedTransfer)||[],...e]}getModifiedInputs(t,e){let r=Object.fromEntries(e.entries());return(t.inputs?.filter(n=>!!n.modifier)||[]).forEach((n,a)=>{if(n.modifier?.startsWith("scale:")){let[,o]=n.modifier.split(":");if(isNaN(Number(o))){let u=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:a,c=t.inputs?.find(B=>B.name===o);if(!c)throw new Error(`WarpActionExecutor: Scalable input ${o} not found`);let p=Number(c.position.split(":")[1])-1,l=r[p].split(":")[1],b=r[u].split(":")[1],C=N(b,+l);r[u]=`${n.type}:${C}`}else{let u=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:a,c=r[u].split(":")[1],p=N(c,+o);r[u]=`${n.type}:${p}`}}}),Object.values(r)}getCombinedInputs(t,e){let r=t.inputs?.filter(o=>o.position.startsWith("arg:"))||[],i=(o,u)=>o.source==="query"?this.serializer.nativeToString(o.type,this.url.searchParams.get(o.name)||""):e[u],n=r.map((o,u)=>({input:o,value:i(o,u)})),a="args"in t?t.args:[];return n.forEach(({input:o,value:u})=>{let c=Number(o.position.split(":")[1])-1;a.splice(c,0,u)}),a}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 vt.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 vt.create(r)}toTypedTransfer(t){return new We({token:new Te({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Nt,ApiNetworkProvider as Pe,TransactionsFactoryConfig as Re,TransferTransactionsFactory as Ue}from"@multiversx/sdk-core";import Fe from"ajv";var A={Warp:s=>`warp:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},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()}};import xe from"qr-code-styling";import{AbiRegistry as St,Address as g,AddressValue as Pt,ApiNetworkProvider as Rt,BytesValue as m,QueryRunnerAdapter as Ae,SmartContractQueriesController as Be,SmartContractTransactionsFactory as ve,TransactionsFactoryConfig as Ve}from"@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 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?[m.fromHex(t),m.fromUTF8(e)]:[m.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[m.fromHex(t)]})}createWarpUpgradeTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromUTF8(t),m.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromUTF8(e)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[m.fromHex(t),m.fromHex(e)]})}async getInfoByAlias(t,e){let r=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 i=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[m.fromUTF8(t)]}),o=await n.runQuery(a),[u]=n.parseQueryResponse(o),c=u?V(u):null,p=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:p},e.ttl),{registryInfo:c,brand:p}}async getInfoByHash(t,e){let r=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 i=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByHash",arguments:[m.fromHex(t)]}),o=await n.runQuery(a),[u]=n.parseQueryResponse(o),c=u?V(u):null,p=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:p},e.ttl),{registryInfo:c,brand:p}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),i=this.getController(),n=i.createQuery({contract:r,function:"getUserWarps",arguments:[new Pt(new g(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a);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 Pt(new g(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a),u=o.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(u.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}async fetchBrand(t,e){let r=A.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=new Rt(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(t),a=JSON.parse(n.data.toString());return a.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,a,e.ttl),a}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),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:[]}),i=await e.runQuery(r),[n]=e.parseQueryResponse(i),a=BigInt(n.toString());this.unitPrice=a}getFactory(){let t=new Ve({chainID:T(this.config.env)}),e=St.create(J);return new ve({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env),e=new Rt(t,{timeout:3e4}),r=new Ae({networkProvider:e}),i=St.create(J);return new Be({queryRunner:r,abi:i})}};var R=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(y.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),a=(await Promise.all(i)).filter(c=>c.match),o=a.length>0,u=a.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:u}}async detect(t){let e=t.startsWith(y.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):W.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,n=new U(this.config),a=new P(this.config),o=null,u=null,c=null;if(r==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:p,brand:l}=await a.getInfoByHash(i);u=p,c=l}catch{}}else if(r==="alias"){let{registryInfo:p,brand:l}=await a.getInfoByAlias(i);u=p,c=l,p&&(o=await n.createFromTransactionHash(p.hash))}return o?{match:!0,url:t,warp:o,registryInfo:u,brand:c}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||d.DefaultClientUrl(this.config.env),i=t===y.DefaultIdentifierType?encodeURIComponent(e):encodeURIComponent(t+y.IdentifierParamSeparator+e);return d.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${y.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",n="black",a="#23F7DD"){let o=this.build(t,e);return new xe({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color: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(a)}" 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),i=e.searchParams.get(y.IdentifierParamName),n=r&&!i?e.pathname.split("/")[1]:i;if(!n)return null;let a=decodeURIComponent(n);return W.getInfoFromPrefixedIdentifier(a)}};var Se="https://",Ut="query",Ft="env",W=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),i=(n,a)=>{r=r.replace(new RegExp(`{{${n.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(t.vars).forEach(([n,a])=>{if(typeof a=="string"&&a.startsWith(`${Ut}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${Ut}:`)[1],u=new URL(e.currentUrl).searchParams.get(o);u&&i(n,u)}else if(typeof a=="string"&&a.startsWith(`${Ft}:`)){let o=a.split(`${Ft}:`)[1],u=e.vars?.[o];u&&i(n,u)}else i(n,a)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(y.IdentifierParamSeparator)?e:`${y.DefaultIdentifierType}${y.IdentifierParamSeparator}${e}`,[i,n]=r.split(y.IdentifierParamSeparator);return{type:i,id:n}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(Se))return t.next;{let r=new R(e),i=s.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}};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 Re({chainID:T(this.config.env)}),r=new Ue({config:e}),i=JSON.stringify(t),n=r.createTransactionForTransfer({sender:Nt.newFromBech32(this.config.userAddress),receiver:Nt.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 this.ensureValidSchema(r),W.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=A.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=new Pe(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(t),a=await this.createFromTransaction(n);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}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 this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Z(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||d.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),n=new Fe,a=n.compile(i);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};var Et=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{Y as BrandBuilder,d as Config,xt as WarpActionExecutor,x as WarpArgSerializer,U as WarpBuilder,y as WarpConstants,S as WarpContractLoader,Et as WarpIndex,R as WarpLink,P as WarpRegistry,W as WarpUtils,cr as address,ar as biguint,or as boolean,dr as codemeta,tr as composite,lr as esdt,T as getChainId,v as getLatestProtocolIdentifier,pr as hex,Xe as list,gr as nothing,Ke as option,Ze as optional,N as shiftBigintBy,er as string,Z as toPreviewText,V as toTypedRegistryInfo,ur as token,nr as u16,ir as u32,sr as u64,rr as u8,Ye as variadic};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",