@vleap/warps 0.0.75 → 0.0.77

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