@vleap/warps 0.0.70 → 0.0.71
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 +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -71,6 +71,7 @@ type WarpLinkAction = {
|
|
|
71
71
|
type WarpActionInputSource = 'field' | 'query';
|
|
72
72
|
type WarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'biguint' | 'boolean' | 'address' | 'hex' | 'esdt' | 'nft';
|
|
73
73
|
type WarpActionInputPosition = 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}`;
|
|
74
|
+
type WarpActionInputModifier = 'scale';
|
|
74
75
|
type WarpActionInput = {
|
|
75
76
|
name: string;
|
|
76
77
|
description?: string | null;
|
|
@@ -83,6 +84,7 @@ type WarpActionInput = {
|
|
|
83
84
|
pattern?: string;
|
|
84
85
|
patternDescription?: string;
|
|
85
86
|
options?: string[];
|
|
87
|
+
modifier?: string;
|
|
86
88
|
};
|
|
87
89
|
type WarpActionExecutionResult = {
|
|
88
90
|
action: WarpAction;
|
|
@@ -164,6 +166,7 @@ declare class WarpActionExecutor {
|
|
|
164
166
|
createTransactionForExecute(action: WarpContractAction, inputArgs: string[], inputTransfers: TokenTransfer[]): Transaction$1;
|
|
165
167
|
getPositionValueFromUrl(action: WarpAction, position: WarpActionInputPosition): string | null;
|
|
166
168
|
getCombinedTokenTransfers(action: WarpContractAction, inputTransfers: TokenTransfer[]): TokenTransfer[];
|
|
169
|
+
getModifiedInputArgs(action: WarpContractAction, inputArgs: string[]): string[];
|
|
167
170
|
getTypedArgsFromInput(inputArgs: string[]): TypedValue[];
|
|
168
171
|
private toTypedTransfer;
|
|
169
172
|
private toTypedArg;
|
|
@@ -230,4 +233,4 @@ declare class WarpRegistry {
|
|
|
230
233
|
private getController;
|
|
231
234
|
}
|
|
232
235
|
|
|
233
|
-
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 WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpBuilder, type WarpCacheConfig, type WarpConfig, type WarpContractAction, type WarpContractActionTransfer, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, WarpRegistry };
|
|
236
|
+
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -71,6 +71,7 @@ type WarpLinkAction = {
|
|
|
71
71
|
type WarpActionInputSource = 'field' | 'query';
|
|
72
72
|
type WarpActionInputType = 'string' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'biguint' | 'boolean' | 'address' | 'hex' | 'esdt' | 'nft';
|
|
73
73
|
type WarpActionInputPosition = 'value' | 'transfer' | `arg:${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10}`;
|
|
74
|
+
type WarpActionInputModifier = 'scale';
|
|
74
75
|
type WarpActionInput = {
|
|
75
76
|
name: string;
|
|
76
77
|
description?: string | null;
|
|
@@ -83,6 +84,7 @@ type WarpActionInput = {
|
|
|
83
84
|
pattern?: string;
|
|
84
85
|
patternDescription?: string;
|
|
85
86
|
options?: string[];
|
|
87
|
+
modifier?: string;
|
|
86
88
|
};
|
|
87
89
|
type WarpActionExecutionResult = {
|
|
88
90
|
action: WarpAction;
|
|
@@ -164,6 +166,7 @@ declare class WarpActionExecutor {
|
|
|
164
166
|
createTransactionForExecute(action: WarpContractAction, inputArgs: string[], inputTransfers: TokenTransfer[]): Transaction$1;
|
|
165
167
|
getPositionValueFromUrl(action: WarpAction, position: WarpActionInputPosition): string | null;
|
|
166
168
|
getCombinedTokenTransfers(action: WarpContractAction, inputTransfers: TokenTransfer[]): TokenTransfer[];
|
|
169
|
+
getModifiedInputArgs(action: WarpContractAction, inputArgs: string[]): string[];
|
|
167
170
|
getTypedArgsFromInput(inputArgs: string[]): TypedValue[];
|
|
168
171
|
private toTypedTransfer;
|
|
169
172
|
private toTypedArg;
|
|
@@ -230,4 +233,4 @@ declare class WarpRegistry {
|
|
|
230
233
|
private getController;
|
|
231
234
|
}
|
|
232
235
|
|
|
233
|
-
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 WarpActionInputPosition, type WarpActionInputSource, type WarpActionInputType, type WarpActionType, WarpBuilder, type WarpCacheConfig, type WarpConfig, type WarpContractAction, type WarpContractActionTransfer, type WarpIdType, WarpLink, type WarpLinkAction, type WarpMeta, WarpRegistry };
|
|
236
|
+
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 };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var $=Object.create;var C=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty;var K=(i,r)=>{for(var t in r)C(i,t,{get:r[t],enumerable:!0})},k=(i,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of Q(r))!j.call(i,n)&&n!==t&&C(i,n,{get:()=>r[n],enumerable:!(e=_(r,n))||e.enumerable});return i};var x=(i,r,t)=>(t=i!=null?$(H(i)):{},k(r||!i||!i.__esModule?C(t,"default",{value:i,enumerable:!0}):t,i)),G=i=>k(C({},"__esModule",{value:!0}),i);var z={};K(z,{BrandBuilder:()=>U,Config:()=>u,WarpActionExecutor:()=>q,WarpBuilder:()=>b,WarpLink:()=>L,WarpRegistry:()=>v});module.exports=G(z);var m=require("@multiversx/sdk-core"),N=x(require("ajv"));var u={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:i=>i==="devnet"?"https://devnet.xwarp.me/to":i==="testnet"?"###Not implemented###":"https://xwarp.me/to",Chain:{ApiUrl:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="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=i=>i==="devnet"?"D":i==="testnet"?"T":"1",W=i=>`${i}:${u.LatestProtocolVersion}`,A=i=>{var r,t,e;return{hash:i.hash.toString("hex"),alias:((r=i.alias)==null?void 0:r.toString())||null,trust:i.trust.toString(),creator:i.creator.toString(),createdAt:i.created_at.toNumber(),brand:((t=i.brand)==null?void 0:t.toString("hex"))||null,upgrade:((e=i.upgrade)==null?void 0:e.toString("hex"))||null}};var U=class{config;pendingBrand={protocol:W(u.ProtocolNameBrand),name:"",description:"",logo:""};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let t=new m.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new m.TransferTransactionsFactory({config:t}),n=JSON.stringify(r);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(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){return await this.createFromRaw(r.data.toString(),t)}async createFromTransactionHash(r){let t=new m.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let e=await t.getTransaction(r);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,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(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.brandSchemaUrl||u.LatestBrandSchemaUrl,n=await(await fetch(t)).json(),a=new N.default,o=a.compile(n);if(!o(r))throw new Error(`BrandBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var c=require("@multiversx/sdk-core/out");var q=class{config;url;constructor(r,t){this.config=r,this.url=new URL(t)}createTransactionForExecute(r,t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=new c.TransactionsFactoryConfig({chainID:y(this.config.env)}),a=new c.SmartContractTransactionsFactory({config:n}),o=this.getTypedArgsFromInput(t),d=this.getPositionValueFromUrl(r,"value"),g=BigInt(d||r.value||0),p=this.getCombinedTokenTransfers(r,e);return a.createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(r.address),function:r.func||"",gasLimit:BigInt(r.gasLimit),arguments:o,tokenTransfers:p,nativeTransferAmount:g})}getPositionValueFromUrl(r,t){var o,d;let e=new URLSearchParams(this.url.search),n=(o=r.inputs)==null?void 0:o.filter(g=>g.source==="query"),a=(d=n==null?void 0:n.find(g=>g.position===t))==null?void 0:d.name;return a?e.get(a):null}getCombinedTokenTransfers(r,t){var n;return[...((n=r.transfers)==null?void 0:n.map(this.toTypedTransfer))||[],...t]}getTypedArgsFromInput(r){return r.map(t=>{let[e,n]=t.split(":");return this.toTypedArg(n,e)})}toTypedTransfer(r){return new c.TokenTransfer({token:new c.Token({identifier:r.token,nonce:BigInt(r.nonce||0)}),amount:BigInt(r.amount||0)})}toTypedArg(r,t){if(t==="string")return c.BytesValue.fromUTF8(r);if(t==="uint8")return new c.U8Value(Number(r));if(t==="uint16")return new c.U16Value(Number(r));if(t==="uint32")return new c.U32Value(Number(r));if(t==="uint64")return new c.U64Value(BigInt(r));if(t==="biguint")return new c.BigUIntValue(BigInt(r));if(t==="boolean")return new c.BooleanValue(r==="true");if(t==="address")return new c.AddressValue(c.Address.newFromBech32(r));if(t==="hex")return c.BytesValue.fromHex(r);throw new Error(`WarpActionExecutor: Unsupported input type: ${t}`)}};var f=require("@multiversx/sdk-core"),V=x(require("ajv"));var T={Warp:i=>`warp:${i}`,RegistryInfo:i=>`registry-info:${i}`,Brand:i=>`brand:${i}`},B=class{cache=new Map;set(r,t,e){let n=Date.now()+e*1e3;this.cache.set(r,{value:t,expiresAt:n})}get(r){let t=this.cache.get(r);return t?Date.now()>t.expiresAt?(this.cache.delete(r),null):t.value:null}clear(){this.cache.clear()}};var b=class{config;cache=new B;pendingWarp={protocol:W(u.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let t=new f.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new f.TransferTransactionsFactory({config:t}),n=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:f.Address.newFromBech32(this.config.userAddress),receiver:f.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){let e=await this.createFromRaw(r.data.toString(),t);return e.meta={hash:r.hash,creator:r.sender.bech32(),createdAt:new Date(r.timestamp).toISOString()},e}async createFromTransactionHash(r,t){let e=T.Warp(r);if(t){let a=this.cache.get(e);if(a)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${r}`),a}let n=new f.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let a=await n.getTransaction(r),o=await this.createFromTransaction(a);return t&&t.ttl&&o&&this.cache.set(e,o,t.ttl),o}catch(a){return console.error("WarpBuilder: Error creating from transaction hash",a),null}}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),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(r,t){if(!r)throw new Error(`WarpBuilder: ${t}`)}async ensureValidSchema(r){let t=this.config.warpSchemaUrl||u.LatestWarpSchemaUrl,n=await(await fetch(t)).json(),a=new V.default,o=a.compile(n);if(!o(r))throw new Error(`WarpBuilder: schema validation failed: ${a.errorsText(o.errors)}`)}};var D=x(require("qr-code-styling"));var s=require("@multiversx/sdk-core/out");var S={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:"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}]}],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 v=class{config;unitPrice;cache=new B;constructor(r){this.config=r,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(r,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");let e=t?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:t?[s.BytesValue.fromHex(r),s.BytesValue.fromUTF8(t)]:[s.BytesValue.fromHex(r)]})}createWarpAliasSetTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r),s.BytesValue.fromUTF8(t)]})}createBrandRegisterTransaction(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:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r)]})}createWarpPublishTransaction(r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),arguments:[s.BytesValue.fromHex(r)]})}createWarpBrandingTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r),s.BytesValue.fromHex(t)]})}async getInfoByAlias(r,t){let e=T.RegistryInfo(r);if(t){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${r}`),l}let n=u.Registry.Contract(this.config.env),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByAlias",arguments:[s.BytesValue.fromUTF8(r)]}),d=await a.runQuery(o),[g]=a.parseQueryResponse(d),p=g?A(g):null,h=p!=null&&p.brand?await this.fetchBrand(p.brand):null;return t&&t.ttl&&this.cache.set(e,{registryInfo:p,brand:h},t.ttl),{registryInfo:p,brand:h}}async getInfoByHash(r,t){let e=T.RegistryInfo(r);if(t){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${r}`),l}let n=u.Registry.Contract(this.config.env),a=this.getController(),o=a.createQuery({contract:n,function:"getInfoByHash",arguments:[s.BytesValue.fromHex(r)]}),d=await a.runQuery(o),[g]=a.parseQueryResponse(d),p=g?A(g):null,h=p!=null&&p.brand?await this.fetchBrand(p.brand):null;return t&&t.ttl&&this.cache.set(e,{registryInfo:p,brand:h},t.ttl),{registryInfo:p,brand:h}}async getUserWarpRegistryInfos(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=u.Registry.Contract(this.config.env),n=this.getController(),a=n.createQuery({contract:e,function:"getUserWarps",arguments:[new s.AddressValue(new s.Address(t))]}),o=await n.runQuery(a),[d]=n.parseQueryResponse(o);return d.map(A)}async getUserBrands(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=u.Registry.Contract(this.config.env),n=this.getController(),a=n.createQuery({contract:e,function:"getUserBrands",arguments:[new s.AddressValue(new s.Address(t))]}),o=await n.runQuery(a),[d]=n.parseQueryResponse(o),g=d.map(l=>l.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(g.map(l=>this.fetchBrand(l,p)))).filter(l=>l!==null)}async fetchBrand(r,t){let e=T.Brand(r);if(t){let a=this.cache.get(e);if(a)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${r}`),a}let n=new s.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let a=await n.getTransaction(r),o=JSON.parse(a.data.toString());return o.meta={hash:a.hash,creator:a.sender.bech32(),createdAt:new Date(a.timestamp).toISOString()},t&&t.ttl&&this.cache.set(e,o,t.ttl),o}catch(a){return console.error("WarpRegistry: Error fetching brand from transaction hash",a),null}}async loadRegistryConfigs(){let r=u.Registry.Contract(this.config.env),t=this.getController(),e=t.createQuery({contract:r,function:"getConfig",arguments:[]}),n=await t.runQuery(e),[a]=t.parseQueryResponse(n),o=BigInt(a.toString());this.unitPrice=o}getFactory(){let r=new s.TransactionsFactoryConfig({chainID:y(this.config.env)}),t=s.AbiRegistry.create(S);return new s.SmartContractTransactionsFactory({config:r,abi:t})}getController(){let r=this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env),t=new s.ApiNetworkProvider(r,{timeout:3e4}),e=new s.QueryRunnerAdapter({networkProvider:t}),n=s.AbiRegistry.create(S);return new s.SmartContractQueriesController({queryRunner:e,abi:n})}};var E="xwarp",I=":",O="alias",L=class{constructor(r){this.config=r;this.config=r}async detect(r){let n=new URL(r).searchParams.get(E);if(!n)return{match:!1,warp:null,registryInfo:null,brand:null};let a=decodeURIComponent(n),o=a.includes(I)?a:`${O}${I}${a}`,[d,g]=o.split(I),p=new b(this.config),h=new v(this.config),l=null,R=null,P=null;if(d==="hash"){l=await p.createFromTransactionHash(g);try{let{registryInfo:w,brand:F}=await h.getInfoByHash(g);R=w,P=F}catch{}}else if(d==="alias"){let{registryInfo:w,brand:F}=await h.getInfoByAlias(g);w&&(l=await p.createFromTransactionHash(w.hash),R=w,P=F)}return l?{match:!0,warp:l,registryInfo:R,brand:P}:{match:!1,warp:null,registryInfo:null,brand:null}}build(r,t){let e=this.config.clientUrl||u.DefaultClientUrl(this.config.env);return r===O?`${e}?${E}=${encodeURIComponent(t)}`:`${e}?${E}=${encodeURIComponent(r+I+t)}`}generateQrCode(r,t,e=512,n="white",a="black",o="#23F7DD"){let d=this.build(r,t);return new D.default({type:"svg",width:e,height:e,data:String(d),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:n},dotsOptions:{type:"extra-rounded",color:a},cornersSquareOptions:{type:"extra-rounded",color:a},cornersDotOptions:{type:"square",color:a},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(o)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpBuilder,WarpLink,WarpRegistry});
|
|
1
|
+
"use strict";var D=Object.create;var C=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty;var K=(a,r)=>{for(var t in r)C(a,t,{get:r[t],enumerable:!0})},N=(a,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of _(r))!j.call(a,n)&&n!==t&&C(a,n,{get:()=>r[n],enumerable:!(e=Q(r,n))||e.enumerable});return a};var x=(a,r,t)=>(t=a!=null?D(H(a)):{},N(r||!a||!a.__esModule?C(t,"default",{value:a,enumerable:!0}):t,a)),G=a=>N(C({},"__esModule",{value:!0}),a);var J={};K(J,{BrandBuilder:()=>U,Config:()=>u,WarpActionExecutor:()=>S,WarpBuilder:()=>W,WarpLink:()=>L,WarpRegistry:()=>v});module.exports=G(J);var h=require("@multiversx/sdk-core"),V=x(require("ajv"));var u={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.xwarp.me/to":a==="testnet"?"###Not implemented###":"https://xwarp.me/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 y=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});var U=class{constructor(r){this.pendingBrand={protocol:I(u.ProtocolNameBrand),name:"",description:"",logo:""};this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let t=new h.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new h.TransferTransactionsFactory({config:t}),n=JSON.stringify(r);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(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){return await this.createFromRaw(r.data.toString(),t)}async createFromTransactionHash(r){let t=new h.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let e=await t.getTransaction(r);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,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(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.brandSchemaUrl||u.LatestBrandSchemaUrl,n=await(await fetch(t)).json(),i=new V.default,o=i.compile(n);if(!o(r))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var c=require("@multiversx/sdk-core/out");var S=class{constructor(r,t){this.config=r,this.url=new URL(t)}createTransactionForExecute(r,t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=new c.TransactionsFactoryConfig({chainID:y(this.config.env)}),i=new c.SmartContractTransactionsFactory({config:n}),o=this.getModifiedInputArgs(r,t),p=this.getTypedArgsFromInput(o),g=this.getPositionValueFromUrl(r,"value"),d=BigInt(g||r.value||0),f=this.getCombinedTokenTransfers(r,e);return i.createTransactionForExecute({sender:c.Address.newFromBech32(this.config.userAddress),contract:c.Address.newFromBech32(r.address),function:r.func||"",gasLimit:BigInt(r.gasLimit),arguments:p,tokenTransfers:f,nativeTransferAmount:d})}getPositionValueFromUrl(r,t){let e=new URLSearchParams(this.url.search),i=r.inputs?.filter(o=>o.source==="query")?.find(o=>o.position===t)?.name;return i?e.get(i):null}getCombinedTokenTransfers(r,t){return[...r.transfers?.map(this.toTypedTransfer)||[],...t]}getModifiedInputArgs(r,t){let e=r.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=r.inputs?.find(T=>T.name===i);if(!p)throw new Error(`WarpActionExecutor: Scalable input ${i} not found`);let g=Number(p.position.split(":")[1])-1,d=BigInt(t[g].split(":")[1]),l=BigInt(t[o].split(":")[1])*BigInt(10)**d;t[o]=`${n.type}:${l}`}else{let o=Number(n.position.split(":")[1])-1,g=BigInt(t[o].split(":")[1])*BigInt(10)**BigInt(i);t[o]=`${n.type}:${g}`}}return t}getTypedArgsFromInput(r){return r.map(t=>{let[e,n]=t.split(":");return this.toTypedArg(n,e)})}toTypedTransfer(r){return new c.TokenTransfer({token:new c.Token({identifier:r.token,nonce:BigInt(r.nonce||0)}),amount:BigInt(r.amount||0)})}toTypedArg(r,t){if(t==="string")return c.BytesValue.fromUTF8(r);if(t==="uint8")return new c.U8Value(Number(r));if(t==="uint16")return new c.U16Value(Number(r));if(t==="uint32")return new c.U32Value(Number(r));if(t==="uint64")return new c.U64Value(BigInt(r));if(t==="biguint")return new c.BigUIntValue(BigInt(r));if(t==="boolean")return new c.BooleanValue(r==="true");if(t==="address")return new c.AddressValue(c.Address.newFromBech32(r));if(t==="hex")return c.BytesValue.fromHex(r);throw new Error(`WarpActionExecutor: Unsupported input type: ${t}`)}};var m=require("@multiversx/sdk-core"),k=x(require("ajv"));var b={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},B=class{constructor(){this.cache=new Map}set(r,t,e){let n=Date.now()+e*1e3;this.cache.set(r,{value:t,expiresAt:n})}get(r){let t=this.cache.get(r);return t?Date.now()>t.expiresAt?(this.cache.delete(r),null):t.value:null}clear(){this.cache.clear()}};var W=class{constructor(r){this.cache=new B;this.pendingWarp={protocol:I(u.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let t=new m.TransactionsFactoryConfig({chainID:y(this.config.env)}),e=new m.TransferTransactionsFactory({config:t}),n=JSON.stringify(r);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(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){let e=await this.createFromRaw(r.data.toString(),t);return e.meta={hash:r.hash,creator:r.sender.bech32(),createdAt:new Date(r.timestamp).toISOString()},e}async createFromTransactionHash(r,t){let e=b.Warp(r);if(t){let i=this.cache.get(e);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${r}`),i}let n=new m.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(r),o=await this.createFromTransaction(i);return t&&t.ttl&&o&&this.cache.set(e,o,t.ttl),o}catch(i){return console.error("WarpBuilder: Error creating from transaction hash",i),null}}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),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(r,t){if(!r)throw new Error(`WarpBuilder: ${t}`)}async ensureValidSchema(r){let t=this.config.warpSchemaUrl||u.LatestWarpSchemaUrl,n=await(await fetch(t)).json(),i=new k.default,o=i.compile(n);if(!o(r))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var O=x(require("qr-code-styling"));var s=require("@multiversx/sdk-core/out");var q={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"}],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:"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}]}],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 v=class{constructor(r){this.cache=new B;this.config=r,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(r,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");let e=t?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:t?[s.BytesValue.fromHex(r),s.BytesValue.fromUTF8(t)]:[s.BytesValue.fromHex(r)]})}createWarpAliasSetTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r),s.BytesValue.fromUTF8(t)]})}createBrandRegisterTransaction(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:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r)]})}createWarpPublishTransaction(r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),arguments:[s.BytesValue.fromHex(r)]})}createWarpBrandingTransaction(r,t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:s.Address.newFromBech32(this.config.userAddress),contract:s.Address.newFromBech32(u.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[s.BytesValue.fromHex(r),s.BytesValue.fromHex(t)]})}async getInfoByAlias(r,t){let e=b.RegistryInfo(r);if(t){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${r}`),l}let n=u.Registry.Contract(this.config.env),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[s.BytesValue.fromUTF8(r)]}),p=await i.runQuery(o),[g]=i.parseQueryResponse(p),d=g?A(g):null,f=d?.brand?await this.fetchBrand(d.brand):null;return t&&t.ttl&&this.cache.set(e,{registryInfo:d,brand:f},t.ttl),{registryInfo:d,brand:f}}async getInfoByHash(r,t){let e=b.RegistryInfo(r);if(t){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${r}`),l}let n=u.Registry.Contract(this.config.env),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[s.BytesValue.fromHex(r)]}),p=await i.runQuery(o),[g]=i.parseQueryResponse(p),d=g?A(g):null,f=d?.brand?await this.fetchBrand(d.brand):null;return t&&t.ttl&&this.cache.set(e,{registryInfo:d,brand:f},t.ttl),{registryInfo:d,brand:f}}async getUserWarpRegistryInfos(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=u.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserWarps",arguments:[new s.AddressValue(new s.Address(t))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o);return p.map(A)}async getUserBrands(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=u.Registry.Contract(this.config.env),n=this.getController(),i=n.createQuery({contract:e,function:"getUserBrands",arguments:[new s.AddressValue(new s.Address(t))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o),g=p.map(l=>l.toString("hex")),d={ttl:365*24*60*60};return(await Promise.all(g.map(l=>this.fetchBrand(l,d)))).filter(l=>l!==null)}async fetchBrand(r,t){let e=b.Brand(r);if(t){let i=this.cache.get(e);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${r}`),i}let n=new s.ApiNetworkProvider(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let i=await n.getTransaction(r),o=JSON.parse(i.data.toString());return o.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp).toISOString()},t&&t.ttl&&this.cache.set(e,o,t.ttl),o}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}async loadRegistryConfigs(){let r=u.Registry.Contract(this.config.env),t=this.getController(),e=t.createQuery({contract:r,function:"getConfig",arguments:[]}),n=await t.runQuery(e),[i]=t.parseQueryResponse(n),o=BigInt(i.toString());this.unitPrice=o}getFactory(){let r=new s.TransactionsFactoryConfig({chainID:y(this.config.env)}),t=s.AbiRegistry.create(q);return new s.SmartContractTransactionsFactory({config:r,abi:t})}getController(){let r=this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env),t=new s.ApiNetworkProvider(r,{timeout:3e4}),e=new s.QueryRunnerAdapter({networkProvider:t}),n=s.AbiRegistry.create(q);return new s.SmartContractQueriesController({queryRunner:e,abi:n})}};var E="xwarp",R=":",$="alias",L=class{constructor(r){this.config=r;this.config=r}async detect(r){let n=new URL(r).searchParams.get(E);if(!n)return{match:!1,warp:null,registryInfo:null,brand:null};let i=decodeURIComponent(n),o=i.includes(R)?i:`${$}${R}${i}`,[p,g]=o.split(R),d=new W(this.config),f=new v(this.config),l=null,T=null,P=null;if(p==="hash"){l=await d.createFromTransactionHash(g);try{let{registryInfo:w,brand:F}=await f.getInfoByHash(g);T=w,P=F}catch{}}else if(p==="alias"){let{registryInfo:w,brand:F}=await f.getInfoByAlias(g);T=w,P=F,w&&(l=await d.createFromTransactionHash(w.hash))}return l?{match:!0,warp:l,registryInfo:T,brand:P}:{match:!1,warp:null,registryInfo:null,brand:null}}build(r,t){let e=this.config.clientUrl||u.DefaultClientUrl(this.config.env);return r===$?`${e}?${E}=${encodeURIComponent(t)}`:`${e}?${E}=${encodeURIComponent(r+R+t)}`}generateQrCode(r,t,e=512,n="white",i="black",o="#23F7DD"){let p=this.build(r,t);return new O.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>`})}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpBuilder,WarpLink,WarpRegistry});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Address as x,ApiNetworkProvider as D,TransactionsFactoryConfig as $,TransferTransactionsFactory as _}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:i=>i==="devnet"?"https://devnet.xwarp.me/to":i==="testnet"?"###Not implemented###":"https://xwarp.me/to",Chain:{ApiUrl:i=>i==="devnet"?"https://devnet-api.multiversx.com":i==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:i=>i==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":i==="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=i=>i==="devnet"?"D":i==="testnet"?"T":"1",B=i=>`${i}:${o.LatestProtocolVersion}`,T=i=>{var r,t,e;return{hash:i.hash.toString("hex"),alias:((r=i.alias)==null?void 0:r.toString())||null,trust:i.trust.toString(),creator:i.creator.toString(),createdAt:i.created_at.toNumber(),brand:((t=i.brand)==null?void 0:t.toString("hex"))||null,upgrade:((e=i.upgrade)==null?void 0:e.toString("hex"))||null}};var U=class{config;pendingBrand={protocol:B(o.ProtocolNameBrand),name:"",description:"",logo:""};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let t=new $({chainID:m(this.config.env)}),e=new _({config:t}),a=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:x.newFromBech32(this.config.userAddress),receiver:x.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(a).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){return await this.createFromRaw(r.data.toString(),t)}async createFromTransactionHash(r){let t=new D(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let e=await t.getTransaction(r);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,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(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.brandSchemaUrl||o.LatestBrandSchemaUrl,a=await(await fetch(t)).json(),n=new Q,s=n.compile(a);if(!s(r))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import{Address as R,AddressValue as H,BigUIntValue as j,BooleanValue as K,BytesValue as q,SmartContractTransactionsFactory as G,Token as J,TokenTransfer as z,TransactionsFactoryConfig as M,U16Value as Z,U32Value as X,U64Value as Y,U8Value as rr}from"@multiversx/sdk-core/out";var S=class{config;url;constructor(r,t){this.config=r,this.url=new URL(t)}createTransactionForExecute(r,t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let a=new M({chainID:m(this.config.env)}),n=new G({config:a}),s=this.getTypedArgsFromInput(t),u=this.getPositionValueFromUrl(r,"value"),p=BigInt(u||r.value||0),c=this.getCombinedTokenTransfers(r,e);return n.createTransactionForExecute({sender:R.newFromBech32(this.config.userAddress),contract:R.newFromBech32(r.address),function:r.func||"",gasLimit:BigInt(r.gasLimit),arguments:s,tokenTransfers:c,nativeTransferAmount:p})}getPositionValueFromUrl(r,t){var s,u;let e=new URLSearchParams(this.url.search),a=(s=r.inputs)==null?void 0:s.filter(p=>p.source==="query"),n=(u=a==null?void 0:a.find(p=>p.position===t))==null?void 0:u.name;return n?e.get(n):null}getCombinedTokenTransfers(r,t){var a;return[...((a=r.transfers)==null?void 0:a.map(this.toTypedTransfer))||[],...t]}getTypedArgsFromInput(r){return r.map(t=>{let[e,a]=t.split(":");return this.toTypedArg(a,e)})}toTypedTransfer(r){return new z({token:new J({identifier:r.token,nonce:BigInt(r.nonce||0)}),amount:BigInt(r.amount||0)})}toTypedArg(r,t){if(t==="string")return q.fromUTF8(r);if(t==="uint8")return new rr(Number(r));if(t==="uint16")return new Z(Number(r));if(t==="uint32")return new X(Number(r));if(t==="uint64")return new Y(BigInt(r));if(t==="biguint")return new j(BigInt(r));if(t==="boolean")return new K(r==="true");if(t==="address")return new H(R.newFromBech32(r));if(t==="hex")return q.fromHex(r);throw new Error(`WarpActionExecutor: Unsupported input type: ${t}`)}};import{Address as E,ApiNetworkProvider as tr,TransactionsFactoryConfig as er,TransferTransactionsFactory as nr}from"@multiversx/sdk-core";import ar from"ajv";var w={Warp:i=>`warp:${i}`,RegistryInfo:i=>`registry-info:${i}`,Brand:i=>`brand:${i}`},y=class{cache=new Map;set(r,t,e){let a=Date.now()+e*1e3;this.cache.set(r,{value:t,expiresAt:a})}get(r){let t=this.cache.get(r);return t?Date.now()>t.expiresAt?(this.cache.delete(r),null):t.value:null}clear(){this.cache.clear()}};var b=class{config;cache=new y;pendingWarp={protocol:B(o.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};constructor(r){this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let t=new er({chainID:m(this.config.env)}),e=new nr({config:t}),a=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:E.newFromBech32(this.config.userAddress),receiver:E.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(a).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){let e=await this.createFromRaw(r.data.toString(),t);return e.meta={hash:r.hash,creator:r.sender.bech32(),createdAt:new Date(r.timestamp).toISOString()},e}async createFromTransactionHash(r,t){let e=w.Warp(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${r}`),n}let a=new tr(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let n=await a.getTransaction(r),s=await this.createFromTransaction(n);return t&&t.ttl&&s&&this.cache.set(e,s,t.ttl),s}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),null}}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),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(r,t){if(!r)throw new Error(`WarpBuilder: ${t}`)}async ensureValidSchema(r){let t=this.config.warpSchemaUrl||o.LatestWarpSchemaUrl,a=await(await fetch(t)).json(),n=new ar,s=n.compile(a);if(!s(r))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import pr from"qr-code-styling";import{AbiRegistry as L,Address as g,AddressValue as k,ApiNetworkProvider as N,BytesValue as l,QueryRunnerAdapter as sr,SmartContractQueriesController as or,SmartContractTransactionsFactory as cr,TransactionsFactoryConfig as ur}from"@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:"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}]}],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 v=class{config;unitPrice;cache=new y;constructor(r){this.config=r,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(r,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");let e=t?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:t?[l.fromHex(r),l.fromUTF8(t)]:[l.fromHex(r)]})}createWarpAliasSetTransaction(r,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:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.fromHex(r),l.fromUTF8(t)]})}createBrandRegisterTransaction(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(o.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.fromHex(r)]})}createWarpPublishTransaction(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:"publishWarp",gasLimit:BigInt(1e7),arguments:[l.fromHex(r)]})}createWarpBrandingTransaction(r,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:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[l.fromHex(r),l.fromHex(t)]})}async getInfoByAlias(r,t){let e=w.RegistryInfo(r);if(t){let d=this.cache.get(e);if(d)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${r}`),d}let a=o.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:a,function:"getInfoByAlias",arguments:[l.fromUTF8(r)]}),u=await n.runQuery(s),[p]=n.parseQueryResponse(u),c=p?T(p):null,h=c!=null&&c.brand?await this.fetchBrand(c.brand):null;return t&&t.ttl&&this.cache.set(e,{registryInfo:c,brand:h},t.ttl),{registryInfo:c,brand:h}}async getInfoByHash(r,t){let e=w.RegistryInfo(r);if(t){let d=this.cache.get(e);if(d)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${r}`),d}let a=o.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:a,function:"getInfoByHash",arguments:[l.fromHex(r)]}),u=await n.runQuery(s),[p]=n.parseQueryResponse(u),c=p?T(p):null,h=c!=null&&c.brand?await this.fetchBrand(c.brand):null;return t&&t.ttl&&this.cache.set(e,{registryInfo:c,brand:h},t.ttl),{registryInfo:c,brand:h}}async getUserWarpRegistryInfos(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),a=this.getController(),n=a.createQuery({contract:e,function:"getUserWarps",arguments:[new k(new g(t))]}),s=await a.runQuery(n),[u]=a.parseQueryResponse(s);return u.map(T)}async getUserBrands(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),a=this.getController(),n=a.createQuery({contract:e,function:"getUserBrands",arguments:[new k(new g(t))]}),s=await a.runQuery(n),[u]=a.parseQueryResponse(s),p=u.map(d=>d.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(p.map(d=>this.fetchBrand(d,c)))).filter(d=>d!==null)}async fetchBrand(r,t){let e=w.Brand(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${r}`),n}let a=new N(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let n=await a.getTransaction(r),s=JSON.parse(n.data.toString());return s.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp).toISOString()},t&&t.ttl&&this.cache.set(e,s,t.ttl),s}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}async loadRegistryConfigs(){let r=o.Registry.Contract(this.config.env),t=this.getController(),e=t.createQuery({contract:r,function:"getConfig",arguments:[]}),a=await t.runQuery(e),[n]=t.parseQueryResponse(a),s=BigInt(n.toString());this.unitPrice=s}getFactory(){let r=new ur({chainID:m(this.config.env)}),t=L.create(P);return new cr({config:r,abi:t})}getController(){let r=this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env),t=new N(r,{timeout:3e4}),e=new sr({networkProvider:t}),a=L.create(P);return new or({queryRunner:e,abi:a})}};var F="xwarp",C=":",V="alias",O=class{constructor(r){this.config=r;this.config=r}async detect(r){let a=new URL(r).searchParams.get(F);if(!a)return{match:!1,warp:null,registryInfo:null,brand:null};let n=decodeURIComponent(a),s=n.includes(C)?n:`${V}${C}${n}`,[u,p]=s.split(C),c=new b(this.config),h=new v(this.config),d=null,W=null,A=null;if(u==="hash"){d=await c.createFromTransactionHash(p);try{let{registryInfo:f,brand:I}=await h.getInfoByHash(p);W=f,A=I}catch{}}else if(u==="alias"){let{registryInfo:f,brand:I}=await h.getInfoByAlias(p);f&&(d=await c.createFromTransactionHash(f.hash),W=f,A=I)}return d?{match:!0,warp:d,registryInfo:W,brand:A}:{match:!1,warp:null,registryInfo:null,brand:null}}build(r,t){let e=this.config.clientUrl||o.DefaultClientUrl(this.config.env);return r===V?`${e}?${F}=${encodeURIComponent(t)}`:`${e}?${F}=${encodeURIComponent(r+C+t)}`}generateQrCode(r,t,e=512,a="white",n="black",s="#23F7DD"){let u=this.build(r,t);return new pr({type:"svg",width:e,height:e,data:String(u),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:a},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>`})}};export{U as BrandBuilder,o as Config,S as WarpActionExecutor,b as WarpBuilder,O as WarpLink,v as WarpRegistry};
|
|
1
|
+
import{Address as x,ApiNetworkProvider as O,TransactionsFactoryConfig as D,TransferTransactionsFactory as Q}from"@multiversx/sdk-core";import _ 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:s=>s==="devnet"?"https://devnet.xwarp.me/to":s==="testnet"?"###Not implemented###":"https://xwarp.me/to",Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var h=s=>s==="devnet"?"D":s==="testnet"?"T":"1",b=s=>`${s}:${o.LatestProtocolVersion}`,T=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 U=class{constructor(r){this.pendingBrand={protocol:b(o.ProtocolNameBrand),name:"",description:"",logo:""};this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let t=new D({chainID:h(this.config.env)}),e=new Q({config:t}),i=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:x.newFromBech32(this.config.userAddress),receiver:x.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){return await this.createFromRaw(r.data.toString(),t)}async createFromTransactionHash(r){let t=new O(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let e=await t.getTransaction(r);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}setName(r){return this.pendingBrand.name=r,this}setDescription(r){return this.pendingBrand.description=r,this}setLogo(r){return this.pendingBrand.logo=r,this}setUrls(r){return this.pendingBrand.urls=r,this}setColors(r){return this.pendingBrand.colors=r,this}setCta(r){return this.pendingBrand.cta=r,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(r,t){if(!r)throw new Error(`Warp: ${t}`)}async ensureValidSchema(r){let t=this.config.brandSchemaUrl||o.LatestBrandSchemaUrl,i=await(await fetch(t)).json(),n=new _,a=n.compile(i);if(!a(r))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};import{Address as R,AddressValue as H,BigUIntValue as j,BooleanValue as K,BytesValue as S,SmartContractTransactionsFactory as G,Token as M,TokenTransfer as J,TransactionsFactoryConfig as z,U16Value as Z,U32Value as X,U64Value as Y,U8Value as rr}from"@multiversx/sdk-core/out";var q=class{constructor(r,t){this.config=r,this.url=new URL(t)}createTransactionForExecute(r,t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=new z({chainID:h(this.config.env)}),n=new G({config:i}),a=this.getModifiedInputArgs(r,t),c=this.getTypedArgsFromInput(a),d=this.getPositionValueFromUrl(r,"value"),u=BigInt(d||r.value||0),l=this.getCombinedTokenTransfers(r,e);return n.createTransactionForExecute({sender:R.newFromBech32(this.config.userAddress),contract:R.newFromBech32(r.address),function:r.func||"",gasLimit:BigInt(r.gasLimit),arguments:c,tokenTransfers:l,nativeTransferAmount:u})}getPositionValueFromUrl(r,t){let e=new URLSearchParams(this.url.search),n=r.inputs?.filter(a=>a.source==="query")?.find(a=>a.position===t)?.name;return n?e.get(n):null}getCombinedTokenTransfers(r,t){return[...r.transfers?.map(this.toTypedTransfer)||[],...t]}getModifiedInputArgs(r,t){let e=r.inputs?.filter(i=>!!i.modifier&&i.position.startsWith("arg:"))||[];for(let i of e)if(i.modifier?.startsWith("scale:")){let[,n]=i.modifier.split(":");if(isNaN(Number(n))){let a=Number(i.position.split(":")[1])-1,c=r.inputs?.find(B=>B.name===n);if(!c)throw new Error(`WarpActionExecutor: Scalable input ${n} not found`);let d=Number(c.position.split(":")[1])-1,u=BigInt(t[d].split(":")[1]),p=BigInt(t[a].split(":")[1])*BigInt(10)**u;t[a]=`${i.type}:${p}`}else{let a=Number(i.position.split(":")[1])-1,d=BigInt(t[a].split(":")[1])*BigInt(10)**BigInt(n);t[a]=`${i.type}:${d}`}}return t}getTypedArgsFromInput(r){return r.map(t=>{let[e,i]=t.split(":");return this.toTypedArg(i,e)})}toTypedTransfer(r){return new J({token:new M({identifier:r.token,nonce:BigInt(r.nonce||0)}),amount:BigInt(r.amount||0)})}toTypedArg(r,t){if(t==="string")return S.fromUTF8(r);if(t==="uint8")return new rr(Number(r));if(t==="uint16")return new Z(Number(r));if(t==="uint32")return new X(Number(r));if(t==="uint64")return new Y(BigInt(r));if(t==="biguint")return new j(BigInt(r));if(t==="boolean")return new K(r==="true");if(t==="address")return new H(R.newFromBech32(r));if(t==="hex")return S.fromHex(r);throw new Error(`WarpActionExecutor: Unsupported input type: ${t}`)}};import{Address as E,ApiNetworkProvider as tr,TransactionsFactoryConfig as er,TransferTransactionsFactory as nr}from"@multiversx/sdk-core";import ir from"ajv";var w={Warp:s=>`warp:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},y=class{constructor(){this.cache=new Map}set(r,t,e){let i=Date.now()+e*1e3;this.cache.set(r,{value:t,expiresAt:i})}get(r){let t=this.cache.get(r);return t?Date.now()>t.expiresAt?(this.cache.delete(r),null):t.value:null}clear(){this.cache.clear()}};var W=class{constructor(r){this.cache=new y;this.pendingWarp={protocol:b(o.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=r}createInscriptionTransaction(r){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let t=new er({chainID:h(this.config.env)}),e=new nr({config:t}),i=JSON.stringify(r);return e.createTransactionForNativeTokenTransfer({sender:E.newFromBech32(this.config.userAddress),receiver:E.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(r,t=!0){let e=JSON.parse(r);return t&&await this.ensureValidSchema(e),e}async createFromTransaction(r,t=!1){let e=await this.createFromRaw(r.data.toString(),t);return e.meta={hash:r.hash,creator:r.sender.bech32(),createdAt:new Date(r.timestamp).toISOString()},e}async createFromTransactionHash(r,t){let e=w.Warp(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${r}`),n}let i=new tr(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(r),a=await this.createFromTransaction(n);return t&&t.ttl&&a&&this.cache.set(e,a,t.ttl),a}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),null}}setName(r){return this.pendingWarp.name=r,this}setTitle(r){return this.pendingWarp.title=r,this}setDescription(r){return this.pendingWarp.description=r,this}setPreview(r){return this.pendingWarp.preview=r,this}setActions(r){return this.pendingWarp.actions=r,this}addAction(r){return this.pendingWarp.actions.push(r),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(r,t){if(!r)throw new Error(`WarpBuilder: ${t}`)}async ensureValidSchema(r){let t=this.config.warpSchemaUrl||o.LatestWarpSchemaUrl,i=await(await fetch(t)).json(),n=new ir,a=n.compile(i);if(!a(r))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};import pr from"qr-code-styling";import{AbiRegistry as L,Address as g,AddressValue as N,ApiNetworkProvider as V,BytesValue as f,QueryRunnerAdapter as sr,SmartContractQueriesController as or,SmartContractTransactionsFactory as cr,TransactionsFactoryConfig as ur}from"@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:"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}]}],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 v=class{constructor(r){this.cache=new y;this.config=r,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(r,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");let e=t?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:t?[f.fromHex(r),f.fromUTF8(t)]:[f.fromHex(r)]})}createWarpAliasSetTransaction(r,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:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(r),f.fromUTF8(t)]})}createBrandRegisterTransaction(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(o.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(r)]})}createWarpPublishTransaction(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:"publishWarp",gasLimit:BigInt(1e7),arguments:[f.fromHex(r)]})}createWarpBrandingTransaction(r,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:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(r),f.fromHex(t)]})}async getInfoByAlias(r,t){let e=w.RegistryInfo(r);if(t){let p=this.cache.get(e);if(p)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${r}`),p}let i=o.Registry.Contract(this.config.env),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[f.fromUTF8(r)]}),c=await n.runQuery(a),[d]=n.parseQueryResponse(c),u=d?T(d):null,l=u?.brand?await this.fetchBrand(u.brand):null;return t&&t.ttl&&this.cache.set(e,{registryInfo:u,brand:l},t.ttl),{registryInfo:u,brand:l}}async getInfoByHash(r,t){let e=w.RegistryInfo(r);if(t){let p=this.cache.get(e);if(p)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${r}`),p}let i=o.Registry.Contract(this.config.env),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByHash",arguments:[f.fromHex(r)]}),c=await n.runQuery(a),[d]=n.parseQueryResponse(c),u=d?T(d):null,l=u?.brand?await this.fetchBrand(u.brand):null;return t&&t.ttl&&this.cache.set(e,{registryInfo:u,brand:l},t.ttl),{registryInfo:u,brand:l}}async getUserWarpRegistryInfos(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:e,function:"getUserWarps",arguments:[new N(new g(t))]}),a=await i.runQuery(n),[c]=i.parseQueryResponse(a);return c.map(T)}async getUserBrands(r){let t=r||this.config.userAddress;if(!t)throw new Error("WarpRegistry: user address not set");let e=o.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:e,function:"getUserBrands",arguments:[new N(new g(t))]}),a=await i.runQuery(n),[c]=i.parseQueryResponse(a),d=c.map(p=>p.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(d.map(p=>this.fetchBrand(p,u)))).filter(p=>p!==null)}async fetchBrand(r,t){let e=w.Brand(r);if(t){let n=this.cache.get(e);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${r}`),n}let i=new V(this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(r),a=JSON.parse(n.data.toString());return a.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp).toISOString()},t&&t.ttl&&this.cache.set(e,a,t.ttl),a}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}async loadRegistryConfigs(){let r=o.Registry.Contract(this.config.env),t=this.getController(),e=t.createQuery({contract:r,function:"getConfig",arguments:[]}),i=await t.runQuery(e),[n]=t.parseQueryResponse(i),a=BigInt(n.toString());this.unitPrice=a}getFactory(){let r=new ur({chainID:h(this.config.env)}),t=L.create(P);return new cr({config:r,abi:t})}getController(){let r=this.config.chainApiUrl||o.Chain.ApiUrl(this.config.env),t=new V(r,{timeout:3e4}),e=new sr({networkProvider:t}),i=L.create(P);return new or({queryRunner:e,abi:i})}};var F="xwarp",C=":",k="alias",$=class{constructor(r){this.config=r;this.config=r}async detect(r){let i=new URL(r).searchParams.get(F);if(!i)return{match:!1,warp:null,registryInfo:null,brand:null};let n=decodeURIComponent(i),a=n.includes(C)?n:`${k}${C}${n}`,[c,d]=a.split(C),u=new W(this.config),l=new v(this.config),p=null,B=null,I=null;if(c==="hash"){p=await u.createFromTransactionHash(d);try{let{registryInfo:m,brand:A}=await l.getInfoByHash(d);B=m,I=A}catch{}}else if(c==="alias"){let{registryInfo:m,brand:A}=await l.getInfoByAlias(d);B=m,I=A,m&&(p=await u.createFromTransactionHash(m.hash))}return p?{match:!0,warp:p,registryInfo:B,brand:I}:{match:!1,warp:null,registryInfo:null,brand:null}}build(r,t){let e=this.config.clientUrl||o.DefaultClientUrl(this.config.env);return r===k?`${e}?${F}=${encodeURIComponent(t)}`:`${e}?${F}=${encodeURIComponent(r+C+t)}`}generateQrCode(r,t,e=512,i="white",n="black",a="#23F7DD"){let c=this.build(r,t);return new pr({type:"svg",width:e,height:e,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}};export{U as BrandBuilder,o as Config,q as WarpActionExecutor,W as WarpBuilder,$ as WarpLink,v as WarpRegistry};
|