@vleap/warps 0.3.0 → 0.3.1

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