@vleap/warps 0.1.0 → 0.2.0
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 +10 -3
- package/dist/index.d.ts +10 -3
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -166,6 +166,7 @@ declare const Config: {
|
|
|
166
166
|
declare class WarpActionExecutor {
|
|
167
167
|
private config;
|
|
168
168
|
private url;
|
|
169
|
+
private serializer;
|
|
169
170
|
constructor(config: WarpConfig, url: string);
|
|
170
171
|
createTransactionForExecute(action: WarpContractAction, inputs: string[], inputTransfers: TokenTransfer[]): Transaction$1;
|
|
171
172
|
getNativeValueFromField(action: WarpAction, inputs: string[]): string | null;
|
|
@@ -173,9 +174,15 @@ declare class WarpActionExecutor {
|
|
|
173
174
|
getCombinedTokenTransfers(action: WarpContractAction, inputTransfers: TokenTransfer[]): TokenTransfer[];
|
|
174
175
|
getModifiedInputs(action: WarpContractAction, inputs: string[]): string[];
|
|
175
176
|
getCombinedInputs(action: WarpContractAction, inputArgs: string[]): string[];
|
|
176
|
-
getTypedArgsFromInput(inputArgs: string[]): TypedValue[];
|
|
177
177
|
private toTypedTransfer;
|
|
178
|
-
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
type NativeValue = string | number | bigint | boolean;
|
|
181
|
+
declare class WarpArgSerializer {
|
|
182
|
+
nativeToStrings(type: WarpActionInputType, value: NativeValue): string;
|
|
183
|
+
stringToNative(value: string): NativeValue;
|
|
184
|
+
nativeToTyped(type: WarpActionInputType, value: NativeValue): TypedValue;
|
|
185
|
+
stringToTyped(value: string): TypedValue;
|
|
179
186
|
}
|
|
180
187
|
|
|
181
188
|
declare class WarpBuilder {
|
|
@@ -262,4 +269,4 @@ declare class WarpUtils {
|
|
|
262
269
|
static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
|
|
263
270
|
}
|
|
264
271
|
|
|
265
|
-
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 };
|
|
272
|
+
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, WarpArgSerializer, 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
|
@@ -166,6 +166,7 @@ declare const Config: {
|
|
|
166
166
|
declare class WarpActionExecutor {
|
|
167
167
|
private config;
|
|
168
168
|
private url;
|
|
169
|
+
private serializer;
|
|
169
170
|
constructor(config: WarpConfig, url: string);
|
|
170
171
|
createTransactionForExecute(action: WarpContractAction, inputs: string[], inputTransfers: TokenTransfer[]): Transaction$1;
|
|
171
172
|
getNativeValueFromField(action: WarpAction, inputs: string[]): string | null;
|
|
@@ -173,9 +174,15 @@ declare class WarpActionExecutor {
|
|
|
173
174
|
getCombinedTokenTransfers(action: WarpContractAction, inputTransfers: TokenTransfer[]): TokenTransfer[];
|
|
174
175
|
getModifiedInputs(action: WarpContractAction, inputs: string[]): string[];
|
|
175
176
|
getCombinedInputs(action: WarpContractAction, inputArgs: string[]): string[];
|
|
176
|
-
getTypedArgsFromInput(inputArgs: string[]): TypedValue[];
|
|
177
177
|
private toTypedTransfer;
|
|
178
|
-
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
type NativeValue = string | number | bigint | boolean;
|
|
181
|
+
declare class WarpArgSerializer {
|
|
182
|
+
nativeToStrings(type: WarpActionInputType, value: NativeValue): string;
|
|
183
|
+
stringToNative(value: string): NativeValue;
|
|
184
|
+
nativeToTyped(type: WarpActionInputType, value: NativeValue): TypedValue;
|
|
185
|
+
stringToTyped(value: string): TypedValue;
|
|
179
186
|
}
|
|
180
187
|
|
|
181
188
|
declare class WarpBuilder {
|
|
@@ -262,4 +269,4 @@ declare class WarpUtils {
|
|
|
262
269
|
static getNextStepUrl(warp: Warp, config: WarpConfig): string | null;
|
|
263
270
|
}
|
|
264
271
|
|
|
265
|
-
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 };
|
|
272
|
+
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, WarpArgSerializer, 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 Q=Object.create;var x=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var G=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty;var K=(s,t)=>{for(var r in t)x(s,r,{get:t[r],enumerable:!0})},k=(s,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of M(t))!J.call(s,e)&&e!==r&&x(s,e,{get:()=>t[e],enumerable:!(n=j(t,e))||n.enumerable});return s};var U=(s,t,r)=>(r=s!=null?Q(G(s)):{},k(t||!s||!s.__esModule?x(r,"default",{value:s,enumerable:!0}):r,s)),z=s=>k(x({},"__esModule",{value:!0}),s);var Y={};K(Y,{BrandBuilder:()=>E,Config:()=>l,WarpActionExecutor:()=>q,WarpBuilder:()=>T,WarpLink:()=>v,WarpRegistry:()=>I,WarpUtils:()=>w});module.exports=z(Y);var m=require("@multiversx/sdk-core"),$=U(require("ajv"));var l={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",R=s=>`${s}:${l.LatestProtocolVersion}`,F=s=>({hash:s.hash.toString("hex"),alias:s.alias?.toString()||null,trust:s.trust.toString(),creator:s.creator.toString(),createdAt:s.created_at.toNumber(),brand:s.brand?.toString("hex")||null,upgrade:s.upgrade?.toString("hex")||null}),S=(s,t)=>{let r=s.toString(),[n,e=""]=r.split("."),i=Math.abs(t);if(t>0)return BigInt(n+e.padEnd(i,"0"));if(t<0){let a=n+e;if(i>=a.length)return 0n;let c=a.slice(0,-i)||"0";return BigInt(c)}else return BigInt(s)},D=(s,t=100)=>{if(!s)return"";let r=s.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r};var E=class{constructor(t){this.pendingBrand={protocol:R(l.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new m.TransactionsFactoryConfig({chainID:y(this.config.env)}),n=new m.TransferTransactionsFactory({config:r}),e=JSON.stringify(t);return n.createTransactionForNativeTokenTransfer({sender:m.Address.newFromBech32(this.config.userAddress),receiver:m.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(e).valueOf()})}async createFromRaw(t,r=!0){let n=JSON.parse(t);return r&&await this.ensureValidSchema(n),n}async createFromTransaction(t,r=!1){return await this.createFromRaw(t.data.toString(),r)}async createFromTransactionHash(t){let r=new m.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let n=await r.getTransaction(t);return this.createFromTransaction(n)}catch(n){return console.error("BrandBuilder: Error creating from transaction hash",n),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.brandSchemaUrl||l.LatestBrandSchemaUrl,e=await(await fetch(r)).json(),i=new $.default,a=i.compile(e);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};var p=require("@multiversx/sdk-core/out");var q=class{constructor(t,r){this.config=t,this.url=new URL(r)}createTransactionForExecute(t,r,n){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let e=p.Address.newFromBech32(this.config.userAddress),i=p.Address.newFromBech32(t.address),a=new p.TransactionsFactoryConfig({chainID:y(this.config.env)}),c=this.getModifiedInputs(t,r),d=this.getCombinedInputs(t,c),u=this.getTypedArgsFromInput(d),f=this.getNativeValueFromField(t,c),g=this.getNativeValueFromUrl(t),C=BigInt(f||g||t.value||0),A=this.getCombinedTokenTransfers(t,n);return i.isContractAddress()?new p.SmartContractTransactionsFactory({config:a}).createTransactionForExecute({sender:e,contract:i,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:u,tokenTransfers:A,nativeTransferAmount:C}):new p.TransferTransactionsFactory({config:a}).createTransactionForTransfer({sender:e,receiver:i,nativeAmount:C,tokenTransfers:A,data:u[0]?.hasExactClass(p.BytesValue.ClassName)?u[0].valueOf():void 0})}getNativeValueFromField(t,r){let n=(t.inputs||[]).findIndex(i=>i.source==="field"&&i.position==="value"),e=n!==-1?r[n]:null;return e?e.split(":")[1]:null}getNativeValueFromUrl(t){let r=new URLSearchParams(this.url.search),e=t.inputs?.filter(i=>i.source==="query")?.find(i=>i.position==="value")?.name;return e?r.get(e):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputs(t,r){return(t.inputs?.filter(e=>!!e.modifier)||[]).forEach((e,i)=>{if(e.modifier?.startsWith("scale:")){let[,a]=e.modifier.split(":");if(isNaN(Number(a))){let c=e.position.startsWith("arg:")?Number(e.position.split(":")[1])-1:i,d=t.inputs?.find(A=>A.name===a);if(!d)throw new Error(`WarpActionExecutor: Scalable input ${a} not found`);let u=Number(d.position.split(":")[1])-1,f=r[u].split(":")[1],g=r[c].split(":")[1],C=S(g,+f);r[c]=`${e.type}:${C}`}else{let c=e.position.startsWith("arg:")?Number(e.position.split(":")[1])-1:i,d=r[c].split(":")[1],u=S(d,+a);r[c]=`${e.type}:${u}`}}}),r}getCombinedInputs(t,r){let e=(t.inputs?.filter(a=>a.source==="field"&&a.position.startsWith("arg:"))||[]).map((a,c)=>({input:a,value:r[c]})),i=t.args||[];return e.forEach(({input:a,value:c})=>{let d=Number(a.position.split(":")[1])-1;i.splice(d,0,c)}),i}getTypedArgsFromInput(t){return t.map(r=>{let[n,e]=r.split(":");return this.toTypedArg(e,n)})}toTypedTransfer(t){return new p.TokenTransfer({token:new p.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}toTypedArg(t,r){if(r==="string")return p.BytesValue.fromUTF8(t);if(r==="uint8")return new p.U8Value(Number(t));if(r==="uint16")return new p.U16Value(Number(t));if(r==="uint32")return new p.U32Value(Number(t));if(r==="uint64")return new p.U64Value(BigInt(t));if(r==="biguint")return new p.BigUIntValue(BigInt(t));if(r==="boolean")return new p.BooleanValue(t==="true");if(r==="address")return new p.AddressValue(p.Address.newFromBech32(t));if(r==="hex")return p.BytesValue.fromHex(t);throw new Error(`WarpActionExecutor: Unsupported input type: ${r}`)}};var h=require("@multiversx/sdk-core"),H=U(require("ajv"));var W={Warp:s=>`warp:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},b=class{constructor(){this.cache=new Map}set(t,r,n){let e=Date.now()+n*1e3;this.cache.set(t,{value:r,expiresAt:e})}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 L="https://",V="warp",B=":",P="alias";var O=U(require("qr-code-styling"));var o=require("@multiversx/sdk-core/out");var N={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var I=class{constructor(t){this.cache=new b;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 n=r?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:n,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(l.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[o.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,r){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(l.Registry.Contract(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[o.BytesValue.fromUTF8(t),o.BytesValue.fromHex(r)]})}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(l.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(l.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(l.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(l.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 n=W.RegistryInfo(t);if(r){let g=this.cache.get(n);if(g)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),g}let e=l.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:e,function:"getInfoByAlias",arguments:[o.BytesValue.fromUTF8(t)]}),c=await i.runQuery(a),[d]=i.parseQueryResponse(c),u=d?F(d):null,f=u?.brand?await this.fetchBrand(u.brand):null;return r&&r.ttl&&this.cache.set(n,{registryInfo:u,brand:f},r.ttl),{registryInfo:u,brand:f}}async getInfoByHash(t,r){let n=W.RegistryInfo(t);if(r){let g=this.cache.get(n);if(g)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),g}let e=l.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:e,function:"getInfoByHash",arguments:[o.BytesValue.fromHex(t)]}),c=await i.runQuery(a),[d]=i.parseQueryResponse(c),u=d?F(d):null,f=u?.brand?await this.fetchBrand(u.brand):null;return r&&r.ttl&&this.cache.set(n,{registryInfo:u,brand:f},r.ttl),{registryInfo:u,brand:f}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let n=l.Registry.Contract(this.config.env),e=this.getController(),i=e.createQuery({contract:n,function:"getUserWarps",arguments:[new o.AddressValue(new o.Address(r))]}),a=await e.runQuery(i),[c]=e.parseQueryResponse(a);return c.map(F)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let n=l.Registry.Contract(this.config.env),e=this.getController(),i=e.createQuery({contract:n,function:"getUserBrands",arguments:[new o.AddressValue(new o.Address(r))]}),a=await e.runQuery(i),[c]=e.parseQueryResponse(a),d=c.map(g=>g.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(d.map(g=>this.fetchBrand(g,u)))).filter(g=>g!==null)}async fetchBrand(t,r){let n=W.Brand(t);if(r){let i=this.cache.get(n);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let e=new o.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let i=await e.getTransaction(t),a=JSON.parse(i.data.toString());return a.meta={hash:i.hash,creator:i.sender.bech32(),createdAt:new Date(i.timestamp*1e3).toISOString()},r&&r.ttl&&this.cache.set(n,a,r.ttl),a}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}async loadRegistryConfigs(){let t=l.Registry.Contract(this.config.env),r=this.getController(),n=r.createQuery({contract:t,function:"getConfig",arguments:[]}),e=await r.runQuery(n),[i]=r.parseQueryResponse(e),a=BigInt(i.toString());this.unitPrice=a}getFactory(){let t=new o.TransactionsFactoryConfig({chainID:y(this.config.env)}),r=o.AbiRegistry.create(N);return new o.SmartContractTransactionsFactory({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env),r=new o.ApiNetworkProvider(t,{timeout:3e4}),n=new o.QueryRunnerAdapter({networkProvider:r}),e=o.AbiRegistry.create(N);return new o.SmartContractQueriesController({queryRunner:n,abi:e})}};var v=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(L)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let e=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),a=(await Promise.all(e)).filter(u=>u.match),c=a.length>0,d=a.map(u=>({url:u.url,warp:u.warp}));return{match:c,results:d}}async detect(t){let r=t.startsWith(L)?this.extractIdentifierInfoFromUrl(t):w.getInfoFromPrefixedIdentifier(t);if(!r)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:n,id:e}=r,i=new T(this.config),a=new I(this.config),c=null,d=null,u=null;if(n==="hash"){c=await i.createFromTransactionHash(e);try{let{registryInfo:f,brand:g}=await a.getInfoByHash(e);d=f,u=g}catch{}}else if(n==="alias"){let{registryInfo:f,brand:g}=await a.getInfoByAlias(e);d=f,u=g,f&&(c=await i.createFromTransactionHash(f.hash))}return c?{match:!0,url:t,warp:c,registryInfo:d,brand:u}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,r){let n=this.config.clientUrl||l.DefaultClientUrl(this.config.env),e=encodeURIComponent(t===P?r:t+B+r);return l.SuperClientUrls(this.config.env).includes(n)?`${n}/${e}`:`${n}?${V}=${e}`}generateQrCode(t,r,n=512,e="white",i="black",a="#23F7DD"){let c=this.build(t,r);return new O.default({type:"svg",width:n,height:n,data:String(c),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:e},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>`})}extractIdentifierInfoFromUrl(t){let r=new URL(t),e=l.SuperClientUrls(this.config.env).includes(r.origin),i=r.searchParams.get(V),a=e&&!i?r.pathname.split("/")[1]:i;if(!a)return null;let c=decodeURIComponent(a);return w.getInfoFromPrefixedIdentifier(c)}};var X="https://",_="query",w=class s{static prepareVars(t,r){if(!t?.vars)return t;let n=JSON.stringify(t),e=(i,a)=>{n=n.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),a)};return Object.entries(t.vars).forEach(([i,a])=>{if(typeof a=="string"&&a.startsWith(`${_}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=a.split(`${_}:`)[1],d=new URL(r.currentUrl).searchParams.get(c);d&&e(i,d)}else e(i,a)}),JSON.parse(n)}static getInfoFromPrefixedIdentifier(t){let r=t.includes(B)?t:`${P}${B}${t}`,[n,e]=r.split(B);return{type:n,id:e}}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(X))return t.next;{let n=new v(r),e=s.getInfoFromPrefixedIdentifier(t.next);return e?n.build(e.type,e.id):null}}};var T=class{constructor(t){this.cache=new b;this.pendingWarp={protocol:R(l.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let r=new h.TransactionsFactoryConfig({chainID:y(this.config.env)}),n=new h.TransferTransactionsFactory({config:r}),e=JSON.stringify(t),i=n.createTransactionForTransfer({sender:h.Address.newFromBech32(this.config.userAddress),receiver:h.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(e).valueOf()});return i.gasLimit=i.gasLimit+BigInt(2e6),i}async createFromRaw(t,r=!0){let n=JSON.parse(t);return r&&await this.ensureValidSchema(n),w.prepareVars(n,this.config)}async createFromTransaction(t,r=!1){let n=await this.createFromRaw(t.data.toString(),r);return n.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},n}async createFromTransactionHash(t,r){let n=W.Warp(t);if(r){let i=this.cache.get(n);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let e=new h.ApiNetworkProvider(this.config.chainApiUrl||l.Chain.ApiUrl(this.config.env));try{let i=await e.getTransaction(t),a=await this.createFromTransaction(i);return r&&r.ttl&&a&&this.cache.set(n,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}getDescriptionPreview(t,r=100){return D(t,r)}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||l.LatestWarpSchemaUrl,e=await(await fetch(r)).json(),i=new H.default,a=i.compile(e);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};0&&(module.exports={BrandBuilder,Config,WarpActionExecutor,WarpBuilder,WarpLink,WarpRegistry,WarpUtils});
|
|
1
|
+
"use strict";var M=Object.create;var F=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var X=(s,t)=>{for(var r in t)F(s,r,{get:t[r],enumerable:!0})},$=(s,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of J(t))!Z.call(s,n)&&n!==r&&F(s,n,{get:()=>t[n],enumerable:!(e=G(t,n))||e.enumerable});return s};var E=(s,t,r)=>(r=s!=null?M(K(s)):{},$(t||!s||!s.__esModule?F(r,"default",{value:s,enumerable:!0}):r,s)),Y=s=>$(F({},"__esModule",{value:!0}),s);var et={};X(et,{BrandBuilder:()=>V,Config:()=>p,WarpActionExecutor:()=>N,WarpArgSerializer:()=>T,WarpBuilder:()=>A,WarpLink:()=>C,WarpRegistry:()=>v,WarpUtils:()=>b});module.exports=Y(et);var h=require("@multiversx/sdk-core"),_=E(require("ajv"));var p={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 w=s=>s==="devnet"?"D":s==="testnet"?"T":"1",P=s=>`${s}:${p.LatestProtocolVersion}`,U=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}),q=(s,t)=>{let r=s.toString(),[e,n=""]=r.split("."),i=Math.abs(t);if(t>0)return BigInt(e+n.padEnd(i,"0"));if(t<0){let a=e+n;if(i>=a.length)return 0n;let c=a.slice(0,-i)||"0";return BigInt(c)}else return BigInt(s)},O=(s,t=100)=>{if(!s)return"";let r=s.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r};var V=class{constructor(t){this.pendingBrand={protocol:P(p.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:w(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||p.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||p.LatestBrandSchemaUrl,n=await(await fetch(r)).json(),i=new _.default,a=i.compile(n);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${i.errorsText(a.errors)}`)}};var m=require("@multiversx/sdk-core/out");var g=require("@multiversx/sdk-core/out"),T=class{nativeToStrings(t,r){return`${t}:${r.toString()}`}stringToNative(t){let[r,e]=t.split(":");return r==="address"?e:r==="boolean"?e==="true":r==="biguint"?BigInt(e):r==="uint8"||r==="uint16"||r==="uint32"||r==="uint64"?Number(e):e}nativeToTyped(t,r){if(t==="string")return g.BytesValue.fromUTF8(r);if(t==="uint8")return new g.U8Value(Number(r));if(t==="uint16")return new g.U16Value(Number(r));if(t==="uint32")return new g.U32Value(Number(r));if(t==="uint64")return new g.U64Value(BigInt(r));if(t==="biguint")return new g.BigUIntValue(BigInt(r));if(t==="boolean")return new g.BooleanValue(typeof r=="boolean"?r:r==="true");if(t==="address")return new g.AddressValue(g.Address.newFromBech32(r));if(t==="hex")return g.BytesValue.fromHex(r);throw new Error(`WarpArgSerializer: Unsupported input type: ${t}`)}stringToTyped(t){let[r,e]=t.split(":");return this.nativeToTyped(r,e)}};var N=class{constructor(t,r){this.config=t,this.url=new URL(r),this.serializer=new T}createTransactionForExecute(t,r,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let n=m.Address.newFromBech32(this.config.userAddress),i=m.Address.newFromBech32(t.address),a=new m.TransactionsFactoryConfig({chainID:w(this.config.env)}),c=this.getModifiedInputs(t,r),u=this.getCombinedInputs(t,c).map(z=>this.serializer.stringToTyped(z)),f=this.getNativeValueFromField(t,c),d=this.getNativeValueFromUrl(t),x=BigInt(f||d||t.value||0),R=this.getCombinedTokenTransfers(t,e);return i.isContractAddress()?new m.SmartContractTransactionsFactory({config:a}).createTransactionForExecute({sender:n,contract:i,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:u,tokenTransfers:R,nativeTransferAmount:x}):new m.TransferTransactionsFactory({config:a}).createTransactionForTransfer({sender:n,receiver:i,nativeAmount:x,tokenTransfers:R,data:u[0]?.hasExactClass(m.BytesValue.ClassName)?u[0].valueOf():void 0})}getNativeValueFromField(t,r){let e=(t.inputs||[]).findIndex(i=>i.source==="field"&&i.position==="value"),n=e!==-1?r[e]:null;return n?n.split(":")[1]:null}getNativeValueFromUrl(t){let r=new URLSearchParams(this.url.search),n=t.inputs?.filter(i=>i.source==="query")?.find(i=>i.position==="value")?.name;return n?r.get(n):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputs(t,r){return(t.inputs?.filter(n=>!!n.modifier)||[]).forEach((n,i)=>{if(n.modifier?.startsWith("scale:")){let[,a]=n.modifier.split(":");if(isNaN(Number(a))){let c=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:i,l=t.inputs?.find(R=>R.name===a);if(!l)throw new Error(`WarpActionExecutor: Scalable input ${a} not found`);let u=Number(l.position.split(":")[1])-1,f=r[u].split(":")[1],d=r[c].split(":")[1],x=q(d,+f);r[c]=`${n.type}:${x}`}else{let c=n.position.startsWith("arg:")?Number(n.position.split(":")[1])-1:i,l=r[c].split(":")[1],u=q(l,+a);r[c]=`${n.type}:${u}`}}}),r}getCombinedInputs(t,r){let n=(t.inputs?.filter(a=>a.source==="field"&&a.position.startsWith("arg:"))||[]).map((a,c)=>({input:a,value:r[c]})),i=t.args||[];return n.forEach(({input:a,value:c})=>{let l=Number(a.position.split(":")[1])-1;i.splice(l,0,c)}),i}toTypedTransfer(t){return new m.TokenTransfer({token:new m.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var y=require("@multiversx/sdk-core"),j=E(require("ajv"));var I={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 L="https://",k="warp",B=":",S="alias";var H=E(require("qr-code-styling"));var o=require("@multiversx/sdk-core/out");var D={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var v=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(p.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(p.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[o.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,r){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:o.Address.newFromBech32(this.config.userAddress),contract:o.Address.newFromBech32(p.Registry.Contract(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[o.BytesValue.fromUTF8(t),o.BytesValue.fromHex(r)]})}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(p.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(p.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(p.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(p.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=I.RegistryInfo(t);if(r){let d=this.cache.get(e);if(d)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),d}let n=p.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[o.BytesValue.fromUTF8(t)]}),c=await i.runQuery(a),[l]=i.parseQueryResponse(c),u=l?U(l):null,f=u?.brand?await this.fetchBrand(u.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:u,brand:f},r.ttl),{registryInfo:u,brand:f}}async getInfoByHash(t,r){let e=I.RegistryInfo(t);if(r){let d=this.cache.get(e);if(d)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let n=p.Registry.Contract(this.config.env),i=this.getController(),a=i.createQuery({contract:n,function:"getInfoByHash",arguments:[o.BytesValue.fromHex(t)]}),c=await i.runQuery(a),[l]=i.parseQueryResponse(c),u=l?U(l):null,f=u?.brand?await this.fetchBrand(u.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:u,brand:f},r.ttl),{registryInfo:u,brand:f}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=p.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),[c]=n.parseQueryResponse(a);return c.map(U)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=p.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),[c]=n.parseQueryResponse(a),l=c.map(d=>d.toString("hex")),u={ttl:365*24*60*60};return(await Promise.all(l.map(d=>this.fetchBrand(d,u)))).filter(d=>d!==null)}async fetchBrand(t,r){let e=I.Brand(t);if(r){let i=this.cache.get(e);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=new o.ApiNetworkProvider(this.config.chainApiUrl||p.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*1e3).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=p.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}getFactory(){let t=new o.TransactionsFactoryConfig({chainID:w(this.config.env)}),r=o.AbiRegistry.create(D);return new o.SmartContractTransactionsFactory({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||p.Chain.ApiUrl(this.config.env),r=new o.ApiNetworkProvider(t,{timeout:3e4}),e=new o.QueryRunnerAdapter({networkProvider:r}),n=o.AbiRegistry.create(D);return new o.SmartContractQueriesController({queryRunner:e,abi:n})}};var C=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(L)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(u=>u[0]).filter(u=>this.isValid(u)).map(u=>this.detect(u)),a=(await Promise.all(n)).filter(u=>u.match),c=a.length>0,l=a.map(u=>({url:u.url,warp:u.warp}));return{match:c,results:l}}async detect(t){let r=t.startsWith(L)?this.extractIdentifierInfoFromUrl(t):b.getInfoFromPrefixedIdentifier(t);if(!r)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:e,id:n}=r,i=new A(this.config),a=new v(this.config),c=null,l=null,u=null;if(e==="hash"){c=await i.createFromTransactionHash(n);try{let{registryInfo:f,brand:d}=await a.getInfoByHash(n);l=f,u=d}catch{}}else if(e==="alias"){let{registryInfo:f,brand:d}=await a.getInfoByAlias(n);l=f,u=d,f&&(c=await i.createFromTransactionHash(f.hash))}return c?{match:!0,url:t,warp:c,registryInfo:l,brand:u}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||p.DefaultClientUrl(this.config.env),n=encodeURIComponent(t===S?r:t+B+r);return p.SuperClientUrls(this.config.env).includes(e)?`${e}/${n}`:`${e}?${k}=${n}`}generateQrCode(t,r,e=512,n="white",i="black",a="#23F7DD"){let c=this.build(t,r);return new H.default({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(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let r=new URL(t),n=p.SuperClientUrls(this.config.env).includes(r.origin),i=r.searchParams.get(k),a=n&&!i?r.pathname.split("/")[1]:i;if(!a)return null;let c=decodeURIComponent(a);return b.getInfoFromPrefixedIdentifier(c)}};var rt="https://",Q="query",b=class s{static prepareVars(t,r){if(!t?.vars)return t;let e=JSON.stringify(t),n=(i,a)=>{e=e.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),a)};return Object.entries(t.vars).forEach(([i,a])=>{if(typeof a=="string"&&a.startsWith(`${Q}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let c=a.split(`${Q}:`)[1],l=new URL(r.currentUrl).searchParams.get(c);l&&n(i,l)}else n(i,a)}),JSON.parse(e)}static getInfoFromPrefixedIdentifier(t){let r=decodeURIComponent(t),e=r.includes(B)?r:`${S}${B}${r}`,[n,i]=e.split(B);return{type:n,id:i}}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(rt))return t.next;{let e=new C(r),n=s.getInfoFromPrefixedIdentifier(t.next);return n?e.build(n.type,n.id):null}}};var A=class{constructor(t){this.cache=new W;this.pendingWarp={protocol:P(p.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let r=new y.TransactionsFactoryConfig({chainID:w(this.config.env)}),e=new y.TransferTransactionsFactory({config:r}),n=JSON.stringify(t),i=e.createTransactionForTransfer({sender:y.Address.newFromBech32(this.config.userAddress),receiver:y.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()});return i.gasLimit=i.gasLimit+BigInt(2e6),i}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),b.prepareVars(e,this.config)}async createFromTransaction(t,r=!1){let e=await this.createFromRaw(t.data.toString(),r);return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,r){let e=I.Warp(t);if(r){let i=this.cache.get(e);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=new y.ApiNetworkProvider(this.config.chainApiUrl||p.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}getDescriptionPreview(t,r=100){return O(t,r)}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||p.LatestWarpSchemaUrl,n=await(await fetch(r)).json(),i=new j.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,WarpArgSerializer,WarpBuilder,WarpLink,WarpRegistry,WarpUtils});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Address as L,ApiNetworkProvider as H,TransactionsFactoryConfig as Q,TransferTransactionsFactory as j}from"@multiversx/sdk-core";import M from"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.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:a=>a==="devnet"?["https://devnet.usewarp.to"]:a==="testnet"?["https://testnet.usewarp.to"]:["https://usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var m=a=>a==="devnet"?"D":a==="testnet"?"T":"1",I=a=>`${a}:${u.LatestProtocolVersion}`,v=a=>({hash:a.hash.toString("hex"),alias:a.alias?.toString()||null,trust:a.trust.toString(),creator:a.creator.toString(),createdAt:a.created_at.toNumber(),brand:a.brand?.toString("hex")||null,upgrade:a.upgrade?.toString("hex")||null}),R=(a,t)=>{let r=a.toString(),[i,e=""]=r.split("."),n=Math.abs(t);if(t>0)return BigInt(i+e.padEnd(n,"0"));if(t<0){let s=i+e;if(n>=s.length)return 0n;let o=s.slice(0,-n)||"0";return BigInt(o)}else return BigInt(a)},q=(a,t=100)=>{if(!a)return"";let r=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r};var V=class{constructor(t){this.pendingBrand={protocol:I(u.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new Q({chainID:m(this.config.env)}),i=new j({config:r}),e=JSON.stringify(t);return i.createTransactionForNativeTokenTransfer({sender:L.newFromBech32(this.config.userAddress),receiver:L.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(e).valueOf()})}async createFromRaw(t,r=!0){let i=JSON.parse(t);return r&&await this.ensureValidSchema(i),i}async createFromTransaction(t,r=!1){return await this.createFromRaw(t.data.toString(),r)}async createFromTransactionHash(t){let r=new H(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let i=await r.getTransaction(t);return this.createFromTransaction(i)}catch(i){return console.error("BrandBuilder: Error creating from transaction hash",i),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.brandSchemaUrl||u.LatestBrandSchemaUrl,e=await(await fetch(r)).json(),n=new M,s=n.compile(e);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import{Address as F,AddressValue as G,BigUIntValue as J,BooleanValue as K,BytesValue as P,SmartContractTransactionsFactory as z,Token as Z,TokenTransfer as X,TransactionsFactoryConfig as Y,TransferTransactionsFactory as tt,U16Value as rt,U32Value as et,U64Value as nt,U8Value as it}from"@multiversx/sdk-core/out";var N=class{constructor(t,r){this.config=t,this.url=new URL(r)}createTransactionForExecute(t,r,i){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let e=F.newFromBech32(this.config.userAddress),n=F.newFromBech32(t.address),s=new Y({chainID:m(this.config.env)}),o=this.getModifiedInputs(t,r),p=this.getCombinedInputs(t,o),c=this.getTypedArgsFromInput(p),d=this.getNativeValueFromField(t,o),l=this.getNativeValueFromUrl(t),W=BigInt(d||l||t.value||0),B=this.getCombinedTokenTransfers(t,i);return n.isContractAddress()?new z({config:s}).createTransactionForExecute({sender:e,contract:n,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:B,nativeTransferAmount:W}):new tt({config:s}).createTransactionForTransfer({sender:e,receiver:n,nativeAmount:W,tokenTransfers:B,data:c[0]?.hasExactClass(P.ClassName)?c[0].valueOf():void 0})}getNativeValueFromField(t,r){let i=(t.inputs||[]).findIndex(n=>n.source==="field"&&n.position==="value"),e=i!==-1?r[i]:null;return e?e.split(":")[1]:null}getNativeValueFromUrl(t){let r=new URLSearchParams(this.url.search),e=t.inputs?.filter(n=>n.source==="query")?.find(n=>n.position==="value")?.name;return e?r.get(e):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputs(t,r){return(t.inputs?.filter(e=>!!e.modifier)||[]).forEach((e,n)=>{if(e.modifier?.startsWith("scale:")){let[,s]=e.modifier.split(":");if(isNaN(Number(s))){let o=e.position.startsWith("arg:")?Number(e.position.split(":")[1])-1:n,p=t.inputs?.find(B=>B.name===s);if(!p)throw new Error(`WarpActionExecutor: Scalable input ${s} not found`);let c=Number(p.position.split(":")[1])-1,d=r[c].split(":")[1],l=r[o].split(":")[1],W=R(l,+d);r[o]=`${e.type}:${W}`}else{let o=e.position.startsWith("arg:")?Number(e.position.split(":")[1])-1:n,p=r[o].split(":")[1],c=R(p,+s);r[o]=`${e.type}:${c}`}}}),r}getCombinedInputs(t,r){let e=(t.inputs?.filter(s=>s.source==="field"&&s.position.startsWith("arg:"))||[]).map((s,o)=>({input:s,value:r[o]})),n=t.args||[];return e.forEach(({input:s,value:o})=>{let p=Number(s.position.split(":")[1])-1;n.splice(p,0,o)}),n}getTypedArgsFromInput(t){return t.map(r=>{let[i,e]=r.split(":");return this.toTypedArg(e,i)})}toTypedTransfer(t){return new X({token:new Z({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 it(Number(t));if(r==="uint16")return new rt(Number(t));if(r==="uint32")return new et(Number(t));if(r==="uint64")return new nt(BigInt(t));if(r==="biguint")return new J(BigInt(t));if(r==="boolean")return new K(t==="true");if(r==="address")return new G(F.newFromBech32(t));if(r==="hex")return P.fromHex(t);throw new Error(`WarpActionExecutor: Unsupported input type: ${r}`)}};import{Address as _,ApiNetworkProvider as dt,TransactionsFactoryConfig as gt,TransferTransactionsFactory as ft}from"@multiversx/sdk-core";import mt from"ajv";var w={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},y=class{constructor(){this.cache=new Map}set(t,r,i){let e=Date.now()+i*1e3;this.cache.set(t,{value:r,expiresAt:e})}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 U="https://",S="warp",b=":",T="alias";import pt from"qr-code-styling";import{AbiRegistry as k,Address as g,AddressValue as D,ApiNetworkProvider as $,BytesValue as f,QueryRunnerAdapter as at,SmartContractQueriesController as ot,SmartContractTransactionsFactory as ct,TransactionsFactoryConfig as ut}from"@multiversx/sdk-core/out";var E={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var C=class{constructor(t){this.cache=new y;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 i=r?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:i,arguments:r?[f.fromHex(t),f.fromUTF8(r)]:[f.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[f.fromHex(t)]})}createWarpUpgradeTransaction(t,r){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromUTF8(t),f.fromHex(r)]})}createWarpAliasSetTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t),f.fromUTF8(r)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t)]})}createWarpBrandingTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t),f.fromHex(r)]})}async getInfoByAlias(t,r){let i=w.RegistryInfo(t);if(r){let l=this.cache.get(i);if(l)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),l}let e=u.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:e,function:"getInfoByAlias",arguments:[f.fromUTF8(t)]}),o=await n.runQuery(s),[p]=n.parseQueryResponse(o),c=p?v(p):null,d=c?.brand?await this.fetchBrand(c.brand):null;return r&&r.ttl&&this.cache.set(i,{registryInfo:c,brand:d},r.ttl),{registryInfo:c,brand:d}}async getInfoByHash(t,r){let i=w.RegistryInfo(t);if(r){let l=this.cache.get(i);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let e=u.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:e,function:"getInfoByHash",arguments:[f.fromHex(t)]}),o=await n.runQuery(s),[p]=n.parseQueryResponse(o),c=p?v(p):null,d=c?.brand?await this.fetchBrand(c.brand):null;return r&&r.ttl&&this.cache.set(i,{registryInfo:c,brand:d},r.ttl),{registryInfo:c,brand:d}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let i=u.Registry.Contract(this.config.env),e=this.getController(),n=e.createQuery({contract:i,function:"getUserWarps",arguments:[new D(new g(r))]}),s=await e.runQuery(n),[o]=e.parseQueryResponse(s);return o.map(v)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let i=u.Registry.Contract(this.config.env),e=this.getController(),n=e.createQuery({contract:i,function:"getUserBrands",arguments:[new D(new g(r))]}),s=await e.runQuery(n),[o]=e.parseQueryResponse(s),p=o.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(p.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}async fetchBrand(t,r){let i=w.Brand(t);if(r){let n=this.cache.get(i);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n}let e=new $(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let n=await e.getTransaction(t),s=JSON.parse(n.data.toString());return s.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp*1e3).toISOString()},r&&r.ttl&&this.cache.set(i,s,r.ttl),s}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}async loadRegistryConfigs(){let t=u.Registry.Contract(this.config.env),r=this.getController(),i=r.createQuery({contract:t,function:"getConfig",arguments:[]}),e=await r.runQuery(i),[n]=r.parseQueryResponse(e),s=BigInt(n.toString());this.unitPrice=s}getFactory(){let t=new ut({chainID:m(this.config.env)}),r=k.create(E);return new ct({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env),r=new $(t,{timeout:3e4}),i=new at({networkProvider:r}),e=k.create(E);return new ot({queryRunner:i,abi:e})}};var A=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(U)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let e=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),s=(await Promise.all(e)).filter(c=>c.match),o=s.length>0,p=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t){let r=t.startsWith(U)?this.extractIdentifierInfoFromUrl(t):h.getInfoFromPrefixedIdentifier(t);if(!r)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:i,id:e}=r,n=new x(this.config),s=new C(this.config),o=null,p=null,c=null;if(i==="hash"){o=await n.createFromTransactionHash(e);try{let{registryInfo:d,brand:l}=await s.getInfoByHash(e);p=d,c=l}catch{}}else if(i==="alias"){let{registryInfo:d,brand:l}=await s.getInfoByAlias(e);p=d,c=l,d&&(o=await n.createFromTransactionHash(d.hash))}return o?{match:!0,url:t,warp:o,registryInfo:p,brand:c}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,r){let i=this.config.clientUrl||u.DefaultClientUrl(this.config.env),e=encodeURIComponent(t===T?r:t+b+r);return u.SuperClientUrls(this.config.env).includes(i)?`${i}/${e}`:`${i}?${S}=${e}`}generateQrCode(t,r,i=512,e="white",n="black",s="#23F7DD"){let o=this.build(t,r);return new pt({type:"svg",width:i,height:i,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:e},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let r=new URL(t),e=u.SuperClientUrls(this.config.env).includes(r.origin),n=r.searchParams.get(S),s=e&&!n?r.pathname.split("/")[1]:n;if(!s)return null;let o=decodeURIComponent(s);return h.getInfoFromPrefixedIdentifier(o)}};var lt="https://",O="query",h=class a{static prepareVars(t,r){if(!t?.vars)return t;let i=JSON.stringify(t),e=(n,s)=>{i=i.replace(new RegExp(`{{${n.toUpperCase()}}}`,"g"),s)};return Object.entries(t.vars).forEach(([n,s])=>{if(typeof s=="string"&&s.startsWith(`${O}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${O}:`)[1],p=new URL(r.currentUrl).searchParams.get(o);p&&e(n,p)}else e(n,s)}),JSON.parse(i)}static getInfoFromPrefixedIdentifier(t){let r=t.includes(b)?t:`${T}${b}${t}`,[i,e]=r.split(b);return{type:i,id:e}}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(lt))return t.next;{let i=new A(r),e=a.getInfoFromPrefixedIdentifier(t.next);return e?i.build(e.type,e.id):null}}};var x=class{constructor(t){this.cache=new y;this.pendingWarp={protocol:I(u.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let r=new gt({chainID:m(this.config.env)}),i=new ft({config:r}),e=JSON.stringify(t),n=i.createTransactionForTransfer({sender:_.newFromBech32(this.config.userAddress),receiver:_.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(e).valueOf()});return n.gasLimit=n.gasLimit+BigInt(2e6),n}async createFromRaw(t,r=!0){let i=JSON.parse(t);return r&&await this.ensureValidSchema(i),h.prepareVars(i,this.config)}async createFromTransaction(t,r=!1){let i=await this.createFromRaw(t.data.toString(),r);return i.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},i}async createFromTransactionHash(t,r){let i=w.Warp(t);if(r){let n=this.cache.get(i);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),n}let e=new dt(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let n=await e.getTransaction(t),s=await this.createFromTransaction(n);return r&&r.ttl&&s&&this.cache.set(i,s,r.ttl),s}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return q(t,r)}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||u.LatestWarpSchemaUrl,e=await(await fetch(r)).json(),n=new mt,s=n.compile(e);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};export{V as BrandBuilder,u as Config,N as WarpActionExecutor,x as WarpBuilder,A as WarpLink,C as WarpRegistry,h as WarpUtils};
|
|
1
|
+
import{Address as q,ApiNetworkProvider as j,TransactionsFactoryConfig as z,TransferTransactionsFactory as M}from"@multiversx/sdk-core";import G from"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.usewarp.to":a==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:a=>a==="devnet"?["https://devnet.usewarp.to"]:a==="testnet"?["https://testnet.usewarp.to"]:["https://usewarp.to"],Chain:{ApiUrl:a=>a==="devnet"?"https://devnet-api.multiversx.com":a==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:a=>a==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":a==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var m=a=>a==="devnet"?"D":a==="testnet"?"T":"1",B=a=>`${a}:${u.LatestProtocolVersion}`,T=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}),F=(a,t)=>{let r=a.toString(),[e,i=""]=r.split("."),n=Math.abs(t);if(t>0)return BigInt(e+i.padEnd(n,"0"));if(t<0){let s=e+i;if(n>=s.length)return 0n;let o=s.slice(0,-n)||"0";return BigInt(o)}else return BigInt(a)},E=(a,t=100)=>{if(!a)return"";let r=a.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return r=r.startsWith("- ")?r.slice(2):r,r=r.length>t?r.substring(0,r.lastIndexOf(" ",t))+"...":r,r};var V=class{constructor(t){this.pendingBrand={protocol:B(u.ProtocolNameBrand),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let r=new z({chainID:m(this.config.env)}),e=new M({config:r}),i=JSON.stringify(t);return e.createTransactionForNativeTokenTransfer({sender:q.newFromBech32(this.config.userAddress),receiver:q.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),e}async createFromTransaction(t,r=!1){return await this.createFromRaw(t.data.toString(),r)}async createFromTransactionHash(t){let r=new j(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let e=await r.getTransaction(t);return this.createFromTransaction(e)}catch(e){return console.error("BrandBuilder: Error creating from transaction hash",e),null}}setName(t){return this.pendingBrand.name=t,this}setDescription(t){return this.pendingBrand.description=t,this}setLogo(t){return this.pendingBrand.logo=t,this}setUrls(t){return this.pendingBrand.urls=t,this}setColors(t){return this.pendingBrand.colors=t,this}setCta(t){return this.pendingBrand.cta=t,this}async build(){return this.ensure(this.pendingBrand.name,"name is required"),this.ensure(this.pendingBrand.description,"description is required"),this.ensure(this.pendingBrand.logo,"logo is required"),await this.ensureValidSchema(this.pendingBrand),this.pendingBrand}ensure(t,r){if(!t)throw new Error(`Warp: ${r}`)}async ensureValidSchema(t){let r=this.config.brandSchemaUrl||u.LatestBrandSchemaUrl,i=await(await fetch(r)).json(),n=new G,s=n.compile(i);if(!s(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};import{Address as L,BytesValue as nt,SmartContractTransactionsFactory as it,Token as st,TokenTransfer as at,TransactionsFactoryConfig as ot,TransferTransactionsFactory as ct}from"@multiversx/sdk-core/out";import{Address as J,AddressValue as K,BigUIntValue as Z,BooleanValue as X,BytesValue as N,U16Value as Y,U32Value as tt,U64Value as rt,U8Value as et}from"@multiversx/sdk-core/out";var v=class{nativeToStrings(t,r){return`${t}:${r.toString()}`}stringToNative(t){let[r,e]=t.split(":");return r==="address"?e:r==="boolean"?e==="true":r==="biguint"?BigInt(e):r==="uint8"||r==="uint16"||r==="uint32"||r==="uint64"?Number(e):e}nativeToTyped(t,r){if(t==="string")return N.fromUTF8(r);if(t==="uint8")return new et(Number(r));if(t==="uint16")return new Y(Number(r));if(t==="uint32")return new tt(Number(r));if(t==="uint64")return new rt(BigInt(r));if(t==="biguint")return new Z(BigInt(r));if(t==="boolean")return new X(typeof r=="boolean"?r:r==="true");if(t==="address")return new K(J.newFromBech32(r));if(t==="hex")return N.fromHex(r);throw new Error(`WarpArgSerializer: Unsupported input type: ${t}`)}stringToTyped(t){let[r,e]=t.split(":");return this.nativeToTyped(r,e)}};var k=class{constructor(t,r){this.config=t,this.url=new URL(r),this.serializer=new v}createTransactionForExecute(t,r,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let i=L.newFromBech32(this.config.userAddress),n=L.newFromBech32(t.address),s=new ot({chainID:m(this.config.env)}),o=this.getModifiedInputs(t,r),c=this.getCombinedInputs(t,o).map(Q=>this.serializer.stringToTyped(Q)),d=this.getNativeValueFromField(t,o),l=this.getNativeValueFromUrl(t),W=BigInt(d||l||t.value||0),I=this.getCombinedTokenTransfers(t,e);return n.isContractAddress()?new it({config:s}).createTransactionForExecute({sender:i,contract:n,function:t.func||"",gasLimit:BigInt(t.gasLimit),arguments:c,tokenTransfers:I,nativeTransferAmount:W}):new ct({config:s}).createTransactionForTransfer({sender:i,receiver:n,nativeAmount:W,tokenTransfers:I,data:c[0]?.hasExactClass(nt.ClassName)?c[0].valueOf():void 0})}getNativeValueFromField(t,r){let e=(t.inputs||[]).findIndex(n=>n.source==="field"&&n.position==="value"),i=e!==-1?r[e]:null;return i?i.split(":")[1]:null}getNativeValueFromUrl(t){let r=new URLSearchParams(this.url.search),i=t.inputs?.filter(n=>n.source==="query")?.find(n=>n.position==="value")?.name;return i?r.get(i):null}getCombinedTokenTransfers(t,r){return[...t.transfers?.map(this.toTypedTransfer)||[],...r]}getModifiedInputs(t,r){return(t.inputs?.filter(i=>!!i.modifier)||[]).forEach((i,n)=>{if(i.modifier?.startsWith("scale:")){let[,s]=i.modifier.split(":");if(isNaN(Number(s))){let o=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:n,p=t.inputs?.find(I=>I.name===s);if(!p)throw new Error(`WarpActionExecutor: Scalable input ${s} not found`);let c=Number(p.position.split(":")[1])-1,d=r[c].split(":")[1],l=r[o].split(":")[1],W=F(l,+d);r[o]=`${i.type}:${W}`}else{let o=i.position.startsWith("arg:")?Number(i.position.split(":")[1])-1:n,p=r[o].split(":")[1],c=F(p,+s);r[o]=`${i.type}:${c}`}}}),r}getCombinedInputs(t,r){let i=(t.inputs?.filter(s=>s.source==="field"&&s.position.startsWith("arg:"))||[]).map((s,o)=>({input:s,value:r[o]})),n=t.args||[];return i.forEach(({input:s,value:o})=>{let p=Number(s.position.split(":")[1])-1;n.splice(p,0,o)}),n}toTypedTransfer(t){return new at({token:new st({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};import{Address as H,ApiNetworkProvider as ht,TransactionsFactoryConfig as yt,TransferTransactionsFactory as wt}from"@multiversx/sdk-core";import bt from"ajv";var w={Warp:a=>`warp:${a}`,RegistryInfo:a=>`registry-info:${a}`,Brand:a=>`brand:${a}`},y=class{constructor(){this.cache=new Map}set(t,r,e){let i=Date.now()+e*1e3;this.cache.set(t,{value:r,expiresAt:i})}get(t){let r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):r.value:null}clear(){this.cache.clear()}};var P="https://",U="warp",b=":",C="alias";import ft from"qr-code-styling";import{AbiRegistry as D,Address as g,AddressValue as $,ApiNetworkProvider as O,BytesValue as f,QueryRunnerAdapter as pt,SmartContractQueriesController as lt,SmartContractTransactionsFactory as dt,TransactionsFactoryConfig as gt}from"@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"},{name:"vault",type:"Address"}],outputs:[]},upgradeConstructor:{inputs:[],outputs:[]},endpoints:[{name:"registerWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias_opt",type:"optional<bytes>",multi_arg:!0},{name:"brand_opt",type:"optional<bytes>",multi_arg:!0}],outputs:[],allow_multiple_var_args:!0},{name:"unregisterWarp",mutability:"mutable",inputs:[{name:"warp",type:"bytes"}],outputs:[]},{name:"upgradeWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"alias",type:"bytes"},{name:"new_warp",type:"bytes"}],outputs:[]},{name:"setWarpAlias",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"},{name:"alias",type:"bytes"}],outputs:[]},{name:"publishWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"getUserWarps",mutability:"readonly",inputs:[{name:"address",type:"Address"}],outputs:[{type:"variadic<InfoView>",multi_result:!0}]},{name:"getInfoByAlias",mutability:"readonly",inputs:[{name:"alias",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"getInfoByHash",mutability:"readonly",inputs:[{name:"hash",type:"bytes"}],outputs:[{type:"InfoView"}]},{name:"setVault",onlyOwner:!0,mutability:"mutable",inputs:[{name:"vault",type:"Address"}],outputs:[]},{name:"setUnitPrice",onlyOwner:!0,mutability:"mutable",inputs:[{name:"amount",type:"BigUint"}],outputs:[]},{name:"getConfig",mutability:"readonly",inputs:[],outputs:[{type:"BigUint"}]},{name:"registerBrand",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"hash",type:"bytes"}],outputs:[]},{name:"brandWarp",mutability:"mutable",payableInTokens:["EGLD"],inputs:[{name:"warp",type:"bytes"},{name:"brand",type:"bytes"}],outputs:[]},{name:"getUserBrands",mutability:"readonly",inputs:[{name:"user",type:"Address"}],outputs:[{type:"variadic<bytes>",multi_result:!0}]}],events:[{identifier:"warpRegistered",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]},{identifier:"warpUnregistered",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"warpUpgraded",inputs:[{name:"alias",type:"bytes",indexed:!0},{name:"new_warp",type:"bytes",indexed:!0}]},{identifier:"warpPublished",inputs:[{name:"hash",type:"bytes",indexed:!0}]},{identifier:"aliasUpdated",inputs:[{name:"hash",type:"bytes",indexed:!0},{name:"alias",type:"bytes",indexed:!0}]}],esdtAttributes:[],hasCallback:!1,types:{InfoView:{type:"struct",fields:[{name:"hash",type:"bytes"},{name:"alias",type:"Option<bytes>"},{name:"trust",type:"bytes"},{name:"creator",type:"Address"},{name:"created_at",type:"u64"},{name:"brand",type:"Option<bytes>"},{name:"upgrade",type:"Option<bytes>"}]}}};var A=class{constructor(t){this.cache=new y;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,r){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");let e=r?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:e,arguments:r?[f.fromHex(t),f.fromUTF8(r)]:[f.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[f.fromHex(t)]})}createWarpUpgradeTransaction(t,r){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromUTF8(t),f.fromHex(r)]})}createWarpAliasSetTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t),f.fromUTF8(r)]})}createBrandRegisterTransaction(t){if(this.unitPrice===BigInt(0))throw new Error("WarpRegistry: config not loaded. forgot to call init()?");if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t)]})}createWarpBrandingTransaction(t,r){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:g.newFromBech32(this.config.userAddress),contract:g.newFromBech32(u.Registry.Contract(this.config.env)),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[f.fromHex(t),f.fromHex(r)]})}async getInfoByAlias(t,r){let e=w.RegistryInfo(t);if(r){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),l}let i=u.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[f.fromUTF8(t)]}),o=await n.runQuery(s),[p]=n.parseQueryResponse(o),c=p?T(p):null,d=c?.brand?await this.fetchBrand(c.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:c,brand:d},r.ttl),{registryInfo:c,brand:d}}async getInfoByHash(t,r){let e=w.RegistryInfo(t);if(r){let l=this.cache.get(e);if(l)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),l}let i=u.Registry.Contract(this.config.env),n=this.getController(),s=n.createQuery({contract:i,function:"getInfoByHash",arguments:[f.fromHex(t)]}),o=await n.runQuery(s),[p]=n.parseQueryResponse(o),c=p?T(p):null,d=c?.brand?await this.fetchBrand(c.brand):null;return r&&r.ttl&&this.cache.set(e,{registryInfo:c,brand:d},r.ttl),{registryInfo:c,brand:d}}async getUserWarpRegistryInfos(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=u.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:e,function:"getUserWarps",arguments:[new $(new g(r))]}),s=await i.runQuery(n),[o]=i.parseQueryResponse(s);return o.map(T)}async getUserBrands(t){let r=t||this.config.userAddress;if(!r)throw new Error("WarpRegistry: user address not set");let e=u.Registry.Contract(this.config.env),i=this.getController(),n=i.createQuery({contract:e,function:"getUserBrands",arguments:[new $(new g(r))]}),s=await i.runQuery(n),[o]=i.parseQueryResponse(s),p=o.map(l=>l.toString("hex")),c={ttl:365*24*60*60};return(await Promise.all(p.map(l=>this.fetchBrand(l,c)))).filter(l=>l!==null)}async fetchBrand(t,r){let e=w.Brand(t);if(r){let n=this.cache.get(e);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n}let i=new O(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(t),s=JSON.parse(n.data.toString());return s.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp*1e3).toISOString()},r&&r.ttl&&this.cache.set(e,s,r.ttl),s}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}async loadRegistryConfigs(){let t=u.Registry.Contract(this.config.env),r=this.getController(),e=r.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await r.runQuery(e),[n]=r.parseQueryResponse(i),s=BigInt(n.toString());this.unitPrice=s}getFactory(){let t=new gt({chainID:m(this.config.env)}),r=D.create(S);return new dt({config:t,abi:r})}getController(){let t=this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env),r=new O(t,{timeout:3e4}),e=new pt({networkProvider:r}),i=D.create(S);return new lt({queryRunner:e,abi:i})}};var x=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(P)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(c=>c[0]).filter(c=>this.isValid(c)).map(c=>this.detect(c)),s=(await Promise.all(i)).filter(c=>c.match),o=s.length>0,p=s.map(c=>({url:c.url,warp:c.warp}));return{match:o,results:p}}async detect(t){let r=t.startsWith(P)?this.extractIdentifierInfoFromUrl(t):h.getInfoFromPrefixedIdentifier(t);if(!r)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:e,id:i}=r,n=new R(this.config),s=new A(this.config),o=null,p=null,c=null;if(e==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:d,brand:l}=await s.getInfoByHash(i);p=d,c=l}catch{}}else if(e==="alias"){let{registryInfo:d,brand:l}=await s.getInfoByAlias(i);p=d,c=l,d&&(o=await n.createFromTransactionHash(d.hash))}return o?{match:!0,url:t,warp:o,registryInfo:p,brand:c}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,r){let e=this.config.clientUrl||u.DefaultClientUrl(this.config.env),i=encodeURIComponent(t===C?r:t+b+r);return u.SuperClientUrls(this.config.env).includes(e)?`${e}/${i}`:`${e}?${U}=${i}`}generateQrCode(t,r,e=512,i="white",n="black",s="#23F7DD"){let o=this.build(t,r);return new ft({type:"svg",width:e,height:e,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(s)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let r=new URL(t),i=u.SuperClientUrls(this.config.env).includes(r.origin),n=r.searchParams.get(U),s=i&&!n?r.pathname.split("/")[1]:n;if(!s)return null;let o=decodeURIComponent(s);return h.getInfoFromPrefixedIdentifier(o)}};var mt="https://",_="query",h=class a{static prepareVars(t,r){if(!t?.vars)return t;let e=JSON.stringify(t),i=(n,s)=>{e=e.replace(new RegExp(`{{${n.toUpperCase()}}}`,"g"),s)};return Object.entries(t.vars).forEach(([n,s])=>{if(typeof s=="string"&&s.startsWith(`${_}:`)){if(!r.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=s.split(`${_}:`)[1],p=new URL(r.currentUrl).searchParams.get(o);p&&i(n,p)}else i(n,s)}),JSON.parse(e)}static getInfoFromPrefixedIdentifier(t){let r=decodeURIComponent(t),e=r.includes(b)?r:`${C}${b}${r}`,[i,n]=e.split(b);return{type:i,id:n}}static getNextStepUrl(t,r){if(!t?.next)return null;if(t.next.startsWith(mt))return t.next;{let e=new x(r),i=a.getInfoFromPrefixedIdentifier(t.next);return i?e.build(i.type,i.id):null}}};var R=class{constructor(t){this.cache=new y;this.pendingWarp={protocol:B(u.ProtocolNameWarp),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let r=new yt({chainID:m(this.config.env)}),e=new wt({config:r}),i=JSON.stringify(t),n=e.createTransactionForTransfer({sender:H.newFromBech32(this.config.userAddress),receiver:H.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return n.gasLimit=n.gasLimit+BigInt(2e6),n}async createFromRaw(t,r=!0){let e=JSON.parse(t);return r&&await this.ensureValidSchema(e),h.prepareVars(e,this.config)}async createFromTransaction(t,r=!1){let e=await this.createFromRaw(t.data.toString(),r);return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,r){let e=w.Warp(t);if(r){let n=this.cache.get(e);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),n}let i=new ht(this.config.chainApiUrl||u.Chain.ApiUrl(this.config.env));try{let n=await i.getTransaction(t),s=await this.createFromTransaction(n);return r&&r.ttl&&s&&this.cache.set(e,s,r.ttl),s}catch(n){return console.error("WarpBuilder: Error creating from transaction hash",n),null}}setName(t){return this.pendingWarp.name=t,this}setTitle(t){return this.pendingWarp.title=t,this}setDescription(t){return this.pendingWarp.description=t,this}setPreview(t){return this.pendingWarp.preview=t,this}setActions(t){return this.pendingWarp.actions=t,this}addAction(t){return this.pendingWarp.actions.push(t),this}async build(){return this.ensure(this.pendingWarp.protocol,"protocol is required"),this.ensure(this.pendingWarp.name,"name is required"),this.ensure(this.pendingWarp.title,"title is required"),this.ensure(this.pendingWarp.actions.length>0,"actions are required"),await this.ensureValidSchema(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,r=100){return E(t,r)}ensure(t,r){if(!t)throw new Error(`WarpBuilder: ${r}`)}async ensureValidSchema(t){let r=this.config.warpSchemaUrl||u.LatestWarpSchemaUrl,i=await(await fetch(r)).json(),n=new bt,s=n.compile(i);if(!s(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(s.errors)}`)}};export{V as BrandBuilder,u as Config,k as WarpActionExecutor,v as WarpArgSerializer,R as WarpBuilder,x as WarpLink,A as WarpRegistry,h as WarpUtils};
|