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