@vleap/warps 0.3.4 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Transaction, TransactionOnNetwork } from '@multiversx/sdk-core';
2
- import { TokenTransfer, Transaction as Transaction$1, TypedValue, Type } from '@multiversx/sdk-core/out';
2
+ import { TypedValue, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, CodeMetadataValue, NothingValue, TokenTransfer, Transaction as Transaction$1, Type } from '@multiversx/sdk-core/out';
3
3
  import QRCodeStyling from 'qr-code-styling';
4
4
 
5
5
  type ChainEnv = 'mainnet' | 'testnet' | 'devnet';
@@ -188,6 +188,24 @@ declare const IdentifierParamName = "warp";
188
188
  declare const IdentifierParamSeparator = ":";
189
189
  declare const DefaultIdentifierType = "alias";
190
190
 
191
+ declare const option: (value: TypedValue | null) => OptionValue;
192
+ declare const optional: (value: TypedValue | null) => OptionalValue;
193
+ declare const list: (values: TypedValue[]) => List;
194
+ declare const variadic: (values: TypedValue[]) => VariadicValue;
195
+ declare const composite: (values: TypedValue[]) => CompositeValue;
196
+ declare const string: (value: string) => StringValue;
197
+ declare const u8: (value: number) => U8Value;
198
+ declare const u16: (value: number) => U16Value;
199
+ declare const u32: (value: number) => U32Value;
200
+ declare const u64: (value: bigint) => U64Value;
201
+ declare const biguint: (value: bigint) => BigUIntValue;
202
+ declare const boolean: (value: boolean) => BooleanValue;
203
+ declare const address: (value: string) => AddressValue;
204
+ declare const token: (value: string) => TokenIdentifierValue;
205
+ declare const hex: (value: string) => BytesValue;
206
+ declare const codemeta: (hexString: string) => CodeMetadataValue;
207
+ declare const nothing: () => NothingValue;
208
+
191
209
  declare class WarpActionExecutor {
192
210
  private config;
193
211
  private url;
@@ -309,4 +327,4 @@ declare class WarpUtils {
309
327
  static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
310
328
  }
311
329
 
312
- export { type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, type ChainEnv, Config, DefaultIdentifierType, HttpProtocolPrefix, IdentifierParamName, IdentifierParamSeparator, 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, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, type WarpNativeValue, type WarpQueryAction, WarpRegistry, WarpUtils, type WarpVarPlaceholder };
330
+ export { type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, type ChainEnv, Config, DefaultIdentifierType, HttpProtocolPrefix, IdentifierParamName, IdentifierParamSeparator, 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, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, type WarpNativeValue, type WarpQueryAction, WarpRegistry, WarpUtils, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, hex, list, nothing, option, optional, string, token, u16, u32, u64, u8, variadic };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Transaction, TransactionOnNetwork } from '@multiversx/sdk-core';
2
- import { TokenTransfer, Transaction as Transaction$1, TypedValue, Type } from '@multiversx/sdk-core/out';
2
+ import { TypedValue, OptionValue, OptionalValue, List, VariadicValue, CompositeValue, StringValue, U8Value, U16Value, U32Value, U64Value, BigUIntValue, BooleanValue, AddressValue, TokenIdentifierValue, BytesValue, CodeMetadataValue, NothingValue, TokenTransfer, Transaction as Transaction$1, Type } from '@multiversx/sdk-core/out';
3
3
  import QRCodeStyling from 'qr-code-styling';
4
4
 
5
5
  type ChainEnv = 'mainnet' | 'testnet' | 'devnet';
@@ -188,6 +188,24 @@ declare const IdentifierParamName = "warp";
188
188
  declare const IdentifierParamSeparator = ":";
189
189
  declare const DefaultIdentifierType = "alias";
190
190
 
