@vleap/warps 0.0.88 → 0.0.90

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