@vleap/warps 0.3.2 → 0.3.3

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
@@ -206,12 +206,12 @@ declare class WarpActionExecutor {
206
206
  private toTypedTransfer;
207
207
  }
208
208
 
209
- type NativeValue = string | number | bigint | boolean | null;
209
+ type WarpNativeValue = string | number | bigint | boolean | null;
210
210
  declare class WarpArgSerializer {
211
- nativeToStrings(type: WarpActionInputType, value: NativeValue): string;
212
- nativeToTyped(type: WarpActionInputType, value: NativeValue): TypedValue;
213
- typedToNative(value: TypedValue): [WarpActionInputType, NativeValue];
214
- stringToNative(value: string): [WarpActionInputType, NativeValue];
211
+ nativeToStrings(type: WarpActionInputType, value: WarpNativeValue): string;
212
+ nativeToTyped(type: WarpActionInputType, value: WarpNativeValue): TypedValue;
213
+ typedToNative(value: TypedValue): [WarpActionInputType, WarpNativeValue];
214
+ stringToNative(value: string): [WarpActionInputType, WarpNativeValue];
215
215
  stringToTyped(value: string): TypedValue;
216
216
  nativeToType(type: BaseWarpActionInputType): Type;
217
217
  typeToNative(type: Type): BaseWarpActionInputType;
@@ -309,4 +309,4 @@ declare class WarpUtils {
309
309
  static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
310
310
  }
311
311
 
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 WarpQueryAction, WarpRegistry, WarpUtils, type WarpVarPlaceholder };
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 };
package/dist/index.d.ts CHANGED
@@ -206,12 +206,12 @@ declare class WarpActionExecutor {
206
206
  private toTypedTransfer;
207
207
  }
208
208
 