191
+ declare const option: (value: TypedValue | null) => OptionValue;
192
+ declare const optional: (value: TypedValue | null) => OptionalValue;
193
+ declare const list: (values: TypedValue[]) => List;
194
+ declare const variadic: (values: TypedValue[]) => VariadicValue;
195
+ declare const composite: (values: TypedValue[]) => CompositeValue;
196
+ declare const string: (value: string) => StringValue;
197
+ declare const u8: (value: number) => U8Value;
198
+ declare const u16: (value: number) => U16Value;
199
+ declare const u32: (value: number) => U32Value;
200
+ declare const u64: (value: bigint) => U64Value;
201
+ declare const biguint: (value: bigint) => BigUIntValue;
202
+ declare const boolean: (value: boolean) => BooleanValue;
203
+ declare const address: (value: string) => AddressValue;
204
+ declare const token: (value: string) => TokenIdentifierValue;
205
+ declare const hex: (value: string) => BytesValue;
206
+ declare const codemeta: (hexString: string) => CodeMetadataValue;
207
+ declare const nothing: () => NothingValue;
208
+
191
209
  declare class WarpActionExecutor {
192
210
  private config;
193
211
  private url;
@@ -309,4 +327,4 @@ declare class WarpUtils {
309
327
  static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
310
328
  }
311
329
 
312
- export { type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, type ChainEnv, Config, DefaultIdentifierType, HttpProtocolPrefix, IdentifierParamName, IdentifierParamSeparator, 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, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, type WarpNativeValue, type WarpQueryAction, WarpRegistry, WarpUtils, type WarpVarPlaceholder };
330
+ export { type BaseWarpActionInputType, type Brand, BrandBuilder, type BrandColors, type BrandCta, type BrandMeta, type BrandUrls, type ChainEnv, Config, DefaultIdentifierType, HttpProtocolPrefix, IdentifierParamName, IdentifierParamSeparator, 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, type WarpContract, type WarpContractAction, type WarpContractActionTransfer, WarpContractLoader, type WarpContractVerification, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, type WarpNativeValue, type WarpQueryAction, WarpRegistry, WarpUtils, type WarpVarPlaceholder, address, biguint, boolean, codemeta, composite, hex, list, nothing, option, optional, string, token, u16, u32, u64, u8, variadic };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var X=Object.create;var F=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var rt=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var nt=(o,t)=>{for(var r in t)F(o,r,{get:t[r],enumerable:!0})},H=(o,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of tt(t))!et.call(o,i)&&i!==r&&F(o,i,{get:()=>t[i],enumerable:!(e=Y(t,i))||e.enumerable});return o};var q=(o,t,r)=>(r=o!=null?X(rt(o)):{},H(t||!o||!o.__esModule?F(r,"default",{value:o,enumerable:!0}):r,o)),it=o=>H(F({},"__esModule",{value:!0}),o);var ot={};nt(ot,{BrandBuilder:()=>$,Config:()=>l,DefaultIdentifierType:()=>B,HttpProtocolPrefix:()=>S,IdentifierParamName:()=>E,IdentifierParamSeparator:()=>W,WarpActionExecutor:()=>Q,WarpArgSerializer:()=>v,WarpBuilder:()=>V,WarpContractLoader:()=>x,WarpLink:()=>P,WarpRegistry:()=>R,WarpUtils:()=>T});module.exports=it(ot);var h=require("@multiversx/sdk-core"),M=q(require("ajv"));var l={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.2.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.2.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:o=>o==="devnet"?"https://devnet.usewarp.to":o==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:o=>o==="devnet"?["https://devnet.usewarp.to"]:o==="testnet"?["https://testnet.usewarp.to"]:["https://usewarp.to"],Chain:{ApiUrl:o=>o==="devnet"?"https://devnet-api.multiversx.com":o==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:o=>o==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":o==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var w=o=>o==="devnet"?"D":o==="testnet"?"T":"1",U=o=>`${o}:${l.LatestProtocolVersion}`,N=o=>({hash:o.hash.toString("hex"),alias:o.alias?.toString()||null,trust:o.trust.toString(),creator:o.creator.toString(),createdAt:o.created_at.toNumber(),brand:o.brand?.toString("hex")||null,upgrade:o.upgrade?.toString("hex")||null}),k=(o,t)=>{let r=o.toString(),[e,i=""]=r.split("."),s=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(s,"0"));if(t<0){let a=e+i;if(s>=a.length)return 0n;let p=a.slice(0,-s)||"0";return BigInt(p)}else return BigInt(o)},j=(o,t=100)=>{if(!o)return"";let r=o.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r};var $=class{constructor(t){this.pendingBrand={protocol:U(l.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new h.TransactionsFactoryConfig({chainID:w(this.config.env)}),e=new h.TransferTransactionsFactory({config:r}),i=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:h.Address.newFromBech32(this.config.userAddress),receiver:h.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}async createFromTransaction(t,r=!1){return await this.createFromRaw(t.data.toString(),r)}async createFromTransactionHash(t){let r=new h.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let e=await r.getTransaction(t);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),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,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.brandSchemaUrl||l.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),s=new M.default,a=s.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};var S="http",E="warp",W=":",B="alias";var g=require("@multiversx/sdk-core/out");var n=require("@multiversx/sdk-core/out"),v=class{nativeToStrings(t,r){return`${t}:${r?.toString()??""}`}nativeToTyped(t,r){if(t.startsWith("option:")){let[e,i]=t.split(":"),s=this.nativeToTyped(i,r);return r?n.OptionValue.newProvided(s):n.OptionValue.newMissingTyped(s.getType())}if(t.startsWith("optional:")){let[e,i]=t.split(":"),s=this.nativeToTyped(i,r);return r?new n.OptionalValue(s.getType(),s):n.OptionalValue.newMissing()}if(t.startsWith("list:")){let[e,i]=t.split(":"),a=r.split(",").map(p=>this.nativeToTyped(i,p));return new n.List(this.nativeToType(i),a)}if(t.startsWith("variadic:")){let[e,i]=t.split(":"),a=r.split(",").map(p=>this.nativeToTyped(i,p));return new n.VariadicValue(new n.VariadicType(new n.PrimitiveType("Custom")),a)}if(t.startsWith("composite:")){let[e,i]=t.split(":"),s=r.split("|"),a=i.split("|"),p=s.map((u,m)=>this.nativeToTyped(a[m],u)),d=a.map(u=>this.nativeToType(u));return new n.CompositeValue(new n.CompositeType(...d),p)}if(t==="string")return r?n.StringValue.fromUTF8(r):new n.NothingValue;if(t==="uint8")return r?new n.U8Value(Number(r)):new n.NothingValue;if(t==="uint16")return r?new n.U16Value(Number(r)):new n.NothingValue;if(t==="uint32")return r?new n.U32Value(Number(r)):new n.NothingValue;if(t==="uint64")return r?new n.U64Value(BigInt(r)):new n.NothingValue;if(t==="biguint")return r?new n.BigUIntValue(BigInt(r)):new n.NothingValue;if(t==="boolean")return r?new n.BooleanValue(typeof r=="boolean"?r:r==="true"):new n.NothingValue;if(t==="address")return r?new n.AddressValue(n.Address.newFromBech32(r)):new n.NothingValue;if(t==="token")return r?new n.TokenIdentifierValue(r):new n.NothingValue;if(t==="hex")return r?n.BytesValue.fromHex(r):new n.NothingValue;if(t==="codemeta")return new n.CodeMetadataValue(n.CodeMetadata.fromBuffer(Buffer.from(r,"hex")));throw new Error(`WarpArgSerializer (nativeToTyped): Unsupported input type: ${t}`)}typedToNative(t){if(t.hasClassOrSuperclass(n.OptionValue.ClassName)){if(!t.isSet())return["option",null];let[r,e]=this.typedToNative(t.getTypedValue());return[`option:${r}`,e]}if(t.hasClassOrSuperclass(n.OptionalValue.ClassName)){if(!t.isSet())return["optional",null];let[r,e]=this.typedToNative(t.getTypedValue());return[`optional:${r}`,e]}if(t.hasClassOrSuperclass(n.List.ClassName)){let r=t.getItems(),i=r.map(a=>this.typedToNative(a)[0])[0],s=r.map(a=>this.typedToNative(a)[1]);return[`list:${i}`,s.join(",")]}if(t.hasClassOrSuperclass(n.VariadicValue.ClassName)){let r=t.getItems(),i=r.map(a=>this.typedToNative(a)[0])[0],s=r.map(a=>this.typedToNative(a)[1]);return[`variadic:${i}`,s.join(",")]}if(t.hasClassOrSuperclass(n.CompositeValue.ClassName)){let r=t.getItems(),e=r.map(p=>this.typeToNative(p.getType())),i=r.map(p=>p.valueOf()),s=e.join("|"),a=i.join("|");return[`composite:${s}`,a]}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName))return["biguint",BigInt(t.valueOf().toFixed())];if(t.hasClassOrSuperclass(n.NumericalValue.ClassName))return["uint64",t.valueOf().toNumber()];if(t.hasClassOrSuperclass(n.StringValue.ClassName))return["string",t.valueOf()];if(t.hasClassOrSuperclass(n.BooleanValue.ClassName))return["boolean",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")];throw new Error(`WarpArgSerializer (typedToNative): Unsupported input type: ${t.getClassName()}`)}stringToNative(t){let[r,e]=t.split(":");return r==="address"?[r,e]:r==="boolean"?[r,e==="true"]:r==="biguint"?[r,BigInt(e||0)]:r==="uint8"||r==="uint16"||r==="uint32"||r==="uint64"?[r,Number(e)]:[r,e]}stringToTyped(t){let[r,e]=t.split(":");return this.nativeToTyped(r,e)}nativeToType(t){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==="boolean")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;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}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"boolean";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";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var z=require("@multiversx/sdk-core/out"),x=class{constructor(t){this.config=t}async getContract(t){try{let e=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:e.ownerAddress,verified:e.isVerified}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t){try{let e=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{codeHash:e.codeHash,abi:e.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}getConfiguredChainApi(){if(!this.config.chainApiUrl)throw new Error("WarpContract: Chain API URL not set");return new z.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4})}};var Q=class{constructor(t,r){this.config=t,this.url=new URL(r),this.serializer=new v,this.contractLoader=new x(t)}createTransactionForExecute(t,r,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=g.Address.newFromBech32(this.config.userAddress),s=g.Address.newFromBech32(t.address),a=new g.TransactionsFactoryConfig({chainID:w(this.config.env)}),p=this.getModifiedInputs(t,r),u=this.getCombinedInputs(t,p).map(L=>this.serializer.stringToTyped(L)),m=this.getNativeValueFromField(t,p),f=this.getNativeValueFromUrl(t),C=BigInt(m||f||t.value||0),b=this.getCombinedTokenTransfers(t,e);return s.isContractAddress()?new g.SmartContractTransactionsFactory({config:a}).createTransactionForExecute({sender:i,contract:s,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:u,tokenTransfers:b,nativeTransferAmount:C}):new g.TransferTransactionsFactory({config:a}).createTransactionForTransfer({sender:i,receiver:s,nativeAmount:C,tokenTransfers:b,data:u[0]?.hasExactClass(g.StringValue.ClassName)?u[0].valueOf():void 0})}async executeQuery(t,r){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let e=new g.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4}),i=new g.QueryRunnerAdapter({networkProvider:e}),s=await this.getAbiForAction(t),a=this.getModifiedInputs(t,r),d=this.getCombinedInputs(t,a).map(O=>this.serializer.stringToTyped(O)),u=new g.SmartContractQueriesController({queryRunner:i,abi:s}),m=u.createQuery({contract:t.address,function:t.func,arguments:d}),f=await u.runQuery(m),C=new g.ResultsParser,b={returnCode:f.returnCode,returnMessage:f.returnMessage,getReturnDataParts:()=>f.returnDataParts.map(O=>Buffer.from(O))},L=f.function,Z=s.getEndpoint(L),_=C.parseQueryResponse(b,Z).firstValue;if(!_)throw new Error("WarpActionExecutor: Query result not found");return _}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let r=await this.contractLoader.getVerificationInfo(t.address);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return g.AbiRegistry.create(r.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");let e=await(await fetch(t.abi)).json();return g.AbiRegistry.create(e)}getNativeValueFromField(t,r){let e=(t.inputs||[]).findIndex(s=>s.source==="field"&&s.position==="value"),i=e!==-1?r[e]:null;return i?i.split(":")[1]:null}getNativeValueFromUrl(t){let r=new URLSearchParams(this.url.search),i=t.inputs?.filter(s=>s.source==="query")?.find(s=>s.position==="value")?.name;return i?r.get(i):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputs(t,r){return(t.inputs?.filter(i=>!!i.modifier)||[]).forEach((i,s)=>{if(i.modifier?.startsWith("scale:")){let[,a]=i.modifier.split(":");if(isNaN(Number(a))){let p=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:s,d=t.inputs?.find(b=>b.name===a);if(!d)throw new Error(`WarpActionExecutor: Scalable input ${a} not found`);let u=Number(d.position.split(":")[1])-1,m=r[u].split(":")[1],f=r[p].split(":")[1],C=k(f,+m);r[p]=`${i.type}:${C}`}else{let p=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:s,d=r[p].split(":")[1],u=k(d,+a);r[p]=`${i.type}:${u}`}}}),r}getCombinedInputs(t,r){let i=(t.inputs?.filter(a=>a.source==="field"&&a.position.startsWith("arg:"))||[]).map((a,p)=>({input:a,value:r[p]})),s="args"in t?t.args:[];return i.forEach(({input:a,value:p})=>{let d=Number(a.position.split(":")[1])-1;s.splice(d,0,p)}),s}toTypedTransfer(t){return new g.TokenTransfer({token:new g.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var y=require("@multiversx/sdk-core"),K=q(require("ajv"));var A={Warp:o=>`warp:${o}`,RegistryInfo:o=>`registry-info:${o}`,Brand:o=>`brand:${o}`},I=class{constructor(){this.cache=new Map}set(t,r,e){let i=Date.now()+e*1e3;this.cache.set(t,{value:r,expiresAt:i})}get(t){let r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):r.value:null}clear(){this.cache.clear()}};var G=q(require("qr-code-styling"));var c=require("@multiversx/sdk-core/out");var D={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var R=class{constructor(t){this.cache=new I;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,r){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 e=r?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:r?[c.BytesValue.fromHex(t),c.BytesValue.fromUTF8(r)]:[c.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[c.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,r){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:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromUTF8(t),c.BytesValue.fromHex(r)]})}createWarpAliasSetTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromHex(t),c.BytesValue.fromUTF8(r)]})}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:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromHex(t),c.BytesValue.fromHex(r)]})}async getInfoByAlias(t,r){let e=A.RegistryInfo(t);if(r){let f=this.cache.get(e);if(f)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),f}let i=l.Registry.Contract(this.config.env),s=this.getController(),a=s.createQuery({contract:i,function:"getInfoByAlias",arguments:[c.BytesValue.fromUTF8(t)]}),p=await s.runQuery(a),[d]=s.parseQueryResponse(p),u=d?N(d):null,m=u?.brand?await this.fetchBrand(u.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:u,brand:m},r.ttl),{registryInfo:u,brand:m}}async getInfoByHash(t,r){let e=A.RegistryInfo(t);if(r){let f=this.cache.get(e);if(f)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),f}let i=l.Registry.Contract(this.config.env),s=this.getController(),a=s.createQuery({contract:i,function:"getInfoByHash",arguments:[c.BytesValue.fromHex(t)]}),p=await s.runQuery(a),[d]=s.parseQueryResponse(p),u=d?N(d):null,m=u?.brand?await this.fetchBrand(u.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:u,brand:m},r.ttl),{registryInfo:u,brand:m}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=l.Registry.Contract(this.config.env),i=this.getController(),s=i.createQuery({contract:e,function:"getUserWarps",arguments:[new c.AddressValue(new c.Address(r))]}),a=await i.runQuery(s),[p]=i.parseQueryResponse(a);return p.map(N)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=l.Registry.Contract(this.config.env),i=this.getController(),s=i.createQuery({contract:e,function:"getUserBrands",arguments:[new c.AddressValue(new c.Address(r))]}),a=await i.runQuery(s),[p]=i.parseQueryResponse(a),d=p.map(f=>f.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(d.map(f=>this.fetchBrand(f,u)))).filter(f=>f!==null)}async fetchBrand(t,r){let e=A.Brand(t);if(r){let s=this.cache.get(e);if(s)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),s}let i=new c.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let s=await i.getTransaction(t),a=JSON.parse(s.data.toString());return a.meta={hash:s.hash,creator:s.sender.bech32(),createdAt:new Date(s.timestamp*1e3).toISOString()},r&&r.ttl&&this.cache.set(e,a,r.ttl),a}catch(s){return console.error("WarpRegistry: Error fetching brand from transaction hash",s),null}}async loadRegistryConfigs(){let t=l.Registry.Contract(this.config.env),r=this.getController(),e=r.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await r.runQuery(e),[s]=r.parseQueryResponse(i),a=BigInt(s.toString());this.unitPrice=a}getFactory(){let t=new c.TransactionsFactoryConfig({chainID:w(this.config.env)}),r=c.AbiRegistry.create(D);return new c.SmartContractTransactionsFactory({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env),r=new c.ApiNetworkProvider(t,{timeout:3e4}),e=new c.QueryRunnerAdapter({networkProvider:r}),i=c.AbiRegistry.create(D);return new c.SmartContractQueriesController({queryRunner:e,abi:i})}};var P=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(S)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),a=(await Promise.all(i)).filter(u=>u.match),p=a.length>0,d=a.map(u=>({url:u.url,warp:u.warp}));return{match:p,results:d}}async detect(t){let r=t.startsWith(S)?this.extractIdentifierInfoFromUrl(t):T.getInfoFromPrefixedIdentifier(t);if(!r)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:e,id:i}=r,s=new V(this.config),a=new R(this.config),p=null,d=null,u=null;if(e==="hash"){p=await s.createFromTransactionHash(i);try{let{registryInfo:m,brand:f}=await a.getInfoByHash(i);d=m,u=f}catch{}}else if(e==="alias"){let{registryInfo:m,brand:f}=await a.getInfoByAlias(i);d=m,u=f,m&&(p=await s.createFromTransactionHash(m.hash))}return p?{match:!0,url:t,warp:p,registryInfo:d,brand:u}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||l.DefaultClientUrl(this.config.env),i=encodeURIComponent(t===B?r:t+W+r);return l.SuperClientUrls(this.config.env).includes(e)?`${e}/${i}`:`${e}?${E}=${i}`}generateQrCode(t,r,e=512,i="white",s="black",a="#23F7DD"){let p=this.build(t,r);return new G.default({type:"svg",width:e,height:e,data:String(p),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:s},cornersSquareOptions:{type:"extra-rounded",color:s},cornersDotOptions:{type:"square",color:s},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(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 r=new URL(t),i=l.SuperClientUrls(this.config.env).includes(r.origin),s=r.searchParams.get(E),a=i&&!s?r.pathname.split("/")[1]:s;if(!a)return null;let p=decodeURIComponent(a);return T.getInfoFromPrefixedIdentifier(p)}};var at="https://",J="query",T=class o{static prepareVars(t,r){if(!t?.vars)return t;let e=JSON.stringify(t),i=(s,a)=>{e=e.replace(new RegExp(`{{${s.toUpperCase()}}}`,"g"),a)};return Object.entries(t.vars).forEach(([s,a])=>{if(typeof a=="string"&&a.startsWith(`${J}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=a.split(`${J}:`)[1],d=new URL(r.currentUrl).searchParams.get(p);d&&i(s,d)}else i(s,a)}),JSON.parse(e)}static getInfoFromPrefixedIdentifier(t){let r=decodeURIComponent(t),e=r.includes(W)?r:`${B}${W}${r}`,[i,s]=e.split(W);return{type:i,id:s}}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(at))return t.next;{let e=new P(r),i=o.getInfoFromPrefixedIdentifier(t.next);return i?e.build(i.type,i.id):null}}};var V=class{constructor(t){this.cache=new I;this.pendingWarp={protocol:U(l.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 r=new y.TransactionsFactoryConfig({chainID:w(this.config.env)}),e=new y.TransferTransactionsFactory({config:r}),i=JSON.stringify(t),s=e.createTransactionForTransfer({sender:y.Address.newFromBech32(this.config.userAddress),receiver:y.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return s.gasLimit=s.gasLimit+BigInt(2e6),s}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),T.prepareVars(e,this.config)}async createFromTransaction(t,r=!1){let e=await this.createFromRaw(t.data.toString(),r);return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,r){let e=A.Warp(t);if(r){let s=this.cache.get(e);if(s)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),s}let i=new y.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let s=await i.getTransaction(t),a=await this.createFromTransaction(s);return r&&r.ttl&&a&&this.cache.set(e,a,r.ttl),a}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,r=100){return j(t,r)}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||l.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),s=new K.default,a=s.compile(i);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${s.errorsText(a.errors)}`)}};0&&(module.exports={BrandBuilder,Config,DefaultIdentifierType,HttpProtocolPrefix,IdentifierParamName,IdentifierParamSeparator,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpContractLoader,WarpLink,WarpRegistry,WarpUtils});
1
+ "use strict";var Y=Object.create;var F=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var rt=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty;var it=(s,t)=>{for(var e in t)F(s,e,{get:t[e],enumerable:!0})},M=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of et(t))!nt.call(s,i)&&i!==e&&F(s,i,{get:()=>t[i],enumerable:!(r=tt(t,i))||r.enumerable});return s};var q=(s,t,e)=>(e=s!=null?Y(rt(s)):{},M(t||!s||!s.__esModule?F(e,"default",{value:s,enumerable:!0}):e,s)),st=s=>M(F({},"__esModule",{value:!0}),s);var At={};it(At,{BrandBuilder:()=>Q,Config:()=>d,DefaultIdentifierType:()=>v,HttpProtocolPrefix:()=>E,IdentifierParamName:()=>L,IdentifierParamSeparator:()=>C,WarpActionExecutor:()=>D,WarpArgSerializer:()=>V,WarpBuilder:()=>U,WarpContractLoader:()=>x,WarpLink:()=>P,WarpRegistry:()=>R,WarpUtils:()=>W,address:()=>wt,biguint:()=>ht,boolean:()=>yt,codemeta:()=>Ct,composite:()=>ut,hex:()=>Wt,list:()=>ct,nothing:()=>bt,option:()=>at,optional:()=>ot,string:()=>lt,token:()=>Tt,u16:()=>gt,u32:()=>ft,u64:()=>mt,u8:()=>dt,variadic:()=>pt});module.exports=st(At);var y=require("@multiversx/sdk-core"),z=q(require("ajv"));var d={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.2.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.2.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:s=>s==="devnet"?["https://devnet.usewarp.to"]:s==="testnet"?["https://testnet.usewarp.to"]:["https://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",N=s=>`${s}:${d.LatestProtocolVersion}`,S=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}),$=(s,t)=>{let e=s.toString(),[r,i=""]=e.split("."),a=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(a,"0"));if(t<0){let o=r+i;if(a>=o.length)return 0n;let p=o.slice(0,-a)||"0";return BigInt(p)}else return BigInt(s)},j=(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 Q=class{constructor(t){this.pendingBrand={protocol:N(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 y.TransactionsFactoryConfig({chainID:T(this.config.env)}),r=new y.TransferTransactionsFactory({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:y.Address.newFromBech32(this.config.userAddress),receiver:y.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 y.ApiNetworkProvider(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(),a=new z.default,o=a.compile(i);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var E="http",L="warp",C=":",v="alias";var u=require("@multiversx/sdk-core/out"),at=s=>s?u.OptionValue.newProvided(s):u.OptionValue.newMissing(),ot=s=>s?new u.OptionalValue(s.getType(),s):u.OptionalValue.newMissing(),ct=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new u.List(t,s)},pt=s=>u.VariadicValue.fromItems(...s),ut=s=>{let t=s.map(e=>e.getType());return new u.CompositeValue(new u.CompositeType(...t),s)},lt=s=>u.StringValue.fromUTF8(s),dt=s=>new u.U8Value(s),gt=s=>new u.U16Value(s),ft=s=>new u.U32Value(s),mt=s=>new u.U64Value(s),ht=s=>new u.BigUIntValue(s),yt=s=>new u.BooleanValue(s),wt=s=>new u.AddressValue(u.Address.newFromBech32(s)),Tt=s=>new u.TokenIdentifierValue(s),Wt=s=>u.BytesValue.fromHex(s),Ct=s=>new u.CodeMetadataValue(u.CodeMetadata.fromBuffer(Buffer.from(s,"hex"))),bt=()=>new u.NothingValue;var f=require("@multiversx/sdk-core/out");var n=require("@multiversx/sdk-core/out"),V=class{nativeToStrings(t,e){return`${t}:${e?.toString()??""}`}nativeToTyped(t,e){if(t.startsWith("option:")){let[r,i]=t.split(":"),a=this.nativeToTyped(i,e);return e?n.OptionValue.newProvided(a):n.OptionValue.newMissingTyped(a.getType())}if(t.startsWith("optional:")){let[r,i]=t.split(":"),a=this.nativeToTyped(i,e);return e?new n.OptionalValue(a.getType(),a):n.OptionalValue.newMissing()}if(t.startsWith("list:")){let[r,i]=t.split(":"),o=e.split(",").map(p=>this.nativeToTyped(i,p));return new n.List(this.nativeToType(i),o)}if(t.startsWith("variadic:")){let[r,i]=t.split(":"),o=e.split(",").map(p=>this.nativeToTyped(i,p));return new n.VariadicValue(new n.VariadicType(new n.PrimitiveType("Custom")),o)}if(t.startsWith("composite:")){let[r,i]=t.split(":"),a=e.split("|"),o=i.split("|"),p=a.map((l,h)=>this.nativeToTyped(o[h],l)),g=o.map(l=>this.nativeToType(l));return new n.CompositeValue(new n.CompositeType(...g),p)}if(t==="string")return e?n.StringValue.fromUTF8(e):new n.NothingValue;if(t==="uint8")return e?new n.U8Value(Number(e)):new n.NothingValue;if(t==="uint16")return e?new n.U16Value(Number(e)):new n.NothingValue;if(t==="uint32")return e?new n.U32Value(Number(e)):new n.NothingValue;if(t==="uint64")return e?new n.U64Value(BigInt(e)):new n.NothingValue;if(t==="biguint")return e?new n.BigUIntValue(BigInt(e)):new n.NothingValue;if(t==="boolean")return e?new n.BooleanValue(typeof e=="boolean"?e:e==="true"):new n.NothingValue;if(t==="address")return e?new n.AddressValue(n.Address.newFromBech32(e)):new n.NothingValue;if(t==="token")return e?new n.TokenIdentifierValue(e):new n.NothingValue;if(t==="hex")return e?n.BytesValue.fromHex(e):new n.NothingValue;if(t==="codemeta")return new n.CodeMetadataValue(n.CodeMetadata.fromBuffer(Buffer.from(e,"hex")));throw new Error(`WarpArgSerializer (nativeToTyped): Unsupported input type: ${t}`)}typedToNative(t){if(t.hasClassOrSuperclass(n.OptionValue.ClassName)){if(!t.isSet())return["option",null];let[e,r]=this.typedToNative(t.getTypedValue());return[`option:${e}`,r]}if(t.hasClassOrSuperclass(n.OptionalValue.ClassName)){if(!t.isSet())return["optional",null];let[e,r]=this.typedToNative(t.getTypedValue());return[`optional:${e}`,r]}if(t.hasClassOrSuperclass(n.List.ClassName)){let e=t.getItems(),i=e.map(o=>this.typedToNative(o)[0])[0],a=e.map(o=>this.typedToNative(o)[1]);return[`list:${i}`,a.join(",")]}if(t.hasClassOrSuperclass(n.VariadicValue.ClassName)){let e=t.getItems(),i=e.map(o=>this.typedToNative(o)[0])[0],a=e.map(o=>this.typedToNative(o)[1]);return[`variadic:${i}`,a.join(",")]}if(t.hasClassOrSuperclass(n.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(p=>this.typeToNative(p.getType())),i=e.map(p=>p.valueOf()),a=r.join("|"),o=i.join("|");return[`composite:${a}`,o]}if(t.hasClassOrSuperclass(n.BigUIntValue.ClassName))return["biguint",BigInt(t.valueOf().toFixed())];if(t.hasClassOrSuperclass(n.NumericalValue.ClassName))return["uint64",t.valueOf().toNumber()];if(t.hasClassOrSuperclass(n.StringValue.ClassName))return["string",t.valueOf()];if(t.hasClassOrSuperclass(n.BooleanValue.ClassName))return["boolean",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")];throw new Error(`WarpArgSerializer (typedToNative): Unsupported input type: ${t.getClassName()}`)}stringToNative(t){let[e,r]=t.split(":");return e==="address"?[e,r]:e==="boolean"?[e,r==="true"]:e==="biguint"?[e,BigInt(r||0)]:e==="uint8"||e==="uint16"||e==="uint32"||e==="uint64"?[e,Number(r)]:[e,r]}stringToTyped(t){let[e,r]=t.split(":");return this.nativeToTyped(e,r)}nativeToType(t){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==="boolean")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;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}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"boolean";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";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var G=require("@multiversx/sdk-core/out"),x=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 G.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4})}};var D=class{constructor(t,e){this.config=t,this.url=new URL(e),this.serializer=new V,this.contractLoader=new x(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),a=f.Address.newFromBech32(t.address),o=new f.TransactionsFactoryConfig({chainID:T(this.config.env)}),p=this.getModifiedInputs(t,e),l=this.getCombinedInputs(t,p).map(O=>this.serializer.stringToTyped(O)),h=this.getNativeValueFromField(t,p),m=this.getNativeValueFromUrl(t),b=BigInt(h||m||t.value||0),I=this.getCombinedTokenTransfers(t,r);return a.isContractAddress()?new f.SmartContractTransactionsFactory({config:o}).createTransactionForExecute({sender:i,contract:a,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:l,tokenTransfers:I,nativeTransferAmount:b}):new f.TransferTransactionsFactory({config:o}).createTransactionForTransfer({sender:i,receiver:a,nativeAmount:b,tokenTransfers:I,data:l[0]?.hasExactClass(f.StringValue.ClassName)?l[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=new f.ApiNetworkProvider(this.config.chainApiUrl,{timeout:3e4}),i=new f.QueryRunnerAdapter({networkProvider:r}),a=await this.getAbiForAction(t),o=this.getModifiedInputs(t,e),g=this.getCombinedInputs(t,o).map(k=>this.serializer.stringToTyped(k)),l=new f.SmartContractQueriesController({queryRunner:i,abi:a}),h=l.createQuery({contract:t.address,function:t.func,arguments:g}),m=await l.runQuery(h),b=new f.ResultsParser,I={returnCode:m.returnCode,returnMessage:m.returnMessage,getReturnDataParts:()=>m.returnDataParts.map(k=>Buffer.from(k))},O=m.function,X=a.getEndpoint(O),H=b.parseQueryResponse(I,X).firstValue;if(!H)throw new Error("WarpActionExecutor: Query result not found");return H}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)}getNativeValueFromField(t,e){let r=(t.inputs||[]).findIndex(a=>a.source==="field"&&a.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(a=>a.source==="query")?.find(a=>a.position==="value")?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,e){return[...t.transfers?.map(this.toTypedTransfer)||[],...e]}getModifiedInputs(t,e){return(t.inputs?.filter(i=>!!i.modifier)||[]).forEach((i,a)=>{if(i.modifier?.startsWith("scale:")){let[,o]=i.modifier.split(":");if(isNaN(Number(o))){let p=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:a,g=t.inputs?.find(I=>I.name===o);if(!g)throw new Error(`WarpActionExecutor: Scalable input ${o} not found`);let l=Number(g.position.split(":")[1])-1,h=e[l].split(":")[1],m=e[p].split(":")[1],b=$(m,+h);e[p]=`${i.type}:${b}`}else{let p=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:a,g=e[p].split(":")[1],l=$(g,+o);e[p]=`${i.type}:${l}`}}}),e}getCombinedInputs(t,e){let i=(t.inputs?.filter(o=>o.source==="field"&&o.position.startsWith("arg:"))||[]).map((o,p)=>({input:o,value:e[p]})),a="args"in t?t.args:[];return i.forEach(({input:o,value:p})=>{let g=Number(o.position.split(":")[1])-1;a.splice(g,0,p)}),a}toTypedTransfer(t){return new f.TokenTransfer({token:new f.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var w=require("@multiversx/sdk-core"),Z=q(require("ajv"));var A={Warp:s=>`warp:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},B=class{constructor(){this.cache=new Map}set(t,e,r){let i=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:i})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};var J=q(require("qr-code-styling"));var c=require("@multiversx/sdk-core/out");var _={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var R=class{constructor(t){this.cache=new B;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(d.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[c.BytesValue.fromHex(t),c.BytesValue.fromUTF8(e)]:[c.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(d.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[c.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:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(d.Registry.Contract(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromUTF8(t),c.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(d.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromHex(t),c.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:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(d.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(d.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(d.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[c.BytesValue.fromHex(t),c.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=A.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=d.Registry.Contract(this.config.env),a=this.getController(),o=a.createQuery({contract:i,function:"getInfoByAlias",arguments:[c.BytesValue.fromUTF8(t)]}),p=await a.runQuery(o),[g]=a.parseQueryResponse(p),l=g?S(g):null,h=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:h},e.ttl),{registryInfo:l,brand:h}}async getInfoByHash(t,e){let r=A.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=d.Registry.Contract(this.config.env),a=this.getController(),o=a.createQuery({contract:i,function:"getInfoByHash",arguments:[c.BytesValue.fromHex(t)]}),p=await a.runQuery(o),[g]=a.parseQueryResponse(p),l=g?S(g):null,h=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:h},e.ttl),{registryInfo:l,brand:h}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=d.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:r,function:"getUserWarps",arguments:[new c.AddressValue(new c.Address(e))]}),o=await i.runQuery(a),[p]=i.parseQueryResponse(o);return p.map(S)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=d.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:r,function:"getUserBrands",arguments:[new c.AddressValue(new c.Address(e))]}),o=await i.runQuery(a),[p]=i.parseQueryResponse(o),g=p.map(m=>m.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(g.map(m=>this.fetchBrand(m,l)))).filter(m=>m!==null)}async fetchBrand(t,e){let r=A.Brand(t);if(e){let a=this.cache.get(r);if(a)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),a}let i=new c.ApiNetworkProvider(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let a=await i.getTransaction(t),o=JSON.parse(a.data.toString());return o.meta={hash:a.hash,creator:a.sender.bech32(),createdAt:new Date(a.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(a){return console.error("WarpRegistry: Error fetching brand from transaction hash",a),null}}async loadRegistryConfigs(){let t=d.Registry.Contract(this.config.env),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await e.runQuery(r),[a]=e.parseQueryResponse(i),o=BigInt(a.toString());this.unitPrice=o}getFactory(){let t=new c.TransactionsFactoryConfig({chainID:T(this.config.env)}),e=c.AbiRegistry.create(_);return new c.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env),e=new c.ApiNetworkProvider(t,{timeout:3e4}),r=new c.QueryRunnerAdapter({networkProvider:e}),i=c.AbiRegistry.create(_);return new c.SmartContractQueriesController({queryRunner:r,abi:i})}};var P=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(E)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),o=(await Promise.all(i)).filter(l=>l.match),p=o.length>0,g=o.map(l=>({url:l.url,warp:l.warp}));return{match:p,results:g}}async detect(t){let e=t.startsWith(E)?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,a=new U(this.config),o=new R(this.config),p=null,g=null,l=null;if(r==="hash"){p=await a.createFromTransactionHash(i);try{let{registryInfo:h,brand:m}=await o.getInfoByHash(i);g=h,l=m}catch{}}else if(r==="alias"){let{registryInfo:h,brand:m}=await o.getInfoByAlias(i);g=h,l=m,h&&(p=await a.createFromTransactionHash(h.hash))}return p?{match:!0,url:t,warp:p,registryInfo:g,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||d.DefaultClientUrl(this.config.env),i=encodeURIComponent(t===v?e:t+C+e);return d.SuperClientUrls(this.config.env).includes(r)?`${r}/${i}`:`${r}?${L}=${i}`}generateQrCode(t,e,r=512,i="white",a="black",o="#23F7DD"){let p=this.build(t,e);return new J.default({type:"svg",width:r,height:r,data:String(p),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},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),i=d.SuperClientUrls(this.config.env).includes(e.origin),a=e.searchParams.get(L),o=i&&!a?e.pathname.split("/")[1]:a;if(!o)return null;let p=decodeURIComponent(o);return W.getInfoFromPrefixedIdentifier(p)}};var Bt="https://",K="query",W=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),i=(a,o)=>{r=r.replace(new RegExp(`{{${a.toUpperCase()}}}`,"g"),o)};return Object.entries(t.vars).forEach(([a,o])=>{if(typeof o=="string"&&o.startsWith(`${K}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=o.split(`${K}:`)[1],g=new URL(e.currentUrl).searchParams.get(p);g&&i(a,g)}else i(a,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(C)?e:`${v}${C}${e}`,[i,a]=r.split(C);return{type:i,id:a}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(Bt))return t.next;{let r=new P(e),i=s.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}};var U=class{constructor(t){this.cache=new B;this.pendingWarp={protocol:N(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 w.TransactionsFactoryConfig({chainID:T(this.config.env)}),r=new w.TransferTransactionsFactory({config:e}),i=JSON.stringify(t),a=r.createTransactionForTransfer({sender:w.Address.newFromBech32(this.config.userAddress),receiver:w.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return a.gasLimit=a.gasLimit+BigInt(2e6),a}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 a=this.cache.get(r);if(a)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),a}let i=new w.ApiNetworkProvider(this.config.chainApiUrl||d.Chain.ApiUrl(this.config.env));try{let a=await i.getTransaction(t),o=await this.createFromTransaction(a);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(a){return console.error("WarpBuilder: Error creating from transaction hash",a),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return j(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||d.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),a=new Z.default,o=a.compile(i);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};0&&(module.exports={BrandBuilder,Config,DefaultIdentifierType,HttpProtocolPrefix,IdentifierParamName,IdentifierParamSeparator,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpContractLoader,WarpLink,WarpRegistry,WarpUtils,address,biguint,boolean,codemeta,composite,hex,list,nothing,option,optional,string,token,u16,u32,u64,u8,variadic});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{Address as Q,ApiNetworkProvider as Tt,TransactionsFactoryConfig as Wt,TransferTransactionsFactory as Ct}from"@multiversx/sdk-core";import bt from"ajv";var p={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.2.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.2.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:a=>a==="devnet"?["https://devnet.usewarp.to"]:a==="testnet"?["https://testnet.usewarp.to"]:["https://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 h=a=>a==="devnet"?"D":a==="testnet"?"T":"1",I=a=>`${a}:${p.LatestProtocolVersion}`,A=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),creator:a.creator.toString(),createdAt:a.created_at.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),N=(a,t)=>{let r=a.toString(),[e,i=""]=r.split("."),n=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(n,"0"));if(t<0){let s=e+i;if(n>=s.length)return 0n;let o=s.slice(0,-n)||"0";return BigInt(o)}else return BigInt(a)},$=(a,t=100)=>{if(!a)return"";let r=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r};var D=class{constructor(t){this.pendingBrand={protocol:I(p.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new Wt({chainID:h(this.config.env)}),e=new Ct({config:r}),i=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:Q.newFromBech32(this.config.userAddress),receiver:Q.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}async createFromTransaction(t,r=!1){return await this.createFromRaw(t.data.toString(),r)}async createFromTransactionHash(t){let r=new Tt(this.config.chainApiUrl||p.Chain.ApiUrl(this.config.env));try{let e=await r.getTransaction(t);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),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,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.brandSchemaUrl||p.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),n=new bt,s=n.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};var S="http",E="warp",W=":",B="alias";import{AbiRegistry as ut,Address as lt,ApiNetworkProvider as St,QueryRunnerAdapter as Et,ResultsParser as Lt,SmartContractQueriesController as Ot,SmartContractTransactionsFactory as qt,StringValue as kt,Token as $t,TokenTransfer as Qt,TransactionsFactoryConfig as Dt,TransferTransactionsFactory as _t}from"@multiversx/sdk-core/out";import{Address as It,AddressType as _,AddressValue as H,BigUIntType as j,BigUIntValue as M,BooleanType as z,BooleanValue as G,BytesType as J,BytesValue as K,CodeMetadata as At,CodeMetadataType as Z,CodeMetadataValue as X,CompositeType as Bt,CompositeValue as Y,List as tt,NothingValue as m,NumericalValue as vt,OptionalValue as L,OptionValue as O,PrimitiveType as xt,StringType as rt,StringValue as et,TokenIdentifierType as nt,TokenIdentifierValue as it,U16Type as st,U16Value as Rt,U32Type as at,U32Value as Pt,U64Type as ot,U64Value as Vt,U8Type as ct,U8Value as Ft,VariadicType as Ut,VariadicValue as pt}from"@multiversx/sdk-core/out";var v=class{nativeToStrings(t,r){return`${t}:${r?.toString()??""}`}nativeToTyped(t,r){if(t.startsWith("option:")){let[e,i]=t.split(":"),n=this.nativeToTyped(i,r);return r?O.newProvided(n):O.newMissingTyped(n.getType())}if(t.startsWith("optional:")){let[e,i]=t.split(":"),n=this.nativeToTyped(i,r);return r?new L(n.getType(),n):L.newMissing()}if(t.startsWith("list:")){let[e,i]=t.split(":"),s=r.split(",").map(o=>this.nativeToTyped(i,o));return new tt(this.nativeToType(i),s)}if(t.startsWith("variadic:")){let[e,i]=t.split(":"),s=r.split(",").map(o=>this.nativeToTyped(i,o));return new pt(new Ut(new xt("Custom")),s)}if(t.startsWith("composite:")){let[e,i]=t.split(":"),n=r.split("|"),s=i.split("|"),o=n.map((c,d)=>this.nativeToTyped(s[d],c)),u=s.map(c=>this.nativeToType(c));return new Y(new Bt(...u),o)}if(t==="string")return r?et.fromUTF8(r):new m;if(t==="uint8")return r?new Ft(Number(r)):new m;if(t==="uint16")return r?new Rt(Number(r)):new m;if(t==="uint32")return r?new Pt(Number(r)):new m;if(t==="uint64")return r?new Vt(BigInt(r)):new m;if(t==="biguint")return r?new M(BigInt(r)):new m;if(t==="boolean")return r?new G(typeof r=="boolean"?r:r==="true"):new m;if(t==="address")return r?new H(It.newFromBech32(r)):new m;if(t==="token")return r?new it(r):new m;if(t==="hex")return r?K.fromHex(r):new m;if(t==="codemeta")return new X(At.fromBuffer(Buffer.from(r,"hex")));throw new Error(`WarpArgSerializer (nativeToTyped): Unsupported input type: ${t}`)}typedToNative(t){if(t.hasClassOrSuperclass(O.ClassName)){if(!t.isSet())return["option",null];let[r,e]=this.typedToNative(t.getTypedValue());return[`option:${r}`,e]}if(t.hasClassOrSuperclass(L.ClassName)){if(!t.isSet())return["optional",null];let[r,e]=this.typedToNative(t.getTypedValue());return[`optional:${r}`,e]}if(t.hasClassOrSuperclass(tt.ClassName)){let r=t.getItems(),i=r.map(s=>this.typedToNative(s)[0])[0],n=r.map(s=>this.typedToNative(s)[1]);return[`list:${i}`,n.join(",")]}if(t.hasClassOrSuperclass(pt.ClassName)){let r=t.getItems(),i=r.map(s=>this.typedToNative(s)[0])[0],n=r.map(s=>this.typedToNative(s)[1]);return[`variadic:${i}`,n.join(",")]}if(t.hasClassOrSuperclass(Y.ClassName)){let r=t.getItems(),e=r.map(o=>this.typeToNative(o.getType())),i=r.map(o=>o.valueOf()),n=e.join("|"),s=i.join("|");return[`composite:${n}`,s]}if(t.hasClassOrSuperclass(M.ClassName))return["biguint",BigInt(t.valueOf().toFixed())];if(t.hasClassOrSuperclass(vt.ClassName))return["uint64",t.valueOf().toNumber()];if(t.hasClassOrSuperclass(et.ClassName))return["string",t.valueOf()];if(t.hasClassOrSuperclass(G.ClassName))return["boolean",t.valueOf()];if(t.hasClassOrSuperclass(H.ClassName))return["address",t.valueOf().bech32()];if(t.hasClassOrSuperclass(it.ClassName))return["token",t.valueOf()];if(t.hasClassOrSuperclass(K.ClassName))return["hex",t.valueOf().toString("hex")];if(t.hasClassOrSuperclass(X.ClassName))return["codemeta",t.valueOf().toBuffer().toString("hex")];throw new Error(`WarpArgSerializer (typedToNative): Unsupported input type: ${t.getClassName()}`)}stringToNative(t){let[r,e]=t.split(":");return r==="address"?[r,e]:r==="boolean"?[r,e==="true"]:r==="biguint"?[r,BigInt(e||0)]:r==="uint8"||r==="uint16"||r==="uint32"||r==="uint64"?[r,Number(e)]:[r,e]}stringToTyped(t){let[r,e]=t.split(":");return this.nativeToTyped(r,e)}nativeToType(t){if(t==="string")return new rt;if(t==="uint8")return new ct;if(t==="uint16")return new st;if(t==="uint32")return new at;if(t==="uint64")return new ot;if(t==="biguint")return new j;if(t==="boolean")return new z;if(t==="address")return new _;if(t==="token")return new nt;if(t==="hex")return new J;if(t==="codemeta")return new Z;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}typeToNative(t){if(t instanceof rt)return"string";if(t instanceof ct)return"uint8";if(t instanceof st)return"uint16";if(t instanceof at)return"uint32";if(t instanceof ot)return"uint64";if(t instanceof j)return"biguint";if(t instanceof z)return"boolean";if(t instanceof _)return"address";if(t instanceof nt)return"token";if(t instanceof J)return"hex";if(t instanceof Z)return"codemeta";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};import{ApiNetworkProvider as Nt}from"@multiversx/sdk-core/out";var x=class{constructor(t){this.config=t}async getContract(t){try{let e=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:e.ownerAddress,verified:e.isVerified}}catch(r){return console.error("WarpContractLoader: getContract error",r),null}}async getVerificationInfo(t){try{let e=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{codeHash:e.codeHash,abi:e.source.abi}}catch(r){return console.error("WarpContractLoader: getVerificationInfo error",r),null}}getConfiguredChainApi(){if(!this.config.chainApiUrl)throw new Error("WarpContract: Chain API URL not set");return new Nt(this.config.chainApiUrl,{timeout:3e4})}};var dt=class{constructor(t,r){this.config=t,this.url=new URL(r),this.serializer=new v,this.contractLoader=new x(t)}createTransactionForExecute(t,r,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=lt.newFromBech32(this.config.userAddress),n=lt.newFromBech32(t.address),s=new Dt({chainID:h(this.config.env)}),o=this.getModifiedInputs(t,r),c=this.getCombinedInputs(t,o).map(F=>this.serializer.stringToTyped(F)),d=this.getNativeValueFromField(t,o),l=this.getNativeValueFromUrl(t),w=BigInt(d||l||t.value||0),T=this.getCombinedTokenTransfers(t,e);return n.isContractAddress()?new qt({config:s}).createTransactionForExecute({sender:i,contract:n,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:T,nativeTransferAmount:w}):new _t({config:s}).createTransactionForTransfer({sender:i,receiver:n,nativeAmount:w,tokenTransfers:T,data:c[0]?.hasExactClass(kt.ClassName)?c[0].valueOf():void 0})}async executeQuery(t,r){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let e=new St(this.config.chainApiUrl,{timeout:3e4}),i=new Et({networkProvider:e}),n=await this.getAbiForAction(t),s=this.getModifiedInputs(t,r),u=this.getCombinedInputs(t,s).map(U=>this.serializer.stringToTyped(U)),c=new Ot({queryRunner:i,abi:n}),d=c.createQuery({contract:t.address,function:t.func,arguments:u}),l=await c.runQuery(d),w=new Lt,T={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(U=>Buffer.from(U))},F=l.function,wt=n.getEndpoint(F),k=w.parseQueryResponse(T,wt).firstValue;if(!k)throw new Error("WarpActionExecutor: Query result not found");return k}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let r=await this.contractLoader.getVerificationInfo(t.address);if(!r)throw new Error("WarpActionExecutor: Verification info not found");return ut.create(r.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");let e=await(await fetch(t.abi)).json();return ut.create(e)}getNativeValueFromField(t,r){let e=(t.inputs||[]).findIndex(n=>n.source==="field"&&n.position==="value"),i=e!==-1?r[e]:null;return i?i.split(":")[1]:null}getNativeValueFromUrl(t){let r=new URLSearchParams(this.url.search),i=t.inputs?.filter(n=>n.source==="query")?.find(n=>n.position==="value")?.name;return i?r.get(i):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputs(t,r){return(t.inputs?.filter(i=>!!i.modifier)||[]).forEach((i,n)=>{if(i.modifier?.startsWith("scale:")){let[,s]=i.modifier.split(":");if(isNaN(Number(s))){let o=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:n,u=t.inputs?.find(T=>T.name===s);if(!u)throw new Error(`WarpActionExecutor: Scalable input ${s} not found`);let c=Number(u.position.split(":")[1])-1,d=r[c].split(":")[1],l=r[o].split(":")[1],w=N(l,+d);r[o]=`${i.type}:${w}`}else{let o=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:n,u=r[o].split(":")[1],c=N(u,+s);r[o]=`${i.type}:${c}`}}}),r}getCombinedInputs(t,r){let i=(t.inputs?.filter(s=>s.source==="field"&&s.position.startsWith("arg:"))||[]).map((s,o)=>({input:s,value:r[o]})),n="args"in t?t.args:[];return i.forEach(({input:s,value:o})=>{let u=Number(s.position.split(":")[1])-1;n.splice(u,0,o)}),n}toTypedTransfer(t){return new Qt({token:new $t({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as yt,ApiNetworkProvider as Zt,TransactionsFactoryConfig as Xt,TransferTransactionsFactory as Yt}from"@multiversx/sdk-core";import tr from"ajv";var b={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},C=class{constructor(){this.cache=new Map}set(t,r,e){let i=Date.now()+e*1e3;this.cache.set(t,{value:r,expiresAt:i})}get(t){let r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):r.value:null}clear(){this.cache.clear()}};import Jt from"qr-code-styling";import{AbiRegistry as gt,Address as g,AddressValue as ft,ApiNetworkProvider as mt,BytesValue as f,QueryRunnerAdapter as jt,SmartContractQueriesController as Mt,SmartContractTransactionsFactory as zt,TransactionsFactoryConfig as Gt}from"@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 R=class{constructor(t){this.cache=new C;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,r){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 e=r?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(p.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:r?[f.fromHex(t),f.fromUTF8(r)]:[f.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(p.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[f.fromHex(t)]})}createWarpUpgradeTransaction(t,r){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(p.Registry.Contract(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromUTF8(t),f.fromHex(r)]})}createWarpAliasSetTransaction(t,r){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(p.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t),f.fromUTF8(r)]})}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(p.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.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(p.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t)]})}createWarpBrandingTransaction(t,r){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(p.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t),f.fromHex(r)]})}async getInfoByAlias(t,r){let e=b.RegistryInfo(t);if(r){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),l}let i=p.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[f.fromUTF8(t)]}),o=await n.runQuery(s),[u]=n.parseQueryResponse(o),c=u?A(u):null,d=c?.brand?await this.fetchBrand(c.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:c,brand:d},r.ttl),{registryInfo:c,brand:d}}async getInfoByHash(t,r){let e=b.RegistryInfo(t);if(r){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let i=p.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:i,function:"getInfoByHash",arguments:[f.fromHex(t)]}),o=await n.runQuery(s),[u]=n.parseQueryResponse(o),c=u?A(u):null,d=c?.brand?await this.fetchBrand(c.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:c,brand:d},r.ttl),{registryInfo:c,brand:d}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=p.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:e,function:"getUserWarps",arguments:[new ft(new g(r))]}),s=await i.runQuery(n),[o]=i.parseQueryResponse(s);return o.map(A)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=p.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:e,function:"getUserBrands",arguments:[new ft(new g(r))]}),s=await i.runQuery(n),[o]=i.parseQueryResponse(s),u=o.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(u.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}async fetchBrand(t,r){let e=b.Brand(t);if(r){let n=this.cache.get(e);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n}let i=new mt(this.config.chainApiUrl||p.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(t),s=JSON.parse(n.data.toString());return s.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp*1e3).toISOString()},r&&r.ttl&&this.cache.set(e,s,r.ttl),s}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}async loadRegistryConfigs(){let t=p.Registry.Contract(this.config.env),r=this.getController(),e=r.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await r.runQuery(e),[n]=r.parseQueryResponse(i),s=BigInt(n.toString());this.unitPrice=s}getFactory(){let t=new Gt({chainID:h(this.config.env)}),r=gt.create(q);return new zt({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||p.Chain.ApiUrl(this.config.env),r=new mt(t,{timeout:3e4}),e=new jt({networkProvider:r}),i=gt.create(q);return new Mt({queryRunner:e,abi:i})}};var P=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(S)?!!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)),s=(await Promise.all(i)).filter(c=>c.match),o=s.length>0,u=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:u}}async detect(t){let r=t.startsWith(S)?this.extractIdentifierInfoFromUrl(t):y.getInfoFromPrefixedIdentifier(t);if(!r)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:e,id:i}=r,n=new V(this.config),s=new R(this.config),o=null,u=null,c=null;if(e==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:d,brand:l}=await s.getInfoByHash(i);u=d,c=l}catch{}}else if(e==="alias"){let{registryInfo:d,brand:l}=await s.getInfoByAlias(i);u=d,c=l,d&&(o=await n.createFromTransactionHash(d.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,r){let e=this.config.clientUrl||p.DefaultClientUrl(this.config.env),i=encodeURIComponent(t===B?r:t+W+r);return p.SuperClientUrls(this.config.env).includes(e)?`${e}/${i}`:`${e}?${E}=${i}`}generateQrCode(t,r,e=512,i="white",n="black",s="#23F7DD"){let o=this.build(t,r);return new Jt({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let r=new URL(t),i=p.SuperClientUrls(this.config.env).includes(r.origin),n=r.searchParams.get(E),s=i&&!n?r.pathname.split("/")[1]:n;if(!s)return null;let o=decodeURIComponent(s);return y.getInfoFromPrefixedIdentifier(o)}};var Kt="https://",ht="query",y=class a{static prepareVars(t,r){if(!t?.vars)return t;let e=JSON.stringify(t),i=(n,s)=>{e=e.replace(new RegExp(`{{${n.toUpperCase()}}}`,"g"),s)};return Object.entries(t.vars).forEach(([n,s])=>{if(typeof s=="string"&&s.startsWith(`${ht}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${ht}:`)[1],u=new URL(r.currentUrl).searchParams.get(o);u&&i(n,u)}else i(n,s)}),JSON.parse(e)}static getInfoFromPrefixedIdentifier(t){let r=decodeURIComponent(t),e=r.includes(W)?r:`${B}${W}${r}`,[i,n]=e.split(W);return{type:i,id:n}}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(Kt))return t.next;{let e=new P(r),i=a.getInfoFromPrefixedIdentifier(t.next);return i?e.build(i.type,i.id):null}}};var V=class{constructor(t){this.cache=new C;this.pendingWarp={protocol:I(p.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 r=new Xt({chainID:h(this.config.env)}),e=new Yt({config:r}),i=JSON.stringify(t),n=e.createTransactionForTransfer({sender:yt.newFromBech32(this.config.userAddress),receiver:yt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return n.gasLimit=n.gasLimit+BigInt(2e6),n}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),y.prepareVars(e,this.config)}async createFromTransaction(t,r=!1){let e=await this.createFromRaw(t.data.toString(),r);return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,r){let e=b.Warp(t);if(r){let n=this.cache.get(e);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),n}let i=new Zt(this.config.chainApiUrl||p.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(t),s=await this.createFromTransaction(n);return r&&r.ttl&&s&&this.cache.set(e,s,r.ttl),s}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return $(t,r)}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||p.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),n=new tr,s=n.compile(i);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};export{D as BrandBuilder,p as Config,B as DefaultIdentifierType,S as HttpProtocolPrefix,E as IdentifierParamName,W as IdentifierParamSeparator,dt as WarpActionExecutor,v as WarpArgSerializer,V as WarpBuilder,x as WarpContractLoader,P as WarpLink,R as WarpRegistry,y as WarpUtils};
1
+ import{Address as Q,ApiNetworkProvider as Ct,TransactionsFactoryConfig as bt,TransferTransactionsFactory as It}from"@multiversx/sdk-core";import Bt from"ajv";var p={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.2.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.2.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:s=>s==="devnet"?["https://devnet.usewarp.to"]:s==="testnet"?["https://testnet.usewarp.to"]:["https://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 h=s=>s==="devnet"?"D":s==="testnet"?"T":"1",I=s=>`${s}:${p.LatestProtocolVersion}`,B=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)},$=(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 D=class{constructor(t){this.pendingBrand={protocol:I(p.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new bt({chainID:h(this.config.env)}),r=new It({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:Q.newFromBech32(this.config.userAddress),receiver:Q.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 Ct(this.config.chainApiUrl||p.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||p.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),n=new Bt,a=n.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};var S="http",E="warp",W=":",A="alias";import{Address as At,AddressValue as vt,BigUIntValue as Vt,BooleanValue as xt,BytesValue as Rt,CodeMetadata as Pt,CodeMetadataValue as Ut,CompositeType as Ft,CompositeValue as Nt,List as St,NothingValue as Et,OptionalValue as _,OptionValue as H,StringValue as Lt,TokenIdentifierValue as Ot,U16Value as kt,U32Value as qt,U64Value as $t,U8Value as Qt,VariadicValue as Dt}from"@multiversx/sdk-core/out";var Ee=s=>s?H.newProvided(s):H.newMissing(),Le=s=>s?new _(s.getType(),s):_.newMissing(),Oe=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new St(t,s)},ke=s=>Dt.fromItems(...s),qe=s=>{let t=s.map(e=>e.getType());return new Nt(new Ft(...t),s)},$e=s=>Lt.fromUTF8(s),Qe=s=>new Qt(s),De=s=>new kt(s),_e=s=>new qt(s),He=s=>new $t(s),Me=s=>new Vt(s),je=s=>new xt(s),ze=s=>new vt(At.newFromBech32(s)),Ge=s=>new Ot(s),Je=s=>Rt.fromHex(s),Ke=s=>new Ut(Pt.fromBuffer(Buffer.from(s,"hex"))),Ze=()=>new Et;import{AbiRegistry as dt,Address as gt,ApiNetworkProvider as te,QueryRunnerAdapter as ee,ResultsParser as re,SmartContractQueriesController as ne,SmartContractTransactionsFactory as ie,StringValue as se,Token as ae,TokenTransfer as oe,TransactionsFactoryConfig as ce,TransferTransactionsFactory as pe}from"@multiversx/sdk-core/out";import{Address as _t,AddressType as M,AddressValue as j,BigUIntType as z,BigUIntValue as G,BooleanType as J,BooleanValue as K,BytesType as Z,BytesValue as X,CodeMetadata as Ht,CodeMetadataType as Y,CodeMetadataValue as tt,CompositeType as Mt,CompositeValue as et,List as rt,NothingValue as m,NumericalValue as jt,OptionalValue as L,OptionValue as O,PrimitiveType as zt,StringType as nt,StringValue as it,TokenIdentifierType as st,TokenIdentifierValue as at,U16Type as ot,U16Value as Gt,U32Type as ct,U32Value as Jt,U64Type as pt,U64Value as Kt,U8Type as ut,U8Value as Zt,VariadicType as Xt,VariadicValue as lt}from"@multiversx/sdk-core/out";var v=class{nativeToStrings(t,e){return`${t}:${e?.toString()??""}`}nativeToTyped(t,e){if(t.startsWith("option:")){let[r,i]=t.split(":"),n=this.nativeToTyped(i,e);return e?O.newProvided(n):O.newMissingTyped(n.getType())}if(t.startsWith("optional:")){let[r,i]=t.split(":"),n=this.nativeToTyped(i,e);return e?new L(n.getType(),n):L.newMissing()}if(t.startsWith("list:")){let[r,i]=t.split(":"),a=e.split(",").map(o=>this.nativeToTyped(i,o));return new rt(this.nativeToType(i),a)}if(t.startsWith("variadic:")){let[r,i]=t.split(":"),a=e.split(",").map(o=>this.nativeToTyped(i,o));return new lt(new Xt(new zt("Custom")),a)}if(t.startsWith("composite:")){let[r,i]=t.split(":"),n=e.split("|"),a=i.split("|"),o=n.map((c,d)=>this.nativeToTyped(a[d],c)),u=a.map(c=>this.nativeToType(c));return new et(new Mt(...u),o)}if(t==="string")return e?it.fromUTF8(e):new m;if(t==="uint8")return e?new Zt(Number(e)):new m;if(t==="uint16")return e?new Gt(Number(e)):new m;if(t==="uint32")return e?new Jt(Number(e)):new m;if(t==="uint64")return e?new Kt(BigInt(e)):new m;if(t==="biguint")return e?new G(BigInt(e)):new m;if(t==="boolean")return e?new K(typeof e=="boolean"?e:e==="true"):new m;if(t==="address")return e?new j(_t.newFromBech32(e)):new m;if(t==="token")return e?new at(e):new m;if(t==="hex")return e?X.fromHex(e):new m;if(t==="codemeta")return new tt(Ht.fromBuffer(Buffer.from(e,"hex")));throw new Error(`WarpArgSerializer (nativeToTyped): Unsupported input type: ${t}`)}typedToNative(t){if(t.hasClassOrSuperclass(O.ClassName)){if(!t.isSet())return["option",null];let[e,r]=this.typedToNative(t.getTypedValue());return[`option:${e}`,r]}if(t.hasClassOrSuperclass(L.ClassName)){if(!t.isSet())return["optional",null];let[e,r]=this.typedToNative(t.getTypedValue());return[`optional:${e}`,r]}if(t.hasClassOrSuperclass(rt.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToNative(a)[0])[0],n=e.map(a=>this.typedToNative(a)[1]);return[`list:${i}`,n.join(",")]}if(t.hasClassOrSuperclass(lt.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToNative(a)[0])[0],n=e.map(a=>this.typedToNative(a)[1]);return[`variadic:${i}`,n.join(",")]}if(t.hasClassOrSuperclass(et.ClassName)){let e=t.getItems(),r=e.map(o=>this.typeToNative(o.getType())),i=e.map(o=>o.valueOf()),n=r.join("|"),a=i.join("|");return[`composite:${n}`,a]}if(t.hasClassOrSuperclass(G.ClassName))return["biguint",BigInt(t.valueOf().toFixed())];if(t.hasClassOrSuperclass(jt.ClassName))return["uint64",t.valueOf().toNumber()];if(t.hasClassOrSuperclass(it.ClassName))return["string",t.valueOf()];if(t.hasClassOrSuperclass(K.ClassName))return["boolean",t.valueOf()];if(t.hasClassOrSuperclass(j.ClassName))return["address",t.valueOf().bech32()];if(t.hasClassOrSuperclass(at.ClassName))return["token",t.valueOf()];if(t.hasClassOrSuperclass(X.ClassName))return["hex",t.valueOf().toString("hex")];if(t.hasClassOrSuperclass(tt.ClassName))return["codemeta",t.valueOf().toBuffer().toString("hex")];throw new Error(`WarpArgSerializer (typedToNative): Unsupported input type: ${t.getClassName()}`)}stringToNative(t){let[e,r]=t.split(":");return e==="address"?[e,r]:e==="boolean"?[e,r==="true"]:e==="biguint"?[e,BigInt(r||0)]:e==="uint8"||e==="uint16"||e==="uint32"||e==="uint64"?[e,Number(r)]:[e,r]}stringToTyped(t){let[e,r]=t.split(":");return this.nativeToTyped(e,r)}nativeToType(t){if(t==="string")return new nt;if(t==="uint8")return new ut;if(t==="uint16")return new ot;if(t==="uint32")return new ct;if(t==="uint64")return new pt;if(t==="biguint")return new z;if(t==="boolean")return new J;if(t==="address")return new M;if(t==="token")return new st;if(t==="hex")return new Z;if(t==="codemeta")return new Y;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}typeToNative(t){if(t instanceof nt)return"string";if(t instanceof ut)return"uint8";if(t instanceof ot)return"uint16";if(t instanceof ct)return"uint32";if(t instanceof pt)return"uint64";if(t instanceof z)return"biguint";if(t instanceof J)return"boolean";if(t instanceof M)return"address";if(t instanceof st)return"token";if(t instanceof Z)return"hex";if(t instanceof Y)return"codemeta";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};import{ApiNetworkProvider as Yt}from"@multiversx/sdk-core/out";var V=class{constructor(t){this.config=t}async getContract(t){try{let r=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await this.getConfiguredChainApi().doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}getConfiguredChainApi(){if(!this.config.chainApiUrl)throw new Error("WarpContract: Chain API URL not set");return new Yt(this.config.chainApiUrl,{timeout:3e4})}};var ft=class{constructor(t,e){this.config=t,this.url=new URL(e),this.serializer=new v,this.contractLoader=new V(t)}createTransactionForExecute(t,e,r){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=gt.newFromBech32(this.config.userAddress),n=gt.newFromBech32(t.address),a=new ce({chainID:h(this.config.env)}),o=this.getModifiedInputs(t,e),c=this.getCombinedInputs(t,o).map(U=>this.serializer.stringToTyped(U)),d=this.getNativeValueFromField(t,o),l=this.getNativeValueFromUrl(t),w=BigInt(d||l||t.value||0),T=this.getCombinedTokenTransfers(t,r);return n.isContractAddress()?new ie({config:a}).createTransactionForExecute({sender:i,contract:n,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:T,nativeTransferAmount:w}):new pe({config:a}).createTransactionForTransfer({sender:i,receiver:n,nativeAmount:w,tokenTransfers:T,data:c[0]?.hasExactClass(se.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 te(this.config.chainApiUrl,{timeout:3e4}),i=new ee({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 ne({queryRunner:i,abi:n}),d=c.createQuery({contract:t.address,function:t.func,arguments:u}),l=await c.runQuery(d),w=new re,T={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(F=>Buffer.from(F))},U=l.function,Wt=n.getEndpoint(U),q=w.parseQueryResponse(T,Wt).firstValue;if(!q)throw new Error("WarpActionExecutor: Query result not found");return q}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 dt.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 dt.create(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){return(t.inputs?.filter(i=>!!i.modifier)||[]).forEach((i,n)=>{if(i.modifier?.startsWith("scale:")){let[,a]=i.modifier.split(":");if(isNaN(Number(a))){let o=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:n,u=t.inputs?.find(T=>T.name===a);if(!u)throw new Error(`WarpActionExecutor: Scalable input ${a} not found`);let c=Number(u.position.split(":")[1])-1,d=e[c].split(":")[1],l=e[o].split(":")[1],w=N(l,+d);e[o]=`${i.type}:${w}`}else{let o=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:n,u=e[o].split(":")[1],c=N(u,+a);e[o]=`${i.type}:${c}`}}}),e}getCombinedInputs(t,e){let i=(t.inputs?.filter(a=>a.source==="field"&&a.position.startsWith("arg:"))||[]).map((a,o)=>({input:a,value:e[o]})),n="args"in t?t.args:[];return i.forEach(({input:a,value:o})=>{let u=Number(a.position.split(":")[1])-1;n.splice(u,0,o)}),n}toTypedTransfer(t){return new oe({token:new ae({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as Tt,ApiNetworkProvider as ye,TransactionsFactoryConfig as we,TransferTransactionsFactory as Te}from"@multiversx/sdk-core";import We from"ajv";var b={Warp:s=>`warp:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},C=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 me from"qr-code-styling";import{AbiRegistry as mt,Address as g,AddressValue as ht,ApiNetworkProvider as yt,BytesValue as f,QueryRunnerAdapter as le,SmartContractQueriesController as de,SmartContractTransactionsFactory as ge,TransactionsFactoryConfig as fe}from"@multiversx/sdk-core/out";var k={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var x=class{constructor(t){this.cache=new C;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let r=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(p.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[f.fromHex(t),f.fromUTF8(e)]:[f.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(p.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[f.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(p.Registry.Contract(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromUTF8(t),f.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(p.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t),f.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(p.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.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(p.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.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(p.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t),f.fromHex(e)]})}async getInfoByAlias(t,e){let r=b.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=p.Registry.Contract(this.config.env),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[f.fromUTF8(t)]}),o=await n.runQuery(a),[u]=n.parseQueryResponse(o),c=u?B(u):null,d=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:d},e.ttl),{registryInfo:c,brand:d}}async getInfoByHash(t,e){let r=b.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=p.Registry.Contract(this.config.env),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByHash",arguments:[f.fromHex(t)]}),o=await n.runQuery(a),[u]=n.parseQueryResponse(o),c=u?B(u):null,d=c?.brand?await this.fetchBrand(c.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:c,brand:d},e.ttl),{registryInfo:c,brand:d}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=p.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:r,function:"getUserWarps",arguments:[new ht(new g(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a);return o.map(B)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=p.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:r,function:"getUserBrands",arguments:[new ht(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=b.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 yt(this.config.chainApiUrl||p.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}}async loadRegistryConfigs(){let t=p.Registry.Contract(this.config.env),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 fe({chainID:h(this.config.env)}),e=mt.create(k);return new ge({config:t,abi:e})}getController(){let t=this.config.chainApiUrl||p.Chain.ApiUrl(this.config.env),e=new yt(t,{timeout:3e4}),r=new le({networkProvider:e}),i=mt.create(k);return new de({queryRunner:r,abi:i})}};var R=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(S)?!!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(S)?this.extractIdentifierInfoFromUrl(t):y.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,n=new P(this.config),a=new x(this.config),o=null,u=null,c=null;if(r==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:d,brand:l}=await a.getInfoByHash(i);u=d,c=l}catch{}}else if(r==="alias"){let{registryInfo:d,brand:l}=await a.getInfoByAlias(i);u=d,c=l,d&&(o=await n.createFromTransactionHash(d.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||p.DefaultClientUrl(this.config.env),i=encodeURIComponent(t===A?e:t+W+e);return p.SuperClientUrls(this.config.env).includes(r)?`${r}/${i}`:`${r}?${E}=${i}`}generateQrCode(t,e,r=512,i="white",n="black",a="#23F7DD"){let o=this.build(t,e);return new me({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),i=p.SuperClientUrls(this.config.env).includes(e.origin),n=e.searchParams.get(E),a=i&&!n?e.pathname.split("/")[1]:n;if(!a)return null;let o=decodeURIComponent(a);return y.getInfoFromPrefixedIdentifier(o)}};var he="https://",wt="query",y=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(`${wt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${wt}:`)[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(W)?e:`${A}${W}${e}`,[i,n]=r.split(W);return{type:i,id:n}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(he))return t.next;{let r=new R(e),i=s.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}};var P=class{constructor(t){this.cache=new C;this.pendingWarp={protocol:I(p.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 we({chainID:h(this.config.env)}),r=new Te({config:e}),i=JSON.stringify(t),n=r.createTransactionForTransfer({sender:Tt.newFromBech32(this.config.userAddress),receiver:Tt.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),y.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=b.Warp(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),n}let i=new ye(this.config.chainApiUrl||p.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 $(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||p.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),n=new We,a=n.compile(i);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};export{D as BrandBuilder,p as Config,A as DefaultIdentifierType,S as HttpProtocolPrefix,E as IdentifierParamName,W as IdentifierParamSeparator,ft as WarpActionExecutor,v as WarpArgSerializer,P as WarpBuilder,V as WarpContractLoader,R as WarpLink,x as WarpRegistry,y as WarpUtils,ze as address,Me as biguint,je as boolean,Ke as codemeta,qe as composite,Je as hex,Oe as list,Ze as nothing,Ee as option,Le as optional,$e as string,Ge as token,De as u16,_e as u32,He as u64,Qe as u8,ke as variadic};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "0.3.4",
3
+ "version": "0.4.1",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",