@vleap/warps 0.14.0 → 0.14.1
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 +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var it=Object.create;var L=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var ot=Object.getPrototypeOf,ct=Object.prototype.hasOwnProperty;var pt=(s,t)=>{for(var e in t)L(s,e,{get:t[e],enumerable:!0})},G=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of st(t))!ct.call(s,n)&&n!==e&&L(s,n,{get:()=>t[n],enumerable:!(r=at(t,n))||r.enumerable});return s};var _=(s,t,e)=>(e=s!=null?it(ot(s)):{},G(t||!s||!s.__esModule?L(e,"default",{value:s,enumerable:!0}):e,s)),ut=s=>G(L({},"__esModule",{value:!0}),s);var Ft={};pt(Ft,{BrandBuilder:()=>j,Config:()=>w,WarpAbiBuilder:()=>E,WarpActionExecutor:()=>M,WarpArgSerializer:()=>N,WarpBuilder:()=>R,WarpConstants:()=>g,WarpContractLoader:()=>k,WarpIndex:()=>z,WarpLink:()=>F,WarpProtocolVersions:()=>b,WarpRegistry:()=>U,WarpUtils:()=>h,address:()=>vt,biguint:()=>It,boolean:()=>Bt,codemeta:()=>Pt,composite:()=>wt,esdt:()=>Vt,getChainId:()=>W,getLatestProtocolIdentifier:()=>I,getWarpActionByIndex:()=>lt,hex:()=>xt,list:()=>ht,nothing:()=>Rt,option:()=>ft,optional:()=>mt,shiftBigintBy:()=>V,string:()=>Tt,toPreviewText:()=>H,toTypedRegistryInfo:()=>x,token:()=>St,u16:()=>At,u32:()=>Ct,u64:()=>bt,u8:()=>Wt,variadic:()=>yt});module.exports=ut(Ft);var v=require("@multiversx/sdk-core"),tt=_(require("ajv"));var b={Warp:"0.5.0",Brand:"0.1.0",Abi:"0.1.0"},w={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${b.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${b.Brand}.schema.json`,DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var W=s=>s==="devnet"?"D":s==="testnet"?"T":"1",I=s=>{if(s==="warp")return`warp:${b.Warp}`;if(s==="brand")return`brand:${b.Brand}`;if(s==="abi")return`abi:${b.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},lt=(s,t)=>s?.actions[t-1],x=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}),V=(s,t)=>{let e=s.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let o=r+n;if(i>=o.length)return 0n;let p=o.slice(0,-i)||"0";return BigInt(p)}else return BigInt(s)},H=(s,t=100)=>{if(!s)return"";let e=s.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};var Y=require("@multiversx/sdk-core/out");var g={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var J=_(require("qr-code-styling"));var B=require("@multiversx/sdk-core");var C={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},A=class{constructor(){this.cache=new Map}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};var K=_(require("ajv"));var P=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||w.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new K.default,o=i.compile(n);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var R=class{constructor(t){this.cache=new A;this.pendingWarp={protocol:I("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new B.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new B.TransferTransactionsFactory({config:e}),n=JSON.stringify(t),i=r.createTransactionForTransfer({sender:B.Address.newFromBech32(this.config.userAddress),receiver:B.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()});return i.gasLimit=i.gasLimit+BigInt(2e6),i}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new P(this.config).validate(r),h.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=C.Warp(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=h.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),o=await this.createFromTransaction(i);return e&&e.ttl&&o&&this.cache.set(r,o,e.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 new P(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return H(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var d=require("@multiversx/sdk-core/out");var Q={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{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 U=class{constructor(t){this.cache=new A;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){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 r=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[d.BytesValue.fromHex(t),d.BytesValue.fromUTF8(e)]:[d.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[d.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){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.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromUTF8(t),d.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t),d.BytesValue.fromUTF8(e)]})}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.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t),d.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=C.RegistryInfo(t);if(e){let y=this.cache.get(r);if(y)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),y}let n=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[d.BytesValue.fromUTF8(t)]}),p=await i.runQuery(o),[u]=i.parseQueryResponse(p),l=u?x(u):null,f=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:f},e.ttl),{registryInfo:l,brand:f}}async getInfoByHash(t,e){let r=C.RegistryInfo(t);if(e){let y=this.cache.get(r);if(y)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),y}let n=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[d.BytesValue.fromHex(t)]}),p=await i.runQuery(o),[u]=i.parseQueryResponse(p),l=u?x(u):null,f=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:f},e.ttl),{registryInfo:l,brand:f}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new d.AddressValue(new d.Address(e))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o);return p.map(x)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new d.AddressValue(new d.Address(e))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o),u=p.map(y=>y.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(u.map(y=>this.fetchBrand(y,l)))).filter(y=>y!==null)}async fetchBrand(t,e){let r=C.Brand(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=h.getConfiguredChainApi(this.config);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*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}getRegistryContractAddress(){return this.config.registryContract||w.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),n=await e.runQuery(r),[i]=e.parseQueryResponse(n),o=BigInt(i.toString());this.unitPrice=o}getFactory(){let t=new d.TransactionsFactoryConfig({chainID:W(this.config.env)}),e=d.AbiRegistry.create(Q);return new d.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=h.getConfiguredChainApi(this.config),e=new d.QueryRunnerAdapter({networkProvider:t}),r=d.AbiRegistry.create(Q);return new d.SmartContractQueriesController({queryRunner:e,abi:r})}};var F=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(g.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),o=(await Promise.all(n)).filter(l=>l.match),p=o.length>0,u=o.map(l=>({url:l.url,warp:l.warp}));return{match:p,results:u}}async detect(t){let e=t.startsWith(g.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):h.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new R(this.config),o=new U(this.config),p=null,u=null,l=null;if(r==="hash"){p=await i.createFromTransactionHash(n);try{let{registryInfo:f,brand:y}=await o.getInfoByHash(n);u=f,l=y}catch{}}else if(r==="alias"){let{registryInfo:f,brand:y}=await o.getInfoByAlias(n);u=f,l=y,f&&(p=await i.createFromTransactionHash(f.hash))}return p?{match:!0,url:t,warp:p,registryInfo:u,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||w.DefaultClientUrl(this.config.env),n=t===g.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+g.IdentifierParamSeparator+e);return w.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${g.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",o="#23F7DD"){let p=this.build(t,e);return new J.default({type:"svg",width:r,height:r,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>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=w.SuperClientUrls.includes(e.origin),n=e.searchParams.get(g.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let o=decodeURIComponent(i);return h.getInfoFromPrefixedIdentifier(o)}};var gt="https://",Z="query",X="env",h=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,o)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([i,o])=>{if(typeof o=="string"&&o.startsWith(`${Z}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=o.split(`${Z}:`)[1],u=new URL(e.currentUrl).searchParams.get(p);u&&n(i,u)}else if(typeof o=="string"&&o.startsWith(`${X}:`)){let p=o.split(`${X}:`)[1],u=e.vars?.[p];u&&n(i,u)}else n(i,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(g.IdentifierParamSeparator)?e:`${g.IdentifierType.Alias}${g.IdentifierParamSeparator}${e}`,[n,i]=r.split(g.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(gt))return t.next;{let r=new F(e),n=s.getInfoFromPrefixedIdentifier(t.next);return n?r.build(n.type,n.id):null}}static getConfiguredChainApi(t){let e=t.chainApiUrl||w.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new Y.ApiNetworkProvider(e,{timeout:3e4,clientName:"warp-sdk"})}};var j=class{constructor(t){this.pendingBrand={protocol:I("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new v.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new v.TransferTransactionsFactory({config:e}),n=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:v.Address.newFromBech32(this.config.userAddress),receiver:v.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=h.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),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,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||w.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new tt.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"),ft=(s,t)=>s?c.OptionValue.newProvided(s):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),mt=(s,t)=>s?new c.OptionalValue(s.getType(),s):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),ht=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new c.List(t,s)},yt=s=>c.VariadicValue.fromItems(...s),wt=s=>{let t=s.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),s)},Tt=s=>c.StringValue.fromUTF8(s),Wt=s=>new c.U8Value(s),At=s=>new c.U16Value(s),Ct=s=>new c.U32Value(s),bt=s=>new c.U64Value(s),It=s=>new c.BigUIntValue(BigInt(s)),Bt=s=>new c.BooleanValue(s),vt=s=>new c.AddressValue(c.Address.newFromBech32(s)),St=s=>new c.TokenIdentifierValue(s),xt=s=>c.BytesValue.fromHex(s),Vt=s=>new c.Struct(new c.StructType("EsdtTokenPayment",[new c.FieldDefinition("token_identifier","",new c.TokenIdentifierType),new c.FieldDefinition("token_nonce","",new c.U64Type),new c.FieldDefinition("amount","",new c.BigUIntType)]),[new c.Field(new c.TokenIdentifierValue(s.token.identifier),"token_identifier"),new c.Field(new c.U64Value(BigInt(s.token.nonce)),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(s.amount)),"amount")]),Pt=s=>new c.CodeMetadataValue(c.CodeMetadata.fromBuffer(Buffer.from(s,"hex"))),Rt=()=>new c.NothingValue;var S=require("@multiversx/sdk-core");var E=class{constructor(t){this.cache=new A;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new S.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new S.TransferTransactionsFactory({config:e}),n={protocol:I("abi"),content:t},i=JSON.stringify(n),o=r.createTransactionForTransfer({sender:S.Address.newFromBech32(this.config.userAddress),receiver:S.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=C.WarpAbi(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),i}let n=h.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),o=await this.createFromTransaction(i);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(i){return console.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}};var m=require("@multiversx/sdk-core/out");var Ut=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],et=s=>Ut.find(t=>t.id===s)||null;var a=require("@multiversx/sdk-core/out");var rt=new RegExp(`${g.ArgParamsSeparator}(.*)`),N=class{nativeToString(t,e){return t==="esdt"&&e instanceof a.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(a.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(a.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(a.List.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(a.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(a.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(p=>this.typedToString(p).split(g.ArgParamsSeparator)[0]),n=e.map(p=>this.typedToString(p).split(g.ArgParamsSeparator)[1]),i=r.join(g.ArgCompositeSeparator),o=n.join(g.ArgCompositeSeparator);return`composite(${i}):${o}`}if(t.hasClassOrSuperclass(a.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(a.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(a.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(a.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(a.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new a.CompositeType(...e.split(g.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new a.StringType;if(t==="uint8")return new a.U8Type;if(t==="uint16")return new a.U16Type;if(t==="uint32")return new a.U32Type;if(t==="uint64")return new a.U64Type;if(t==="biguint")return new a.BigUIntType;if(t==="bool")return new a.BooleanType;if(t==="address")return new a.AddressType;if(t==="token")return new a.TokenIdentifierType;if(t==="hex")return new a.BytesType;if(t==="codemeta")return new a.CodeMetadataType;if(t==="esdt"||t==="nft")return new a.StructType("EsdtTokenPayment",[new a.FieldDefinition("token_identifier","",new a.TokenIdentifierType),new a.FieldDefinition("token_nonce","",new a.U64Type),new a.FieldDefinition("amount","",new a.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(g.ArgParamsSeparator),r=e[0],n=e.slice(1).join(g.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,o]=n.split(g.ArgParamsSeparator);return[`option:${i}`,o||null]}else if(r==="optional"){let[i,o]=n.split(g.ArgParamsSeparator);return[`optional:${i}`,o||null]}else if(r==="list"){let i=n.split(g.ArgParamsSeparator),o=i.slice(0,-1).join(g.ArgParamsSeparator),p=i[i.length-1],l=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`list:${o}`,l]}else if(r==="variadic"){let i=n.split(g.ArgParamsSeparator),o=i.slice(0,-1).join(g.ArgParamsSeparator),p=i[i.length-1],l=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`variadic:${o}`,l]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(g.ArgCompositeSeparator),p=n.split(g.ArgCompositeSeparator).map((u,l)=>this.stringToNative(`${i[l]}:${u}`)[1]);return[r,p]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,o,p]=n.split(g.ArgCompositeSeparator);return[r,new a.TokenTransfer({token:new a.Token({identifier:i,nonce:BigInt(o)}),amount:BigInt(p)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new a.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionValue.newMissingTyped(n.getType()):a.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionalValue.newMissing():new a.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(rt,2),p=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new a.List(this.nativeToType(n),p)}if(e==="variadic"){let[n,i]=r.split(rt,2),p=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new a.VariadicValue(new a.VariadicType(this.nativeToType(n)),p)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(g.ArgCompositeSeparator),o=n.split(g.ArgCompositeSeparator),p=i.map((l,f)=>this.stringToTyped(`${o[f]}:${l}`)),u=p.map(l=>l.getType());return new a.CompositeValue(new a.CompositeType(...u),p)}if(e==="string")return r?a.StringValue.fromUTF8(r):new a.NothingValue;if(e==="uint8")return r?new a.U8Value(Number(r)):new a.NothingValue;if(e==="uint16")return r?new a.U16Value(Number(r)):new a.NothingValue;if(e==="uint32")return r?new a.U32Value(Number(r)):new a.NothingValue;if(e==="uint64")return r?new a.U64Value(BigInt(r)):new a.NothingValue;if(e==="biguint")return r?new a.BigUIntValue(BigInt(r)):new a.NothingValue;if(e==="bool")return r?new a.BooleanValue(typeof r=="boolean"?r:r==="true"):new a.NothingValue;if(e==="address")return r?new a.AddressValue(a.Address.newFromBech32(r)):new a.NothingValue;if(e==="token")return r?new a.TokenIdentifierValue(r):new a.NothingValue;if(e==="hex")return r?a.BytesValue.fromHex(r):new a.NothingValue;if(e==="codemeta")return new a.CodeMetadataValue(a.CodeMetadata.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let n=r.split(g.ArgCompositeSeparator);return new a.Struct(this.nativeToType("esdt"),[new a.Field(new a.TokenIdentifierValue(n[0]),"token_identifier"),new a.Field(new a.U64Value(BigInt(n[1])),"token_nonce"),new a.Field(new a.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof a.StringType)return"string";if(t instanceof a.U8Type)return"uint8";if(t instanceof a.U16Type)return"uint16";if(t instanceof a.U32Type)return"uint32";if(t instanceof a.U64Type)return"uint64";if(t instanceof a.BigUIntType)return"biguint";if(t instanceof a.BooleanType)return"bool";if(t instanceof a.AddressType)return"address";if(t instanceof a.TokenIdentifierType)return"token";if(t instanceof a.BytesType)return"hex";if(t instanceof a.CodeMetadataType)return"codemeta";if(t instanceof a.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var k=class{constructor(t){this.config=t}async getContract(t){try{let r=await h.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await h.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var M=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new N,this.contractLoader=new k(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=m.Address.newFromBech32(this.config.userAddress),n=new m.TransactionsFactoryConfig({chainID:W(this.config.env)}),{destination:i,args:o,value:p,transfers:u}=await this.getTxComponentsFromInputs(t,e,r),l=o.map(f=>this.serializer.stringToTyped(f));return i.isContractAddress()?new m.SmartContractTransactionsFactory({config:n}).createTransactionForExecute({sender:r,contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:l,tokenTransfers:u,nativeTransferAmount:p}):new m.TransferTransactionsFactory({config:n}).createTransactionForTransfer({sender:r,receiver:i,nativeAmount:p,tokenTransfers:u,data:l[0]?.hasExactClass(m.StringValue.ClassName)?l[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=h.getConfiguredChainApi(this.config),n=new m.QueryRunnerAdapter({networkProvider:r}),i=await this.getAbiForAction(t),{args:o}=await this.getTxComponentsFromInputs(t,e),p=o.map(T=>this.serializer.stringToTyped(T)),u=new m.SmartContractQueriesController({queryRunner:n,abi:i}),l=u.createQuery({contract:t.address,function:t.func,arguments:p}),f=await u.runQuery(l),y=new m.ResultsParser,$={returnCode:f.returnCode,returnMessage:f.returnMessage,getReturnDataParts:()=>f.returnDataParts.map(T=>Buffer.from(T))},q=f.function,D=i.getEndpoint(q),O=y.parseQueryResponse($,D).firstValue;if(!O)throw new Error("WarpActionExecutor: Query result not found");return O}async executeCollect(t,e,r){let n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([i,o])=>{n.set(i,o)}),await fetch(t.destination.url,{method:t.destination.method,headers:n,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),o=i.find(T=>T.input.position==="receiver")?.value,p="address"in t?t.address:null,u=o?.split(":")[1]||p||r?.toBech32();if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=m.Address.newFromBech32(u),f=this.getPreparedArgs(t,i),y=i.find(T=>T.input.position==="value")?.value||null,$="value"in t?t.value:null,q=BigInt(y?.split(":")[1]||$||0),D=i.filter(T=>T.input.position==="transfer"&&T.value).map(T=>T.value),O=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...D?.map(T=>this.serializer.stringToNative(T)[1])||[]];return{destination:l,args:f,value:q,transfers:O}}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(u=>u.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let o=e.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=V(o,+i);return{...e,value:`${e.input.type}:${p}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=V(i,+n);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(o=>this.preprocessInput(o))),i=(o,p)=>o.source==="query"?this.serializer.nativeToString(o.type,this.url.searchParams.get(o.name)||""):n[p]||null;return r.map((o,p)=>({input:o,value:i(o,p)}))}async preprocessInput(t){try{let[e,r]=this.serializer.stringToNative(t);if(e==="esdt"){let[,,,n]=t.split(g.ArgCompositeSeparator);if(n)return t;let i=r;if(!new m.TokenComputer().isFungible(i.token))return t;let u=et(i.token.identifier)?.decimals;if(!u){let f=this.config.chainApiUrl||w.Chain.ApiUrl(this.config.env);u=(await(await fetch(`${f}/tokens/${i.token.identifier}`)).json()).decimals}if(!u)throw new Error(`WarpActionExecutor: Decimals not found for token ${i.token.identifier}`);let l=new m.TokenTransfer({token:i.token,amount:V(i.amount,u)});return this.serializer.nativeToString(e,l)+g.ArgCompositeSeparator+u}return t}catch{return t}}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position.startsWith("arg:"))return;let o=Number(n.position.split(":")[1])-1;r.splice(o,0,i)}),r}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return m.AbiRegistry.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(g.IdentifierType.Hash)){let r=await new E(this.config).createFromTransactionHash(t.abi);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return m.AbiRegistry.create(r.content)}else{let r=await(await fetch(t.abi)).json();return m.AbiRegistry.create(r)}}toTypedTransfer(t){return new m.TokenTransfer({token:new m.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var z=class{constructor(t){this.config=t}async search(t){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let e=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t})});if(!e.ok)throw new Error(`WarpIndex: search failed with status ${e.status}`);return(await e.json()).hits}catch(e){throw console.error("WarpIndex: Error searching for warps: ",e),e}}};0&&(module.exports={BrandBuilder,Config,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpConstants,WarpContractLoader,WarpIndex,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,address,biguint,boolean,codemeta,composite,esdt,getChainId,getLatestProtocolIdentifier,getWarpActionByIndex,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
|
|
1
|
+
"use strict";var it=Object.create;var L=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var ot=Object.getPrototypeOf,ct=Object.prototype.hasOwnProperty;var pt=(s,t)=>{for(var e in t)L(s,e,{get:t[e],enumerable:!0})},G=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of st(t))!ct.call(s,n)&&n!==e&&L(s,n,{get:()=>t[n],enumerable:!(r=at(t,n))||r.enumerable});return s};var _=(s,t,e)=>(e=s!=null?it(ot(s)):{},G(t||!s||!s.__esModule?L(e,"default",{value:s,enumerable:!0}):e,s)),ut=s=>G(L({},"__esModule",{value:!0}),s);var Ft={};pt(Ft,{BrandBuilder:()=>j,Config:()=>w,WarpAbiBuilder:()=>E,WarpActionExecutor:()=>M,WarpArgSerializer:()=>N,WarpBuilder:()=>R,WarpConstants:()=>g,WarpContractLoader:()=>k,WarpIndex:()=>z,WarpLink:()=>F,WarpProtocolVersions:()=>b,WarpRegistry:()=>U,WarpUtils:()=>h,address:()=>vt,biguint:()=>It,boolean:()=>Bt,codemeta:()=>Pt,composite:()=>wt,esdt:()=>Vt,getChainId:()=>W,getLatestProtocolIdentifier:()=>I,getWarpActionByIndex:()=>lt,hex:()=>xt,list:()=>ht,nothing:()=>Rt,option:()=>ft,optional:()=>mt,shiftBigintBy:()=>V,string:()=>Tt,toPreviewText:()=>H,toTypedRegistryInfo:()=>x,token:()=>St,u16:()=>At,u32:()=>Ct,u64:()=>bt,u8:()=>Wt,variadic:()=>yt});module.exports=ut(Ft);var v=require("@multiversx/sdk-core"),tt=_(require("ajv"));var b={Warp:"0.5.0",Brand:"0.1.0",Abi:"0.1.0"},w={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${b.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${b.Brand}.schema.json`,DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.usewarp.to"],Chain:{ApiUrl:s=>s==="devnet"?"https://devnet-api.multiversx.com":s==="testnet"?"https://testnet-api.multiversx.com":"https://api.multiversx.com"},Registry:{Contract:s=>s==="devnet"?"erd1qqqqqqqqqqqqqpgqje2f99vr6r7sk54thg03c9suzcvwr4nfl3tsfkdl36":s==="testnet"?"####":"erd1qqqqqqqqqqqqqpgq3mrpj3u6q7tejv6d7eqhnyd27n9v5c5tl3ts08mffe"},AvailableActionInputSources:["field","query"],AvailableActionInputTypes:["string","uint8","uint16","uint32","uint64","biguint","boolean","address"],AvailableActionInputPositions:["value","arg:1","arg:2","arg:3","arg:4","arg:5","arg:6","arg:7","arg:8","arg:9","arg:10"]};var W=s=>s==="devnet"?"D":s==="testnet"?"T":"1",I=s=>{if(s==="warp")return`warp:${b.Warp}`;if(s==="brand")return`brand:${b.Brand}`;if(s==="abi")return`abi:${b.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},lt=(s,t)=>s?.actions[t-1],x=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}),V=(s,t)=>{let e=s.toString(),[r,n=""]=e.split("."),i=Math.abs(t);if(t>0)return BigInt(r+n.padEnd(i,"0"));if(t<0){let o=r+n;if(i>=o.length)return 0n;let p=o.slice(0,-i)||"0";return BigInt(p)}else return BigInt(s)},H=(s,t=100)=>{if(!s)return"";let e=s.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};var Y=require("@multiversx/sdk-core/out");var g={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};var J=_(require("qr-code-styling"));var B=require("@multiversx/sdk-core");var C={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},A=class{constructor(){this.cache=new Map}set(t,e,r){let n=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:n})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};var K=_(require("ajv"));var P=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||w.LatestWarpSchemaUrl,n=await(await fetch(e)).json(),i=new K.default,o=i.compile(n);if(!o(t))throw new Error(`WarpBuilder: schema validation failed: ${i.errorsText(o.errors)}`)}};var R=class{constructor(t){this.cache=new A;this.pendingWarp={protocol:I("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new B.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new B.TransferTransactionsFactory({config:e}),n=JSON.stringify(t),i=r.createTransactionForTransfer({sender:B.Address.newFromBech32(this.config.userAddress),receiver:B.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()});return i.gasLimit=i.gasLimit+BigInt(2e6),i}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new P(this.config).validate(r),h.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=C.Warp(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),i}let n=h.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),o=await this.createFromTransaction(i);return e&&e.ttl&&o&&this.cache.set(r,o,e.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 new P(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return H(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};var d=require("@multiversx/sdk-core/out");var Q={buildInfo:{rustc:{version:"1.80.0-nightly",commitHash:"791adf759cc065316f054961875052d5bc03e16c",commitDate:"2024-05-21",channel:"Nightly",short:"rustc 1.80.0-nightly (791adf759 2024-05-21)"},contractCrate:{name:"registry",version:"0.0.1"},framework:{name:"multiversx-sc",version:"0.51.1"}},name:"RegistryContract",constructor:{inputs:[{name:"unit_price",type:"BigUint"},{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 U=class{constructor(t){this.cache=new A;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){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 r=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[d.BytesValue.fromHex(t),d.BytesValue.fromUTF8(e)]:[d.BytesValue.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[d.BytesValue.fromHex(t)]})}createWarpUpgradeTransaction(t,e){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.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromUTF8(t),d.BytesValue.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t),d.BytesValue.fromUTF8(e)]})}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.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:d.Address.newFromBech32(this.config.userAddress),contract:d.Address.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[d.BytesValue.fromHex(t),d.BytesValue.fromHex(e)]})}async getInfoByAlias(t,e){let r=C.RegistryInfo(t);if(e){let y=this.cache.get(r);if(y)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),y}let n=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByAlias",arguments:[d.BytesValue.fromUTF8(t)]}),p=await i.runQuery(o),[u]=i.parseQueryResponse(p),l=u?x(u):null,f=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:f},e.ttl),{registryInfo:l,brand:f}}async getInfoByHash(t,e){let r=C.RegistryInfo(t);if(e){let y=this.cache.get(r);if(y)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),y}let n=this.getRegistryContractAddress(),i=this.getController(),o=i.createQuery({contract:n,function:"getInfoByHash",arguments:[d.BytesValue.fromHex(t)]}),p=await i.runQuery(o),[u]=i.parseQueryResponse(p),l=u?x(u):null,f=l?.brand?await this.fetchBrand(l.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:l,brand:f},e.ttl),{registryInfo:l,brand:f}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserWarps",arguments:[new d.AddressValue(new d.Address(e))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o);return p.map(x)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),n=this.getController(),i=n.createQuery({contract:r,function:"getUserBrands",arguments:[new d.AddressValue(new d.Address(e))]}),o=await n.runQuery(i),[p]=n.parseQueryResponse(o),u=p.map(y=>y.toString("hex")),l={ttl:365*24*60*60};return(await Promise.all(u.map(y=>this.fetchBrand(y,l)))).filter(y=>y!==null)}async fetchBrand(t,e){let r=C.Brand(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),i}let n=h.getConfiguredChainApi(this.config);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*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,o,e.ttl),o}catch(i){return console.error("WarpRegistry: Error fetching brand from transaction hash",i),null}}getRegistryContractAddress(){return this.config.registryContract||w.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),n=await e.runQuery(r),[i]=e.parseQueryResponse(n),o=BigInt(i.toString());this.unitPrice=o}getFactory(){let t=new d.TransactionsFactoryConfig({chainID:W(this.config.env)}),e=d.AbiRegistry.create(Q);return new d.SmartContractTransactionsFactory({config:t,abi:e})}getController(){let t=h.getConfiguredChainApi(this.config),e=new d.QueryRunnerAdapter({networkProvider:t}),r=d.AbiRegistry.create(Q);return new d.SmartContractQueriesController({queryRunner:e,abi:r})}};var F=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(g.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let n=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(l=>l[0]).filter(l=>this.isValid(l)).map(l=>this.detect(l)),o=(await Promise.all(n)).filter(l=>l.match),p=o.length>0,u=o.map(l=>({url:l.url,warp:l.warp}));return{match:p,results:u}}async detect(t){let e=t.startsWith(g.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):h.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:n}=e,i=new R(this.config),o=new U(this.config),p=null,u=null,l=null;if(r==="hash"){p=await i.createFromTransactionHash(n);try{let{registryInfo:f,brand:y}=await o.getInfoByHash(n);u=f,l=y}catch{}}else if(r==="alias"){let{registryInfo:f,brand:y}=await o.getInfoByAlias(n);u=f,l=y,f&&(p=await i.createFromTransactionHash(f.hash))}return p?{match:!0,url:t,warp:p,registryInfo:u,brand:l}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||w.DefaultClientUrl(this.config.env),n=t===g.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+g.IdentifierParamSeparator+e);return w.SuperClientUrls.includes(r)?`${r}/${n}`:`${r}?${g.IdentifierParamName}=${n}`}generateQrCode(t,e,r=512,n="white",i="black",o="#23F7DD"){let p=this.build(t,e);return new J.default({type:"svg",width:r,height:r,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>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=w.SuperClientUrls.includes(e.origin),n=e.searchParams.get(g.IdentifierParamName),i=r&&!n?e.pathname.split("/")[1]:n;if(!i)return null;let o=decodeURIComponent(i);return h.getInfoFromPrefixedIdentifier(o)}};var gt="https://",Z="query",X="env",h=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),n=(i,o)=>{r=r.replace(new RegExp(`{{${i.toUpperCase()}}}`,"g"),o.toString())};return Object.entries(t.vars).forEach(([i,o])=>{if(typeof o=="string"&&o.startsWith(`${Z}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let p=o.split(`${Z}:`)[1],u=new URL(e.currentUrl).searchParams.get(p);u&&n(i,u)}else if(typeof o=="string"&&o.startsWith(`${X}:`)){let p=o.split(`${X}:`)[1],u=e.vars?.[p];u&&n(i,u)}else n(i,o)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(g.IdentifierParamSeparator)?e:`${g.IdentifierType.Alias}${g.IdentifierParamSeparator}${e}`,[n,i]=r.split(g.IdentifierParamSeparator);return{type:n,id:i}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(gt))return t.next;{let r=new F(e),n=s.getInfoFromPrefixedIdentifier(t.next);return n?r.build(n.type,n.id):null}}static getConfiguredChainApi(t){let e=t.chainApiUrl||w.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new Y.ApiNetworkProvider(e,{timeout:3e4,clientName:"warp-sdk"})}};var j=class{constructor(t){this.pendingBrand={protocol:I("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new v.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new v.TransferTransactionsFactory({config:e}),n=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:v.Address.newFromBech32(this.config.userAddress),receiver:v.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=h.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),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,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||w.LatestBrandSchemaUrl,n=await(await fetch(e)).json(),i=new tt.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"),ft=(s,t)=>s?c.OptionValue.newProvided(s):t?c.OptionValue.newMissingTyped(t):c.OptionValue.newMissing(),mt=(s,t)=>s?new c.OptionalValue(s.getType(),s):t?new c.OptionalValue(t):c.OptionalValue.newMissing(),ht=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new c.List(t,s)},yt=s=>c.VariadicValue.fromItems(...s),wt=s=>{let t=s.map(e=>e.getType());return new c.CompositeValue(new c.CompositeType(...t),s)},Tt=s=>c.StringValue.fromUTF8(s),Wt=s=>new c.U8Value(s),At=s=>new c.U16Value(s),Ct=s=>new c.U32Value(s),bt=s=>new c.U64Value(s),It=s=>new c.BigUIntValue(BigInt(s)),Bt=s=>new c.BooleanValue(s),vt=s=>new c.AddressValue(c.Address.newFromBech32(s)),St=s=>new c.TokenIdentifierValue(s),xt=s=>c.BytesValue.fromHex(s),Vt=s=>new c.Struct(new c.StructType("EsdtTokenPayment",[new c.FieldDefinition("token_identifier","",new c.TokenIdentifierType),new c.FieldDefinition("token_nonce","",new c.U64Type),new c.FieldDefinition("amount","",new c.BigUIntType)]),[new c.Field(new c.TokenIdentifierValue(s.token.identifier),"token_identifier"),new c.Field(new c.U64Value(BigInt(s.token.nonce)),"token_nonce"),new c.Field(new c.BigUIntValue(BigInt(s.amount)),"amount")]),Pt=s=>new c.CodeMetadataValue(c.CodeMetadata.fromBuffer(Buffer.from(s,"hex"))),Rt=()=>new c.NothingValue;var S=require("@multiversx/sdk-core");var E=class{constructor(t){this.cache=new A;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new S.TransactionsFactoryConfig({chainID:W(this.config.env)}),r=new S.TransferTransactionsFactory({config:e}),n={protocol:I("abi"),content:t},i=JSON.stringify(n),o=r.createTransactionForTransfer({sender:S.Address.newFromBech32(this.config.userAddress),receiver:S.Address.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return o.gasLimit=o.gasLimit+BigInt(2e6),o}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=C.WarpAbi(t);if(e){let i=this.cache.get(r);if(i)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),i}let n=h.getConfiguredChainApi(this.config);try{let i=await n.getTransaction(t),o=await this.createFromTransaction(i);return e&&e.ttl&&o&&this.cache.set(r,o,e.ttl),o}catch(i){return console.error("WarpAbiBuilder: Error creating from transaction hash",i),null}}};var m=require("@multiversx/sdk-core/out");var Ut=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],et=s=>Ut.find(t=>t.id===s)||null;var a=require("@multiversx/sdk-core/out");var rt=new RegExp(`${g.ArgParamsSeparator}(.*)`),N=class{nativeToString(t,e){return t==="esdt"&&e instanceof a.TokenTransfer?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(a.OptionValue.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(a.OptionalValue.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(a.List.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[1]);return`list:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(a.VariadicValue.ClassName)){let e=t.getItems(),n=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[0])[0],i=e.map(o=>this.typedToString(o).split(g.ArgParamsSeparator)[1]);return`variadic:${n}:${i.join(",")}`}if(t.hasClassOrSuperclass(a.CompositeValue.ClassName)){let e=t.getItems(),r=e.map(p=>this.typedToString(p).split(g.ArgParamsSeparator)[0]),n=e.map(p=>this.typedToString(p).split(g.ArgParamsSeparator)[1]),i=r.join(g.ArgCompositeSeparator),o=n.join(g.ArgCompositeSeparator);return`composite(${i}):${o}`}if(t.hasClassOrSuperclass(a.BigUIntValue.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(a.U8Value.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U16Value.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U32Value.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(a.U64Value.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(a.StringValue.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.BooleanValue.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.AddressValue.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(a.TokenIdentifierValue.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(a.BytesValue.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(a.CodeMetadataValue.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),n=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${n}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new a.CompositeType(...e.split(g.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new a.StringType;if(t==="uint8")return new a.U8Type;if(t==="uint16")return new a.U16Type;if(t==="uint32")return new a.U32Type;if(t==="uint64")return new a.U64Type;if(t==="biguint")return new a.BigUIntType;if(t==="bool")return new a.BooleanType;if(t==="address")return new a.AddressType;if(t==="token")return new a.TokenIdentifierType;if(t==="hex")return new a.BytesType;if(t==="codemeta")return new a.CodeMetadataType;if(t==="esdt"||t==="nft")return new a.StructType("EsdtTokenPayment",[new a.FieldDefinition("token_identifier","",new a.TokenIdentifierType),new a.FieldDefinition("token_nonce","",new a.U64Type),new a.FieldDefinition("amount","",new a.BigUIntType)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(g.ArgParamsSeparator),r=e[0],n=e.slice(1).join(g.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[i,o]=n.split(g.ArgParamsSeparator);return[`option:${i}`,o||null]}else if(r==="optional"){let[i,o]=n.split(g.ArgParamsSeparator);return[`optional:${i}`,o||null]}else if(r==="list"){let i=n.split(g.ArgParamsSeparator),o=i.slice(0,-1).join(g.ArgParamsSeparator),p=i[i.length-1],l=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`list:${o}`,l]}else if(r==="variadic"){let i=n.split(g.ArgParamsSeparator),o=i.slice(0,-1).join(g.ArgParamsSeparator),p=i[i.length-1],l=(p?p.split(","):[]).map(f=>this.stringToNative(`${o}:${f}`)[1]);return[`variadic:${o}`,l]}else if(r.startsWith("composite")){let i=r.match(/\(([^)]+)\)/)?.[1]?.split(g.ArgCompositeSeparator),p=n.split(g.ArgCompositeSeparator).map((u,l)=>this.stringToNative(`${i[l]}:${u}`)[1]);return[r,p]}else{if(r==="string")return[r,n];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(n)];if(r==="uint64"||r==="biguint")return[r,BigInt(n||0)];if(r==="bool")return[r,n==="true"];if(r==="address")return[r,n];if(r==="token")return[r,n];if(r==="hex")return[r,n];if(r==="codemeta")return[r,n];if(r==="esdt"){let[i,o,p]=n.split(g.ArgCompositeSeparator);return[r,new a.TokenTransfer({token:new a.Token({identifier:i,nonce:BigInt(o)}),amount:BigInt(p)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new a.NothingValue;if(e==="option"){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionValue.newMissingTyped(n.getType()):a.OptionValue.newProvided(n)}if(e==="optional"){let n=this.stringToTyped(r);return n instanceof a.NothingValue?a.OptionalValue.newMissing():new a.OptionalValue(n.getType(),n)}if(e==="list"){let[n,i]=r.split(rt,2),p=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new a.List(this.nativeToType(n),p)}if(e==="variadic"){let[n,i]=r.split(rt,2),p=i.split(",").map(u=>this.stringToTyped(`${n}:${u}`));return new a.VariadicValue(new a.VariadicType(this.nativeToType(n)),p)}if(e.startsWith("composite")){let n=e.match(/\(([^)]+)\)/)?.[1],i=r.split(g.ArgCompositeSeparator),o=n.split(g.ArgCompositeSeparator),p=i.map((l,f)=>this.stringToTyped(`${o[f]}:${l}`)),u=p.map(l=>l.getType());return new a.CompositeValue(new a.CompositeType(...u),p)}if(e==="string")return r?a.StringValue.fromUTF8(r):new a.NothingValue;if(e==="uint8")return r?new a.U8Value(Number(r)):new a.NothingValue;if(e==="uint16")return r?new a.U16Value(Number(r)):new a.NothingValue;if(e==="uint32")return r?new a.U32Value(Number(r)):new a.NothingValue;if(e==="uint64")return r?new a.U64Value(BigInt(r)):new a.NothingValue;if(e==="biguint")return r?new a.BigUIntValue(BigInt(r)):new a.NothingValue;if(e==="bool")return r?new a.BooleanValue(typeof r=="boolean"?r:r==="true"):new a.NothingValue;if(e==="address")return r?new a.AddressValue(a.Address.newFromBech32(r)):new a.NothingValue;if(e==="token")return r?new a.TokenIdentifierValue(r):new a.NothingValue;if(e==="hex")return r?a.BytesValue.fromHex(r):new a.NothingValue;if(e==="codemeta")return new a.CodeMetadataValue(a.CodeMetadata.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let n=r.split(g.ArgCompositeSeparator);return new a.Struct(this.nativeToType("esdt"),[new a.Field(new a.TokenIdentifierValue(n[0]),"token_identifier"),new a.Field(new a.U64Value(BigInt(n[1])),"token_nonce"),new a.Field(new a.BigUIntValue(BigInt(n[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof a.StringType)return"string";if(t instanceof a.U8Type)return"uint8";if(t instanceof a.U16Type)return"uint16";if(t instanceof a.U32Type)return"uint32";if(t instanceof a.U64Type)return"uint64";if(t instanceof a.BigUIntType)return"biguint";if(t instanceof a.BooleanType)return"bool";if(t instanceof a.AddressType)return"address";if(t instanceof a.TokenIdentifierType)return"token";if(t instanceof a.BytesType)return"hex";if(t instanceof a.CodeMetadataType)return"codemeta";if(t instanceof a.StructType&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var k=class{constructor(t){this.config=t}async getContract(t){try{let r=await h.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await h.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var M=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new N,this.contractLoader=new k(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=m.Address.newFromBech32(this.config.userAddress),n=new m.TransactionsFactoryConfig({chainID:W(this.config.env)}),{destination:i,args:o,value:p,transfers:u}=await this.getTxComponentsFromInputs(t,e,r),l=o.map(f=>this.serializer.stringToTyped(f));return i.isContractAddress()?new m.SmartContractTransactionsFactory({config:n}).createTransactionForExecute({sender:r,contract:i,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:l,tokenTransfers:u,nativeTransferAmount:p}):new m.TransferTransactionsFactory({config:n}).createTransactionForTransfer({sender:r,receiver:i,nativeAmount:p,tokenTransfers:u,data:l[0]?.hasExactClass(m.StringValue.ClassName)?l[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=h.getConfiguredChainApi(this.config),n=new m.QueryRunnerAdapter({networkProvider:r}),i=await this.getAbiForAction(t),{args:o}=await this.getTxComponentsFromInputs(t,e),p=o.map(T=>this.serializer.stringToTyped(T)),u=new m.SmartContractQueriesController({queryRunner:n,abi:i}),l=u.createQuery({contract:t.address,function:t.func,arguments:p}),f=await u.runQuery(l),y=new m.ResultsParser,$={returnCode:f.returnCode,returnMessage:f.returnMessage,getReturnDataParts:()=>f.returnDataParts.map(T=>Buffer.from(T))},q=f.function,D=i.getEndpoint(q),O=y.parseQueryResponse($,D).firstValue;if(!O)throw new Error("WarpActionExecutor: Query result not found");return O}async executeCollect(t,e,r){let n=new Headers;n.set("Content-Type","application/json"),n.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([i,o])=>{n.set(i,o)}),await fetch(t.destination.url,{method:t.destination.method,headers:n,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let n=await this.getResolvedInputs(t,e),i=this.getModifiedInputs(n),o=i.find(T=>T.input.position==="receiver")?.value,p="address"in t?t.address:null,u=o?.split(":")[1]||p||r?.toBech32();if(!u)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let l=m.Address.newFromBech32(u),f=this.getPreparedArgs(t,i),y=i.find(T=>T.input.position==="value")?.value||null,$="value"in t?t.value:null,q=BigInt(y?.split(":")[1]||$||0),D=i.filter(T=>T.input.position==="transfer"&&T.value).map(T=>T.value),O=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...D?.map(T=>this.serializer.stringToNative(T)[1])||[]];return{destination:l,args:f,value:q,transfers:O}}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,n]=e.input.modifier.split(":");if(isNaN(Number(n))){let i=Number(t.find(u=>u.input.name===n)?.value?.split(":")[1]);if(!i)throw new Error(`WarpActionExecutor: Exponent value not found for input ${n}`);let o=e.value?.split(":")[1];if(!o)throw new Error("WarpActionExecutor: Scalable value not found");let p=V(o,+i);return{...e,value:`${e.input.type}:${p}`}}else{let i=e.value?.split(":")[1];if(!i)throw new Error("WarpActionExecutor: Scalable value not found");let o=V(i,+n);return{...e,value:`${e.input.type}:${o}`}}}else return e})}async getResolvedInputs(t,e){let r=t.inputs||[],n=await Promise.all(e.map(o=>this.preprocessInput(o))),i=(o,p)=>o.source==="query"?this.serializer.nativeToString(o.type,this.url.searchParams.get(o.name)||""):n[p]||null;return r.map((o,p)=>({input:o,value:i(o,p)}))}async preprocessInput(t){try{let[e,r]=this.serializer.stringToNative(t);if(e==="esdt"){let[,,,n]=t.split(g.ArgCompositeSeparator);if(n)return t;let i=r;if(!new m.TokenComputer().isFungible(i.token))return t;let u=et(i.token.identifier)?.decimals;if(!u){let f=this.config.chainApiUrl||w.Chain.ApiUrl(this.config.env);u=(await(await fetch(`${f}/tokens/${i.token.identifier}`)).json()).decimals}if(!u)throw new Error(`WarpActionExecutor: Decimals not found for token ${i.token.identifier}`);let l=new m.TokenTransfer({token:i.token,amount:V(i.amount,u)});return this.serializer.nativeToString(e,l)+g.ArgCompositeSeparator+u}return t}catch{return t}}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:n,value:i})=>{if(!i||!n.position.startsWith("arg:"))return;let o=Number(n.position.split(":")[1])-1;r.splice(o,0,i)}),r}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return m.AbiRegistry.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(g.IdentifierType.Hash)){let e=new E(this.config),r=t.abi.split(g.IdentifierParamSeparator)[1],n=await e.createFromTransactionHash(r);if(!n)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return m.AbiRegistry.create(n.content)}else{let r=await(await fetch(t.abi)).json();return m.AbiRegistry.create(r)}}toTypedTransfer(t){return new m.TokenTransfer({token:new m.Token({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var z=class{constructor(t){this.config=t}async search(t){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let e=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t})});if(!e.ok)throw new Error(`WarpIndex: search failed with status ${e.status}`);return(await e.json()).hits}catch(e){throw console.error("WarpIndex: Error searching for warps: ",e),e}}};0&&(module.exports={BrandBuilder,Config,WarpAbiBuilder,WarpActionExecutor,WarpArgSerializer,WarpBuilder,WarpConstants,WarpContractLoader,WarpIndex,WarpLink,WarpProtocolVersions,WarpRegistry,WarpUtils,address,biguint,boolean,codemeta,composite,esdt,getChainId,getLatestProtocolIdentifier,getWarpActionByIndex,hex,list,nothing,option,optional,shiftBigintBy,string,toPreviewText,toTypedRegistryInfo,token,u16,u32,u64,u8,variadic});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Address as at,TransactionsFactoryConfig as Zt,TransferTransactionsFactory as Xt}from"@multiversx/sdk-core";import Yt from"ajv";var C={Warp:"0.5.0",Brand:"0.1.0",Abi:"0.1.0"},h={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${C.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${C.Brand}.schema.json`,DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.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 T=s=>s==="devnet"?"D":s==="testnet"?"T":"1",b=s=>{if(s==="warp")return`warp:${C.Warp}`;if(s==="brand")return`brand:${C.Brand}`;if(s==="abi")return`abi:${C.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},Le=(s,t)=>s?.actions[t-1],S=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}),x=(s,t)=>{let e=s.toString(),[r,i=""]=e.split("."),n=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(n,"0"));if(t<0){let a=r+i;if(n>=a.length)return 0n;let o=a.slice(0,-n)||"0";return BigInt(o)}else return BigInt(s)},Y=(s,t=100)=>{if(!s)return"";let e=s.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};import{ApiNetworkProvider as Kt}from"@multiversx/sdk-core/out";var u={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import Gt from"qr-code-styling";import{Address as tt,TransactionsFactoryConfig as Dt,TransferTransactionsFactory as _t}from"@multiversx/sdk-core";var A={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},W=class{constructor(){this.cache=new Map}set(t,e,r){let i=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:i})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};import qt from"ajv";var I=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||h.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),n=new qt,a=n.compile(i);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};var V=class{constructor(t){this.cache=new W;this.pendingWarp={protocol:b("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Dt({chainID:T(this.config.env)}),r=new _t({config:e}),i=JSON.stringify(t),n=r.createTransactionForTransfer({sender:tt.newFromBech32(this.config.userAddress),receiver:tt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return n.gasLimit=n.gasLimit+BigInt(2e6),n}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new I(this.config).validate(r),g.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=A.Warp(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),n}let i=g.getConfiguredChainApi(this.config);try{let n=await i.getTransaction(t),a=await this.createFromTransaction(n);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}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 new I(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Y(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};import{AbiRegistry as et,Address as f,AddressValue as rt,BytesValue as y,QueryRunnerAdapter as Qt,SmartContractQueriesController as jt,SmartContractTransactionsFactory as Mt,TransactionsFactoryConfig as zt}from"@multiversx/sdk-core/out";var $={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 P=class{constructor(t){this.cache=new W;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){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 r=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[y.fromHex(t),y.fromUTF8(e)]:[y.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[y.fromHex(t)]})}createWarpUpgradeTransaction(t,e){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:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromUTF8(t),y.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromUTF8(e)]})}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:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromHex(e)]})}async getInfoByAlias(t,e){let r=A.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),d}let i=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[y.fromUTF8(t)]}),o=await n.runQuery(a),[c]=n.parseQueryResponse(o),p=c?S(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}async getInfoByHash(t,e){let r=A.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let i=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByHash",arguments:[y.fromHex(t)]}),o=await n.runQuery(a),[c]=n.parseQueryResponse(o),p=c?S(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),i=this.getController(),n=i.createQuery({contract:r,function:"getUserWarps",arguments:[new rt(new f(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a);return o.map(S)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),i=this.getController(),n=i.createQuery({contract:r,function:"getUserBrands",arguments:[new rt(new f(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a),c=o.map(d=>d.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(d=>this.fetchBrand(d,p)))).filter(d=>d!==null)}async fetchBrand(t,e){let r=A.Brand(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n}let i=g.getConfiguredChainApi(this.config);try{let n=await i.getTransaction(t),a=JSON.parse(n.data.toString());return a.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,a,e.ttl),a}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}getRegistryContractAddress(){return this.config.registryContract||h.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await e.runQuery(r),[n]=e.parseQueryResponse(i),a=BigInt(n.toString());this.unitPrice=a}getFactory(){let t=new zt({chainID:T(this.config.env)}),e=et.create($);return new Mt({config:t,abi:e})}getController(){let t=g.getConfiguredChainApi(this.config),e=new Qt({networkProvider:t}),r=et.create($);return new jt({queryRunner:e,abi:r})}};var R=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(i)).filter(p=>p.match),o=a.length>0,c=a.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t){let e=t.startsWith(u.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):g.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,n=new V(this.config),a=new P(this.config),o=null,c=null,p=null;if(r==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:l,brand:d}=await a.getInfoByHash(i);c=l,p=d}catch{}}else if(r==="alias"){let{registryInfo:l,brand:d}=await a.getInfoByAlias(i);c=l,p=d,l&&(o=await n.createFromTransactionHash(l.hash))}return o?{match:!0,url:t,warp:o,registryInfo:c,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||h.DefaultClientUrl(this.config.env),i=t===u.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+u.IdentifierParamSeparator+e);return h.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${u.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",n="black",a="#23F7DD"){let o=this.build(t,e);return new Gt({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=h.SuperClientUrls.includes(e.origin),i=e.searchParams.get(u.IdentifierParamName),n=r&&!i?e.pathname.split("/")[1]:i;if(!n)return null;let a=decodeURIComponent(n);return g.getInfoFromPrefixedIdentifier(a)}};var Jt="https://",nt="query",it="env",g=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),i=(n,a)=>{r=r.replace(new RegExp(`{{${n.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(t.vars).forEach(([n,a])=>{if(typeof a=="string"&&a.startsWith(`${nt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${nt}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&i(n,c)}else if(typeof a=="string"&&a.startsWith(`${it}:`)){let o=a.split(`${it}:`)[1],c=e.vars?.[o];c&&i(n,c)}else i(n,a)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(u.IdentifierParamSeparator)?e:`${u.IdentifierType.Alias}${u.IdentifierParamSeparator}${e}`,[i,n]=r.split(u.IdentifierParamSeparator);return{type:i,id:n}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(Jt))return t.next;{let r=new R(e),i=s.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}static getConfiguredChainApi(t){let e=t.chainApiUrl||h.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new Kt(e,{timeout:3e4,clientName:"warp-sdk"})}};var st=class{constructor(t){this.pendingBrand={protocol:b("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new Zt({chainID:T(this.config.env)}),r=new Xt({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:at.newFromBech32(this.config.userAddress),receiver:at.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=g.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),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,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||h.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),n=new Yt,a=n.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};import{Address as te,AddressValue as ee,BigUIntType as re,BigUIntValue as ot,BooleanValue as ne,BytesValue as ie,CodeMetadata as ae,CodeMetadataValue as se,CompositeType as oe,CompositeValue as ce,Field as O,FieldDefinition as L,List as pe,NothingValue as ue,OptionalValue as q,OptionValue as D,StringValue as le,Struct as de,StructType as ge,TokenIdentifierType as fe,TokenIdentifierValue as ct,U16Value as me,U32Value as he,U64Type as ye,U64Value as pt,U8Value as we,VariadicValue as Te}from"@multiversx/sdk-core/out";var Fr=(s,t)=>s?D.newProvided(s):t?D.newMissingTyped(t):D.newMissing(),Er=(s,t)=>s?new q(s.getType(),s):t?new q(t):q.newMissing(),Nr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new pe(t,s)},kr=s=>Te.fromItems(...s),$r=s=>{let t=s.map(e=>e.getType());return new ce(new oe(...t),s)},Or=s=>le.fromUTF8(s),Lr=s=>new we(s),qr=s=>new me(s),Dr=s=>new he(s),_r=s=>new pt(s),Hr=s=>new ot(BigInt(s)),Qr=s=>new ne(s),jr=s=>new ee(te.newFromBech32(s)),Mr=s=>new ct(s),zr=s=>ie.fromHex(s),Gr=s=>new de(new ge("EsdtTokenPayment",[new L("token_identifier","",new fe),new L("token_nonce","",new ye),new L("amount","",new re)]),[new O(new ct(s.token.identifier),"token_identifier"),new O(new pt(BigInt(s.token.nonce)),"token_nonce"),new O(new ot(BigInt(s.amount)),"amount")]),Kr=s=>new se(ae.fromBuffer(Buffer.from(s,"hex"))),Jr=()=>new ue;import{Address as ut,TransactionsFactoryConfig as We,TransferTransactionsFactory as Ae}from"@multiversx/sdk-core";var U=class{constructor(t){this.cache=new W;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new We({chainID:T(this.config.env)}),r=new Ae({config:e}),i={protocol:b("abi"),content:t},n=JSON.stringify(i),a=r.createTransactionForTransfer({sender:ut.newFromBech32(this.config.userAddress),receiver:ut.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()});return a.gasLimit=a.gasLimit+BigInt(2e6),a}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=A.WarpAbi(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),n}let i=g.getConfiguredChainApi(this.config);try{let n=await i.getTransaction(t),a=await this.createFromTransaction(n);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}catch(n){return console.error("WarpAbiBuilder: Error creating from transaction hash",n),null}}};import{AbiRegistry as X,Address as Nt,QueryRunnerAdapter as xe,ResultsParser as Ve,SmartContractQueriesController as Pe,SmartContractTransactionsFactory as Re,StringValue as Ue,Token as Fe,TokenComputer as Ee,TokenTransfer as kt,TransactionsFactoryConfig as Ne,TransferTransactionsFactory as ke}from"@multiversx/sdk-core/out";var Ce=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],lt=s=>Ce.find(t=>t.id===s)||null;import{Address as be,AddressType as dt,AddressValue as gt,BigUIntType as _,BigUIntValue as H,BooleanType as ft,BooleanValue as mt,BytesType as ht,BytesValue as yt,CodeMetadata as Ie,CodeMetadataType as wt,CodeMetadataValue as Tt,CompositeType as Wt,CompositeValue as At,Field as Q,FieldDefinition as j,List as Ct,NothingValue as w,OptionalValue as M,OptionValue as z,StringType as bt,StringValue as It,Struct as Be,StructType as Bt,Token as ve,TokenIdentifierType as G,TokenIdentifierValue as K,TokenTransfer as vt,U16Type as St,U16Value as xt,U32Type as Vt,U32Value as Pt,U64Type as J,U64Value as Z,U8Type as Rt,U8Value as Ut,VariadicType as Se,VariadicValue as Ft}from"@multiversx/sdk-core/out";var Et=new RegExp(`${u.ArgParamsSeparator}(.*)`),F=class{nativeToString(t,e){return t==="esdt"&&e instanceof vt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(z.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(M.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Ct.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[0])[0],n=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[1]);return`list:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(Ft.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[0])[0],n=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[1]);return`variadic:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(At.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[0]),i=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[1]),n=r.join(u.ArgCompositeSeparator),a=i.join(u.ArgCompositeSeparator);return`composite(${n}):${a}`}if(t.hasClassOrSuperclass(H.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Ut.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(xt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Z.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(It.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(mt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(gt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(K.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(yt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Tt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),i=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${i}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new Wt(...e.split(u.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new bt;if(t==="uint8")return new Rt;if(t==="uint16")return new St;if(t==="uint32")return new Vt;if(t==="uint64")return new J;if(t==="biguint")return new _;if(t==="bool")return new ft;if(t==="address")return new dt;if(t==="token")return new G;if(t==="hex")return new ht;if(t==="codemeta")return new wt;if(t==="esdt"||t==="nft")return new Bt("EsdtTokenPayment",[new j("token_identifier","",new G),new j("token_nonce","",new J),new j("amount","",new _)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(u.ArgParamsSeparator),r=e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[n,a]=i.split(u.ArgParamsSeparator);return[`option:${n}`,a||null]}else if(r==="optional"){let[n,a]=i.split(u.ArgParamsSeparator);return[`optional:${n}`,a||null]}else if(r==="list"){let n=i.split(u.ArgParamsSeparator),a=n.slice(0,-1).join(u.ArgParamsSeparator),o=n[n.length-1],p=(o?o.split(","):[]).map(l=>this.stringToNative(`${a}:${l}`)[1]);return[`list:${a}`,p]}else if(r==="variadic"){let n=i.split(u.ArgParamsSeparator),a=n.slice(0,-1).join(u.ArgParamsSeparator),o=n[n.length-1],p=(o?o.split(","):[]).map(l=>this.stringToNative(`${a}:${l}`)[1]);return[`variadic:${a}`,p]}else if(r.startsWith("composite")){let n=r.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),o=i.split(u.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${n[p]}:${c}`)[1]);return[r,o]}else{if(r==="string")return[r,i];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(i)];if(r==="uint64"||r==="biguint")return[r,BigInt(i||0)];if(r==="bool")return[r,i==="true"];if(r==="address")return[r,i];if(r==="token")return[r,i];if(r==="hex")return[r,i];if(r==="codemeta")return[r,i];if(r==="esdt"){let[n,a,o]=i.split(u.ArgCompositeSeparator);return[r,new vt({token:new ve({identifier:n,nonce:BigInt(a)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new w;if(e==="option"){let i=this.stringToTyped(r);return i instanceof w?z.newMissingTyped(i.getType()):z.newProvided(i)}if(e==="optional"){let i=this.stringToTyped(r);return i instanceof w?M.newMissing():new M(i.getType(),i)}if(e==="list"){let[i,n]=r.split(Et,2),o=n.split(",").map(c=>this.stringToTyped(`${i}:${c}`));return new Ct(this.nativeToType(i),o)}if(e==="variadic"){let[i,n]=r.split(Et,2),o=n.split(",").map(c=>this.stringToTyped(`${i}:${c}`));return new Ft(new Se(this.nativeToType(i)),o)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],n=r.split(u.ArgCompositeSeparator),a=i.split(u.ArgCompositeSeparator),o=n.map((p,l)=>this.stringToTyped(`${a[l]}:${p}`)),c=o.map(p=>p.getType());return new At(new Wt(...c),o)}if(e==="string")return r?It.fromUTF8(r):new w;if(e==="uint8")return r?new Ut(Number(r)):new w;if(e==="uint16")return r?new xt(Number(r)):new w;if(e==="uint32")return r?new Pt(Number(r)):new w;if(e==="uint64")return r?new Z(BigInt(r)):new w;if(e==="biguint")return r?new H(BigInt(r)):new w;if(e==="bool")return r?new mt(typeof r=="boolean"?r:r==="true"):new w;if(e==="address")return r?new gt(be.newFromBech32(r)):new w;if(e==="token")return r?new K(r):new w;if(e==="hex")return r?yt.fromHex(r):new w;if(e==="codemeta")return new Tt(Ie.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let i=r.split(u.ArgCompositeSeparator);return new Be(this.nativeToType("esdt"),[new Q(new K(i[0]),"token_identifier"),new Q(new Z(BigInt(i[1])),"token_nonce"),new Q(new H(BigInt(i[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof bt)return"string";if(t instanceof Rt)return"uint8";if(t instanceof St)return"uint16";if(t instanceof Vt)return"uint32";if(t instanceof J)return"uint64";if(t instanceof _)return"biguint";if(t instanceof ft)return"bool";if(t instanceof dt)return"address";if(t instanceof G)return"token";if(t instanceof ht)return"hex";if(t instanceof wt)return"codemeta";if(t instanceof Bt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var E=class{constructor(t){this.config=t}async getContract(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var $t=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new F,this.contractLoader=new E(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=Nt.newFromBech32(this.config.userAddress),i=new Ne({chainID:T(this.config.env)}),{destination:n,args:a,value:o,transfers:c}=await this.getTxComponentsFromInputs(t,e,r),p=a.map(l=>this.serializer.stringToTyped(l));return n.isContractAddress()?new Re({config:i}).createTransactionForExecute({sender:r,contract:n,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:p,tokenTransfers:c,nativeTransferAmount:o}):new ke({config:i}).createTransactionForTransfer({sender:r,receiver:n,nativeAmount:o,tokenTransfers:c,data:p[0]?.hasExactClass(Ue.ClassName)?p[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=g.getConfiguredChainApi(this.config),i=new xe({networkProvider:r}),n=await this.getAbiForAction(t),{args:a}=await this.getTxComponentsFromInputs(t,e),o=a.map(m=>this.serializer.stringToTyped(m)),c=new Pe({queryRunner:i,abi:n}),p=c.createQuery({contract:t.address,function:t.func,arguments:o}),l=await c.runQuery(p),d=new Ve,B={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(m=>Buffer.from(m))},N=l.function,k=n.getEndpoint(N),v=d.parseQueryResponse(B,k).firstValue;if(!v)throw new Error("WarpActionExecutor: Query result not found");return v}async executeCollect(t,e,r){let i=new Headers;i.set("Content-Type","application/json"),i.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([n,a])=>{i.set(n,a)}),await fetch(t.destination.url,{method:t.destination.method,headers:i,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let i=await this.getResolvedInputs(t,e),n=this.getModifiedInputs(i),a=n.find(m=>m.input.position==="receiver")?.value,o="address"in t?t.address:null,c=a?.split(":")[1]||o||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=Nt.newFromBech32(c),l=this.getPreparedArgs(t,n),d=n.find(m=>m.input.position==="value")?.value||null,B="value"in t?t.value:null,N=BigInt(d?.split(":")[1]||B||0),k=n.filter(m=>m.input.position==="transfer"&&m.value).map(m=>m.value),v=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...k?.map(m=>this.serializer.stringToNative(m)[1])||[]];return{destination:p,args:l,value:N,transfers:v}}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,i]=e.input.modifier.split(":");if(isNaN(Number(i))){let n=Number(t.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!n)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=x(a,+n);return{...e,value:`${e.input.type}:${o}`}}else{let n=e.value?.split(":")[1];if(!n)throw new Error("WarpActionExecutor: Scalable value not found");let a=x(n,+i);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async getResolvedInputs(t,e){let r=t.inputs||[],i=await Promise.all(e.map(a=>this.preprocessInput(a))),n=(a,o)=>a.source==="query"?this.serializer.nativeToString(a.type,this.url.searchParams.get(a.name)||""):i[o]||null;return r.map((a,o)=>({input:a,value:n(a,o)}))}async preprocessInput(t){try{let[e,r]=this.serializer.stringToNative(t);if(e==="esdt"){let[,,,i]=t.split(u.ArgCompositeSeparator);if(i)return t;let n=r;if(!new Ee().isFungible(n.token))return t;let c=lt(n.token.identifier)?.decimals;if(!c){let l=this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env);c=(await(await fetch(`${l}/tokens/${n.token.identifier}`)).json()).decimals}if(!c)throw new Error(`WarpActionExecutor: Decimals not found for token ${n.token.identifier}`);let p=new kt({token:n.token,amount:x(n.amount,c)});return this.serializer.nativeToString(e,p)+u.ArgCompositeSeparator+c}return t}catch{return t}}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:i,value:n})=>{if(!n||!i.position.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;r.splice(a,0,n)}),r}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return X.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(u.IdentifierType.Hash)){let r=await new U(this.config).createFromTransactionHash(t.abi);if(!r)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return X.create(r.content)}else{let r=await(await fetch(t.abi)).json();return X.create(r)}}toTypedTransfer(t){return new kt({token:new Fe({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var Ot=class{constructor(t){this.config=t}async search(t){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let e=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t})});if(!e.ok)throw new Error(`WarpIndex: search failed with status ${e.status}`);return(await e.json()).hits}catch(e){throw console.error("WarpIndex: Error searching for warps: ",e),e}}};export{st as BrandBuilder,h as Config,U as WarpAbiBuilder,$t as WarpActionExecutor,F as WarpArgSerializer,V as WarpBuilder,u as WarpConstants,E as WarpContractLoader,Ot as WarpIndex,R as WarpLink,C as WarpProtocolVersions,P as WarpRegistry,g as WarpUtils,jr as address,Hr as biguint,Qr as boolean,Kr as codemeta,$r as composite,Gr as esdt,T as getChainId,b as getLatestProtocolIdentifier,Le as getWarpActionByIndex,zr as hex,Nr as list,Jr as nothing,Fr as option,Er as optional,x as shiftBigintBy,Or as string,Y as toPreviewText,S as toTypedRegistryInfo,Mr as token,qr as u16,Dr as u32,_r as u64,Lr as u8,kr as variadic};
|
|
1
|
+
import{Address as at,TransactionsFactoryConfig as Zt,TransferTransactionsFactory as Xt}from"@multiversx/sdk-core";import Yt from"ajv";var C={Warp:"0.5.0",Brand:"0.1.0",Abi:"0.1.0"},h={LatestWarpSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/v${C.Warp}.schema.json`,LatestBrandSchemaUrl:`https://raw.githubusercontent.com/vLeapGroup/warps-specs/refs/heads/main/schemas/brand/v${C.Brand}.schema.json`,DefaultClientUrl:s=>s==="devnet"?"https://devnet.usewarp.to":s==="testnet"?"https://testnet.usewarp.to":"https://usewarp.to",SuperClientUrls:["https://usewarp.to","https://testnet.usewarp.to","https://devnet.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 T=s=>s==="devnet"?"D":s==="testnet"?"T":"1",b=s=>{if(s==="warp")return`warp:${C.Warp}`;if(s==="brand")return`brand:${C.Brand}`;if(s==="abi")return`abi:${C.Abi}`;throw new Error(`getLatestProtocolIdentifier: Invalid protocol name: ${s}`)},Le=(s,t)=>s?.actions[t-1],S=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}),x=(s,t)=>{let e=s.toString(),[r,i=""]=e.split("."),n=Math.abs(t);if(t>0)return BigInt(r+i.padEnd(n,"0"));if(t<0){let a=r+i;if(n>=a.length)return 0n;let o=a.slice(0,-n)||"0";return BigInt(o)}else return BigInt(s)},Y=(s,t=100)=>{if(!s)return"";let e=s.replace(/<\/?(h[1-6])[^>]*>/gi," - ").replace(/<\/?(p|div|ul|ol|li|br|hr)[^>]*>/gi," ").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();return e=e.startsWith("- ")?e.slice(2):e,e=e.length>t?e.substring(0,e.lastIndexOf(" ",t))+"...":e,e};import{ApiNetworkProvider as Kt}from"@multiversx/sdk-core/out";var u={HttpProtocolPrefix:"http",IdentifierParamName:"warp",IdentifierParamSeparator:":",IdentifierType:{Alias:"alias",Hash:"hash"},ArgParamsSeparator:":",ArgCompositeSeparator:"|",Egld:{Identifier:"EGLD",DisplayName:"eGold",Decimals:18}};import Gt from"qr-code-styling";import{Address as tt,TransactionsFactoryConfig as Dt,TransferTransactionsFactory as _t}from"@multiversx/sdk-core";var A={Warp:s=>`warp:${s}`,WarpAbi:s=>`warp-abi:${s}`,RegistryInfo:s=>`registry-info:${s}`,Brand:s=>`brand:${s}`},W=class{constructor(){this.cache=new Map}set(t,e,r){let i=Date.now()+r*1e3;this.cache.set(t,{value:e,expiresAt:i})}get(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.value:null}clear(){this.cache.clear()}};import qt from"ajv";var I=class{constructor(t){this.config=t;this.config=t}async validate(t){this.ensureMaxOneValuePosition(t),await this.ensureValidSchema(t)}ensureMaxOneValuePosition(t){if(t.actions.filter(r=>"position"in r?r.position==="value":!1).length>1)throw new Error("WarpBuilder: only one value position action is allowed")}async ensureValidSchema(t){let e=this.config.warpSchemaUrl||h.LatestWarpSchemaUrl,i=await(await fetch(e)).json(),n=new qt,a=n.compile(i);if(!a(t))throw new Error(`WarpBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};var V=class{constructor(t){this.cache=new W;this.pendingWarp={protocol:b("warp"),name:"",title:"",description:null,preview:"",actions:[]};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new Dt({chainID:T(this.config.env)}),r=new _t({config:e}),i=JSON.stringify(t),n=r.createTransactionForTransfer({sender:tt.newFromBech32(this.config.userAddress),receiver:tt.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()});return n.gasLimit=n.gasLimit+BigInt(2e6),n}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await new I(this.config).validate(r),g.prepareVars(r,this.config)}async createFromTransaction(t,e=!1){let r=await this.createFromRaw(t.data.toString(),e);return r.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},r}async createFromTransactionHash(t,e){let r=A.Warp(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpBuilder (createFromTransactionHash): Warp found in cache: ${t}`),n}let i=g.getConfiguredChainApi(this.config);try{let n=await i.getTransaction(t),a=await this.createFromTransaction(n);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}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 new I(this.config).validate(this.pendingWarp),this.pendingWarp}getDescriptionPreview(t,e=100){return Y(t,e)}ensure(t,e){if(!t)throw new Error(`WarpBuilder: ${e}`)}};import{AbiRegistry as et,Address as f,AddressValue as rt,BytesValue as y,QueryRunnerAdapter as Qt,SmartContractQueriesController as jt,SmartContractTransactionsFactory as Mt,TransactionsFactoryConfig as zt}from"@multiversx/sdk-core/out";var $={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 P=class{constructor(t){this.cache=new W;this.config=t,this.unitPrice=BigInt(0)}async init(){await this.loadRegistryConfigs()}createWarpRegisterTransaction(t,e){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 r=e?this.unitPrice*BigInt(2):this.unitPrice;return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"registerWarp",gasLimit:BigInt(1e7),nativeTransferAmount:r,arguments:e?[y.fromHex(t),y.fromUTF8(e)]:[y.fromHex(t)]})}createWarpUnregisterTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"unregisterWarp",gasLimit:BigInt(1e7),arguments:[y.fromHex(t)]})}createWarpUpgradeTransaction(t,e){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:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"upgradeWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromUTF8(t),y.fromHex(e)]})}createWarpAliasSetTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"setWarpAlias",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromUTF8(e)]})}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:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"registerBrand",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t)]})}createWarpPublishTransaction(t){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"publishWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t)]})}createWarpBrandingTransaction(t,e){if(!this.config.userAddress)throw new Error("WarpRegistry: user address not set");return this.getFactory().createTransactionForExecute({sender:f.newFromBech32(this.config.userAddress),contract:f.newFromBech32(this.getRegistryContractAddress()),function:"brandWarp",gasLimit:BigInt(1e7),nativeTransferAmount:this.unitPrice,arguments:[y.fromHex(t),y.fromHex(e)]})}async getInfoByAlias(t,e){let r=A.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByAlias): RegistryInfo found in cache: ${t}`),d}let i=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByAlias",arguments:[y.fromUTF8(t)]}),o=await n.runQuery(a),[c]=n.parseQueryResponse(o),p=c?S(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}async getInfoByHash(t,e){let r=A.RegistryInfo(t);if(e){let d=this.cache.get(r);if(d)return console.log(`WarpRegistry (getInfoByHash): RegistryInfo found in cache: ${t}`),d}let i=this.getRegistryContractAddress(),n=this.getController(),a=n.createQuery({contract:i,function:"getInfoByHash",arguments:[y.fromHex(t)]}),o=await n.runQuery(a),[c]=n.parseQueryResponse(o),p=c?S(c):null,l=p?.brand?await this.fetchBrand(p.brand):null;return e&&e.ttl&&this.cache.set(r,{registryInfo:p,brand:l},e.ttl),{registryInfo:p,brand:l}}async getUserWarpRegistryInfos(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),i=this.getController(),n=i.createQuery({contract:r,function:"getUserWarps",arguments:[new rt(new f(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a);return o.map(S)}async getUserBrands(t){let e=t||this.config.userAddress;if(!e)throw new Error("WarpRegistry: user address not set");let r=this.getRegistryContractAddress(),i=this.getController(),n=i.createQuery({contract:r,function:"getUserBrands",arguments:[new rt(new f(e))]}),a=await i.runQuery(n),[o]=i.parseQueryResponse(a),c=o.map(d=>d.toString("hex")),p={ttl:365*24*60*60};return(await Promise.all(c.map(d=>this.fetchBrand(d,p)))).filter(d=>d!==null)}async fetchBrand(t,e){let r=A.Brand(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpRegistry (fetchBrand): Brand found in cache: ${t}`),n}let i=g.getConfiguredChainApi(this.config);try{let n=await i.getTransaction(t),a=JSON.parse(n.data.toString());return a.meta={hash:n.hash,creator:n.sender.bech32(),createdAt:new Date(n.timestamp*1e3).toISOString()},e&&e.ttl&&this.cache.set(r,a,e.ttl),a}catch(n){return console.error("WarpRegistry: Error fetching brand from transaction hash",n),null}}getRegistryContractAddress(){return this.config.registryContract||h.Registry.Contract(this.config.env)}async loadRegistryConfigs(){let t=this.getRegistryContractAddress(),e=this.getController(),r=e.createQuery({contract:t,function:"getConfig",arguments:[]}),i=await e.runQuery(r),[n]=e.parseQueryResponse(i),a=BigInt(n.toString());this.unitPrice=a}getFactory(){let t=new zt({chainID:T(this.config.env)}),e=et.create($);return new Mt({config:t,abi:e})}getController(){let t=g.getConfiguredChainApi(this.config),e=new Qt({networkProvider:t}),r=et.create($);return new jt({queryRunner:e,abi:r})}};var R=class{constructor(t){this.config=t;this.config=t}isValid(t){return t.startsWith(u.HttpProtocolPrefix)?!!this.extractIdentifierInfoFromUrl(t):!1}async detectFromHtml(t){if(!t.length)return{match:!1,results:[]};let i=[...t.matchAll(/https?:\/\/[^\s"'<>]+/gi)].map(p=>p[0]).filter(p=>this.isValid(p)).map(p=>this.detect(p)),a=(await Promise.all(i)).filter(p=>p.match),o=a.length>0,c=a.map(p=>({url:p.url,warp:p.warp}));return{match:o,results:c}}async detect(t){let e=t.startsWith(u.HttpProtocolPrefix)?this.extractIdentifierInfoFromUrl(t):g.getInfoFromPrefixedIdentifier(t);if(!e)return{match:!1,url:t,warp:null,registryInfo:null,brand:null};let{type:r,id:i}=e,n=new V(this.config),a=new P(this.config),o=null,c=null,p=null;if(r==="hash"){o=await n.createFromTransactionHash(i);try{let{registryInfo:l,brand:d}=await a.getInfoByHash(i);c=l,p=d}catch{}}else if(r==="alias"){let{registryInfo:l,brand:d}=await a.getInfoByAlias(i);c=l,p=d,l&&(o=await n.createFromTransactionHash(l.hash))}return o?{match:!0,url:t,warp:o,registryInfo:c,brand:p}:{match:!1,url:t,warp:null,registryInfo:null,brand:null}}build(t,e){let r=this.config.clientUrl||h.DefaultClientUrl(this.config.env),i=t===u.IdentifierType.Alias?encodeURIComponent(e):encodeURIComponent(t+u.IdentifierParamSeparator+e);return h.SuperClientUrls.includes(r)?`${r}/${i}`:`${r}?${u.IdentifierParamName}=${i}`}generateQrCode(t,e,r=512,i="white",n="black",a="#23F7DD"){let o=this.build(t,e);return new Gt({type:"svg",width:r,height:r,data:String(o),margin:16,qrOptions:{typeNumber:0,mode:"Byte",errorCorrectionLevel:"Q"},backgroundOptions:{color:i},dotsOptions:{type:"extra-rounded",color:n},cornersSquareOptions:{type:"extra-rounded",color:n},cornersDotOptions:{type:"square",color:n},imageOptions:{hideBackgroundDots:!0,imageSize:.4,margin:8},image:`data:image/svg+xml;utf8,<svg width="16" height="16" viewBox="0 0 100 100" fill="${encodeURIComponent(a)}" xmlns="http://www.w3.org/2000/svg"><path d="M54.8383 50.0242L95 28.8232L88.2456 16L51.4717 30.6974C50.5241 31.0764 49.4759 31.0764 48.5283 30.6974L11.7544 16L5 28.8232L45.1616 50.0242L5 71.2255L11.7544 84.0488L48.5283 69.351C49.4759 68.9724 50.5241 68.9724 51.4717 69.351L88.2456 84.0488L95 71.2255L54.8383 50.0242Z"/></svg>`})}extractIdentifierInfoFromUrl(t){let e=new URL(t),r=h.SuperClientUrls.includes(e.origin),i=e.searchParams.get(u.IdentifierParamName),n=r&&!i?e.pathname.split("/")[1]:i;if(!n)return null;let a=decodeURIComponent(n);return g.getInfoFromPrefixedIdentifier(a)}};var Jt="https://",nt="query",it="env",g=class s{static prepareVars(t,e){if(!t?.vars)return t;let r=JSON.stringify(t),i=(n,a)=>{r=r.replace(new RegExp(`{{${n.toUpperCase()}}}`,"g"),a.toString())};return Object.entries(t.vars).forEach(([n,a])=>{if(typeof a=="string"&&a.startsWith(`${nt}:`)){if(!e.currentUrl)throw new Error("WarpUtils: currentUrl config is required to prepare vars");let o=a.split(`${nt}:`)[1],c=new URL(e.currentUrl).searchParams.get(o);c&&i(n,c)}else if(typeof a=="string"&&a.startsWith(`${it}:`)){let o=a.split(`${it}:`)[1],c=e.vars?.[o];c&&i(n,c)}else i(n,a)}),JSON.parse(r)}static getInfoFromPrefixedIdentifier(t){let e=decodeURIComponent(t),r=e.includes(u.IdentifierParamSeparator)?e:`${u.IdentifierType.Alias}${u.IdentifierParamSeparator}${e}`,[i,n]=r.split(u.IdentifierParamSeparator);return{type:i,id:n}}static getNextStepUrl(t,e){if(!t?.next)return null;if(t.next.startsWith(Jt))return t.next;{let r=new R(e),i=s.getInfoFromPrefixedIdentifier(t.next);return i?r.build(i.type,i.id):null}}static getConfiguredChainApi(t){let e=t.chainApiUrl||h.Chain.ApiUrl(t.env);if(!e)throw new Error("WarpUtils: Chain API URL not configured");return new Kt(e,{timeout:3e4,clientName:"warp-sdk"})}};var st=class{constructor(t){this.pendingBrand={protocol:b("brand"),name:"",description:"",logo:""};this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("BrandBuilder: user address not set");let e=new Zt({chainID:T(this.config.env)}),r=new Xt({config:e}),i=JSON.stringify(t);return r.createTransactionForNativeTokenTransfer({sender:at.newFromBech32(this.config.userAddress),receiver:at.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(i).valueOf()})}async createFromRaw(t,e=!0){let r=JSON.parse(t);return e&&await this.ensureValidSchema(r),r}async createFromTransaction(t,e=!1){return await this.createFromRaw(t.data.toString(),e)}async createFromTransactionHash(t){let e=g.getConfiguredChainApi(this.config);try{let r=await e.getTransaction(t);return this.createFromTransaction(r)}catch(r){return console.error("BrandBuilder: Error creating from transaction hash",r),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,e){if(!t)throw new Error(`Warp: ${e}`)}async ensureValidSchema(t){let e=this.config.brandSchemaUrl||h.LatestBrandSchemaUrl,i=await(await fetch(e)).json(),n=new Yt,a=n.compile(i);if(!a(t))throw new Error(`BrandBuilder: schema validation failed: ${n.errorsText(a.errors)}`)}};import{Address as te,AddressValue as ee,BigUIntType as re,BigUIntValue as ot,BooleanValue as ne,BytesValue as ie,CodeMetadata as ae,CodeMetadataValue as se,CompositeType as oe,CompositeValue as ce,Field as O,FieldDefinition as L,List as pe,NothingValue as ue,OptionalValue as q,OptionValue as D,StringValue as le,Struct as de,StructType as ge,TokenIdentifierType as fe,TokenIdentifierValue as ct,U16Value as me,U32Value as he,U64Type as ye,U64Value as pt,U8Value as we,VariadicValue as Te}from"@multiversx/sdk-core/out";var Fr=(s,t)=>s?D.newProvided(s):t?D.newMissingTyped(t):D.newMissing(),Er=(s,t)=>s?new q(s.getType(),s):t?new q(t):q.newMissing(),Nr=s=>{if(s.length===0)throw new Error("Cannot create a list from an empty array");let t=s[0].getType();return new pe(t,s)},kr=s=>Te.fromItems(...s),$r=s=>{let t=s.map(e=>e.getType());return new ce(new oe(...t),s)},Or=s=>le.fromUTF8(s),Lr=s=>new we(s),qr=s=>new me(s),Dr=s=>new he(s),_r=s=>new pt(s),Hr=s=>new ot(BigInt(s)),Qr=s=>new ne(s),jr=s=>new ee(te.newFromBech32(s)),Mr=s=>new ct(s),zr=s=>ie.fromHex(s),Gr=s=>new de(new ge("EsdtTokenPayment",[new L("token_identifier","",new fe),new L("token_nonce","",new ye),new L("amount","",new re)]),[new O(new ct(s.token.identifier),"token_identifier"),new O(new pt(BigInt(s.token.nonce)),"token_nonce"),new O(new ot(BigInt(s.amount)),"amount")]),Kr=s=>new se(ae.fromBuffer(Buffer.from(s,"hex"))),Jr=()=>new ue;import{Address as ut,TransactionsFactoryConfig as We,TransferTransactionsFactory as Ae}from"@multiversx/sdk-core";var U=class{constructor(t){this.cache=new W;this.config=t}createInscriptionTransaction(t){if(!this.config.userAddress)throw new Error("WarpBuilder: user address not set");let e=new We({chainID:T(this.config.env)}),r=new Ae({config:e}),i={protocol:b("abi"),content:t},n=JSON.stringify(i),a=r.createTransactionForTransfer({sender:ut.newFromBech32(this.config.userAddress),receiver:ut.newFromBech32(this.config.userAddress),nativeAmount:BigInt(0),data:Buffer.from(n).valueOf()});return a.gasLimit=a.gasLimit+BigInt(2e6),a}async createFromRaw(t){return JSON.parse(t)}async createFromTransaction(t){let e=await this.createFromRaw(t.data.toString());return e.meta={hash:t.hash,creator:t.sender.bech32(),createdAt:new Date(t.timestamp*1e3).toISOString()},e}async createFromTransactionHash(t,e){let r=A.WarpAbi(t);if(e){let n=this.cache.get(r);if(n)return console.log(`WarpAbiBuilder (createFromTransactionHash): Warp abi found in cache: ${t}`),n}let i=g.getConfiguredChainApi(this.config);try{let n=await i.getTransaction(t),a=await this.createFromTransaction(n);return e&&e.ttl&&a&&this.cache.set(r,a,e.ttl),a}catch(n){return console.error("WarpAbiBuilder: Error creating from transaction hash",n),null}}};import{AbiRegistry as X,Address as Nt,QueryRunnerAdapter as xe,ResultsParser as Ve,SmartContractQueriesController as Pe,SmartContractTransactionsFactory as Re,StringValue as Ue,Token as Fe,TokenComputer as Ee,TokenTransfer as kt,TransactionsFactoryConfig as Ne,TransferTransactionsFactory as ke}from"@multiversx/sdk-core/out";var Ce=[{id:"EGLD",name:"eGold",decimals:18},{id:"EGLD-000000",name:"eGold",decimals:18}],lt=s=>Ce.find(t=>t.id===s)||null;import{Address as be,AddressType as dt,AddressValue as gt,BigUIntType as _,BigUIntValue as H,BooleanType as ft,BooleanValue as mt,BytesType as ht,BytesValue as yt,CodeMetadata as Ie,CodeMetadataType as wt,CodeMetadataValue as Tt,CompositeType as Wt,CompositeValue as At,Field as Q,FieldDefinition as j,List as Ct,NothingValue as w,OptionalValue as M,OptionValue as z,StringType as bt,StringValue as It,Struct as Be,StructType as Bt,Token as ve,TokenIdentifierType as G,TokenIdentifierValue as K,TokenTransfer as vt,U16Type as St,U16Value as xt,U32Type as Vt,U32Value as Pt,U64Type as J,U64Value as Z,U8Type as Rt,U8Value as Ut,VariadicType as Se,VariadicValue as Ft}from"@multiversx/sdk-core/out";var Et=new RegExp(`${u.ArgParamsSeparator}(.*)`),F=class{nativeToString(t,e){return t==="esdt"&&e instanceof vt?`esdt:${e.token.identifier}|${e.token.nonce.toString()}|${e.amount.toString()}`:`${t}:${e?.toString()??""}`}typedToString(t){if(t.hasClassOrSuperclass(z.ClassName))return t.isSet()?`option:${this.typedToString(t.getTypedValue())}`:"option:null";if(t.hasClassOrSuperclass(M.ClassName))return t.isSet()?`optional:${this.typedToString(t.getTypedValue())}`:"optional:null";if(t.hasClassOrSuperclass(Ct.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[0])[0],n=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[1]);return`list:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(Ft.ClassName)){let e=t.getItems(),i=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[0])[0],n=e.map(a=>this.typedToString(a).split(u.ArgParamsSeparator)[1]);return`variadic:${i}:${n.join(",")}`}if(t.hasClassOrSuperclass(At.ClassName)){let e=t.getItems(),r=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[0]),i=e.map(o=>this.typedToString(o).split(u.ArgParamsSeparator)[1]),n=r.join(u.ArgCompositeSeparator),a=i.join(u.ArgCompositeSeparator);return`composite(${n}):${a}`}if(t.hasClassOrSuperclass(H.ClassName)||t.getType().getName()==="BigUint")return`biguint:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(Ut.ClassName))return`uint8:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(xt.ClassName))return`uint16:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Pt.ClassName))return`uint32:${t.valueOf().toNumber()}`;if(t.hasClassOrSuperclass(Z.ClassName))return`uint64:${BigInt(t.valueOf().toFixed())}`;if(t.hasClassOrSuperclass(It.ClassName))return`string:${t.valueOf()}`;if(t.hasClassOrSuperclass(mt.ClassName))return`bool:${t.valueOf()}`;if(t.hasClassOrSuperclass(gt.ClassName))return`address:${t.valueOf().bech32()}`;if(t.hasClassOrSuperclass(K.ClassName))return`token:${t.valueOf()}`;if(t.hasClassOrSuperclass(yt.ClassName))return`hex:${t.valueOf().toString("hex")}`;if(t.hasClassOrSuperclass(Tt.ClassName))return`codemeta:${t.valueOf().toBuffer().toString("hex")}`;if(t.getType().getName()==="EsdtTokenPayment"){let e=t.getFieldValue("token_identifier").valueOf(),r=t.getFieldValue("token_nonce").valueOf(),i=t.getFieldValue("amount").valueOf();return`esdt:${e}|${r}|${i}`}throw new Error(`WarpArgSerializer (typedToString): Unsupported input type: ${t.getClassName()}`)}typedToNative(t){let e=this.typedToString(t);return this.stringToNative(e)}nativeToTyped(t,e){let r=this.nativeToString(t,e);return this.stringToTyped(r)}nativeToType(t){if(t.startsWith("composite")){let e=t.match(/\(([^)]+)\)/)?.[1];return new Wt(...e.split(u.ArgCompositeSeparator).map(r=>this.nativeToType(r)))}if(t==="string")return new bt;if(t==="uint8")return new Rt;if(t==="uint16")return new St;if(t==="uint32")return new Vt;if(t==="uint64")return new J;if(t==="biguint")return new _;if(t==="bool")return new ft;if(t==="address")return new dt;if(t==="token")return new G;if(t==="hex")return new ht;if(t==="codemeta")return new wt;if(t==="esdt"||t==="nft")return new Bt("EsdtTokenPayment",[new j("token_identifier","",new G),new j("token_nonce","",new J),new j("amount","",new _)]);throw new Error(`WarpArgSerializer (nativeToType): Unsupported input type: ${t}`)}stringToNative(t){let e=t.split(u.ArgParamsSeparator),r=e[0],i=e.slice(1).join(u.ArgParamsSeparator);if(r==="null")return[r,null];if(r==="option"){let[n,a]=i.split(u.ArgParamsSeparator);return[`option:${n}`,a||null]}else if(r==="optional"){let[n,a]=i.split(u.ArgParamsSeparator);return[`optional:${n}`,a||null]}else if(r==="list"){let n=i.split(u.ArgParamsSeparator),a=n.slice(0,-1).join(u.ArgParamsSeparator),o=n[n.length-1],p=(o?o.split(","):[]).map(l=>this.stringToNative(`${a}:${l}`)[1]);return[`list:${a}`,p]}else if(r==="variadic"){let n=i.split(u.ArgParamsSeparator),a=n.slice(0,-1).join(u.ArgParamsSeparator),o=n[n.length-1],p=(o?o.split(","):[]).map(l=>this.stringToNative(`${a}:${l}`)[1]);return[`variadic:${a}`,p]}else if(r.startsWith("composite")){let n=r.match(/\(([^)]+)\)/)?.[1]?.split(u.ArgCompositeSeparator),o=i.split(u.ArgCompositeSeparator).map((c,p)=>this.stringToNative(`${n[p]}:${c}`)[1]);return[r,o]}else{if(r==="string")return[r,i];if(r==="uint8"||r==="uint16"||r==="uint32")return[r,Number(i)];if(r==="uint64"||r==="biguint")return[r,BigInt(i||0)];if(r==="bool")return[r,i==="true"];if(r==="address")return[r,i];if(r==="token")return[r,i];if(r==="hex")return[r,i];if(r==="codemeta")return[r,i];if(r==="esdt"){let[n,a,o]=i.split(u.ArgCompositeSeparator);return[r,new vt({token:new ve({identifier:n,nonce:BigInt(a)}),amount:BigInt(o)})]}}throw new Error(`WarpArgSerializer (stringToNative): Unsupported input type: ${r}`)}stringToTyped(t){let[e,r]=t.split(/:(.*)/,2);if(e==="null"||e===null)return new w;if(e==="option"){let i=this.stringToTyped(r);return i instanceof w?z.newMissingTyped(i.getType()):z.newProvided(i)}if(e==="optional"){let i=this.stringToTyped(r);return i instanceof w?M.newMissing():new M(i.getType(),i)}if(e==="list"){let[i,n]=r.split(Et,2),o=n.split(",").map(c=>this.stringToTyped(`${i}:${c}`));return new Ct(this.nativeToType(i),o)}if(e==="variadic"){let[i,n]=r.split(Et,2),o=n.split(",").map(c=>this.stringToTyped(`${i}:${c}`));return new Ft(new Se(this.nativeToType(i)),o)}if(e.startsWith("composite")){let i=e.match(/\(([^)]+)\)/)?.[1],n=r.split(u.ArgCompositeSeparator),a=i.split(u.ArgCompositeSeparator),o=n.map((p,l)=>this.stringToTyped(`${a[l]}:${p}`)),c=o.map(p=>p.getType());return new At(new Wt(...c),o)}if(e==="string")return r?It.fromUTF8(r):new w;if(e==="uint8")return r?new Ut(Number(r)):new w;if(e==="uint16")return r?new xt(Number(r)):new w;if(e==="uint32")return r?new Pt(Number(r)):new w;if(e==="uint64")return r?new Z(BigInt(r)):new w;if(e==="biguint")return r?new H(BigInt(r)):new w;if(e==="bool")return r?new mt(typeof r=="boolean"?r:r==="true"):new w;if(e==="address")return r?new gt(be.newFromBech32(r)):new w;if(e==="token")return r?new K(r):new w;if(e==="hex")return r?yt.fromHex(r):new w;if(e==="codemeta")return new Tt(Ie.fromBuffer(Buffer.from(r,"hex")));if(e==="esdt"){let i=r.split(u.ArgCompositeSeparator);return new Be(this.nativeToType("esdt"),[new Q(new K(i[0]),"token_identifier"),new Q(new Z(BigInt(i[1])),"token_nonce"),new Q(new H(BigInt(i[2])),"amount")])}throw new Error(`WarpArgSerializer (stringToTyped): Unsupported input type: ${e}`)}typeToNative(t){if(t instanceof bt)return"string";if(t instanceof Rt)return"uint8";if(t instanceof St)return"uint16";if(t instanceof Vt)return"uint32";if(t instanceof J)return"uint64";if(t instanceof _)return"biguint";if(t instanceof ft)return"bool";if(t instanceof dt)return"address";if(t instanceof G)return"token";if(t instanceof ht)return"hex";if(t instanceof wt)return"codemeta";if(t instanceof Bt&&t.getClassName()==="EsdtTokenPayment")return"esdt";throw new Error(`WarpArgSerializer (typeToNative): Unsupported input type: ${t.getClassName()}`)}};var E=class{constructor(t){this.config=t}async getContract(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{address:t,owner:r.ownerAddress,verified:r.isVerified}}catch(e){return console.error("WarpContractLoader: getContract error",e),null}}async getVerificationInfo(t){try{let r=await g.getConfiguredChainApi(this.config).doGetGeneric(`accounts/${t}/verification`);return{codeHash:r.codeHash,abi:r.source.abi}}catch(e){return console.error("WarpContractLoader: getVerificationInfo error",e),null}}};var $t=class{constructor(t){if(!t.currentUrl)throw new Error("WarpActionExecutor: currentUrl config not set");this.config=t,this.url=new URL(t.currentUrl),this.serializer=new F,this.contractLoader=new E(t)}async createTransactionForExecute(t,e){if(!this.config.userAddress)throw new Error("WarpActionExecutor: user address not set");let r=Nt.newFromBech32(this.config.userAddress),i=new Ne({chainID:T(this.config.env)}),{destination:n,args:a,value:o,transfers:c}=await this.getTxComponentsFromInputs(t,e,r),p=a.map(l=>this.serializer.stringToTyped(l));return n.isContractAddress()?new Re({config:i}).createTransactionForExecute({sender:r,contract:n,function:"func"in t&&t.func||"",gasLimit:"gasLimit"in t?BigInt(t.gasLimit||0):0n,arguments:p,tokenTransfers:c,nativeTransferAmount:o}):new ke({config:i}).createTransactionForTransfer({sender:r,receiver:n,nativeAmount:o,tokenTransfers:c,data:p[0]?.hasExactClass(Ue.ClassName)?p[0].valueOf():void 0})}async executeQuery(t,e){if(!this.config.chainApiUrl)throw new Error("WarpActionExecutor: Chain API URL not set");if(!t.func)throw new Error("WarpActionExecutor: Function not found");let r=g.getConfiguredChainApi(this.config),i=new xe({networkProvider:r}),n=await this.getAbiForAction(t),{args:a}=await this.getTxComponentsFromInputs(t,e),o=a.map(m=>this.serializer.stringToTyped(m)),c=new Pe({queryRunner:i,abi:n}),p=c.createQuery({contract:t.address,function:t.func,arguments:o}),l=await c.runQuery(p),d=new Ve,B={returnCode:l.returnCode,returnMessage:l.returnMessage,getReturnDataParts:()=>l.returnDataParts.map(m=>Buffer.from(m))},N=l.function,k=n.getEndpoint(N),v=d.parseQueryResponse(B,k).firstValue;if(!v)throw new Error("WarpActionExecutor: Query result not found");return v}async executeCollect(t,e,r){let i=new Headers;i.set("Content-Type","application/json"),i.set("Accept","application/json"),Object.entries(t.destination.headers).forEach(([n,a])=>{i.set(n,a)}),await fetch(t.destination.url,{method:t.destination.method,headers:i,body:JSON.stringify({inputs:e,meta:r})})}async getTxComponentsFromInputs(t,e,r){let i=await this.getResolvedInputs(t,e),n=this.getModifiedInputs(i),a=n.find(m=>m.input.position==="receiver")?.value,o="address"in t?t.address:null,c=a?.split(":")[1]||o||r?.toBech32();if(!c)throw new Error("WarpActionExecutor: Destination/Receiver not provided");let p=Nt.newFromBech32(c),l=this.getPreparedArgs(t,n),d=n.find(m=>m.input.position==="value")?.value||null,B="value"in t?t.value:null,N=BigInt(d?.split(":")[1]||B||0),k=n.filter(m=>m.input.position==="transfer"&&m.value).map(m=>m.value),v=[...("transfers"in t?t.transfers:[])?.map(this.toTypedTransfer)||[],...k?.map(m=>this.serializer.stringToNative(m)[1])||[]];return{destination:p,args:l,value:N,transfers:v}}getModifiedInputs(t){return t.map((e,r)=>{if(e.input.modifier?.startsWith("scale:")){let[,i]=e.input.modifier.split(":");if(isNaN(Number(i))){let n=Number(t.find(c=>c.input.name===i)?.value?.split(":")[1]);if(!n)throw new Error(`WarpActionExecutor: Exponent value not found for input ${i}`);let a=e.value?.split(":")[1];if(!a)throw new Error("WarpActionExecutor: Scalable value not found");let o=x(a,+n);return{...e,value:`${e.input.type}:${o}`}}else{let n=e.value?.split(":")[1];if(!n)throw new Error("WarpActionExecutor: Scalable value not found");let a=x(n,+i);return{...e,value:`${e.input.type}:${a}`}}}else return e})}async getResolvedInputs(t,e){let r=t.inputs||[],i=await Promise.all(e.map(a=>this.preprocessInput(a))),n=(a,o)=>a.source==="query"?this.serializer.nativeToString(a.type,this.url.searchParams.get(a.name)||""):i[o]||null;return r.map((a,o)=>({input:a,value:n(a,o)}))}async preprocessInput(t){try{let[e,r]=this.serializer.stringToNative(t);if(e==="esdt"){let[,,,i]=t.split(u.ArgCompositeSeparator);if(i)return t;let n=r;if(!new Ee().isFungible(n.token))return t;let c=lt(n.token.identifier)?.decimals;if(!c){let l=this.config.chainApiUrl||h.Chain.ApiUrl(this.config.env);c=(await(await fetch(`${l}/tokens/${n.token.identifier}`)).json()).decimals}if(!c)throw new Error(`WarpActionExecutor: Decimals not found for token ${n.token.identifier}`);let p=new kt({token:n.token,amount:x(n.amount,c)});return this.serializer.nativeToString(e,p)+u.ArgCompositeSeparator+c}return t}catch{return t}}getPreparedArgs(t,e){let r="args"in t?t.args||[]:[];return e.forEach(({input:i,value:n})=>{if(!n||!i.position.startsWith("arg:"))return;let a=Number(i.position.split(":")[1])-1;r.splice(a,0,n)}),r}async getAbiForAction(t){if(t.abi)return await this.fetchAbi(t);let e=await this.contractLoader.getVerificationInfo(t.address);if(!e)throw new Error("WarpActionExecutor: Verification info not found");return X.create(e.abi)}async fetchAbi(t){if(!t.abi)throw new Error("WarpActionExecutor: ABI not found");if(t.abi.startsWith(u.IdentifierType.Hash)){let e=new U(this.config),r=t.abi.split(u.IdentifierParamSeparator)[1],i=await e.createFromTransactionHash(r);if(!i)throw new Error(`WarpActionExecutor: ABI not found for hash: ${t.abi}`);return X.create(i.content)}else{let r=await(await fetch(t.abi)).json();return X.create(r)}}toTypedTransfer(t){return new kt({token:new Fe({identifier:t.token,nonce:BigInt(t.nonce||0)}),amount:BigInt(t.amount||0)})}};var Ot=class{constructor(t){this.config=t}async search(t){if(!this.config.indexUrl)throw new Error("WarpIndex: Index URL is not set");try{let e=await fetch(this.config.indexUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.indexApiKey}`},body:JSON.stringify({[this.config.indexSearchParamName||"search"]:t})});if(!e.ok)throw new Error(`WarpIndex: search failed with status ${e.status}`);return(await e.json()).hits}catch(e){throw console.error("WarpIndex: Error searching for warps: ",e),e}}};export{st as BrandBuilder,h as Config,U as WarpAbiBuilder,$t as WarpActionExecutor,F as WarpArgSerializer,V as WarpBuilder,u as WarpConstants,E as WarpContractLoader,Ot as WarpIndex,R as WarpLink,C as WarpProtocolVersions,P as WarpRegistry,g as WarpUtils,jr as address,Hr as biguint,Qr as boolean,Kr as codemeta,$r as composite,Gr as esdt,T as getChainId,b as getLatestProtocolIdentifier,Le as getWarpActionByIndex,zr as hex,Nr as list,Jr as nothing,Fr as option,Er as optional,x as shiftBigintBy,Or as string,Y as toPreviewText,S as toTypedRegistryInfo,Mr as token,qr as u16,Dr as u32,_r as u64,Lr as u8,kr as variadic};
|