@vleap/warps 0.0.79 → 0.0.80
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 +7 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -6,6 +6,7 @@ type ChainEnv = 'mainnet' | 'testnet' | 'devnet';
|
|
|
6
6
|
type WarpConfig = {
|
|
7
7
|
env: ChainEnv;
|
|
8
8
|
clientUrl?: string;
|
|
9
|
+
currentUrl?: string;
|
|
9
10
|
userAddress?: string;
|
|
10
11
|
chainApiUrl?: string;
|
|
11
12
|
warpSchemaUrl?: string;
|
|
@@ -26,12 +27,14 @@ type RegistryInfo = {
|
|
|
26
27
|
upgrade: string | null;
|
|
27
28
|
};
|
|
28
29
|
type WarpIdType = 'hash' | 'alias';
|
|
30
|
+
type WarpVarPlaceholder = string;
|
|
29
31
|
type Warp = {
|
|
30
32
|
protocol: string;
|
|
31
33
|
name: string;
|
|
32
34
|
title: string;
|
|
33
35
|
description: string | null;
|
|
34
36
|
preview: string;
|
|
37
|
+
vars?: Record<WarpVarPlaceholder, string>;
|
|
35
38
|
actions: WarpAction[];
|
|
36
39
|
next?: string;
|
|
37
40
|
meta?: WarpMeta;
|
|
@@ -79,8 +82,8 @@ type WarpActionInput = {
|
|
|
79
82
|
position: WarpActionInputPosition;
|
|
80
83
|
source: WarpActionInputSource;
|
|
81
84
|
required?: boolean;
|
|
82
|
-
min?: number;
|
|
83
|
-
max?: number;
|
|
85
|
+
min?: number | WarpVarPlaceholder;
|
|
86
|
+
max?: number | WarpVarPlaceholder;
|
|
84
87
|
pattern?: string;
|
|
85
88
|
patternDescription?: string;
|
|
86
89
|
options?: string[];
|
|
@@ -242,7 +245,8 @@ declare class WarpRegistry {
|
|
|
242
245
|
}
|
|
243
246
|
|
|
244
247
|
declare class WarpUtils {
|
|
248
|
+
static prepareVars(warp: Warp, config: WarpConfig): Warp;
|
|
245
249
|
static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
|
|
246
250
|
}
|
|
247
251
|
|
|
248
|
-
export { 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, WarpBuilder, type WarpCacheConfig, type WarpConfig, type WarpContractAction, type WarpContractActionTransfer, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, WarpRegistry, WarpUtils };
|
|
252
|
+
export { 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, WarpBuilder, type WarpCacheConfig, type WarpConfig, type WarpContractAction, type WarpContractActionTransfer, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, WarpRegistry, WarpUtils, type WarpVarPlaceholder };
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ type ChainEnv = 'mainnet' | 'testnet' | 'devnet';
|
|
|
6
6
|
type WarpConfig = {
|
|
7
7
|
env: ChainEnv;
|
|
8
8
|
clientUrl?: string;
|
|
9
|
+
currentUrl?: string;
|
|
9
10
|
userAddress?: string;
|
|
10
11
|
chainApiUrl?: string;
|
|
11
12
|
warpSchemaUrl?: string;
|
|
@@ -26,12 +27,14 @@ type RegistryInfo = {
|
|
|
26
27
|
upgrade: string | null;
|
|
27
28
|
};
|
|
28
29
|
type WarpIdType = 'hash' | 'alias';
|
|
30
|
+
type WarpVarPlaceholder = string;
|
|
29
31
|
type Warp = {
|
|
30
32
|
protocol: string;
|
|
31
33
|
name: string;
|
|
32
34
|
title: string;
|
|
33
35
|
description: string | null;
|
|
34
36
|
preview: string;
|
|
37
|
+
vars?: Record<WarpVarPlaceholder, string>;
|
|
35
38
|
actions: WarpAction[];
|
|
36
39
|
next?: string;
|
|
37
40
|
meta?: WarpMeta;
|
|
@@ -79,8 +82,8 @@ type WarpActionInput = {
|
|
|
79
82
|
position: WarpActionInputPosition;
|
|
80
83
|
source: WarpActionInputSource;
|
|
81
84
|
required?: boolean;
|
|
82
|
-
min?: number;
|
|
83
|
-
max?: number;
|
|
85
|
+
min?: number | WarpVarPlaceholder;
|
|
86
|
+
max?: number | WarpVarPlaceholder;
|
|
84
87
|
pattern?: string;
|
|
85
88
|
patternDescription?: string;
|
|
86
89
|
options?: string[];
|
|
@@ -242,7 +245,8 @@ declare class WarpRegistry {
|
|
|
242
245
|
}
|
|
243
246
|
|
|
244
247
|
declare class WarpUtils {
|
|
248
|
+
static prepareVars(warp: Warp, config: WarpConfig): Warp;
|
|
245
249
|
static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
|
|
246
250
|
}
|
|
247
251
|
|
|
248
|
-
export { 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, WarpBuilder, type WarpCacheConfig, type WarpConfig, type WarpContractAction, type WarpContractActionTransfer, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, WarpRegistry, WarpUtils };
|
|
252
|
+
export { 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, WarpBuilder, type WarpCacheConfig, type WarpConfig, type WarpContractAction, type WarpContractActionTransfer, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, WarpRegistry, WarpUtils, type WarpVarPlaceholder };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var $=Object.create;var I=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var H=(s,t)=>{for(var r in t)I(s,r,{get:t[r],enumerable:!0})},S=(s,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of O(t))!_.call(s,n)&&n!==r&&I(s,n,{get:()=>t[n],enumerable:!(e=D(t,n))||e.enumerable});return s};var R=(s,t,r)=>(r=s!=null?$(Q(s)):{},S(t||!s||!s.__esModule?I(r,"default",{value:s,enumerable:!0}):r,s)),j=s=>S(I({},"__esModule",{value:!0}),s);var M={};H(M,{BrandBuilder:()=>x,Config:()=>c,WarpActionExecutor:()=>F,WarpBuilder:()=>b,WarpLink:()=>C,WarpRegistry:()=>W,WarpUtils:()=>U});module.exports=j(M);var h=require("@multiversx/sdk-core"),q=R(require("ajv"));var c={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.1.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.1.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:s=>s==="devnet"?["https://devnet.usewarp.to"]:s==="testnet"?["https://testnet.usewarp.to"]:["https://usewarp.to"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var y=s=>s==="devnet"?"D":s==="testnet"?"T":"1",T=s=>`${s}:${c.LatestProtocolVersion}`,v=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null});var x=class{constructor(t){this.pendingBrand={protocol:T(c.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new h.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new h.TransferTransactionsFactory({config:r}),n=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:h.Address.newFromBech32(this.config.userAddress),receiver:h.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()})}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}async createFromTransaction(t,r=!1){return await this.createFromRaw(t.data.toString(),r)}async createFromTransactionHash(t){let r=new h.ApiNetworkProvider(this.config.chainApiUrl||c.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||c.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),i=new q.default,o=i.compile(n);if(!o(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var u=require("@multiversx/sdk-core/out");var F=class{constructor(t,r){this.config=t,this.url=new URL(r)}createTransactionForExecute(t,r,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=new u.TransactionsFactoryConfig({chainID:y(this.config.env)}),i=new u.SmartContractTransactionsFactory({config:n}),o=this.getModifiedInputArgs(t,r),p=this.getTypedArgsFromInput(o),d=this.getPositionValueFromUrl(t,"value"),l=BigInt(d||t.value||0),f=this.getCombinedTokenTransfers(t,e);return i.createTransactionForExecute({sender:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(t.address),function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:p,tokenTransfers:f,nativeTransferAmount:l})}getPositionValueFromUrl(t,r){let e=new URLSearchParams(this.url.search),i=t.inputs?.filter(o=>o.source==="query")?.find(o=>o.position===r)?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputArgs(t,r){let e=t.inputs?.filter(n=>!!n.modifier&&n.position.startsWith("arg:"))||[];for(let n of e)if(n.modifier?.startsWith("scale:")){let[,i]=n.modifier.split(":");if(isNaN(Number(i))){let o=Number(n.position.split(":")[1])-1,p=t.inputs?.find(N=>N.name===i);if(!p)throw new Error(`WarpActionExecutor: Scalable input ${i} not found`);let d=Number(p.position.split(":")[1])-1,l=BigInt(r[d].split(":")[1]),g=BigInt(r[o].split(":")[1])*BigInt(10)**l;r[o]=`${n.type}:${g}`}else{let o=Number(n.position.split(":")[1])-1,d=BigInt(r[o].split(":")[1])*BigInt(10)**BigInt(i);r[o]=`${n.type}:${d}`}}return r}getTypedArgsFromInput(t){return t.map(r=>{let[e,n]=r.split(":");return this.toTypedArg(n,e)})}toTypedTransfer(t){return new u.TokenTransfer({token:new u.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}toTypedArg(t,r){if(r==="string")return u.BytesValue.fromUTF8(t);if(r==="uint8")return new u.U8Value(Number(t));if(r==="uint16")return new u.U16Value(Number(t));if(r==="uint32")return new u.U32Value(Number(t));if(r==="uint64")return new u.U64Value(BigInt(t));if(r==="biguint")return new u.BigUIntValue(BigInt(t));if(r==="boolean")return new u.BooleanValue(t==="true");if(r==="address")return new u.AddressValue(u.Address.newFromBech32(t));if(r==="hex")return u.BytesValue.fromHex(t);throw new Error(`WarpActionExecutor: Unsupported input type: ${r}`)}};var m=require("@multiversx/sdk-core"),E=R(require("ajv"));var B={Warp:s=>`warp:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},w=class{constructor(){this.cache=new Map}set(t,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 b=class{constructor(t){this.cache=new w;this.pendingWarp={protocol:T(c.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 m.TransactionsFactoryConfig({chainID:y(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){let e=await this.createFromRaw(t.data.toString(),r);return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp).toISOString()},e}async createFromTransactionHash(t,r){let e=B.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 m.ApiNetworkProvider(this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),o=await this.createFromTransaction(i);return r&&r.ttl&&o&&this.cache.set(e,o,r.ttl),o}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||c.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new E.default,o=i.compile(n);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var k=R(require("qr-code-styling"));var a=require("@multiversx/sdk-core/out");var P={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"}],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:"claimBalance",onlyOwner:!0,mutability:"mutable",inputs:[],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",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:"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},{name:"upgrade",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",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 W=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:a.Address.newFromBech32(this.config.userAddress),contract:a.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:r?[a.BytesValue.fromHex(t),a.BytesValue.fromUTF8(r)]:[a.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:a.Address.newFromBech32(this.config.userAddress),contract:a.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[a.BytesValue.fromHex(t)]})}createWarpAliasSetTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:a.Address.newFromBech32(this.config.userAddress),contract:a.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[a.BytesValue.fromHex(t),a.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:a.Address.newFromBech32(this.config.userAddress),contract:a.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[a.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:a.Address.newFromBech32(this.config.userAddress),contract:a.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[a.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:a.Address.newFromBech32(this.config.userAddress),contract:a.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[a.BytesValue.fromHex(t),a.BytesValue.fromHex(r)]})}async getInfoByAlias(t,r){let e=B.RegistryInfo(t);if(r){let g=this.cache.get(e);if(g)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),g}let n=c.Registry.Contract(this.config.env),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[a.BytesValue.fromUTF8(t)]}),p=await i.runQuery(o),[d]=i.parseQueryResponse(p),l=d?v(d):null,f=l?.brand?await this.fetchBrand(l.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:l,brand:f},r.ttl),{registryInfo:l,brand:f}}async getInfoByHash(t,r){let e=B.RegistryInfo(t);if(r){let g=this.cache.get(e);if(g)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=c.Registry.Contract(this.config.env),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[a.BytesValue.fromHex(t)]}),p=await i.runQuery(o),[d]=i.parseQueryResponse(p),l=d?v(d):null,f=l?.brand?await this.fetchBrand(l.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:l,brand:f},r.ttl),{registryInfo:l,brand:f}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=c.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserWarps",arguments:[new a.AddressValue(new a.Address(r))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o);return p.map(v)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=c.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserBrands",arguments:[new a.AddressValue(new a.Address(r))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o),d=p.map(g=>g.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(d.map(g=>this.fetchBrand(g,l)))).filter(g=>g!==null)}async fetchBrand(t,r){let e=B.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 a.ApiNetworkProvider(this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),o=JSON.parse(i.data.toString());return o.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp).toISOString()},r&&r.ttl&&this.cache.set(e,o,r.ttl),o}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}async loadRegistryConfigs(){let t=c.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),o=BigInt(i.toString());this.unitPrice=o}getUnitPrice(){if(this.unitPrice===0n)throw new Error("WarpRegistry: config not loaded. forgot to call init()?");return this.unitPrice}getFactory(){let t=new a.TransactionsFactoryConfig({chainID:y(this.config.env)}),r=a.AbiRegistry.create(P);return new a.SmartContractTransactionsFactory({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env),r=new a.ApiNetworkProvider(t,{timeout:3e4}),e=new a.QueryRunnerAdapter({networkProvider:r}),n=a.AbiRegistry.create(P);return new a.SmartContractQueriesController({queryRunner:e,abi:n})}};var L="warp",A=":",V="alias",C=class{constructor(t){this.config=t;this.config=t}async detect(t){let r=this.extractIdentifierInfoFromUrl(t);if(!r)return{match:!1,warp:null,registryInfo:null,brand:null};let{type:e,id:n}=r,i=new b(this.config),o=new W(this.config),p=null,d=null,l=null;if(e==="hash"){p=await i.createFromTransactionHash(n);try{let{registryInfo:f,brand:g}=await o.getInfoByHash(n);d=f,l=g}catch{}}else if(e==="alias"){let{registryInfo:f,brand:g}=await o.getInfoByAlias(n);d=f,l=g,f&&(p=await i.createFromTransactionHash(f.hash))}return p?{match:!0,warp:p,registryInfo:d,brand:l}:{match:!1,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||c.DefaultClientUrl(this.config.env),n=encodeURIComponent(t===V?r:t+A+r);return c.SuperClientUrls(this.config.env).includes(e)?`${e}/${n}`:`${e}?${L}=${n}`}generateQrCode(t,r,e=512,n="white",i="black",o="#23F7DD"){let p=this.build(t,r);return new k.default({type:"svg",width:e,height:e,data:String(p),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}getIdentifierInfo(t){let r=t.includes(A)?t:`${V}${A}${t}`,[e,n]=r.split(A);return{type:e,id:n}}extractIdentifierInfoFromUrl(t){let r=new URL(t),n=c.SuperClientUrls(this.config.env).includes(r.origin),i=r.searchParams.get(L),o=n&&!i?r.pathname.split("/")[1]:i;if(!o)return null;let p=decodeURIComponent(o);return this.getIdentifierInfo(p)}};var G="https://",U=class{static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(G))return t.next;{let e=new C(r),n=e.getIdentifierInfo(t.next);return n?e.build(n.type,n.id):null}}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpBuilder,WarpLink,WarpRegistry,WarpUtils});
|
|
1
|
+
"use strict";var O=Object.create;var T=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var j=(s,t)=>{for(var r in t)T(s,r,{get:t[r],enumerable:!0})},S=(s,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Q(t))!H.call(s,n)&&n!==r&&T(s,n,{get:()=>t[n],enumerable:!(e=D(t,n))||e.enumerable});return s};var U=(s,t,r)=>(r=s!=null?O(_(s)):{},S(t||!s||!s.__esModule?T(r,"default",{value:s,enumerable:!0}):r,s)),J=s=>S(T({},"__esModule",{value:!0}),s);var M={};j(M,{BrandBuilder:()=>P,Config:()=>c,WarpActionExecutor:()=>x,WarpBuilder:()=>C,WarpLink:()=>b,WarpRegistry:()=>W,WarpUtils:()=>I});module.exports=J(M);var h=require("@multiversx/sdk-core"),q=U(require("ajv"));var c={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.1.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.1.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:s=>s==="devnet"?["https://devnet.usewarp.to"]:s==="testnet"?["https://testnet.usewarp.to"]:["https://usewarp.to"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var y=s=>s==="devnet"?"D":s==="testnet"?"T":"1",v=s=>`${s}:${c.LatestProtocolVersion}`,A=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null});var P=class{constructor(t){this.pendingBrand={protocol:v(c.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new h.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new h.TransferTransactionsFactory({config:r}),n=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:h.Address.newFromBech32(this.config.userAddress),receiver:h.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()})}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}async createFromTransaction(t,r=!1){return await this.createFromRaw(t.data.toString(),r)}async createFromTransactionHash(t){let r=new h.ApiNetworkProvider(this.config.chainApiUrl||c.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||c.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),i=new q.default,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};var u=require("@multiversx/sdk-core/out");var x=class{constructor(t,r){this.config=t,this.url=new URL(r)}createTransactionForExecute(t,r,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=new u.TransactionsFactoryConfig({chainID:y(this.config.env)}),i=new u.SmartContractTransactionsFactory({config:n}),a=this.getModifiedInputArgs(t,r),p=this.getTypedArgsFromInput(a),l=this.getPositionValueFromUrl(t,"value"),d=BigInt(l||t.value||0),f=this.getCombinedTokenTransfers(t,e);return i.createTransactionForExecute({sender:u.Address.newFromBech32(this.config.userAddress),contract:u.Address.newFromBech32(t.address),function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:p,tokenTransfers:f,nativeTransferAmount:d})}getPositionValueFromUrl(t,r){let e=new URLSearchParams(this.url.search),i=t.inputs?.filter(a=>a.source==="query")?.find(a=>a.position===r)?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputArgs(t,r){let e=t.inputs?.filter(n=>!!n.modifier&&n.position.startsWith("arg:"))||[];for(let n of e)if(n.modifier?.startsWith("scale:")){let[,i]=n.modifier.split(":");if(isNaN(Number(i))){let a=Number(n.position.split(":")[1])-1,p=t.inputs?.find($=>$.name===i);if(!p)throw new Error(`WarpActionExecutor: Scalable input ${i} not found`);let l=Number(p.position.split(":")[1])-1,d=BigInt(r[l].split(":")[1]),g=BigInt(r[a].split(":")[1])*BigInt(10)**d;r[a]=`${n.type}:${g}`}else{let a=Number(n.position.split(":")[1])-1,l=BigInt(r[a].split(":")[1])*BigInt(10)**BigInt(i);r[a]=`${n.type}:${l}`}}return r}getTypedArgsFromInput(t){return t.map(r=>{let[e,n]=r.split(":");return this.toTypedArg(n,e)})}toTypedTransfer(t){return new u.TokenTransfer({token:new u.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}toTypedArg(t,r){if(r==="string")return u.BytesValue.fromUTF8(t);if(r==="uint8")return new u.U8Value(Number(t));if(r==="uint16")return new u.U16Value(Number(t));if(r==="uint32")return new u.U32Value(Number(t));if(r==="uint64")return new u.U64Value(BigInt(t));if(r==="biguint")return new u.BigUIntValue(BigInt(t));if(r==="boolean")return new u.BooleanValue(t==="true");if(r==="address")return new u.AddressValue(u.Address.newFromBech32(t));if(r==="hex")return u.BytesValue.fromHex(t);throw new Error(`WarpActionExecutor: Unsupported input type: ${r}`)}};var m=require("@multiversx/sdk-core"),k=U(require("ajv"));var B={Warp:s=>`warp:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},w=class{constructor(){this.cache=new Map}set(t,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 V=U(require("qr-code-styling"));var o=require("@multiversx/sdk-core/out");var F={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"}],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:"claimBalance",onlyOwner:!0,mutability:"mutable",inputs:[],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",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:"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},{name:"upgrade",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",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 W=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:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:r?[o.BytesValue.fromHex(t),o.BytesValue.fromUTF8(r)]:[o.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[o.BytesValue.fromHex(t)]})}createWarpAliasSetTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[o.BytesValue.fromHex(t),o.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:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[o.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[o.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(c.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[o.BytesValue.fromHex(t),o.BytesValue.fromHex(r)]})}async getInfoByAlias(t,r){let e=B.RegistryInfo(t);if(r){let g=this.cache.get(e);if(g)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),g}let n=c.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[o.BytesValue.fromUTF8(t)]}),p=await i.runQuery(a),[l]=i.parseQueryResponse(p),d=l?A(l):null,f=d?.brand?await this.fetchBrand(d.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:d,brand:f},r.ttl),{registryInfo:d,brand:f}}async getInfoByHash(t,r){let e=B.RegistryInfo(t);if(r){let g=this.cache.get(e);if(g)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let n=c.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[o.BytesValue.fromHex(t)]}),p=await i.runQuery(a),[l]=i.parseQueryResponse(p),d=l?A(l):null,f=d?.brand?await this.fetchBrand(d.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:d,brand:f},r.ttl),{registryInfo:d,brand:f}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=c.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserWarps",arguments:[new o.AddressValue(new o.Address(r))]}),a=await n.runQuery(i),[p]=n.parseQueryResponse(a);return p.map(A)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=c.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserBrands",arguments:[new o.AddressValue(new o.Address(r))]}),a=await n.runQuery(i),[p]=n.parseQueryResponse(a),l=p.map(g=>g.toString("hex")),d={ttl:365*24*60*60};return(await Promise.all(l.map(g=>this.fetchBrand(g,d)))).filter(g=>g!==null)}async fetchBrand(t,r){let e=B.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 o.ApiNetworkProvider(this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),a=JSON.parse(i.data.toString());return a.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp).toISOString()},r&&r.ttl&&this.cache.set(e,a,r.ttl),a}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}async loadRegistryConfigs(){let t=c.Registry.Contract(this.config.env),r=this.getController(),e=r.createQuery({contract:t,function:"getConfig",arguments:[]}),n=await r.runQuery(e),[i]=r.parseQueryResponse(n),a=BigInt(i.toString());this.unitPrice=a}getUnitPrice(){if(this.unitPrice===0n)throw new Error("WarpRegistry: config not loaded. forgot to call init()?");return this.unitPrice}getFactory(){let t=new o.TransactionsFactoryConfig({chainID:y(this.config.env)}),r=o.AbiRegistry.create(F);return new o.SmartContractTransactionsFactory({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env),r=new o.ApiNetworkProvider(t,{timeout:3e4}),e=new o.QueryRunnerAdapter({networkProvider:r}),n=o.AbiRegistry.create(F);return new o.SmartContractQueriesController({queryRunner:e,abi:n})}};var E="warp",R=":",L="alias",b=class{constructor(t){this.config=t;this.config=t}async detect(t){let r=this.extractIdentifierInfoFromUrl(t);if(!r)return{match:!1,warp:null,registryInfo:null,brand:null};let{type:e,id:n}=r,i=new C(this.config),a=new W(this.config),p=null,l=null,d=null;if(e==="hash"){p=await i.createFromTransactionHash(n);try{let{registryInfo:f,brand:g}=await a.getInfoByHash(n);l=f,d=g}catch{}}else if(e==="alias"){let{registryInfo:f,brand:g}=await a.getInfoByAlias(n);l=f,d=g,f&&(p=await i.createFromTransactionHash(f.hash))}return p?{match:!0,warp:p,registryInfo:l,brand:d}:{match:!1,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||c.DefaultClientUrl(this.config.env),n=encodeURIComponent(t===L?r:t+R+r);return c.SuperClientUrls(this.config.env).includes(e)?`${e}/${n}`:`${e}?${E}=${n}`}generateQrCode(t,r,e=512,n="white",i="black",a="#23F7DD"){let p=this.build(t,r);return new V.default({type:"svg",width:e,height:e,data:String(p),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:i},cornersSquareOptions:{type:"extra-rounded",color:i},cornersDotOptions:{type:"square",color:i},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}getIdentifierInfo(t){let r=t.includes(R)?t:`${L}${R}${t}`,[e,n]=r.split(R);return{type:e,id:n}}extractIdentifierInfoFromUrl(t){let r=new URL(t),n=c.SuperClientUrls(this.config.env).includes(r.origin),i=r.searchParams.get(E),a=n&&!i?r.pathname.split("/")[1]:i;if(!a)return null;let p=decodeURIComponent(a);return this.getIdentifierInfo(p)}};var G="https://",N="query",I=class{static prepareVars(t,r){if(!t?.vars)return t;let e=JSON.stringify(t),n=(i,a)=>e=e.replace(`{{${i.toUpperCase()}}}`,a);return Object.entries(t.vars).forEach(([i,a])=>{if(typeof a=="string"&&a.startsWith(`${N}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=a.split(`${N}:`)[1],l=new URL(r.currentUrl).searchParams.get(p);l&&n(i,l)}else n(i,a)}),JSON.parse(e)}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(G))return t.next;{let e=new b(r),n=e.getIdentifierInfo(t.next);return n?e.build(n.type,n.id):null}}};var C=class{constructor(t){this.cache=new w;this.pendingWarp={protocol:v(c.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 m.TransactionsFactoryConfig({chainID:y(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),I.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).toISOString()},e}async createFromTransactionHash(t,r){let e=B.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 m.ApiNetworkProvider(this.config.chainApiUrl||c.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(t),a=await this.createFromTransaction(i);return r&&r.ttl&&a&&this.cache.set(e,a,r.ttl),a}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||c.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new k.default,a=i.compile(n);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpBuilder,WarpLink,WarpRegistry,WarpUtils});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Address as A,ApiNetworkProvider as N,TransactionsFactoryConfig as $,TransferTransactionsFactory as D}from"@multiversx/sdk-core";import O from"ajv";var o={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.1.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.1.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:a=>a==="devnet"?["https://devnet.usewarp.to"]:a==="testnet"?["https://testnet.usewarp.to"]:["https://usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var h=a=>a==="devnet"?"D":a==="testnet"?"T":"1",w=a=>`${a}:${o.LatestProtocolVersion}`,B=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});var R=class{constructor(t){this.pendingBrand={protocol:w(o.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new $({chainID:h(this.config.env)}),e=new D({config:r}),n=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:A.newFromBech32(this.config.userAddress),receiver:A.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 N(this.config.chainApiUrl||o.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||o.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),i=new O,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as T,AddressValue as Q,BigUIntValue as _,BooleanValue as H,BytesValue as x,SmartContractTransactionsFactory as j,Token as K,TokenTransfer as G,TransactionsFactoryConfig as M,U16Value as J,U32Value as z,U64Value as Z,U8Value as X}from"@multiversx/sdk-core/out";var F=class{constructor(t,r){this.config=t,this.url=new URL(r)}createTransactionForExecute(t,r,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=new M({chainID:h(this.config.env)}),i=new j({config:n}),s=this.getModifiedInputArgs(t,r),c=this.getTypedArgsFromInput(s),p=this.getPositionValueFromUrl(t,"value"),u=BigInt(p||t.value||0),d=this.getCombinedTokenTransfers(t,e);return i.createTransactionForExecute({sender:T.newFromBech32(this.config.userAddress),contract:T.newFromBech32(t.address),function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:d,nativeTransferAmount:u})}getPositionValueFromUrl(t,r){let e=new URLSearchParams(this.url.search),i=t.inputs?.filter(s=>s.source==="query")?.find(s=>s.position===r)?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputArgs(t,r){let e=t.inputs?.filter(n=>!!n.modifier&&n.position.startsWith("arg:"))||[];for(let n of e)if(n.modifier?.startsWith("scale:")){let[,i]=n.modifier.split(":");if(isNaN(Number(i))){let s=Number(n.position.split(":")[1])-1,c=t.inputs?.find(k=>k.name===i);if(!c)throw new Error(`WarpActionExecutor: Scalable input ${i} not found`);let p=Number(c.position.split(":")[1])-1,u=BigInt(r[p].split(":")[1]),l=BigInt(r[s].split(":")[1])*BigInt(10)**u;r[s]=`${n.type}:${l}`}else{let s=Number(n.position.split(":")[1])-1,p=BigInt(r[s].split(":")[1])*BigInt(10)**BigInt(i);r[s]=`${n.type}:${p}`}}return r}getTypedArgsFromInput(t){return t.map(r=>{let[e,n]=r.split(":");return this.toTypedArg(n,e)})}toTypedTransfer(t){return new G({token:new K({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}toTypedArg(t,r){if(r==="string")return x.fromUTF8(t);if(r==="uint8")return new X(Number(t));if(r==="uint16")return new J(Number(t));if(r==="uint32")return new z(Number(t));if(r==="uint64")return new Z(BigInt(t));if(r==="biguint")return new _(BigInt(t));if(r==="boolean")return new H(t==="true");if(r==="address")return new Q(T.newFromBech32(t));if(r==="hex")return x.fromHex(t);throw new Error(`WarpActionExecutor: Unsupported input type: ${r}`)}};import{Address as P,ApiNetworkProvider as Y,TransactionsFactoryConfig as tt,TransferTransactionsFactory as rt}from"@multiversx/sdk-core";import et from"ajv";var y={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},m=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 b=class{constructor(t){this.cache=new m;this.pendingWarp={protocol:w(o.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 tt({chainID:h(this.config.env)}),e=new rt({config:r}),n=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:P.newFromBech32(this.config.userAddress),receiver:P.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){let e=await this.createFromRaw(t.data.toString(),r);return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp).toISOString()},e}async createFromTransactionHash(t,r){let e=y.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(this.config.chainApiUrl||o.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}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||o.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new et,s=i.compile(n);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import ct from"qr-code-styling";import{AbiRegistry as U,Address as g,AddressValue as S,ApiNetworkProvider as q,BytesValue as f,QueryRunnerAdapter as it,SmartContractQueriesController as st,SmartContractTransactionsFactory as at,TransactionsFactoryConfig as ot}from"@multiversx/sdk-core/out";var v={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"}],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:"claimBalance",onlyOwner:!0,mutability:"mutable",inputs:[],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",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:"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},{name:"upgrade",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",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 W=class{constructor(t){this.cache=new m;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(o.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(o.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[f.fromHex(t)]})}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(o.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(o.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(o.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(o.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=y.RegistryInfo(t);if(r){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),l}let n=o.Registry.Contract(this.config.env),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[f.fromUTF8(t)]}),c=await i.runQuery(s),[p]=i.parseQueryResponse(c),u=p?B(p):null,d=u?.brand?await this.fetchBrand(u.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:u,brand:d},r.ttl),{registryInfo:u,brand:d}}async getInfoByHash(t,r){let e=y.RegistryInfo(t);if(r){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let n=o.Registry.Contract(this.config.env),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[f.fromHex(t)]}),c=await i.runQuery(s),[p]=i.parseQueryResponse(c),u=p?B(p):null,d=u?.brand?await this.fetchBrand(u.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:u,brand:d},r.ttl),{registryInfo:u,brand:d}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserWarps",arguments:[new S(new g(r))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s);return c.map(B)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserBrands",arguments:[new S(new g(r))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s),p=c.map(l=>l.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(p.map(l=>this.fetchBrand(l,u)))).filter(l=>l!==null)}async fetchBrand(t,r){let e=y.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 q(this.config.chainApiUrl||o.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).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=o.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}getUnitPrice(){if(this.unitPrice===0n)throw new Error("WarpRegistry: config not loaded. forgot to call init()?");return this.unitPrice}getFactory(){let t=new ot({chainID:h(this.config.env)}),r=U.create(v);return new at({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env),r=new q(t,{timeout:3e4}),e=new it({networkProvider:r}),n=U.create(v);return new st({queryRunner:e,abi:n})}};var E="warp",C=":",L="alias",I=class{constructor(t){this.config=t;this.config=t}async detect(t){let r=this.extractIdentifierInfoFromUrl(t);if(!r)return{match:!1,warp:null,registryInfo:null,brand:null};let{type:e,id:n}=r,i=new b(this.config),s=new W(this.config),c=null,p=null,u=null;if(e==="hash"){c=await i.createFromTransactionHash(n);try{let{registryInfo:d,brand:l}=await s.getInfoByHash(n);p=d,u=l}catch{}}else if(e==="alias"){let{registryInfo:d,brand:l}=await s.getInfoByAlias(n);p=d,u=l,d&&(c=await i.createFromTransactionHash(d.hash))}return c?{match:!0,warp:c,registryInfo:p,brand:u}:{match:!1,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||o.DefaultClientUrl(this.config.env),n=encodeURIComponent(t===L?r:t+C+r);return o.SuperClientUrls(this.config.env).includes(e)?`${e}/${n}`:`${e}?${E}=${n}`}generateQrCode(t,r,e=512,n="white",i="black",s="#23F7DD"){let c=this.build(t,r);return new ct({type:"svg",width:e,height:e,data:String(c),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>`})}getIdentifierInfo(t){let r=t.includes(C)?t:`${L}${C}${t}`,[e,n]=r.split(C);return{type:e,id:n}}extractIdentifierInfoFromUrl(t){let r=new URL(t),n=o.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 c=decodeURIComponent(s);return this.getIdentifierInfo(c)}};var ut="https://",V=class{static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(ut))return t.next;{let e=new I(r),n=e.getIdentifierInfo(t.next);return n?e.build(n.type,n.id):null}}};export{R as BrandBuilder,o as Config,F as WarpActionExecutor,b as WarpBuilder,I as WarpLink,W as WarpRegistry,V as WarpUtils};
|
|
1
|
+
import{Address as R,ApiNetworkProvider as $,TransactionsFactoryConfig as O,TransferTransactionsFactory as D}from"@multiversx/sdk-core";import Q from"ajv";var o={ProtocolNameWarp:"warp",ProtocolNameBrand:"warp-brand",LatestProtocolVersion:"0.1.0",LatestWarpSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v0.1.0.schema.json",LatestBrandSchemaUrl:"https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v0.1.0.schema.json",DefaultClientUrl:a=>a==="devnet"?"https://devnet.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:a=>a==="devnet"?["https://devnet.usewarp.to"]:a==="testnet"?["https://testnet.usewarp.to"]:["https://usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var h=a=>a==="devnet"?"D":a==="testnet"?"T":"1",w=a=>`${a}:${o.LatestProtocolVersion}`,B=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});var U=class{constructor(t){this.pendingBrand={protocol:w(o.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new O({chainID:h(this.config.env)}),e=new D({config:r}),n=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:R.newFromBech32(this.config.userAddress),receiver:R.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 $(this.config.chainApiUrl||o.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||o.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),i=new Q,s=i.compile(n);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};import{Address as v,AddressValue as _,BigUIntValue as H,BooleanValue as j,BytesValue as P,SmartContractTransactionsFactory as J,Token as K,TokenTransfer as G,TransactionsFactoryConfig as M,U16Value as z,U32Value as Z,U64Value as X,U8Value as Y}from"@multiversx/sdk-core/out";var x=class{constructor(t,r){this.config=t,this.url=new URL(r)}createTransactionForExecute(t,r,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=new M({chainID:h(this.config.env)}),i=new J({config:n}),s=this.getModifiedInputArgs(t,r),c=this.getTypedArgsFromInput(s),u=this.getPositionValueFromUrl(t,"value"),p=BigInt(u||t.value||0),d=this.getCombinedTokenTransfers(t,e);return i.createTransactionForExecute({sender:v.newFromBech32(this.config.userAddress),contract:v.newFromBech32(t.address),function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:d,nativeTransferAmount:p})}getPositionValueFromUrl(t,r){let e=new URLSearchParams(this.url.search),i=t.inputs?.filter(s=>s.source==="query")?.find(s=>s.position===r)?.name;return i?e.get(i):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputArgs(t,r){let e=t.inputs?.filter(n=>!!n.modifier&&n.position.startsWith("arg:"))||[];for(let n of e)if(n.modifier?.startsWith("scale:")){let[,i]=n.modifier.split(":");if(isNaN(Number(i))){let s=Number(n.position.split(":")[1])-1,c=t.inputs?.find(k=>k.name===i);if(!c)throw new Error(`WarpActionExecutor: Scalable input ${i} not found`);let u=Number(c.position.split(":")[1])-1,p=BigInt(r[u].split(":")[1]),l=BigInt(r[s].split(":")[1])*BigInt(10)**p;r[s]=`${n.type}:${l}`}else{let s=Number(n.position.split(":")[1])-1,u=BigInt(r[s].split(":")[1])*BigInt(10)**BigInt(i);r[s]=`${n.type}:${u}`}}return r}getTypedArgsFromInput(t){return t.map(r=>{let[e,n]=r.split(":");return this.toTypedArg(n,e)})}toTypedTransfer(t){return new G({token:new K({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}toTypedArg(t,r){if(r==="string")return P.fromUTF8(t);if(r==="uint8")return new Y(Number(t));if(r==="uint16")return new z(Number(t));if(r==="uint32")return new Z(Number(t));if(r==="uint64")return new X(BigInt(t));if(r==="biguint")return new H(BigInt(t));if(r==="boolean")return new j(t==="true");if(r==="address")return new _(v.newFromBech32(t));if(r==="hex")return P.fromHex(t);throw new Error(`WarpActionExecutor: Unsupported input type: ${r}`)}};import{Address as N,ApiNetworkProvider as ot,TransactionsFactoryConfig as ct,TransferTransactionsFactory as ut}from"@multiversx/sdk-core";import pt from"ajv";var y={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},m=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()}};import st from"qr-code-styling";import{AbiRegistry as F,Address as g,AddressValue as S,ApiNetworkProvider as q,BytesValue as f,QueryRunnerAdapter as rt,SmartContractQueriesController as et,SmartContractTransactionsFactory as nt,TransactionsFactoryConfig as it}from"@multiversx/sdk-core/out";var A={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"}],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:"claimBalance",onlyOwner:!0,mutability:"mutable",inputs:[],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",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:"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},{name:"upgrade",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",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 W=class{constructor(t){this.cache=new m;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(o.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(o.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[f.fromHex(t)]})}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(o.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(o.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(o.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(o.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=y.RegistryInfo(t);if(r){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),l}let n=o.Registry.Contract(this.config.env),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[f.fromUTF8(t)]}),c=await i.runQuery(s),[u]=i.parseQueryResponse(c),p=u?B(u):null,d=p?.brand?await this.fetchBrand(p.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:p,brand:d},r.ttl),{registryInfo:p,brand:d}}async getInfoByHash(t,r){let e=y.RegistryInfo(t);if(r){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let n=o.Registry.Contract(this.config.env),i=this.getController(),s=i.createQuery({contract:n,function:"getInfoByHash",arguments:[f.fromHex(t)]}),c=await i.runQuery(s),[u]=i.parseQueryResponse(c),p=u?B(u):null,d=p?.brand?await this.fetchBrand(p.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:p,brand:d},r.ttl),{registryInfo:p,brand:d}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserWarps",arguments:[new S(new g(r))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s);return c.map(B)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserBrands",arguments:[new S(new g(r))]}),s=await n.runQuery(i),[c]=n.parseQueryResponse(s),u=c.map(l=>l.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(u.map(l=>this.fetchBrand(l,p)))).filter(l=>l!==null)}async fetchBrand(t,r){let e=y.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 q(this.config.chainApiUrl||o.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).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=o.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}getUnitPrice(){if(this.unitPrice===0n)throw new Error("WarpRegistry: config not loaded. forgot to call init()?");return this.unitPrice}getFactory(){let t=new it({chainID:h(this.config.env)}),r=F.create(A);return new nt({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env),r=new q(t,{timeout:3e4}),e=new rt({networkProvider:r}),n=F.create(A);return new et({queryRunner:e,abi:n})}};var E="warp",b=":",L="alias",C=class{constructor(t){this.config=t;this.config=t}async detect(t){let r=this.extractIdentifierInfoFromUrl(t);if(!r)return{match:!1,warp:null,registryInfo:null,brand:null};let{type:e,id:n}=r,i=new I(this.config),s=new W(this.config),c=null,u=null,p=null;if(e==="hash"){c=await i.createFromTransactionHash(n);try{let{registryInfo:d,brand:l}=await s.getInfoByHash(n);u=d,p=l}catch{}}else if(e==="alias"){let{registryInfo:d,brand:l}=await s.getInfoByAlias(n);u=d,p=l,d&&(c=await i.createFromTransactionHash(d.hash))}return c?{match:!0,warp:c,registryInfo:u,brand:p}:{match:!1,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||o.DefaultClientUrl(this.config.env),n=encodeURIComponent(t===L?r:t+b+r);return o.SuperClientUrls(this.config.env).includes(e)?`${e}/${n}`:`${e}?${E}=${n}`}generateQrCode(t,r,e=512,n="white",i="black",s="#23F7DD"){let c=this.build(t,r);return new st({type:"svg",width:e,height:e,data:String(c),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>`})}getIdentifierInfo(t){let r=t.includes(b)?t:`${L}${b}${t}`,[e,n]=r.split(b);return{type:e,id:n}}extractIdentifierInfoFromUrl(t){let r=new URL(t),n=o.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 c=decodeURIComponent(s);return this.getIdentifierInfo(c)}};var at="https://",V="query",T=class{static prepareVars(t,r){if(!t?.vars)return t;let e=JSON.stringify(t),n=(i,s)=>e=e.replace(`{{${i.toUpperCase()}}}`,s);return Object.entries(t.vars).forEach(([i,s])=>{if(typeof s=="string"&&s.startsWith(`${V}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=s.split(`${V}:`)[1],u=new URL(r.currentUrl).searchParams.get(c);u&&n(i,u)}else n(i,s)}),JSON.parse(e)}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(at))return t.next;{let e=new C(r),n=e.getIdentifierInfo(t.next);return n?e.build(n.type,n.id):null}}};var I=class{constructor(t){this.cache=new m;this.pendingWarp={protocol:w(o.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 ct({chainID:h(this.config.env)}),e=new ut({config:r}),n=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:N.newFromBech32(this.config.userAddress),receiver:N.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),T.prepareVars(e,this.config)}async createFromTransaction(t,r=!1){let e=await this.createFromRaw(t.data.toString(),r);return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp).toISOString()},e}async createFromTransactionHash(t,r){let e=y.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 ot(this.config.chainApiUrl||o.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}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||o.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new pt,s=i.compile(n);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(s.errors)}`)}};export{U as BrandBuilder,o as Config,x as WarpActionExecutor,I as WarpBuilder,C as WarpLink,W as WarpRegistry,T as WarpUtils};
|