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