209
- type NativeValue = string | number | bigint | boolean | null;
209
+ type WarpNativeValue = string | number | bigint | boolean | null;
210
210
  declare class WarpArgSerializer {
211
- nativeToStrings(type: WarpActionInputType, value: NativeValue): string;
212
- nativeToTyped(type: WarpActionInputType, value: NativeValue): TypedValue;
213
- typedToNative(value: TypedValue): [WarpActionInputType, NativeValue];
214
- stringToNative(value: string): [WarpActionInputType, NativeValue];
211
+ nativeToStrings(type: WarpActionInputType, value: WarpNativeValue): string;
212
+ nativeToTyped(type: WarpActionInputType, value: WarpNativeValue): TypedValue;
213
+ typedToNative(value: TypedValue): [WarpActionInputType, WarpNativeValue];
214
+ stringToNative(value: string): [WarpActionInputType, WarpNativeValue];
215
215
  stringToTyped(value: string): TypedValue;
216
216
  nativeToType(type: BaseWarpActionInputType): Type;
217
217
  typeToNative(type: Type): BaseWarpActionInputType;
@@ -309,4 +309,4 @@ declare class WarpUtils {
309
309
  static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
310
310
  }
311
311
 
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 WarpQueryAction, WarpRegistry, WarpUtils, type WarpVarPlaceholder };
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 };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var X=Object.create;var U=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)U(o,r,{get:t[r],enumerable:!0})},H=(o,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of tt(t))!et.call(o,n)&&n!==r&&U(o,n,{get:()=>t[n],enumerable:!(e=Y(t,n))||e.enumerable});return o};var O=(o,t,r)=>(r=o!=null?X(rt(o)):{},H(t||!o||!o.__esModule?U(r,"default",{value:o,enumerable:!0}):r,o)),it=o=>H(U({},"__esModule",{value:!0}),o);var ot={};nt(ot,{BrandBuilder:()=>$,Config:()=>l,DefaultIdentifierType:()=>B,HttpProtocolPrefix:()=>S,IdentifierParamName:()=>E,IdentifierParamSeparator:()=>W,WarpActionExecutor:()=>Q,WarpArgSerializer:()=>v,WarpBuilder:()=>F,WarpContractLoader:()=>x,WarpLink:()=>P,WarpRegistry:()=>R,WarpUtils:()=>T});module.exports=it(ot);var h=require("@multiversx/sdk-core"),M=O(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",V=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,n=""]=r.split("."),i=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(i,"0"));if(t<0){let a=e+n;if(i>=a.length)return 0n;let u=a.slice(0,-i)||"0";return BigInt(u)}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:V(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}),n=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(n).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,n=await(await fetch(r)).json(),i=new M.default,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};var S="http",E="warp",W=":",B="alias";var g=require("@multiversx/sdk-core/out");var s=require("@multiversx/sdk-core/out"),v=class{nativeToStrings(t,r){return`${t}:${r?.toString()??""}`}nativeToTyped(t,r){if(t.startsWith("opt:")){let[e,n]=t.split(":"),i=this.nativeToTyped(n,r);return r?s.OptionValue.newProvided(i):s.OptionValue.newMissingTyped(i.getType())}if(t.startsWith("list:")){let[e,n]=t.split(":"),a=r.split(",").map(u=>this.nativeToTyped(n,u));return new s.List(this.nativeToType(n),a)}if(t.startsWith("variadic:")){let[e,n]=t.split(":"),a=r.split(",").map(u=>this.nativeToTyped(n,u));return new s.VariadicValue(new s.VariadicType(new s.PrimitiveType("Custom")),a)}if(t.startsWith("composite:")){let[e,n]=t.split(":"),i=r.split("|"),a=n.split("|"),u=i.map((p,m)=>this.nativeToTyped(a[m],p)),d=a.map(p=>this.nativeToType(p));return new s.CompositeValue(new s.CompositeType(...d),u)}if(t==="string")return r?s.StringValue.fromUTF8(r):new s.NothingValue;if(t==="uint8")return r?new s.U8Value(Number(r)):new s.NothingValue;if(t==="uint16")return r?new s.U16Value(Number(r)):new s.NothingValue;if(t==="uint32")return r?new s.U32Value(Number(r)):new s.NothingValue;if(t==="uint64")return r?new s.U64Value(BigInt(r)):new s.NothingValue;if(t==="biguint")return r?new s.BigUIntValue(BigInt(r)):new s.NothingValue;if(t==="boolean")return r?new s.BooleanValue(typeof r=="boolean"?r:r==="true"):new s.NothingValue;if(t==="address")return r?new s.AddressValue(s.Address.newFromBech32(r)):new s.NothingValue;if(t==="hex")return r?s.BytesValue.fromHex(r):new s.NothingValue;if(t==="codemeta")return new s.CodeMetadataValue(s.CodeMetadata.fromBuffer(Buffer.from(r,"hex")));throw new Error(`WarpArgSerializer (nativeToTyped): Unsupported input type: ${t}`)}typedToNative(t){if(t.hasClassOrSuperclass(s.OptionValue.ClassName)){if(!t.isSet())return["opt",null];let[r,e]=this.typedToNative(t.getTypedValue());return[`opt:${r}`,e]}if(t.hasClassOrSuperclass(s.List.ClassName)){let r=t.getItems(),n=r.map(a=>this.typedToNative(a)[0])[0],i=r.map(a=>this.typedToNative(a)[1]);return[`list:${n}`,i.join(",")]}if(t.hasClassOrSuperclass(s.VariadicValue.ClassName)){let r=t.getItems(),n=r.map(a=>this.typedToNative(a)[0])[0],i=r.map(a=>this.typedToNative(a)[1]);return[`variadic:${n}`,i.join(",")]}if(t.hasClassOrSuperclass(s.CompositeValue.ClassName)){let r=t.getItems(),e=r.map(u=>this.typeToNative(u.getType())),n=r.map(u=>u.valueOf()),i=e.join("|"),a=n.join("|");return[`composite:${i}`,a]}if(t.hasClassOrSuperclass(s.BigUIntValue.ClassName))return["biguint",BigInt(t.valueOf().toFixed())];if(t.hasClassOrSuperclass(s.NumericalValue.ClassName))return["uint64",t.valueOf().toNumber()];if(t.hasClassOrSuperclass(s.StringValue.ClassName))return["string",t.valueOf()];if(t.hasClassOrSuperclass(s.BooleanValue.ClassName))return["boolean",t.valueOf()];if(t.hasClassOrSuperclass(s.AddressValue.ClassName))return["address",t.valueOf().bech32()];if(t.hasClassOrSuperclass(s.BytesValue.ClassName))return["hex",t.valueOf().toString("hex")];if(t.hasClassOrSuperclass(s.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 s.StringType;if(t==="uint8")return new s.U8Type;if(t==="uint16")return new s.U16Type;if(t==="uint32")return new s.U32Type;if(t==="uint64")return new s.U64Type;if(t==="biguint")return new s.BigUIntType;if(t==="boolean")return new s.BooleanType;if(t==="address")return new s.AddressType;if(t==="hex")return new s.BytesType;if(t==="codemeta")return new s.CodeMetadataType;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}typeToNative(t){if(t instanceof s.StringType)return"string";if(t instanceof s.U8Type)return"uint8";if(t instanceof s.U16Type)return"uint16";if(t instanceof s.U32Type)return"uint32";if(t instanceof s.U64Type)return"uint64";if(t instanceof s.BigUIntType)return"biguint";if(t instanceof s.BooleanType)return"boolean";if(t instanceof s.AddressType)return"address";if(t instanceof s.BytesType)return"hex";if(t instanceof s.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 n=g.Address.newFromBech32(this.config.userAddress),i=g.Address.newFromBech32(t.address),a=new g.TransactionsFactoryConfig({chainID:w(this.config.env)}),u=this.getModifiedInputs(t,r),p=this.getCombinedInputs(t,u).map(L=>this.serializer.stringToTyped(L)),m=this.getNativeValueFromField(t,u),f=this.getNativeValueFromUrl(t),C=BigInt(m||f||t.value||0),b=this.getCombinedTokenTransfers(t,e);return i.isContractAddress()?new g.SmartContractTransactionsFactory({config:a}).createTransactionForExecute({sender:n,contract:i,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:p,tokenTransfers:b,nativeTransferAmount:C}):new g.TransferTransactionsFactory({config:a}).createTransactionForTransfer({sender:n,receiver:i,nativeAmount:C,tokenTransfers:b,data:p[0]?.hasExactClass(g.StringValue.ClassName)?p[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}),n=new g.QueryRunnerAdapter({networkProvider:e}),i=await this.getAbiForAction(t),a=this.getModifiedInputs(t,r),d=this.getCombinedInputs(t,a).map(q=>this.serializer.stringToTyped(q)),p=new g.SmartContractQueriesController({queryRunner:n,abi:i}),m=p.createQuery({contract:t.address,function:t.func,arguments:d}),f=await p.runQuery(m),C=new g.ResultsParser,b={returnCode:f.returnCode,returnMessage:f.returnMessage,getReturnDataParts:()=>f.returnDataParts.map(q=>Buffer.from(q))},L=f.function,Z=i.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(i=>i.source==="field"&&i.position==="value"),n=e!==-1?r[e]:null;return n?n.split(":")[1]:null}getNativeValueFromUrl(t){let r=new URLSearchParams(this.url.search),n=t.inputs?.filter(i=>i.source==="query")?.find(i=>i.position==="value")?.name;return n?r.get(n):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputs(t,r){return(t.inputs?.filter(n=>!!n.modifier)||[]).forEach((n,i)=>{if(n.modifier?.startsWith("scale:")){let[,a]=n.modifier.split(":");if(isNaN(Number(a))){let u=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:i,d=t.inputs?.find(b=>b.name===a);if(!d)throw new Error(`WarpActionExecutor: Scalable input ${a} not found`);let p=Number(d.position.split(":")[1])-1,m=r[p].split(":")[1],f=r[u].split(":")[1],C=k(f,+m);r[u]=`${n.type}:${C}`}else{let u=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:i,d=r[u].split(":")[1],p=k(d,+a);r[u]=`${n.type}:${p}`}}}),r}getCombinedInputs(t,r){let n=(t.inputs?.filter(a=>a.source==="field"&&a.position.startsWith("arg:"))||[]).map((a,u)=>({input:a,value:r[u]})),i="args"in t?t.args:[];return n.forEach(({input:a,value:u})=>{let d=Number(a.position.split(":")[1])-1;i.splice(d,0,u)}),i}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=O(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 n=Date.now()+e*1e3;this.cache.set(t,{value:r,expiresAt:n})}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=O(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 n=l.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[c.BytesValue.fromUTF8(t)]}),u=await i.runQuery(a),[d]=i.parseQueryResponse(u),p=d?N(d):null,m=p?.brand?await this.fetchBrand(p.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:p,brand:m},r.ttl),{registryInfo:p,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 n=l.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[c.BytesValue.fromHex(t)]}),u=await i.runQuery(a),[d]=i.parseQueryResponse(u),p=d?N(d):null,m=p?.brand?await this.fetchBrand(p.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:p,brand:m},r.ttl),{registryInfo:p,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),n=this.getController(),i=n.createQuery({contract:e,function:"getUserWarps",arguments:[new c.AddressValue(new c.Address(r))]}),a=await n.runQuery(i),[u]=n.parseQueryResponse(a);return u.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),n=this.getController(),i=n.createQuery({contract:e,function:"getUserBrands",arguments:[new c.AddressValue(new c.Address(r))]}),a=await n.runQuery(i),[u]=n.parseQueryResponse(a),d=u.map(f=>f.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(d.map(f=>this.fetchBrand(f,p)))).filter(f=>f!==null)}async fetchBrand(t,r){let e=A.Brand(t);if(r){let i=this.cache.get(e);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=new c.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),a=JSON.parse(i.data.toString());return a.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},r&&r.ttl&&this.cache.set(e,a,r.ttl),a}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}async loadRegistryConfigs(){let t=l.Registry.Contract(this.config.env),r=this.getController(),e=r.createQuery({contract:t,function:"getConfig",arguments:[]}),n=await r.runQuery(e),[i]=r.parseQueryResponse(n),a=BigInt(i.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}),n=c.AbiRegistry.create(D);return new c.SmartContractQueriesController({queryRunner:e,abi:n})}};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 n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(n)).filter(p=>p.match),u=a.length>0,d=a.map(p=>({url:p.url,warp:p.warp}));return{match:u,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:n}=r,i=new F(this.config),a=new R(this.config),u=null,d=null,p=null;if(e==="hash"){u=await i.createFromTransactionHash(n);try{let{registryInfo:m,brand:f}=await a.getInfoByHash(n);d=m,p=f}catch{}}else if(e==="alias"){let{registryInfo:m,brand:f}=await a.getInfoByAlias(n);d=m,p=f,m&&(u=await i.createFromTransactionHash(m.hash))}return u?{match:!0,url:t,warp:u,registryInfo:d,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||l.DefaultClientUrl(this.config.env),n=encodeURIComponent(t===B?r:t+W+r);return l.SuperClientUrls(this.config.env).includes(e)?`${e}/${n}`:`${e}?${E}=${n}`}generateQrCode(t,r,e=512,n="white",i="black",a="#23F7DD"){let u=this.build(t,r);return new G.default({type:"svg",width:e,height:e,data:String(u),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(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),n=l.SuperClientUrls(this.config.env).includes(r.origin),i=r.searchParams.get(E),a=n&&!i?r.pathname.split("/")[1]:i;if(!a)return null;let u=decodeURIComponent(a);return T.getInfoFromPrefixedIdentifier(u)}};var at="https://",J="query",T=class o{static prepareVars(t,r){if(!t?.vars)return t;let e=JSON.stringify(t),n=(i,a)=>{e=e.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),a)};return Object.entries(t.vars).forEach(([i,a])=>{if(typeof a=="string"&&a.startsWith(`${J}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let u=a.split(`${J}:`)[1],d=new URL(r.currentUrl).searchParams.get(u);d&&n(i,d)}else n(i,a)}),JSON.parse(e)}static getInfoFromPrefixedIdentifier(t){let r=decodeURIComponent(t),e=r.includes(W)?r:`${B}${W}${r}`,[n,i]=e.split(W);return{type:n,id:i}}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(at))return t.next;{let e=new P(r),n=o.getInfoFromPrefixedIdentifier(t.next);return n?e.build(n.type,n.id):null}}};var F=class{constructor(t){this.cache=new I;this.pendingWarp={protocol:V(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}),n=JSON.stringify(t),i=e.createTransactionForTransfer({sender:y.Address.newFromBech32(this.config.userAddress),receiver:y.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()});return i.gasLimit=i.gasLimit+BigInt(2e6),i}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 i=this.cache.get(e);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=new y.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return r&&r.ttl&&a&&this.cache.set(e,a,r.ttl),a}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,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,n=await(await fetch(r)).json(),i=new K.default,a=i.compile(n);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};0&&(module.exports={BrandBuilder,Config,DefaultIdentifierType,HttpProtocolPrefix,IdentifierParamName,IdentifierParamSeparator,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpContractLoader,WarpLink,WarpRegistry,WarpUtils});
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 n of tt(t))!et.call(o,n)&&n!==r&&F(o,n,{get:()=>t[n],enumerable:!(e=Y(t,n))||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,n=""]=r.split("."),i=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(i,"0"));if(t<0){let a=e+n;if(i>=a.length)return 0n;let p=a.slice(0,-i)||"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}),n=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(n).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,n=await(await fetch(r)).json(),i=new M.default,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};var S="http",E="warp",W=":",B="alias";var g=require("@multiversx/sdk-core/out");var s=require("@multiversx/sdk-core/out"),v=class{nativeToStrings(t,r){return`${t}:${r?.toString()??""}`}nativeToTyped(t,r){if(t.startsWith("option:")){let[e,n]=t.split(":"),i=this.nativeToTyped(n,r);return r?s.OptionValue.newProvided(i):s.OptionValue.newMissingTyped(i.getType())}if(t.startsWith("optional:")){let[e,n]=t.split(":"),i=this.nativeToTyped(n,r);return r?new s.OptionalValue(i.getType(),i):s.OptionalValue.newMissing()}if(t.startsWith("list:")){let[e,n]=t.split(":"),a=r.split(",").map(p=>this.nativeToTyped(n,p));return new s.List(this.nativeToType(n),a)}if(t.startsWith("variadic:")){let[e,n]=t.split(":"),a=r.split(",").map(p=>this.nativeToTyped(n,p));return new s.VariadicValue(new s.VariadicType(new s.PrimitiveType("Custom")),a)}if(t.startsWith("composite:")){let[e,n]=t.split(":"),i=r.split("|"),a=n.split("|"),p=i.map((u,m)=>this.nativeToTyped(a[m],u)),d=a.map(u=>this.nativeToType(u));return new s.CompositeValue(new s.CompositeType(...d),p)}if(t==="string")return r?s.StringValue.fromUTF8(r):new s.NothingValue;if(t==="uint8")return r?new s.U8Value(Number(r)):new s.NothingValue;if(t==="uint16")return r?new s.U16Value(Number(r)):new s.NothingValue;if(t==="uint32")return r?new s.U32Value(Number(r)):new s.NothingValue;if(t==="uint64")return r?new s.U64Value(BigInt(r)):new s.NothingValue;if(t==="biguint")return r?new s.BigUIntValue(BigInt(r)):new s.NothingValue;if(t==="boolean")return r?new s.BooleanValue(typeof r=="boolean"?r:r==="true"):new s.NothingValue;if(t==="address")return r?new s.AddressValue(s.Address.newFromBech32(r)):new s.NothingValue;if(t==="hex")return r?s.BytesValue.fromHex(r):new s.NothingValue;if(t==="codemeta")return new s.CodeMetadataValue(s.CodeMetadata.fromBuffer(Buffer.from(r,"hex")));throw new Error(`WarpArgSerializer (nativeToTyped): Unsupported input type: ${t}`)}typedToNative(t){if(t.hasClassOrSuperclass(s.OptionValue.ClassName)){if(!t.isSet())return["option",null];let[r,e]=this.typedToNative(t.getTypedValue());return[`option:${r}`,e]}if(t.hasClassOrSuperclass(s.OptionalValue.ClassName)){if(!t.isSet())return["optional",null];let[r,e]=this.typedToNative(t.getTypedValue());return[`optional:${r}`,e]}if(t.hasClassOrSuperclass(s.List.ClassName)){let r=t.getItems(),n=r.map(a=>this.typedToNative(a)[0])[0],i=r.map(a=>this.typedToNative(a)[1]);return[`list:${n}`,i.join(",")]}if(t.hasClassOrSuperclass(s.VariadicValue.ClassName)){let r=t.getItems(),n=r.map(a=>this.typedToNative(a)[0])[0],i=r.map(a=>this.typedToNative(a)[1]);return[`variadic:${n}`,i.join(",")]}if(t.hasClassOrSuperclass(s.CompositeValue.ClassName)){let r=t.getItems(),e=r.map(p=>this.typeToNative(p.getType())),n=r.map(p=>p.valueOf()),i=e.join("|"),a=n.join("|");return[`composite:${i}`,a]}if(t.hasClassOrSuperclass(s.BigUIntValue.ClassName))return["biguint",BigInt(t.valueOf().toFixed())];if(t.hasClassOrSuperclass(s.NumericalValue.ClassName))return["uint64",t.valueOf().toNumber()];if(t.hasClassOrSuperclass(s.StringValue.ClassName))return["string",t.valueOf()];if(t.hasClassOrSuperclass(s.BooleanValue.ClassName))return["boolean",t.valueOf()];if(t.hasClassOrSuperclass(s.AddressValue.ClassName))return["address",t.valueOf().bech32()];if(t.hasClassOrSuperclass(s.BytesValue.ClassName))return["hex",t.valueOf().toString("hex")];if(t.hasClassOrSuperclass(s.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 s.StringType;if(t==="uint8")return new s.U8Type;if(t==="uint16")return new s.U16Type;if(t==="uint32")return new s.U32Type;if(t==="uint64")return new s.U64Type;if(t==="biguint")return new s.BigUIntType;if(t==="boolean")return new s.BooleanType;if(t==="address")return new s.AddressType;if(t==="hex")return new s.BytesType;if(t==="codemeta")return new s.CodeMetadataType;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}typeToNative(t){if(t instanceof s.StringType)return"string";if(t instanceof s.U8Type)return"uint8";if(t instanceof s.U16Type)return"uint16";if(t instanceof s.U32Type)return"uint32";if(t instanceof s.U64Type)return"uint64";if(t instanceof s.BigUIntType)return"biguint";if(t instanceof s.BooleanType)return"boolean";if(t instanceof s.AddressType)return"address";if(t instanceof s.BytesType)return"hex";if(t instanceof s.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 n=g.Address.newFromBech32(this.config.userAddress),i=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 i.isContractAddress()?new g.SmartContractTransactionsFactory({config:a}).createTransactionForExecute({sender:n,contract:i,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:u,tokenTransfers:b,nativeTransferAmount:C}):new g.TransferTransactionsFactory({config:a}).createTransactionForTransfer({sender:n,receiver:i,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}),n=new g.QueryRunnerAdapter({networkProvider:e}),i=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:n,abi:i}),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=i.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(i=>i.source==="field"&&i.position==="value"),n=e!==-1?r[e]:null;return n?n.split(":")[1]:null}getNativeValueFromUrl(t){let r=new URLSearchParams(this.url.search),n=t.inputs?.filter(i=>i.source==="query")?.find(i=>i.position==="value")?.name;return n?r.get(n):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputs(t,r){return(t.inputs?.filter(n=>!!n.modifier)||[]).forEach((n,i)=>{if(n.modifier?.startsWith("scale:")){let[,a]=n.modifier.split(":");if(isNaN(Number(a))){let p=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:i,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]=`${n.type}:${C}`}else{let p=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:i,d=r[p].split(":")[1],u=k(d,+a);r[p]=`${n.type}:${u}`}}}),r}getCombinedInputs(t,r){let n=(t.inputs?.filter(a=>a.source==="field"&&a.position.startsWith("arg:"))||[]).map((a,p)=>({input:a,value:r[p]})),i="args"in t?t.args:[];return n.forEach(({input:a,value:p})=>{let d=Number(a.position.split(":")[1])-1;i.splice(d,0,p)}),i}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 n=Date.now()+e*1e3;this.cache.set(t,{value:r,expiresAt:n})}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 n=l.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[c.BytesValue.fromUTF8(t)]}),p=await i.runQuery(a),[d]=i.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 n=l.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[c.BytesValue.fromHex(t)]}),p=await i.runQuery(a),[d]=i.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),n=this.getController(),i=n.createQuery({contract:e,function:"getUserWarps",arguments:[new c.AddressValue(new c.Address(r))]}),a=await n.runQuery(i),[p]=n.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),n=this.getController(),i=n.createQuery({contract:e,function:"getUserBrands",arguments:[new c.AddressValue(new c.Address(r))]}),a=await n.runQuery(i),[p]=n.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 i=this.cache.get(e);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=new c.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),a=JSON.parse(i.data.toString());return a.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},r&&r.ttl&&this.cache.set(e,a,r.ttl),a}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}async loadRegistryConfigs(){let t=l.Registry.Contract(this.config.env),r=this.getController(),e=r.createQuery({contract:t,function:"getConfig",arguments:[]}),n=await r.runQuery(e),[i]=r.parseQueryResponse(n),a=BigInt(i.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}),n=c.AbiRegistry.create(D);return new c.SmartContractQueriesController({queryRunner:e,abi:n})}};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 n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),a=(await Promise.all(n)).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:n}=r,i=new V(this.config),a=new R(this.config),p=null,d=null,u=null;if(e==="hash"){p=await i.createFromTransactionHash(n);try{let{registryInfo:m,brand:f}=await a.getInfoByHash(n);d=m,u=f}catch{}}else if(e==="alias"){let{registryInfo:m,brand:f}=await a.getInfoByAlias(n);d=m,u=f,m&&(p=await i.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),n=encodeURIComponent(t===B?r:t+W+r);return l.SuperClientUrls(this.config.env).includes(e)?`${e}/${n}`:`${e}?${E}=${n}`}generateQrCode(t,r,e=512,n="white",i="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:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(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),n=l.SuperClientUrls(this.config.env).includes(r.origin),i=r.searchParams.get(E),a=n&&!i?r.pathname.split("/")[1]:i;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),n=(i,a)=>{e=e.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),a)};return Object.entries(t.vars).forEach(([i,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&&n(i,d)}else n(i,a)}),JSON.parse(e)}static getInfoFromPrefixedIdentifier(t){let r=decodeURIComponent(t),e=r.includes(W)?r:`${B}${W}${r}`,[n,i]=e.split(W);return{type:n,id:i}}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(at))return t.next;{let e=new P(r),n=o.getInfoFromPrefixedIdentifier(t.next);return n?e.build(n.type,n.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}),n=JSON.stringify(t),i=e.createTransactionForTransfer({sender:y.Address.newFromBech32(this.config.userAddress),receiver:y.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()});return i.gasLimit=i.gasLimit+BigInt(2e6),i}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 i=this.cache.get(e);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=new y.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return r&&r.ttl&&a&&this.cache.set(e,a,r.ttl),a}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,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,n=await(await fetch(r)).json(),i=new K.default,a=i.compile(n);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};0&&(module.exports={BrandBuilder,Config,DefaultIdentifierType,HttpProtocolPrefix,IdentifierParamName,IdentifierParamSeparator,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpContractLoader,WarpLink,WarpRegistry,WarpUtils});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{Address as $,ApiNetworkProvider as ht,TransactionsFactoryConfig as yt,TransferTransactionsFactory as wt}from"@multiversx/sdk-core";import Tt from"ajv";var u={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}:${u.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)},k=(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 Q=class{constructor(t){this.pendingBrand={protocol:I(u.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new yt({chainID:h(this.config.env)}),e=new wt({config:r}),i=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:$.newFromBech32(this.config.userAddress),receiver:$.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 ht(this.config.chainApiUrl||u.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||u.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),n=new Tt,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 ot,Address as ct,ApiNetworkProvider as Ut,QueryRunnerAdapter as Vt,ResultsParser as Nt,SmartContractQueriesController as St,SmartContractTransactionsFactory as Et,StringValue as Lt,Token as qt,TokenTransfer as Ot,TransactionsFactoryConfig as kt,TransferTransactionsFactory as $t}from"@multiversx/sdk-core/out";import{Address as Wt,AddressType as D,AddressValue as _,BigUIntType as H,BigUIntValue as j,BooleanType as M,BooleanValue as z,BytesType as G,BytesValue as J,CodeMetadata as Ct,CodeMetadataType as K,CodeMetadataValue as Z,CompositeType as bt,CompositeValue as X,List as Y,NothingValue as m,NumericalValue as It,OptionValue as L,PrimitiveType as At,StringType as tt,StringValue as rt,U16Type as et,U16Value as Bt,U32Type as nt,U32Value as vt,U64Type as it,U64Value as xt,U8Type as st,U8Value as Rt,VariadicType as Pt,VariadicValue as at}from"@multiversx/sdk-core/out";var v=class{nativeToStrings(t,r){return`${t}:${r?.toString()??""}`}nativeToTyped(t,r){if(t.startsWith("opt:")){let[e,i]=t.split(":"),n=this.nativeToTyped(i,r);return r?L.newProvided(n):L.newMissingTyped(n.getType())}if(t.startsWith("list:")){let[e,i]=t.split(":"),s=r.split(",").map(o=>this.nativeToTyped(i,o));return new Y(this.nativeToType(i),s)}if(t.startsWith("variadic:")){let[e,i]=t.split(":"),s=r.split(",").map(o=>this.nativeToTyped(i,o));return new at(new Pt(new At("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)),p=s.map(c=>this.nativeToType(c));return new X(new bt(...p),o)}if(t==="string")return r?rt.fromUTF8(r):new m;if(t==="uint8")return r?new Rt(Number(r)):new m;if(t==="uint16")return r?new Bt(Number(r)):new m;if(t==="uint32")return r?new vt(Number(r)):new m;if(t==="uint64")return r?new xt(BigInt(r)):new m;if(t==="biguint")return r?new j(BigInt(r)):new m;if(t==="boolean")return r?new z(typeof r=="boolean"?r:r==="true"):new m;if(t==="address")return r?new _(Wt.newFromBech32(r)):new m;if(t==="hex")return r?J.fromHex(r):new m;if(t==="codemeta")return new Z(Ct.fromBuffer(Buffer.from(r,"hex")));throw new Error(`WarpArgSerializer (nativeToTyped): Unsupported input type: ${t}`)}typedToNative(t){if(t.hasClassOrSuperclass(L.ClassName)){if(!t.isSet())return["opt",null];let[r,e]=this.typedToNative(t.getTypedValue());return[`opt:${r}`,e]}if(t.hasClassOrSuperclass(Y.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(at.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(X.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(j.ClassName))return["biguint",BigInt(t.valueOf().toFixed())];if(t.hasClassOrSuperclass(It.ClassName))return["uint64",t.valueOf().toNumber()];if(t.hasClassOrSuperclass(rt.ClassName))return["string",t.valueOf()];if(t.hasClassOrSuperclass(z.ClassName))return["boolean",t.valueOf()];if(t.hasClassOrSuperclass(_.ClassName))return["address",t.valueOf().bech32()];if(t.hasClassOrSuperclass(J.ClassName))return["hex",t.valueOf().toString("hex")];if(t.hasClassOrSuperclass(Z.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 tt;if(t==="uint8")return new st;if(t==="uint16")return new et;if(t==="uint32")return new nt;if(t==="uint64")return new it;if(t==="biguint")return new H;if(t==="boolean")return new M;if(t==="address")return new D;if(t==="hex")return new G;if(t==="codemeta")return new K;throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}typeToNative(t){if(t instanceof tt)return"string";if(t instanceof st)return"uint8";if(t instanceof et)return"uint16";if(t instanceof nt)return"uint32";if(t instanceof it)return"uint64";if(t instanceof H)return"biguint";if(t instanceof M)return"boolean";if(t instanceof D)return"address";if(t instanceof G)return"hex";if(t instanceof K)return"codemeta";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};import{ApiNetworkProvider as Ft}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 Ft(this.config.chainApiUrl,{timeout:3e4})}};var ut=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=ct.newFromBech32(this.config.userAddress),n=ct.newFromBech32(t.address),s=new kt({chainID:h(this.config.env)}),o=this.getModifiedInputs(t,r),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,e);return n.isContractAddress()?new Et({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(Lt.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 Ut(this.config.chainApiUrl,{timeout:3e4}),i=new Vt({networkProvider:e}),n=await this.getAbiForAction(t),s=this.getModifiedInputs(t,r),p=this.getCombinedInputs(t,s).map(V=>this.serializer.stringToTyped(V)),c=new St({queryRunner:i,abi:n}),d=c.createQuery({contract:t.address,function:t.func,arguments:p}),l=await c.runQuery(d),w=new Nt,T={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(V=>Buffer.from(V))},U=l.function,mt=n.getEndpoint(U),O=w.parseQueryResponse(T,mt).firstValue;if(!O)throw new Error("WarpActionExecutor: Query result not found");return O}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 ot.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 ot.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,p=t.inputs?.find(T=>T.name===s);if(!p)throw new Error(`WarpActionExecutor: Scalable input ${s} not found`);let c=Number(p.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,p=r[o].split(":")[1],c=N(p,+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 p=Number(s.position.split(":")[1])-1;n.splice(p,0,o)}),n}toTypedTransfer(t){return new Ot({token:new qt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as ft,ApiNetworkProvider as Gt,TransactionsFactoryConfig as Jt,TransferTransactionsFactory as Kt}from"@multiversx/sdk-core";import Zt 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 Mt from"qr-code-styling";import{AbiRegistry as pt,Address as g,AddressValue as lt,ApiNetworkProvider as dt,BytesValue as f,QueryRunnerAdapter as Dt,SmartContractQueriesController as _t,SmartContractTransactionsFactory as Ht,TransactionsFactoryConfig as jt}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(u.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(u.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(u.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(u.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(u.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(u.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(u.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=u.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[f.fromUTF8(t)]}),o=await n.runQuery(s),[p]=n.parseQueryResponse(o),c=p?A(p):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=u.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:i,function:"getInfoByHash",arguments:[f.fromHex(t)]}),o=await n.runQuery(s),[p]=n.parseQueryResponse(o),c=p?A(p):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=u.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:e,function:"getUserWarps",arguments:[new lt(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=u.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:e,function:"getUserBrands",arguments:[new lt(new g(r))]}),s=await i.runQuery(n),[o]=i.parseQueryResponse(s),p=o.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(p.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}async fetchBrand(t,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 dt(this.config.chainApiUrl||u.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=u.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 jt({chainID:h(this.config.env)}),r=pt.create(q);return new Ht({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env),r=new dt(t,{timeout:3e4}),e=new Dt({networkProvider:r}),i=pt.create(q);return new _t({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,p=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}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 F(this.config),s=new R(this.config),o=null,p=null,c=null;if(e==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:d,brand:l}=await s.getInfoByHash(i);p=d,c=l}catch{}}else if(e==="alias"){let{registryInfo:d,brand:l}=await s.getInfoByAlias(i);p=d,c=l,d&&(o=await n.createFromTransactionHash(d.hash))}return o?{match:!0,url:t,warp:o,registryInfo:p,brand:c}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||u.DefaultClientUrl(this.config.env),i=encodeURIComponent(t===B?r:t+W+r);return u.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 Mt({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=u.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 zt="https://",gt="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(`${gt}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${gt}:`)[1],p=new URL(r.currentUrl).searchParams.get(o);p&&i(n,p)}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(zt))return t.next;{let e=new P(r),i=a.getInfoFromPrefixedIdentifier(t.next);return i?e.build(i.type,i.id):null}}};var F=class{constructor(t){this.cache=new C;this.pendingWarp={protocol:I(u.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 Jt({chainID:h(this.config.env)}),e=new Kt({config:r}),i=JSON.stringify(t),n=e.createTransactionForTransfer({sender:ft.newFromBech32(this.config.userAddress),receiver:ft.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return n.gasLimit=n.gasLimit+BigInt(2e6),n}async createFromRaw(t,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 Gt(this.config.chainApiUrl||u.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 k(t,r)}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||u.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),n=new Zt,s=n.compile(i);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};export{Q as BrandBuilder,u as Config,B as DefaultIdentifierType,S as HttpProtocolPrefix,E as IdentifierParamName,W as IdentifierParamSeparator,ut as WarpActionExecutor,v as WarpArgSerializer,F as WarpBuilder,x as WarpContractLoader,P as WarpLink,R as WarpRegistry,y as WarpUtils};
1
+ import{Address as Q,ApiNetworkProvider as yt,TransactionsFactoryConfig as wt,TransferTransactionsFactory as Tt}from"@multiversx/sdk-core";import Wt 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 Tt({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 yt(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 Wt,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 ct,Address as pt,ApiNetworkProvider as Ut,QueryRunnerAdapter as Nt,ResultsParser as St,SmartContractQueriesController as Et,SmartContractTransactionsFactory as Lt,StringValue as Ot,Token as qt,TokenTransfer as kt,TransactionsFactoryConfig as $t,TransferTransactionsFactory as Qt}from"@multiversx/sdk-core/out";import{Address as Ct,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 bt,CodeMetadataType as Z,CodeMetadataValue as X,CompositeType as It,CompositeValue as Y,List as tt,NothingValue as m,NumericalValue as At,OptionalValue as L,OptionValue as O,PrimitiveType as Bt,StringType as rt,StringValue as et,U16Type as nt,U16Value as vt,U32Type as it,U32Value as xt,U64Type as st,U64Value as Rt,U8Type as at,U8Value as Pt,VariadicType as Vt,VariadicValue as ot}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 ot(new Vt(new Bt("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 It(...u),o)}if(t==="string")return r?et.fromUTF8(r):new m;if(t==="uint8")return r?new Pt(Number(r)):new m;if(t==="uint16")return r?new vt(Number(r)):new m;if(t==="uint32")return r?new xt(Number(r)):new m;if(t==="uint64")return r?new Rt(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(Ct.newFromBech32(r)):new m;if(t==="hex")return r?K.fromHex(r):new m;if(t==="codemeta")return new X(bt.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(ot.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(At.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(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 at;if(t==="uint16")return new nt;if(t==="uint32")return new it;if(t==="uint64")return new st;if(t==="biguint")return new j;if(t==="boolean")return new z;if(t==="address")return new _;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 at)return"uint8";if(t instanceof nt)return"uint16";if(t instanceof it)return"uint32";if(t instanceof st)return"uint64";if(t instanceof j)return"biguint";if(t instanceof z)return"boolean";if(t instanceof _)return"address";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 Ft}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 Ft(this.config.chainApiUrl,{timeout:3e4})}};var ut=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=pt.newFromBech32(this.config.userAddress),n=pt.newFromBech32(t.address),s=new $t({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 Lt({config:s}).createTransactionForExecute({sender:i,contract:n,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:T,nativeTransferAmount:w}):new Qt({config:s}).createTransactionForTransfer({sender:i,receiver:n,nativeAmount:w,tokenTransfers:T,data:c[0]?.hasExactClass(Ot.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 Ut(this.config.chainApiUrl,{timeout:3e4}),i=new Nt({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 Et({queryRunner:i,abi:n}),d=c.createQuery({contract:t.address,function:t.func,arguments:u}),l=await c.runQuery(d),w=new St,T={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(U=>Buffer.from(U))},F=l.function,ht=n.getEndpoint(F),k=w.parseQueryResponse(T,ht).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 ct.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 ct.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 kt({token:new qt({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as mt,ApiNetworkProvider as Jt,TransactionsFactoryConfig as Kt,TransferTransactionsFactory as Zt}from"@multiversx/sdk-core";import Xt 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 zt from"qr-code-styling";import{AbiRegistry as lt,Address as g,AddressValue as dt,ApiNetworkProvider as gt,BytesValue as f,QueryRunnerAdapter as _t,SmartContractQueriesController as Ht,SmartContractTransactionsFactory as jt,TransactionsFactoryConfig as Mt}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 dt(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 dt(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 gt(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 Mt({chainID:h(this.config.env)}),r=lt.create(q);return new jt({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||p.Chain.ApiUrl(this.config.env),r=new gt(t,{timeout:3e4}),e=new _t({networkProvider:r}),i=lt.create(q);return new Ht({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 zt({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 Gt="https://",ft="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(`${ft}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${ft}:`)[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(Gt))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 Kt({chainID:h(this.config.env)}),e=new Zt({config:r}),i=JSON.stringify(t),n=e.createTransactionForTransfer({sender:mt.newFromBech32(this.config.userAddress),receiver:mt.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 Jt(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 Xt,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,ut as WarpActionExecutor,v as WarpArgSerializer,V as WarpBuilder,x as WarpContractLoader,P as WarpLink,R as WarpRegistry,y as WarpUtils};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vleap/warps",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -9,6 +9,7 @@
9
9
  "build": "tsup src/index.ts --dts --format cjs,esm --minify --clean",
10
10
  "test": "jest --config jest.config.js",
11
11
  "lint": "tsc --noEmit",
12
+ "prepare": "npm run build",
12
13
  "preversion": "npm run lint && npm run build"
13
14
  },
14
15
  "author": "",