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