@oceanprotocol/lib 8.0.5 → 8.0.6
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/lib.cjs +2 -2
- package/dist/lib.module.mjs +2 -2
- package/dist/lib.umd.js +2 -2
- package/dist/types/services/providers/BaseProvider.d.ts +2 -2
- package/dist/types/services/providers/HttpProvider.d.ts +2 -2
- package/dist/types/services/providers/P2pProvider.d.ts +2 -2
- package/package.json +1 -1
package/dist/lib.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var e=require("fs"),t=require("ethers"),n=require("@oasisprotocol/sapphire-paratime"),r=require("bignumber.js"),i=require("decimal.js"),s=require("cross-fetch"),a=require("@oceanprotocol/ddo-js"),o=require("jsonwebtoken"),u=require("eciesjs"),d=require("crypto-js/sha256.js");function c(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function l(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,t}var p,h,f=/*#__PURE__*/c(e),m=/*#__PURE__*/l(n),y=/*#__PURE__*/c(r),b=/*#__PURE__*/c(i),g=/*#__PURE__*/c(s),v=/*#__PURE__*/c(o),w=/*#__PURE__*/c(d);exports.FileObjectType=void 0,(p=exports.FileObjectType||(exports.FileObjectType={})).URL="url",p.IPFS="ipfs",p.ARWEAVE="arweave",p.S3="s3",p.FTP="ftp",exports.EncryptMethod=void 0,(h=exports.EncryptMethod||(exports.EncryptMethod={})).AES="AES",h.ECIES="ECIES";var T={DOWNLOAD:"download",ENCRYPT:"encrypt",ENCRYPT_FILE:"encryptFile",DECRYPT_DDO:"decryptDDO",GET_DDO:"getDDO",QUERY:"query",NONCE:"nonce",STATUS:"status",DETAILED_STATUS:"detailedStatus",FIND_DDO:"findDDO",GET_FEES:"getFees",FILE_INFO:"fileInfo",VALIDATE_DDO:"validateDDO",COMPUTE_GET_ENVIRONMENTS:"getComputeEnvironments",COMPUTE_START:"startCompute",FREE_COMPUTE_START:"freeStartCompute",COMPUTE_STOP:"stopCompute",COMPUTE_GET_STATUS:"getComputeStatus",COMPUTE_GET_STREAMABLE_LOGS:"getComputeStreamableLogs",COMPUTE_GET_RESULT:"getComputeResult",COMPUTE_INITIALIZE:"initializeCompute",STOP_NODE:"stopNode",REINDEX_TX:"reindexTx",REINDEX_CHAIN:"reindexChain",HANDLE_INDEXING_THREAD:"handleIndexingThread",COLLECT_FEES:"collectFees",POLICY_SERVER_PASSTHROUGH:"PolicyServerPassthrough",GET_P2P_PEER:"getP2PPeer",GET_P2P_PEERS:"getP2PPeers",GET_P2P_NETWORK_STATS:"getP2PNetworkStats",FIND_PEER:"findPeer",CREATE_AUTH_TOKEN:"createAuthToken",INVALIDATE_AUTH_TOKEN:"invalidateAuthToken",FETCH_CONFIG:"fetchConfig",PUSH_CONFIG:"pushConfig",GET_LOGS:"getLogs",JOBS:"jobs",PERSISTENT_STORAGE_CREATE_BUCKET:"persistentStorageCreateBucket",PERSISTENT_STORAGE_GET_BUCKETS:"persistentStorageGetBuckets",PERSISTENT_STORAGE_LIST_FILES:"persistentStorageListFiles",PERSISTENT_STORAGE_UPLOAD_FILE:"persistentStorageUploadFile",PERSISTENT_STORAGE_GET_FILE_OBJECT:"persistentStorageGetFileObject",PERSISTENT_STORAGE_DELETE_FILE:"persistentStorageDeleteFile"};function E(e,t){this.v=e,this.k=t}function x(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function P(e){var t,n,r,i=2;for("undefined"!=typeof Symbol&&(n=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(n&&null!=(t=e[n]))return t.call(e);if(r&&null!=(t=e[r]))return new S(t.call(e));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function S(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then(function(e){return{value:e,done:t}})}return S=function(e){this.s=e,this.n=e.next},S.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?Promise.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?Promise.reject(e):t(n.apply(this.s,arguments))}},new S(e)}function A(e){return new E(e,0)}function C(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return x(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?x(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function k(){return k=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},k.apply(null,arguments)}function I(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,M(e,t)}function D(){D=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(e,t,n){e[t]=n.value},s="function"==typeof Symbol?Symbol:{},a=s.iterator||"@@iterator",o=s.asyncIterator||"@@asyncIterator",u=s.toStringTag||"@@toStringTag";function d(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{d({},"")}catch(e){d=function(e,t,n){return e[t]=n}}function c(e,t,n,r){var s=Object.create((t&&t.prototype instanceof b?t:b).prototype),a=new M(r||[]);return i(s,"_invoke",{value:A(e,n,a)}),s}function l(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}t.wrap=c;var p="suspendedStart",h="suspendedYield",f="executing",m="completed",y={};function b(){}function g(){}function v(){}var w={};d(w,a,function(){return this});var T=Object.getPrototypeOf,E=T&&T(T(F([])));E&&E!==n&&r.call(E,a)&&(w=E);var x=v.prototype=b.prototype=Object.create(w);function P(e){["next","throw","return"].forEach(function(t){d(e,t,function(e){return this._invoke(t,e)})})}function S(e,t){function n(i,s,a,o){var u=l(e[i],e,s);if("throw"!==u.type){var d=u.arg,c=d.value;return c&&"object"==typeof c&&r.call(c,"__await")?t.resolve(c.__await).then(function(e){n("next",e,a,o)},function(e){n("throw",e,a,o)}):t.resolve(c).then(function(e){d.value=e,a(d)},function(e){return n("throw",e,a,o)})}o(u.arg)}var s;i(this,"_invoke",{value:function(e,r){function i(){return new t(function(t,i){n(e,r,t,i)})}return s=s?s.then(i,i):i()}})}function A(t,n,r){var i=p;return function(s,a){if(i===f)throw Error("Generator is already running");if(i===m){if("throw"===s)throw a;return{value:e,done:!0}}for(r.method=s,r.arg=a;;){var o=r.delegate;if(o){var u=C(o,r);if(u){if(u===y)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===p)throw i=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=f;var d=l(t,n,r);if("normal"===d.type){if(i=r.done?m:h,d.arg===y)continue;return{value:d.arg,done:r.done}}"throw"===d.type&&(i=m,r.method="throw",r.arg=d.arg)}}}function C(t,n){var r=n.method,i=t.iterator[r];if(i===e)return n.delegate=null,"throw"===r&&t.iterator.return&&(n.method="return",n.arg=e,C(t,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),y;var s=l(i,t.iterator,n.arg);if("throw"===s.type)return n.method="throw",n.arg=s.arg,n.delegate=null,y;var a=s.arg;return a?a.done?(n[t.resultName]=a.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,y):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,y)}function k(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function I(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function M(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(k,this),this.reset(!0)}function F(t){if(t||""===t){var n=t[a];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function n(){for(;++i<t.length;)if(r.call(t,i))return n.value=t[i],n.done=!1,n;return n.value=e,n.done=!0,n};return s.next=s}}throw new TypeError(typeof t+" is not iterable")}return g.prototype=v,i(x,"constructor",{value:v,configurable:!0}),i(v,"constructor",{value:g,configurable:!0}),g.displayName=d(v,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===g||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,v):(e.__proto__=v,d(e,u,"GeneratorFunction")),e.prototype=Object.create(x),e},t.awrap=function(e){return{__await:e}},P(S.prototype),d(S.prototype,o,function(){return this}),t.AsyncIterator=S,t.async=function(e,n,r,i,s){void 0===s&&(s=Promise);var a=new S(c(e,n,r,i),s);return t.isGeneratorFunction(n)?a:a.next().then(function(e){return e.done?e.value:a.next()})},P(x),d(x,u,"Generator"),d(x,a,function(){return this}),d(x,"toString",function(){return"[object Generator]"}),t.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=F,M.prototype={constructor:M,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(I),!t)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var n=this;function i(r,i){return o.type="throw",o.arg=t,n.next=r,i&&(n.method="next",n.arg=e),!!i}for(var s=this.tryEntries.length-1;s>=0;--s){var a=this.tryEntries[s],o=a.completion;if("root"===a.tryLoc)return i("end");if(a.tryLoc<=this.prev){var u=r.call(a,"catchLoc"),d=r.call(a,"finallyLoc");if(u&&d){if(this.prev<a.catchLoc)return i(a.catchLoc,!0);if(this.prev<a.finallyLoc)return i(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return i(a.catchLoc,!0)}else{if(!d)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return i(a.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var s=i;break}}s&&("break"===e||"continue"===e)&&s.tryLoc<=t&&t<=s.finallyLoc&&(s=null);var a=s?s.completion:{};return a.type=e,a.arg=t,s?(this.method="next",this.next=s.finallyLoc,y):this.complete(a)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),y},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),I(n),y}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;I(n)}return i}}throw Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:F(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),y}},t}function M(e,t){return M=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},M(e,t)}function F(e){return function(){return new R(e.apply(this,arguments))}}function R(e){var t,n;function r(t,n){try{var s=e[t](n),a=s.value,o=a instanceof E;Promise.resolve(o?a.v:a).then(function(n){if(o){var u="return"===t?"return":"next";if(!a.k||n.done)return r(u,n);n=e[u](n).value}i(s.done?"return":"normal",n)},function(e){r("throw",e)})}catch(e){i("throw",e)}}function i(e,i){switch(e){case"return":t.resolve({value:i,done:!0});break;case"throw":t.reject(i);break;default:t.resolve({value:i,done:!1})}(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(s,a){var o={key:e,arg:i,resolve:s,reject:a,next:null};n?n=n.next=o:(t=n=o,r(e,i))})},"function"!=typeof e.return&&(this.return=void 0)}R.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},R.prototype.next=function(e){return this._invoke("next",e)},R.prototype.throw=function(e){return this._invoke("throw",e)},R.prototype.return=function(e){return this._invoke("return",e)};var _,L={mumbai:{chainId:80001,Ocean:"0xd8992Ed72C445c35Cb4A2be468568Ed1079357c8",OPFCommunityFeeCollector:"0xd8839c98ca8CE07dDa4e460a71B634A4A82f8BD6",startBlock:26354458,poolTemplate:"0x101fd973F488c40DC57305CFED84bB2a2C8A7D6E",Router:"0x564955E9d25B49afE5Abd66966Ab4Bc9Ad55Fedb",FixedPrice:"0x25e1926E3d57eC0651e89C654AB0FA182C6D5CF7",Staking:"0xdFa50781f1E58419f56A00A8Bb5Fce1a9dE67269",ERC20Template:{1:"0xd31f74d1D5a83b896Ad746d96f78fd65B0a66EBf",2:"0x80c5DcCc76a54b3c43494Ca3c857426aA4ce0a52"},ERC721Template:{1:"0xda01B7dD00ef97Eb477B69D943779b7df5ed0Aec"},Dispenser:"0x21bc18b92F7551e715B490E2C2875E8532317F8d",ERC721Factory:"0x7d46d74023507D30ccc2d3868129fbE4e400e40B",veAllocate:"0x3fa1d5AC45ab1Ff9CFAe227c5583Ec0484b54Ef9",veOCEAN:"0x061955B6980A34fce74b235f90DBe20d76f087b1",veDelegation:"0x96E3aE4247a01C3d40a261df1F8ead70E32E7C0c",veFeeDistributor:"0x35F1e6765750E874EB9d0675393A1A394A4749b4",DFRewards:"0x4259c164eedA7483dda2b4b622D761A88674D31f",DFStrategyV1:"0x1be9C72500B41c286C797D4FE727747Ae9C4E195",veFeeEstimate:"0xCFeF55c6ae4d250586e293f29832967a04A9087d",Splitter:"0x648306FF10673e4eAad6F69473e49C973f9F5872",VestingWallet0:"0x4699B0f191C68975e89E70c5704537f7ad033f62"},polygon:{chainId:137,Ocean:"0x282d8efCe846A88B159800bd4130ad77443Fa1A1",OPFCommunityFeeCollector:"0x042BFbd88c3998282153088604207b2AeF045b43",startBlock:28443969,poolTemplate:"0xBB3051dF2D3E408DAE6E6dAa2296BC6215F0dCFd",Router:"0x78e1317186786591912A10a7aF2490B8B4697A93",FixedPrice:"0xb28Ab1AaDe4c75F8cF013136fc0c290AeaeA9BA6",Staking:"0x3EFDD8f728c8e774aB81D14d0B2F07a8238960f4",ERC20Template:{1:"0x8B8E187CF9c551e63f54AA04E21F48CDAF2296aE",2:"0xE282492d50879b911844fA6dD87aAD6169963fC6"},ERC721Template:{1:"0xd09789Ce05aa0f6feFc18315de4964Db07Cc0618"},Dispenser:"0x257fe2e49530A4B7FC3Ed597465e2931db3f20b7",ERC721Factory:"0x6fd867E5AEE6D62a24f97939db90C4e67A73A651",DFRewards:"0x0cea7DA063EA910D6904299b5A29A8b68DBC1947",DFStrategyV1:"0x0000000000cEAe464ae8a73EDDc0B482383490e7"},bsc:{chainId:56,Ocean:"0xDCe07662CA8EbC241316a15B611c89711414Dd1a",OPFCommunityFeeCollector:"0x973e69303259B0c2543a38665122b773D28405fB",startBlock:18407552,poolTemplate:"0x3E85e7Cb15880b6d4871092E74bF65CE03E8448D",Router:"0x4344D4Bc29531DB736378e9A3dA85BF1eff0CB22",FixedPrice:"0x8bA04715B1b210f710426b21A29887EEd4EA6751",Staking:"0x1706DF1f2d93558D1d77bEd49ccdB8B88fAfC306",ERC20Template:{1:"0x45dA5988d4fEAEdc5Ee60FC83eA7Caa8Fb485883",2:"0xA8513c0457AfaD54a57664Ba5C742c24f1D624be"},ERC721Template:{1:"0xDB55DCBbAC940aCb5c28817802f17A48B15d558b"},Dispenser:"0x042BFbd88c3998282153088604207b2AeF045b43",ERC721Factory:"0xbFBc7A21133B4e0e54a182BE8d4337A5e036A615",DFRewards:"0x0cea7DA063EA910D6904299b5A29A8b68DBC1947",DFStrategyV1:"0x0000000000cEAe464ae8a73EDDc0B482383490e7"},energyweb:{chainId:246,Ocean:"0x593122AAE80A6Fc3183b2AC0c4ab3336dEbeE528",OPFCommunityFeeCollector:"0x3c21a90599b5B7f37014cA5Bf30d3f1b73d7e391",startBlock:18264850,poolTemplate:"0xCfDdA22C9837aE76E0faA845354f33C62E03653a",Router:"0x4E6058dC00e90C0DCA47A5d0D3346F409939A5ab",FixedPrice:"0xE9397625Df9B63f0C152f975234b7988b54710B8",Staking:"0x159924ca0F47D6F704B97E29099b89e518A17B5E",ERC20Template:{1:"0xc313e19146Fc9a04470689C9d41a4D3054693531",2:"0x98679D582AB3398C03D3308dEB9c7AeC50B52ded"},ERC721Template:{1:"0x1d535147a97bd87c8443125376E6671B60556E07"},Dispenser:"0x042D709b72B437d7d387F2679bD4ac060e561c9f",ERC721Factory:"0x4dD281EB67DED07E76E413Df16176D66ae69e240",DFRewards:"0x0cea7DA063EA910D6904299b5A29A8b68DBC1947",DFStrategyV1:"0x0000000000cEAe464ae8a73EDDc0B482383490e7"},moonriver:{chainId:1285,Ocean:"0x99C409E5f62E4bd2AC142f17caFb6810B8F0BAAE",OPFCommunityFeeCollector:"0x12bB8D85a091A69A07E22E52d4567dBB91568f52",startBlock:1960563,poolTemplate:"0x9497d1d64F2aFeBcd4f9916Eef3d9094E5Df962f",Router:"0x7b0576CF01E868bce46cca91b2a8E674141b0355",FixedPrice:"0x8389bC1306208488D665F939AFB4079adf6f5a06",Staking:"0xc97fa83746aDe91b0eeB16cb51326a0A980Af7c3",ERC20Template:{1:"0xE5aa2C9B551aFcA4C0A98BB3B37D7A43084d0a66",2:"0xf0c7A31D7Ee26bEBfb4BAD8e37490bEadE3F846f"},ERC721Template:{1:"0xA0329eFFa1370eAb1DC5998Db4292ae0F535a282"},Dispenser:"0x0Ee8b03Dafc868a0899ebE1c12d734D53A957250",ERC721Factory:"0x86F2BB9F8f18B5a836b342199a3eC89F282E4018",DFRewards:"0x0cea7DA063EA910D6904299b5A29A8b68DBC1947",DFStrategyV1:"0x0000000000cEAe464ae8a73EDDc0B482383490e7"},mainnet:{chainId:1,Ocean:"0x967da4048cD07aB37855c090aAF366e4ce1b9F48",OPFCommunityFeeCollector:"0x49E35cd2bAE043Abd9074B6e5a649a5AdEB05C33",startBlock:14907021,poolTemplate:"0x8daC419D5D81Af8c8E795D0D73f64d5220e28cd8",Router:"0x8149276f275EEFAc110D74AFE8AFECEaeC7d1593",FixedPrice:"0xfa48673a7C36A2A768f89AC1ee8C355D5c367B02",Staking:"0x7842Fa3B2d87Ff1cd52C4152382f7C4B3406E5A6",ERC20Template:{1:"0x973e69303259B0c2543a38665122b773D28405fB",2:"0x3E85e7Cb15880b6d4871092E74bF65CE03E8448D"},ERC721Template:{1:"0x4344D4Bc29531DB736378e9A3dA85BF1eff0CB22"},Dispenser:"0x8bA04715B1b210f710426b21A29887EEd4EA6751",ERC721Factory:"0x1706DF1f2d93558D1d77bEd49ccdB8B88fAfC306",DFRewards:"0xFe27534EA0c016634b2DaA97Ae3eF43fEe71EEB0",DFStrategyV1:"0x545138e8D76C304C916B1261B3f6c446fe4f63e3",veOCEAN:"0xE86Bf3B0D3a20444DE7c78932ACe6e5EfFE92379",veAllocate:"0x55567E038b0a50283084ae773FA433a5029822d3",veDelegation:"0xc768eDF2d21fe00ef5804A7Caa775E877e65A70E",veFeeDistributor:"0x256c54219816603BB8327F9019533B020a76e936",veFeeEstimate:"0x4aA261bC595abC6fDEf0255C83e2a9305261753f",SmartWalletChecker:"0xd7ddf62257A41cc6cdAd7A3d36e4f1d925fD142a",Splitter:"0xadF0D06e58E618de36Af0F1b52891b14FAA61187",Distribute:"0x01BE353d9Fd3A64C591A30A8c4a6a37B5dfAe165",VestingWallet0:"0x8D011915C437AD5f5e3B0E4c6dd6380c92599f99",VestingWalletA:"0xf9FB1f54eA825734E3a77e73A3864f4B46C815d9",VestingWalletB:"0xf02e3163Dc3409D69D88D7AcDA613432E9A18741",VestingWalletC:"0x29F74B853C4B8D36273666FB63a3b71c754424Ed",OceanNodesBooster:"0x73558Ef3bb6543A8107ac032C5a98Da03ceb0eEf",OPFCommunityFeeCollectorCompute:"0x1705CaF86B86e85804e20FE342f39B17322Ff592",Escrow:"0xC98C71A9efeF2a940c73B7986f1D8469f1815F94",AccessListFactory:"0x7ed6ac4243472adA55408fEE45c5Dff379f7aBE0",EnterpriseFeeCollector:"0x254302d1Ae1e1200319c885D93D40a8927ACFcD7",EnterpriseEscrow:"0x2213FeBd4E681633bE255AfceFbd233EbcFc33c9",FixedPriceEnterprise:"0x6C97D128f7E7D21ac3C722458Dc5d71f7e1bBa6e"},goerli:{chainId:5,Ocean:"0xCfDdA22C9837aE76E0faA845354f33C62E03653a",OPFCommunityFeeCollector:"0xE9397625Df9B63f0C152f975234b7988b54710B8",startBlock:7425573,Router:"0x159924ca0F47D6F704B97E29099b89e518A17B5E",FixedPrice:"0xc313e19146Fc9a04470689C9d41a4D3054693531",Staking:"0x98679D582AB3398C03D3308dEB9c7AeC50B52ded",ERC20Template:{1:"0x1d535147a97bd87c8443125376E6671B60556E07",2:"0x042D709b72B437d7d387F2679bD4ac060e561c9f"},ERC721Template:{1:"0x4dD281EB67DED07E76E413Df16176D66ae69e240"},Dispenser:"0xFe7967A5176fDAFa8DE109b3507016B885a82D6e",ERC721Factory:"0xe8c6Dc39602031A152440311e364818ba25C2Bc1",veAllocate:"0x3EFDD8f728c8e774aB81D14d0B2F07a8238960f4",veOCEAN:"0x8B8E187CF9c551e63f54AA04E21F48CDAF2296aE",veDelegation:"0xE282492d50879b911844fA6dD87aAD6169963fC6",veFeeDistributor:"0xd09789Ce05aa0f6feFc18315de4964Db07Cc0618",DFRewards:"0x6fd867E5AEE6D62a24f97939db90C4e67A73A651",DFStrategyV1:"0x1Af3CC30fD18af837f7630Aff12aE2b826bD3c5D",veFeeEstimate:"0xB3AB945aa7553EbC8Ce234a53b03a1bbA23E8fAB"},polygonedge:{chainId:81001,Ocean:"0x8c98ea273bA22327F896Aa1a1a46E1BFf56e9b1D",OPFCommunityFeeCollector:"0x8daC419D5D81Af8c8E795D0D73f64d5220e28cd8",startBlock:3256707,Router:"0x8149276f275EEFAc110D74AFE8AFECEaeC7d1593",FixedPrice:"0xfa48673a7C36A2A768f89AC1ee8C355D5c367B02",Staking:"0x7842Fa3B2d87Ff1cd52C4152382f7C4B3406E5A6",ERC20Template:{1:"0x973e69303259B0c2543a38665122b773D28405fB",2:"0x3E85e7Cb15880b6d4871092E74bF65CE03E8448D"},ERC721Template:{1:"0x4344D4Bc29531DB736378e9A3dA85BF1eff0CB22"},Dispenser:"0x8bA04715B1b210f710426b21A29887EEd4EA6751",ERC721Factory:"0x1706DF1f2d93558D1d77bEd49ccdB8B88fAfC306"},gaiaxtestnet:{chainId:2021e3,Ocean:"0x80E63f73cAc60c1662f27D2DFd2EA834acddBaa8",OPFCommunityFeeCollector:"0xD3173c3E3d9ea662E914C30Bcd647eF573AcE405",startBlock:7711332,Router:"0x23A8b2D7176485a6349e4830605F323f31019333",FixedPrice:"0xb65F19225fEBb650Fcc211dC9F18FEC6f4a328D5",Staking:"0xcD8674D32E940B14ABF2Cc8C32B21952cB354101",ERC20Template:{1:"0x43eC0a34E1b70C7f8E579ab866F37642777727E7",2:"0x6976320eC365202118B4B0B0906E13DDf21633A5"},ERC721Template:{1:"0x5494711392a67DA50D3bC7b1fcC2d1877cFaA4d2"},Dispenser:"0x8c98ea273bA22327F896Aa1a1a46E1BFf56e9b1D",ERC721Factory:"0x49E35cd2bAE043Abd9074B6e5a649a5AdEB05C33"},alfajores:{chainId:44787,Ocean:"0xd8992Ed72C445c35Cb4A2be468568Ed1079357c8",OPFCommunityFeeCollector:"0xEF62FB495266C72a5212A11Dce8baa79Ec0ABeB1",startBlock:16422659,Router:"0xc37F8341Ac6e4a94538302bCd4d49Cf0852D30C0",FixedPrice:"0x3c21a90599b5B7f37014cA5Bf30d3f1b73d7e391",Staking:"0xCfDdA22C9837aE76E0faA845354f33C62E03653a",ERC20Template:{1:"0x4E6058dC00e90C0DCA47A5d0D3346F409939A5ab",2:"0xE9397625Df9B63f0C152f975234b7988b54710B8"},ERC721Template:{1:"0x159924ca0F47D6F704B97E29099b89e518A17B5E"},Dispenser:"0xc313e19146Fc9a04470689C9d41a4D3054693531",ERC721Factory:"0x98679D582AB3398C03D3308dEB9c7AeC50B52ded"},"gen-x-testnet":{chainId:100,Ocean:"0x0995527d3473b3a98c471f1ed8787acd77fbf009",startBlock:3665369,OPFCommunityFeeCollector:"0x2e0C9e15A45c9884F7768BB852E7399B9153525d",Router:"0x7A3C9F0729AB93e4F9945221168A56eCf450187D",FixedPrice:"0xAD8E7d2aFf5F5ae7c2645a52110851914eE6664b",ERC20Template:{1:"0xA7D7Cb8dDd46c1B13e9Ccab2fA7D4fC5926f0348",2:"0x7fEcdEDaE245d3AD5ad93c6Df9603d06887786e8"},ERC721Template:{"1:":"0x2CBCD3b10783378e34209B760e5A70531198f65E"},Dispenser:"0x94cb8FC8719Ed09bE3D9c696d2037EA95ef68d3e",ERC721Factory:"0x6cb85858183B82154921f68b434299EC4281da53"},filecointestnet:{chainId:3141,Ocean:"0xf26c6C93f9f1d725e149d95f8E7B2334a406aD10",OPFCommunityFeeCollector:"0xF6410bf5d773C7a41ebFf972f38e7463FA242477",startBlock:145290,Router:"0x1B083D8584dd3e6Ff37d04a6e7e82b5F622f3985",FixedPrice:"0x69B6E54Ad2b3c2801d11d8Ad56ea1d892555b776",Staking:"0x2112Eb973af1DBf83a4f11eda82f7a7527D7Fde5",ERC20Template:{1:"0x80E63f73cAc60c1662f27D2DFd2EA834acddBaa8",2:"0x3C5605202eD47C162450AE975415473e73F93072"},ERC721Template:{1:"0x30E4CC2C7A9c6aA2b2Ce93586E3Df24a3A00bcDD"},Dispenser:"0xDEfD0018969cd2d4E648209F876ADe184815f038",ERC721Factory:"0x9C9eE07b8Ce907D2f9244F8317C1Ed29A3193bAe"},oasis_sapphire_testnet:{chainId:23295,Ocean:"0x973e69303259B0c2543a38665122b773D28405fB",OPFCommunityFeeCollector:"0xe8c6Dc39602031A152440311e364818ba25C2Bc1",startBlock:2565487,Router:"0x5FBC2A29f7C8e4533dECD14Dc1c561A8eF0d4e31",FixedPrice:"0x0846aec7aADD547131484Bf7fE548589b7F057fe",ERC20Template:{1:"0x519d462294958A935D34351b3ad9F98cCAB0b7f8",2:"0x2bCa501a6f9FB8a96f1b7B09D4f74A32ACAa7584",3:"0xf00c16665b79F23c04e5c8652Fe9853046b987c8",4:"0x89b752C3e272feBA17B363EaaBFe0d653cF75bE7",5:"0xb4914dfeC7f70C708673620eDF6d8839F81E7612"},ERC721Template:{1:"0x9Ab15cc945b2B58A51384539211dE8a88a1355E8"},Dispenser:"0xbde8224d15885c2E46Be665b9392E619cD142de8",ERC721Factory:"0x315ef329D214cde5cE7C206104aC35B1fe66bb8c",PredictoorHelper:"0x2e4cb19faD077768fDcB04Bc0549AB76BE8eA63F",AccessListFactory:"0xdA412123a3Cc0D921bcf7246f8742e3b7c3E7b94"},sepolia:{chainId:11155111,Ocean:"0x1B083D8584dd3e6Ff37d04a6e7e82b5F622f3985",OPFCommunityFeeCollector:"0x69B6E54Ad2b3c2801d11d8Ad56ea1d892555b776",startBlock:3722802,Router:"0x2112Eb973af1DBf83a4f11eda82f7a7527D7Fde5",FixedPrice:"0x80E63f73cAc60c1662f27D2DFd2EA834acddBaa8",Staking:"0x3C5605202eD47C162450AE975415473e73F93072",ERC20Template:{1:"0x30E4CC2C7A9c6aA2b2Ce93586E3Df24a3A00bcDD",2:"0xDEfD0018969cd2d4E648209F876ADe184815f038"},ERC721Template:{1:"0x9C9eE07b8Ce907D2f9244F8317C1Ed29A3193bAe"},Dispenser:"0x2720d405ef7cDC8a2E2e5AeBC8883C99611d893C",ERC721Factory:"0xEF62FB495266C72a5212A11Dce8baa79Ec0ABeB1",OPFCommunityFeeCollectorCompute:"0x0Ee8b03Dafc868a0899ebE1c12d734D53A957250",Escrow:"0xd09789Ce05aa0f6feFc18315de4964Db07Cc0618",EnterpriseFeeCollector:"0x8c98ea273bA22327F896Aa1a1a46E1BFf56e9b1D",FixedPriceEnterprise:"0xfa48673a7C36A2A768f89AC1ee8C355D5c367B02",AccessListFactory:"0x43eC0a34E1b70C7f8E579ab866F37642777727E7",EnterpriseEscrow:"0x6fd867E5AEE6D62a24f97939db90C4e67A73A651",COMPY:"0x973e69303259B0c2543a38665122b773D28405fB",COMPYFaucet:"0x3EFDD8f728c8e774aB81D14d0B2F07a8238960f4",COMPYSwap:"0x8B8E187CF9c551e63f54AA04E21F48CDAF2296aE"},oasis_sapphire:{chainId:23294,Ocean:"0x39d22B78A7651A76Ffbde2aaAB5FD92666Aca520",OPFCommunityFeeCollector:"0x06100AB868206861a4D7936166A91668c2Ce1312",startBlock:905232,Router:"0xd8992Ed72C445c35Cb4A2be468568Ed1079357c8",FixedPrice:"0xf26c6C93f9f1d725e149d95f8E7B2334a406aD10",ERC20Template:{1:"0xDBDa486d8fE29F75e9Ca858F438b380Fc14b1232",2:"0xF6410bf5d773C7a41ebFf972f38e7463FA242477",3:"0x1B083D8584dd3e6Ff37d04a6e7e82b5F622f3985",4:"0x4dD281EB67DED07E76E413Df16176D66ae69e240",5:"0xA4E108a4fa07C931cFe4bF2c1c6f9C1579d5a819"},ERC721Template:{1:"0x69B6E54Ad2b3c2801d11d8Ad56ea1d892555b776"},Dispenser:"0x2112Eb973af1DBf83a4f11eda82f7a7527D7Fde5",ERC721Factory:"0x80E63f73cAc60c1662f27D2DFd2EA834acddBaa8",DFRewards:"0xc37F8341Ac6e4a94538302bCd4d49Cf0852D30C0",DFStrategyV1:"0x3c21a90599b5B7f37014cA5Bf30d3f1b73d7e391",PredictoorHelper:"0xE9397625Df9B63f0C152f975234b7988b54710B8",AccessListFactory:"0x12bB8D85a091A69A07E22E52d4567dBB91568f52",BatchPayments:"0x9497d1d64F2aFeBcd4f9916Eef3d9094E5Df962f",OPFCommunityFeeCollectorCompute:"0xE5aa2C9B551aFcA4C0A98BB3B37D7A43084d0a66",Escrow:"0x0Ee8b03Dafc868a0899ebE1c12d734D53A957250"},optimism_sepolia:{chainId:11155420,Ocean:"0xf26c6C93f9f1d725e149d95f8E7B2334a406aD10",OPFCommunityFeeCollector:"0xF6410bf5d773C7a41ebFf972f38e7463FA242477",startBlock:3867703,Router:"0x1B083D8584dd3e6Ff37d04a6e7e82b5F622f3985",FixedPrice:"0x69B6E54Ad2b3c2801d11d8Ad56ea1d892555b776",ERC20Template:{1:"0x2112Eb973af1DBf83a4f11eda82f7a7527D7Fde5",2:"0x80E63f73cAc60c1662f27D2DFd2EA834acddBaa8"},ERC721Template:{1:"0x3C5605202eD47C162450AE975415473e73F93072"},Dispenser:"0x30E4CC2C7A9c6aA2b2Ce93586E3Df24a3A00bcDD",ERC721Factory:"0xDEfD0018969cd2d4E648209F876ADe184815f038",OPFCommunityFeeCollectorCompute:"0xe47991939632757DEe324E8ec9A3268c62C0DB76",Escrow:"0x23A8b2D7176485a6349e4830605F323f31019333",AccessListFactory:"0xEcD0C3519a081e3924D6F3197f86980eA7dfCf71"},optimism:{chainId:10,Ocean:"0x2561aa2bB1d2Eb6629EDd7b0938d7679B8b49f9E",OPFCommunityFeeCollector:"0xd8992Ed72C445c35Cb4A2be468568Ed1079357c8",startBlock:112181681,Router:"0xf26c6C93f9f1d725e149d95f8E7B2334a406aD10",FixedPrice:"0xDBDa486d8fE29F75e9Ca858F438b380Fc14b1232",ERC20Template:{1:"0xF6410bf5d773C7a41ebFf972f38e7463FA242477",2:"0x1B083D8584dd3e6Ff37d04a6e7e82b5F622f3985"},ERC721Template:{1:"0x69B6E54Ad2b3c2801d11d8Ad56ea1d892555b776"},Dispenser:"0x2112Eb973af1DBf83a4f11eda82f7a7527D7Fde5",ERC721Factory:"0x80E63f73cAc60c1662f27D2DFd2EA834acddBaa8",OPFCommunityFeeCollectorCompute:"0xc37F8341Ac6e4a94538302bCd4d49Cf0852D30C0",Escrow:"0x4dD281EB67DED07E76E413Df16176D66ae69e240",AccessListFactory:"0x4E6058dC00e90C0DCA47A5d0D3346F409939A5ab",EnterpriseFeeCollector:"0xE9397625Df9B63f0C152f975234b7988b54710B8",EnterpriseEscrow:"0xFe7967A5176fDAFa8DE109b3507016B885a82D6e",FixedPriceEnterprise:"0x1d535147a97bd87c8443125376E6671B60556E07"},"pontus-x-devnet":{chainId:32456,Ocean:"0xdF171F74a8d3f4e2A789A566Dce9Fa4945196112",OPFCommunityFeeCollector:"0x1f84fB438292269219f9396D57431eA9257C23d4",Router:"0x4Ede1776D6B75de6c907172Abc0453a3C8AB372a",FixedPrice:"0x8372715D834d286c9aECE1AcD51Da5755B32D505",ERC20Template:{1:"0x02eCd3850B53b1BA8dbCdD146C963cC27f27Dd3C",2:"0x23Efb300c8778d6842bB0cCBD07D356eCeB97070"},ERC721Template:{1:"0x5B0cc649134791c2357c93868d6e8D325A31aE29"},Dispenser:"0x5461b629E01f72E0A468931A36e039Eea394f9eA",ERC721Factory:"0xFdC4a5DEaCDfc6D82F66e894539461a269900E13",startBlock:57428},base:{chainId:8453,OPFCommunityFeeCollector:"0x2720d405ef7cDC8a2E2e5AeBC8883C99611d893C",startBlock:30562198,Router:"0xEF62FB495266C72a5212A11Dce8baa79Ec0ABeB1",FixedPrice:"0xc37F8341Ac6e4a94538302bCd4d49Cf0852D30C0",ERC20Template:{1:"0x3c21a90599b5B7f37014cA5Bf30d3f1b73d7e391",2:"0xCfDdA22C9837aE76E0faA845354f33C62E03653a"},ERC721Template:{1:"0x4E6058dC00e90C0DCA47A5d0D3346F409939A5ab"},Dispenser:"0xE9397625Df9B63f0C152f975234b7988b54710B8",ERC721Factory:"0x159924ca0F47D6F704B97E29099b89e518A17B5E",BatchPayments:"0xFe7967A5176fDAFa8DE109b3507016B885a82D6e",OPFCommunityFeeCollectorCompute:"0x7b0576CF01E868bce46cca91b2a8E674141b0355",Escrow:"0x43eC0a34E1b70C7f8E579ab866F37642777727E7",AccessListFactory:"0xE5aa2C9B551aFcA4C0A98BB3B37D7A43084d0a66",COMPY:"0x298f163244e0c8cc9316D6E97162e5792ac5d410",COMPYFaucet:"0x23A8b2D7176485a6349e4830605F323f31019333",COMPYSwap:"0xb65F19225fEBb650Fcc211dC9F18FEC6f4a328D5"}};exports.LogLevel=void 0,(_=exports.LogLevel||(exports.LogLevel={}))[_.None=-1]="None",_[_.Error=0]="Error",_[_.Warn=1]="Warn",_[_.Log=2]="Log",_[_.Verbose=3]="Verbose";var N=/*#__PURE__*/function(){function e(e){this.logLevel=void 0,this.logLevel=e,this.logLevel=e||exports.LogLevel.Error}var t=e.prototype;return t.setLevel=function(e){this.logLevel=e},t.bypass=function(){this.dispatch.apply(this,["log",-Infinity].concat([].slice.call(arguments)))},t.debug=function(){this.dispatch.apply(this,["debug",exports.LogLevel.Verbose].concat([].slice.call(arguments)))},t.log=function(){this.dispatch.apply(this,["log",exports.LogLevel.Log].concat([].slice.call(arguments)))},t.warn=function(){this.dispatch.apply(this,["warn",exports.LogLevel.Warn].concat([].slice.call(arguments)))},t.error=function(){this.dispatch.apply(this,["error",exports.LogLevel.Error].concat([].slice.call(arguments)))},t.dispatch=function(e,t){var n;this.logLevel>=t&&(n=console)[e].apply(n,[].slice.call(arguments,2))},e}(),O=new N,B={chainId:null,network:"unknown",nodeUri:"http://127.0.0.1:8545",oceanNodeUri:"http://127.0.0.1:8001",explorerUri:null,oceanTokenAddress:null,oceanTokenSymbol:"OCEAN",fixedRateExchangeAddress:null,dispenserAddress:null,startBlock:0,transactionBlockTimeout:50,transactionConfirmationBlocks:1,transactionPollingTimeout:750,gasFeeMultiplier:1},U=[k({},B),k({},B,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),k({},B,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),k({},B,{chainId:1,network:"mainnet",nodeUri:"https://mainnet.infura.io/v3",explorerUri:"https://etherscan.io",startBlock:11105459,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),k({},B,{chainId:8453,network:"base",nodeUri:"https://mainnet.base.org",explorerUri:"https://etherscan.io",startBlock:30562198,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),k({},B,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),k({},B,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),k({},B,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),k({},B,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),k({},B,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),k({},B,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),k({},B,{chainId:100,network:"gen-x-testnet",nodeUri:"https://rpc.genx.minimal-gaia-x.eu",explorerUri:"https://explorer.genx.minimal-gaia-x.eu/",gasFeeMultiplier:1,sdk:"evm"}),k({},B,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),k({},B,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),k({},B,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),k({},B,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),k({},B,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],j=[23294,23295],q=function(){return process.env.NODE_ENDPOINT||process.env.NODE_URL?{oceanNodeUri:process.env.NODE_ENDPOINT||process.env.NODE_URL}:{}},$=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getAddressesFromEnv=function(e,t){var n;if(t&&t[e]){var r=t[e];n=k({nftFactoryAddress:r.ERC721Factory,opfCommunityFeeCollector:r.OPFCommunityFeeCollector,fixedRateExchangeAddress:r.FixedPrice,dispenserAddress:r.Dispenser,oceanTokenAddress:r.Ocean,routerFactoryAddress:r.Router,chainId:r.chainId,startBlock:r.startBlock,accessListFactory:r.AccessListFactory,escrow:r.Escrow,EnterpriseFeeCollector:r.EnterpriseFeeCollector},q())}else if(L[e]){var i=L[e];n=k({nftFactoryAddress:i.ERC721Factory,opfCommunityFeeCollector:i.OPFCommunityFeeCollector,fixedRateExchangeAddress:i.FixedPrice,dispenserAddress:i.Dispenser,oceanTokenAddress:i.Ocean,routerFactoryAddress:i.Router,chainId:i.chainId,startBlock:i.startBlock,accessListFactory:i.AccessListFactory,escrow:i.Escrow,EnterpriseFeeCollector:i.EnterpriseFeeCollector},q())}return n},t.getConfig=function(e,t){var n="string"==typeof e?"network":"chainId",r=U.find(function(t){return t[n]===e});if(!r)return O.error("No config found for given network '"+e+"'"),null;var i=null;try{"undefined"==typeof window&&process.env.ADDRESS_FILE&&(i=JSON.parse(f.default.readFileSync(process.env.ADDRESS_FILE,"utf8")))}catch(e){console.log(e),i=null}var s=this.getAddressesFromEnv(r.network,i);return!s&&j.includes(r.chainId)&&(s=this.getAddressesFromEnv(r.network.replace("sapph","saph"),i)),"sdk"in r&&null!==r.sdk||(r.sdk=j.includes(r.chainId)?"oasis":"evm"),s&&"accessListFactory"in s&&(r.accessListFactory=s.accessListFactory),r=k({},r,s),k({},r,{nodeUri:t?r.nodeUri+"/"+t:r.nodeUri})},e}(),z=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}],V=function(e,t,n,r){try{var i=arguments;return Promise.resolve(t.provider.getNetwork()).then(function(s){var a=s.chainId;return Promise.resolve(t.provider.getFeeData()).then(function(t){var s={};if(t.maxPriorityFeePerGas){var o=t.maxPriorityFeePerGas.toString(),u=t.maxFeePerGas.toString();n>1&&(o=Math.round(Number(t.maxPriorityFeePerGas)*n).toString(),u=Math.round(Number(t.maxFeePerGas)*n).toString()),s={maxPriorityFeePerGas:(Number(a)===X||Number(a)===Z)&&Number(o)<Q?Q:Number(a)===ee&&Number(o)<Y?Y:j.includes(Number(a))&&Number(o)<J?J:Number(o),maxFeePerGas:(Number(a)===X||Number(a)===Z)&&Number(u)<Q?Q:Number(a)===ee&&Number(u)<Y?Y:j.includes(Number(a))&&Number(u)<J?J:Number(u)}}else s={gasPrice:t.gasPrice};return s.gasLimit=BigInt(new y.default(e).plus(20000n).toString()),function(e,t){try{var n=Promise.resolve(r.apply(void 0,[].slice.call(i,4).concat([s]))).then(function(e){return Promise.resolve(e.wait()).then(function(){return e})})}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(0,function(e){return O.error("Send tx error: ",e),null})})})}catch(e){return Promise.reject(e)}},G=function(e,n,r,i){try{var s=function(e){return"0"===e&&(e=18),t.parseUnits(r,e).toString()};return Promise.resolve(i?s(i):Promise.resolve(H(e,n)).then(s))}catch(e){return Promise.reject(e)}},K=function(e,n,r,i){try{var s=function(e){return"0"===e&&(e=18),t.formatUnits(r,e).toString()};return Promise.resolve(i?s(i):Promise.resolve(H(e,n)).then(s))}catch(e){return Promise.reject(e)}},H=function(e,n){try{var r=new t.ethers.Contract(n,z,e);return Promise.resolve(r.decimals())}catch(e){return Promise.reject(e)}},W=function(e,t){try{return Promise.resolve(e.provider.getFeeData()).then(function(e){var n=BigInt(e.gasPrice.toString());return t?(n*BigInt(t)).toString(10):n.toString()})}catch(e){return Promise.reject(e)}},Q=3e10,Y=4e9,J=1e10,Z=137,X=80001,ee=11155111;function te(e,t){return e}function ne(e,n){if(e&&e.logs){var r=e.logs.filter(function(e){return e instanceof t.EventLog&&e.eventName===n})[0];return r}}var re=/*#__PURE__*/function(){function e(e,t,n,r){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=e,this.config=n||(new $).getConfig(t),this.abi=r||this.getDefaultAbi()}var n=e.prototype;return n.getSignerAccordingSdk=function(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?m.wrap(this.signer):this.signer},n.amountToUnits=function(e,t,n){try{return Promise.resolve(G(this.signer,e,t,n))}catch(e){return Promise.reject(e)}},n.unitsToAmount=function(e,t,n){try{return Promise.resolve(K(this.signer,e,t,n))}catch(e){return Promise.reject(e)}},n.getFairGasPrice=function(){try{var e;return Promise.resolve(W(this.signer,null==(e=this.config)?void 0:e.gasFeeMultiplier))}catch(e){return Promise.reject(e)}},n.getContract=function(e,n){if(!e)throw new Error("Contract address is required but not provided");return te(new t.ethers.Contract(e,new t.ethers.Interface(JSON.stringify(n||this.abi)),this.signer))},e}(),ie=/*#__PURE__*/function(e){function t(t,n,r,i,s){var a;return(a=e.call(this,n,r,i,s)||this).address=void 0,a.contract=void 0,a.address=t,a.contract=a.getContract(a.address),a}return I(t,e),t}(re),se=[{inputs:[{internalType:"address",name:"_router",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"datatokenAddress",type:"address"}],name:"DispenserActivated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"datatoken",type:"address"},{indexed:!0,internalType:"address",name:"newAllowedSwapper",type:"address"}],name:"DispenserAllowedSwapperChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"datatokenAddress",type:"address"},{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"uint256",name:"maxTokens",type:"uint256"},{indexed:!1,internalType:"uint256",name:"maxBalance",type:"uint256"},{indexed:!1,internalType:"address",name:"allowedSwapper",type:"address"}],name:"DispenserCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"datatokenAddress",type:"address"}],name:"DispenserDeactivated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"datatoken",type:"address"},{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"OwnerWithdrawed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"datatokenAddress",type:"address"},{indexed:!0,internalType:"address",name:"userAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"TokensDispensed",type:"event"},{inputs:[{internalType:"address",name:"datatoken",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"}],name:"activate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"datatoken",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"allowedSwapper",type:"address"}],name:"create",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"datatokensList",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"datatoken",type:"address"}],name:"deactivate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"datatoken",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"destination",type:"address"}],name:"dispense",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"datatoken",type:"address"}],name:"ownerWithdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"router",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"datatoken",type:"address"},{internalType:"address",name:"newAllowedSwapper",type:"address"}],name:"setAllowedSwapper",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"datatoken",type:"address"}],name:"status",outputs:[{internalType:"bool",name:"active",type:"bool"},{internalType:"address",name:"owner",type:"address"},{internalType:"bool",name:"isMinter",type:"bool"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"address",name:"allowedSwapper",type:"address"}],stateMutability:"view",type:"function"}],ae=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}I(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return se},n.status=function(e){try{var t=this;return Promise.resolve(t.contract.status(e)).then(function(e){if(!e)throw new Error("Np dispenser found for the given datatoken address");var n=e.isMinter,r=e.owner,i=e.active;return Promise.resolve(t.unitsToAmount(null,e.maxTokens,18)).then(function(s){return Promise.resolve(t.unitsToAmount(null,e.maxBalance,18)).then(function(a){return Promise.resolve(t.unitsToAmount(null,e.balance,18)).then(function(t){return{active:i,owner:r,isMinter:n,maxTokens:s,maxBalance:a,balance:t,allowedSwapper:e.allowedSwapper}})})})})}catch(e){return Promise.reject(e)}},n.create=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.contract.create.estimateGas(e,a.amountToUnits(null,n,18),a.amountToUnits(null,r,18),t,i)).then(function(o){var u;return s?o:Promise.resolve(V(o,a.getSignerAccordingSdk(),null==(u=a.config)?void 0:u.gasFeeMultiplier,a.contract.create,e,a.amountToUnits(null,n,18),a.amountToUnits(null,r,18),t,i))})}catch(e){return Promise.reject(e)}},n.activate=function(e,t,n,r){try{var i=this;return Promise.resolve(i.contract.activate.estimateGas(e,i.amountToUnits(null,t,18),i.amountToUnits(null,n,18))).then(function(s){var a;return r?s:Promise.resolve(V(s,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,i.contract.activate,e,i.amountToUnits(null,t,18),i.amountToUnits(null,n,18)))})}catch(e){return Promise.reject(e)}},n.deactivate=function(e,t){try{var n=this;return Promise.resolve(n.contract.deactivate.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.deactivate,e))})}catch(e){return Promise.reject(e)}},n.setAllowedSwapper=function(e,t,n){try{var r=this;return Promise.resolve(r.contract.setAllowedSwapper.estimateGas(e,t)).then(function(i){var s;return n?i:Promise.resolve(V(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.setAllowedSwapper,e,t))})}catch(e){return Promise.reject(e)}},n.dispense=function(e,t,n,r){void 0===t&&(t="1");try{var i=this;return Promise.resolve(i.contract.dispense.estimateGas(e,i.amountToUnits(null,t,18),n)).then(function(s){var a;return r?s:Promise.resolve(V(s,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,i.contract.dispense,e,i.amountToUnits(null,t,18),n))})}catch(e){return Promise.reject(e)}},n.ownerWithdraw=function(e,t){try{var n=this;return Promise.resolve(n.contract.ownerWithdraw.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.ownerWithdraw,e))})}catch(e){return Promise.reject(e)}},n.isDispensable=function(e,t,n,r){void 0===r&&(r="1");try{return Promise.resolve(this.status(e)).then(function(i){return!!i&&!1!==i.active&&Promise.resolve(t.balance(e,n)).then(function(e){return!(new b.default(e).greaterThanOrEqualTo(i.maxBalance)||new b.default(String(r)).greaterThan(i.maxTokens)||!new b.default(i.balance).greaterThanOrEqualTo(r)&&!0!==i.isMinter)})})}catch(e){return Promise.reject(e)}},t}(ie),oe=[{inputs:[{internalType:"address",name:"_router",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!1,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"ConsumeMarketFee",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"exchangeOwner",type:"address"}],name:"ExchangeActivated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"allowedSwapper",type:"address"}],name:"ExchangeAllowedSwapperChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"baseToken",type:"address"},{indexed:!0,internalType:"address",name:"datatoken",type:"address"},{indexed:!1,internalType:"address",name:"exchangeOwner",type:"address"},{indexed:!1,internalType:"uint256",name:"fixedRate",type:"uint256"}],name:"ExchangeCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"exchangeOwner",type:"address"}],name:"ExchangeDeactivated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"exchangeOwner",type:"address"},{indexed:!1,internalType:"bool",name:"withMint",type:"bool"}],name:"ExchangeMintStateChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"exchangeOwner",type:"address"},{indexed:!1,internalType:"uint256",name:"newRate",type:"uint256"}],name:"ExchangeRateChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"feeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"feeAmount",type:"uint256"}],name:"MarketFeeCollected",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"feeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"feeAmount",type:"uint256"}],name:"OceanFeeCollected",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!1,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"address",name:"newMarketCollector",type:"address"},{indexed:!1,internalType:"uint256",name:"swapFee",type:"uint256"}],name:"PublishMarketFeeChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"oceanFeeAmount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"marketFeeAmount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"tokenFeeAddress",type:"address"}],name:"SWAP_FEES",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"by",type:"address"},{indexed:!1,internalType:"uint256",name:"baseTokenSwappedAmount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"datatokenSwappedAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"tokenOutAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"marketFeeAmount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"oceanFeeAmount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],name:"Swapped",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"TokenCollected",type:"event"},{inputs:[],name:"MAX_FEE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_FEE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_RATE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"datatokenAmount",type:"uint256"},{internalType:"uint256",name:"maxBaseTokenAmount",type:"uint256"},{internalType:"address",name:"consumeMarketAddress",type:"address"},{internalType:"uint256",name:"consumeMarketSwapFeeAmount",type:"uint256"}],name:"buyDT",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"datatokenAmount",type:"uint256"},{internalType:"uint256",name:"consumeMarketSwapFeeAmount",type:"uint256"}],name:"calcBaseInGivenOutDT",outputs:[{internalType:"uint256",name:"baseTokenAmount",type:"uint256"},{internalType:"uint256",name:"oceanFeeAmount",type:"uint256"},{internalType:"uint256",name:"publishMarketFeeAmount",type:"uint256"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"datatokenAmount",type:"uint256"},{internalType:"uint256",name:"consumeMarketSwapFeeAmount",type:"uint256"}],name:"calcBaseOutGivenInDT",outputs:[{internalType:"uint256",name:"baseTokenAmount",type:"uint256"},{internalType:"uint256",name:"oceanFeeAmount",type:"uint256"},{internalType:"uint256",name:"publishMarketFeeAmount",type:"uint256"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"collectBT",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"collectDT",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"collectMarketFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32[]",name:"exchangeId",type:"bytes32[]"}],name:"collectMarketFeeBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"collectOceanFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32[]",name:"exchangeId",type:"bytes32[]"}],name:"collectOceanFeeBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"datatoken",type:"address"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"}],name:"createWithDecimals",outputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"baseToken",type:"address"},{internalType:"address",name:"datatoken",type:"address"}],name:"generateExchangeId",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"getAllowedSwapper",outputs:[{internalType:"address",name:"allowedSwapper",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"getBTSupply",outputs:[{internalType:"uint256",name:"supply",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"getDTSupply",outputs:[{internalType:"uint256",name:"supply",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"getExchange",outputs:[{internalType:"address",name:"exchangeOwner",type:"address"},{internalType:"address",name:"datatoken",type:"address"},{internalType:"uint256",name:"dtDecimals",type:"uint256"},{internalType:"address",name:"baseToken",type:"address"},{internalType:"uint256",name:"btDecimals",type:"uint256"},{internalType:"uint256",name:"fixedRate",type:"uint256"},{internalType:"bool",name:"active",type:"bool"},{internalType:"uint256",name:"dtSupply",type:"uint256"},{internalType:"uint256",name:"btSupply",type:"uint256"},{internalType:"uint256",name:"dtBalance",type:"uint256"},{internalType:"uint256",name:"btBalance",type:"uint256"},{internalType:"bool",name:"withMint",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"getExchanges",outputs:[{internalType:"bytes32[]",name:"",type:"bytes32[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"getFeesInfo",outputs:[{internalType:"uint256",name:"marketFee",type:"uint256"},{internalType:"address",name:"marketFeeCollector",type:"address"},{internalType:"uint256",name:"opcFee",type:"uint256"},{internalType:"uint256",name:"marketFeeAvailable",type:"uint256"},{internalType:"uint256",name:"oceanFeeAvailable",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"getMarketFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getNumberOfExchanges",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"baseTokenAddress",type:"address"}],name:"getOPCFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"getRate",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"isActive",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"isContract",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"router",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"datatokenAmount",type:"uint256"},{internalType:"uint256",name:"minBaseTokenAmount",type:"uint256"},{internalType:"address",name:"consumeMarketAddress",type:"address"},{internalType:"uint256",name:"consumeMarketSwapFeeAmount",type:"uint256"}],name:"sellDT",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"address",name:"newAllowedSwapper",type:"address"}],name:"setAllowedSwapper",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"newRate",type:"uint256"}],name:"setRate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],name:"toggleExchangeState",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"bool",name:"withMint",type:"bool"}],name:"toggleMintState",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"_newMarketFee",type:"uint256"}],name:"updateMarketFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"address",name:"_newMarketCollector",type:"address"}],name:"updateMarketFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"}],ue="0x0000000000000000000000000000000000000000",de=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}I(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return oe},n.generateExchangeId=function(e,t){try{return Promise.resolve(this.contract.generateExchangeId(e,t))}catch(e){return Promise.reject(e)}},n.buyDatatokens=function(e,t,n,r,i,s){void 0===r&&(r=ue),void 0===i&&(i="0");try{var a=this;return Promise.resolve(a.getExchange(e)).then(function(o){return Promise.resolve(a.amountToUnits(null,i,18)).then(function(i){return Promise.resolve(a.amountToUnits(o.datatoken,t,Number(o.dtDecimals))).then(function(t){return Promise.resolve(a.amountToUnits(o.baseToken,n,Number(o.btDecimals))).then(function(n){return Promise.resolve(a.contract.buyDT.estimateGas(e,t,n,r,i)).then(function(o){var u;return s?o:Promise.resolve(V(o,a.getSignerAccordingSdk(),null==(u=a.config)?void 0:u.gasFeeMultiplier,a.contract.buyDT,e,t,n,r,i))})})})})})}catch(e){return Promise.reject(e)}},n.sellDatatokens=function(e,t,n,r,i,s){void 0===r&&(r=ue),void 0===i&&(i="0");try{var a=this;return Promise.resolve(a.getExchange(e)).then(function(o){return Promise.resolve(a.amountToUnits(null,i,18)).then(function(i){return Promise.resolve(a.amountToUnits(o.datatoken,t,Number(o.dtDecimals))).then(function(t){return Promise.resolve(a.amountToUnits(o.baseToken,n,Number(o.btDecimals))).then(function(n){return Promise.resolve(a.contract.sellDT.estimateGas(e,t,n,r,i)).then(function(o){var u;return s?o:Promise.resolve(V(o,a.getSignerAccordingSdk(),null==(u=a.config)?void 0:u.gasFeeMultiplier,a.contract.sellDT,e,t,n,r,i))})})})})})}catch(e){return Promise.reject(e)}},n.getNumberOfExchanges=function(){try{return Promise.resolve(this.contract.getNumberOfExchanges()).then(Number)}catch(e){return Promise.reject(e)}},n.setRate=function(e,t,n){try{var r=this,i=r.contract.setRate,s=i.estimateGas;return Promise.resolve(r.amountToUnits(null,t,18)).then(function(a){return Promise.resolve(s.call(i,e,a)).then(function(i){var s;if(n)return i;var a=r.contract.setRate,o=null==(s=r.config)?void 0:s.gasFeeMultiplier,u=r.getSignerAccordingSdk();return Promise.resolve(r.amountToUnits(null,t,18)).then(function(t){return Promise.resolve(V(i,u,o,a,e,t))})})})}catch(e){return Promise.reject(e)}},n.setAllowedSwapper=function(e,t,n){try{var r=this;return Promise.resolve(r.contract.setAllowedSwapper.estimateGas(e,t)).then(function(i){var s;return n?i:Promise.resolve(V(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.setAllowedSwapper,e,t))})}catch(e){return Promise.reject(e)}},n.activate=function(e,t){try{var n=this;return Promise.resolve(n.getExchange(e)).then(function(r){return r?!0===r.active?null:Promise.resolve(n.contract.toggleExchangeState.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.toggleExchangeState,e))}):null})}catch(e){return Promise.reject(e)}},n.deactivate=function(e,t){try{var n=this;return Promise.resolve(n.getExchange(e)).then(function(r){return r?!1===r.active?null:Promise.resolve(n.contract.toggleExchangeState.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.toggleExchangeState,e))}):null})}catch(e){return Promise.reject(e)}},n.getRate=function(e){try{var t=this;return Promise.resolve(t.contract.getRate(e)).then(function(e){return Promise.resolve(t.unitsToAmount(null,e,18))})}catch(e){return Promise.reject(e)}},n.getDatatokenSupply=function(e){try{var t=this;return Promise.resolve(t.contract.getDTSupply(e)).then(function(n){return Promise.resolve(t.getExchange(e)).then(function(e){return Promise.resolve(t.unitsToAmount(e.datatoken,n,Number(e.dtDecimals)))})})}catch(e){return Promise.reject(e)}},n.getBasetokenSupply=function(e){try{var t=this;return Promise.resolve(t.contract.getBTSupply(e)).then(function(n){return Promise.resolve(t.getExchange(e)).then(function(e){return Promise.resolve(t.unitsToAmount(e.baseToken,n,Number(e.btDecimals)))})})}catch(e){return Promise.reject(e)}},n.getAllowedSwapper=function(e){try{return Promise.resolve(this.contract.getAllowedSwapper(e))}catch(e){return Promise.reject(e)}},n.calcBaseInGivenDatatokensOut=function(e,t,n){void 0===n&&(n="0");try{var r=this;return Promise.resolve(r.getExchange(e)).then(function(i){var s=r.contract,a=s.calcBaseInGivenOutDT;return Promise.resolve(r.amountToUnits(i.datatoken,t,Number(i.dtDecimals))).then(function(t){return Promise.resolve(r.amountToUnits(null,n,18)).then(function(n){return Promise.resolve(a.call(s,e,t,n)).then(function(e){return Promise.resolve(r.unitsToAmount(i.baseToken,e.baseTokenAmount,Number(i.btDecimals))).then(function(t){return Promise.resolve(r.unitsToAmount(i.baseToken,e.publishMarketFeeAmount,Number(i.btDecimals))).then(function(n){return Promise.resolve(r.unitsToAmount(i.baseToken,e.oceanFeeAmount,Number(i.btDecimals))).then(function(s){return Promise.resolve(r.unitsToAmount(i.baseToken,e.consumeMarketFeeAmount,Number(i.btDecimals))).then(function(e){return{baseTokenAmount:t,marketFeeAmount:n,oceanFeeAmount:s,consumeMarketFeeAmount:e}})})})})})})})})}catch(e){return Promise.reject(e)}},n.getAmountBasetokensOut=function(e,t,n){void 0===n&&(n="0");try{var r=this;return Promise.resolve(r.getExchange(e)).then(function(i){var s=r.contract,a=s.calcBaseOutGivenInDT;return Promise.resolve(r.amountToUnits(i.datatoken,t,Number(i.dtDecimals))).then(function(t){return Promise.resolve(r.amountToUnits(null,n,18)).then(function(n){return Promise.resolve(a.call(s,e,t,n)).then(function(e){return Promise.resolve(r.unitsToAmount(i.baseToken,e[0],Number(i.btDecimals)))})})})})}catch(e){return Promise.reject(e)}},n.getExchange=function(e){try{var t=this;return Promise.resolve(t.contract.getExchange(e)).then(function(n){var r=n.btDecimals.toString(),i=n.dtDecimals.toString(),s=n.allowedSwapper,a=n.exchangeOwner,o=n.withMint,u=n.baseToken,d=n.datatoken,c=n.active;return Promise.resolve(t.unitsToAmount(n.datatoken,n.dtBalance,Number(n.dtDecimals))).then(function(l){return Promise.resolve(t.unitsToAmount(n.baseToken,n.btBalance,Number(n.btDecimals))).then(function(p){return Promise.resolve(t.unitsToAmount(n.datatoken,n.dtSupply,Number(n.dtDecimals))).then(function(h){return Promise.resolve(t.unitsToAmount(n.baseToken,n.btSupply,Number(n.btDecimals))).then(function(f){return Promise.resolve(t.unitsToAmount(null,n.fixedRate,18)).then(function(t){return{active:c,datatoken:d,baseToken:u,withMint:o,exchangeOwner:a,allowedSwapper:s,dtDecimals:i,btDecimals:r,dtBalance:l,btBalance:p,dtSupply:h,btSupply:f,fixedRate:t,exchangeId:e}})})})})})})}catch(e){return Promise.reject(e)}},n.getFeesInfo=function(e){try{var t=this;return Promise.resolve(t.contract.getFeesInfo(e)).then(function(n){return Promise.resolve(t.getExchange(e)).then(function(r){return Promise.resolve(t.unitsToAmount(null,n.opcFee.toString(),18)).then(function(i){return Promise.resolve(t.unitsToAmount(null,n.marketFee.toString(),18)).then(function(s){var a=n.marketFeeCollector;return Promise.resolve(t.unitsToAmount(r.baseToken,n.marketFeeAvailable,Number(r.btDecimals))).then(function(o){return Promise.resolve(t.unitsToAmount(r.baseToken,n.oceanFeeAvailable,Number(r.btDecimals))).then(function(t){return{opcFee:i,marketFee:s,marketFeeCollector:a,marketFeeAvailable:o,oceanFeeAvailable:t,exchangeId:e}})})})})})})}catch(e){return Promise.reject(e)}},n.getExchanges=function(){try{return Promise.resolve(this.contract.getExchanges())}catch(e){return Promise.reject(e)}},n.isActive=function(e){try{return Promise.resolve(this.contract.isActive(e))}catch(e){return Promise.reject(e)}},n.activateMint=function(e,t){try{var n=this;return Promise.resolve(n.getExchange(e)).then(function(r){return r?!0===r.withMint?null:Promise.resolve(n.contract.toggleMintState.estimateGas(e,!0)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.toggleMintState,e,!0))}):null})}catch(e){return Promise.reject(e)}},n.deactivateMint=function(e,t){try{var n=this;return Promise.resolve(n.getExchange(e)).then(function(r){return r?!1===r.withMint?null:Promise.resolve(n.contract.toggleMintState.estimateGas(e,!1)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.toggleMintState,e,!1))}):null})}catch(e){return Promise.reject(e)}},n.collectBasetokens=function(e,t,n){try{var r=this;return Promise.resolve(r.getExchange(e)).then(function(i){return i?Promise.resolve(r.contract.getExchange(e)).then(function(i){return Promise.resolve(r.amountToUnits(i.baseToken,t,Number(i.btDecimals))).then(function(t){return Promise.resolve(r.contract.collectBT.estimateGas(e,t)).then(function(i){var s;return n?i:Promise.resolve(V(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.collectBT,e,t))})})}):null})}catch(e){return Promise.reject(e)}},n.collectDatatokens=function(e,t,n){try{var r=this;return Promise.resolve(r.getExchange(e)).then(function(i){return i?Promise.resolve(r.contract.getExchange(e)).then(function(i){return Promise.resolve(r.amountToUnits(i.datatoken,t,Number(i.dtDecimals))).then(function(t){return Promise.resolve(r.contract.collectDT.estimateGas(e,t)).then(function(i){var s;return n?i:Promise.resolve(V(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.collectDT,e,t))})})}):null})}catch(e){return Promise.reject(e)}},n.collectMarketFee=function(e,t){try{var n=this;return Promise.resolve(n.getExchange(e)).then(function(r){return r?Promise.resolve(n.contract.collectMarketFee.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.collectMarketFee,e))}):null})}catch(e){return Promise.reject(e)}},n.collectOceanFee=function(e,t){try{var n=this;return Promise.resolve(n.getExchange(e)).then(function(r){return r?Promise.resolve(n.contract.collectOceanFee.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.collectOceanFee,e))}):null})}catch(e){return Promise.reject(e)}},n.getOPCCollector=function(){try{return Promise.resolve(this.contract.opcCollector())}catch(e){return Promise.reject(e)}},n.getRouter=function(){try{return Promise.resolve(this.contract.router())}catch(e){return Promise.reject(e)}},n.getExchangeOwner=function(e){try{return Promise.resolve(this.getExchange(e)).then(function(e){return e.exchangeOwner})}catch(e){return Promise.reject(e)}},n.updateMarketFee=function(e,t,n){try{var r=this,i=r.contract.updateMarketFee,s=i.estimateGas;return Promise.resolve(r.amountToUnits(null,t,18)).then(function(a){return Promise.resolve(s.call(i,e,a)).then(function(i){var s;if(n)return i;var a=r.contract.updateMarketFee,o=null==(s=r.config)?void 0:s.gasFeeMultiplier,u=r.getSignerAccordingSdk();return Promise.resolve(r.amountToUnits(null,t,18)).then(function(t){return Promise.resolve(V(i,u,o,a,e,t))})})})}catch(e){return Promise.reject(e)}},n.updateMarketFeeCollector=function(e,t,n){try{var r=this;return Promise.resolve(r.contract.updateMarketFeeCollector.estimateGas(e,t)).then(function(i){var s;return n?i:Promise.resolve(V(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.updateMarketFeeCollector,e,t))})}catch(e){return Promise.reject(e)}},t}(ie),ce=[{inputs:[{internalType:"address",name:"_routerOwner",type:"address"},{internalType:"address",name:"_oceanToken",type:"address"},{internalType:"address",name:"_bpoolTemplate",type:"address"},{internalType:"address",name:"_opcCollector",type:"address"},{internalType:"address[]",name:"_preCreatedPools",type:"address[]"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newBPoolAddress",type:"address"},{indexed:!0,internalType:"address",name:"registeredBy",type:"address"},{indexed:!0,internalType:"address",name:"datatokenAddress",type:"address"},{indexed:!1,internalType:"address",name:"baseTokenAddress",type:"address"},{indexed:!1,internalType:"address",name:"bpoolTemplateAddress",type:"address"},{indexed:!1,internalType:"address",name:"ssAddress",type:"address"}],name:"BPoolCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"DispenserContractAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"DispenserContractRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"FactoryContractChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"FixedRateContractAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"FixedRateContractRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"instance",type:"address"}],name:"InstanceDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"poolAddress",type:"address"},{indexed:!1,internalType:"bool",name:"isOcean",type:"bool"}],name:"NewPool",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"_newOpcCollector",type:"address"}],name:"OPCCollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint256",name:"newSwapOceanFee",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newSwapNonOceanFee",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newConsumeFee",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newProviderFee",type:"uint256"}],name:"OPCFeeChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"PoolTemplateAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"PoolTemplateRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"newRouter",type:"address"}],name:"RouterChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"SSContractAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"SSContractRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"}],name:"TokenAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"}],name:"TokenRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint256",name:"minVestingPeriodInBlocks",type:"uint256"}],name:"VestingPeriodChanges",type:"event"},{inputs:[],name:"BONE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"BPOW_PRECISION",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"EXIT_FEE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"INIT_POOL_SUPPLY",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_BOUND_TOKENS",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_BPOW_BASE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_FEE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_IN_RATIO",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_OUT_RATIO",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_TOTAL_WEIGHT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_WEIGHT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_BALANCE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_BOUND_TOKENS",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_BPOW_BASE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_FEE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_WEIGHT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"addApprovedToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"}],name:"addDispenserContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_factory",type:"address"}],name:"addFactory",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_fixedRate",type:"address"}],name:"addFixedRateContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"poolTemplate",type:"address"}],name:"addPoolTemplate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_ssContract",type:"address"}],name:"addSSContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"approvedTokens",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"bytes32",name:"exchangeIds",type:"bytes32"},{internalType:"address",name:"source",type:"address"},{internalType:"enum IFactoryRouter.operationType",name:"operation",type:"uint8"},{internalType:"address",name:"tokenIn",type:"address"},{internalType:"uint256",name:"amountsIn",type:"uint256"},{internalType:"address",name:"tokenOut",type:"address"},{internalType:"uint256",name:"amountsOut",type:"uint256"},{internalType:"uint256",name:"maxPrice",type:"uint256"},{internalType:"uint256",name:"swapMarketFee",type:"uint256"},{internalType:"address",name:"marketFeeAddress",type:"address"}],internalType:"struct IFactoryRouter.Operations[]",name:"_operations",type:"tuple[]"}],name:"buyDTBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_routerOwner",type:"address"}],name:"changeRouterOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"consumeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"},{internalType:"address",name:"datatoken",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"allowedSwapper",type:"address"}],name:"deployDispenser",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"fixedPriceAddress",type:"address"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"}],name:"deployFixedRate",outputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address[2]",name:"tokens",type:"address[2]"},{internalType:"uint256[]",name:"ssParams",type:"uint256[]"},{internalType:"uint256[]",name:"swapFees",type:"uint256[]"},{internalType:"address[]",name:"addresses",type:"address[]"}],name:"deployPool",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"dispensers",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"fixedRate",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"fixedrates",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getApprovedTokens",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getDispensersContracts",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFixedRatesContracts",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getMinVestingPeriod",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getOPCCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getOPCConsumeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"baseToken",type:"address"}],name:"getOPCFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getOPCFees",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getOPCProviderFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getPoolTemplates",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getSSContracts",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"isApprovedToken",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"}],name:"isDispenserContract",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_fixedRate",type:"address"}],name:"isFixedRateContract",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"poolTemplate",type:"address"}],name:"isPoolTemplate",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_ssContract",type:"address"}],name:"isSSContract",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"minVestingPeriodInBlocks",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"opcCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"poolTemplates",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"providerFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"removeApprovedToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"}],name:"removeDispenserContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_fixedRate",type:"address"}],name:"removeFixedRateContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"poolTemplate",type:"address"}],name:"removePoolTemplate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_ssContract",type:"address"}],name:"removeSSContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"routerOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"ssContracts",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"address",name:"poolAddress",type:"address"},{internalType:"uint256",name:"tokenAmountIn",type:"uint256"},{internalType:"uint256",name:"minPoolAmountOut",type:"uint256"}],internalType:"struct IFactoryRouter.Stakes[]",name:"_stakes",type:"tuple[]"}],name:"stakeBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"swapNonOceanFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"swapOceanFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_newPeriod",type:"uint256"}],name:"updateMinVestingPeriod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_opcCollector",type:"address"}],name:"updateOPCCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_newSwapOceanFee",type:"uint256"},{internalType:"uint256",name:"_newSwapNonOceanFee",type:"uint256"},{internalType:"uint256",name:"_newConsumeFee",type:"uint256"},{internalType:"uint256",name:"_newProviderFee",type:"uint256"}],name:"updateOPCFee",outputs:[],stateMutability:"nonpayable",type:"function"}],le=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}I(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return ce},n.buyDatatokenBatch=function(e,t){try{var n=this;return Promise.resolve(n.contract.buyDTBatch.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.buyDTBatch,e))})}catch(e){return Promise.reject(e)}},n.isApprovedToken=function(e){try{return Promise.resolve(this.contract.isApprovedToken(e))}catch(e){return Promise.reject(e)}},n.isFixedPrice=function(e){try{return Promise.resolve(this.contract.isFixedRateContract(e))}catch(e){return Promise.reject(e)}},n.getOwner=function(){try{return Promise.resolve(this.contract.routerOwner())}catch(e){return Promise.reject(e)}},n.getNFTFactory=function(){try{return Promise.resolve(this.contract.factory())}catch(e){return Promise.reject(e)}},n.addApprovedToken=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(r.contract.addApprovedToken.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.addApprovedToken,t))})})}catch(e){return Promise.reject(e)}},n.removeApprovedToken=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(r.contract.removeApprovedToken.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.removeApprovedToken,t))})})}catch(e){return Promise.reject(e)}},n.addFixedRateContract=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(r.contract.addFixedRateContract.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.addFixedRateContract,t))})})}catch(e){return Promise.reject(e)}},n.removeFixedRateContract=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(r.contract.removeFixedRateContract.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.removeFixedRateContract,t))})})}catch(e){return Promise.reject(e)}},n.addDispenserContract=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(r.contract.addDispenserContract.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.addDispenserContract,t))})})}catch(e){return Promise.reject(e)}},n.removeDispenserContract=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(r.contract.removeDispenserContract.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.removeDispenserContract,t))})})}catch(e){return Promise.reject(e)}},n.getOPCFee=function(e){try{return Promise.resolve(this.contract.getOPCFee(e)).then(Number)}catch(e){return Promise.reject(e)}},n.getCurrentOPCFee=function(){try{return Promise.resolve(this.contract.swapOceanFee()).then(Number)}catch(e){return Promise.reject(e)}},n.updateOPCFee=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getOwner()).then(function(o){if(o!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(a.contract.updateOPCFee.estimateGas(t,n,r,i)).then(function(e){var o;return s?e:Promise.resolve(V(e,a.getSignerAccordingSdk(),null==(o=a.config)?void 0:o.gasFeeMultiplier,a.contract.updateOPCFee,t,n,r,i))})})}catch(e){return Promise.reject(e)}},t}(ie),pe=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedMinter",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedPaymentManager",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"CleanedPermissions",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"consumeMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],name:"ConsumeMarketFee",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"currentMinter",type:"address"},{indexed:!1,internalType:"address",name:"newMinter",type:"address"}],name:"MinterApproved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"currentMinter",type:"address"},{indexed:!1,internalType:"address",name:"newMinter",type:"address"}],name:"MinterProposed",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"dispenserContract",type:"address"}],name:"NewDispenser",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"address",name:"exchangeContract",type:"address"},{indexed:!0,internalType:"address",name:"baseToken",type:"address"}],name:"NewFixedRate",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"_newPaymentCollector",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"NewPaymentCollector",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"poolAddress",type:"address"},{indexed:!1,internalType:"address",name:"ssContract",type:"address"},{indexed:!1,internalType:"address",name:"baseTokenAddress",type:"address"}],name:"NewPool",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"providerAddress",type:"address"},{indexed:!0,internalType:"address",name:"consumerAddress",type:"address"},{indexed:!1,internalType:"bytes32",name:"orderTxId",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"providerData",type:"bytes"},{indexed:!1,internalType:"bytes",name:"providerSignature",type:"bytes"},{indexed:!1,internalType:"bytes",name:"consumerData",type:"bytes"},{indexed:!1,internalType:"bytes",name:"consumerSignature",type:"bytes"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"OrderExecuted",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"bytes32",name:"orderTxId",type:"bytes32"},{indexed:!1,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"number",type:"uint256"}],name:"OrderReused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"consumer",type:"address"},{indexed:!1,internalType:"address",name:"payer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"serviceIndex",type:"uint256"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!0,internalType:"address",name:"publishMarketAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"OrderStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"providerFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"providerFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{indexed:!1,internalType:"bytes",name:"providerData",type:"bytes"},{indexed:!1,internalType:"uint8",name:"v",type:"uint8"},{indexed:!1,internalType:"bytes32",name:"r",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"s",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"validUntil",type:"uint256"}],name:"ProviderFee",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"PublishMarketFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"PublishMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"PublishMarketFeeAmount",type:"uint256"}],name:"PublishMarketFee",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"address",name:"PublishMarketFeeAddress",type:"address"},{indexed:!1,internalType:"address",name:"PublishMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"PublishMarketFeeAmount",type:"uint256"}],name:"PublishMarketFeeChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedMinter",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedPaymentManager",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"datatokenAddress",type:"address"},{indexed:!0,internalType:"address",name:"publisherAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"vestingEndBlock",type:"uint256"},{indexed:!1,internalType:"uint256",name:"totalVestingAmount",type:"uint256"}],name:"VestingCreated",type:"event"},{stateMutability:"payable",type:"fallback"},{inputs:[],name:"BASE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"DOMAIN_SEPARATOR",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PERMIT_TYPEHASH",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_minter",type:"address"}],name:"addMinter",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_paymentManager",type:"address"}],name:"addPaymentManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"authERC20",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"}],name:"burn",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"burnFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cap",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"cleanFrom721",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cleanPermissions",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"bool",name:"withMint",type:"bool"},{internalType:"address",name:"allowedSwapper",type:"address"}],name:"createDispenser",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"fixedPriceAddress",type:"address"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"}],name:"createFixedRate",outputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"subtractedValue",type:"uint256"}],name:"decreaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"ssParams",type:"uint256[]"},{internalType:"uint256[]",name:"swapFees",type:"uint256[]"},{internalType:"address[]",name:"addresses",type:"address[]"}],name:"deployPool",outputs:[{internalType:"address",name:"pool",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"getDispensers",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getERC721Address",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFixedRates",outputs:[{components:[{internalType:"address",name:"contractAddress",type:"address"},{internalType:"bytes32",name:"id",type:"bytes32"}],internalType:"struct ERC20Template.fixedRate[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getPaymentCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getPermissions",outputs:[{components:[{internalType:"bool",name:"minter",type:"bool"},{internalType:"bool",name:"paymentManager",type:"bool"}],internalType:"struct ERC20Roles.RolesERC20",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getPools",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getPublishingMarketFee",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"addedValue",type:"uint256"}],name:"increaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string[]",name:"strings_",type:"string[]"},{internalType:"address[]",name:"addresses_",type:"address[]"},{internalType:"address[]",name:"factoryAddresses_",type:"address[]"},{internalType:"uint256[]",name:"uints_",type:"uint256[]"},{internalType:"bytes[]",name:"bytes_",type:"bytes[]"}],name:"initialize",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"isERC20Deployer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"isInitialized",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isMinter",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"mint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"nonces",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderTxId",type:"bytes32"},{internalType:"bytes",name:"providerData",type:"bytes"},{internalType:"bytes",name:"providerSignature",type:"bytes"},{internalType:"bytes",name:"consumerData",type:"bytes"},{internalType:"bytes",name:"consumerSignature",type:"bytes"},{internalType:"address",name:"consumerAddress",type:"address"}],name:"orderExecuted",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"permissions",outputs:[{internalType:"bool",name:"minter",type:"bool"},{internalType:"bool",name:"paymentManager",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_minter",type:"address"}],name:"removeMinter",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_paymentManager",type:"address"}],name:"removePaymentManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderTxId",type:"bytes32"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20Template.providerFee",name:"_providerFee",type:"tuple"}],name:"reuseOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"router",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_value",type:"bytes"}],name:"setData",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newPaymentCollector",type:"address"}],name:"setPaymentCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_publishMarketFeeAddress",type:"address"},{internalType:"address",name:"_publishMarketFeeToken",type:"address"},{internalType:"uint256",name:"_publishMarketFeeAmount",type:"uint256"}],name:"setPublishingMarketFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20Template.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct ERC20Template.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],name:"startOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"withdrawETH",outputs:[],stateMutability:"payable",type:"function"},{stateMutability:"payable",type:"receive"}],he={_format:"hh-sol-artifact-1",contractName:"ERC20TemplateEnterprise",sourceName:"contracts/templates/ERC20TemplateEnterprise.sol",abi:[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedMinter",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedPaymentManager",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"CleanedPermissions",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"consumeMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],name:"ConsumeMarketFee",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"currentMinter",type:"address"},{indexed:!1,internalType:"address",name:"newMinter",type:"address"}],name:"MinterApproved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"currentMinter",type:"address"},{indexed:!1,internalType:"address",name:"newMinter",type:"address"}],name:"MinterProposed",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"dispenserContract",type:"address"}],name:"NewDispenser",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"address",name:"exchangeContract",type:"address"},{indexed:!0,internalType:"address",name:"baseToken",type:"address"}],name:"NewFixedRate",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"_newPaymentCollector",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"NewPaymentCollector",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"providerAddress",type:"address"},{indexed:!0,internalType:"address",name:"consumerAddress",type:"address"},{indexed:!1,internalType:"bytes32",name:"orderTxId",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"providerData",type:"bytes"},{indexed:!1,internalType:"bytes",name:"providerSignature",type:"bytes"},{indexed:!1,internalType:"bytes",name:"consumerData",type:"bytes"},{indexed:!1,internalType:"bytes",name:"consumerSignature",type:"bytes"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"OrderExecuted",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"bytes32",name:"orderTxId",type:"bytes32"},{indexed:!1,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"number",type:"uint256"}],name:"OrderReused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"consumer",type:"address"},{indexed:!1,internalType:"address",name:"payer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"serviceIndex",type:"uint256"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!0,internalType:"address",name:"publishMarketAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"OrderStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"providerFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"providerFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{indexed:!1,internalType:"bytes",name:"providerData",type:"bytes"},{indexed:!1,internalType:"uint8",name:"v",type:"uint8"},{indexed:!1,internalType:"bytes32",name:"r",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"s",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"validUntil",type:"uint256"}],name:"ProviderFee",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"PublishMarketFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"PublishMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"PublishMarketFeeAmount",type:"uint256"}],name:"PublishMarketFee",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"address",name:"PublishMarketFeeAddress",type:"address"},{indexed:!1,internalType:"address",name:"PublishMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"PublishMarketFeeAmount",type:"uint256"}],name:"PublishMarketFeeChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedMinter",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedPaymentManager",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{stateMutability:"payable",type:"fallback"},{inputs:[],name:"BASE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"DOMAIN_SEPARATOR",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PERMIT_TYPEHASH",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_minter",type:"address"}],name:"addMinter",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_paymentManager",type:"address"}],name:"addPaymentManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"authERC20",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"}],name:"burn",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"burnFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20TemplateEnterprise.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct ERC20TemplateEnterprise.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],internalType:"struct ERC20TemplateEnterprise.OrderParams",name:"_orderParams",type:"tuple"},{internalType:"address",name:"dispenserContract",type:"address"}],name:"buyFromDispenserAndOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20TemplateEnterprise.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct ERC20TemplateEnterprise.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],internalType:"struct ERC20TemplateEnterprise.OrderParams",name:"_orderParams",type:"tuple"},{components:[{internalType:"address",name:"exchangeContract",type:"address"},{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"maxBaseTokenAmount",type:"uint256"},{internalType:"uint256",name:"swapMarketFee",type:"uint256"},{internalType:"address",name:"marketFeeAddress",type:"address"}],internalType:"struct ERC20TemplateEnterprise.FreParams",name:"_freParams",type:"tuple"}],name:"buyFromFreAndOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cap",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"cleanFrom721",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cleanPermissions",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"bool",name:"withMint",type:"bool"},{internalType:"address",name:"",type:"address"}],name:"createDispenser",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"fixedPriceAddress",type:"address"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"}],name:"createFixedRate",outputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"subtractedValue",type:"uint256"}],name:"decreaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"getDispensers",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getERC721Address",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFixedRates",outputs:[{components:[{internalType:"address",name:"contractAddress",type:"address"},{internalType:"bytes32",name:"id",type:"bytes32"}],internalType:"struct ERC20TemplateEnterprise.fixedRate[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getPaymentCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getPermissions",outputs:[{components:[{internalType:"bool",name:"minter",type:"bool"},{internalType:"bool",name:"paymentManager",type:"bool"}],internalType:"struct ERC20Roles.RolesERC20",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getPublishingMarketFee",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"addedValue",type:"uint256"}],name:"increaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string[]",name:"strings_",type:"string[]"},{internalType:"address[]",name:"addresses_",type:"address[]"},{internalType:"address[]",name:"factoryAddresses_",type:"address[]"},{internalType:"uint256[]",name:"uints_",type:"uint256[]"},{internalType:"bytes[]",name:"bytes_",type:"bytes[]"}],name:"initialize",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"isERC20Deployer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"isInitialized",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isMinter",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"mint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"nonces",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderTxId",type:"bytes32"},{internalType:"bytes",name:"providerData",type:"bytes"},{internalType:"bytes",name:"providerSignature",type:"bytes"},{internalType:"bytes",name:"consumerData",type:"bytes"},{internalType:"bytes",name:"consumerSignature",type:"bytes"},{internalType:"address",name:"consumerAddress",type:"address"}],name:"orderExecuted",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"permissions",outputs:[{internalType:"bool",name:"minter",type:"bool"},{internalType:"bool",name:"paymentManager",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_minter",type:"address"}],name:"removeMinter",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_paymentManager",type:"address"}],name:"removePaymentManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderTxId",type:"bytes32"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20TemplateEnterprise.providerFee",name:"_providerFee",type:"tuple"}],name:"reuseOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"router",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_value",type:"bytes"}],name:"setData",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newPaymentCollector",type:"address"}],name:"setPaymentCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_publishMarketFeeAddress",type:"address"},{internalType:"address",name:"_publishMarketFeeToken",type:"address"},{internalType:"uint256",name:"_publishMarketFeeAmount",type:"uint256"}],name:"setPublishingMarketFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20TemplateEnterprise.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct ERC20TemplateEnterprise.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],name:"startOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"withdrawETH",outputs:[],stateMutability:"payable",type:"function"},{stateMutability:"payable",type:"receive"}],bytecode:"0x6080604052600b805460ff191690553480156200001b57600080fd5b5060408051808201825260048152631d195cdd60e21b60208083019182528351808501909452600a8452691d195cdd14de5b589bdb60b21b9084015281519192916200006a916003916200008e565b508051620000809060049060208401906200008e565b505060016007555062000171565b8280546200009c9062000134565b90600052602060002090601f016020900481019282620000c057600085556200010b565b82601f10620000db57805160ff19168380011785556200010b565b828001600101855582156200010b579182015b828111156200010b578251825591602001919060010190620000ee565b50620001199291506200011d565b5090565b5b808211156200011957600081556001016200011e565b600181811c908216806200014957607f821691505b602082108114156200016b57634e487b7160e01b600052602260045260246000fd5b50919050565b615dcf80620001816000396000f3fe6080604052600436106102c65760003560e01c80635d1ca6311161017e578063a8c09b0b116100d3578063d505accf1161008f578063e487c2e81161006c578063e487c2e814610988578063ec342ad01461099d578063ef867ff4146109b9578063f887ea40146109d957005b8063d505accf14610940578063dd62ed3e14610960578063e086e5ec1461098057005b8063a8c09b0b14610867578063a9059cbb14610887578063aa271e1a146108a7578063aa492ef9146108e0578063ab62f0e114610900578063b3998be01461092057005b806382c03da51161013a57806395d89b411161011757806395d89b41146107f257806396fb3eaf14610807578063983b2d5614610827578063a457c2d71461084757005b806382c03da51461079d57806389208f0f146107b25780638b96412b146107d257005b80635d1ca631146106c457806370a08231146106d857806379cc67901461070e57806379d9d7f31461072e5780637dda231e1461074e5780637ecebe001461077057005b8063313ce56711610234578063397b3743116101f057806347ac7d55116101cd57806347ac7d551461064d5780634f189cb21461066f57806357a3a31b1461068457806357ad5ff6146106a457005b8063397b3743146105d157806340c10f191461060d57806342966c681461062d57005b8063313ce5671461052c578063355274ea1461054e578063361fef49146105635780633644e51514610583578063392e53cd1461059957806339509351146105b157005b8063191c918a11610283578063191c918a146104585780631b53b05f1461047857806323b872dd1461049857806325b00243146104b85780633092afd5146104d857806330adf81f146104f857005b80627ffb78146102cf57806301e882081461030b57806306fdde031461035b578063095ea7b31461037d578063160a7925146103ad57806318160ddd1461043957005b366102cd57005b005b3480156102db57600080fd5b50600b5461010090046001600160a01b03165b6040516001600160a01b0390911681526020015b60405180910390f35b34801561031757600080fd5b50610344610326366004614d5e565b60056020526000908152604090205460ff8082169161010090041682565b604080519215158352901515602083015201610302565b34801561036757600080fd5b506103706109f9565b6040516103029190614da7565b34801561038957600080fd5b5061039d610398366004614dda565b610a8b565b6040519015158152602001610302565b3480156103b957600080fd5b5061041a6103c8366004614d5e565b6040805180820190915260008082526020820152506001600160a01b031660009081526005602090815260409182902082518084019093525460ff808216151584526101009091041615159082015290565b6040805182511515815260209283015115159281019290925201610302565b34801561044557600080fd5b506002545b604051908152602001610302565b34801561046457600080fd5b506102cd610473366004614e14565b610aa5565b34801561048457600080fd5b506102cd610493366004614e8b565b610cea565b3480156104a457600080fd5b5061039d6104b3366004614edc565b610dfd565b3480156104c457600080fd5b506102cd6104d3366004614d5e565b610e23565b3480156104e457600080fd5b506102cd6104f3366004614d5e565b610f42565b34801561050457600080fd5b5061044a7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b34801561053857600080fd5b5060125b60405160ff9091168152602001610302565b34801561055a57600080fd5b50600a5461044a565b34801561056f57600080fd5b506102cd61057e366004614f30565b61105e565b34801561058f57600080fd5b5061044a60105481565b3480156105a557600080fd5b50600b5460ff1661039d565b3480156105bd57600080fd5b5061039d6105cc366004614dda565b6110ab565b3480156105dd57600080fd5b50600d54600e54600f54604080516001600160a01b03948516815293909216602084015290820152606001610302565b34801561061957600080fd5b506102cd610628366004614dda565b6110cd565b34801561063957600080fd5b506102cd610648366004614f76565b61119a565b34801561065957600080fd5b506106626111a4565b6040516103029190614fd3565b34801561067b57600080fd5b506102cd611205565b34801561069057600080fd5b506102cd61069f366004614d5e565b6112e0565b3480156106b057600080fd5b506102cd6106bf366004614edc565b6114a7565b3480156106d057600080fd5b50600261053c565b3480156106e457600080fd5b5061044a6106f3366004614d5e565b6001600160a01b031660009081526020819052604090205490565b34801561071a57600080fd5b506102cd610729366004614dda565b611660565b34801561073a57600080fd5b506102cd610749366004614fe6565b611675565b34801561075a57600080fd5b506107636118ee565b6040516103029190615059565b34801561077c57600080fd5b5061044a61078b366004614d5e565b60116020526000908152604090205481565b3480156107a957600080fd5b506102cd611963565b3480156107be57600080fd5b506102cd6107cd3660046150f9565b6119c2565b3480156107de57600080fd5b5061044a6107ed3660046152aa565b611caf565b3480156107fe57600080fd5b50610370611fd7565b34801561081357600080fd5b5061039d610822366004614d5e565b611fe6565b34801561083357600080fd5b506102cd610842366004614d5e565b612064565b34801561085357600080fd5b5061039d610862366004614dda565b612180565b34801561087357600080fd5b506102cd61088236600461537f565b612206565b34801561089357600080fd5b5061039d6108a2366004614dda565b612673565b3480156108b357600080fd5b5061039d6108c2366004614d5e565b6001600160a01b031660009081526005602052604090205460ff1690565b3480156108ec57600080fd5b506102cd6108fb366004614d5e565b612681565b34801561090c57600080fd5b506102cd61091b3660046153d8565b61279d565b34801561092c57600080fd5b5061039d61093b36600461545d565b612958565b34801561094c57600080fd5b506102cd61095b36600461555e565b612a8b565b34801561096c57600080fd5b5061044a61097b3660046155cc565b612c9d565b6102cd612cc8565b34801561099457600080fd5b506102ee612d08565b3480156109a957600080fd5b5061044a670de0b6b3a764000081565b3480156109c557600080fd5b506102ee6109d4366004614f76565b612da1565b3480156109e557600080fd5b506012546102ee906001600160a01b031681565b606060088054610a08906155fa565b80601f0160208091040260200160405190810160405280929190818152602001828054610a34906155fa565b8015610a815780601f10610a5657610100808354040283529160200191610a81565b820191906000526020600020905b815481529060010190602001808311610a6457829003601f168201915b5050505050905090565b600033610a99818585612dcb565b60019150505b92915050565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa158015610af1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b15919061562f565b6020015180610b9c5750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015610b6d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b9191906156b3565b6001600160a01b0316145b610bc15760405162461bcd60e51b8152600401610bb8906156d0565b60405180910390fd5b610bc9612ef0565b8115610bd857610bd885612f4a565b601480546001810182556000919091527fce6d7b5282bd9a3661ae061feed1dbda4e52ab073b1f9285be6e155d9c38d4ec0180546001600160a01b0319166001600160a01b0387169081179091556040519081527fa31ffd41531537eb31bfd827a3f5372b5f62bf4dd8579e5354b280dc58490e709060200160405180910390a1601254604051636b14d00560e11b81526001600160a01b0387811660048301523060248301819052604483018890526064830187905233608484015260a48301529091169063d629a00a9060c401600060405180830381600087803b158015610cc157600080fd5b505af1158015610cd5573d6000803e3d6000fd5b50505050610ce36001600755565b5050505050565b610cf2612ef0565b604051631d746d8360e01b8152306004820152670de0b6b3a764000060248201819052336044830152906001600160a01b03831690631d746d8390606401600060405180830381600087803b158015610d4a57600080fd5b505af1158015610d5e573d6000803e3d6000fd5b50503360009081526020819052604090205483925090501015610dc35760405162461bcd60e51b815260206004820152601f60248201527f556e61626c6520746f206765742044542066726f6d2044697370656e736572006044820152606401610bb8565b610dee610dd36020850185614d5e565b6020850135610de56040870187615705565b86606001611675565b50610df96001600755565b5050565b600033610e0b858285613021565b610e1685858561309b565b60019150505b9392505050565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa158015610e6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e93919061562f565b6020015180610f1a5750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015610eeb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f0f91906156b3565b6001600160a01b0316145b610f365760405162461bcd60e51b8152600401610bb8906156d0565b610f3f8161323f565b50565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa158015610f8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fb2919061562f565b60200151806110395750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa15801561100a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061102e91906156b3565b6001600160a01b0316145b6110555760405162461bcd60e51b8152600401610bb8906156d0565b610f3f816132b1565b60408051838152336020820152428183015243606082015290517f526e31449ea46e2aecf9b480c8d7dfa191348ef74ffdf75b445a6ab726daa6ff9181900360800190a1610df981613311565b600033610a998185856110be8383612c9d565b6110c8919061573b565b612dcb565b3360009081526005602052604090205460ff1661112c5760405162461bcd60e51b815260206004820152601960248201527f455243323054656d706c6174653a204e4f54204d494e544552000000000000006044820152606401610bb8565b600a546111428261113c60025490565b90613723565b11156111905760405162461bcd60e51b815260206004820152601f60248201527f44617461746f6b656e54656d706c6174653a20636170206578636565646564006044820152606401610bb8565b610df9828261372f565b610f3f33826137ee565b60606014805480602002602001604051908101604052809291908181526020018280548015610a8157602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116111de575050505050905090565b600b546040516331a9108f60e11b8152600160048201526101009091046001600160a01b031690636352211e90602401602060405180830381865afa158015611252573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061127691906156b3565b6001600160a01b0316336001600160a01b0316146112d65760405162461bcd60e51b815260206004820152601b60248201527f455243323054656d706c6174653a206e6f74204e46544f776e657200000000006044820152606401610bb8565b6112de61391d565b565b33600090815260056020526040902054610100900460ff16806113735750600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa15801561134a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061136e919061562f565b602001515b806113f65750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa1580156113c7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113eb91906156b3565b6001600160a01b0316145b6114565760405162461bcd60e51b815260206004820152602b60248201527f455243323054656d706c6174653a204e4f54205041594d454e54204d414e414760448201526a22a91037b91027aba722a960a91b6064820152608401610bb8565b61145f81613df8565b604080514281524360208201526001600160a01b0383169133917f4d7694d695c57cc54947177c8e8a0e61aae664e9223492a798c32fadfc6419cc910160405180910390a350565b600d546001600160a01b031633146115145760405162461bcd60e51b815260206004820152602a60248201527f455243323054656d706c6174653a206e6f74207075626c6973684d61726b65746044820152694665654164647265737360b01b6064820152608401610bb8565b6001600160a01b03831661157b5760405162461bcd60e51b815260206004820152602860248201527f496e76616c6964205f7075626c6973684d61726b657446656541646472657373604482015267206164647265737360c01b6064820152608401610bb8565b6001600160a01b0382166115e05760405162461bcd60e51b815260206004820152602660248201527f496e76616c6964205f7075626c6973684d61726b6574466565546f6b656e206160448201526564647265737360d01b6064820152608401610bb8565b600d80546001600160a01b038581166001600160a01b03199283168117909355600e8054918616919092168117909155600f839055604080513381526020810193909352820152606081018290527f02ab4b3fc023109c2d0da394bda239166c833f63c42b71b67ed4b836dca0ddfe9060800160405180910390a1505050565b61166b823383613021565b610df982826137ee565b33600090815260208190526040902054670de0b6b3a7640000908111156116ea5760405162461bcd60e51b8152602060048201526024808201527f4e6f7420656e6f7567682064617461746f6b656e7320746f207374617274204f604482015263393232b960e11b6064820152608401610bb8565b600d5460408051338152602081018490529081018690524260608201524360808201526001600160a01b03918216918716907fe1c4fa794edfa8f619b8257a077398950357b9c6398528f94480307352f9afcc9060a00160405180910390a36000600f541180156117655750600e546001600160a01b031615155b801561177b5750600d546001600160a01b031615155b156117f057600e54600d54600f546117a3926001600160a01b03908116923392911690613e1a565b600e54600d54600f546040519081526001600160a01b0392831692909116907f4049a448ac6f0284a98d2cb9199e73605944ea5bec901a037f88c84703de82b29060200160405180910390a35b6000826040013511801561181d575060006118116040840160208501614d5e565b6001600160a01b031614155b801561183f575060006118336020840184614d5e565b6001600160a01b031614155b156118dc5761186f6118576040840160208501614d5e565b336118656020860186614d5e565b8560400135613e1a565b61187f6040830160208401614d5e565b6001600160a01b03166118956020840184614d5e565b6001600160a01b03167f6d11837f46cc09b011cf4aae09fcade046c020aac088090ae4f77ff67b70797284604001356040516118d391815260200190565b60405180910390a35b6118e583613311565b610ce38161119a565b60606013805480602002602001604051908101604052809291908181526020016000905b8282101561195a576000848152602090819020604080518082019091526002850290910180546001600160a01b03168252600190810154828401529083529092019101611912565b50505050905090565b600b5461010090046001600160a01b031633146112d65760405162461bcd60e51b815260206004820152601f60248201527f455243323054656d706c6174653a204e4f542037323120436f6e7472616374006044820152606401610bb8565b336001600160a01b0382161415611a1b5760405162461bcd60e51b815260206004820152601f60248201527f50726f76696465722063616e6e6f742062652074686520636f6e73756d6572006044820152606401610bb8565b60006040518060400160405280601c81526020017f19457468657265756d205369676e6564204d6573736167653a0a33320000000081525090506000818c8c8c604051602001611a6d93929190615753565b60405160208183030381529060405280519060200120604051602001611a9492919061576d565b604051602081830303815290604052805190602001209050336001600160a01b0316611af6828b8b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250613f6192505050565b6001600160a01b031614611b4c5760405162461bcd60e51b815260206004820152601f60248201527f50726f7669646572207369676e617475726520636865636b206661696c6564006044820152606401610bb8565b6000828888604051602001611b6292919061578f565b60405160208183030381529060405280519060200120604051602001611b8992919061576d565b604051602081830303815290604052805190602001209050836001600160a01b0316611beb8288888080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250613f6192505050565b6001600160a01b031614611c415760405162461bcd60e51b815260206004820152601f60248201527f436f6e73756d6572207369676e617475726520636865636b206661696c6564006044820152606401610bb8565b836001600160a01b0316336001600160a01b03167fc9a10280e9c735c63092fa5431e6acb3ed342e08b69a083e5e676994eb7070f98f8f8f8f8f8f8f8f8f4243604051611c989b9a999897969594939291906157c8565b60405180910390a350505050505050505050505050565b600b5460405163160a792560e01b815233600482015260009161010090046001600160a01b03169063160a792590602401608060405180830381865afa158015611cfd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d21919061562f565b6020015180611da85750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015611d79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d9d91906156b3565b6001600160a01b0316145b611dc45760405162461bcd60e51b8152600401610bb8906156d0565b611dcc612ef0565b3083600381518110611de057611de061583a565b60200260200101906001600160a01b031690816001600160a01b031681525050600082600481518110611e1557611e1561583a565b60200260200101511115611e2c57611e2c84612f4a565b601254604051638244937560e01b81526001600160a01b0390911690638244937590611e6090879087908790600401615850565b6020604051808303816000875af1158015611e7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ea391906158b6565b905082600081518110611eb857611eb861583a565b60200260200101516001600160a01b031683600181518110611edc57611edc61583a565b60200260200101516001600160a01b03167fb3fac3ae95956dbac74e63ba8dac94081832395c8788e3049c900a7732f348058387604051611f309291909182526001600160a01b0316602082015260400190565b60405180910390a3604080518082019091526001600160a01b03858116825260208201838152601380546001808201835560009290925293517f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a090600290950294850180546001600160a01b0319169190941617909255517f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a09190920191909155600755610e1c565b606060098054610a08906155fa565b600b5460405163160a792560e01b81526001600160a01b0383811660048301526000926101009004169063160a792590602401608060405180830381865afa158015612036573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061205a919061562f565b6020015192915050565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa1580156120b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120d4919061562f565b602001518061215b5750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa15801561212c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061215091906156b3565b6001600160a01b0316145b6121775760405162461bcd60e51b8152600401610bb8906156d0565b610f3f81612f4a565b6000338161218e8286612c9d565b9050838110156121ee5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610bb8565b6121fb8286868403612dcb565b506001949350505050565b61220e612ef0565b600061221d6020830183614d5e565b604051634c87087d60e01b81526020840135600482015290915060009081906001600160a01b03841690634c87087d9060240161018060405180830381865afa15801561226e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061229291906158cf565b5050505050505050935050925050306001600160a01b0316826001600160a01b0316146123115760405162461bcd60e51b815260206004820152602760248201527f5468697320466978656452617465206973206e6f742070726f766964696e67206044820152661d1a1a5cc8111560ca1b6064820152608401610bb8565b604051636e8de4b560e11b815260208501356004820152670de0b6b3a76400006024820152606085013560448201526000906001600160a01b0385169063dd1bc96a90606401608060405180830381865afa158015612374573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612398919061598c565b505050905084604001358111156124015760405162461bcd60e51b815260206004820152602760248201527f46697865645261746545786368616e67653a20546f6f206d616e79206261736560448201526620746f6b656e7360c81b6064820152608401610bb8565b61240d82333084613e1a565b61242e61241d6020870187614d5e565b6001600160a01b0384169083614039565b6001600160a01b0384166368c4b7e96020870135670de0b6b3a76400008461245c60a08b0160808c01614d5e565b6040516001600160e01b031960e087901b1681526004810194909452602484019290925260448301526001600160a01b031660648201526060880135608482015260a401600060405180830381600087803b1580156124ba57600080fd5b505af11580156124ce573d6000803e3d6000fd5b505030600090815260208190526040902054670de0b6b3a764000092509050101561253b5760405162461bcd60e51b815260206004820152601f60248201527f556e61626c6520746f206275792044542066726f6d20466978656452617465006044820152606401610bb8565b61254e3033670de0b6b3a764000061309b565b61257961255e6020880188614d5e565b602088013561257060408a018a615705565b89606001611675565b604051634c87087d60e01b8152602086013560048201526000906001600160a01b03861690634c87087d9060240161018060405180830381865afa1580156125c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125e991906158cf565b509a5050505050505050505050600081111561266457604051637997ca3b60e11b815260208701356004820152602481018290526001600160a01b0386169063f32f947690604401600060405180830381600087803b15801561264b57600080fd5b505af115801561265f573d6000803e3d6000fd5b505050505b5050505050610df96001600755565b600033610a9981858561309b565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa1580156126cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126f1919061562f565b60200151806127785750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015612749573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061276d91906156b3565b6001600160a01b0316145b6127945760405162461bcd60e51b8152600401610bb8906156d0565b610f3f81614119565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa1580156127e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061280d919061562f565b60200151806128945750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015612865573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061288991906156b3565b6001600160a01b0316145b6128b05760405162461bcd60e51b8152600401610bb8906156d0565b6040516bffffffffffffffffffffffff193060601b16602082015260009060340160408051808303601f19018152908290528051602090910120600b546301caf8fd60e31b835290925061010090046001600160a01b031690630e57c7e890612921908490879087906004016159c2565b600060405180830381600087803b15801561293b57600080fd5b505af115801561294f573d6000803e3d6000fd5b50505050505050565b600b5460009060ff16156129c85760405162461bcd60e51b815260206004820152603160248201527f455243323054656d706c6174653a20746f6b656e20696e7374616e636520616c6044820152701c9958591e481a5b9a5d1a585b1a5e9959607a1b6064820152608401610bb8565b612a7c6129d58b8d615a3c565b8a8a8080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525050604080516020808e0282810182019093528d82529093508d92508c91829185019084908082843760009201919091525050604080516020808d0282810182019093528c82529093508c92508b918291850190849080828437600092019190915250612a7792508991508a9050615ac3565b6141fa565b9b9a5050505050505050505050565b43841015612ace5760405162461bcd60e51b815260206004820152601060248201526f115490cc8c11150e881156141254915160821b6044820152606401610bb8565b6010546001600160a01b038816600090815260116020526040812080549192917f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9918b918b918b919087612b2183615b3e565b909155506040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810187905260e00160405160208183030381529060405280519060200120604051602001612b9a92919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa158015612c05573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615801590612c3b5750886001600160a01b0316816001600160a01b0316145b612c875760405162461bcd60e51b815260206004820152601a60248201527f455243323044543a20494e56414c49445f5349474e41545552450000000000006044820152606401610bb8565b612c92898989612dcb565b505050505050505050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b612cd0612d08565b6001600160a01b03166108fc479081150290604051600060405180830381858888f19350505050158015610f3f573d6000803e3d6000fd5b600c546000906001600160a01b0316612d9157600b546040516331a9108f60e11b8152600160048201526101009091046001600160a01b031690636352211e90602401602060405180830381865afa158015612d68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d8c91906156b3565b905090565b50600c546001600160a01b031690565b60068181548110612db157600080fd5b6000918252602090912001546001600160a01b0316905081565b6001600160a01b038316612e2d5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610bb8565b6001600160a01b038216612e8e5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610bb8565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b60026007541415612f435760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610bb8565b6002600755565b6001600160a01b03811615610f3f576001600160a01b0381166000908152600560205260409020805460ff1615612fc35760405162461bcd60e51b815260206004820152601d60248201527f4552433230526f6c65733a2020414c52454144592041204d494e5445520000006044820152606401610bb8565b805460ff19166001178155612fd7826146e4565b6040805142815243602082015233916001600160a01b038516917f4f7e100eb1ee13e903798bd0d6aa854152e07eb05544f392b9409c12935c809591015b60405180910390a35050565b600061302d8484612c9d565b9050600019811461309557818110156130885760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610bb8565b6130958484848403612dcb565b50505050565b6001600160a01b0383166130ff5760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610bb8565b6001600160a01b0382166131615760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610bb8565b6001600160a01b038316600090815260208190526040902054818110156131d95760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610bb8565b6001600160a01b03848116600081815260208181526040808320878703905593871680835291849020805487019055925185815290927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3613095565b6001600160a01b03811660008181526005602052604090819020805461ff00191681559051909133917faee911eec8b2df8f3ae0464841541b1e5f339519bd5cf51889fe8b07fecff658906132a09042904390918252602082015260400190565b60405180910390a3610df98261479b565b6001600160a01b03811660008181526005602052604090819020805460ff191681559051909133917fefa2735987005aaa89c050c0ff8cc9ae7d9079d19382081c429130f98c52d480906132a09042904390918252602082015260400190565b60408051808201909152601c81527f19457468657265756d205369676e6564204d6573736167653a0a333200000000602082015260008161335560e0850185615b59565b6133626020870187614d5e565b6133726040880160208901614d5e565b87604001358860c0013560405160200161339196959493929190615b9f565b604051602081830303815290604052805190602001206040516020016133b892919061576d565b60408051601f198184030181529190528051602090910120905060006001826133e76080870160608801615bdd565b6040805160008152602081018083529390935260ff90911690820152608080870135606083015260a08088013591830191909152016020604051602081039080840390855afa15801561343e573d6000803e3d6000fd5b5050604051601f190151915061345990506020850185614d5e565b6001600160a01b0316816001600160a01b0316146134b05760405162461bcd60e51b8152602060048201526014602482015273496e76616c69642070726f76696465722066656560601b6044820152606401610bb8565b6134c06040850160208601614d5e565b6001600160a01b03166134d66020860186614d5e565b6001600160a01b03167ff8ed11cdaaf10eca2b6c941fb802cb8682afe86cac1eb93f70d0780fa062c544604087013561351260e0890189615b59565b61352260808b0160608c01615bdd565b8a608001358b60a001358c60c001356040516135449796959493929190615bf8565b60405180910390a3600084604001351180156135795750600061356d6040860160208701614d5e565b6001600160a01b031614155b801561359b5750600061358f6020860186614d5e565b6001600160a01b031614155b156130955760125460408051636c45e88160e01b815290516000926001600160a01b031691636c45e8819160048083019260209291908290030181865afa1580156135ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061360e91906158b6565b90506000811561363b57613638670de0b6b3a76400006136326040890135856148e9565b906148f5565b90505b600061364b604088013583614901565b905061366c6136606040890160208a01614d5e565b33308a60400135613e1a565b61369d61367c6020890189614d5e565b8261368d60408b0160208c01614d5e565b6001600160a01b0316919061490d565b811561294f5760125460408051631a81876d60e01b8152905161294f926001600160a01b031691631a81876d9160048083019260209291908290030181865afa1580156136ee573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061371291906156b3565b8361368d60408b0160208c01614d5e565b6000610e1c828461573b565b6001600160a01b0382166137855760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610bb8565b8060026000828254613797919061573b565b90915550506001600160a01b038216600081815260208181526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b6001600160a01b03821661384e5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610bb8565b6001600160a01b038216600090815260208190526040902054818110156138c25760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610bb8565b6001600160a01b0383166000818152602081815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9101612ee3565b505050565b60145460135460009161392f9161573b565b9050600080826001600160401b0381111561394c5761394c6151d6565b604051908082528060200260200182016040528015613975578160200160208202803683370190505b50905060005b601354811015613c5b5760006013828154811061399a5761399a61583a565b60009182526020822060029091020154601380546001600160a01b039092169350829182918591634c87087d9190889081106139d8576139d861583a565b9060005260206000209060020201600101546040518263ffffffff1660e01b8152600401613a0891815260200190565b61018060405180830381865afa158015613a26573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a4a91906158cf565b9b509b509b505050505050505050506000821115613af057836001600160a01b031663f32f947660138781548110613a8457613a8461583a565b906000526020600020906002020160010154846040518363ffffffff1660e01b8152600401613abd929190918252602082015260400190565b600060405180830381600087803b158015613ad757600080fd5b505af1158015613aeb573d6000803e3d6000fd5b505050505b8215613b8457836001600160a01b031663c612e48a60138781548110613b1857613b1861583a565b906000526020600020906002020160010154856040518363ffffffff1660e01b8152600401613b51929190918252602082015260400190565b600060405180830381600087803b158015613b6b57600080fd5b505af1158015613b7f573d6000803e3d6000fd5b505050505b613bc760138681548110613b9a57613b9a61583a565b600091825260208083206002909202909101546001600160a01b0316825260059052604090205460ff1690565b8015613bd557506001811515145b15613c445760138581548110613bed57613bed61583a565b600091825260209091206002909102015486516001600160a01b0390911690879089908110613c1e57613c1e61583a565b6001600160a01b039092166020928302919091019091015286613c4081615b3e565b9750505b505050508080613c5390615b3e565b91505061397b565b5060005b601454811015613da05760148181548110613c7c57613c7c61583a565b60009182526020909120015460405163f9bfaa7d60e01b81523060048201526001600160a01b039091169063f9bfaa7d90602401600060405180830381600087803b158015613cca57600080fd5b505af1158015613cde573d6000803e3d6000fd5b50505050613d2060148281548110613cf857613cf861583a565b60009182526020808320909101546001600160a01b0316825260059052604090205460ff1690565b15613d8e5760148181548110613d3857613d3861583a565b9060005260206000200160009054906101000a90046001600160a01b0316828481518110613d6857613d6861583a565b6001600160a01b039092166020928302919091019091015282613d8a81615b3e565b9350505b80613d9881615b3e565b915050613c5f565b613da861493d565b50600c80546001600160a01b031916905560005b8281101561309557613de6828281518110613dd957613dd961583a565b6020026020010151612f4a565b80613df081615b3e565b915050613dbc565b600c80546001600160a01b0319166001600160a01b0392909216919091179055565b6040516370a0823160e01b81526001600160a01b038381166004830152600091908616906370a0823190602401602060405180830381865afa158015613e64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613e8891906158b6565b9050613e9f6001600160a01b0386168585856149ec565b613ea98183613723565b6040516370a0823160e01b81526001600160a01b0385811660048301528716906370a0823190602401602060405180830381865afa158015613eef573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f1391906158b6565b1015610ce35760405162461bcd60e51b815260206004820152601a60248201527f5472616e7366657220616d6f756e7420697320746f6f206c6f770000000000006044820152606401610bb8565b6000806000808451604114613f7c5760009350505050610a9f565b50505060208201516040830151604184015160ff16601b811015613fa857613fa5601b82615c3b565b90505b8060ff16601b14158015613fc057508060ff16601c14155b15613fd15760009350505050610a9f565b60408051600081526020810180835288905260ff831691810191909152606081018490526080810183905260019060a0016020604051602081039080840390855afa158015614024573d6000803e3d6000fd5b5050604051601f190151979650505050505050565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015614089573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140ad91906158b6565b90506130958463095ea7b360e01b856140c6868661573b565b6040516001600160a01b03909216602483015260448201526064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614a24565b6001600160a01b03811615610f3f576001600160a01b03811660009081526005602052604090208054610100900460ff16156141a25760405162461bcd60e51b815260206004820152602260248201527f4552433230526f6c65733a2020414c5245414459204120464545204d414e414760448201526122a960f11b6064820152608401610bb8565b805461ff0019166101001781556141b8826146e4565b6040805142815243602082015233916001600160a01b038516917fb17da2e9910b4ba5754e8872385ba315a238bafb5ae221fc85093c33432c40a79101613015565b600080846000815181106142105761421061583a565b602002602001015190508460018151811061422d5761422d61583a565b6020908102919091010151601280546001600160a01b0319166001600160a01b0392831617905581166142b75760405162461bcd60e51b815260206004820152602c60248201527f455243323054656d706c6174653a20496e76616c6964206d696e7465722c202060448201526b7a65726f206164647265737360a01b6064820152608401610bb8565b6012546001600160a01b03166143235760405162461bcd60e51b815260206004820152602b60248201527f455243323054656d706c6174653a20496e76616c696420726f757465722c207a60448201526a65726f206164647265737360a81b6064820152608401610bb8565b836000815181106143365761433661583a565b60200260200101516000141561439a5760405162461bcd60e51b8152602060048201526024808201527f44617461746f6b656e54656d706c6174653a20496e76616c6964206361702076604482015263616c756560e01b6064820152608401610bb8565b836000815181106143ad576143ad61583a565b6020026020010151600a81905550866000815181106143ce576143ce61583a565b6020026020010151600890805190602001906143eb929190614c86565b50866001815181106143ff576143ff61583a565b60200260200101516009908051906020019061441c929190614c86565b50600b805460ff196001600160a01b03841661010002166001600160a81b0319909116176001179055855161445c908790600090613dd957613dd961583a565b60006001600160a01b03168660018151811061447a5761447a61583a565b60200260200101516001600160a01b031614614524576144b3866001815181106144a6576144a661583a565b6020026020010151613df8565b856001815181106144c6576144c661583a565b60200260200101516001600160a01b0316336001600160a01b03167f4d7694d695c57cc54947177c8e8a0e61aae664e9223492a798c32fadfc6419cc424360405161451b929190918252602082015260400190565b60405180910390a35b856002815181106145375761453761583a565b6020026020010151600d60006101000a8154816001600160a01b0302191690836001600160a01b03160217905550856003815181106145785761457861583a565b6020026020010151600e60006101000a8154816001600160a01b0302191690836001600160a01b03160217905550836001815181106145b9576145b961583a565b602090810291909101810151600f819055600d54600e54604080513381526001600160a01b039384169581019590955291169083015260608201527f02ab4b3fc023109c2d0da394bda239166c833f63c42b71b67ed4b836dca0ddfe9060800160405180910390a160405146907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f9061465490600890615c60565b60408051918290038220828201825260018352603160f81b6020938401528151928301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc66060820152608081018290523060a082015260c00160408051808303601f1901815291905280516020909101206010555050600b5460ff169695505050505050565b60005b60065481101561474057816001600160a01b03166006828154811061470e5761470e61583a565b6000918252602090912001546001600160a01b0316141561472e57614740565b8061473881615b3e565b9150506146e7565b600654811415610df957600680546001810182556000919091527ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f0180546001600160a01b0384166001600160a01b03199091161790555050565b6001600160a01b0381166000908152600560205260409020805460ff161580156147cc57508054610100900460ff16155b15610df95760005b60065481101561482d57826001600160a01b0316600682815481106147fb576147fb61583a565b6000918252602090912001546001600160a01b0316141561481b5761482d565b8061482581615b3e565b9150506147d4565b600654811015613918576006805461484790600190615cfc565b815481106148575761485761583a565b600091825260209091200154600680546001600160a01b0390921691839081106148835761488361583a565b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060068054806148c2576148c2615d13565b600082815260209020810160001990810180546001600160a01b0319169055019055505050565b6000610e1c8284615d29565b6000610e1c8284615d48565b6000610e1c8284615cfc565b6040516001600160a01b03831660248201526044810182905261391890849063a9059cbb60e01b906064016140e2565b60005b6006548110156149a357600060056000600684815481106149635761496361583a565b60009182526020808320909101546001600160a01b031683528201929092526040019020805461ffff19169055508061499b81615b3e565b915050614940565b506149b060066000614d0a565b6040805142815243602082015233917f712bc71db81927a76b8bf1ea346247bb0ad58f18e4e5c1bd4aa0ec6573e02a2b910160405180910390a2565b6040516001600160a01b03808516602483015283166044820152606481018290526130959085906323b872dd60e01b906084016140e2565b6000614a79826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614af99092919063ffffffff16565b9050805160001480614a9a575080806020019051810190614a9a9190615d6a565b6139185760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610bb8565b6060614b088484600085614b10565b949350505050565b606082471015614b715760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610bb8565b600080866001600160a01b03168587604051614b8d9190615d87565b60006040518083038185875af1925050503d8060008114614bca576040519150601f19603f3d011682016040523d82523d6000602084013e614bcf565b606091505b5091509150614be087838387614beb565b979650505050505050565b60608315614c57578251614c50576001600160a01b0385163b614c505760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610bb8565b5081614b08565b614b088383815115614c6c5781518083602001fd5b8060405162461bcd60e51b8152600401610bb89190614da7565b828054614c92906155fa565b90600052602060002090601f016020900481019282614cb45760008555614cfa565b82601f10614ccd57805160ff1916838001178555614cfa565b82800160010185558215614cfa579182015b82811115614cfa578251825591602001919060010190614cdf565b50614d06929150614d24565b5090565b5080546000825590600052602060002090810190610f3f91905b5b80821115614d065760008155600101614d25565b6001600160a01b0381168114610f3f57600080fd5b8035614d5981614d39565b919050565b600060208284031215614d7057600080fd5b8135610e1c81614d39565b60005b83811015614d96578181015183820152602001614d7e565b838111156130955750506000910152565b6020815260008251806020840152614dc6816040850160208701614d7b565b601f01601f19169190910160400192915050565b60008060408385031215614ded57600080fd5b8235614df881614d39565b946020939093013593505050565b8015158114610f3f57600080fd5b600080600080600060a08688031215614e2c57600080fd5b8535614e3781614d39565b945060208601359350604086013592506060860135614e5581614e06565b91506080860135614e6581614d39565b809150509295509295909350565b600060c08284031215614e8557600080fd5b50919050565b60008060408385031215614e9e57600080fd5b82356001600160401b03811115614eb457600080fd5b614ec085828601614e73565b9250506020830135614ed181614d39565b809150509250929050565b600080600060608486031215614ef157600080fd5b8335614efc81614d39565b92506020840135614f0c81614d39565b929592945050506040919091013590565b60006101008284031215614e8557600080fd5b60008060408385031215614f4357600080fd5b8235915060208301356001600160401b03811115614f6057600080fd5b614f6c85828601614f1d565b9150509250929050565b600060208284031215614f8857600080fd5b5035919050565b600081518084526020808501945080840160005b83811015614fc85781516001600160a01b031687529582019590820190600101614fa3565b509495945050505050565b602081526000610e1c6020830184614f8f565b60008060008084860360c0811215614ffd57600080fd5b853561500881614d39565b94506020860135935060408601356001600160401b0381111561502a57600080fd5b61503688828901614f1d565b9350506060605f198201121561504b57600080fd5b509295919450926060019150565b602080825282518282018190526000919060409081850190868401855b828110156150a457815180516001600160a01b03168552860151868501529284019290850190600101615076565b5091979650505050505050565b60008083601f8401126150c357600080fd5b5081356001600160401b038111156150da57600080fd5b6020830191508360208285010111156150f257600080fd5b9250929050565b60008060008060008060008060008060c08b8d03121561511857600080fd5b8a35995060208b01356001600160401b038082111561513657600080fd5b6151428e838f016150b1565b909b50995060408d013591508082111561515b57600080fd5b6151678e838f016150b1565b909950975060608d013591508082111561518057600080fd5b61518c8e838f016150b1565b909750955060808d01359150808211156151a557600080fd5b506151b28d828e016150b1565b90945092506151c5905060a08c01614d4e565b90509295989b9194979a5092959850565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715615214576152146151d6565b604052919050565b60006001600160401b03821115615235576152356151d6565b5060051b60200190565b600082601f83011261525057600080fd5b813560206152656152608361521c565b6151ec565b82815260059290921b8401810191818101908684111561528457600080fd5b8286015b8481101561529f5780358352918301918301615288565b509695505050505050565b6000806000606084860312156152bf57600080fd5b83356152ca81614d39565b92506020848101356001600160401b03808211156152e757600080fd5b818701915087601f8301126152fb57600080fd5b81356153096152608261521c565b81815260059190911b8301840190848101908a83111561532857600080fd5b938501935b8285101561534f57843561534081614d39565b8252938501939085019061532d565b96505050604087013592508083111561536757600080fd5b50506153758682870161523f565b9150509250925092565b60008082840360c081121561539357600080fd5b83356001600160401b038111156153a957600080fd5b6153b586828701614e73565b93505060a0601f19820112156153ca57600080fd5b506020830190509250929050565b600080602083850312156153eb57600080fd5b82356001600160401b0381111561540157600080fd5b61540d858286016150b1565b90969095509350505050565b60008083601f84011261542b57600080fd5b5081356001600160401b0381111561544257600080fd5b6020830191508360208260051b85010111156150f257600080fd5b60008060008060008060008060008060a08b8d03121561547c57600080fd5b8a356001600160401b038082111561549357600080fd5b61549f8e838f01615419565b909c509a5060208d01359150808211156154b857600080fd5b6154c48e838f01615419565b909a50985060408d01359150808211156154dd57600080fd5b6154e98e838f01615419565b909850965060608d013591508082111561550257600080fd5b61550e8e838f01615419565b909650945060808d013591508082111561552757600080fd5b506155348d828e01615419565b915080935050809150509295989b9194979a5092959850565b803560ff81168114614d5957600080fd5b600080600080600080600060e0888a03121561557957600080fd5b873561558481614d39565b9650602088013561559481614d39565b955060408801359450606088013593506155b06080890161554d565b925060a0880135915060c0880135905092959891949750929550565b600080604083850312156155df57600080fd5b82356155ea81614d39565b91506020830135614ed181614d39565b600181811c9082168061560e57607f821691505b60208210811415614e8557634e487b7160e01b600052602260045260246000fd5b60006080828403121561564157600080fd5b604051608081018181106001600160401b0382111715615663576156636151d6565b604052825161567181614e06565b8152602083015161568181614e06565b6020820152604083015161569481614e06565b604082015260608301516156a781614e06565b60608201529392505050565b6000602082840312156156c557600080fd5b8151610e1c81614d39565b6020808252818101527f455243323054656d706c6174653a204e4f54204445504c4f59455220524f4c45604082015260600190565b6000823560fe1983360301811261571b57600080fd5b9190910192915050565b634e487b7160e01b600052601160045260246000fd5b6000821982111561574e5761574e615725565b500190565b838152818360208301376000910160200190815292915050565b6000835161577f818460208801614d7b565b9190910191825250602001919050565b8183823760009101908152919050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b8b815260e0602082015260006157e260e083018c8e61579f565b82810360408401526157f5818b8d61579f565b9050828103606084015261580a81898b61579f565b9050828103608084015261581f81878961579f565b60a0840195909552505060c001529998505050505050505050565b634e487b7160e01b600052603260045260246000fd5b6001600160a01b03841681526060602080830182905260009161587590840186614f8f565b838103604085015284518082528286019183019060005b818110156158a85783518352928401929184019160010161588c565b509098975050505050505050565b6000602082840312156158c857600080fd5b5051919050565b6000806000806000806000806000806000806101808d8f0312156158f257600080fd5b8c516158fd81614d39565b60208e0151909c5061590e81614d39565b60408e015160608f0151919c509a5061592681614d39565b8099505060808d0151975060a08d0151965060c08d015161594681614e06565b8096505060e08d015194506101008d015193506101208d015192506101408d015191506101608d015161597881614e06565b809150509295989b509295989b509295989b565b600080600080608085870312156159a257600080fd5b505082516020840151604085015160609095015191969095509092509050565b8381526040602082015260006159dc60408301848661579f565b95945050505050565b60006001600160401b038311156159fe576159fe6151d6565b615a11601f8401601f19166020016151ec565b9050828152838383011115615a2557600080fd5b828260208301376000602084830101529392505050565b6000615a4a6152608461521c565b80848252602080830192508560051b850136811115615a6857600080fd5b855b81811015615ab75780356001600160401b03811115615a895760008081fd5b870136601f820112615a9b5760008081fd5b615aa93682358684016159e5565b865250938201938201615a6a565b50919695505050505050565b6000615ad16152608461521c565b80848252602080830192508560051b850136811115615aef57600080fd5b855b81811015615ab75780356001600160401b03811115615b105760008081fd5b870136601f820112615b225760008081fd5b615b303682358684016159e5565b865250938201938201615af1565b6000600019821415615b5257615b52615725565b5060010190565b6000808335601e19843603018112615b7057600080fd5b8301803591506001600160401b03821115615b8a57600080fd5b6020019150368190038213156150f257600080fd5b858782376bffffffffffffffffffffffff19606095861b8116969091019586529290931b909116601484015260288301526048820152606801919050565b600060208284031215615bef57600080fd5b610e1c8261554d565b87815260c060208201526000615c1260c08301888a61579f565b905060ff861660408301528460608301528360808301528260a083015298975050505050505050565b600060ff821660ff84168060ff03821115615c5857615c58615725565b019392505050565b600080835481600182811c915080831680615c7c57607f831692505b6020808410821415615c9c57634e487b7160e01b86526022600452602486fd5b818015615cb05760018114615cc157615cee565b60ff19861689528489019650615cee565b60008a81526020902060005b86811015615ce65781548b820152908501908301615ccd565b505084890196505b509498975050505050505050565b600082821015615d0e57615d0e615725565b500390565b634e487b7160e01b600052603160045260246000fd5b6000816000190483118215151615615d4357615d43615725565b500290565b600082615d6557634e487b7160e01b600052601260045260246000fd5b500490565b600060208284031215615d7c57600080fd5b8151610e1c81614e06565b6000825161571b818460208701614d7b56fea264697066735822122033f2af53437addf43f15eb1acb2e4001ce9ebf429ce8fdd59580fd7feae2079564736f6c634300080c0033",deployedBytecode:"0x6080604052600436106102c65760003560e01c80635d1ca6311161017e578063a8c09b0b116100d3578063d505accf1161008f578063e487c2e81161006c578063e487c2e814610988578063ec342ad01461099d578063ef867ff4146109b9578063f887ea40146109d957005b8063d505accf14610940578063dd62ed3e14610960578063e086e5ec1461098057005b8063a8c09b0b14610867578063a9059cbb14610887578063aa271e1a146108a7578063aa492ef9146108e0578063ab62f0e114610900578063b3998be01461092057005b806382c03da51161013a57806395d89b411161011757806395d89b41146107f257806396fb3eaf14610807578063983b2d5614610827578063a457c2d71461084757005b806382c03da51461079d57806389208f0f146107b25780638b96412b146107d257005b80635d1ca631146106c457806370a08231146106d857806379cc67901461070e57806379d9d7f31461072e5780637dda231e1461074e5780637ecebe001461077057005b8063313ce56711610234578063397b3743116101f057806347ac7d55116101cd57806347ac7d551461064d5780634f189cb21461066f57806357a3a31b1461068457806357ad5ff6146106a457005b8063397b3743146105d157806340c10f191461060d57806342966c681461062d57005b8063313ce5671461052c578063355274ea1461054e578063361fef49146105635780633644e51514610583578063392e53cd1461059957806339509351146105b157005b8063191c918a11610283578063191c918a146104585780631b53b05f1461047857806323b872dd1461049857806325b00243146104b85780633092afd5146104d857806330adf81f146104f857005b80627ffb78146102cf57806301e882081461030b57806306fdde031461035b578063095ea7b31461037d578063160a7925146103ad57806318160ddd1461043957005b366102cd57005b005b3480156102db57600080fd5b50600b5461010090046001600160a01b03165b6040516001600160a01b0390911681526020015b60405180910390f35b34801561031757600080fd5b50610344610326366004614d5e565b60056020526000908152604090205460ff8082169161010090041682565b604080519215158352901515602083015201610302565b34801561036757600080fd5b506103706109f9565b6040516103029190614da7565b34801561038957600080fd5b5061039d610398366004614dda565b610a8b565b6040519015158152602001610302565b3480156103b957600080fd5b5061041a6103c8366004614d5e565b6040805180820190915260008082526020820152506001600160a01b031660009081526005602090815260409182902082518084019093525460ff808216151584526101009091041615159082015290565b6040805182511515815260209283015115159281019290925201610302565b34801561044557600080fd5b506002545b604051908152602001610302565b34801561046457600080fd5b506102cd610473366004614e14565b610aa5565b34801561048457600080fd5b506102cd610493366004614e8b565b610cea565b3480156104a457600080fd5b5061039d6104b3366004614edc565b610dfd565b3480156104c457600080fd5b506102cd6104d3366004614d5e565b610e23565b3480156104e457600080fd5b506102cd6104f3366004614d5e565b610f42565b34801561050457600080fd5b5061044a7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b34801561053857600080fd5b5060125b60405160ff9091168152602001610302565b34801561055a57600080fd5b50600a5461044a565b34801561056f57600080fd5b506102cd61057e366004614f30565b61105e565b34801561058f57600080fd5b5061044a60105481565b3480156105a557600080fd5b50600b5460ff1661039d565b3480156105bd57600080fd5b5061039d6105cc366004614dda565b6110ab565b3480156105dd57600080fd5b50600d54600e54600f54604080516001600160a01b03948516815293909216602084015290820152606001610302565b34801561061957600080fd5b506102cd610628366004614dda565b6110cd565b34801561063957600080fd5b506102cd610648366004614f76565b61119a565b34801561065957600080fd5b506106626111a4565b6040516103029190614fd3565b34801561067b57600080fd5b506102cd611205565b34801561069057600080fd5b506102cd61069f366004614d5e565b6112e0565b3480156106b057600080fd5b506102cd6106bf366004614edc565b6114a7565b3480156106d057600080fd5b50600261053c565b3480156106e457600080fd5b5061044a6106f3366004614d5e565b6001600160a01b031660009081526020819052604090205490565b34801561071a57600080fd5b506102cd610729366004614dda565b611660565b34801561073a57600080fd5b506102cd610749366004614fe6565b611675565b34801561075a57600080fd5b506107636118ee565b6040516103029190615059565b34801561077c57600080fd5b5061044a61078b366004614d5e565b60116020526000908152604090205481565b3480156107a957600080fd5b506102cd611963565b3480156107be57600080fd5b506102cd6107cd3660046150f9565b6119c2565b3480156107de57600080fd5b5061044a6107ed3660046152aa565b611caf565b3480156107fe57600080fd5b50610370611fd7565b34801561081357600080fd5b5061039d610822366004614d5e565b611fe6565b34801561083357600080fd5b506102cd610842366004614d5e565b612064565b34801561085357600080fd5b5061039d610862366004614dda565b612180565b34801561087357600080fd5b506102cd61088236600461537f565b612206565b34801561089357600080fd5b5061039d6108a2366004614dda565b612673565b3480156108b357600080fd5b5061039d6108c2366004614d5e565b6001600160a01b031660009081526005602052604090205460ff1690565b3480156108ec57600080fd5b506102cd6108fb366004614d5e565b612681565b34801561090c57600080fd5b506102cd61091b3660046153d8565b61279d565b34801561092c57600080fd5b5061039d61093b36600461545d565b612958565b34801561094c57600080fd5b506102cd61095b36600461555e565b612a8b565b34801561096c57600080fd5b5061044a61097b3660046155cc565b612c9d565b6102cd612cc8565b34801561099457600080fd5b506102ee612d08565b3480156109a957600080fd5b5061044a670de0b6b3a764000081565b3480156109c557600080fd5b506102ee6109d4366004614f76565b612da1565b3480156109e557600080fd5b506012546102ee906001600160a01b031681565b606060088054610a08906155fa565b80601f0160208091040260200160405190810160405280929190818152602001828054610a34906155fa565b8015610a815780601f10610a5657610100808354040283529160200191610a81565b820191906000526020600020905b815481529060010190602001808311610a6457829003601f168201915b5050505050905090565b600033610a99818585612dcb565b60019150505b92915050565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa158015610af1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b15919061562f565b6020015180610b9c5750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015610b6d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b9191906156b3565b6001600160a01b0316145b610bc15760405162461bcd60e51b8152600401610bb8906156d0565b60405180910390fd5b610bc9612ef0565b8115610bd857610bd885612f4a565b601480546001810182556000919091527fce6d7b5282bd9a3661ae061feed1dbda4e52ab073b1f9285be6e155d9c38d4ec0180546001600160a01b0319166001600160a01b0387169081179091556040519081527fa31ffd41531537eb31bfd827a3f5372b5f62bf4dd8579e5354b280dc58490e709060200160405180910390a1601254604051636b14d00560e11b81526001600160a01b0387811660048301523060248301819052604483018890526064830187905233608484015260a48301529091169063d629a00a9060c401600060405180830381600087803b158015610cc157600080fd5b505af1158015610cd5573d6000803e3d6000fd5b50505050610ce36001600755565b5050505050565b610cf2612ef0565b604051631d746d8360e01b8152306004820152670de0b6b3a764000060248201819052336044830152906001600160a01b03831690631d746d8390606401600060405180830381600087803b158015610d4a57600080fd5b505af1158015610d5e573d6000803e3d6000fd5b50503360009081526020819052604090205483925090501015610dc35760405162461bcd60e51b815260206004820152601f60248201527f556e61626c6520746f206765742044542066726f6d2044697370656e736572006044820152606401610bb8565b610dee610dd36020850185614d5e565b6020850135610de56040870187615705565b86606001611675565b50610df96001600755565b5050565b600033610e0b858285613021565b610e1685858561309b565b60019150505b9392505050565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa158015610e6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e93919061562f565b6020015180610f1a5750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015610eeb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f0f91906156b3565b6001600160a01b0316145b610f365760405162461bcd60e51b8152600401610bb8906156d0565b610f3f8161323f565b50565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa158015610f8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fb2919061562f565b60200151806110395750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa15801561100a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061102e91906156b3565b6001600160a01b0316145b6110555760405162461bcd60e51b8152600401610bb8906156d0565b610f3f816132b1565b60408051838152336020820152428183015243606082015290517f526e31449ea46e2aecf9b480c8d7dfa191348ef74ffdf75b445a6ab726daa6ff9181900360800190a1610df981613311565b600033610a998185856110be8383612c9d565b6110c8919061573b565b612dcb565b3360009081526005602052604090205460ff1661112c5760405162461bcd60e51b815260206004820152601960248201527f455243323054656d706c6174653a204e4f54204d494e544552000000000000006044820152606401610bb8565b600a546111428261113c60025490565b90613723565b11156111905760405162461bcd60e51b815260206004820152601f60248201527f44617461746f6b656e54656d706c6174653a20636170206578636565646564006044820152606401610bb8565b610df9828261372f565b610f3f33826137ee565b60606014805480602002602001604051908101604052809291908181526020018280548015610a8157602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116111de575050505050905090565b600b546040516331a9108f60e11b8152600160048201526101009091046001600160a01b031690636352211e90602401602060405180830381865afa158015611252573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061127691906156b3565b6001600160a01b0316336001600160a01b0316146112d65760405162461bcd60e51b815260206004820152601b60248201527f455243323054656d706c6174653a206e6f74204e46544f776e657200000000006044820152606401610bb8565b6112de61391d565b565b33600090815260056020526040902054610100900460ff16806113735750600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa15801561134a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061136e919061562f565b602001515b806113f65750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa1580156113c7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113eb91906156b3565b6001600160a01b0316145b6114565760405162461bcd60e51b815260206004820152602b60248201527f455243323054656d706c6174653a204e4f54205041594d454e54204d414e414760448201526a22a91037b91027aba722a960a91b6064820152608401610bb8565b61145f81613df8565b604080514281524360208201526001600160a01b0383169133917f4d7694d695c57cc54947177c8e8a0e61aae664e9223492a798c32fadfc6419cc910160405180910390a350565b600d546001600160a01b031633146115145760405162461bcd60e51b815260206004820152602a60248201527f455243323054656d706c6174653a206e6f74207075626c6973684d61726b65746044820152694665654164647265737360b01b6064820152608401610bb8565b6001600160a01b03831661157b5760405162461bcd60e51b815260206004820152602860248201527f496e76616c6964205f7075626c6973684d61726b657446656541646472657373604482015267206164647265737360c01b6064820152608401610bb8565b6001600160a01b0382166115e05760405162461bcd60e51b815260206004820152602660248201527f496e76616c6964205f7075626c6973684d61726b6574466565546f6b656e206160448201526564647265737360d01b6064820152608401610bb8565b600d80546001600160a01b038581166001600160a01b03199283168117909355600e8054918616919092168117909155600f839055604080513381526020810193909352820152606081018290527f02ab4b3fc023109c2d0da394bda239166c833f63c42b71b67ed4b836dca0ddfe9060800160405180910390a1505050565b61166b823383613021565b610df982826137ee565b33600090815260208190526040902054670de0b6b3a7640000908111156116ea5760405162461bcd60e51b8152602060048201526024808201527f4e6f7420656e6f7567682064617461746f6b656e7320746f207374617274204f604482015263393232b960e11b6064820152608401610bb8565b600d5460408051338152602081018490529081018690524260608201524360808201526001600160a01b03918216918716907fe1c4fa794edfa8f619b8257a077398950357b9c6398528f94480307352f9afcc9060a00160405180910390a36000600f541180156117655750600e546001600160a01b031615155b801561177b5750600d546001600160a01b031615155b156117f057600e54600d54600f546117a3926001600160a01b03908116923392911690613e1a565b600e54600d54600f546040519081526001600160a01b0392831692909116907f4049a448ac6f0284a98d2cb9199e73605944ea5bec901a037f88c84703de82b29060200160405180910390a35b6000826040013511801561181d575060006118116040840160208501614d5e565b6001600160a01b031614155b801561183f575060006118336020840184614d5e565b6001600160a01b031614155b156118dc5761186f6118576040840160208501614d5e565b336118656020860186614d5e565b8560400135613e1a565b61187f6040830160208401614d5e565b6001600160a01b03166118956020840184614d5e565b6001600160a01b03167f6d11837f46cc09b011cf4aae09fcade046c020aac088090ae4f77ff67b70797284604001356040516118d391815260200190565b60405180910390a35b6118e583613311565b610ce38161119a565b60606013805480602002602001604051908101604052809291908181526020016000905b8282101561195a576000848152602090819020604080518082019091526002850290910180546001600160a01b03168252600190810154828401529083529092019101611912565b50505050905090565b600b5461010090046001600160a01b031633146112d65760405162461bcd60e51b815260206004820152601f60248201527f455243323054656d706c6174653a204e4f542037323120436f6e7472616374006044820152606401610bb8565b336001600160a01b0382161415611a1b5760405162461bcd60e51b815260206004820152601f60248201527f50726f76696465722063616e6e6f742062652074686520636f6e73756d6572006044820152606401610bb8565b60006040518060400160405280601c81526020017f19457468657265756d205369676e6564204d6573736167653a0a33320000000081525090506000818c8c8c604051602001611a6d93929190615753565b60405160208183030381529060405280519060200120604051602001611a9492919061576d565b604051602081830303815290604052805190602001209050336001600160a01b0316611af6828b8b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250613f6192505050565b6001600160a01b031614611b4c5760405162461bcd60e51b815260206004820152601f60248201527f50726f7669646572207369676e617475726520636865636b206661696c6564006044820152606401610bb8565b6000828888604051602001611b6292919061578f565b60405160208183030381529060405280519060200120604051602001611b8992919061576d565b604051602081830303815290604052805190602001209050836001600160a01b0316611beb8288888080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250613f6192505050565b6001600160a01b031614611c415760405162461bcd60e51b815260206004820152601f60248201527f436f6e73756d6572207369676e617475726520636865636b206661696c6564006044820152606401610bb8565b836001600160a01b0316336001600160a01b03167fc9a10280e9c735c63092fa5431e6acb3ed342e08b69a083e5e676994eb7070f98f8f8f8f8f8f8f8f8f4243604051611c989b9a999897969594939291906157c8565b60405180910390a350505050505050505050505050565b600b5460405163160a792560e01b815233600482015260009161010090046001600160a01b03169063160a792590602401608060405180830381865afa158015611cfd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d21919061562f565b6020015180611da85750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015611d79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d9d91906156b3565b6001600160a01b0316145b611dc45760405162461bcd60e51b8152600401610bb8906156d0565b611dcc612ef0565b3083600381518110611de057611de061583a565b60200260200101906001600160a01b031690816001600160a01b031681525050600082600481518110611e1557611e1561583a565b60200260200101511115611e2c57611e2c84612f4a565b601254604051638244937560e01b81526001600160a01b0390911690638244937590611e6090879087908790600401615850565b6020604051808303816000875af1158015611e7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ea391906158b6565b905082600081518110611eb857611eb861583a565b60200260200101516001600160a01b031683600181518110611edc57611edc61583a565b60200260200101516001600160a01b03167fb3fac3ae95956dbac74e63ba8dac94081832395c8788e3049c900a7732f348058387604051611f309291909182526001600160a01b0316602082015260400190565b60405180910390a3604080518082019091526001600160a01b03858116825260208201838152601380546001808201835560009290925293517f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a090600290950294850180546001600160a01b0319169190941617909255517f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a09190920191909155600755610e1c565b606060098054610a08906155fa565b600b5460405163160a792560e01b81526001600160a01b0383811660048301526000926101009004169063160a792590602401608060405180830381865afa158015612036573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061205a919061562f565b6020015192915050565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa1580156120b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120d4919061562f565b602001518061215b5750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa15801561212c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061215091906156b3565b6001600160a01b0316145b6121775760405162461bcd60e51b8152600401610bb8906156d0565b610f3f81612f4a565b6000338161218e8286612c9d565b9050838110156121ee5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610bb8565b6121fb8286868403612dcb565b506001949350505050565b61220e612ef0565b600061221d6020830183614d5e565b604051634c87087d60e01b81526020840135600482015290915060009081906001600160a01b03841690634c87087d9060240161018060405180830381865afa15801561226e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061229291906158cf565b5050505050505050935050925050306001600160a01b0316826001600160a01b0316146123115760405162461bcd60e51b815260206004820152602760248201527f5468697320466978656452617465206973206e6f742070726f766964696e67206044820152661d1a1a5cc8111560ca1b6064820152608401610bb8565b604051636e8de4b560e11b815260208501356004820152670de0b6b3a76400006024820152606085013560448201526000906001600160a01b0385169063dd1bc96a90606401608060405180830381865afa158015612374573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612398919061598c565b505050905084604001358111156124015760405162461bcd60e51b815260206004820152602760248201527f46697865645261746545786368616e67653a20546f6f206d616e79206261736560448201526620746f6b656e7360c81b6064820152608401610bb8565b61240d82333084613e1a565b61242e61241d6020870187614d5e565b6001600160a01b0384169083614039565b6001600160a01b0384166368c4b7e96020870135670de0b6b3a76400008461245c60a08b0160808c01614d5e565b6040516001600160e01b031960e087901b1681526004810194909452602484019290925260448301526001600160a01b031660648201526060880135608482015260a401600060405180830381600087803b1580156124ba57600080fd5b505af11580156124ce573d6000803e3d6000fd5b505030600090815260208190526040902054670de0b6b3a764000092509050101561253b5760405162461bcd60e51b815260206004820152601f60248201527f556e61626c6520746f206275792044542066726f6d20466978656452617465006044820152606401610bb8565b61254e3033670de0b6b3a764000061309b565b61257961255e6020880188614d5e565b602088013561257060408a018a615705565b89606001611675565b604051634c87087d60e01b8152602086013560048201526000906001600160a01b03861690634c87087d9060240161018060405180830381865afa1580156125c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125e991906158cf565b509a5050505050505050505050600081111561266457604051637997ca3b60e11b815260208701356004820152602481018290526001600160a01b0386169063f32f947690604401600060405180830381600087803b15801561264b57600080fd5b505af115801561265f573d6000803e3d6000fd5b505050505b5050505050610df96001600755565b600033610a9981858561309b565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa1580156126cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126f1919061562f565b60200151806127785750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015612749573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061276d91906156b3565b6001600160a01b0316145b6127945760405162461bcd60e51b8152600401610bb8906156d0565b610f3f81614119565b600b5460405163160a792560e01b81523360048201526101009091046001600160a01b03169063160a792590602401608060405180830381865afa1580156127e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061280d919061562f565b60200151806128945750600b546040516331a9108f60e11b815260016004820152339161010090046001600160a01b031690636352211e90602401602060405180830381865afa158015612865573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061288991906156b3565b6001600160a01b0316145b6128b05760405162461bcd60e51b8152600401610bb8906156d0565b6040516bffffffffffffffffffffffff193060601b16602082015260009060340160408051808303601f19018152908290528051602090910120600b546301caf8fd60e31b835290925061010090046001600160a01b031690630e57c7e890612921908490879087906004016159c2565b600060405180830381600087803b15801561293b57600080fd5b505af115801561294f573d6000803e3d6000fd5b50505050505050565b600b5460009060ff16156129c85760405162461bcd60e51b815260206004820152603160248201527f455243323054656d706c6174653a20746f6b656e20696e7374616e636520616c6044820152701c9958591e481a5b9a5d1a585b1a5e9959607a1b6064820152608401610bb8565b612a7c6129d58b8d615a3c565b8a8a8080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525050604080516020808e0282810182019093528d82529093508d92508c91829185019084908082843760009201919091525050604080516020808d0282810182019093528c82529093508c92508b918291850190849080828437600092019190915250612a7792508991508a9050615ac3565b6141fa565b9b9a5050505050505050505050565b43841015612ace5760405162461bcd60e51b815260206004820152601060248201526f115490cc8c11150e881156141254915160821b6044820152606401610bb8565b6010546001600160a01b038816600090815260116020526040812080549192917f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9918b918b918b919087612b2183615b3e565b909155506040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810187905260e00160405160208183030381529060405280519060200120604051602001612b9a92919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa158015612c05573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811615801590612c3b5750886001600160a01b0316816001600160a01b0316145b612c875760405162461bcd60e51b815260206004820152601a60248201527f455243323044543a20494e56414c49445f5349474e41545552450000000000006044820152606401610bb8565b612c92898989612dcb565b505050505050505050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b612cd0612d08565b6001600160a01b03166108fc479081150290604051600060405180830381858888f19350505050158015610f3f573d6000803e3d6000fd5b600c546000906001600160a01b0316612d9157600b546040516331a9108f60e11b8152600160048201526101009091046001600160a01b031690636352211e90602401602060405180830381865afa158015612d68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d8c91906156b3565b905090565b50600c546001600160a01b031690565b60068181548110612db157600080fd5b6000918252602090912001546001600160a01b0316905081565b6001600160a01b038316612e2d5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610bb8565b6001600160a01b038216612e8e5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610bb8565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b60026007541415612f435760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610bb8565b6002600755565b6001600160a01b03811615610f3f576001600160a01b0381166000908152600560205260409020805460ff1615612fc35760405162461bcd60e51b815260206004820152601d60248201527f4552433230526f6c65733a2020414c52454144592041204d494e5445520000006044820152606401610bb8565b805460ff19166001178155612fd7826146e4565b6040805142815243602082015233916001600160a01b038516917f4f7e100eb1ee13e903798bd0d6aa854152e07eb05544f392b9409c12935c809591015b60405180910390a35050565b600061302d8484612c9d565b9050600019811461309557818110156130885760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610bb8565b6130958484848403612dcb565b50505050565b6001600160a01b0383166130ff5760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610bb8565b6001600160a01b0382166131615760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610bb8565b6001600160a01b038316600090815260208190526040902054818110156131d95760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610bb8565b6001600160a01b03848116600081815260208181526040808320878703905593871680835291849020805487019055925185815290927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3613095565b6001600160a01b03811660008181526005602052604090819020805461ff00191681559051909133917faee911eec8b2df8f3ae0464841541b1e5f339519bd5cf51889fe8b07fecff658906132a09042904390918252602082015260400190565b60405180910390a3610df98261479b565b6001600160a01b03811660008181526005602052604090819020805460ff191681559051909133917fefa2735987005aaa89c050c0ff8cc9ae7d9079d19382081c429130f98c52d480906132a09042904390918252602082015260400190565b60408051808201909152601c81527f19457468657265756d205369676e6564204d6573736167653a0a333200000000602082015260008161335560e0850185615b59565b6133626020870187614d5e565b6133726040880160208901614d5e565b87604001358860c0013560405160200161339196959493929190615b9f565b604051602081830303815290604052805190602001206040516020016133b892919061576d565b60408051601f198184030181529190528051602090910120905060006001826133e76080870160608801615bdd565b6040805160008152602081018083529390935260ff90911690820152608080870135606083015260a08088013591830191909152016020604051602081039080840390855afa15801561343e573d6000803e3d6000fd5b5050604051601f190151915061345990506020850185614d5e565b6001600160a01b0316816001600160a01b0316146134b05760405162461bcd60e51b8152602060048201526014602482015273496e76616c69642070726f76696465722066656560601b6044820152606401610bb8565b6134c06040850160208601614d5e565b6001600160a01b03166134d66020860186614d5e565b6001600160a01b03167ff8ed11cdaaf10eca2b6c941fb802cb8682afe86cac1eb93f70d0780fa062c544604087013561351260e0890189615b59565b61352260808b0160608c01615bdd565b8a608001358b60a001358c60c001356040516135449796959493929190615bf8565b60405180910390a3600084604001351180156135795750600061356d6040860160208701614d5e565b6001600160a01b031614155b801561359b5750600061358f6020860186614d5e565b6001600160a01b031614155b156130955760125460408051636c45e88160e01b815290516000926001600160a01b031691636c45e8819160048083019260209291908290030181865afa1580156135ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061360e91906158b6565b90506000811561363b57613638670de0b6b3a76400006136326040890135856148e9565b906148f5565b90505b600061364b604088013583614901565b905061366c6136606040890160208a01614d5e565b33308a60400135613e1a565b61369d61367c6020890189614d5e565b8261368d60408b0160208c01614d5e565b6001600160a01b0316919061490d565b811561294f5760125460408051631a81876d60e01b8152905161294f926001600160a01b031691631a81876d9160048083019260209291908290030181865afa1580156136ee573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061371291906156b3565b8361368d60408b0160208c01614d5e565b6000610e1c828461573b565b6001600160a01b0382166137855760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610bb8565b8060026000828254613797919061573b565b90915550506001600160a01b038216600081815260208181526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b6001600160a01b03821661384e5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610bb8565b6001600160a01b038216600090815260208190526040902054818110156138c25760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610bb8565b6001600160a01b0383166000818152602081815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9101612ee3565b505050565b60145460135460009161392f9161573b565b9050600080826001600160401b0381111561394c5761394c6151d6565b604051908082528060200260200182016040528015613975578160200160208202803683370190505b50905060005b601354811015613c5b5760006013828154811061399a5761399a61583a565b60009182526020822060029091020154601380546001600160a01b039092169350829182918591634c87087d9190889081106139d8576139d861583a565b9060005260206000209060020201600101546040518263ffffffff1660e01b8152600401613a0891815260200190565b61018060405180830381865afa158015613a26573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a4a91906158cf565b9b509b509b505050505050505050506000821115613af057836001600160a01b031663f32f947660138781548110613a8457613a8461583a565b906000526020600020906002020160010154846040518363ffffffff1660e01b8152600401613abd929190918252602082015260400190565b600060405180830381600087803b158015613ad757600080fd5b505af1158015613aeb573d6000803e3d6000fd5b505050505b8215613b8457836001600160a01b031663c612e48a60138781548110613b1857613b1861583a565b906000526020600020906002020160010154856040518363ffffffff1660e01b8152600401613b51929190918252602082015260400190565b600060405180830381600087803b158015613b6b57600080fd5b505af1158015613b7f573d6000803e3d6000fd5b505050505b613bc760138681548110613b9a57613b9a61583a565b600091825260208083206002909202909101546001600160a01b0316825260059052604090205460ff1690565b8015613bd557506001811515145b15613c445760138581548110613bed57613bed61583a565b600091825260209091206002909102015486516001600160a01b0390911690879089908110613c1e57613c1e61583a565b6001600160a01b039092166020928302919091019091015286613c4081615b3e565b9750505b505050508080613c5390615b3e565b91505061397b565b5060005b601454811015613da05760148181548110613c7c57613c7c61583a565b60009182526020909120015460405163f9bfaa7d60e01b81523060048201526001600160a01b039091169063f9bfaa7d90602401600060405180830381600087803b158015613cca57600080fd5b505af1158015613cde573d6000803e3d6000fd5b50505050613d2060148281548110613cf857613cf861583a565b60009182526020808320909101546001600160a01b0316825260059052604090205460ff1690565b15613d8e5760148181548110613d3857613d3861583a565b9060005260206000200160009054906101000a90046001600160a01b0316828481518110613d6857613d6861583a565b6001600160a01b039092166020928302919091019091015282613d8a81615b3e565b9350505b80613d9881615b3e565b915050613c5f565b613da861493d565b50600c80546001600160a01b031916905560005b8281101561309557613de6828281518110613dd957613dd961583a565b6020026020010151612f4a565b80613df081615b3e565b915050613dbc565b600c80546001600160a01b0319166001600160a01b0392909216919091179055565b6040516370a0823160e01b81526001600160a01b038381166004830152600091908616906370a0823190602401602060405180830381865afa158015613e64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613e8891906158b6565b9050613e9f6001600160a01b0386168585856149ec565b613ea98183613723565b6040516370a0823160e01b81526001600160a01b0385811660048301528716906370a0823190602401602060405180830381865afa158015613eef573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f1391906158b6565b1015610ce35760405162461bcd60e51b815260206004820152601a60248201527f5472616e7366657220616d6f756e7420697320746f6f206c6f770000000000006044820152606401610bb8565b6000806000808451604114613f7c5760009350505050610a9f565b50505060208201516040830151604184015160ff16601b811015613fa857613fa5601b82615c3b565b90505b8060ff16601b14158015613fc057508060ff16601c14155b15613fd15760009350505050610a9f565b60408051600081526020810180835288905260ff831691810191909152606081018490526080810183905260019060a0016020604051602081039080840390855afa158015614024573d6000803e3d6000fd5b5050604051601f190151979650505050505050565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015614089573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140ad91906158b6565b90506130958463095ea7b360e01b856140c6868661573b565b6040516001600160a01b03909216602483015260448201526064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614a24565b6001600160a01b03811615610f3f576001600160a01b03811660009081526005602052604090208054610100900460ff16156141a25760405162461bcd60e51b815260206004820152602260248201527f4552433230526f6c65733a2020414c5245414459204120464545204d414e414760448201526122a960f11b6064820152608401610bb8565b805461ff0019166101001781556141b8826146e4565b6040805142815243602082015233916001600160a01b038516917fb17da2e9910b4ba5754e8872385ba315a238bafb5ae221fc85093c33432c40a79101613015565b600080846000815181106142105761421061583a565b602002602001015190508460018151811061422d5761422d61583a565b6020908102919091010151601280546001600160a01b0319166001600160a01b0392831617905581166142b75760405162461bcd60e51b815260206004820152602c60248201527f455243323054656d706c6174653a20496e76616c6964206d696e7465722c202060448201526b7a65726f206164647265737360a01b6064820152608401610bb8565b6012546001600160a01b03166143235760405162461bcd60e51b815260206004820152602b60248201527f455243323054656d706c6174653a20496e76616c696420726f757465722c207a60448201526a65726f206164647265737360a81b6064820152608401610bb8565b836000815181106143365761433661583a565b60200260200101516000141561439a5760405162461bcd60e51b8152602060048201526024808201527f44617461746f6b656e54656d706c6174653a20496e76616c6964206361702076604482015263616c756560e01b6064820152608401610bb8565b836000815181106143ad576143ad61583a565b6020026020010151600a81905550866000815181106143ce576143ce61583a565b6020026020010151600890805190602001906143eb929190614c86565b50866001815181106143ff576143ff61583a565b60200260200101516009908051906020019061441c929190614c86565b50600b805460ff196001600160a01b03841661010002166001600160a81b0319909116176001179055855161445c908790600090613dd957613dd961583a565b60006001600160a01b03168660018151811061447a5761447a61583a565b60200260200101516001600160a01b031614614524576144b3866001815181106144a6576144a661583a565b6020026020010151613df8565b856001815181106144c6576144c661583a565b60200260200101516001600160a01b0316336001600160a01b03167f4d7694d695c57cc54947177c8e8a0e61aae664e9223492a798c32fadfc6419cc424360405161451b929190918252602082015260400190565b60405180910390a35b856002815181106145375761453761583a565b6020026020010151600d60006101000a8154816001600160a01b0302191690836001600160a01b03160217905550856003815181106145785761457861583a565b6020026020010151600e60006101000a8154816001600160a01b0302191690836001600160a01b03160217905550836001815181106145b9576145b961583a565b602090810291909101810151600f819055600d54600e54604080513381526001600160a01b039384169581019590955291169083015260608201527f02ab4b3fc023109c2d0da394bda239166c833f63c42b71b67ed4b836dca0ddfe9060800160405180910390a160405146907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f9061465490600890615c60565b60408051918290038220828201825260018352603160f81b6020938401528151928301939093528101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc66060820152608081018290523060a082015260c00160408051808303601f1901815291905280516020909101206010555050600b5460ff169695505050505050565b60005b60065481101561474057816001600160a01b03166006828154811061470e5761470e61583a565b6000918252602090912001546001600160a01b0316141561472e57614740565b8061473881615b3e565b9150506146e7565b600654811415610df957600680546001810182556000919091527ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f0180546001600160a01b0384166001600160a01b03199091161790555050565b6001600160a01b0381166000908152600560205260409020805460ff161580156147cc57508054610100900460ff16155b15610df95760005b60065481101561482d57826001600160a01b0316600682815481106147fb576147fb61583a565b6000918252602090912001546001600160a01b0316141561481b5761482d565b8061482581615b3e565b9150506147d4565b600654811015613918576006805461484790600190615cfc565b815481106148575761485761583a565b600091825260209091200154600680546001600160a01b0390921691839081106148835761488361583a565b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060068054806148c2576148c2615d13565b600082815260209020810160001990810180546001600160a01b0319169055019055505050565b6000610e1c8284615d29565b6000610e1c8284615d48565b6000610e1c8284615cfc565b6040516001600160a01b03831660248201526044810182905261391890849063a9059cbb60e01b906064016140e2565b60005b6006548110156149a357600060056000600684815481106149635761496361583a565b60009182526020808320909101546001600160a01b031683528201929092526040019020805461ffff19169055508061499b81615b3e565b915050614940565b506149b060066000614d0a565b6040805142815243602082015233917f712bc71db81927a76b8bf1ea346247bb0ad58f18e4e5c1bd4aa0ec6573e02a2b910160405180910390a2565b6040516001600160a01b03808516602483015283166044820152606481018290526130959085906323b872dd60e01b906084016140e2565b6000614a79826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614af99092919063ffffffff16565b9050805160001480614a9a575080806020019051810190614a9a9190615d6a565b6139185760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610bb8565b6060614b088484600085614b10565b949350505050565b606082471015614b715760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610bb8565b600080866001600160a01b03168587604051614b8d9190615d87565b60006040518083038185875af1925050503d8060008114614bca576040519150601f19603f3d011682016040523d82523d6000602084013e614bcf565b606091505b5091509150614be087838387614beb565b979650505050505050565b60608315614c57578251614c50576001600160a01b0385163b614c505760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610bb8565b5081614b08565b614b088383815115614c6c5781518083602001fd5b8060405162461bcd60e51b8152600401610bb89190614da7565b828054614c92906155fa565b90600052602060002090601f016020900481019282614cb45760008555614cfa565b82601f10614ccd57805160ff1916838001178555614cfa565b82800160010185558215614cfa579182015b82811115614cfa578251825591602001919060010190614cdf565b50614d06929150614d24565b5090565b5080546000825590600052602060002090810190610f3f91905b5b80821115614d065760008155600101614d25565b6001600160a01b0381168114610f3f57600080fd5b8035614d5981614d39565b919050565b600060208284031215614d7057600080fd5b8135610e1c81614d39565b60005b83811015614d96578181015183820152602001614d7e565b838111156130955750506000910152565b6020815260008251806020840152614dc6816040850160208701614d7b565b601f01601f19169190910160400192915050565b60008060408385031215614ded57600080fd5b8235614df881614d39565b946020939093013593505050565b8015158114610f3f57600080fd5b600080600080600060a08688031215614e2c57600080fd5b8535614e3781614d39565b945060208601359350604086013592506060860135614e5581614e06565b91506080860135614e6581614d39565b809150509295509295909350565b600060c08284031215614e8557600080fd5b50919050565b60008060408385031215614e9e57600080fd5b82356001600160401b03811115614eb457600080fd5b614ec085828601614e73565b9250506020830135614ed181614d39565b809150509250929050565b600080600060608486031215614ef157600080fd5b8335614efc81614d39565b92506020840135614f0c81614d39565b929592945050506040919091013590565b60006101008284031215614e8557600080fd5b60008060408385031215614f4357600080fd5b8235915060208301356001600160401b03811115614f6057600080fd5b614f6c85828601614f1d565b9150509250929050565b600060208284031215614f8857600080fd5b5035919050565b600081518084526020808501945080840160005b83811015614fc85781516001600160a01b031687529582019590820190600101614fa3565b509495945050505050565b602081526000610e1c6020830184614f8f565b60008060008084860360c0811215614ffd57600080fd5b853561500881614d39565b94506020860135935060408601356001600160401b0381111561502a57600080fd5b61503688828901614f1d565b9350506060605f198201121561504b57600080fd5b509295919450926060019150565b602080825282518282018190526000919060409081850190868401855b828110156150a457815180516001600160a01b03168552860151868501529284019290850190600101615076565b5091979650505050505050565b60008083601f8401126150c357600080fd5b5081356001600160401b038111156150da57600080fd5b6020830191508360208285010111156150f257600080fd5b9250929050565b60008060008060008060008060008060c08b8d03121561511857600080fd5b8a35995060208b01356001600160401b038082111561513657600080fd5b6151428e838f016150b1565b909b50995060408d013591508082111561515b57600080fd5b6151678e838f016150b1565b909950975060608d013591508082111561518057600080fd5b61518c8e838f016150b1565b909750955060808d01359150808211156151a557600080fd5b506151b28d828e016150b1565b90945092506151c5905060a08c01614d4e565b90509295989b9194979a5092959850565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715615214576152146151d6565b604052919050565b60006001600160401b03821115615235576152356151d6565b5060051b60200190565b600082601f83011261525057600080fd5b813560206152656152608361521c565b6151ec565b82815260059290921b8401810191818101908684111561528457600080fd5b8286015b8481101561529f5780358352918301918301615288565b509695505050505050565b6000806000606084860312156152bf57600080fd5b83356152ca81614d39565b92506020848101356001600160401b03808211156152e757600080fd5b818701915087601f8301126152fb57600080fd5b81356153096152608261521c565b81815260059190911b8301840190848101908a83111561532857600080fd5b938501935b8285101561534f57843561534081614d39565b8252938501939085019061532d565b96505050604087013592508083111561536757600080fd5b50506153758682870161523f565b9150509250925092565b60008082840360c081121561539357600080fd5b83356001600160401b038111156153a957600080fd5b6153b586828701614e73565b93505060a0601f19820112156153ca57600080fd5b506020830190509250929050565b600080602083850312156153eb57600080fd5b82356001600160401b0381111561540157600080fd5b61540d858286016150b1565b90969095509350505050565b60008083601f84011261542b57600080fd5b5081356001600160401b0381111561544257600080fd5b6020830191508360208260051b85010111156150f257600080fd5b60008060008060008060008060008060a08b8d03121561547c57600080fd5b8a356001600160401b038082111561549357600080fd5b61549f8e838f01615419565b909c509a5060208d01359150808211156154b857600080fd5b6154c48e838f01615419565b909a50985060408d01359150808211156154dd57600080fd5b6154e98e838f01615419565b909850965060608d013591508082111561550257600080fd5b61550e8e838f01615419565b909650945060808d013591508082111561552757600080fd5b506155348d828e01615419565b915080935050809150509295989b9194979a5092959850565b803560ff81168114614d5957600080fd5b600080600080600080600060e0888a03121561557957600080fd5b873561558481614d39565b9650602088013561559481614d39565b955060408801359450606088013593506155b06080890161554d565b925060a0880135915060c0880135905092959891949750929550565b600080604083850312156155df57600080fd5b82356155ea81614d39565b91506020830135614ed181614d39565b600181811c9082168061560e57607f821691505b60208210811415614e8557634e487b7160e01b600052602260045260246000fd5b60006080828403121561564157600080fd5b604051608081018181106001600160401b0382111715615663576156636151d6565b604052825161567181614e06565b8152602083015161568181614e06565b6020820152604083015161569481614e06565b604082015260608301516156a781614e06565b60608201529392505050565b6000602082840312156156c557600080fd5b8151610e1c81614d39565b6020808252818101527f455243323054656d706c6174653a204e4f54204445504c4f59455220524f4c45604082015260600190565b6000823560fe1983360301811261571b57600080fd5b9190910192915050565b634e487b7160e01b600052601160045260246000fd5b6000821982111561574e5761574e615725565b500190565b838152818360208301376000910160200190815292915050565b6000835161577f818460208801614d7b565b9190910191825250602001919050565b8183823760009101908152919050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b8b815260e0602082015260006157e260e083018c8e61579f565b82810360408401526157f5818b8d61579f565b9050828103606084015261580a81898b61579f565b9050828103608084015261581f81878961579f565b60a0840195909552505060c001529998505050505050505050565b634e487b7160e01b600052603260045260246000fd5b6001600160a01b03841681526060602080830182905260009161587590840186614f8f565b838103604085015284518082528286019183019060005b818110156158a85783518352928401929184019160010161588c565b509098975050505050505050565b6000602082840312156158c857600080fd5b5051919050565b6000806000806000806000806000806000806101808d8f0312156158f257600080fd5b8c516158fd81614d39565b60208e0151909c5061590e81614d39565b60408e015160608f0151919c509a5061592681614d39565b8099505060808d0151975060a08d0151965060c08d015161594681614e06565b8096505060e08d015194506101008d015193506101208d015192506101408d015191506101608d015161597881614e06565b809150509295989b509295989b509295989b565b600080600080608085870312156159a257600080fd5b505082516020840151604085015160609095015191969095509092509050565b8381526040602082015260006159dc60408301848661579f565b95945050505050565b60006001600160401b038311156159fe576159fe6151d6565b615a11601f8401601f19166020016151ec565b9050828152838383011115615a2557600080fd5b828260208301376000602084830101529392505050565b6000615a4a6152608461521c565b80848252602080830192508560051b850136811115615a6857600080fd5b855b81811015615ab75780356001600160401b03811115615a895760008081fd5b870136601f820112615a9b5760008081fd5b615aa93682358684016159e5565b865250938201938201615a6a565b50919695505050505050565b6000615ad16152608461521c565b80848252602080830192508560051b850136811115615aef57600080fd5b855b81811015615ab75780356001600160401b03811115615b105760008081fd5b870136601f820112615b225760008081fd5b615b303682358684016159e5565b865250938201938201615af1565b6000600019821415615b5257615b52615725565b5060010190565b6000808335601e19843603018112615b7057600080fd5b8301803591506001600160401b03821115615b8a57600080fd5b6020019150368190038213156150f257600080fd5b858782376bffffffffffffffffffffffff19606095861b8116969091019586529290931b909116601484015260288301526048820152606801919050565b600060208284031215615bef57600080fd5b610e1c8261554d565b87815260c060208201526000615c1260c08301888a61579f565b905060ff861660408301528460608301528360808301528260a083015298975050505050505050565b600060ff821660ff84168060ff03821115615c5857615c58615725565b019392505050565b600080835481600182811c915080831680615c7c57607f831692505b6020808410821415615c9c57634e487b7160e01b86526022600452602486fd5b818015615cb05760018114615cc157615cee565b60ff19861689528489019650615cee565b60008a81526020902060005b86811015615ce65781548b820152908501908301615ccd565b505084890196505b509498975050505050505050565b600082821015615d0e57615d0e615725565b500390565b634e487b7160e01b600052603160045260246000fd5b6000816000190483118215151615615d4357615d43615725565b500290565b600082615d6557634e487b7160e01b600052601260045260246000fd5b500490565b600060208284031215615d7c57600080fd5b8151610e1c81614e06565b6000825161571b818460208701614d7b56fea264697066735822122033f2af53437addf43f15eb1acb2e4001ce9ebf429ce8fdd59580fd7feae2079564736f6c634300080c0033",linkReferences:{},deployedLinkReferences:{}},fe=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedManager",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedTo725StoreList",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedToCreateERC20List",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedToMetadataList",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"approved",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"CleanedPermissions",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"ContractCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"key",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"value",type:"bytes"}],name:"DataChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"_operation",type:"uint256"},{indexed:!0,internalType:"address",name:"_to",type:"address"},{indexed:!0,internalType:"uint256",name:"_value",type:"uint256"},{indexed:!1,internalType:"bytes",name:"_data",type:"bytes"}],name:"Executed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"createdBy",type:"address"},{indexed:!1,internalType:"uint8",name:"state",type:"uint8"},{indexed:!1,internalType:"string",name:"decryptorUrl",type:"string"},{indexed:!1,internalType:"bytes",name:"flags",type:"bytes"},{indexed:!1,internalType:"bytes",name:"data",type:"bytes"},{indexed:!1,internalType:"bytes32",name:"metaDataHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"MetadataCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"updatedBy",type:"address"},{indexed:!1,internalType:"uint8",name:"state",type:"uint8"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"MetadataState",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"updatedBy",type:"address"},{indexed:!1,internalType:"uint8",name:"state",type:"uint8"},{indexed:!1,internalType:"string",name:"decryptorUrl",type:"string"},{indexed:!1,internalType:"bytes",name:"flags",type:"bytes"},{indexed:!1,internalType:"bytes",name:"data",type:"bytes"},{indexed:!1,internalType:"bytes32",name:"metaDataHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"MetadataUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"validator",type:"address"},{indexed:!1,internalType:"bytes32",name:"metaDataHash",type:"bytes32"},{indexed:!1,internalType:"uint8",name:"v",type:"uint8"},{indexed:!1,internalType:"bytes32",name:"r",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"s",type:"bytes32"}],name:"MetadataValidated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedFrom725StoreList",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedFromCreateERC20List",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedFromMetadataList",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedManager",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newTokenAddress",type:"address"},{indexed:!0,internalType:"address",name:"templateAddress",type:"address"},{indexed:!1,internalType:"string",name:"name",type:"string"},{indexed:!1,internalType:"string",name:"symbol",type:"string"},{indexed:!1,internalType:"uint256",name:"cap",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"}],name:"TokenCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"updatedBy",type:"address"},{indexed:!1,internalType:"string",name:"tokenURI",type:"string"},{indexed:!1,internalType:"uint256",name:"tokenID",type:"uint256"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"TokenURIUpdate",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Transfer",type:"event"},{stateMutability:"payable",type:"fallback"},{inputs:[{internalType:"address",name:"_managerAddress",type:"address"}],name:"addManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"enum ERC721RolesAddress.RolesType[]",name:"roles",type:"uint8[]"}],name:"addMultipleUsersToRoles",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_allowedAddress",type:"address"}],name:"addTo725StoreList",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_allowedAddress",type:"address"}],name:"addToCreateERC20List",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_allowedAddress",type:"address"}],name:"addToMetadataList",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"auth",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseURI",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"cleanPermissions",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_templateIndex",type:"uint256"},{internalType:"string[]",name:"strings",type:"string[]"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"},{internalType:"bytes[]",name:"bytess",type:"bytes[]"}],name:"createERC20",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_operation",type:"uint256"},{internalType:"address",name:"_to",type:"address"},{internalType:"uint256",name:"_value",type:"uint256"},{internalType:"bytes",name:"_data",type:"bytes"}],name:"executeCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getApproved",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_key",type:"bytes32"}],name:"getData",outputs:[{internalType:"bytes",name:"_value",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getMetaData",outputs:[{internalType:"string",name:"",type:"string"},{internalType:"string",name:"",type:"string"},{internalType:"uint8",name:"",type:"uint8"},{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getPermissions",outputs:[{components:[{internalType:"bool",name:"manager",type:"bool"},{internalType:"bool",name:"deployERC20",type:"bool"},{internalType:"bool",name:"updateMetadata",type:"bool"},{internalType:"bool",name:"store",type:"bool"}],internalType:"struct ERC721RolesAddress.Roles",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getTokensList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"hasMetaData",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"},{internalType:"address",name:"tokenFactory",type:"address"},{internalType:"address",name:"additionalERC20Deployer",type:"address"},{internalType:"address",name:"additionalMetaDataUpdater",type:"address"},{internalType:"string",name:"tokenURI",type:"string"},{internalType:"bool",name:"transferable_",type:"bool"}],name:"initialize",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"datatoken",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isERC20Deployer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"isInitialized",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"metaDataDecryptorAddress",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"metaDataDecryptorUrl",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"metaDataState",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ownerOf",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_allowedAddress",type:"address"}],name:"removeFrom725StoreList",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_allowedAddress",type:"address"}],name:"removeFromCreateERC20List",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_allowedAddress",type:"address"}],name:"removeFromMetadataList",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_managerAddress",type:"address"}],name:"removeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"_baseURI",type:"string"}],name:"setBaseURI",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"_key",type:"bytes32"},{internalType:"bytes",name:"_value",type:"bytes"}],name:"setDataERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint8",name:"_metaDataState",type:"uint8"},{internalType:"string",name:"_metaDataDecryptorUrl",type:"string"},{internalType:"string",name:"_metaDataDecryptorAddress",type:"string"},{internalType:"bytes",name:"flags",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"},{internalType:"bytes32",name:"_metaDataHash",type:"bytes32"},{components:[{internalType:"address",name:"validatorAddress",type:"address"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],internalType:"struct ERC721Template.metaDataProof[]",name:"_metadataProofs",type:"tuple[]"}],name:"setMetaData",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint8",name:"metaDataState",type:"uint8"},{internalType:"string",name:"metaDataDecryptorUrl",type:"string"},{internalType:"string",name:"metaDataDecryptorAddress",type:"string"},{internalType:"bytes",name:"flags",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"},{internalType:"bytes32",name:"metaDataHash",type:"bytes32"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"string",name:"tokenURI",type:"string"},{components:[{internalType:"address",name:"validatorAddress",type:"address"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],internalType:"struct ERC721Template.metaDataProof[]",name:"metadataProofs",type:"tuple[]"}],internalType:"struct ERC721Template.metaDataAndTokenURI",name:"_metaDataAndTokenURI",type:"tuple"}],name:"setMetaDataAndTokenURI",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint8",name:"_metaDataState",type:"uint8"}],name:"setMetaDataState",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"_key",type:"bytes32"},{internalType:"bytes",name:"_value",type:"bytes"}],name:"setNewData",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"string",name:"tokenURI",type:"string"}],name:"setTokenURI",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"index",type:"uint256"}],name:"tokenByIndex",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"uint256",name:"index",type:"uint256"}],name:"tokenOfOwnerByIndex",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"tokenURI",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"transferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"transferable",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"withdrawETH",outputs:[],stateMutability:"payable",type:"function"},{stateMutability:"payable",type:"receive"}],me={nouns:["Crab","Fish","Seal","Octopus","Shark","Seahorse","Walrus","Starfish","Whale","Orca","Penguin","Jellyfish","Squid","Lobster","Pelican","Shrimp","Oyster","Clam","Seagull","Dolphin","Shell","Cormorant","Otter","Anemone","Turtle","Coral","Ray","Barracuda","Krill","Anchovy","Angelfish","Barnacle","Clownfish","Cod","Cuttlefish","Eel","Fugu","Herring","Haddock","Ling","Mackerel","Manatee","Narwhal","Nautilus","Plankton","Porpoise","Prawn","Pufferfish","Swordfish","Tuna"],adjectives:["adamant","adroit","amatory","ambitious","amused","animistic","antic","arcadian","artistic","astonishing","astounding","baleful","bellicose","bilious","blissful","boorish","brave","breathtaking","brilliant","calamitous","caustic","cerulean","clever","charming","comely","competent","concomitant","confident","contumacious","corpulent","crapulous","creative","dazzling","dedicated","defamatory","delighted","delightful","determined","didactic","dilatory","dowdy","efficacious","effulgent","egregious","empowered","endemic","enthusiastic","equanimous","exceptional","execrable","fabulous","fantastic","fastidious","feckless","fecund","friable","fulsome","garrulous","generous","gentle","guileless","gustatory","heuristic","histrionic","hubristic","incendiary","incredible","insidious","insolent","inspired","intransigent","inveterate","invidious","invigorated","irksome","jejune","juicy","jocular","joyful","judicious","kind","lachrymose","limpid","loquacious","lovely","luminous","mannered","marvelous","mendacious","meretricious","minatory","mordant","motivated","munificent","nefarious","noxious","obtuse","optimistic","parsimonious","pendulous","pernicious","pervasive","petulant","passionate","phenomenal","platitudinous","pleasant","powerful","precipitate","propitious","puckish","querulous","quiescent","rebarbative","recalcitant","redolent","rhadamanthine","risible","ruminative","sagacious","salubrious","sartorial","sclerotic","serpentine","smart","spasmodic","strident","stunning","stupendous","taciturn","tactful","tasty","tenacious","tremendous","tremulous","trenchant","turbulent","turgid","ubiquitous","uxorious","verdant","vibrant","voluble","voracious","wheedling","withering","wonderful","zealous"]};function ye(e){var t=e||me,n=Math.floor(Math.random()*t.adjectives.length),r=Math.floor(Math.random()*t.nouns.length),i=Math.floor(100*Math.random()),s=t.adjectives[n].replace(/^\w/,function(e){return e.toUpperCase()}),a=t.nouns[r].replace(/^\w/,function(e){return e.toUpperCase()});return{name:s+" "+a+" Token",symbol:(s.substring(0,3)+a.substring(0,3)).toUpperCase()+"-"+i}}var be=[{inputs:[{internalType:"address",name:"_template721",type:"address"},{internalType:"address",name:"_template",type:"address"},{internalType:"address",name:"_router",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"datatokenAddress",type:"address"},{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"uint256",name:"maxTokens",type:"uint256"},{indexed:!1,internalType:"uint256",name:"maxBalance",type:"uint256"},{indexed:!1,internalType:"address",name:"allowedSwapper",type:"address"}],name:"DispenserCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"instance",type:"address"}],name:"InstanceDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"newTokenAddress",type:"address"},{indexed:!0,internalType:"address",name:"templateAddress",type:"address"},{indexed:!1,internalType:"string",name:"tokenName",type:"string"},{indexed:!0,internalType:"address",name:"admin",type:"address"},{indexed:!1,internalType:"string",name:"symbol",type:"string"},{indexed:!1,internalType:"string",name:"tokenURI",type:"string"},{indexed:!1,internalType:"bool",name:"transferable",type:"bool"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"NFTCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"dispenserContract",type:"address"}],name:"NewDispenser",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"address",name:"exchangeContract",type:"address"},{indexed:!0,internalType:"address",name:"baseToken",type:"address"}],name:"NewFixedRate",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"poolAddress",type:"address"},{indexed:!1,internalType:"address",name:"ssContract",type:"address"},{indexed:!1,internalType:"address",name:"baseTokenAddress",type:"address"}],name:"NewPool",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"_templateAddress",type:"address"},{indexed:!0,internalType:"uint256",name:"nftTemplateCount",type:"uint256"}],name:"Template20Added",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"_templateAddress",type:"address"},{indexed:!0,internalType:"uint256",name:"nftTemplateCount",type:"uint256"}],name:"Template721Added",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newTokenAddress",type:"address"},{indexed:!0,internalType:"address",name:"templateAddress",type:"address"},{indexed:!1,internalType:"string",name:"name",type:"string"},{indexed:!1,internalType:"string",name:"symbol",type:"string"},{indexed:!1,internalType:"uint256",name:"cap",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"}],name:"TokenCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"_templateAddress",type:"address"}],name:"add721TokenTemplate",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_templateAddress",type:"address"}],name:"addTokenTemplate",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string",name:"tokenURI",type:"string"},{internalType:"bool",name:"transferable",type:"bool"},{internalType:"address",name:"owner",type:"address"}],internalType:"struct IFactory.NftCreateData",name:"_NftCreateData",type:"tuple"},{components:[{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string[]",name:"strings",type:"string[]"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"},{internalType:"bytes[]",name:"bytess",type:"bytes[]"}],internalType:"struct IFactory.ErcCreateData",name:"_ErcCreateData",type:"tuple"}],name:"createNftWithErc20",outputs:[{internalType:"address",name:"erc721Address",type:"address"},{internalType:"address",name:"erc20Address",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string",name:"tokenURI",type:"string"},{internalType:"bool",name:"transferable",type:"bool"},{internalType:"address",name:"owner",type:"address"}],internalType:"struct IFactory.NftCreateData",name:"_NftCreateData",type:"tuple"},{components:[{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string[]",name:"strings",type:"string[]"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"},{internalType:"bytes[]",name:"bytess",type:"bytes[]"}],internalType:"struct IFactory.ErcCreateData",name:"_ErcCreateData",type:"tuple"},{components:[{internalType:"address",name:"dispenserAddress",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"bool",name:"withMint",type:"bool"},{internalType:"address",name:"allowedSwapper",type:"address"}],internalType:"struct IFactory.DispenserData",name:"_DispenserData",type:"tuple"}],name:"createNftWithErc20WithDispenser",outputs:[{internalType:"address",name:"erc721Address",type:"address"},{internalType:"address",name:"erc20Address",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string",name:"tokenURI",type:"string"},{internalType:"bool",name:"transferable",type:"bool"},{internalType:"address",name:"owner",type:"address"}],internalType:"struct IFactory.NftCreateData",name:"_NftCreateData",type:"tuple"},{components:[{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string[]",name:"strings",type:"string[]"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"},{internalType:"bytes[]",name:"bytess",type:"bytes[]"}],internalType:"struct IFactory.ErcCreateData",name:"_ErcCreateData",type:"tuple"},{components:[{internalType:"address",name:"fixedPriceAddress",type:"address"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"}],internalType:"struct IFactory.FixedData",name:"_FixedData",type:"tuple"}],name:"createNftWithErc20WithFixedRate",outputs:[{internalType:"address",name:"erc721Address",type:"address"},{internalType:"address",name:"erc20Address",type:"address"},{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string",name:"tokenURI",type:"string"},{internalType:"bool",name:"transferable",type:"bool"},{internalType:"address",name:"owner",type:"address"}],internalType:"struct IFactory.NftCreateData",name:"_NftCreateData",type:"tuple"},{components:[{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string[]",name:"strings",type:"string[]"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"},{internalType:"bytes[]",name:"bytess",type:"bytes[]"}],internalType:"struct IFactory.ErcCreateData",name:"_ErcCreateData",type:"tuple"},{components:[{internalType:"uint256[]",name:"ssParams",type:"uint256[]"},{internalType:"uint256[]",name:"swapFees",type:"uint256[]"},{internalType:"address[]",name:"addresses",type:"address[]"}],internalType:"struct IFactory.PoolData",name:"_PoolData",type:"tuple"}],name:"createNftWithErc20WithPool",outputs:[{internalType:"address",name:"erc721Address",type:"address"},{internalType:"address",name:"erc20Address",type:"address"},{internalType:"address",name:"poolAddress",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"templateIndex",type:"uint256"},{internalType:"string",name:"tokenURI",type:"string"},{internalType:"bool",name:"transferable",type:"bool"},{internalType:"address",name:"owner",type:"address"}],internalType:"struct IFactory.NftCreateData",name:"_NftCreateData",type:"tuple"},{components:[{internalType:"uint8",name:"_metaDataState",type:"uint8"},{internalType:"string",name:"_metaDataDecryptorUrl",type:"string"},{internalType:"string",name:"_metaDataDecryptorAddress",type:"string"},{internalType:"bytes",name:"flags",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"},{internalType:"bytes32",name:"_metaDataHash",type:"bytes32"},{components:[{internalType:"address",name:"validatorAddress",type:"address"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],internalType:"struct IERC721Template.metaDataProof[]",name:"_metadataProofs",type:"tuple[]"}],internalType:"struct ERC721Factory.MetaData",name:"_MetaData",type:"tuple"}],name:"createNftWithMetaData",outputs:[{internalType:"address",name:"erc721Address",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_templateIndex",type:"uint256"},{internalType:"string[]",name:"strings",type:"string[]"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"},{internalType:"bytes[]",name:"bytess",type:"bytes[]"}],name:"createToken",outputs:[{internalType:"address",name:"token",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"_templateIndex",type:"uint256"},{internalType:"address",name:"additionalERC20Deployer",type:"address"},{internalType:"address",name:"additionalMetaDataUpdater",type:"address"},{internalType:"string",name:"tokenURI",type:"string"},{internalType:"bool",name:"transferable",type:"bool"},{internalType:"address",name:"owner",type:"address"}],name:"deployERC721Contract",outputs:[{internalType:"address",name:"token",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_index",type:"uint256"}],name:"disable721TokenTemplate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_index",type:"uint256"}],name:"disableTokenTemplate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"erc20List",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"erc721List",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentNFTCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentNFTTemplateCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentTemplateCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentTokenCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_index",type:"uint256"}],name:"getNFTTemplate",outputs:[{components:[{internalType:"address",name:"templateAddress",type:"address"},{internalType:"bool",name:"isActive",type:"bool"}],internalType:"struct ERC721Factory.Template",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_index",type:"uint256"}],name:"getTokenTemplate",outputs:[{components:[{internalType:"address",name:"templateAddress",type:"address"},{internalType:"bool",name:"isActive",type:"bool"}],internalType:"struct ERC721Factory.Template",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"nftTemplateList",outputs:[{internalType:"address",name:"templateAddress",type:"address"},{internalType:"bool",name:"isActive",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_index",type:"uint256"}],name:"reactivate721TokenTemplate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_index",type:"uint256"}],name:"reactivateTokenTemplate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"tokenAddress",type:"address"},{internalType:"bytes32",name:"orderTxId",type:"bytes32"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct IERC20Template.providerFee",name:"_providerFee",type:"tuple"}],internalType:"struct ERC721Factory.reuseTokenOrder[]",name:"orders",type:"tuple[]"}],name:"reuseMultipleTokenOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"router",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"address",name:"tokenAddress",type:"address"},{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct IERC20Template.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct IERC20Template.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],internalType:"struct ERC721Factory.tokenOrder[]",name:"orders",type:"tuple[]"}],name:"startMultipleTokenOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"templateCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"templateList",outputs:[{internalType:"address",name:"templateAddress",type:"address"},{internalType:"bool",name:"isActive",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];function ge(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var ve=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}I(n,e);var r=n.prototype;return r.getDefaultAbi=function(){return be},r.createNFT=function(e,t){try{var n=this;if(e.templateIndex||(e.templateIndex=1),!e.name||!e.symbol){var r=ye(),i=r.symbol;e.name=r.name,e.symbol=i}var s=e.templateIndex;return Promise.resolve(n.getCurrentNFTTemplateCount()).then(function(r){if(s>r)throw new Error("Template index doesnt exist");if(0===e.templateIndex)throw new Error("Template index cannot be ZERO");return Promise.resolve(n.getNFTTemplate(e.templateIndex)).then(function(r){if(!1===r.isActive)throw new Error("Template is not active");return Promise.resolve(n.contract.deployERC721Contract.estimateGas(e.name,e.symbol,e.templateIndex,ue,ue,e.tokenURI,e.transferable,e.owner)).then(function(r){return t?r:ge(function(){var t;return Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(t=n.config)?void 0:t.gasFeeMultiplier,n.contract.deployERC721Contract,e.name,e.symbol,e.templateIndex,ue,ue,e.tokenURI,e.transferable,e.owner)).then(function(e){if(!e){var t="Tx for deploying new NFT contract does not exist or status is not successful.";throw console.error(t),t}return Promise.resolve(e.wait()).then(function(e){return ne(e,"NFTCreated").args[0]})})},function(e){console.error("Creation of NFT failed: "+e)})})})})}catch(e){return Promise.reject(e)}},r.getCurrentNFTCount=function(){try{return Promise.resolve(this.contract.getCurrentNFTCount()).then(Number)}catch(e){return Promise.reject(e)}},r.getCurrentTokenCount=function(){try{return Promise.resolve(this.contract.getCurrentTokenCount()).then(Number)}catch(e){return Promise.reject(e)}},r.getOwner=function(){try{return Promise.resolve(this.contract.owner())}catch(e){return Promise.reject(e)}},r.getCurrentNFTTemplateCount=function(){try{return Promise.resolve(this.contract.getCurrentNFTTemplateCount()).then(Number)}catch(e){return Promise.reject(e)}},r.getCurrentTokenTemplateCount=function(){try{return Promise.resolve(this.contract.getCurrentTemplateCount()).then(Number)}catch(e){return Promise.reject(e)}},r.getNFTTemplate=function(e){try{var t=this;return Promise.resolve(t.getCurrentNFTTemplateCount()).then(function(n){if(e>n)throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");return Promise.resolve(t.contract.getNFTTemplate(e))})}catch(e){return Promise.reject(e)}},r.getTokenTemplate=function(e){try{return Promise.resolve(this.contract.getTokenTemplate(e))}catch(e){return Promise.reject(e)}},r.checkDatatoken=function(e){try{return Promise.resolve(this.contract.erc20List(e))}catch(e){return Promise.reject(e)}},r.checkNFT=function(e){try{return Promise.resolve(this.contract.erc721List(e))}catch(e){return Promise.reject(e)}},r.addNFTTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Factory Owner");if(t===ue)throw new Error("Template cannot be ZERO address");return Promise.resolve(r.contract.add721TokenTemplate.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.add721TokenTemplate,t))})})}catch(e){return Promise.reject(e)}},r.disableNFTTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Factory Owner");return Promise.resolve(r.getCurrentNFTTemplateCount()).then(function(e){if(t>e)throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return Promise.resolve(r.contract.disable721TokenTemplate.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.disable721TokenTemplate,t))})})})}catch(e){return Promise.reject(e)}},r.reactivateNFTTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Factory Owner");return Promise.resolve(r.getCurrentNFTTemplateCount()).then(function(e){if(t>e)throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return Promise.resolve(r.contract.reactivate721TokenTemplate.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.reactivate721TokenTemplate,t))})})})}catch(e){return Promise.reject(e)}},r.addTokenTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Factory Owner");if(t===ue)throw new Error("Template cannot be address ZERO");return Promise.resolve(r.contract.addTokenTemplate.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.addTokenTemplate,t))})})}catch(e){return Promise.reject(e)}},r.disableTokenTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Factory Owner");return Promise.resolve(r.getCurrentTokenTemplateCount()).then(function(e){if(t>e)throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return Promise.resolve(r.getTokenTemplate(t)).then(function(e){if(!1===e.isActive)throw new Error("Template is already disabled");return Promise.resolve(r.contract.disableTokenTemplate.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.disableTokenTemplate,t))})})})})}catch(e){return Promise.reject(e)}},r.reactivateTokenTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Factory Owner");return Promise.resolve(r.getCurrentTokenTemplateCount()).then(function(e){if(t>e)throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return Promise.resolve(r.getTokenTemplate(t)).then(function(e){if(!0===e.isActive)throw new Error("Template is already active");return Promise.resolve(r.contract.reactivateTokenTemplate.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.reactivateTokenTemplate,t))})})})})}catch(e){return Promise.reject(e)}},r.startMultipleTokenOrder=function(e,t){try{var n=this;if(e.length>50)throw new Error("Too many orders");return Promise.resolve(n.contract.startMultipleTokenOrder.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.startMultipleTokenOrder,e))})}catch(e){return Promise.reject(e)}},r.createNftWithDatatoken=function(e,t,n){try{var r=this;return Promise.resolve(r.getErcCreationParams(t)).then(function(t){return Promise.resolve(r.contract.createNftWithErc20.estimateGas(e,t)).then(function(i){var s;return n?i:Promise.resolve(V(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.createNftWithErc20,e,t))})})}catch(e){return Promise.reject(e)}},r.createNftWithDatatokenWithFixedRate=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getErcCreationParams(t)).then(function(t){return Promise.resolve(i.getFreCreationParams(n)).then(function(n){return Promise.resolve(i.contract.createNftWithErc20WithFixedRate.estimateGas(e,t,n)).then(function(s){var a;return r?s:Promise.resolve(V(s,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,i.contract.createNftWithErc20WithFixedRate,e,t,n))})})})}catch(e){return Promise.reject(e)}},r.createNftWithDatatokenWithDispenser=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getErcCreationParams(t)).then(function(t){return Promise.resolve(i.amountToUnits(null,n.maxBalance,18)).then(function(s){return n.maxBalance=s,Promise.resolve(i.amountToUnits(null,n.maxTokens,18)).then(function(s){return n.maxTokens=s,Promise.resolve(i.contract.createNftWithErc20WithDispenser.estimateGas(e,t,n)).then(function(s){var a;return r?s:Promise.resolve(V(s,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,i.contract.createNftWithErc20WithDispenser,e,t,n))})})})})}catch(e){return Promise.reject(e)}},r.getErcCreationParams=function(e){try{var n,r,i=function(){var i=[e.minter,e.paymentCollector,e.mpFeeAddress,e.feeToken];e.filesObject&&(e.accessListFactory&&i.push(e.accessListFactory),e.allowAccessList&&i.push(e.allowAccessList),e.denyAccessList&&i.push(e.denyAccessList));var a=[e.name||n,e.symbol||r],u=e.templateIndex;return Promise.resolve(s.amountToUnits(null,e.cap,18)).then(function(n){return Promise.resolve(s.amountToUnits(null,e.feeAmount,o)).then(function(r){return{templateIndex:u,strings:a,addresses:i,uints:[n,r],bytess:e.filesObject?[t.toUtf8Bytes(JSON.stringify(e.filesObject))]:[]}})})},s=this;if(!e.name||!e.symbol){var a=ye();n=a.name,r=a.symbol}var o=18,u=function(){if(e.feeToken!==ue){var t=ge(function(){return Promise.resolve(H(s.signer,e.feeToken)).then(function(e){o=e})},function(e){O.error("getTokenDecimals error",e)});if(t&&t.then)return t.then(function(){})}}();return Promise.resolve(u&&u.then?u.then(i):i())}catch(e){return Promise.reject(e)}},r.getFreCreationParams=function(e){try{var t=this;e.allowedConsumer||(e.allowedConsumer=ue);var n=!1===e.withMint?0:1,r=[e.baseTokenAddress,e.owner,e.marketFeeCollector,e.allowedConsumer],i=e.fixedRateAddress,s=e.datatokenDecimals,a=e.baseTokenDecimals;return Promise.resolve(t.amountToUnits(null,e.fixedRate,e.datatokenDecimals)).then(function(o){return Promise.resolve(t.amountToUnits(null,e.marketFee,e.datatokenDecimals)).then(function(e){return{fixedPriceAddress:i,addresses:r,uints:[a,s,o,e,n]}})})}catch(e){return Promise.reject(e)}},n}(ie),we=[{inputs:[],name:"DOMAIN_SEPARATOR",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PERMIT_TYPEHASH",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"}],name:"burn",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"burnFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cap",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"cleanFrom721",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"bool",name:"withMint",type:"bool"},{internalType:"address",name:"allowedSwapper",type:"address"}],name:"createDispenser",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"fixedPriceAddress",type:"address"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"}],name:"createFixedRate",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"uint256[]",name:"ssParams",type:"uint256[]"},{internalType:"uint256[]",name:"swapFees",type:"uint256[]"},{internalType:"address[]",name:"addresses",type:"address[]"}],name:"deployPool",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"getDispensers",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getERC721Address",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFixedRates",outputs:[{components:[{internalType:"address",name:"contractAddress",type:"address"},{internalType:"bytes32",name:"id",type:"bytes32"}],internalType:"struct IERC20Template.fixedRate[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getPaymentCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getPools",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getPublishingMarketFee",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string[]",name:"strings_",type:"string[]"},{internalType:"address[]",name:"addresses_",type:"address[]"},{internalType:"address[]",name:"factoryAddresses_",type:"address[]"},{internalType:"uint256[]",name:"uints_",type:"uint256[]"},{internalType:"bytes[]",name:"bytes_",type:"bytes[]"}],name:"initialize",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"isERC20Deployer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isMinter",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"mint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"nonces",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"permissions",outputs:[{components:[{internalType:"bool",name:"minter",type:"bool"},{internalType:"bool",name:"feeManager",type:"bool"}],internalType:"struct IERC20Template.RolesERC20",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderTxId",type:"bytes32"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct IERC20Template.providerFee",name:"_providerFee",type:"tuple"}],name:"reuseOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_publishMarketFeeAddress",type:"address"},{internalType:"address",name:"_publishMarketFeeToken",type:"address"},{internalType:"uint256",name:"_publishMarketFeeAmount",type:"uint256"}],name:"setPublishingMarketFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct IERC20Template.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct IERC20Template.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],name:"startOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];function Te(e,t,n){if(!e.s){if(n instanceof Ee){if(!n.s)return void(n.o=Te.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(Te.bind(null,e,t),Te.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var Ee=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var s=1&i?t:n;if(s){try{Te(r,1,s(this.v))}catch(e){Te(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?Te(r,1,t?t(i):i):n?Te(r,1,n(i)):Te(r,2,i)}catch(e){Te(r,2,e)}},r},e}();function xe(e){return e instanceof Ee&&1&e.s}var Pe=function(e,n,r,i){try{var s="number"==typeof r,a=new ve(n,e,i);return Promise.resolve(a.getCurrentTokenTemplateCount()).then(function(n){var i;function o(e){return i?e:-1}var u=1,d=function(e,t,n){for(var r;;){var i=e();if(xe(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!xe(s)){r=1;break}s=s.s}if(t){var a=t();if(a&&a.then&&!xe(a)){r=2;break}}}var o=new Ee,u=Te.bind(null,o,2);return(0===r?i.then(c):1===r?s.then(d):a.then(l)).then(void 0,u),o;function d(r){s=r;do{if(t&&(a=t())&&a.then&&!xe(a))return void a.then(l).then(void 0,u);if(!(i=e())||xe(i)&&!i.v)return void Te(o,1,s);if(i.then)return void i.then(c).then(void 0,u);xe(s=n())&&(s=s.v)}while(!s||!s.then);s.then(d).then(void 0,u)}function c(e){e?(s=n())&&s.then?s.then(d).then(void 0,u):d(s):Te(o,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):Te(o,1,s)}}(function(){return!i&&u<=n},function(){return u++},function(){return Promise.resolve(a.getTokenTemplate(u)).then(function(n){var a=new t.ethers.Contract(n.templateAddress,we,e);return s?Promise.resolve(a.getId()).then(function(e){if(n.isActive&&e.toString()===r.toString())return i=1,u}):n.isActive&&n.templateAddress===r.toString()?(i=1,u):void 0})});return d&&d.then?d.then(o):o(d)})}catch(e){return Promise.reject(e)}};function Se(){try{if("undefined"==typeof window&&process.env.ADDRESS_FILE){var e=f.default.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(e)}return L}catch(e){return L}}function Ae(e){try{var t=Se();if(t)for(var n=Object.keys(t),r=0,i=n;r<i.length;r++){var s=i[r];if(t[s].chainId===e)return t[s]}}catch(e){console.error(e)}return null}var Ce=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}I(n,e);var r=n.prototype;return r.getDefaultAbi=function(){return fe},r.createDatatoken=function(e,n,r,i,s,a,o,u,d,c,l,p,h,f,m,y){try{var b=this;return Promise.resolve(b.getNftPermissions(e,n)).then(function(n){if(!0!==n.deployERC20)throw new Error("Caller is not DatatokenDeployer");if(l||(l=1),!d||!c){var g=ye();d=g.name,c=g.symbol}var v=b.getContract(e);if(!b.signer.provider)throw new Error("Provider is required but not available");return Promise.resolve(b.signer.provider.getNetwork()).then(function(e){var n=e.chainId;function g(){var e=v.createERC20,n=e.estimateGas,g=[d,c],w=l;return Promise.resolve(b.amountToUnits(null,u,18)).then(function(T){return Promise.resolve(b.amountToUnits(null,o,18)).then(function(E){return Promise.resolve(n.call(e,w,g,[r,i,s,a],[T,E],[])).then(function(e){var n;if(y)return e;var g=[r,i,s,a];h&&(g.push(h.toLowerCase()),g.push(f?f.toLowerCase():ue),g.push(m||ue));var w=[d,c],T=l,E=v.createERC20,x=null==(n=b.config)?void 0:n.gasFeeMultiplier,P=b.getSignerAccordingSdk();return Promise.resolve(b.amountToUnits(null,u,18)).then(function(n){return Promise.resolve(b.amountToUnits(null,o,18)).then(function(r){return Promise.resolve(V(e,P,x,E,T,w,g,[n,r],p?[t.toUtf8Bytes(p)]:[])).then(function(e){return Promise.resolve(e.wait()).then(function(e){var t=ne(e,"TokenCreated");return null==t?void 0:t.args[0]})})})})})})})}var w=Ae(Number(n)),T=function(){if(p)return Promise.resolve(Pe(b.signer,w.ERC721Factory,4,Number(n))).then(function(e){l=e})}();return T&&T.then?T.then(g):g()})})}catch(e){return Promise.reject(e)}},r.addManager=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftOwner(e)).then(function(e){if(e!==t)throw new Error("Caller is not NFT Owner");return Promise.resolve(s.addManager.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.addManager,n))})})}catch(e){return Promise.reject(e)}},r.removeManager=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftOwner(e)).then(function(e){if(e!==t)throw new Error("Caller is not NFT Owner");return Promise.resolve(s.removeManager.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.removeManager,n))})})}catch(e){return Promise.reject(e)}},r.addDatatokenDeployer=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftPermissions(e,t)).then(function(e){if(!0!==e.manager)throw new Error("Caller is not Manager");return Promise.resolve(s.addToCreateERC20List.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.addToCreateERC20List,n))})})}catch(e){return Promise.reject(e)}},r.removeDatatokenDeployer=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftPermissions(e,t)).then(function(a){function o(e){if(u||t===n&&!0!==e.deployERC20)throw new Error("Caller is not Manager nor DatatokenDeployer");return Promise.resolve(s.removeFromCreateERC20List.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.removeFromCreateERC20List,n))})}var u=!0!==a.manager;return u||t!==n?o(u||t===n&&i.getNftPermissions(e,t)):Promise.resolve(u||t===n&&i.getNftPermissions(e,t)).then(o)})}catch(e){return Promise.reject(e)}},r.addMetadataUpdater=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftPermissions(e,t)).then(function(e){if(!0!==e.manager)throw new Error("Caller is not Manager");return Promise.resolve(s.addToMetadataList.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.addToMetadataList,n))})})}catch(e){return Promise.reject(e)}},r.removeMetadataUpdater=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftPermissions(e,t)).then(function(a){function o(e){if(u||t!==n&&!0!==e.updateMetadata)throw new Error("Caller is not Manager nor Metadata Updater");return Promise.resolve(s.removeFromMetadataList.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.removeFromMetadataList,n))})}var u=!0!==a.manager;return u||t===n?o(u||t!==n&&i.getNftPermissions(e,t)):Promise.resolve(u||t!==n&&i.getNftPermissions(e,t)).then(o)})}catch(e){return Promise.reject(e)}},r.addStoreUpdater=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftPermissions(e,t)).then(function(e){if(!0!==e.manager)throw new Error("Caller is not Manager");return Promise.resolve(s.addTo725StoreList.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.addTo725StoreList,n))})})}catch(e){return Promise.reject(e)}},r.removeStoreUpdater=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftPermissions(e,t)).then(function(a){function o(e){if(u||t!==n&&!0!==e.store)throw new Error("Caller is not Manager nor storeUpdater");return Promise.resolve(s.removeFrom725StoreList.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.removeFrom725StoreList,n))})}var u=!0!==a.manager;return u||t===n?o(u||t!==n&&i.getNftPermissions(e,t)):Promise.resolve(u||t!==n&&i.getNftPermissions(e,t)).then(o)})}catch(e){return Promise.reject(e)}},r.cleanPermissions=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftOwner(e)).then(function(e){if(e!==t)throw new Error("Caller is not NFT Owner");return Promise.resolve(i.cleanPermissions.estimateGas()).then(function(e){var t;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier,i.cleanPermissions))})})}catch(e){return Promise.reject(e)}},r.transferNft=function(e,t,n,r,i){try{var s=this,a=s.getContract(e);return Promise.resolve(s.getNftOwner(e)).then(function(e){if(e!==t)throw new Error("Caller is not NFT Owner");var o=r||1;return Promise.resolve(a.transferFrom.estimateGas(t,n,o)).then(function(e){var r;return i?e:Promise.resolve(V(e,s.getSignerAccordingSdk(),null==(r=s.config)?void 0:r.gasFeeMultiplier,a.transferFrom,t,n,o))})})}catch(e){return Promise.reject(e)}},r.safeTransferNft=function(e,t,n,r,i){try{var s=this,a=s.getContract(e);return Promise.resolve(s.getNftOwner(e)).then(function(e){if(e!==t)throw new Error("Caller is not NFT Owner");var o=r||1;return Promise.resolve(a.safeTransferFrom.estimateGas(t,n,o)).then(function(e){var r;return i?e:Promise.resolve(V(e,s.getSignerAccordingSdk(),null==(r=s.config)?void 0:r.gasFeeMultiplier,a.safeTransferFrom,t,n,o))})})}catch(e){return Promise.reject(e)}},r.setMetadata=function(e,t,n,r,i,s,a,o,u,d){try{var c=this,l=c.getContract(e);return u||(u=[]),Promise.resolve(c.getNftPermissions(e,t)).then(function(e){if(!e.updateMetadata)throw new Error("Caller is not Metadata updater");var t=r;if(null!=r&&r.includes("/p2p/")){var p,h=r.match(/\/p2p\/([^/]+)/);t=null!=(p=null==h?void 0:h[1])?p:r}return Promise.resolve(l.setMetaData.estimateGas(n,t,i,s,a,o,u)).then(function(e){var r;return d?e:Promise.resolve(V(e,c.signer,null==(r=c.config)?void 0:r.gasFeeMultiplier,l.setMetaData,n,t,i,s,a,o,u))})})}catch(e){return Promise.reject(e)}},r.setMetadataAndTokenURI=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftPermissions(e,t)).then(function(e){if(!e.updateMetadata)throw new Error("Caller is not Metadata updater");var t=k({},n,{metadataProofs:n.metadataProofs||[]});return Promise.resolve(s.setMetaDataAndTokenURI.estimateGas(t)).then(function(e){var n;return r?e:Promise.resolve(V(e,i.signer,null==(n=i.config)?void 0:n.gasFeeMultiplier,s.setMetaDataAndTokenURI,t))})})}catch(e){return Promise.reject(e)}},r.setMetadataState=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getNftPermissions(e,t)).then(function(e){if(!e.updateMetadata)throw new Error("Caller is not Metadata updater");return Promise.resolve(s.setMetaDataState.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.setMetaDataState,n))})})}catch(e){return Promise.reject(e)}},r.setTokenURI=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(i.setTokenURI.estimateGas("1",t)).then(function(e){var s;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,i.setTokenURI,"1",t))})}catch(e){return Promise.reject(e)}},r.getNftOwner=function(e){try{var t=this.getContract(e);return Promise.resolve(t.ownerOf(1))}catch(e){return Promise.reject(e)}},r.getNftPermissions=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.getPermissions(t))}catch(e){return Promise.reject(e)}},r.getMetadata=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getMetaData())}catch(e){return Promise.reject(e)}},r.isDatatokenDeployer=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.isERC20Deployer(t))}catch(e){return Promise.reject(e)}},r.setData=function(e,n,r,i,s){try{var a=this;return Promise.resolve(a.getNftPermissions(e,n)).then(function(n){if(!0!==n.store)throw new Error("User is not ERC20 store updater");var o=a.getContract(e),u=t.keccak256(r),d=t.hexlify(t.toUtf8Bytes(i));return Promise.resolve(o.setNewData.estimateGas(u,d)).then(function(e){var t;return s?e:Promise.resolve(V(e,a.getSignerAccordingSdk(),null==(t=a.config)?void 0:t.gasFeeMultiplier,o.setNewData,u,d))})})}catch(e){return Promise.reject(e)}},r.getData=function(e,n){try{var r=this.getContract(e),i=t.keccak256(n);return Promise.resolve(r.getData(i)).then(function(e){return e?t.toUtf8String(e):null})}catch(e){return Promise.reject(e)}},r.getTokenURI=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.tokenURI(t))}catch(e){return Promise.reject(e)}},r.isDatatokenDeployed=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.isDeployed(t))}catch(e){return Promise.reject(e)}},n}(re),ke=/*#__PURE__*/function(e){function n(t,n,r,i,s){var a;return(a=e.call(this,t,n,r,i)||this).abiEnterprise=void 0,a.nft=void 0,a.abiEnterprise=s||he.abi,a.nft=new Ce(a.signer,n),a}I(n,e);var r=n.prototype;return r.getDefaultAbi=function(){return pe},r.approve=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(s.approve.estimateGas(t,G(null,null,n,18))).then(function(e){var a;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,s.approve,t,G(null,null,n,18)))})}catch(e){return Promise.reject(e)}},r.createFixedRate=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.isDatatokenDeployer(e,t)).then(function(e){if(!e)throw new Error("User is not Datatoken Deployer");n.allowedConsumer||(n.allowedConsumer=ue);var t=!1===n.withMint?0:1;return Promise.resolve(s.createFixedRate.estimateGas(n.fixedRateAddress,[n.baseTokenAddress,n.owner,n.marketFeeCollector,n.allowedConsumer],[n.baseTokenDecimals,n.datatokenDecimals,n.fixedRate,n.marketFee,t])).then(function(e){var a;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,s.createFixedRate,n.fixedRateAddress,[n.baseTokenAddress,n.owner,n.marketFeeCollector,n.allowedConsumer],[n.baseTokenDecimals,n.datatokenDecimals,n.fixedRate,n.marketFee,t]))})})}catch(e){return Promise.reject(e)}},r.createDispenser=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.isDatatokenDeployer(e,t)).then(function(t){if(!t)throw new Error("User is not Datatoken Deployer");var a=s.getContract(e);return r.allowedSwapper||(r.allowedSwapper=ue),r.withMint=!1!==r.withMint,Promise.resolve(a.createDispenser.estimateGas(n,r.maxTokens,r.maxBalance,r.withMint,r.allowedSwapper)).then(function(e){var t;return i?e:Promise.resolve(V(e,s.getSignerAccordingSdk(),null==(t=s.config)?void 0:t.gasFeeMultiplier,a.createDispenser,n,r.maxTokens,r.maxBalance,r.withMint,r.allowedSwapper))})})}catch(e){return Promise.reject(e)}},r.mint=function(e,t,n,r,i){try{var s=this,a=s.getContract(e);return Promise.resolve(s.getPermissions(e,t)).then(function(o){if(!0!==o.minter)throw new Error("Caller is not Minter");return Promise.resolve(s.getCap(e)).then(function(e){if(new b.default(e).gte(n))return Promise.resolve(a.mint.estimateGas(r||t,G(null,null,n,18))).then(function(e){var o;return i?e:Promise.resolve(V(e,s.getSignerAccordingSdk(),null==(o=s.config)?void 0:o.gasFeeMultiplier,a.mint,r||t,G(null,null,n,18)))});throw new Error("Mint amount exceeds cap available")})})}catch(e){return Promise.reject(e)}},r.addMinter=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.isDatatokenDeployer(e,t)).then(function(e){if(!0!==e)throw new Error("Caller is not DatatokenDeployer");return Promise.resolve(s.addMinter.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.addMinter,n))})})}catch(e){return Promise.reject(e)}},r.removeMinter=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.isDatatokenDeployer(e,t)).then(function(e){if(!0!==e)throw new Error("Caller is not DatatokenDeployer");return Promise.resolve(s.removeMinter.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.removeMinter,n))})})}catch(e){return Promise.reject(e)}},r.addPaymentManager=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.isDatatokenDeployer(e,t)).then(function(e){if(!0!==e)throw new Error("Caller is not DatatokenDeployer");return Promise.resolve(s.addPaymentManager.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.addPaymentManager,n))})})}catch(e){return Promise.reject(e)}},r.removePaymentManager=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.isDatatokenDeployer(e,t)).then(function(e){if(!0!==e)throw new Error("Caller is not DatatokenDeployer");return Promise.resolve(s.removePaymentManager.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.removePaymentManager,n))})})}catch(e){return Promise.reject(e)}},r.setPaymentCollector=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getPermissions(e,t)).then(function(a){function o(e){function a(a){function o(e){if(!u&&!d&&!(null==e?void 0:e.deployERC20))throw new Error("Caller is not Fee Manager, owner or Datatoken Deployer");return Promise.resolve(s.setPaymentCollector.estimateGas(n)).then(function(e){var t;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier,s.setPaymentCollector,n))})}var d=e&&a===t;return e&&!d?Promise.resolve(e&&!d&&i.nft.getNftPermissions(e,t)).then(o):o(e&&!d&&i.nft.getNftPermissions(e,t))}return e?Promise.resolve(i.nft.getNftOwner(e)).then(a):a(e)}var u=a.paymentManager;return u?o(!u&&i.getNFTAddress(e)):Promise.resolve(!u&&i.getNFTAddress(e)).then(o)})}catch(e){return Promise.reject(e)}},r.getPaymentCollector=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getPaymentCollector())}catch(e){return Promise.reject(e)}},r.transfer=function(e,t,n,r){try{var i=this,s=i.transferWei;return Promise.resolve(G(null,null,n,18)).then(function(n){return s.call(i,e,t,n,r)})}catch(e){return Promise.reject(e)}},r.transferWei=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(s.transfer.estimateGas(t,n)).then(function(e){var a;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,s.transfer,t,n))})}catch(e){return Promise.reject(e)}},r.startOrder=function(e,t,n,r,i,s){try{var a=this,o=a.getContract(e,a.abi);return i||(i={consumeMarketFeeAddress:ue,consumeMarketFeeToken:ue,consumeMarketFeeAmount:"0"}),Promise.resolve(o.startOrder.estimateGas(t,n,r,i)).then(function(e){var u;return s?e:Promise.resolve(V(e,a.getSignerAccordingSdk(),null==(u=a.config)?void 0:u.gasFeeMultiplier,o.startOrder,t,n,r,i))})}catch(e){return Promise.reject(e)}},r.reuseOrder=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(s.reuseOrder.estimateGas(t,n)).then(function(e){var a;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,s.reuseOrder,t,n))})}catch(e){return Promise.reject(e)}},r.buyFromFreAndOrder=function(e,t,n,r){try{var i=this,s=i.getContract(e,i.abiEnterprise);return Promise.resolve(i.getFreOrderParams(n)).then(function(e){return Promise.resolve(s.buyFromFreAndOrder.estimateGas(t,e)).then(function(n){var a;return r?n:Promise.resolve(V(n,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,s.buyFromFreAndOrder,t,e))})})}catch(e){return Promise.reject(e)}},r.buyFromDispenserAndOrder=function(e,t,n,r){try{var i=this,s=i.getContract(e,i.abiEnterprise);return Promise.resolve(s.buyFromDispenserAndOrder.estimateGas(t,n)).then(function(e){var a;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,s.buyFromDispenserAndOrder,t,n))})}catch(e){return Promise.reject(e)}},r.setData=function(e,n,r,i){try{var s=this;return Promise.resolve(s.isDatatokenDeployer(e,n)).then(function(n){if(!n)throw new Error("User is not Datatoken Deployer");var a=s.getContract(e),o=t.hexlify(t.toUtf8Bytes(r));return Promise.resolve(a.setData.estimateGas(o)).then(function(e){var t;return i?e:Promise.resolve(V(e,s.getSignerAccordingSdk(),null==(t=s.config)?void 0:t.gasFeeMultiplier,a.setData,o))})})}catch(e){return Promise.reject(e)}},r.cleanPermissions=function(e,t,n){try{var r=this,i=r.nft,s=i.getNftOwner;return Promise.resolve(r.getNFTAddress(e)).then(function(a){return Promise.resolve(s.call(i,a)).then(function(i){if(i!==t)throw new Error("Caller is NOT Nft Owner");var s=r.getContract(e);return Promise.resolve(s.cleanPermissions.estimateGas()).then(function(e){var t;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier,s.cleanPermissions))})})})}catch(e){return Promise.reject(e)}},r.getPermissions=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.permissions(t))}catch(e){return Promise.reject(e)}},r.getCap=function(e){try{var t=this,n=t.getContract(e);return Promise.resolve(n.cap()).then(function(e){return Promise.resolve(t.unitsToAmount(null,e,18))})}catch(e){return Promise.reject(e)}},r.getDecimals=function(e){try{var t=this.getContract(e);return Promise.resolve(t.decimals()).then(Number)}catch(e){return Promise.reject(e)}},r.getId=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getId()).then(Number)}catch(e){return Promise.reject(e)}},r.getSymbol=function(e){try{var t=this.getContract(e);return Promise.resolve(t.symbol())}catch(e){return Promise.reject(e)}},r.getName=function(e){try{var t=this.getContract(e);return Promise.resolve(t.name())}catch(e){return Promise.reject(e)}},r.getNFTAddress=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getERC721Address())}catch(e){return Promise.reject(e)}},r.getFixedRates=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getFixedRates())}catch(e){return Promise.reject(e)}},r.getDispensers=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getDispensers())}catch(e){return Promise.reject(e)}},r.isDatatokenDeployer=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.isERC20Deployer(t))}catch(e){return Promise.reject(e)}},r.balance=function(e,t){try{var n=this,r=n.getContract(e);return Promise.resolve(r.balanceOf(t)).then(function(e){return Promise.resolve(n.unitsToAmount(null,e,18))})}catch(e){return Promise.reject(e)}},r.allowance=function(e,t,n,r){void 0===r&&(r=18);try{var i=this,s=i.getContract(e);return Promise.resolve(s.allowance(t,n)).then(function(e){return Promise.resolve(i.unitsToAmount(null,e,r))})}catch(e){return Promise.reject(e)}},r.setPublishingMarketFee=function(e,t,n,r,i,s){try{var a=this,o=a.getContract(e);return Promise.resolve(o.getPublishingMarketFee()).then(function(e){if(e[0]!==i)throw new Error("Caller is not the Publishing Market Fee Address");return Promise.resolve(o.setPublishingMarketFee.estimateGas(t,n,r)).then(function(e){var i;return s?e:Promise.resolve(V(e,a.getSignerAccordingSdk(),null==(i=a.config)?void 0:i.gasFeeMultiplier,o.setPublishingMarketFee,t,n,r))})})}catch(e){return Promise.reject(e)}},r.getPublishingMarketFee=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getPublishingMarketFee()).then(function(e){return{publishMarketFeeAddress:e[0],publishMarketFeeToken:e[1],publishMarketFeeAmount:e[2].toString()}})}catch(e){return Promise.reject(e)}},r.getFreOrderParams=function(e){try{var t=this,n=e.exchangeId,r=e.exchangeContract;return Promise.resolve(G(t.signer,e.baseTokenAddress,e.maxBaseTokenAmount,e.baseTokenDecimals)).then(function(i){return Promise.resolve(G(t.signer,e.baseTokenAddress,e.swapMarketFee,e.baseTokenDecimals)).then(function(t){return{exchangeContract:r,exchangeId:n,maxBaseTokenAmount:i,swapMarketFee:t,marketFeeAddress:e.marketFeeAddress}})})}catch(e){return Promise.reject(e)}},n}(re),Ie=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedMinter",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"AddedPaymentManager",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"CleanedPermissions",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"consumeMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],name:"ConsumeMarketFee",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"currentMinter",type:"address"},{indexed:!1,internalType:"address",name:"newMinter",type:"address"}],name:"MinterApproved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"currentMinter",type:"address"},{indexed:!1,internalType:"address",name:"newMinter",type:"address"}],name:"MinterProposed",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"dispenserContract",type:"address"}],name:"NewDispenser",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"bytes32",name:"exchangeId",type:"bytes32"},{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"address",name:"exchangeContract",type:"address"},{indexed:!0,internalType:"address",name:"baseToken",type:"address"}],name:"NewFixedRate",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"_newPaymentCollector",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"NewPaymentCollector",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"providerAddress",type:"address"},{indexed:!0,internalType:"address",name:"consumerAddress",type:"address"},{indexed:!1,internalType:"bytes32",name:"orderTxId",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"providerData",type:"bytes"},{indexed:!1,internalType:"bytes",name:"providerSignature",type:"bytes"},{indexed:!1,internalType:"bytes",name:"consumerData",type:"bytes"},{indexed:!1,internalType:"bytes",name:"consumerSignature",type:"bytes"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"OrderExecuted",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"bytes32",name:"orderTxId",type:"bytes32"},{indexed:!1,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"number",type:"uint256"}],name:"OrderReused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"consumer",type:"address"},{indexed:!1,internalType:"address",name:"payer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"serviceIndex",type:"uint256"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!0,internalType:"address",name:"publishMarketAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"OrderStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"providerFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"providerFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{indexed:!1,internalType:"bytes",name:"providerData",type:"bytes"},{indexed:!1,internalType:"uint8",name:"v",type:"uint8"},{indexed:!1,internalType:"bytes32",name:"r",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"s",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"validUntil",type:"uint256"}],name:"ProviderFee",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"PublishMarketFeeAddress",type:"address"},{indexed:!0,internalType:"address",name:"PublishMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"PublishMarketFeeAmount",type:"uint256"}],name:"PublishMarketFee",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"address",name:"PublishMarketFeeAddress",type:"address"},{indexed:!1,internalType:"address",name:"PublishMarketFeeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"PublishMarketFeeAmount",type:"uint256"}],name:"PublishMarketFeeChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedMinter",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"signer",type:"address"},{indexed:!1,internalType:"uint256",name:"timestamp",type:"uint256"},{indexed:!1,internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"RemovedPaymentManager",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{stateMutability:"payable",type:"fallback"},{inputs:[{internalType:"address",name:"_minter",type:"address"}],name:"addMinter",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_paymentManager",type:"address"}],name:"addPaymentManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"authERC20",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"}],name:"burn",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"burnFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20Template4.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct ERC20Template4.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],internalType:"struct ERC20Template4.OrderParams",name:"_orderParams",type:"tuple"},{internalType:"address",name:"dispenserContract",type:"address"}],name:"buyFromDispenserAndOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20Template4.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct ERC20Template4.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],internalType:"struct ERC20Template4.OrderParams",name:"_orderParams",type:"tuple"},{components:[{internalType:"address",name:"exchangeContract",type:"address"},{internalType:"bytes32",name:"exchangeId",type:"bytes32"},{internalType:"uint256",name:"maxBaseTokenAmount",type:"uint256"},{internalType:"uint256",name:"swapMarketFee",type:"uint256"},{internalType:"address",name:"marketFeeAddress",type:"address"}],internalType:"struct ERC20Template4.FreParams",name:"_freParams",type:"tuple"}],name:"buyFromFreAndOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cap",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"cleanFrom721",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"cleanPermissions",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"bool",name:"withMint",type:"bool"},{internalType:"address",name:"",type:"address"}],name:"createDispenser",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"fixedPriceAddress",type:"address"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"}],name:"createFixedRate",outputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"subtractedValue",type:"uint256"}],name:"decreaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"getAllowListContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getDenyListContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getDispensers",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getERC721Address",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"serviceId",type:"uint256"},{internalType:"address",name:"providerAddress",type:"address"},{internalType:"bytes",name:"providerSignature",type:"bytes"},{internalType:"bytes",name:"consumerData",type:"bytes"},{internalType:"bytes",name:"consumerSignature",type:"bytes"},{internalType:"address",name:"consumerAddress",type:"address"}],name:"getFilesObject",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFixedRates",outputs:[{components:[{internalType:"address",name:"contractAddress",type:"address"},{internalType:"bytes32",name:"id",type:"bytes32"}],internalType:"struct ERC20Template4.fixedRate[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getPaymentCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getPermissions",outputs:[{components:[{internalType:"bool",name:"minter",type:"bool"},{internalType:"bool",name:"paymentManager",type:"bool"}],internalType:"struct ERC20Roles.RolesERC20",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getPublishingMarketFee",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"addedValue",type:"uint256"}],name:"increaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string[]",name:"strings_",type:"string[]"},{internalType:"address[]",name:"addresses_",type:"address[]"},{internalType:"address[]",name:"factoryAddresses_",type:"address[]"},{internalType:"uint256[]",name:"uints_",type:"uint256[]"},{internalType:"bytes[]",name:"bytes_",type:"bytes[]"}],name:"initialize",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"isERC20Deployer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"isInitialized",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"isMinter",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"mint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"permissions",outputs:[{internalType:"bool",name:"minter",type:"bool"},{internalType:"bool",name:"paymentManager",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_minter",type:"address"}],name:"removeMinter",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_paymentManager",type:"address"}],name:"removePaymentManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderTxId",type:"bytes32"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20Template4.providerFee",name:"_providerFee",type:"tuple"}],name:"reuseOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"contractAddress",type:"address"}],name:"setAllowListContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"contractAddress",type:"address"}],name:"setDenyListContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes",name:"filesObject",type:"bytes"}],name:"setFilesObject",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newPaymentCollector",type:"address"}],name:"setPaymentCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_publishMarketFeeAddress",type:"address"},{internalType:"address",name:"_publishMarketFeeToken",type:"address"},{internalType:"uint256",name:"_publishMarketFeeAmount",type:"uint256"}],name:"setPublishingMarketFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"consumer",type:"address"},{internalType:"uint256",name:"serviceIndex",type:"uint256"},{components:[{internalType:"address",name:"providerFeeAddress",type:"address"},{internalType:"address",name:"providerFeeToken",type:"address"},{internalType:"uint256",name:"providerFeeAmount",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"},{internalType:"uint256",name:"validUntil",type:"uint256"},{internalType:"bytes",name:"providerData",type:"bytes"}],internalType:"struct ERC20Template4.providerFee",name:"_providerFee",type:"tuple"},{components:[{internalType:"address",name:"consumeMarketFeeAddress",type:"address"},{internalType:"address",name:"consumeMarketFeeToken",type:"address"},{internalType:"uint256",name:"consumeMarketFeeAmount",type:"uint256"}],internalType:"struct ERC20Template4.consumeMarketFee",name:"_consumeMarketFee",type:"tuple"}],name:"startOrder",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"withdrawETH",outputs:[],stateMutability:"payable",type:"function"},{stateMutability:"payable",type:"receive"}],De=/*#__PURE__*/function(e){function t(t,n,r,i,s){var a;return(a=e.call(this,t,r,i,s)||this).accessList=void 0,a.fileObject=void 0,a.abi=a.getDefaultAbi(),a.fileObject=n,a}I(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Ie},n.setFileObj=function(e){this.fileObject=e},n.getAllowlistContract=function(e){try{var t=this.getContract(e,this.getDefaultAbi());return Promise.resolve(t.getAllowListContract())}catch(e){return Promise.reject(e)}},n.getDenylistContract=function(e){try{var t=this.getContract(e,this.getDefaultAbi());return Promise.resolve(t.getDenyListContract())}catch(e){return Promise.reject(e)}},n.setAllowListContract=function(e,t,n,r){try{var i=this;return Promise.resolve(i.isDatatokenDeployer(e,n)).then(function(n){if(!n)throw new Error("User is not Datatoken Deployer");var s=i.getContract(e);return Promise.resolve(s.setAllowListContract.estimateGas(t)).then(function(e){var n;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(n=i.config)?void 0:n.gasFeeMultiplier,s.setAllowListContract,t))})})}catch(e){return Promise.reject(e)}},n.setDenyListContract=function(e,t,n,r){try{var i=this;return Promise.resolve(i.isDatatokenDeployer(e,n)).then(function(n){if(!n)throw new Error("User is not Datatoken Deployer");var s=i.getContract(e);return Promise.resolve(s.setDenyListContract.estimateGas(t)).then(function(e){var n;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(n=i.config)?void 0:n.gasFeeMultiplier,s.setDenyListContract,t))})})}catch(e){return Promise.reject(e)}},n.setFileObject=function(e,t,n){try{var r=this;return Promise.resolve(r.isDatatokenDeployer(e,t)).then(function(t){if(!t)throw new Error("User is not Datatoken Deployer");var i=r.getContract(e);return Promise.resolve(i.setFilesObject.estimateGas(r.fileObject)).then(function(e){var t;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier,i.setFilesObject,r.fileObject))})})}catch(e){return Promise.reject(e)}},n.getFileObject=function(e,t,n,r,i,s,a){try{var o=this.getContract(e,this.getDefaultAbi());return Promise.resolve(o.getFileObject(t,n,r,i,s,a))}catch(e){return Promise.reject(e)}},t}(ke),Me=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"wallet",type:"address"},{indexed:!1,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"AddressAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"AddressRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"approved",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"_fromTokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"_toTokenId",type:"uint256"}],name:"BatchMetadataUpdate",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"_tokenId",type:"uint256"}],name:"MetadataUpdate",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"user",type:"address[]"},{internalType:"string[]",name:"_tokenURI",type:"string[]"}],name:"batchMint",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"burn",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getApproved",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner_",type:"address"},{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"},{internalType:"bool",name:"transferable_",type:"bool"},{internalType:"address[]",name:"user",type:"address[]"},{internalType:"string[]",name:"_tokenURI",type:"string[]"}],name:"initialize",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"_tokenURI",type:"string"}],name:"mint",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ownerOf",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"index",type:"uint256"}],name:"tokenByIndex",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"uint256",name:"index",type:"uint256"}],name:"tokenOfOwnerByIndex",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"tokenURI",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"transferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"transferable",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],Fe=/*#__PURE__*/function(e){function t(t,n,r,i,s){var a;return(a=e.call(this,t,n,r,i,s)||this).abiEnterprise=void 0,a.abi=s||a.getDefaultAbi(),a}I(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Me},n.getTokenUri=function(e){try{return Promise.resolve(this.contract.tokenURI(e))}catch(e){return Promise.reject(e)}},n.getOwner=function(){try{return Promise.resolve(this.contract.owner())}catch(e){return Promise.reject(e)}},n.getId=function(){try{return Promise.resolve(this.contract.getId()).then(Number)}catch(e){return Promise.reject(e)}},n.getName=function(){try{return Promise.resolve(this.contract.name())}catch(e){return Promise.reject(e)}},n.getSymbol=function(){try{return Promise.resolve(this.contract.symbol())}catch(e){return Promise.reject(e)}},n.balance=function(e){try{var t=this;return Promise.resolve(t.contract.balanceOf(e)).then(function(e){return Promise.resolve(t.unitsToAmount(null,e,18))})}catch(e){return Promise.reject(e)}},n.mint=function(e,t,n){try{var r=this;return Promise.resolve(r.contract.mint.estimateGas(e,t)).then(function(i){var s;return n?i:Promise.resolve(V(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.mint,e,t))})}catch(e){return Promise.reject(e)}},n.batchMint=function(e,t,n){try{var r=this;return Promise.resolve(r.contract.batchMint.estimateGas(e,t)).then(function(i){var s;return n?i:Promise.resolve(V(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.batchMint,e,t))})}catch(e){return Promise.reject(e)}},n.burn=function(e,t){try{var n=this;return Promise.resolve(n.contract.burn.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.burn,e))})}catch(e){return Promise.reject(e)}},n.transferOwnership=function(e,t){try{var n=this;return Promise.resolve(n.contract.transferOwnership.estimateGas(e)).then(function(r){var i;return t?r:Promise.resolve(V(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier,n.contract.transferOwnership,e))})}catch(e){return Promise.reject(e)}},n.renounceOwnership=function(e){try{var t=this;return Promise.resolve(t.contract.renounceOwnership.estimateGas()).then(function(n){var r;return e?n:Promise.resolve(V(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier,t.contract.renounceOwnership))})}catch(e){return Promise.reject(e)}},t}(ie),Re=[{inputs:[{internalType:"address",name:"_template",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"instance",type:"address"}],name:"InstanceDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"contractAddress",type:"address"},{indexed:!0,internalType:"address",name:"owner",type:"address"}],name:"NewAccessList",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"accessListDeployedContracts",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_newTemplateAddress",type:"address"}],name:"changeTemplateAddress",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"bool",name:"transferable",type:"bool"},{internalType:"address",name:"owner",type:"address"},{internalType:"address[]",name:"user",type:"address[]"},{internalType:"string[]",name:"_tokenURI",type:"string[]"}],name:"deployAccessListContract",outputs:[{internalType:"address",name:"token",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"contractAddress",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"contractAddress",type:"address"}],name:"isSoulBound",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}],_e=/*#__PURE__*/function(e){function t(t,n,r,i,s){var a;return(a=e.call(this,t,n,r,i,s)||this).abi=s||a.getDefaultAbi(),a}I(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Re},n.deployAccessListContract=function(e,t,n,r,i,s,a){void 0===r&&(r=!1);try{var o=this;if(!e||!t){var u=ye();e=u.name,t=u.symbol}return Promise.resolve(o.contract.deployAccessListContract.estimateGas(e,t,r,i,s,n)).then(function(u){return a?u:function(a,d){try{var c=Promise.resolve(V(u,o.getSignerAccordingSdk(),null==(l=o.config)?void 0:l.gasFeeMultiplier,o.contract.deployAccessListContract,e,t,r,i,s,n)).then(function(e){if(!e){var t="Tx for deploying new access list was not processed on chain.";throw console.error(t),t}return Promise.resolve(e.wait()).then(function(e){return ne(e,"NewAccessList").args[0]})})}catch(e){return d(e)}var l;return c&&c.then?c.then(void 0,d):c}(0,function(e){console.error("Creation of AccessList failed: "+e)})})}catch(e){return Promise.reject(e)}},n.getOwner=function(){try{return Promise.resolve(this.contract.owner())}catch(e){return Promise.reject(e)}},n.isSoulbound=function(e){try{return Promise.resolve(this.contract.isSoulBound(e))}catch(e){return Promise.reject(e)}},n.isDeployed=function(e){try{return Promise.resolve(this.contract.isDeployed(e))}catch(e){return Promise.reject(e)}},n.changeTemplateAddress=function(e,t,n){try{var r=this;return Promise.resolve(r.getOwner()).then(function(i){if(i!==e)throw new Error("Caller is not Factory Owner");if(t===ue)throw new Error("Template address cannot be ZERO address");return Promise.resolve(r.contract.changeTemplateAddress.estimateGas(t)).then(function(e){var i;return n?e:Promise.resolve(V(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.changeTemplateAddress,t))})})}catch(e){return Promise.reject(e)}},t}(ie),Le=[{inputs:[{internalType:"address",name:"_factoryRouter",type:"address"},{internalType:"address",name:"_opcCollector",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"payer",type:"address"},{indexed:!0,internalType:"address",name:"payee",type:"address"},{indexed:!1,internalType:"uint256",name:"maxLockedAmount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"maxLockSeconds",type:"uint256"},{indexed:!1,internalType:"uint256",name:"maxLockCounts",type:"uint256"}],name:"Auth",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"payee",type:"address"},{indexed:!1,internalType:"uint256",name:"jobId",type:"uint256"},{indexed:!1,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"payer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Canceled",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"payee",type:"address"},{indexed:!1,internalType:"uint256",name:"jobId",type:"uint256"},{indexed:!1,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"payer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bytes",name:"proof",type:"bytes"}],name:"Claimed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"payer",type:"address"},{indexed:!1,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"payer",type:"address"},{indexed:!1,internalType:"address",name:"payee",type:"address"},{indexed:!1,internalType:"uint256",name:"jobId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"expiry",type:"uint256"},{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"Lock",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"payer",type:"address"},{indexed:!1,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"payee",type:"address"},{internalType:"uint256",name:"maxLockedAmount",type:"uint256"},{internalType:"uint256",name:"maxLockSeconds",type:"uint256"},{internalType:"uint256",name:"maxLockCounts",type:"uint256"}],name:"authorize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address[]",name:"token",type:"address[]"},{internalType:"address[]",name:"payee",type:"address[]"},{internalType:"uint256[]",name:"maxLockedAmount",type:"uint256[]"},{internalType:"uint256[]",name:"maxLockSeconds",type:"uint256[]"},{internalType:"uint256[]",name:"maxLockCounts",type:"uint256[]"}],name:"authorizeMultiple",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"jobId",type:"uint256"},{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"payer",type:"address"},{internalType:"address",name:"payee",type:"address"}],name:"cancelExpiredLock",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"jobId",type:"uint256[]"},{internalType:"address[]",name:"token",type:"address[]"},{internalType:"address[]",name:"payer",type:"address[]"},{internalType:"address[]",name:"payee",type:"address[]"}],name:"cancelExpiredLocks",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"jobId",type:"uint256"},{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"payer",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"proof",type:"bytes"}],name:"claimLock",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"jobId",type:"uint256"},{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"payer",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"proof",type:"bytes"}],name:"claimLockAndWithdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"jobId",type:"uint256[]"},{internalType:"address[]",name:"token",type:"address[]"},{internalType:"address[]",name:"payer",type:"address[]"},{internalType:"uint256[]",name:"amount",type:"uint256[]"},{internalType:"bytes[]",name:"proof",type:"bytes[]"}],name:"claimLocks",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"jobId",type:"uint256[]"},{internalType:"address[]",name:"token",type:"address[]"},{internalType:"address[]",name:"payer",type:"address[]"},{internalType:"uint256[]",name:"amount",type:"uint256[]"},{internalType:"bytes[]",name:"proof",type:"bytes[]"}],name:"claimLocksAndWithdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"jobId",type:"uint256"},{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"payer",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"expiry",type:"uint256"}],name:"createLock",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"jobId",type:"uint256[]"},{internalType:"address[]",name:"token",type:"address[]"},{internalType:"address[]",name:"payer",type:"address[]"},{internalType:"uint256[]",name:"amount",type:"uint256[]"},{internalType:"uint256[]",name:"expiry",type:"uint256[]"}],name:"createLocks",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"deposit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address[]",name:"token",type:"address[]"},{internalType:"uint256[]",name:"amount",type:"uint256[]"}],name:"depositMultiple",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"depositWithPermit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"factoryRouter",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"payer",type:"address"},{internalType:"address",name:"payee",type:"address"}],name:"getAuthorizations",outputs:[{components:[{internalType:"address",name:"payee",type:"address"},{internalType:"uint256",name:"maxLockedAmount",type:"uint256"},{internalType:"uint256",name:"currentLockedAmount",type:"uint256"},{internalType:"uint256",name:"maxLockSeconds",type:"uint256"},{internalType:"uint256",name:"maxLockCounts",type:"uint256"},{internalType:"uint256",name:"currentLocks",type:"uint256"}],internalType:"struct Escrow.auth[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"getFunds",outputs:[{components:[{internalType:"uint256",name:"available",type:"uint256"},{internalType:"uint256",name:"locked",type:"uint256"}],internalType:"struct Escrow.userFunds",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"payer",type:"address"},{internalType:"address",name:"payee",type:"address"}],name:"getLocks",outputs:[{components:[{internalType:"uint256",name:"jobId",type:"uint256"},{internalType:"address",name:"payer",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"address",name:"token",type:"address"}],internalType:"struct Escrow.lock[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"payer",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"getUserFunds",outputs:[{components:[{internalType:"uint256",name:"available",type:"uint256"},{internalType:"uint256",name:"locked",type:"uint256"}],internalType:"struct Escrow.userFunds",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserTokens",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"opcCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"token",type:"address[]"},{internalType:"uint256[]",name:"amount",type:"uint256[]"}],name:"withdraw",outputs:[],stateMutability:"nonpayable",type:"function"}];function Ne(e,t,n){if(!e.s){if(n instanceof Oe){if(!n.s)return void(n.o=Ne.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(Ne.bind(null,e,t),Ne.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var Oe=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var s=1&i?t:n;if(s){try{Ne(r,1,s(this.v))}catch(e){Ne(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?Ne(r,1,t?t(i):i):n?Ne(r,1,n(i)):Ne(r,2,i)}catch(e){Ne(r,2,e)}},r},e}(),Be=/*#__PURE__*/function(e){function n(t,n,r,i,s){var a;return(a=e.call(this,t,n,r,i,s)||this).abiEnterprise=void 0,a.abi=s||a.getDefaultAbi(),a}I(n,e);var r=n.prototype;return r.getDefaultAbi=function(){return Le},r.getFunds=function(e){try{return Promise.resolve(this.contract.getFunds(e))}catch(e){return Promise.reject(e)}},r.getUserFunds=function(e,t){try{return Promise.resolve(this.contract.getUserFunds(e,t))}catch(e){return Promise.reject(e)}},r.getUserTokens=function(e){try{return Promise.resolve(this.contract.getUserTokens(e))}catch(e){return Promise.reject(e)}},r.getLocks=function(e,t,n){try{return Promise.resolve(this.contract.getLocks(e,t,n))}catch(e){return Promise.reject(e)}},r.getAuthorizations=function(e,t,n){try{return Promise.resolve(this.contract.getAuthorizations(e,t,n))}catch(e){return Promise.reject(e)}},r.verifyFundsForEscrowPayment=function(e,n,r,i,s,a,o){try{var u,d=this;return Promise.resolve(null==(u=d.signer.provider)?void 0:u.getBalance(t.getAddress(n))).then(function(u){if(new y.default(u).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};var c=new ke(d.signer),l=c.allowance;return Promise.resolve(d.signer.getAddress()).then(function(u){return Promise.resolve(l.call(c,e,u,d.contract.target.toString(),o)).then(function(u){return Promise.resolve(d.amountToUnits(e,u,18)).then(function(u){function l(){var u=c.balance;return Promise.resolve(d.signer.getAddress()).then(function(l){return Promise.resolve(u.call(c,e,l)).then(function(u){if(new y.default(u).isZero())return{isValid:!1,message:"Payment token balance is 0. Please add funds"};var c=d.getAuthorizations;return Promise.resolve(d.signer.getAddress()).then(function(l){return Promise.resolve(c.call(d,e,l,n)).then(function(c){var l=d.getUserFunds;return Promise.resolve(d.signer.getAddress()).then(function(p){return Promise.resolve(l.call(d,p,e)).then(function(l){function p(){var r=function(){if(0===c.length)return Promise.resolve(d.authorize(t.getAddress(e),t.getAddress(n),(Number(i)/2).toString(),s,a)).then(function(){})}();return r&&r.then?r.then(function(){return{isValid:!0,message:""}}):{isValid:!0,message:""}}var h=function(){if(new y.default(l[0]).isZero()){var n=function(){if(r&&new y.default(t.parseEther(u)).isLessThanOrEqualTo(new y.default(t.parseEther(r)))&&new y.default(t.parseEther(r)).isGreaterThan(new y.default(i)))return Promise.resolve(d.deposit(e,r,o)).then(function(){});var n=function(){if(new y.default(t.parseEther(u)).isLessThanOrEqualTo(new y.default(t.parseEther(i)))){var n=d.deposit;return Promise.resolve(d.unitsToAmount(e,i,o)).then(function(t){return Promise.resolve(n.call(d,e,t,o)).then(function(){})})}return Promise.resolve(d.deposit(e,u,o)).then(function(){})}();return n&&n.then?n.then(function(){}):void 0}();if(n&&n.then)return n.then(function(){})}}();return h&&h.then?h.then(p):p()})})})})})})}var p=function(){if(new y.default(u).isLessThan(new y.default(i)))return Promise.resolve(c.approve(t.getAddress(e),t.getAddress(d.contract.target.toString()),i)).then(function(){})}();return p&&p.then?p.then(l):l()})})})})}catch(e){return Promise.reject(e)}},r.deposit=function(e,t,n,r){try{var i=this;return Promise.resolve(i.amountToUnits(e,t,n)).then(function(t){return Promise.resolve(i.contract.deposit.estimateGas(e,t)).then(function(n){var s;return r?n:Promise.resolve(V(n,i.getSignerAccordingSdk(),null==(s=i.config)?void 0:s.gasFeeMultiplier,i.contract.deposit,e,t))})})}catch(e){return Promise.reject(e)}},r.withdraw=function(e,t,n,r){try{var i=this,s=[],a=[];if(e.length!==t.length)throw new Error("Tokens and amounts arrays must have the same length");return Promise.resolve(i.signer.getAddress()).then(function(o){function u(){return Promise.resolve(Promise.all(a.map(function(e,t){return i.amountToUnits(s[t],e,n)}))).then(function(t){return Promise.resolve(i.contract.withdraw.estimateGas(e,t)).then(function(e){var n;return r?e:Promise.resolve(V(e,i.getSignerAccordingSdk(),null==(n=i.config)?void 0:n.gasFeeMultiplier,i.contract.withdraw,s,t))})})}var d=function(e,t){var n,r,i=-1;return function s(a){try{for(;++i<e.length;)if((a=t(i))&&a.then){if(!((o=a)instanceof Oe&&1&o.s))return void a.then(s,r||(r=Ne.bind(null,n=new Oe,2)));a=a.v}n?Ne(n,1,a):n=a}catch(e){Ne(n||(n=new Oe),2,e)}var o}(),n}(e,function(n){var r=e[n],u=new y.default(t[n]);return Promise.resolve(i.getUserFunds(o,r)).then(function(e){var i=new y.default(e[0]);u.isGreaterThan(0)&&u.isLessThanOrEqualTo(i)?(s.push(r),a.push(t[n])):console.log("Insufficient funds for token "+r)})});return d&&d.then?d.then(u):u()})}catch(e){return Promise.reject(e)}},r.authorize=function(e,t,n,r,i,s,a){try{var o=this,u=o.getAuthorizations;return Promise.resolve(o.signer.getAddress()).then(function(d){return Promise.resolve(u.call(o,e,d,t)).then(function(u){return 0!==u.length?(console.log("Payee "+t+" already authorized"),null):Promise.resolve(o.amountToUnits(e,n,s)).then(function(n){return Promise.resolve(o.amountToUnits(e,r,s)).then(function(r){return Promise.resolve(o.amountToUnits(e,i,s)).then(function(i){return Promise.resolve(o.contract.authorize.estimateGas(e,t,n,r,i)).then(function(s){var u;return a?s:Promise.resolve(V(s,o.getSignerAccordingSdk(),null==(u=o.config)?void 0:u.gasFeeMultiplier,o.contract.authorize,e,t,n,r,i))})})})})})})}catch(e){return Promise.reject(e)}},r.cancelExpiredLocks=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.contract.cancelExpiredLocks.estimateGas(e,t,n,r)).then(function(a){var o;return i?a:Promise.resolve(V(a,s.getSignerAccordingSdk(),null==(o=s.config)?void 0:o.gasFeeMultiplier,s.contract.cancelExpiredLocks,e,t,n,r))})}catch(e){return Promise.reject(e)}},n}(ie),Ue=[{inputs:[{internalType:"address payable",name:"newCollector",type:"address"},{internalType:"address",name:"OwnerAddress",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"oldCollector",type:"address"},{indexed:!0,internalType:"address",name:"newCollector",type:"address"},{indexed:!1,internalType:"address",name:"caller",type:"address"}],name:"CollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"tokenAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"minFee",type:"uint256"},{indexed:!1,internalType:"uint256",name:"maxFee",type:"uint256"},{indexed:!1,internalType:"uint256",name:"feePercentage",type:"uint256"},{indexed:!1,internalType:"bool",name:"allowed",type:"bool"},{indexed:!1,internalType:"address",name:"caller",type:"address"}],name:"TokenUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"collector",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"address",name:"caller",type:"address"}],name:"WithdrawETH",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"collector",type:"address"},{indexed:!0,internalType:"address",name:"tokenAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"address",name:"caller",type:"address"}],name:"WithdrawToken",type:"event"},{stateMutability:"payable",type:"fallback"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"calculateFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address payable",name:"newCollector",type:"address"}],name:"changeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"getToken",outputs:[{components:[{internalType:"bool",name:"allowed",type:"bool"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"feePercentage",type:"uint256"}],internalType:"struct EnterpriseFeeCollector.Token",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"isTokenAllowed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"tokenList",outputs:[{internalType:"bool",name:"allowed",type:"bool"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"feePercentage",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"},{internalType:"uint256",name:"minFee",type:"uint256"},{internalType:"uint256",name:"maxFee",type:"uint256"},{internalType:"uint256",name:"feePercentage",type:"uint256"},{internalType:"bool",name:"allowed",type:"bool"}],name:"updateToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"withdrawETH",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"withdrawToken",outputs:[],stateMutability:"nonpayable",type:"function"},{stateMutability:"payable",type:"receive"}],je=/*#__PURE__*/function(e){function t(t,n,r,i,s){var a;return(a=e.call(this,t,n,r,i,s)||this).abi=s||a.getDefaultAbi(),a}I(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Ue},n.isTokenAllowed=function(e){try{return Promise.resolve(this.contract.isTokenAllowed(e))}catch(e){return Promise.reject(e)}},n.getToken=function(e){try{return Promise.resolve(this.contract.getToken(e))}catch(e){return Promise.reject(e)}},n.calculateFee=function(e,t,n){try{var r=this,i=r.amountToUnits(e,t.toString(),n);return Promise.resolve(r.contract.calculateFee(e,i)).then(function(t){return r.unitsToAmount(e,t,n)})}catch(e){return Promise.reject(e)}},t}(ie),qe=function(e){try{return Promise.resolve(new Promise(function(t){setTimeout(t,e)}))}catch(e){return Promise.reject(e)}},$e=function(e,n){try{var r=t.ethers.solidityPackedKeccak256(["bytes"],[t.ethers.hexlify(t.ethers.toUtf8Bytes(n))]),i=t.ethers.toBeArray(r);return Promise.resolve(function(t,n){try{var r=Promise.resolve(e.signMessage(i))}catch(e){return n()}return r&&r.then?r.then(void 0,n):r}(0,function(){return Promise.resolve(e.provider.getNetwork()).then(function(t){var n=Number(t.chainId);return function(){if(8996===Number(n))return console.log("Signing message with _legacySignMessage"),Promise.resolve(e._legacySignMessage(i))}()})}))}catch(e){return Promise.reject(e)}};const ze=Symbol.for("@libp2p/connection"),Ve=Symbol.for("@libp2p/content-routing");class Ge extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class Ke extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}class He extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}}class We extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Qe extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}Error;class Ye extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class Je extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class Ze extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class Xe extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class et extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class tt extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class nt extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}}class rt extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}class it extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}}class st extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class at extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class ot extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class ut extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}class dt extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}}class ct extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}}class lt extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}class pt extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}class ht extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}}class ft extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class mt extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class yt extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class bt extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}class gt extends Event{data;constructor(e,t){super("message",t),this.data=e}}class vt extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}}class wt extends vt{constructor(e,t){super(!0,e,t)}}class Tt extends vt{constructor(e,t){super(!1,e,t)}}const Et=Symbol.for("@libp2p/peer-discovery"),xt=Symbol.for("@libp2p/peer-id");function Pt(e){return Boolean(e?.[xt])}const St=Symbol.for("@libp2p/peer-routing"),At="keep-alive";function Ct(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}async function kt(...e){const t=[];for(const n of e)Ct(n)&&t.push(n);await Promise.all(t.map(async e=>{null!=e.beforeStart&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{null!=e.afterStart&&await e.afterStart()}))}async function It(...e){const t=[];for(const n of e)Ct(n)&&t.push(n);await Promise.all(t.map(async e=>{null!=e.beforeStop&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{null!=e.afterStop&&await e.afterStop()}))}const Dt=Symbol.for("@libp2p/transport");var Mt;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Mt||(Mt={}));class Ft extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let r=this.#e.get(e);null==r&&(r=[],this.#e.set(e,r)),r.push({callback:t,once:(!0!==n&&!1!==n&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let r=this.#e.get(e);null!=r&&(r=r.filter(({callback:e})=>e!==t),this.#e.set(e,r))}dispatchEvent(e){const t=super.dispatchEvent(e);let n=this.#e.get(e.type);return null==n||(n=n.filter(({once:e})=>!e),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}const Rt=Symbol.for("@libp2p/service-capabilities"),_t=Symbol.for("@libp2p/service-dependencies");function Lt(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}class Nt{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Ot{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;const r=t.codePointAt(0);if(void 0===r)throw new Error("Invalid prefix character");this.prefixCodePoint=r,this.baseDecode=n}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Ut(this,e)}}class Bt{decoders;constructor(e){this.decoders=e}or(e){return Ut(this,e)}decode(e){const t=this.decoders[e[0]];if(null!=t)return t.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Ut(e,t){return new Bt({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class jt{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,r){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=r,this.encoder=new Nt(e,t,n),this.decoder=new Ot(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function qt({name:e,prefix:t,encode:n,decode:r}){return new jt(e,t,n,r)}function $t({name:e,prefix:t,alphabet:n}){const{encode:r,decode:i}=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),a=s.charCodeAt(0);if(255!==n[a])throw new TypeError(s+" is ambiguous");n[a]=i}var o=e.length,u=e.charAt(0),d=Math.log(o)/Math.log(256),c=Math.log(256)/Math.log(o);function l(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var r=0,i=0;e[t]===u;)r++,t++;for(var s=(e.length-t)*d+1>>>0,a=new Uint8Array(s);e[t];){var c=n[e.charCodeAt(t)];if(255===c)return;for(var l=0,p=s-1;(0!==c||l<i)&&-1!==p;p--,l++)a[p]=(c+=o*a[p]>>>0)%256>>>0,c=c/256>>>0;if(0!==c)throw new Error("Non-zero carry");i=l,t++}if(" "!==e[t]){for(var h=s-i;h!==s&&0===a[h];)h++;for(var f=new Uint8Array(r+(s-h)),m=r;h!==s;)f[m++]=a[h++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var n=0,r=0,i=0,s=t.length;i!==s&&0===t[i];)i++,n++;for(var a=(s-i)*c+1>>>0,d=new Uint8Array(a);i!==s;){for(var l=t[i],p=0,h=a-1;(0!==l||p<r)&&-1!==h;h--,p++)d[h]=(l+=256*d[h]>>>0)%o>>>0,l=l/o>>>0;if(0!==l)throw new Error("Non-zero carry");r=p,i++}for(var f=a-r;f!==a&&0===d[f];)f++;for(var m=u.repeat(n);f<a;++f)m+=e.charAt(d[f]);return m},decodeUnsafe:l,decode:function(e){var n=l(e);if(n)return n;throw new Error(`Non-${t} character`)}}}(n,e);return qt({prefix:t,name:e,encode:r,decode:e=>Lt(i(e))})}function zt({name:e,prefix:t,bitsPerChar:n,alphabet:r}){const i=function(e){const t={};for(let n=0;n<e.length;++n)t[e[n]]=n;return t}(r);return qt({prefix:t,name:e,encode:e=>function(e,t,n){const r="="===t[t.length-1],i=(1<<n)-1;let s="",a=0,o=0;for(let r=0;r<e.length;++r)for(o=o<<8|e[r],a+=8;a>n;)a-=n,s+=t[i&o>>a];if(0!==a&&(s+=t[i&o<<n-a]),r)for(;s.length*n&7;)s+="=";return s}(e,r,n),decode:t=>function(e,t,n,r){let i=e.length;for(;"="===e[i-1];)--i;const s=new Uint8Array(i*n/8|0);let a=0,o=0,u=0;for(let d=0;d<i;++d){const i=t[e[d]];if(void 0===i)throw new SyntaxError(`Non-${r} character`);o=o<<n|i,a+=n,a>=8&&(a-=8,s[u++]=255&o>>a)}if(a>=n||255&o<<8-a)throw new SyntaxError("Unexpected end of data");return s}(t,i,n,e)})}const Vt=$t({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gt=$t({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Kt={__proto__:null,base58btc:Vt,base58flickr:Gt};const Ht=zt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wt=zt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qt=zt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yt=zt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Jt=zt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Zt=zt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xt=zt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),en=zt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tn=zt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var nn={__proto__:null,base32:Ht,base32upper:Wt,base32pad:Qt,base32padupper:Yt,base32hex:Jt,base32hexupper:Zt,base32hexpad:Xt,base32hexpadupper:en,base32z:tn};const rn=$t({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sn=$t({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var an={__proto__:null,base36:rn,base36upper:sn},on=Math.pow(2,31),un=Math.pow(2,7),dn=Math.pow(2,14),cn=Math.pow(2,21),ln=Math.pow(2,28),pn=Math.pow(2,35),hn=Math.pow(2,42),fn=Math.pow(2,49),mn=Math.pow(2,56),yn=Math.pow(2,63),bn={encode:function e(t,n,r){n=n||[];for(var i=r=r||0;t>=on;)n[r++]=255&t|128,t/=128;for(;-128&t;)n[r++]=255&t|128,t>>>=7;return n[r]=0|t,e.bytes=r-i+1,n},decode:function e(t,n){var r,i=0,s=0,a=n=n||0,o=t.length;do{if(a>=o)throw e.bytes=0,new RangeError("Could not decode varint");r=t[a++],i+=s<28?(127&r)<<s:(127&r)*Math.pow(2,s),s+=7}while(r>=128);return e.bytes=a-n,i},encodingLength:function(e){return e<un?1:e<dn?2:e<cn?3:e<ln?4:e<pn?5:e<hn?6:e<fn?7:e<mn?8:e<yn?9:10}},gn=bn;function vn(e,t=0){return[gn.decode(e,t),gn.decode.bytes]}function wn(e,t,n=0){return gn.encode(e,t,n),t}function Tn(e){return gn.encodingLength(e)}function En(e,t){const n=t.byteLength,r=Tn(e),i=r+Tn(n),s=new Uint8Array(i+n);return wn(e,s,0),wn(n,s,r),s.set(t,i),new Pn(e,n,t,s)}function xn(e){const t=Lt(e),[n,r]=vn(t),[i,s]=vn(t.subarray(r)),a=t.subarray(r+s);if(a.byteLength!==i)throw new Error("Incorrect length");return new Pn(n,i,a,t)}class Pn{code;size;digest;bytes;constructor(e,t,n,r){this.code=e,this.size=t,this.digest=n,this.bytes=r}}function Sn(e,t){const{bytes:n,version:r}=e;return 0===r?function(e,t,n){const{prefix:r}=n;if(r!==Vt.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const i=t.get(r);if(null==i){const i=n.encode(e).slice(1);return t.set(r,i),i}return i}(n,Cn(e),t??Vt.encoder):function(e,t,n){const{prefix:r}=n,i=t.get(r);if(null==i){const i=n.encode(e);return t.set(r,i),i}return i}(n,Cn(e),t??Ht.encoder)}const An=new WeakMap;function Cn(e){const t=An.get(e);if(null==t){const t=new Map;return An.set(e,t),t}return t}class kn{code;version;multihash;bytes;"/";constructor(e,t,n,r){this.code=t,this.version=e,this.multihash=n,this.bytes=r,this["/"]=r}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:t}=this;if(e!==In)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Dn)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return kn.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,n=En(e,t);return kn.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return kn.equals(this,e)}static equals(e,t){return null!=t&&e.code===t.code&&e.version===t.version&&function(e,t){return e===t||e.code===t.code&&e.size===t.size&&t.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}(e.bytes,t.bytes)}(e.multihash,t.multihash)}toString(e){return Sn(this,e)}toJSON(){return{"/":Sn(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof kn)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:n,multihash:r,bytes:i}=t;return new kn(e,n,r,i??Mn(e,n,r.bytes))}if(!0===t[Fn]){const{version:e,multihash:n,code:r}=t,i=xn(n);return kn.create(e,r,i)}return null}static create(e,t,n){if("number"!=typeof t)throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:if(t!==In)throw new Error(`Version 0 CID must use dag-pb (code: ${In}) block encoding`);return new kn(e,t,n,n.bytes);case 1:{const r=Mn(e,t,n.bytes);return new kn(e,t,n,r)}default:throw new Error("Invalid version")}}static createV0(e){return kn.create(0,In,e)}static createV1(e,t){return kn.create(1,e,t)}static decode(e){const[t,n]=kn.decodeFirst(e);if(0!==n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=kn.inspectBytes(e),n=t.size-t.multihashSize,r=Lt(e.subarray(n,n+t.multihashSize));if(r.byteLength!==t.multihashSize)throw new Error("Incorrect length");const i=r.subarray(t.multihashSize-t.digestSize),s=new Pn(t.multihashCode,t.digestSize,i,r);return[0===t.version?kn.createV0(s):kn.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0;const n=()=>{const[n,r]=vn(e.subarray(t));return t+=r,n};let r=n(),i=In;if(18===r?(r=0,t=0):i=n(),0!==r&&1!==r)throw new RangeError(`Invalid CID version ${r}`);const s=t,a=n(),o=n(),u=t+o;return{version:r,codec:i,multihashCode:a,digestSize:o,multihashSize:u-s,size:u}}static parse(e,t){const[n,r]=function(e,t){switch(e[0]){case"Q":return[Vt.prefix,(t??Vt).decode(`${Vt.prefix}${e}`)];case Vt.prefix:return[Vt.prefix,(t??Vt).decode(e)];case Ht.prefix:return[Ht.prefix,(t??Ht).decode(e)];case rn.prefix:return[rn.prefix,(t??rn).decode(e)];default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),i=kn.decode(r);if(0===i.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return Cn(i).set(n,e),i}}const In=112,Dn=18;function Mn(e,t,n){const r=Tn(e),i=r+Tn(t),s=new Uint8Array(i+n.byteLength);return wn(e,s,0),wn(t,s,r),s.set(n,i),s}const Fn=Symbol.for("@ipld/js-cid/CID"),Rn=Lt,_n=function(e,t){if(null!=t?.truncate&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return En(0,Rn(e))};function Ln(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function Nn(e=0){return new Uint8Array(e)}function On(e=0){return new Uint8Array(e)}function Bn(e,t){null==t&&(t=e.reduce((e,t)=>e+t.length,0));const n=On(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}const Un=Symbol.for("@achingbrain/uint8arraylist");function jn(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let n=0;for(const r of e){const e=n+r.byteLength;if(t<e)return{buf:r,index:t-n};n=e}throw new RangeError("index is out of bounds")}function qn(e){return Boolean(e?.[Un])}class $n{bufs;length;[Un]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else{if(!qn(n))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=n.byteLength,this.bufs.push(...n.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else{if(!qn(n))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=n.byteLength,this.bufs.unshift(...n.bufs)}this.length+=t}get(e){const t=jn(this.bufs,e);return t.buf[t.index]}set(e,t){const n=jn(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else{if(!qn(e))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let n=0;n<e.length;n++)this.set(t+n,e.get(n))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:n,length:r}=this._subList(e,t);return Bn(n,r)}subarray(e,t){const{bufs:n,length:r}=this._subList(e,t);return 1===n.length?n[0]:Bn(n,r)}sublist(e,t){const{bufs:n,length:r}=this._subList(e,t),i=new $n;return i.length=r,i.bufs=[...n],i}_subList(e,t){if((e=e??0)<0&&(e=this.length+e),(t=t??this.length)<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const n=[];let r=0;for(let i=0;i<this.bufs.length;i++){const s=this.bufs[i],a=r,o=a+s.byteLength;if(r=o,e>=o)continue;const u=e>=a&&e<o,d=t>a&&t<=o;if(u&&d){if(e===a&&t===o){n.push(s);break}const r=e-a;n.push(s.subarray(r,r+(t-e)));break}if(u){if(0===e){n.push(s);continue}n.push(s.subarray(e-a))}else{if(d){if(t===o){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!(qn(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const r=n.byteLength;if(0===r)throw new TypeError("search must be at least 1 byte long");const i=new Int32Array(256);for(let e=0;e<256;e++)i[e]=-1;for(let e=0;e<r;e++)i[n[e]]=e;const s=i,a=this.byteLength-n.byteLength,o=n.byteLength-1;let u;for(let e=t;e<=a;e+=u){u=0;for(let t=o;t>=0;t--){const r=this.get(e+t);if(n[t]!==r){u=Math.max(1,t-s[r]);break}}if(0===u)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const n=On(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){const r=Nn(2);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt16(0,t,n),this.write(r,e)}getInt32(e,t){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){const r=Nn(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt32(0,t,n),this.write(r,e)}getBigInt64(e,t){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){const r=Nn(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setBigInt64(0,t,n),this.write(r,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const n=On(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){const r=Nn(2);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint16(0,t,n),this.write(r,e)}getUint32(e,t){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){const r=Nn(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint32(0,t,n),this.write(r,e)}getBigUint64(e,t){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){const r=Nn(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setBigUint64(0,t,n),this.write(r,e)}getFloat32(e,t){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){const r=Nn(4);new DataView(r.buffer,r.byteOffset,r.byteLength).setFloat32(0,t,n),this.write(r,e)}getFloat64(e,t){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){const r=Nn(8);new DataView(r.buffer,r.byteOffset,r.byteLength).setFloat64(0,t,n),this.write(r,e)}equals(e){if(null==e)return!1;if(!(e instanceof $n))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ln(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const n=new $n;return n.bufs=e,null==t&&(t=e.reduce((e,t)=>e+t.byteLength,0)),n.length=t,n}}var zn={__proto__:null,base10:$t({prefix:"9",name:"base10",alphabet:"0123456789"})},Vn={__proto__:null,base16:zt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper:zt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})},Gn={__proto__:null,base2:zt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})};const Kn=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Hn=Kn.reduce((e,t,n)=>(e[n]=t,e),[]),Wn=Kn.reduce((e,t,n)=>{const r=t.codePointAt(0);if(null==r)throw new Error(`Invalid character: ${t}`);return e[r]=n,e},[]),Qn=qt({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+Hn[t],"")},decode:function(e){const t=[];for(const n of e){const e=n.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${n}`);const r=Wn[e];if(null==r)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}});var Yn={__proto__:null,base256emoji:Qn};const Jn=zt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zn=zt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Xn=zt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),er=zt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var tr={__proto__:null,base64:Jn,base64pad:Zn,base64url:Xn,base64urlpad:er},nr={__proto__:null,base8:zt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})},rr={__proto__:null,identity:qt({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)})};function ir({name:e,code:t,encode:n,minDigestLength:r,maxDigestLength:i}){return new sr(e,t,n,r,i)}new TextEncoder,new TextDecoder;class sr{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,r,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=r??20,this.maxDigestLength=i}digest(e,t){if(null!=t?.truncate){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(null!=this.maxDigestLength&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?ar(n,this.code,t?.truncate):n.then(e=>ar(e,this.code,t?.truncate))}throw Error("Unknown type, must be binary type")}}function ar(e,t,n){if(null!=n&&n!==e.byteLength){if(n>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,n)}return En(t,e)}function or(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const ur=ir({name:"sha2-256",code:18,encode:or("SHA-256")});ir({name:"sha2-512",code:19,encode:or("SHA-512")});const dr={...rr,...Gn,...nr,...zn,...Vn,...nn,...an,...Kt,...tr,...Yn};function cr(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const lr=cr("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),pr=cr("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{const t=On((e=e.substring(1)).length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),hr={utf8:lr,"utf-8":lr,hex:dr.base16,latin1:pr,ascii:pr,binary:pr,...dr};function fr(e,t="utf8"){const n=hr[t];if(null==n)throw new Error(`Unsupported encoding "${t}"`);return n.decoder.decode(`${n.prefix}${e}`)}function mr(e,t="utf8"){const n=hr[t];if(null==n)throw new Error(`Unsupported encoding "${t}"`);return n.encoder.encode(e).substring(1)}const yr=parseInt("11111",2),br=parseInt("10000000",2),gr=parseInt("01111111",2),vr={0:Er,1:Er,2:function(e,t){const n=Tr(e,t),r=t.offset,i=t.offset+n,s=[];for(let t=r;t<i;t++)t===r&&0===e[t]||s.push(e[t]);return t.offset+=n,Uint8Array.from(s)},3:function(e,t){const n=Tr(e,t),r=e[t.offset];t.offset++;const i=e.subarray(t.offset,t.offset+n-1);if(t.offset+=n,0!==r)throw new Error("Unused bits in bit string is unimplemented");return i},4:function(e,t){const n=Tr(e,t),r=e.subarray(t.offset,t.offset+n);return t.offset+=n,r},5:function(e,t){return t.offset++,null},6:function(e,t){const n=Tr(e,t),r=t.offset+n,i=e[t.offset];t.offset++;let s=0,a=0;i<40?(s=0,a=i):i<80?(s=1,a=i-40):(s=2,a=i-80);let o=`${s}.${a}`,u=[];for(;t.offset<r;){const n=e[t.offset];if(t.offset++,u.push(127&n),n<128){u.reverse();let e=0;for(let t=0;t<u.length;t++)e+=u[t]<<7*t;o+=`.${e}`,u=[]}}return o},16:Er,22:Er,48:Er};function wr(e,t={offset:0}){const n=e[t.offset]&yr;if(t.offset++,null!=vr[n])return vr[n](e,t);throw new Error("No decoder for tag "+n)}function Tr(e,t){let n=0;if((e[t.offset]&br)===br){const r=e[t.offset]&gr;let i="0x";t.offset++;for(let n=0;n<r;n++,t.offset++)i+=e[t.offset].toString(16).padStart(2,"0");n=parseInt(i,16)}else n=e[t.offset],t.offset++;return n}function Er(e,t){Tr(e,t);const n=[];for(;!(t.offset>=e.byteLength);){const r=wr(e,t);if(null===r)break;n.push(r)}return n}function xr(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const n=new $n;for(let e=0;e<t.length;e+=2)n.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return n}(e.byteLength);return new $n(Uint8Array.from([t.byteLength|br]),t)}function Pr(e){const t=new $n;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new $n(Uint8Array.from([2]),xr(t),t)}function Sr(e){const t=Uint8Array.from([0]),n=new $n(t,e);return new $n(Uint8Array.from([3]),xr(n),n)}function Ar(e,t=48){const n=new $n;for(const t of e)n.append(t);return new $n(Uint8Array.from([t]),xr(n),n)}const Cr=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),kr=Uint8Array.from([6,5,43,129,4,0,34]),Ir=Uint8Array.from([6,5,43,129,4,0,35]),Dr={ext:!0,kty:"EC",crv:"P-256"},Mr={ext:!0,kty:"EC",crv:"P-384"},Fr={ext:!0,kty:"EC",crv:"P-521"};function Rr(e){return function(e){const t=e[1][1][0];let n,r;if(65===t.byteLength)return n=mr(t.subarray(1,33),"base64url"),r=mr(t.subarray(33),"base64url"),new Lr({...Dr,key_ops:["verify"],x:n,y:r});if(97===t.byteLength)return n=mr(t.subarray(1,49),"base64url"),r=mr(t.subarray(49),"base64url"),new Lr({...Mr,key_ops:["verify"],x:n,y:r});if(133===t.byteLength)return n=mr(t.subarray(1,67),"base64url"),r=mr(t.subarray(67),"base64url"),new Lr({...Fr,key_ops:["verify"],x:n,y:r});throw new We(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(wr(e))}function _r(e){if("P-256"===e)return Cr;if("P-384"===e)return kr;if("P-521"===e)return Ir;throw new We(`Invalid curve ${e}`)}class Lr{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return null==this._raw&&(this._raw=(e=this.jwk,Ar([Pr(Uint8Array.from([1])),Ar([_r(e.crv)],160),Ar([Sr(new $n(Uint8Array.from([4]),fr(e.x??"","base64url"),fr(e.y??"","base64url")))],161)]).subarray())),this._raw;var e}toMultihash(){return _n(Fo(this))}toCID(){return kn.createV1(114,this.toMultihash())}toString(){return Vt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}async verify(e,t,n){return async function(e,t,n,r){const i=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,t,n.subarray());return r?.signal?.throwIfAborted(),s}(this.jwk,t,e,n)}}function Nr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Or(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Br(e,t,n=""){const r=Nr(e),i=e?.length,s=void 0!==t;if(!r||s&&i!==t)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e));return e}function Ur(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");Or(e.outputLen),Or(e.blockLen)}function jr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function qr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $r(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function zr(e,t){return e<<32-t|e>>>t}const Vr=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Gr=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Kr(e){if(Br(e),Vr)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Gr[e[n]];return t}function Hr(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Wr(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Vr)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=Hr(e.charCodeAt(i)),s=Hr(e.charCodeAt(i+1));if(void 0===n||void 0===s)throw new Error('hex string expected, got non-hex character "'+(e[i]+e[i+1])+'" at index '+i);r[t]=16*n+s}return r}function Qr(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Br(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n}function Yr(e,t={}){const n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}function Jr(e=32){const t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}const Zr=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Xr(e,t,n){return e&t^~e&n}function ei(e,t,n){return e&t^e&n^t&n}class ti{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=$r(this.buffer)}update(e){jr(this),Br(e);const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const a=Math.min(r-this.pos,i-s);if(a!==r)n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=$r(e);for(;r<=i-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){jr(this),function(e,t){Br(e,void 0,"digestInto() output");const n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;t[s++]=128,qr(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(8*this.length),i),this.process(n,0);const a=$r(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=o/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<u;e++)a.setUint32(4*e,d[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=a,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const ni=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ri=/* @__PURE__ */Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ii=/* @__PURE__ */BigInt(2**32-1),si=/* @__PURE__ */BigInt(32);function ai(e,t=!1){return t?{h:Number(e&ii),l:Number(e>>si&ii)}:{h:0|Number(e>>si&ii),l:0|Number(e&ii)}}const oi=(e,t,n)=>e>>>n,ui=(e,t,n)=>e<<32-n|t>>>n,di=(e,t,n)=>e>>>n|t<<32-n,ci=(e,t,n)=>e<<32-n|t>>>n,li=(e,t,n)=>e<<64-n|t>>>n-32,pi=(e,t,n)=>e>>>n-32|t<<64-n;function hi(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const fi=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),mi=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,yi=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),bi=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,gi=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),vi=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,wi=/* @__PURE__ */Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ti=/* @__PURE__ */new Uint32Array(64);class Ei extends ti{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:a,H:o}=this;return[e,t,n,r,i,s,a,o]}set(e,t,n,r,i,s,a,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|a,this.H=0|o}process(e,t){for(let n=0;n<16;n++,t+=4)Ti[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ti[e-15],n=Ti[e-2],r=zr(t,7)^zr(t,18)^t>>>3,i=zr(n,17)^zr(n,19)^n>>>10;Ti[e]=i+Ti[e-7]+r+Ti[e-16]|0}let{A:n,B:r,C:i,D:s,E:a,F:o,G:u,H:d}=this;for(let e=0;e<64;e++){const t=d+(zr(a,6)^zr(a,11)^zr(a,25))+Xr(a,o,u)+wi[e]+Ti[e]|0,c=(zr(n,2)^zr(n,13)^zr(n,22))+ei(n,r,i)|0;d=u,u=o,o=a,a=s+t|0,s=i,i=r,r=n,n=t+c|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,r,i,s,a,o,u,d)}roundClean(){qr(Ti)}destroy(){this.set(0,0,0,0,0,0,0,0),qr(this.buffer)}}class xi extends Ei{A=0|ni[0];B=0|ni[1];C=0|ni[2];D=0|ni[3];E=0|ni[4];F=0|ni[5];G=0|ni[6];H=0|ni[7];constructor(){super(32)}}const Pi=/* @__PURE__ */(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:a}=ai(e[s],t);[r[s],i[s]]=[n,a]}return[r,i]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),Si=/* @__PURE__ */(()=>Pi[0])(),Ai=/* @__PURE__ */(()=>Pi[1])(),Ci=/* @__PURE__ */new Uint32Array(80),ki=/* @__PURE__ */new Uint32Array(80);class Ii extends ti{constructor(e){super(128,e,16,!1)}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:s,Dh:a,Dl:o,Eh:u,El:d,Fh:c,Fl:l,Gh:p,Gl:h,Hh:f,Hl:m}=this;return[e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m]}set(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|u,this.El=0|d,this.Fh=0|c,this.Fl=0|l,this.Gh=0|p,this.Gl=0|h,this.Hh=0|f,this.Hl=0|m}process(e,t){for(let n=0;n<16;n++,t+=4)Ci[n]=e.getUint32(t),ki[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Ci[e-15],n=0|ki[e-15],r=di(t,n,1)^di(t,n,8)^oi(t,0,7),i=ci(t,n,1)^ci(t,n,8)^ui(t,n,7),s=0|Ci[e-2],a=0|ki[e-2],o=di(s,a,19)^li(s,a,61)^oi(s,0,6),u=ci(s,a,19)^pi(s,a,61)^ui(s,a,6),d=yi(i,u,ki[e-7],ki[e-16]),c=bi(d,r,o,Ci[e-7],Ci[e-16]);Ci[e]=0|c,ki[e]=0|d}let{Ah:n,Al:r,Bh:i,Bl:s,Ch:a,Cl:o,Dh:u,Dl:d,Eh:c,El:l,Fh:p,Fl:h,Gh:f,Gl:m,Hh:y,Hl:b}=this;for(let e=0;e<80;e++){const t=di(c,l,14)^di(c,l,18)^li(c,l,41),g=ci(c,l,14)^ci(c,l,18)^pi(c,l,41),v=c&p^~c&f,w=gi(b,g,l&h^~l&m,Ai[e],ki[e]),T=vi(w,y,t,v,Si[e],Ci[e]),E=0|w,x=di(n,r,28)^li(n,r,34)^li(n,r,39),P=ci(n,r,28)^pi(n,r,34)^pi(n,r,39),S=n&i^n&a^i&a,A=r&s^r&o^s&o;y=0|f,b=0|m,f=0|p,m=0|h,p=0|c,h=0|l,({h:c,l:l}=hi(0|u,0|d,0|T,0|E)),u=0|a,d=0|o,a=0|i,o=0|s,i=0|n,s=0|r;const C=fi(E,P,A);n=mi(C,T,x,S),r=0|C}({h:n,l:r}=hi(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:s}=hi(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=hi(0|this.Ch,0|this.Cl,0|a,0|o)),({h:u,l:d}=hi(0|this.Dh,0|this.Dl,0|u,0|d)),({h:c,l:l}=hi(0|this.Eh,0|this.El,0|c,0|l)),({h:p,l:h}=hi(0|this.Fh,0|this.Fl,0|p,0|h)),({h:f,l:m}=hi(0|this.Gh,0|this.Gl,0|f,0|m)),({h:y,l:b}=hi(0|this.Hh,0|this.Hl,0|y,0|b)),this.set(n,r,i,s,a,o,u,d,c,l,p,h,f,m,y,b)}roundClean(){qr(Ci,ki)}destroy(){qr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Di extends Ii{Ah=0|ri[0];Al=0|ri[1];Bh=0|ri[2];Bl=0|ri[3];Ch=0|ri[4];Cl=0|ri[5];Dh=0|ri[6];Dl=0|ri[7];Eh=0|ri[8];El=0|ri[9];Fh=0|ri[10];Fl=0|ri[11];Gh=0|ri[12];Gl=0|ri[13];Hh=0|ri[14];Hl=0|ri[15];constructor(){super(64)}}const Mi=/* @__PURE__ */Yr(()=>new xi
|
|
2
2
|
/* @__PURE__ */,Zr(1)),Fi=/* @__PURE__ */Yr(()=>new Di
|
|
3
|
-
/* @__PURE__ */,Zr(3)),Ri=/* @__PURE__ */BigInt(0),_i=/* @__PURE__ */BigInt(1);function Li(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e);return e}function Ni(e){if("bigint"==typeof e){if(!Vi(e))throw new Error("positive bigint expected, got "+e)}else Or(e);return e}function Oi(e){const t=Ni(e).toString(16);return 1&t.length?"0"+t:t}function Bi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Ri:BigInt("0x"+e)}function Ui(e){return Bi(Kr(e))}function ji(e){return Bi(Kr(zi(Br(e)).reverse()))}function qi(e,t){Or(t);const n=Wr((e=Ni(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}function $i(e,t){return qi(e,t).reverse()}function zi(e){return Uint8Array.from(e)}const Vi=e=>"bigint"==typeof e&&Ri<=e;function Gi(e,t,n,r){if(!function(e,t,n){return Vi(e)&&Vi(t)&&Vi(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const Ki=e=>(_i<<BigInt(e))-_i;function Hi(e,t={},n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");const r=(t,n)=>Object.entries(t).forEach(([t,r])=>function(t,n,r){const i=e[t];if(r&&void 0===i)return;const s=typeof i;if(s!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${s}`)}(t,r,n));r(t,!1),r(n,!0)}function Wi(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const s=e(n,...r);return t.set(n,s),s}}const Qi=/* @__PURE__ */BigInt(0),Yi=/* @__PURE__ */BigInt(1),Ji=/* @__PURE__ */BigInt(2),Zi=/* @__PURE__ */BigInt(3),Xi=/* @__PURE__ */BigInt(4),es=/* @__PURE__ */BigInt(5),ts=/* @__PURE__ */BigInt(7),ns=/* @__PURE__ */BigInt(8),rs=/* @__PURE__ */BigInt(9),is=/* @__PURE__ */BigInt(16);function ss(e,t){const n=e%t;return n>=Qi?n:t+n}function as(e,t,n){let r=e;for(;t-- >Qi;)r*=r,r%=n;return r}function os(e,t){if(e===Qi)throw new Error("invert: expected non-zero number");if(t<=Qi)throw new Error("invert: expected positive modulus, got "+t);let n=ss(e,t),r=t,i=Qi,s=Yi;for(;n!==Qi;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==Yi)throw new Error("invert: does not exist");return ss(i,t)}function us(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function ds(e,t){const n=e.pow(t,(e.ORDER+Yi)/Xi);return us(e,n,t),n}function cs(e,t){const n=(e.ORDER-es)/ns,r=e.mul(t,Ji),i=e.pow(r,n),s=e.mul(t,i),a=e.mul(e.mul(s,Ji),i),o=e.mul(s,e.sub(a,e.ONE));return us(e,o,t),o}function ls(e){if(e<Zi)throw new Error("sqrt is not defined for small field");let t=e-Yi,n=0;for(;t%Ji===Qi;)t/=Ji,n++;let r=Ji;const i=ys(e);for(;1===fs(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return ds;let s=i.pow(r,t);const a=(t+Yi)/Ji;return function(e,r){if(e.is0(r))return r;if(1!==fs(e,r))throw new Error("Cannot find square root");let i=n,o=e.mul(e.ONE,s),u=e.pow(r,t),d=e.pow(r,a);for(;!e.eql(u,e.ONE);){if(e.is0(u))return e.ZERO;let t=1,n=e.sqr(u);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw new Error("Cannot find square root");const r=Yi<<BigInt(i-t-1),s=e.pow(o,r);i=t,o=e.sqr(s),u=e.mul(u,o),d=e.mul(d,s)}return d}}const ps=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hs(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),s=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),s),r}function fs(e,t){const n=e.pow(t,(e.ORDER-Yi)/Ji),r=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!r&&!i&&!s)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}class ms{ORDER;BITS;BYTES;isLE;ZERO=Qi;ONE=Yi;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Qi)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,null!=t&&"object"==typeof t&&("number"==typeof t.BITS&&(n=t.BITS),"function"==typeof t.sqrt&&(this.sqrt=t.sqrt),"boolean"==typeof t.isLE&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),"boolean"==typeof t.modFromBytes&&(this._mod=t.modFromBytes));const{nBitLength:r,nByteLength:i}=function(e,t){void 0!==t&&Or(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ss(e,this.ORDER)}isValid(e){if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return Qi<=e&&e<this.ORDER}is0(e){return e===Qi}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Yi)===Yi}neg(e){return ss(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ss(e*e,this.ORDER)}add(e,t){return ss(e+t,this.ORDER)}sub(e,t){return ss(e-t,this.ORDER)}mul(e,t){return ss(e*t,this.ORDER)}pow(e,t){return function(e,t,n){if(n<Qi)throw new Error("invalid exponent, negatives unsupported");if(n===Qi)return e.ONE;if(n===Yi)return t;let r=e.ONE,i=t;for(;n>Qi;)n&Yi&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Yi;return r}(this,e,t)}div(e,t){return ss(e*os(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return os(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=(t=this.ORDER)%Xi===Zi?ds:t%ns===es?cs:t%is===rs?function(e){const t=ys(e),n=ls(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),a=(e+ts)/is;return(e,t)=>{let n=e.pow(t,a),o=e.mul(n,r);const u=e.mul(n,i),d=e.mul(n,s),c=e.eql(e.sqr(o),t),l=e.eql(e.sqr(u),t);n=e.cmov(n,o,c),o=e.cmov(d,u,l);const p=e.eql(e.sqr(o),t),h=e.cmov(n,o,p);return us(e,h,t),h}}(t):ls(t)),this._sqrt(this,e);var t}toBytes(e){return this.isLE?$i(e,this.BYTES):qi(e,this.BYTES)}fromBytes(e,t=!1){Br(e);const{_lengths:n,BYTES:r,isLE:i,ORDER:s,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);const t=new Uint8Array(r);t.set(e,i?0:t.length-e.length),e=t}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let o=i?ji(e):Ui(e);if(a&&(o=ss(o,s)),!t&&!this.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o}invertBatch(e){return hs(this,e)}cmov(e,t,n){return n?t:e}}function ys(e,t={}){return new ms(e,t)}function bs(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function gs(e){const t=bs(e);return t+Math.ceil(t/2)}const vs=/* @__PURE__ */BigInt(0),ws=/* @__PURE__ */BigInt(1);function Ts(e,t){const n=t.negate();return e?n:t}function Es(e,t){const n=hs(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function xs(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ps(e,t){xs(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Ki(e),maxNumber:n,shiftBy:BigInt(e)}}function Ss(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:a}=n;let o=Number(e&i),u=e>>a;o>r&&(o-=s,u+=ws);const d=t*r;return{nextN:u,offset:d+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:d}}const As=new WeakMap,Cs=new WeakMap;function ks(e){return Cs.get(e)||1}function Is(e){if(e!==vs)throw new Error("invalid wNAF")}class Ds{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>vs;)t&ws&&(n=n.add(r)),r=r.double(),t>>=ws;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Ps(t,this.bits),i=[];let s=e,a=s;for(let e=0;e<n;e++){a=s,i.push(a);for(let e=1;e<r;e++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const s=Ps(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:a,offset:o,isZero:u,isNeg:d,isNegF:c,offsetF:l}=Ss(n,e,s);n=a,u?i=i.add(Ts(c,t[l])):r=r.add(Ts(d,t[o]))}return Is(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Ps(e,this.bits);for(let e=0;e<i.windows&&n!==vs;e++){const{nextN:s,offset:a,isZero:o,isNeg:u}=Ss(n,e,i);if(n=s,!o){const e=t[a];r=r.add(u?e.negate():e)}}return Is(n),r}getPrecomputes(e,t,n){let r=As.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),As.set(t,r))),r}cached(e,t,n){const r=ks(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=ks(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){xs(t,this.bits),Cs.set(e,t),As.delete(e)}hasCache(e){return 1!==ks(e)}}function Ms(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=ps.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",BYTES:"number",BITS:"number"});Hi(e,t)}(t),t}return ys(e,{isLE:n})}function Fs(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>vs))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Ms(t.p,n.Fp,r),s=Ms(t.n,n.Fn,r),a=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of a)if(!i.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:i,Fn:s}}function Rs(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}const _s=BigInt(0),Ls=BigInt(1),Ns=BigInt(2),Os=BigInt(8);function Bs(e,t={}){const n=Fs("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a}=s;Hi(t,{},{uvRatio:"function"});const o=Ns<<BigInt(8*i.BYTES)-Ls,u=e=>r.create(e),d=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:_s}}});if(!function(e,t,n,r){const i=e.sqr(n),s=e.sqr(r),a=e.add(e.mul(t.a,i),s),o=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(a,o)}(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function c(e,t,n=!1){return Gi("coordinate "+e,t,n?Ls:_s,o),t}function l(e){if(!(e instanceof f))throw new Error("EdwardsPoint expected")}const p=Wi((e,t)=>{const{X:n,Y:i,Z:s}=e,a=e.is0();null==t&&(t=a?Os:r.inv(s));const o=u(n*t),d=u(i*t),c=r.mul(s,t);if(a)return{x:_s,y:Ls};if(c!==Ls)throw new Error("invZ was invalid");return{x:o,y:d}}),h=Wi(e=>{const{a:t,d:n}=s;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:a,T:o}=e,d=u(r*r),c=u(i*i),l=u(a*a),p=u(l*l),h=u(d*t);if(u(l*u(h+c))!==u(p+u(n*u(d*c))))throw new Error("bad point: equation left != right (1)");if(u(r*i)!==u(a*o))throw new Error("bad point: equation left != right (2)");return!0});class f{static BASE=new f(s.Gx,s.Gy,Ls,u(s.Gx*s.Gy));static ZERO=new f(_s,Ls,Ls,_s);static Fp=r;static Fn=i;X;Y;Z;T;constructor(e,t,n,r){this.X=c("x",e),this.Y=c("y",t),this.Z=c("z",n,!0),this.T=c("t",r),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){if(e instanceof f)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return c("x",t),c("y",n),new f(t,n,Ls,u(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:a}=s;e=zi(Br(e,n,"point")),Li(t,"zip215");const c=zi(e),l=e[n-1];c[n-1]=-129&l;const p=ji(c);Gi("point.y",p,_s,t?o:r.ORDER);const h=u(p*p),m=u(h-Ls),y=u(a*h-i);let{isValid:b,value:g}=d(m,y);if(!b)throw new Error("bad point: invalid y coordinate");const v=(g&Ls)===Ls,w=!!(128&l);if(!t&&g===_s&&w)throw new Error("bad point: x=0 and x_0=1");return w!==v&&(g=u(-g)),f.fromAffine({x:g,y:p})}static fromHex(e,t=!1){return f.fromBytes(Wr(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return m.createCache(this,e),t||this.multiply(Ns),this}assertValidity(){h(this)}equals(e){l(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:s,Z:a}=e,o=u(t*a),d=u(i*r),c=u(n*a),p=u(s*r);return o===d&&c===p}is0(){return this.equals(f.ZERO)}negate(){return new f(u(-this.X),this.Y,this.Z,u(-this.T))}double(){const{a:e}=s,{X:t,Y:n,Z:r}=this,i=u(t*t),a=u(n*n),o=u(Ns*u(r*r)),d=u(e*i),c=t+n,l=u(u(c*c)-i-a),p=d+a,h=p-o,m=d-a,y=u(l*h),b=u(p*m),g=u(l*m),v=u(h*p);return new f(y,b,v,g)}add(e){l(e);const{a:t,d:n}=s,{X:r,Y:i,Z:a,T:o}=this,{X:d,Y:c,Z:p,T:h}=e,m=u(r*d),y=u(i*c),b=u(o*n*h),g=u(a*p),v=u((r+i)*(d+c)-m-y),w=g-b,T=g+b,E=u(y-t*m),x=u(v*w),P=u(T*E),S=u(v*E),A=u(w*T);return new f(x,P,A,S)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=m.cached(this,e,e=>Es(f,e));return Es(f,[t,n])[0]}multiplyUnsafe(e,t=f.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===_s?f.ZERO:this.is0()||e===Ls?this:m.unsafe(this,e,e=>Es(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(e){return p(this,e)}clearCofactor(){return a===Ls?this:this.multiplyUnsafe(a)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Ls?128:0,n}toHex(){return Kr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const m=new Ds(f,i.BITS);return f.BASE.precompute(8),f}const Us=BigInt(1),js=BigInt(2),qs=BigInt(5),$s=BigInt(8),zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Vs=/* @__PURE__ */(()=>({p:zs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:$s,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Gs(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ks=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Hs=/* @__PURE__ */Bs(Vs,{uvRatio:function(e,t){const n=zs,r=ss(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=zs,a=e*e%s*e%s,o=as(a,js,s)*a%s,u=as(o,Us,s)*e%s,d=as(u,qs,s)*u%s,c=as(d,t,s)*d%s,l=as(c,n,s)*c%s,p=as(l,r,s)*l%s,h=as(p,i,s)*p%s,f=as(h,i,s)*p%s,m=as(f,t,s)*d%s;return{pow_p_5_8:as(m,js,s)*e%s,b2:a}}(e*ss(r*r*t,n)).pow_p_5_8;let s=ss(e*r*i,n);const a=ss(t*s*s,n),o=s,u=ss(s*Ks,n),d=a===e,c=a===ss(-e,n),l=a===ss(-e*Ks,n);return d&&(s=o),(c||l)&&(s=u),(ss(s,n)&Yi)===Yi&&(s=ss(-s,n)),{isValid:d||c,value:s}}});function Ws(e){return function(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Hi(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:a}=e,o=n.randomBytes||Jr,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Li(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function c(e){return a.create(ji(e))}function l(e){const{head:n,prefix:r,scalar:s}=function(e){const n=y.secretKey;Br(e,y.secretKey,"secretKey");const r=Br(t(e),2*n,"hashedSecretKey"),i=u(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:c(i)}}(e),a=i.multiply(s),o=a.toBytes();return{head:n,prefix:r,scalar:s,point:a,pointBytes:o}}function p(e){return l(e).pointBytes}function h(e=Uint8Array.of(),...n){const i=Qr(...n);return c(t(d(i,Br(e,void 0,"context"),!!r)))}const f={zip215:!0},m=s.BYTES,y={secretKey:m,publicKey:m,signature:2*m,seed:m};function b(e=o(y.seed)){return Br(e,y.seed,"seed")}const g={getExtendedPublicKey:l,randomSecretKey:b,isValidSecretKey:function(e){return Nr(e)&&e.length===a.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=y.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const a=i?s.div(Ls+n,Ls-n):s.div(n-Ls,n+Ls);return s.toBytes(a)},toMontgomerySecret(e){const n=y.secretKey;Br(e,n);const r=t(e.subarray(0,n));return u(r).subarray(0,n)}};return Object.freeze({keygen:Rs(b,p),getPublicKey:p,sign:function(e,t,n={}){e=Br(e,void 0,"message"),r&&(e=r(e));const{prefix:s,scalar:o,pointBytes:u}=l(t),d=h(n.context,s,e),c=i.multiply(d).toBytes(),p=h(n.context,c,u,e),f=a.create(d+p*o);if(!a.isValid(f))throw new Error("sign failed: invalid s");return Br(Qr(c,a.toBytes(f)),y.signature,"result")},verify:function(t,n,s,a=f){const{context:o,zip215:u}=a,d=y.signature;t=Br(t,d,"signature"),n=Br(n,void 0,"message"),s=Br(s,y.publicKey,"publicKey"),void 0!==u&&Li(u,"zip215"),r&&(n=r(n));const c=d/2,l=t.subarray(0,c),p=ji(t.subarray(c,d));let m,b,g;try{m=e.fromBytes(s,u),b=e.fromBytes(l,u),g=i.multiplyUnsafe(p)}catch(e){return!1}if(!u&&m.isSmallOrder())return!1;const v=h(o,b.toBytes(),m.toBytes(),n);return b.add(m.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()},utils:g,Point:e,lengths:y})}(Hs,Fi,Object.assign({adjustScalarBytes:Gs},e))}const Qs=/* @__PURE__ */Ws({});Error;class Ys extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Js extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var Zs={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Js("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let Xs;const ea=(async()=>{try{return await Zs.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function ta(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class na{type="Ed25519";raw;constructor(e){this.raw=sa(e,32)}toMultihash(){return _n(Fo(this))}toCID(){return kn.createV1(114,this.toMultihash())}toString(){return Vt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();const r=async function(e,t,n){return null==Xs&&(Xs=await ea),Xs?async function(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await Zs.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Zs.get().subtle.verify({name:"Ed25519"},r,t,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,n):function(e,t,n){return Qs.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}(e,t,n)}(this.raw,t,e);return ta(r)?r.then(e=>(n?.signal?.throwIfAborted(),e)):r}}class ra{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=sa(e,64),this.publicKey=new na(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const n=async function(e,t){return null==Xs&&(Xs=await ea),Xs?async function(e,t){let n;n=64===e.length?e.subarray(0,32):e;const r={crv:"Ed25519",kty:"OKP",x:mr(e.subarray(32),"base64url"),d:mr(n,"base64url"),ext:!0,key_ops:["sign"]},i=await Zs.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await Zs.get().subtle.sign({name:"Ed25519"},i,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(s,0,s.byteLength)}(e,t):function(e,t){const n=e.subarray(0,32);return Qs.sign(t instanceof Uint8Array?t:t.subarray(),n)}(e,t)}(this.raw,e);return ta(n)?n.then(e=>(t?.signal?.throwIfAborted(),e)):(t?.signal?.throwIfAborted(),n)}}function ia(e){return e=sa(e,32),new na(e)}function sa(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new We(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const aa=Math.pow(2,7),oa=Math.pow(2,14),ua=Math.pow(2,21),da=Math.pow(2,28),ca=Math.pow(2,35),la=Math.pow(2,42),pa=Math.pow(2,49),ha=128,fa=127;function ma(e){if(e<aa)return 1;if(e<oa)return 2;if(e<ua)return 3;if(e<da)return 4;if(e<ca)return 5;if(e<la)return 6;if(e<pa)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ya(e,t,n=0){switch(ma(e)){case 8:t[n++]=255&e|ha,e/=128;case 7:t[n++]=255&e|ha,e/=128;case 6:t[n++]=255&e|ha,e/=128;case 5:t[n++]=255&e|ha,e/=128;case 4:t[n++]=255&e|ha,e>>>=7;case 3:t[n++]=255&e|ha,e>>>=7;case 2:t[n++]=255&e|ha,e>>>=7;case 1:t[n++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function ba(e,t){let n=e[t],r=0;if(r+=n&fa,n<ha)return r;if(n=e[t+1],r+=(n&fa)<<7,n<ha)return r;if(n=e[t+2],r+=(n&fa)<<14,n<ha)return r;if(n=e[t+3],r+=(n&fa)<<21,n<ha)return r;if(n=e[t+4],r+=(n&fa)*da,n<ha)return r;if(n=e[t+5],r+=(n&fa)*ca,n<ha)return r;if(n=e[t+6],r+=(n&fa)*la,n<ha)return r;if(n=e[t+7],r+=(n&fa)*pa,n<ha)return r;throw new RangeError("Could not decode varint")}function ga(e,t,n=0){return null==t&&(t=On(ma(e))),t instanceof Uint8Array?ya(e,t,n):function(e,t,n=0){switch(ma(e)){case 8:t.set(n++,255&e|ha),e/=128;case 7:t.set(n++,255&e|ha),e/=128;case 6:t.set(n++,255&e|ha),e/=128;case 5:t.set(n++,255&e|ha),e/=128;case 4:t.set(n++,255&e|ha),e>>>=7;case 3:t.set(n++,255&e|ha),e>>>=7;case 2:t.set(n++,255&e|ha),e>>>=7;case 1:t.set(n++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,n)}function va(e,t=0){return e instanceof Uint8Array?ba(e,t):function(e,t){let n=e.get(t),r=0;if(r+=n&fa,n<ha)return r;if(n=e.get(t+1),r+=(n&fa)<<7,n<ha)return r;if(n=e.get(t+2),r+=(n&fa)<<14,n<ha)return r;if(n=e.get(t+3),r+=(n&fa)<<21,n<ha)return r;if(n=e.get(t+4),r+=(n&fa)*da,n<ha)return r;if(n=e.get(t+5),r+=(n&fa)*ca,n<ha)return r;if(n=e.get(t+6),r+=(n&fa)*la,n<ha)return r;if(n=e.get(t+7),r+=(n&fa)*pa,n<ha)return r;throw new RangeError("Could not decode varint")}(e,t)}const wa=new Float32Array([-0]),Ta=new Uint8Array(wa.buffer);function Ea(e,t,n){wa[0]=e,t[n]=Ta[0],t[n+1]=Ta[1],t[n+2]=Ta[2],t[n+3]=Ta[3]}const xa=new Float64Array([-0]),Pa=new Uint8Array(xa.buffer);function Sa(e,t,n){xa[0]=e,t[n]=Pa[0],t[n+1]=Pa[1],t[n+2]=Pa[2],t[n+3]=Pa[3],t[n+4]=Pa[4],t[n+5]=Pa[5],t[n+6]=Pa[6],t[n+7]=Pa[7]}const Aa=BigInt(Number.MAX_SAFE_INTEGER),Ca=BigInt(Number.MIN_SAFE_INTEGER);class ka{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(0n===e)return Ia;if(e<Aa&&e>Ca)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let n=e>>32n,r=e-(n<<32n);return t&&(n=0n|~n,r=0n|~r,++r>Da&&(r=0n,++n>Da&&(n=0n))),new ka(Number(r),Number(n))}static fromNumber(e){if(0===e)return Ia;const t=e<0;t&&(e=-e);let n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new ka(n,r)}static from(e){return"number"==typeof e?ka.fromNumber(e):"bigint"==typeof e?ka.fromBigInt(e):"string"==typeof e?ka.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new ka(e.low>>>0,e.high>>>0):Ia}}const Ia=new ka(0,0);Ia.toBigInt=function(){return 0n},Ia.zzEncode=Ia.zzDecode=function(){return this},Ia.length=function(){return 1};const Da=4294967296n;function Ma(e,t,n){const r=n;let i,s;for(let r=0;r<e.length;++r)i=e.charCodeAt(r),i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-r}function Fa(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Ra(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class _a{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Fa(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Fa(this,4);return Ra(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Fa(this,4);return 0|Ra(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Fa(this,4);const e=(Ta[0]=(t=this.buf)[n=this.pos],Ta[1]=t[n+1],Ta[2]=t[n+2],Ta[3]=t[n+3],wa[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Fa(this,4);const e=(Pa[0]=(t=this.buf)[n=this.pos],Pa[1]=t[n+1],Pa[2]=t[n+2],Pa[3]=t[n+3],Pa[4]=t[n+4],Pa[5]=t[n+5],Pa[6]=t[n+6],Pa[7]=t[n+7],xa[0]);var t,n;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Fa(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){const e=this.bytes();return function(e,t,n){if(n-t<1)return"";let r;const i=[];let s,a=0;for(;t<n;)s=e[t++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=r?(a>0&&r.push(String.fromCharCode.apply(String,i.slice(0,a))),r.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Fa(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Fa(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new ka(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Fa(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Fa(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Fa(this,8);const e=Ra(this.buf,this.pos+=4),t=Ra(this.buf,this.pos+=4);return new ka(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=ba(this.buf,this.pos);return this.pos+=ma(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function La(e){return new _a(e instanceof Uint8Array?e:e.subarray())}function Na(e,t,n){const r=La(e);return t.decode(r,void 0,n)}class Oa{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Ba(){}class Ua{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const ja=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return On(r);n+r>e&&(t=On(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class qa{len;head;tail;states;constructor(){this.len=0,this.head=new Oa(Ba,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Oa(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Va((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ga,10,ka.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=ka.fromBigInt(e);return this._push(Ga,t.length(),t)}uint64Number(e){return this._push(ya,ma(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=ka.fromBigInt(e).zzEncode();return this._push(Ga,t.length(),t)}sint64Number(e){const t=ka.fromNumber(e).zzEncode();return this._push(Ga,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push($a,1,e?1:0)}fixed32(e){return this._push(Ka,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=ka.fromBigInt(e);return this._push(Ka,4,t.lo)._push(Ka,4,t.hi)}fixed64Number(e){const t=ka.fromNumber(e);return this._push(Ka,4,t.lo)._push(Ka,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ea,4,e)}double(e){return this._push(Sa,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push($a,1,0):this.uint32(t)._push(Ha,t,e)}string(e){const t=function(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(Ma,t,e):this._push($a,1,0)}fork(){return this.states=new Ua(this),this.head=this.tail=new Oa(Ba,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Oa(Ba,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next;const t=(n=this.len,null!=globalThis.Buffer?On(n):ja(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function $a(e,t,n){t[n]=255&e}function za(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class Va extends Oa{next;constructor(e,t){super(za,e,t),this.next=void 0}}function Ga(e,t,n){for(;0!==e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function Ka(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function Ha(e,t,n){t.set(e,n)}function Wa(e,t,n){t.set(e,n)}function Qa(e,t,n){e.length<40?Ma(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(fr(e),n)}function Ya(e,t){const n=new qa;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*Ja(e,t,n){const r=La(e);yield*t.stream(r,void 0,"$",n)}function Za(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function Xa(e,t,n){return Za("message",2,e,t,n)}var eo,to,no,ro;function io(e){if(isNaN(e)||e<=0)throw new We("random bytes length must be a Number bigger than 0");return Jr(e)}null!=globalThis.Buffer&&(qa.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Wa,t,e),this},qa.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Qa,t,e),this}),function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(eo||(eo={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(to||(to={})),function(e){e.codec=()=>function(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Za("enum",0,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())},function*(e){const n=e.int32();yield t(n)})}(to)}(eo||(eo={})),function(e){let t;e.codec=()=>(null==t&&(t=Xa((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eo.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.Type=eo.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.Type`,value:eo.codec().decode(e)};break;case 2:yield{field:`${n}.Data`,value:e.bytes()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Ya(t,e.codec())},e.decode=function(t,n){return Na(t,e.codec(),n)},e.stream=function(t,n){return Ja(t,e.codec(),n)}}(no||(no={})),function(e){let t;e.codec=()=>(null==t&&(t=Xa((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eo.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.Type=eo.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.Type`,value:eo.codec().decode(e)};break;case 2:yield{field:`${n}.Data`,value:e.bytes()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Ya(t,e.codec())},e.decode=function(t,n){return Na(t,e.codec(),n)},e.stream=function(t,n){return Ja(t,e.codec(),n)}}(ro||(ro={}));class so{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new We("JWK was missing components");return Ar([ao,Sr(Ar([Pr(fr(e.n,"base64url")),Pr(fr(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return kn.createV1(114,this._multihash)}toString(){return Vt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}verify(e,t,n){return async function(e,t,n,r){const i=await Zs.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Zs.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,t,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}(this.jwk,t,e,n)}}const ao=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class oo{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ur(e),Br(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),qr(r)}update(e){return jr(this),this.iHash.update(e),this}digestInto(e){jr(this),Br(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:s,outputLen:a}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const uo=(e,t,n)=>new oo(e,t).update(n).digest();uo.create=(e,t)=>new oo(e,t);const co=(e,t)=>(e+(e>=0?t:-t)/bo)/t;function lo(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function po(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Li(n.lowS,"lowS"),Li(n.prehash,"prehash"),void 0!==n.format&&lo(n.format),n}class ho extends Error{constructor(e=""){super(e)}}const fo={Err:ho,_tlv:{encode:(e,t)=>{const{Err:n}=fo;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,i=Oi(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Oi(i.length/2|128):"";return Oi(e)+s+i+t},decode(e,t){const{Err:n}=fo;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const i=t[r++];let s=0;if(128&i){const e=127&i;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const a=t.subarray(r,r+e);if(a.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===a[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of a)s=s<<8|e;if(r+=e,s<128)throw new n("tlv.decode(long): not minimal encoding")}else s=i;const a=t.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+s)}}},_int:{encode(e){const{Err:t}=fo;if(e<mo)throw new t("integer: negative integers are not allowed");let n=Oi(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=fo;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Ui(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=fo,i=Br(e,void 0,"signature"),{v:s,l:a}=r.decode(48,i);if(a.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:u}=r.decode(2,s),{v:d,l:c}=r.decode(2,u);if(c.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(o),s:n.decode(d)}},hexFromSig(e){const{_tlv:t,_int:n}=fo,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s));return t.encode(48,r+i)}},mo=BigInt(0),yo=BigInt(1),bo=BigInt(2),go=BigInt(3),vo=BigInt(4);function wo(e,t={}){const n=Fs("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a,n:o}=s;Hi(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:u}=t;if(u&&(!r.is0(s.a)||"bigint"!=typeof u.beta||!Array.isArray(u.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const d=Eo(r,i);function c(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const l=t.toBytes||function(e,t,n){const{x:i,y:s}=t.toAffine(),a=r.toBytes(i);return Li(n,"isCompressed"),n?(c(),Qr(To(!r.isOdd(s)),a)):Qr(Uint8Array.of(4),a,r.toBytes(s))},p=t.fromBytes||function(e){Br(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=d,i=e.length,s=e[0],a=e.subarray(1);if(i!==t||2!==s&&3!==s){if(i===n&&4===s){const e=r.BYTES,t=r.fromBytes(a.subarray(0,e)),n=r.fromBytes(a.subarray(e,2*e));if(!f(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(a);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=h(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}return c(),!(1&~s)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function h(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,s.a)),s.b)}function f(e,t){const n=r.sqr(t),i=h(e);return r.eql(n,i)}if(!f(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const m=r.mul(r.pow(s.a,go),vo),y=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(m,y)))throw new Error("bad curve params: a or b");function b(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function g(e){if(!(e instanceof x))throw new Error("Weierstrass Point expected")}function v(e){if(!u||!u.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[s,a]]=t,o=co(a*e,n),u=co(-i*e,n);let d=e-o*r-u*s,c=-o*i-u*a;const l=d<mo,p=c<mo;l&&(d=-d),p&&(c=-c);const h=Ki(Math.ceil(function(e){let t;for(t=0;e>Ri;e>>=_i,t+=1);return t}(n)/2))+yo;if(d<mo||d>=h||c<mo||c>=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:d,k2neg:p,k2:c}}(e,u.basises,i.ORDER)}const w=Wi((e,t)=>{const{X:n,Y:i,Z:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const a=e.is0();null==t&&(t=a?r.ONE:r.inv(s));const o=r.mul(n,t),u=r.mul(i,t),d=r.mul(s,t);if(a)return{x:r.ZERO,y:r.ZERO};if(!r.eql(d,r.ONE))throw new Error("invZ was invalid");return{x:o,y:u}}),T=Wi(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw new Error("bad point: x or y not field elements");if(!f(n,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(e,t,n,i,s){return n=new x(r.mul(n.X,e),n.Y,n.Z),t=Ts(i,t),n=Ts(s,n),t.add(n)}class x{static BASE=new x(s.Gx,s.Gy,r.ONE);static ZERO=new x(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=i;X;Y;Z;constructor(e,t,n){this.X=b("x",e),this.Y=b("y",t,!0),this.Z=b("z",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof x)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?x.ZERO:new x(t,n,r.ONE)}static fromBytes(e){const t=x.fromAffine(p(Br(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return x.fromBytes(Wr(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return S.createCache(this,e),t||this.multiply(go),this}assertValidity(){T(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){g(e);const{X:t,Y:n,Z:i}=this,{X:s,Y:a,Z:o}=e,u=r.eql(r.mul(t,o),r.mul(s,i)),d=r.eql(r.mul(n,o),r.mul(a,i));return u&&d}negate(){return new x(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,go),{X:i,Y:a,Z:o}=this;let u=r.ZERO,d=r.ZERO,c=r.ZERO,l=r.mul(i,i),p=r.mul(a,a),h=r.mul(o,o),f=r.mul(i,a);return f=r.add(f,f),c=r.mul(i,o),c=r.add(c,c),u=r.mul(e,c),d=r.mul(n,h),d=r.add(u,d),u=r.sub(p,d),d=r.add(p,d),d=r.mul(u,d),u=r.mul(f,u),c=r.mul(n,c),h=r.mul(e,h),f=r.sub(l,h),f=r.mul(e,f),f=r.add(f,c),c=r.add(l,l),l=r.add(c,l),l=r.add(l,h),l=r.mul(l,f),d=r.add(d,l),h=r.mul(a,o),h=r.add(h,h),l=r.mul(h,f),u=r.sub(u,l),c=r.mul(h,p),c=r.add(c,c),c=r.add(c,c),new x(u,d,c)}add(e){g(e);const{X:t,Y:n,Z:i}=this,{X:a,Y:o,Z:u}=e;let d=r.ZERO,c=r.ZERO,l=r.ZERO;const p=s.a,h=r.mul(s.b,go);let f=r.mul(t,a),m=r.mul(n,o),y=r.mul(i,u),b=r.add(t,n),v=r.add(a,o);b=r.mul(b,v),v=r.add(f,m),b=r.sub(b,v),v=r.add(t,i);let w=r.add(a,u);return v=r.mul(v,w),w=r.add(f,y),v=r.sub(v,w),w=r.add(n,i),d=r.add(o,u),w=r.mul(w,d),d=r.add(m,y),w=r.sub(w,d),l=r.mul(p,v),d=r.mul(h,y),l=r.add(d,l),d=r.sub(m,l),l=r.add(m,l),c=r.mul(d,l),m=r.add(f,f),m=r.add(m,f),y=r.mul(p,y),v=r.mul(h,v),m=r.add(m,y),y=r.sub(f,y),y=r.mul(p,y),v=r.add(v,y),f=r.mul(m,v),c=r.add(c,f),f=r.mul(w,v),d=r.mul(b,d),d=r.sub(d,f),f=r.mul(b,m),l=r.mul(w,l),l=r.add(l,f),new x(d,c,l)}subtract(e){return this.add(e.negate())}is0(){return this.equals(x.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,s;const a=e=>S.cached(this,e,e=>Es(x,e));if(n){const{k1neg:t,k1:i,k2neg:o,k2:u}=v(e),{p:d,f:c}=a(i),{p:l,f:p}=a(u);s=c.add(p),r=E(n.beta,d,l,t,o)}else{const{p:t,f:n}=a(e);r=t,s=n}return Es(x,[r,s])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===mo||r.is0())return x.ZERO;if(e===yo)return r;if(S.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:s,k2:a}=v(e),{p1:o,p2:u}=function(e,t,n,r){let i=t,s=e.ZERO,a=e.ZERO;for(;n>vs||r>vs;)n&ws&&(s=s.add(i)),r&ws&&(a=a.add(i)),i=i.double(),n>>=ws,r>>=ws;return{p1:s,p2:a}}(x,r,i,a);return E(n.beta,o,u,t,s)}return S.unsafe(r,e)}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return a===yo||(e?e(x,this):S.unsafe(this,o).is0())}clearCofactor(){const{clearCofactor:e}=t;return a===yo?this:e?e(x,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return Li(e,"isCompressed"),this.assertValidity(),l(x,this,e)}toHex(e=!0){return Kr(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const P=i.BITS,S=new Ds(x,t.endo?Math.ceil(P/2):P);return x.BASE.precompute(8),x}function To(e){return Uint8Array.of(e?2:3)}function Eo(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function xo(e,t,n={}){Ur(t),Hi(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=(n=Object.assign({},n)).randomBytes||Jr,i=n.hmac||((e,n)=>uo(t,e,n)),{Fp:s,Fn:a}=e,{ORDER:o,BITS:u}=a,{keygen:d,getPublicKey:c,getSharedSecret:l,utils:p,lengths:h}=function(e,t={}){const{Fn:n}=e,r=t.randomBytes||Jr,i=Object.assign(Eo(e.Fp,n),{seed:gs(n.ORDER)});function s(e=r(i.seed)){return function(e,t,n=!1){Br(e);const r=e.length,i=bs(t),s=gs(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const a=ss(n?ji(e):Ui(e),t-Yi)+Yi;return n?$i(a,i):qi(a,i)}(Br(e,i.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(n.fromBytes(t)).toBytes(r)}function o(e){const{secretKey:t,publicKey:r,publicKeyUncompressed:s}=i;if(!Nr(e))return;if("_lengths"in n&&n._lengths||t===r)return;const a=Br(e,void 0,"key").length;return a===r||a===s}const u={isValidSecretKey:function(e){try{const t=n.fromBytes(e);return n.isValidNot0(t)}catch(e){return!1}},isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:s}=i;try{const i=t.length;return!(!0===n&&i!==r||!1===n&&i!==s||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s},d=Rs(s,a);return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,i=!0){if(!0===o(t))throw new Error("first arg must be private key");if(!1===o(r))throw new Error("second arg must be public key");const s=n.fromBytes(t);return e.fromBytes(r).multiply(s).toBytes(i)},keygen:d,Point:e,utils:u,lengths:i})}(e,n),f={prehash:!0,lowS:"boolean"!=typeof n.lowS||n.lowS,format:"compact",extraEntropy:!1},m=o*bo<s.ORDER;function y(e){return e>o>>yo}function b(e,t){if(!a.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function g(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function v(e,t){lo(t);const n=h.signature;return Br(e,"compact"===t?n:"recovered"===t?n+1:void 0)}class w{r;s;recovery;constructor(e,t,n){if(this.r=b("r",e),this.s=b("s",t),null!=n){if(g(),![0,1,2,3].includes(n))throw new Error("invalid recovery id");this.recovery=n}Object.freeze(this)}static fromBytes(e,t=f.format){let n;if(v(e,t),"der"===t){const{r:t,s:n}=fo.toSig(Br(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=h.signature/2,i=e.subarray(0,r),s=e.subarray(r,2*r);return new w(a.fromBytes(i),a.fromBytes(s),n)}static fromHex(e,t){return this.fromBytes(Wr(e),t)}assertRecovery(){const{recovery:e}=this;if(null==e)throw new Error("invalid recovery id: must be present");return e}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const{r:n,s:r}=this,i=this.assertRecovery(),u=2===i||3===i?n+o:n;if(!s.isValid(u))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const d=s.toBytes(u),c=e.fromBytes(Qr(To(!(1&i)),d)),l=a.inv(u),p=E(Br(t,void 0,"msgHash")),h=a.create(-p*l),f=a.create(r*l),m=e.BASE.multiplyUnsafe(h).add(c.multiplyUnsafe(f));if(m.is0())throw new Error("invalid recovery: point at infinify");return m.assertValidity(),m}hasHighS(){return y(this.s)}toBytes(e=f.format){if(lo(e),"der"===e)return Wr(fo.hexFromSig(this));const{r:t,s:n}=this,r=a.toBytes(t),i=a.toBytes(n);return"recovered"===e?(g(),Qr(Uint8Array.of(this.assertRecovery()),r,i)):Qr(r,i)}toHex(e){return Kr(this.toBytes(e))}}const T=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Ui(e),n=8*e.length-u;return n>0?t>>BigInt(n):t},E=n.bits2int_modN||function(e){return a.create(T(e))},x=Ki(u);function P(e){return Gi("num < 2^"+u,e,mo,x),a.toBytes(e)}function S(e,n){return Br(e,void 0,"message"),n?Br(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:d,getPublicKey:c,getSharedSecret:l,utils:p,lengths:h,Point:e,sign:function(n,s,o={}){const{seed:u,k2sig:d}=function(t,n,i){const{lowS:s,prehash:o,extraEntropy:u}=po(i,f);t=S(t,o);const d=E(t),c=a.fromBytes(n);if(!a.isValidNot0(c))throw new Error("invalid private key");const l=[P(c),P(d)];if(null!=u&&!1!==u){const e=!0===u?r(h.secretKey):u;l.push(Br(e,void 0,"extraEntropy"))}const p=Qr(...l),b=d;return{seed:p,k2sig:function(t){const n=T(t);if(!a.isValidNot0(n))return;const r=a.inv(n),i=e.BASE.multiply(n).toAffine(),o=a.create(i.x);if(o===mo)return;const u=a.create(r*a.create(b+o*c));if(u===mo)return;let d=(i.x===o?0:2)|Number(i.y&yo),l=u;return s&&y(u)&&(l=a.neg(u),d^=1),new w(o,l,m?void 0:d)}}}(n,s,o),c=function(e,t,n){if(Or(e,"hashLen"),Or(t,"qByteLen"),"function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),i=Uint8Array.of(),s=Uint8Array.of(0),a=Uint8Array.of(1);let o=r(e),u=r(e),d=0;const c=()=>{o.fill(1),u.fill(0),d=0},l=(...e)=>n(u,Qr(o,...e)),p=(e=i)=>{u=l(s,e),o=l(),0!==e.length&&(u=l(a,e),o=l())},h=()=>{if(d++>=1e3)throw new Error("drbg: tried max amount of iterations");let e=0;const n=[];for(;e<t;){o=l();const t=o.slice();n.push(t),e+=o.length}return Qr(...n)};return(e,t)=>{let n;for(c(),p(e);!(n=t(h()));)p();return c(),n}}(t.outputLen,a.BYTES,i);return c(u,d).toBytes(o.format)},verify:function(t,n,r,i={}){const{lowS:s,prehash:o,format:u}=po(i,f);if(r=Br(r,void 0,"publicKey"),n=S(n,o),!Nr(t))throw new Error("verify expects Uint8Array signature"+(t instanceof w?", use sig.toBytes()":""));v(t,u);try{const i=w.fromBytes(t,u),o=e.fromBytes(r);if(s&&i.hasHighS())return!1;const{r:d,s:c}=i,l=E(n),p=a.inv(c),h=a.create(l*p),f=a.create(d*p),m=e.BASE.multiplyUnsafe(h).add(o.multiplyUnsafe(f));return!m.is0()&&a.create(m.x)===d}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=po(n,f);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}const Po={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},So={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ao=/* @__PURE__ */BigInt(2),Co=ys(Po.p,{sqrt:function(e){const t=Po.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),u=BigInt(88),d=e*e*e%t,c=d*d*e%t,l=as(c,n,t)*c%t,p=as(l,n,t)*c%t,h=as(p,Ao,t)*d%t,f=as(h,i,t)*h%t,m=as(f,s,t)*f%t,y=as(m,o,t)*m%t,b=as(y,u,t)*y%t,g=as(b,o,t)*m%t,v=as(g,n,t)*c%t,w=as(v,a,t)*f%t,T=as(w,r,t)*d%t,E=as(T,Ao,t);if(!Co.eql(Co.sqr(E),e))throw new Error("Cannot find square root");return E}}),ko=/* @__PURE__ */xo(/* @__PURE__ */wo(Po,{Fp:Co,endo:So}),Mi);class Io{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return ko.Point.fromBytes(e),e}catch(e){throw new Qe(String(e))}}(e),this.raw=function(e){return ko.Point.fromBytes(e).toBytes()}(this._key)}toMultihash(){return _n(Fo(this))}toCID(){return kn.createV1(114,this.toMultihash())}toString(){return Vt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}verify(e,t,n){return function(e,t,n,r){const i=ur.digest(n instanceof Uint8Array?n:n.subarray());if(ta(i))return i.then(({digest:n})=>(r?.signal?.throwIfAborted(),ko.verify(t,n,e,{prehash:!1,format:"der"}))).catch(e=>{if("AbortError"===e.name)throw e;throw new Ys(String(e))});try{return r?.signal?.throwIfAborted(),ko.verify(t,i.digest,e,{prehash:!1,format:"der"})}catch(e){throw new Ys(String(e))}}(this._key,t,e,n)}}function Do(e){return new Io(e)}function Mo(e,t){const{Type:n,Data:r}=no.decode(e),i=r??new Uint8Array;switch(n){case eo.RSA:return function(e,t){if(e.byteLength>=1062)throw new Qe("Key size is too large");return function(e,t,n){const r=function(e){const t=wr(e[1],{offset:0});return{kty:"RSA",n:mr(t[0],"base64url"),e:mr(t[1],"base64url")}}(e);return null==n&&(n=En(18,Mi(no.encode({Type:eo.RSA,Data:t})))),new so(r,n)}(wr(e,{offset:0}),e,t)}(i,t);case eo.Ed25519:return ia(i);case eo.secp256k1:return Do(i);case eo.ECDSA:return Rr(i);default:throw new bt}}function Fo(e){return no.encode({Type:eo[e.type],Data:e.raw})}const Ro=Symbol.for("nodejs.util.inspect.custom");class _o{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[xt]=!0;toString(){return null==this.string&&(this.string=Vt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return kn.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Ln(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Ln(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ro](){return`PeerId(${this.toString()})`}}class Lo extends _o{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class No extends _o{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Oo extends _o{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class Bo{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=_n(fr(this.url))}[Ro](){return`PeerId(${this.url})`}[xt]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return kn.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=mr(e)),e.toString()===this.toString())}}function Uo(e,t){let n;if("1"===e.charAt(0)||"Q"===e.charAt(0))n=xn(Vt.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return $o(kn.parse(e));if(null==t)throw new We('Please pass a multibase decoder for strings that do not start with "1" or "Q"');n=xn(t.decode(e))}return qo(n)}function jo(e){if("Ed25519"===e.type)return new No({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Oo({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Lo({multihash:e.toCID().multihash,publicKey:e});throw new bt}function qo(e){if(function(e){return e.code===ur.code}(e))return new Lo({multihash:e});if(function(e){return 0===e.code}(e))try{const t=function(e){const{Type:t,Data:n}=no.decode(e.digest),r=n??new Uint8Array;switch(t){case eo.Ed25519:return ia(r);case eo.secp256k1:return Do(r);case eo.ECDSA:return Rr(r);default:throw new bt}}(e);if("Ed25519"===t.type)return new No({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Oo({multihash:e,publicKey:t})}catch(t){const n=mr(e.digest);return new Bo(new URL(n))}throw new at("Supplied PeerID Multihash is invalid")}function $o(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new st("Supplied PeerID CID is invalid");if(2336===e.code){const t=mr(e.multihash.digest);return new Bo(new URL(t))}return qo(e.multihash)}class zo extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Vo extends Error{static name="ValidationError";name="ValidationError"}class Go extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Ko extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const Ho=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,n=e();return void 0===n&&(this.index=t),n}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{const t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return n()})}readNumber(e,t,n,r){return this.readAtomically(()=>{let i=0,s=0;const a=this.peekChar();if(void 0===a)return;const o="0"===a,u=2**(8*r)-1;for(;;){const n=this.readAtomically(()=>{const t=this.readChar();if(void 0===t)return;const n=Number.parseInt(t,e);return Number.isNaN(n)?void 0:n});if(void 0===n)break;if(i*=e,i+=n,i>u)return;if(s+=1,void 0!==t&&s>t)return}return 0===s||!n&&o&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(void 0===n)return;e[t]=n}return e})}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const n=2*t;if(t<e.length-3){const r=this.readSeparator(":",t,()=>this.readIPv4Addr());if(void 0!==r)return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],[n+4,!0]}const r=this.readSeparator(":",t,()=>this.readNumber(16,4,!0,2));if(void 0===r)return[n,!1];e[n]=r>>8,e[n+1]=255&r}return[e.length,!1]};return this.readAtomically(()=>{const t=new Uint8Array(16),[n,r]=e(t);if(16===n)return t;if(r)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Wo(e){if(!(e.length>15))return Ho.new(e).parseWith(()=>Ho.readIPv4Addr())}function Qo(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Ho.new(e).parseWith(()=>Ho.readIPv6Addr())}function Yo(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const n=Ho.new(e).parseWith(()=>Ho.readIPAddr());return n?t&&4===n.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,n[0],n[1],n[2],n[3]]):n:void 0}function Jo(e){return Boolean(Wo(e))}function Zo(e){return Boolean(Qo(e))}const Xo=41,eu=421,tu=448,nu=449,ru=466,iu=281,su=290;function au(e){return t=>mr(t,e)}function ou(e){return t=>fr(t,e)}function uu(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function du(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function cu(e){const t=e.subarray(0,e.length-2),n=e.subarray(e.length-2);return`${mr(t,"base32")}:${uu(n)}`}const lu=function(e){e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach((e,n)=>{const r=parseInt(e,10);if(isNaN(r)||r<0||r>255)throw new zo("Invalid byte value in IP address");t[n]=r}),t},pu=Object.values(dr).map(e=>e.decoder),hu=function(){let e=pu[0].or(pu[1]);return pu.slice(2).forEach(t=>e=e.or(t)),e}(),fu=function(...e){return t=>{for(const n of e)n(t)}}(function(e){if(parseInt(e).toString()!==e)throw new Vo("Value must be an integer")},function(e){if(e<0)throw new Vo("Value must be a positive integer, or zero")},e=>{if(e>65535)throw new Vo("Value must be smaller than or equal to 65535")}),mu=-1,yu=new class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new Ko(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){const t=this.protocolsByCode.get(e);null!=t&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(e=>{this.protocolsByName.delete(e)}))}},bu=[{code:4,name:"ip4",size:32,valueToBytes:lu,bytesToValue:function(e){if(4!==e.byteLength)throw new zo("IPv4 address was incorrect length");const t=[];for(let n=0;n<e.byteLength;n++)t.push(e[n]);return t.join(".")},validate:e=>{if(!Jo(e))throw new Vo(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:du,bytesToValue:uu,validate:fu},{code:273,name:"udp",size:16,valueToBytes:du,bytesToValue:uu,validate:fu},{code:33,name:"dccp",size:16,valueToBytes:du,bytesToValue:uu,validate:fu},{code:Xo,name:"ip6",size:128,valueToBytes:function(e){let t=0;const n=(e=e.toString().trim()).split(":",8);let r;for(r=0;r<n.length;r++){let e;Jo(n[r])&&(e=lu(n[r]),n[r]=mr(e.subarray(0,2),"base16")),null!=e&&++r<8&&n.splice(r,0,mr(e.subarray(2,4),"base16"))}if(""===n[0])for(;n.length<8;)n.unshift("0");else if(""===n[n.length-1])for(;n.length<8;)n.push("0");else if(n.length<8){for(r=0;r<n.length&&""!==n[r];r++);const e=[r,1];for(r=9-n.length;r>0;r--)e.push("0");n.splice.apply(n,e)}const i=new Uint8Array(t+16);for(r=0;r<n.length;r++){""===n[r]&&(n[r]="0");const e=parseInt(n[r],16);if(isNaN(e)||e<0||e>65535)throw new zo("Invalid byte value in IP address");i[t++]=e>>8&255,i[t++]=255&e}return i},bytesToValue:function(e){if(16!==e.byteLength)throw new zo("IPv6 address was incorrect length");const t=[];for(let n=0;n<e.byteLength;n+=2){const r=e[n+1],i=`${e[n].toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`;t.push(i)}const n=t.join(":");try{const e=new URL(`http://[${n}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new zo(`Invalid IPv6 address "${n}"`)}},stringToValue:function(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new zo(`Invalid IPv6 address "${e}"`)}},validate:e=>{if(!Zo(e))throw new Vo(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:mu},{code:43,name:"ipcidr",size:8,bytesToValue:au("base10"),valueToBytes:ou("base10")},{code:53,name:"dns",size:mu},{code:54,name:"dns4",size:mu},{code:55,name:"dns6",size:mu},{code:56,name:"dnsaddr",size:mu},{code:132,name:"sctp",size:16,valueToBytes:du,bytesToValue:uu,validate:fu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mu,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:eu,name:"p2p",aliases:["ipfs"],size:mu,bytesToValue:au("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?ou("base58btc")(e):kn.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:cu,valueToBytes:function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const n=fr(t[0],"base32"),r=parseInt(t[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const i=du(r);return Bn([n,i],n.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:cu,valueToBytes:function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const n=Ht.decode(`b${t[0]}`),r=parseInt(t[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const i=du(r);return Bn([n,i],n.length+i.length)}},{code:446,name:"garlic64",size:mu},{code:447,name:"garlic32",size:mu},{code:tu,name:"tls"},{code:nu,name:"sni",size:mu},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:ru,name:"certhash",size:mu,bytesToValue:(gu=Xn,e=>gu.encoder.encode(e)),valueToBytes:function(e){return hu.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:mu,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:iu,name:"webrtc"},{code:su,name:"p2p-circuit"},{code:777,name:"memory",size:mu}];var gu;function vu(e,t,n){return null==e.size||0===e.size?0:e.size>0?e.size/8:va(t,n)}bu.forEach(e=>{yu.addProtocol(e)});const wu=Symbol.for("nodejs.util.inspect.custom"),Tu=Symbol.for("@multiformats/multiaddr");class Eu{[Tu]=!0;#t;#n;#r;constructor(e="/",t={}){this.#t=function(e){if(null==e&&(e="/"),xu(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let n=0;for(;n<e.length;){const r=va(e,n),i=yu.getProtocol(r),s=ma(r),a=vu(i,e,n+s);let o=0;a>0&&i.size===mu&&(o=ma(a));const u=s+o+a,d={code:r,name:i.name,bytes:e.subarray(n,n+u)};if(a>0){const t=n+s+o,r=e.subarray(t,t+a);d.value=i.bytesToValue?.(r)??mr(r)}t.push(d),n+=u}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new zo('String multiaddr must start with "/"');const t=[];let n="protocol",r="",i="";for(let s=1;s<e.length;s++){const a=e.charAt(s);"/"!==a&&("protocol"===n?i+=e.charAt(s):r+=e.charAt(s));const o=s===e.length-1;if("/"===a||o){const e=yu.getProtocol(i);if("protocol"===n){if(null==e.size||0===e.size){t.push({code:e.code,name:e.name}),r="",i="",n="protocol";continue}if(o)throw new zo(`Component ${i} was missing value`);n="value"}else if("value"===n){const s={code:e.code,name:e.name};if(null!=e.size&&0!==e.size){if(""===r)throw new zo(`Component ${i} was missing value`);s.value=e.stringToValue?.(r)??r}t.push(s),r="",i="",n="protocol"}}}if(""!==i&&""!==r)throw new zo("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new zo("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach(e=>{const t=yu.getProtocol(e.code);null!=e.value&&t.validate?.(e.value)})}(this)}get bytes(){return null==this.#r&&(this.#r=function(e){let t=0;const n=[];for(const r of e){if(null==r.bytes){const e=yu.getProtocol(r.code),t=ma(r.code);let n,i=0,s=0;null!=r.value&&(n=e.valueToBytes?.(r.value)??fr(r.value),i=n.byteLength,e.size===mu&&(s=ma(i)));const a=new Uint8Array(t+s+i);let o=0;ya(r.code,a,o),o+=t,null!=n&&(e.size===mu&&(ya(i,a,o),o+=s),a.set(n,o)),r.bytes=a}n.push(r.bytes),t+=r.bytes.byteLength}return Bn(n,t)}(this.#t)),this.#r}toString(){return null==this.#n&&(this.#n=`/${this.#t.flatMap(e=>{if(null==e.value)return e.name;const t=yu.getProtocol(e.code);if(null==t)throw new zo(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`),this.#n}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(e=>({...e}))]}encapsulate(e){const t=new Eu(e);return new Eu([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),n=this.toString(),r=n.lastIndexOf(t);if(r<0)throw new Go(`Address ${this.toString()} does not contain subaddress: ${t}`);return new Eu(n.slice(0,r),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===e){t=n;break}return new Eu(this.#t.slice(0,t),{validate:!1})}equals(e){return Ln(this.bytes,e.bytes)}[wu](){return`Multiaddr(${this.toString()})`}}function xu(e){return Boolean(e?.[Tu])}function Pu(e){return new Eu(e)}function Su(e){return Array.from(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function Au(e){for(var t,n=e.reduce(function(e,t){return e+t.length},0),r=new Uint8Array(n),i=0,s=C(e);!(t=s()).done;){var a=t.value;r.set(a,i),i+=a.length}return r}function Cu(e,t){var n=u.PublicKey.fromHex(function(e){if("string"==typeof e)return e.startsWith("0x")?e:"0x"+e;var t=e instanceof Uint8Array?e:Array.isArray(e)?Uint8Array.from(e):Uint8Array.from(Object.keys(e).sort(function(e,t){return Number(e)-Number(t)}).map(function(t){return e[Number(t)]}));return"0x"+Su(t)}(e)),r=u.encrypt(n.toHex(),(new TextEncoder).encode(t));return Su(new Uint8Array(r))}function ku(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Iu=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getConsumerAddress=function(e){return pT(e)},t.getSignature=function(e,t,n){return lT(e,t,n)},t.getAuthorization=function(e){return hT(e)},t.getPersistentStorageSignaturePayload=function(e,t,n,r){try{var i=this;if("string"==typeof t)throw new Error("Persistent storage operations require a Signer because these commands require nonce/signature.");return Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(a){return Promise.resolve(i.getConsumerAddress(t)).then(function(o){return Promise.resolve(i.getNonce(e,o,r,s,a)).then(function(e){var r=(e+1).toString();return Promise.resolve(i.getSignature(t,r,n)).then(function(e){if(!e)throw new Error("Could not sign persistent storage request.");return{consumerAddress:o,nonce:r,signature:e}})})})})})}catch(e){return Promise.reject(e)}},t.resolvePersistentStorageRoute=function(e,t,n,r){for(var i,s=C(n);!(i=s()).done;){var a=this.getEndpointURL(t,i.value);if(null!=a&&a.urlPath)return a.urlPath}return e.replace(/\/+$/,"")+r},t.getEndpoints=function(e,t){try{var n=this;return Promise.resolve(ku(function(){return Promise.resolve(n.getData(e,t)).then(function(e){return Promise.resolve(e.json())})},function(e){throw O.error("Finding the service endpoints failed:",e),new Error("HTTP request failed calling Provider")}))}catch(e){return Promise.reject(e)}},t.getNodeStatus=function(e,t){try{var n=this;return Promise.resolve(n.getEndpoints(e)).then(function(r){return Promise.resolve(n.getServiceEndpoints(e,r)).then(function(e){var r=n.getEndpointURL(e,"directCommand");return null!=r&&r.urlPath?ku(function(){return Promise.resolve(g.default(r.urlPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:T.STATUS}),signal:t})).then(function(e){return null!=e&&e.ok?e.json():null})},function(e){return O.error("getNodeStatus failed:",e),null}):null})})}catch(e){return Promise.reject(e)}},t.getNodeJobs=function(e,t,n){try{var r=this;return Promise.resolve(r.getEndpoints(e)).then(function(i){return Promise.resolve(r.getServiceEndpoints(e,i)).then(function(e){var i=r.getEndpointURL(e,"jobs");if(null==i||!i.urlPath)return[];var s=i.urlPath;return t&&(s+="?fromTimestamp="+t),ku(function(){return Promise.resolve(g.default(s,{method:"GET",headers:{"Content-Type":"application/json"},signal:n})).then(function(e){var t;function n(e){return t?e:[]}var r=function(){if(null!=e&&e.ok)return Promise.resolve(e.json()).then(function(e){var n=Array.isArray(null==e?void 0:e.jobs)?e.jobs:[];return t=1,n})}();return r&&r.then?r.then(n):n(r)})},function(e){return O.error("getNodeJobs failed:",e),[]})})})}catch(e){return Promise.reject(e)}},t.getNodePublicKey=function(e){try{return Promise.resolve(this.getEndpoints(e)).then(function(e){return e.nodePublicKey})}catch(e){return Promise.reject(e)}},t.getEndpointURL=function(e,t){return e?e.find(function(e){return e.serviceName.toLowerCase()===t.toLowerCase()}):null},t.getServiceEndpoints=function(e,t){try{var n=[];for(var r in t.serviceEndpoints){var i={serviceName:r,method:t.serviceEndpoints[r][0],urlPath:e.replace(/\/+$/,"")+"/"+t.serviceEndpoints[r][1].replace(/^\/+/,"")};n.push(i)}return Promise.resolve(n)}catch(e){return Promise.reject(e)}},t.getNonce=function(e,t,n,r,i){try{var s=function(){function s(){var e=a.getEndpointURL(i,"nonce")?a.getEndpointURL(i,"nonce").urlPath:null;return e?ku(function(){return Promise.resolve(g.default(e+"?userAddress="+t,{method:"GET",headers:{"Content-Type":"application/json"},signal:n})).then(function(e){return Promise.resolve(e.json()).then(function(e){var t=e.nonce;return t&&null!==t?Number(t):0})})},function(e){throw O.error(e),new Error(e.message)}):null}var o=function(){if(!i)return Promise.resolve(a.getServiceEndpoints(e,r)).then(function(e){i=e})}();return o&&o.then?o.then(s):s()},a=this,o=function(){if(!r)return Promise.resolve(a.getEndpoints(e)).then(function(e){r=e})}();return Promise.resolve(o&&o.then?o.then(s):s())}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getEndpoints(n)).then(function(i){return Promise.resolve(a.getServiceEndpoints(n,i)).then(function(o){return Promise.resolve(a.getConsumerAddress(r)).then(function(u){return Promise.resolve(a.getNonce(n,u,s,i,o)).then(function(n){var i=(n+1).toString();return Promise.resolve(a.getSignature(r,i,T.ENCRYPT)).then(function(n){var r=(a.getEndpointURL(o,"encrypt")?a.getEndpointURL(o,"encrypt").urlPath:null)+"?chainId="+t;return r?(r+="&nonce="+i,r+="&consumerAddress="+u,r+="&signature="+n,ku(function(){return Promise.resolve(g.default(r,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/octet-stream"},signal:s})).then(function(e){return Promise.resolve(e.text())})},function(e){throw O.error(e),new Error("HTTP request failed calling Provider")})):null})})})})})}catch(e){return Promise.reject(e)}},t.checkDidFiles=function(e,t,n,r,i){void 0===r&&(r=!1);try{var s=this;return Promise.resolve(s.getEndpoints(n)).then(function(a){return Promise.resolve(s.getServiceEndpoints(n,a)).then(function(n){function a(e){var t;function n(e){return t?e:Promise.resolve(o.json()).then(function(e){throw O.error("File info call failed: ",o.status,o.statusText,e),new Error(JSON.stringify(e))})}var r=function(e){if(null!=(e=o)&&e.ok)return Promise.resolve(o.json()).then(function(e){for(var n,r=C(e);!(n=r()).done;)d.push(n.value);return t=1,d})}();return r&&r.then?r.then(n):n(r)}var o,u={did:e,serviceId:t,checksum:r},d=[],c=s.getEndpointURL(n,"fileinfo")?s.getEndpointURL(n,"fileinfo").urlPath:null;if(!c)return null;var l=ku(function(){return Promise.resolve(g.default(c,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json"},signal:i})).then(function(e){o=e})},function(e){throw O.error("File info call failed: "),O.error(e),new Error(e)});return l&&l.then?l.then(a):a()})})}catch(e){return Promise.reject(e)}},t.getFileInfo=function(e,t,n,r){void 0===n&&(n=!1);try{var i=this;return Promise.resolve(i.getEndpoints(t)).then(function(s){return Promise.resolve(i.getServiceEndpoints(t,s)).then(function(t){function s(e){var t;function n(e){return t?e:Promise.resolve(a.json()).then(function(e){throw O.error("File info call failed: ",a.status,a.statusText,e),new Error(JSON.stringify(e))})}var r=function(e){if(null!=(e=a)&&e.ok)return Promise.resolve(a.json()).then(function(e){for(var n,r=C(e);!(n=r()).done;)u.push(n.value);return t=1,u})}();return r&&r.then?r.then(n):n(r)}var a,o=k({},e,{checksum:n}),u=[],d=i.getEndpointURL(t,"fileinfo")?i.getEndpointURL(t,"fileinfo").urlPath:null;if(!d)return null;var c=ku(function(){return Promise.resolve(g.default(d,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){a=e})},function(e){throw O.error("File info call failed: "),O.error(e),new Error(e)});return c&&c.then?c.then(s):s()})})}catch(e){return Promise.reject(e)}},t.getComputeEnvironments=function(e,t){try{var n=this;return Promise.resolve(n.getEndpoints(e)).then(function(r){return Promise.resolve(n.getServiceEndpoints(e,r)).then(function(e){var r;function i(e){var t;return null!=(t=s)&&t.ok?s.json():Promise.resolve(s.json()).then(function(e){throw O.error("Fetch compute env failed: ",s.status,s.statusText,e),new Error(JSON.stringify(e))})}var s,a=null==(r=n.getEndpointURL(e,"computeEnvironments"))?void 0:r.urlPath;if(!a)return null;var o=ku(function(){return Promise.resolve(g.default(a,{method:"GET",headers:{"Content-Type":"application/json"},signal:t})).then(function(e){s=e})},function(e){throw O.error("Fetch compute env failed: "),O.error(e),new Error(e)});return o&&o.then?o.then(i):i()})})}catch(e){return Promise.reject(e)}},t.initialize=function(e,t,n,r,i,s,a,o,u){try{var d=this;return Promise.resolve(d.getEndpoints(i)).then(function(c){return Promise.resolve(d.getServiceEndpoints(i,c)).then(function(i){function c(e){var t;function n(e){return t?e:Promise.resolve(l.json()).then(function(e){throw O.error("Provider initialized failed: ",l.status,l.statusText,e),new Error(JSON.stringify(e))})}var r=function(e){if(200===(null==(e=l)?void 0:e.status))return Promise.resolve(l.json()).then(function(e){return t=1,e})}();return r&&r.then?r.then(n):n(r)}var l,p=d.getEndpointURL(i,"initialize")?d.getEndpointURL(i,"initialize").urlPath:null;if(!p)return null;p+="?documentId="+e,p+="&serviceId="+t,p+="&fileIndex="+n,p+="&consumerAddress="+r,a&&(p+="&userdata="+encodeURI(JSON.stringify(a))),o&&(p+="&environment="+encodeURI(o)),u&&(p+="&validUntil="+u);var h=ku(function(){return Promise.resolve(g.default(p,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})).then(function(e){l=e})},function(e){throw O.error("Provider initialized failed: "),O.error(e),new Error("Provider initialize failed url: "+p+" ")});return h&&h.then?h.then(c):c()})})}catch(e){return Promise.reject(e)}},t.initializeCompute=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h){try{var f=this;return Promise.resolve(f.getEndpoints(s)).then(function(m){return Promise.resolve(f.getServiceEndpoints(s,m)).then(function(m){function y(){function e(){var e;function t(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw O.error("Initialize compute failed: ",e.status,e.statusText,t),O.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(t))})}var i=function(t){if(null!=(t=e)&&t.ok)return Promise.resolve(e.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var n=ku(function(){return Promise.resolve(g.default(b,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json"},signal:c})).then(function(t){return e=t,function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(""+e)})}()})},function(e){throw O.error("Initialize compute failed: "),O.error(e),new Error("ComputeJob cannot be initialized: "+e.message+".")});return n&&n.then?n.then(t):t()}var t=function(){if(h)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(v.output=Cu(e,JSON.stringify(h)))})}();return t&&t.then?t.then(e):e()}var b=f.getEndpointURL(m,"initializeCompute")?f.getEndpointURL(m,"initializeCompute").urlPath:null;if(!b)return null;var v={datasets:e,algorithm:t,environment:n,payment:{chainId:u,token:r,resources:o},maxJobDuration:i,consumerAddress:a};d&&(v.policyServer=d),l&&(v.queueMaxWaitTime=l);var w=function(){if(p)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(v.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(p)))})}();return w&&w.then?w.then(y):y()})})}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,a,o){try{var u=this;return Promise.resolve(u.getEndpoints(i)).then(function(d){return Promise.resolve(u.getServiceEndpoints(i,d)).then(function(c){var l=u.getEndpointURL(c,"download")?u.getEndpointURL(c,"download").urlPath:null;return l?Promise.resolve(u.getConsumerAddress(s)).then(function(p){return Promise.resolve(u.getNonce(i,p,null,d,c)).then(function(i){var d=(i+1).toString();return Promise.resolve(u.getSignature(s,d,T.DOWNLOAD)).then(function(i){var s=l;return s+="?fileIndex="+n,s+="&documentId="+e,s+="&transferTxId="+r,s+="&serviceId="+t,s+="&consumerAddress="+p,s+="&nonce="+d,a&&(s+="&policyServer="+encodeURI(JSON.stringify(a))),s+="&signature="+i,o&&(s+="&userdata="+encodeURI(JSON.stringify(o))),s})})}):null})})}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m){try{var y=this;return Promise.resolve(y.getEndpoints(e)).then(function(b){return Promise.resolve(y.getServiceEndpoints(e,b)).then(function(v){var w=y.getEndpointURL(v,"computeStart")?y.getEndpointURL(v,"computeStart").urlPath:null;return w?Promise.resolve(y.getConsumerAddress(t)).then(function(E){return Promise.resolve(y.getNonce(e,E,h,b,v)).then(function(b){var v=(b+1).toString();return Promise.resolve(y.getSignature(t,v,T.COMPUTE_START)).then(function(b){function T(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw O.error("Compute start failed: ",e.status,e.statusText,t),O.error("Payload was:",x),new Error(JSON.stringify(t))})}var i=function(t){if(null!=(t=e)&&t.ok)return Promise.resolve(e.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}p&&(x.policyServer=p),f&&(x.queueMaxWaitTime=f);var r=ku(function(){return Promise.resolve(g.default(w,{method:"POST",body:JSON.stringify(x),headers:{"Content-Type":"application/json",Authorization:y.getAuthorization(t)},signal:h})).then(function(t){e=t})},function(e){throw O.error("Compute start failed:"),O.error(e),O.error("Payload was:",x),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}o&&(x.resources=o),d&&(x.metadata=d),c&&(x.additionalViewers=c);var r=function(){if(l)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(x.output=Cu(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var x=Object();x.consumerAddress=E,x.signature=b,x.nonce=v,x.environment=n,x.maxJobDuration=s,x.resources=o,x.dataset=r[0],x.datasets=r,x.algorithm=i,x.chainId=u,x.payment={chainId:u,token:a,maxJobDuration:s,resources:o};var P=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(x.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(m)))})}();return P&&P.then?P.then(T):T()})})}):(O.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null)})})}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p){try{var h=this;return Promise.resolve(h.getEndpoints(e)).then(function(f){return Promise.resolve(h.getServiceEndpoints(e,f)).then(function(m){var y=h.getEndpointURL(m,"freeCompute")?h.getEndpointURL(m,"freeCompute").urlPath:null;return y?Promise.resolve(h.getConsumerAddress(t)).then(function(b){return Promise.resolve(h.getNonce(e,b,c,f,m)).then(function(f){var m=(f+1).toString();return Promise.resolve(h.getSignature(t,m,T.FREE_COMPUTE_START)).then(function(f){function v(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw O.error("Compute start failed: ",e.status,e.statusText,t),O.error("Payload was:",w),new Error(JSON.stringify(t))})}var i=function(t){if(null!=(t=e)&&t.ok)return Promise.resolve(e.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}d&&(w.policyServer=d),l&&(w.queueMaxWaitTime=l);var r=ku(function(){return Promise.resolve(g.default(y,{method:"POST",body:JSON.stringify(w),headers:{"Content-Type":"application/json",Authorization:h.getAuthorization(t)},signal:c})).then(function(t){e=t})},function(e){throw O.error("Compute start failed:"),O.error(e),O.error("Payload was:",w),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}var r=function(){if(u)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(w.output=Cu(e,JSON.stringify(u)))})}();return r&&r.then?r.then(n):n()}var w=Object();w.consumerAddress=b,w.signature=f,w.nonce=m,w.environment=n,w.resources=s,w.dataset=r[0],w.datasets=r,w.algorithm=i,a&&(w.metadata=a),o&&(w.additionalViewers=o);var T=function(){if(p)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(w.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(p)))})}();return T&&T.then?T.then(v):v()})})}):(O.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null)})})}catch(e){return Promise.reject(e)}},t.computeStreamableLogs=function(e,t,n,r){try{var i=this,s="string"==typeof t;return Promise.resolve(i.getEndpoints(e)).then(function(a){return Promise.resolve(i.getServiceEndpoints(e,a)).then(function(o){var u=i.getEndpointURL(o,"computeStreamableLogs")?i.getEndpointURL(o,"computeStreamableLogs").urlPath:null;return u?Promise.resolve(i.getConsumerAddress(t)).then(function(d){return Promise.resolve(i.getNonce(e,d,r,a,o)).then(function(e){function a(){var e;function n(t){var n,r;if(null!=(n=e)&&n.ok||200===(null==(r=e)?void 0:r.status))return e.body;var i=O.error,s=e.statusText,a=e.status;return Promise.resolve(e.json()).then(function(e){return i.call(O,"computeStreamableLogs failed: ",a,s,e),null})}var s=ku(function(){return Promise.resolve(g.default(u+c,{method:"GET",headers:{"Content-Type":"application/json",Authorization:i.getAuthorization(t)},signal:r})).then(function(t){e=t})},function(e){throw O.error("computeStreamableLogs failed:"),O.error(e),new Error("HTTP request failed calling Provider")});return s&&s.then?s.then(n):n()}var o=(e+1).toString(),c="?consumerAddress="+d+"&jobId="+n,l=function(){if(!s)return Promise.resolve(i.getSignature(t,o,T.COMPUTE_GET_STREAMABLE_LOGS)).then(function(e){c+="&signature="+e,c+="&nonce="+o})}();return l&&l.then?l.then(a):a()})}):(O.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null)})})}catch(e){return Promise.reject(e)}},t.computeStop=function(e,t,n,r,i){try{var s=this,a="string"==typeof n;return Promise.resolve(s.getEndpoints(t)).then(function(o){return Promise.resolve(s.getServiceEndpoints(t,o)).then(function(u){var d=s.getEndpointURL(u,"computeStop")?s.getEndpointURL(u,"computeStop").urlPath:null;return Promise.resolve(s.getConsumerAddress(n)).then(function(c){return Promise.resolve(s.getNonce(t,c,i,o,u)).then(function(t){var o=(t+1).toString();return Promise.resolve(s.getSignature(n,o,T.COMPUTE_STOP)).then(function(t){function u(e){var t;function n(e){return t?e:Promise.resolve(p.json()).then(function(e){throw O.error("Compute stop failed: ",p.status,p.statusText,e),new Error(JSON.stringify(e))})}var r=function(e){if(null!=(e=p)&&e.ok)return Promise.resolve(p.json()).then(function(e){return t=1,e})}();return r&&r.then?r.then(n):n(r)}var l=new URLSearchParams;l.set("consumerAddress",c),l.set("nonce",o),l.set("jobId",e),a||l.set("signature",t),r&&l.set("agreementId",r);var p,h=l.toString();if(!h)return null;var f=ku(function(){return Promise.resolve(g.default(d+"?"+h,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:s.getAuthorization(n)},signal:i})).then(function(e){p=e})},function(e){throw O.error("Compute stop failed:"),O.error(e),new Error("HTTP request failed calling Provider")});return f&&f.then?f.then(u):u()})})})})})}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{var s=this;return Promise.resolve(pT(t)).then(function(a){var o=hT(t);return Promise.resolve(s.getEndpoints(e)).then(function(t){return Promise.resolve(s.getServiceEndpoints(e,t)).then(function(e){function t(e){var t;function n(e){var n;if(t)return e;function r(e){return n?e:Promise.resolve(u.json()).then(function(e){throw O.error("Get compute status failed:",u.status,u.statusText,e),new Error(JSON.stringify(e))})}O.error("Get compute status failed:",u.status,u.statusText);var i=function(e){if(null!=(e=u)&&e.ok)return Promise.resolve(u.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var r=function(e){if(null!=(e=u)&&e.ok)return Promise.resolve(u.json()).then(function(e){return t=1,e})}();return r&&r.then?r.then(n):n(r)}var u,d=s.getEndpointURL(e,"computeStatus")?s.getEndpointURL(e,"computeStatus").urlPath:null,c="?consumerAddress="+a;if(c+=r&&"&agreementId="+r||"",c+=n&&"&jobId="+n||"",!d)return null;var l=ku(function(){return Promise.resolve(g.default(d+c,{method:"GET",headers:{"Content-Type":"application/json",Authorization:o},signal:i})).then(function(e){u=e})},function(e){throw O.error("Get compute status failed"),O.error(e),new Error(e)});return l&&l.then?l.then(t):t()})})})}catch(e){return Promise.reject(e)}},t.getComputeResultUrl=function(e,t,n,r){try{var i=this,s="string"==typeof t;return Promise.resolve(i.getEndpoints(e)).then(function(a){return Promise.resolve(i.getServiceEndpoints(e,a)).then(function(o){var u=i.getEndpointURL(o,"computeResult")?i.getEndpointURL(o,"computeResult").urlPath:null;return Promise.resolve(i.getConsumerAddress(t)).then(function(d){return Promise.resolve(i.getNonce(e,d,null,a,o)).then(function(e){var a=(e+1).toString();return Promise.resolve(i.getSignature(t,a,T.COMPUTE_GET_RESULT)).then(function(e){if(!u)return null;var t=u;return t+="?consumerAddress="+d,t+="&jobId="+n,t+="&index="+r.toString(),s||(t+="&nonce="+a,t+="&signature="+e),t})})})})})}catch(e){return Promise.reject(e)}},t.getComputeResult=function(e,t,n,r,i){void 0===i&&(i=0);try{return Promise.resolve(this.getComputeResultUrl(e,t,n,r)).then(function(e){if(!e)throw new Error("Could not retrieve compute result URL");return Promise.resolve(g.default(e,{headers:i>0?{Range:"bytes="+i+"-"}:{}})).then(function(e){if(!e.ok)throw new Error("Failed to fetch compute result: "+e.status);return e.body})})}catch(e){return Promise.reject(e)}},t.generateAuthToken=function(e,t,n){try{var r=this;return Promise.resolve(e.getAddress()).then(function(i){return Promise.resolve(r.getEndpoints(t)).then(function(s){return Promise.resolve(r.getServiceEndpoints(t,s)).then(function(a){var o=r.getEndpointURL(a,"generateAuthToken").urlPath||null;return Promise.resolve(r.getNonce(t,i,n,s,a)).then(function(t){var s=(t+1).toString();return Promise.resolve(r.getSignature(e,s,T.CREATE_AUTH_TOKEN)).then(function(e){return ku(function(){return Promise.resolve(g.default(o,{method:"POST",body:JSON.stringify({address:i,signature:e,nonce:s}),headers:{"Content-Type":"application/json"},signal:n})).then(function(e){if(null==e||!e.ok)throw new Error("Failed to generate auth token: "+e.status+" "+e.statusText);return Promise.resolve(e.json()).then(function(e){return null==e?void 0:e.token})})},function(e){throw O.error("Generate auth token failed:"),O.error(e),new Error("HTTP request failed calling Provider")})})})})})})}catch(e){return Promise.reject(e)}},t.invalidateAuthToken=function(e,t,n,r){try{var i=this;return Promise.resolve(e.getAddress()).then(function(s){return Promise.resolve(i.getEndpoints(n)).then(function(a){return Promise.resolve(i.getServiceEndpoints(n,a)).then(function(o){var u=i.getEndpointURL(o,"invalidateAuthToken").urlPath||null;return Promise.resolve(i.getNonce(n,s,r,a,o)).then(function(n){var i=(n+1).toString();return Promise.resolve($e(e,s+i)).then(function(e){return ku(function(){return Promise.resolve(g.default(u,{method:"POST",body:JSON.stringify({address:s,signature:e,token:t,nonce:i}),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){if(null==e||!e.ok)throw new Error("Failed to invalidate auth token: "+e.status+" "+e.statusText);return Promise.resolve(e.json())})},function(e){throw O.error("Generate auth token failed:"),O.error(e),new Error("HTTP request failed calling Provider")})})})})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){try{return Promise.resolve(ku(function(){return Promise.resolve(g.default(e,{method:"GET",headers:{"Content-Type":"application/json"},signal:t})).then(function(e){var t,n=function(){if(null!=e&&e.ok)return Promise.resolve(e.json()).then(function(e){if(e&&(e.providerAddress||e.providerAddresses))return t=!0})}();return n&&n.then?n.then(function(e){return!!t&&e}):!!t&&n})},function(e){return O.error("Error validating provider: "+e.message),!1}))}catch(e){return Promise.reject(e)}},t.PolicyServerPassthrough=function(e,t,n){try{var r=this;return Promise.resolve(r.getEndpoints(e)).then(function(i){return Promise.resolve(r.getServiceEndpoints(e,i)).then(function(e){function i(e){var n;function r(e){return n?e:Promise.resolve(s.json()).then(function(e){throw O.error("PolicyServerPassthrough failed: ",s.status,s.statusText,e),O.error("Payload was:",JSON.stringify(t)),new Error(JSON.stringify(e))})}var i=function(e){if(null!=(e=s)&&e.ok)return Promise.resolve(s.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var s,a=r.getEndpointURL(e,"PolicyServerPassthrough")?r.getEndpointURL(e,"PolicyServerPassthrough").urlPath:null;if(!a)return null;var o=ku(function(){return Promise.resolve(g.default(a,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"},signal:n})).then(function(e){return s=e,function(){if(!s.ok)return Promise.resolve(s.text()).then(function(e){throw new Error(""+e)})}()})},function(e){throw O.error("PolicyServerPassthrough failed: "),O.error(e),new Error("PolicyServerPassthrough failed: "+e.message+".")});return o&&o.then?o.then(i):i()})})}catch(e){return Promise.reject(e)}},t.initializePSVerification=function(e,t,n){try{var r=this;return Promise.resolve(r.getEndpoints(e)).then(function(i){return Promise.resolve(r.getServiceEndpoints(e,i)).then(function(e){function i(e){var n;function r(e){return n?e:Promise.resolve(s.json()).then(function(e){throw O.error("initializePSVerification failed: ",s.status,s.statusText,e),O.error("Payload was:",JSON.stringify(t)),new Error(JSON.stringify(e))})}var i=function(e){if(null!=(e=s)&&e.ok)return Promise.resolve(s.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var s,a=r.getEndpointURL(e,"initializePSVerification")?r.getEndpointURL(e,"initializePSVerification").urlPath:null;if(!a)return null;var o=ku(function(){return Promise.resolve(g.default(a,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"},signal:n})).then(function(e){return s=e,function(){if(!s.ok)return Promise.resolve(s.text()).then(function(e){throw new Error(""+e)})}()})},function(e){throw O.error("initializePSVerification failed: "),O.error(e),new Error("initializePSVerification failed: "+e.message+".")});return o&&o.then?o.then(i):i()})})}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,a,o,u){try{var d=this;return Promise.resolve(d.getEndpoints(e)).then(function(c){return Promise.resolve(d.getServiceEndpoints(e,c)).then(function(l){var p=d.getEndpointURL(l,"logs")?d.getEndpointURL(l,"logs").urlPath:null;return p?Promise.resolve(t.getAddress()).then(function(h){return Promise.resolve(d.getNonce(e,h,u,c,l)).then(function(e){var c=(e+1).toString();return Promise.resolve(d.getSignature(t,c,T.GET_LOGS)).then(function(e){function t(e){var t;return null!=(t=d)&&t.ok?d.body:Promise.resolve(d.json()).then(function(e){throw O.error("Download node logs failed: ",d.status,d.statusText,e),new Error(JSON.stringify(e))})}var d,l=p+"?startTime="+n+"&endTime="+r;i&&(l+="&maxLogs="+i),s&&(l+="&moduleName="+s),a&&(l+="&level="+a),o&&(l+="&page="+o);var f=ku(function(){return Promise.resolve(g.default(l,{method:"POST",body:JSON.stringify({signature:e,nonce:c,address:h}),headers:{"Content-Type":"application/json"},signal:u})).then(function(e){d=e})},function(e){throw O.error("Download node logs failed:"),O.error(e),new Error("HTTP request failed calling Provider")});return f&&f.then?f.then(t):t()})})}):(O.error("Download node logs failed: Cannot get proper logs route (perhaps not implemented on provider?)"),null)})})}catch(e){return Promise.reject(e)}},t.noZeroX=function(e){return this.zeroXTransformer(e,!1)},t.zeroXTransformer=function(e,t){void 0===e&&(e="");var n=this.inputMatch(e,/^(?:0x)*([a-f0-9]+)$/i,"zeroXTransformer");return(t&&n.valid?"0x":"")+n.output},t.inputMatch=function(e,t,n){if("string"!=typeof e)throw O.debug("Not input string:"),O.debug(e),new Error("["+n+"] Expected string, input type: "+typeof e);var r=e.match(t);return r?{valid:!0,output:r[1]}:(O.warn("["+n+"] Input transformation failed."),{valid:!1,output:e})},t.resolveDdo=function(e,t,n){try{return Promise.resolve(g.default(e+"/api/aquarius/assets/ddo/"+t,{method:"GET",headers:{"Content-Type":"application/json"},signal:n})).then(function(e){return e.ok?e.json():null})}catch(e){return Promise.reject(e)}},t.validateDdo=function(e,t,n,r){try{var i=this;return Promise.resolve(n.getAddress()).then(function(s){return Promise.resolve(i.getData(e+"/api/services/nonce?userAddress="+s)).then(function(i){return Promise.resolve(i.json()).then(function(i){var a,o=(Number(null!=(a=i.nonce)?a:0)+1).toString();return Promise.resolve($e(n,s+o+T.VALIDATE_DDO)).then(function(n){return Promise.resolve(g.default(e+"/api/aquarius/assets/ddo/validate",{method:"POST",body:JSON.stringify({ddo:t,publisherAddress:s,nonce:o,signature:n}),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){return e.ok?Promise.resolve(e.json()).then(function(e){return{valid:!0,hash:e.hash,proof:{validatorAddress:e.publicKey,r:e.r[0],s:e.s[0],v:e.v}}}):null})})})})})}catch(e){return Promise.reject(e)}},t.getData=function(e,t){try{return Promise.resolve(g.default(e,{method:"GET",headers:{"Content-type":"application/json",Authorization:t}}))}catch(e){return Promise.reject(e)}},t.createPersistentStorageBucket=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(s){var a=i.resolvePersistentStorageRoute(e,s,["persistentStorageCreateBucket"],"/api/services/persistentStorage/buckets");return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(e){var t;return Promise.resolve(g.default(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k({},e,{accessLists:null!=(t=n.accessLists)?t:[]})),signal:r})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},t.getPersistentStorageBuckets=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getEndpoints(e)).then(function(a){return Promise.resolve(s.getServiceEndpoints(e,a)).then(function(a){var o=s.resolvePersistentStorageRoute(e,a,["persistentStorageGetBuckets"],"/api/services/persistentStorage/buckets");return Promise.resolve(s.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_GET_BUCKETS,i)).then(function(e){var t=new URLSearchParams({consumerAddress:e.consumerAddress,signature:e.signature,nonce:e.nonce,chainId:String(r),owner:n});return Promise.resolve(g.default(o+"?"+t.toString(),{method:"GET",signal:i})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},t.listPersistentStorageFiles=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(s){var a=i.resolvePersistentStorageRoute(e,s,["persistentStorageListFiles"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files");return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(e){var t=new URLSearchParams({consumerAddress:e.consumerAddress,signature:e.signature,nonce:e.nonce});return Promise.resolve(g.default(a+"?"+t.toString(),{method:"GET",signal:r})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},t.getPersistentStorageFileObject=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getEndpoints(e)).then(function(a){return Promise.resolve(s.getServiceEndpoints(e,a)).then(function(a){var o=s.resolvePersistentStorageRoute(e,a,["persistentStorageGetFileObject"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r)+"/object");return Promise.resolve(s.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(e){var t=new URLSearchParams({consumerAddress:e.consumerAddress,signature:e.signature,nonce:e.nonce});return Promise.resolve(g.default(o+"?"+t.toString(),{method:"GET",signal:i})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},t.uploadPersistentStorageFile=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getEndpoints(e)).then(function(o){return Promise.resolve(a.getServiceEndpoints(e,o)).then(function(o){var u=a.resolvePersistentStorageRoute(e,o,["persistentStorageUploadFile"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r));return Promise.resolve(a.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(e){function n(e){var n={"Content-Type":"application/octet-stream"},i=a.getAuthorization(t);return i&&(n.Authorization=i),Promise.resolve(g.default(u+"?"+o.toString(),{method:"POST",body:r,headers:k({},n),signal:s})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})}var r,o=new URLSearchParams({consumerAddress:e.consumerAddress,signature:e.signature,nonce:e.nonce}),d=function(){if("undefined"==typeof window)return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return l(require("stream"))})).then(function(e){var t=e.Readable,n=new TextEncoder,s=F(/*#__PURE__*/D().mark(function e(){var t,r,s,a,o,u,d;return D().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=!1,r=!1,e.prev=2,a=P(i);case 4:return e.next=6,A(a.next());case 6:if(!(t=!(o=e.sent).done)){e.next=25;break}if(!((u=o.value)instanceof Uint8Array)){e.next=12;break}return e.next=11,u;case 11:return e.abrupt("continue",22);case 12:if("string"!=typeof u){e.next=16;break}return e.next=15,n.encode(u);case 15:return e.abrupt("continue",22);case 16:if(!u||"object"!=typeof u||!ArrayBuffer.isView(u)){e.next=21;break}return d=u,e.next=20,new Uint8Array(d.buffer,d.byteOffset,d.byteLength);case 20:return e.abrupt("continue",22);case 21:throw new Error("Unsupported chunk type for HTTP persistent storage upload");case 22:t=!1,e.next=4;break;case 25:e.next=31;break;case 27:e.prev=27,e.t0=e.catch(2),r=!0,s=e.t0;case 31:if(e.prev=31,e.prev=32,!t||null==a.return){e.next=36;break}return e.next=36,A(a.return());case 36:if(e.prev=36,!r){e.next=39;break}throw s;case 39:return e.finish(36);case 40:return e.finish(31);case 41:case"end":return e.stop()}},e,null,[[2,27,31,41],[32,,36,40]])}))();r=t.from(s)});var e=globalThis.ReadableStream;if("function"!=typeof e)throw new Error("ReadableStream is not available in this environment");var t=new TextEncoder,n=i[Symbol.asyncIterator]();r=new e({pull:function(e){try{return Promise.resolve(n.next()).then(function(n){var r=n.value;if(n.done)e.close();else if(r instanceof Uint8Array)e.enqueue(r);else if("string"!=typeof r){if(!r||"object"!=typeof r||!ArrayBuffer.isView(r))throw new Error("Unsupported chunk type for HTTP persistent storage upload");e.enqueue(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}else e.enqueue(t.encode(r))})}catch(e){return Promise.reject(e)}},cancel:function(){try{var e=function(){if("function"==typeof n.return)return Promise.resolve(n.return()).then(function(){})}();return Promise.resolve(e&&e.then?e.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}})}();return d&&d.then?d.then(n):n()})})})}catch(e){return Promise.reject(e)}},t.deletePersistentStorageFile=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getEndpoints(e)).then(function(o){return Promise.resolve(a.getServiceEndpoints(e,o)).then(function(o){var u=a.resolvePersistentStorageRoute(e,o,["persistentStorageDeleteFile"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r));return Promise.resolve(a.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_DELETE_FILE,s)).then(function(e){var n=new URLSearchParams({consumerAddress:e.consumerAddress,signature:e.signature,nonce:e.nonce,chainId:String(i)});return Promise.resolve(g.default(u+"?"+n.toString(),{method:"DELETE",headers:k({"Content-Type":"application/json"},a.getAuthorization(t)?{Authorization:a.getAuthorization(t)}:{}),signal:s})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},e}();async function Du(e){if(null===e.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new We("Private network is enforced, but no protector was provided");return e}const Mu=1e3,Fu=60*Mu,Ru=60*Fu,_u=24*Ru,Lu=7*_u,Nu=365.25*_u,Ou=Nu/12;var Bu=function(e,t){if("string"==typeof e)return Uu(e);if("number"==typeof e)return function(e,t){if("number"!=typeof e||!Number.isFinite(e))throw Error("Value provided to ms.format() must be of type number.");return t?.long?qu(e):ju(e)}(e,t);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(e)}`)};function Uu(e){if("string"!=typeof e||0===e.length||e.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(e)}`);let t=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(e);if(!t?.groups)return NaN;let{value:n,unit:r="ms"}=t.groups,i=parseFloat(n),s=r.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return i*Nu;case"months":case"month":case"mo":return i*Ou;case"weeks":case"week":case"w":return i*Lu;case"days":case"day":case"d":return i*_u;case"hours":case"hour":case"hrs":case"hr":case"h":return i*Ru;case"minutes":case"minute":case"mins":case"min":case"m":return i*Fu;case"seconds":case"second":case"secs":case"sec":case"s":return i*Mu;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(e)}`)}}function ju(e){let t=Math.abs(e);return t>=Nu?`${Math.round(e/Nu)}y`:t>=Ou?`${Math.round(e/Ou)}mo`:t>=Lu?`${Math.round(e/Lu)}w`:t>=_u?`${Math.round(e/_u)}d`:t>=Ru?`${Math.round(e/Ru)}h`:t>=Fu?`${Math.round(e/Fu)}m`:t>=Mu?`${Math.round(e/Mu)}s`:`${e}ms`}function qu(e){let t=Math.abs(e);return t>=Nu?$u(e,t,Nu,"year"):t>=Ou?$u(e,t,Ou,"month"):t>=Lu?$u(e,t,Lu,"week"):t>=_u?$u(e,t,_u,"day"):t>=Ru?$u(e,t,Ru,"hour"):t>=Fu?$u(e,t,Fu,"minute"):t>=Mu?$u(e,t,Mu,"second"):`${e} ms`}function $u(e,t,n,r){let i=t>=1.5*n;return`${Math.round(e/n)} ${r}${i?"s":""}`}const zu=function(){try{return localStorage}catch(e){}}(),Vu=console.debug??console.log??(()=>{});var Gu=function(e){function t(e,r){let i,s,a,o=null;function u(...e){if(!u.enabled)return;const n=u,s=Number(new Date);n.diff=s-(i||s),n.prev=i,n.curr=s,i=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";a++;const s=t.formatters[i];return"function"==typeof s&&(r=s.call(n,e[a]),e.splice(a,1),a--),r}),t.formatArgs.call(n,e),null!=r?.onLog&&r.onLog(...e),(n.log||t.log).apply(n,e)}return u.namespace=e,u.useColors=t.useColors(),u.color=t.selectColor(e),u.extend=n,u.destroy=t.destroy,Object.defineProperty(u,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,a=t.enabled(e)),a),set:e=>{o=e}}),"function"==typeof t.init&&t.init(u),u}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=Bu,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(n=>{t[n]=e[n]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs:function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Bu(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let n=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(r=n))}),e.splice(r,0,t)},save:function(e){try{e?zu?.setItem("debug",e):zu?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=zu?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/))},setupFormatters:function(e){e.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:zu,log:Vu});function Ku(e,t=""){const n=Yu(e.message),r=Yu(e.stack);return null!=n&&null!=r?r.includes(n)?`${r.split("\n").join(`\n${t}`)}`:`${n}\n${t}${r.split("\n").join(`\n${t}`)}`:null!=r?`${r.split("\n").join(`\n${t}`)}`:null!=n?`${n}`:`${e.toString()}`}function Hu(e,t=""){if(function(e){return e instanceof AggregateError||"AggregateError"===e?.name&&Array.isArray(e.errors)}(e)){let n=Ku(e,t);return n+=e.errors.length>0?`\n${t=`${t} `}${e.errors.map(e=>`${Hu(e,`${t}`)}`).join(`\n${t}`)}`:`\n${t}[Error list was empty]`,n.trim()}return Ku(e,t)}function Wu(e){return{forComponent:t=>Qu(t,e)}}function Qu(e,t){let n=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`);return Gu.enabled(`${e}:trace`)&&null!=Gu.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(n=Gu(`${e}:trace`,t)),Object.assign(Gu(e,t),{error:Gu(`${e}:error`,t),trace:n,newScope:n=>Qu(`${e}:${n}`,t)})}function Yu(e){if(null!=e&&0!==(e=e.trim()).length)return e}function Ju(e,t){const n={[Symbol.iterator]:()=>n,next:()=>{const n=e.next(),r=n.value;return!0===n.done||null==r?{done:!0,value:void 0}:{done:!1,value:t(r)}}};return n}function Zu(e){return qo(xn(Vt.decode(`z${e}`)))}Gu.formatters.b=e=>null==e?"undefined":Vt.baseEncode(e),Gu.formatters.t=e=>null==e?"undefined":Ht.baseEncode(e),Gu.formatters.m=e=>null==e?"undefined":Jn.baseEncode(e),Gu.formatters.p=e=>null==e?"undefined":e.toString(),Gu.formatters.c=e=>null==e?"undefined":e.toString(),Gu.formatters.k=e=>null==e?"undefined":e.toString(),Gu.formatters.a=e=>null==e?"undefined":e.toString(),Gu.formatters.e=e=>null==e?"undefined":Hu(e);class Xu{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Ju(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Ju(this.map.values(),e=>e.key)}values(){return Ju(this.map.values(),e=>e.value)}get size(){return this.map.size}}class ed{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Ju(this.set.entries(),e=>{const t=Zu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{const n=Zu(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ju(this.set.values(),e=>Zu(e))}intersection(e){const t=new ed;for(const n of e)this.has(n)&&t.add(n);return t}difference(e){const t=new ed;for(const n of this)e.has(n)||t.add(n);return t}union(e){const t=new ed;for(const n of e)t.add(n);for(const e of this)t.add(e);return t}}const td={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},nd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},rd=new globalThis.TextEncoder,id={hash:e=>Number(function(e,{size:t=32,utf8Buffer:n}={}){if(!td[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(n)return function(e,t,n){if(0===n.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const r=td[t];let i=nd[t],s=e;for(;s.length>0;){const e=rd.encodeInto(s,n);s=s.slice(e.read);for(let s=0;s<e.written;s++)i^=BigInt(n[s]),i=BigInt.asUintN(t,i*r)}return i}(e,t,n);e=rd.encode(e)}return function(e,t){const n=td[t];let r=nd[t];for(let i=0;i<e.length;i++)r^=BigInt(e[i]),r=BigInt.asUintN(t,r*n);return r}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),fr(t,"base16")}(id.hash(e,t))};class sd{fp;h;seed;constructor(e,t,n,r=2){if(r>64)throw new TypeError("Invalid Fingerprint Size");const i=t.hashV(e,n),s=Nn(r);for(let e=0;e<s.length;e++)s[e]=i[e];0===s.length&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&Ln(this.fp,e.fp)}}function ad(e,t){return Math.floor(Math.random()*(t-e))+e}class od{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof sd))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof sd))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof sd))throw new TypeError("Invalid Fingerprint");const t=ad(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof sd))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex(t=>e.equals(t));return t>-1&&(this.contents[t]=null,!0)}}class ud{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??id,this.seed=e.seed??ad(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=fr(e));const t=new sd(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,r=(n^t.hash())%this.filterSize;if(null==this.buckets[n]&&(this.buckets[n]=new od(this.bucketSize)),null==this.buckets[r]&&(this.buckets[r]=new od(this.bucketSize)),this.buckets[n].add(t)||this.buckets[r].add(t))return this.count++,!0;const i=[n,r];let s=i[ad(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new od(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[s].swap(t);if(null!=e&&(s=(s^e.hash())%this.filterSize,null==this.buckets[s]&&(this.buckets[s]=new od(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=fr(e));const t=new sd(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,r=this.buckets[n]?.has(t)??!1;if(r)return r;const i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){"string"==typeof e&&(e=fr(e));const t=new sd(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,r=this.buckets[n]?.remove(t)??!1;if(r)return this.count--,r;const i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const dd={1:.5,2:.84,4:.95,8:.98};function cd(e,t=.001){const n=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/dd[n]),bucketSize:n,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*n)),64)}}class ld{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??id,this.seed=e.seed??ad(0,Math.pow(2,10)),this.filterSeries=[new ud({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=fr(e)),this.has(e))return!0;let t=this.filterSeries.find(e=>e.reliable);if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ud({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=fr(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=fr(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}}function pd(e,t=.001,n){return new ld({...cd(e,t),...n??{}})}function hd(e){const t=e.getComponents(),n={};let r=0;if("ip6zone"===t[r]?.name&&(n.zone=`${t[r].value}`,r++),"ip4"===t[r].name||"ip6"===t[r].name||"dns"===t[r].name||"dns4"===t[r].name||"dns6"===t[r].name?(n.type=t[r].name,n.host=t[r].value,r++):"dnsaddr"===t[r].name&&(n.type=t[r].name,n.host=`_dnsaddr.${t[r].value}`,r++),"tcp"!==t[r]?.name&&"udp"!==t[r]?.name||(n.protocol="tcp"===t[r].name?"tcp":"udp",n.port=parseInt(`${t[r].value}`),r++),"ipcidr"===t[r]?.name&&("ip4"===n.type?n.cidr=parseInt(`${t[r].value}`):"ip6"===n.type&&(n.cidr=`${t[r].value}`),r++),null==n.type||null==n.host)throw new We(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return"tls"===t[r]?.name&&"sni"===t[r+1]?.name&&(n.sni=t[r+1].value,r+=2),n}const fd=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function md(e,t){16===t.length&&4===e.length&&function(e){let t=0;for(const n of e)if(!(t<0)){if(t>11)break;if(255!==n)return!1;t++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t){let n=0;for(const r of e)if(!(n<0)){if(n>11)break;if(r!==t[n])return!1;n++}return!0}(e,fd)&&(e=e.slice(12));const n=e.length;if(n!=t.length)throw new Error("Failed to mask ip");const r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=e[i]&t[i];return r}function yd(e,t){if(32!==t&&128!==t)throw new Error("Invalid CIDR mask");if(e<0||e>t)throw new Error("Invalid CIDR mask");const n=t/8,r=new Uint8Array(n);for(let t=0;t<n;t++)e>=8?(r[t]=255,e-=8):(r[t]=255-(255>>e),e=0);return r}class bd{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,n]=e.split("/");if(!t||!n)throw new Error("Failed to parse given CIDR: "+e);let r=4,i=Wo(t);if(null==i&&(r=16,i=Qo(t),null==i))throw new Error("Failed to parse given CIDR: "+e);const s=parseInt(n,10);if(Number.isNaN(s)||String(s).length!==n.length||s<0||s>8*r)throw new Error("Failed to parse given CIDR: "+e);const a=yd(s,8*r);return{network:md(i,a),mask:a}}(e));else{const n=Yo(e);if(null==n)throw new Error("Failed to parse network");t=String(t);const r=parseInt(t,10);if(Number.isNaN(r)||String(r).length!==t.length||r<0||r>8*n.length){const e=Yo(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=yd(r,8*n.length);this.network=md(n,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Yo(t)),null==t)throw new Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let n=0;n<t.length;n++)if((e.network[n]&e.mask[n])!=(t[n]&e.mask[n]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[n,r]of e.entries()){if(255!==r){for(;128&r;)t++,r<<=1;if(128&r)return-1;for(let t=n+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?String(e):function(e){let t="0x";for(const n of e)t+=(n>>4).toString(16)+(15&n).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let n=0;n<e.length;n++)n%2==0&&t.push(e[n].toString(16).padStart(2,"0")+e[n+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}(this.network)+"/"+t}}function gd(e){try{const n=hd(e);switch(n.type){case"ip4":case"ip6":return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t=n.host)||/^::1$/.test(t);default:return!1}}catch{return!1}var t}function vd(e){try{return hd(e),!0}catch{return!1}}var wd="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Td(e){var t={exports:{}};return e(t,t.exports),t.exports}var Ed=Td(function(e,t){(function(){var e,n,r,i,s,a,o,u;u=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},o=function(e){var t,r,i,s,a;for(t=[],r=i=0;i<=3&&0!==e.length;r=++i){if(r>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}s=(a=n(e))[0],e=e.substring(a[1]),t.push(s)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},i=(r=function(e){return e.charCodeAt(0)})("0"),a=r("a"),s=r("A"),n=function(e){var t,n,o,u,d;for(u=0,t=10,n="9",o=0,e.length>1&&"0"===e[o]&&("x"===e[o+1]||"X"===e[o+1]?(o+=2,t=16):"0"<=e[o+1]&&e[o+1]<="9"&&(o++,t=8,n="7")),d=o;o<e.length;){if("0"<=e[o]&&e[o]<=n)u=u*t+(r(e[o])-i)>>>0;else{if(16!==t)break;if("a"<=e[o]&&e[o]<="f")u=u*t+(10+r(e[o])-a)>>>0;else{if(!("A"<=e[o]&&e[o]<="F"))break;u=u*t+(10+r(e[o])-s)>>>0}}if(u>4294967295)throw new Error("too large");o++}if(o===d)throw new Error("empty octet");return[u,o]},e=function(){function e(e,t){var n,r,i;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=o(t)}catch(e){throw new Error("Invalid mask: "+t)}for(n=r=32;r>=0;n=--r)if(this.maskLong===4294967295<<32-n>>>0){this.bitmask=n;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(o(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=u(this.netLong),this.mask=u(this.maskLong),this.hostmask=u(~this.maskLong),this.first=this.bitmask<=30?u(this.netLong+1):this.base,this.last=u(this.bitmask<=30?this.netLong+this.size-2:this.netLong+this.size-1),this.broadcast=this.bitmask<=30?u(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(o(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(u(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,n,r;for(r=o(this.first),n=o(this.last),t=0;r<=n;)e(u(r),r,t),t++,r++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=o,t.long2ip=u,t.Netmask=e}).call(wd)});const xd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map(e=>new Ed.Netmask(e));function Pd(e){for(const t of xd)if(t.contains(e))return!0;return!1}function Sd(e){return Jo(e)?Pd(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const n=t[t.length-1].padStart(4,"0"),r=t[t.length-2].padStart(4,"0");return Pd(`${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}.${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}`)}(e):/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)?function(e){const t=e.split(":");return Pd(t[t.length-1])}(e):Zo(e)?/^::$/.test(t=e)||/^::1$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t):void 0;var t}function Ad(e){try{const t=hd(e);switch(t.type){case"ip4":case"ip6":return Sd(t.host)??!1;default:return"localhost"===t.host}}catch{return!1}}function Cd(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class kd{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class Id{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new kd(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){null!=e?.value&&(this.size+=this.calculateSize(e.value)),this.head.push(e)||(this.head=this.head.next=new kd(2*this.head.buffer.length),this.head.push(e))}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class Dd extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Md(e={}){return function(e,t){let n,r,i,s=(t=t??{}).onEnd,a=new Id,o=Cd();const u=e=>null!=r?r(e):(a.push(e),n),d=e=>{if(i)return n;if(!0!==t?.objectMode&&null==e?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:e})},c=e=>i?n:(i=!0,null!=e?(e=>(a=new Id,null!=r?r({error:e}):(a.push({error:e}),n)))(e):u({done:!0}));if(n={[Symbol.asyncIterator](){return this},next:async()=>{try{return a.isEmpty()?i?{done:!0}:await new Promise((t,i)=>{r=s=>{r=null,a.push(s);try{t(e(a))}catch(e){i(e)}return n}}):e(a)}finally{a.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=Cd()})}},return:()=>(a=new Id,c(),{done:!0}),throw:e=>(c(e),{done:!0}),push:d,end:c,get readableLength(){return a.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),a.isEmpty())return;let n,r;null!=t&&(n=new Promise((e,n)=>{r=()=>{n(new Dd)},t.addEventListener("abort",r)}));try{await Promise.race([o.promise,n])}finally{null!=r&&null!=t&&t?.removeEventListener("abort",r)}}},null==s)return n;const l=n;return n={[Symbol.asyncIterator](){return this},next:()=>l.next(),throw:e=>(l.throw(e),null!=s&&(s(e),s=void 0),{done:!0}),return:()=>(l.return(),null!=s&&(s(),s=void 0),{done:!0}),push:d,end:e=>(l.end(e),null!=s&&(s(e),s=void 0),n),get readableLength(){return l.readableLength},onEmpty:e=>l.onEmpty(e)},n}(e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}},e)}class Fd extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Fd)}}const Rd=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function _d(e,t,n){"function"==typeof n&&(n={filter:n});const r=function(e,t,n){let r;const i=new Promise((i,s)=>{if(!((n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n}).count>=0)||n.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(n.count))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[t].flat(),o=[],{addListener:u,removeListener:d}=(e=>{const t=e.addEventListener||e.on||e.addListener,n=e.removeEventListener||e.off||e.removeListener;if(!t||!n)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:n.bind(e)}})(e),c=async(...e)=>{const t=n.multiArgs?e:e[0];if(n.filter)try{if(!await n.filter(t))return}catch(e){return r(),void s(e)}o.push(t),n.count===o.length&&(r(),i(o))},l=(...e)=>{r(),s(n.rejectionMultiArgs?e:e[0])};r=()=>{for(const e of a)d(e,c);for(const e of n.rejectionEvents)a.includes(e)||d(e,l)};for(const e of a)u(e,c);for(const e of n.rejectionEvents)a.includes(e)||u(e,l);n.signal&&n.signal.addEventListener("abort",()=>{l(n.signal.reason)},{once:!0}),n.resolveImmediately&&i(o)});if(i.cancel=r,"number"==typeof n.timeout){const e=function(e,t){const{milliseconds:n,fallback:r,message:i,customTimers:s={setTimeout:setTimeout,clearTimeout:clearTimeout},signal:a}=t;let o,u;const d=new Promise((t,d)=>{if("number"!=typeof n||1!==Math.sign(n))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(a?.aborted)return void d(Rd(a));if(a&&(u=()=>{d(Rd(a))},a.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Fd;o=s.setTimeout.call(void 0,()=>{if(r)try{t(r())}catch(e){d(e)}else"function"==typeof e.cancel&&e.cancel(),!1===i?t():i instanceof Error?d(i):(c.message=i??`Promise timed out after ${n} milliseconds`,d(c))},n)}).finally(()=>{d.clear(),u&&a&&a.removeEventListener("abort",u)});return d.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},d}(i,{milliseconds:n.timeout});return e.cancel=()=>{r(),e.clear()},e}return i}(e,t,n={...n,count:1,resolveImmediately:!1}),i=r.then(e=>e[0]);return i.cancel=r.cancel,i}function Ld(e,t){let n;const r=function(){clearTimeout(n),n=setTimeout(function(){n=void 0,e()},t)};return r.start=()=>{},r.stop=()=>{clearTimeout(n)},r}class Nd extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}class Od extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Bd extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class Ud extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"}class jd extends Error{static name="StreamClosedError";name="StreamClosedError"}function qd(e){return e.reason}async function $d(e,t,n){if(null==t)return e;const r=n?.translateError??qd;if(t.aborted)return e.catch(()=>{}),Promise.reject(r(t));let i;try{return await Promise.race([e,new Promise((e,n)=>{i=()=>{n(r(t))},t.addEventListener("abort",i)})])}finally{null!=i&&t.removeEventListener("abort",i)}}class zd{deferred;signal;constructor(e){this.signal=e,this.deferred=Cd(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ge)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Vd{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((e,t)=>e&&!0===t.signal?.aborted,!0)&&(this.controller.abort(new Ge),this.cleanup())}async join(e={}){const t=new zd(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await $d(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}}class Gd extends Ft{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ld(this.emitEmpty.bind(this),1),this.emitIdle=Ld(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Od;const n=new Vd(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:n,result:e}}),e)).catch(e=>{if("queued"===n.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===n){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:n,error:e}}),e})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ge)}),this.clear()}async onEmpty(e){0!==this.size&&await _d(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await _d(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await _d(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Md({objectMode:!0}),n=e=>{null!=e?this.abort():this.clear(),t.end(e)},r=e=>{null!=e.detail&&t.push(e.detail)},i=e=>{n(e.detail.error)},s=()=>{n()},a=()=>{n(new Ge("Queue aborted"))};this.addEventListener("completed",r),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}}const Kd=4*Math.pow(2,20);class Hd extends Ft{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Kd,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new $n,this.writeBuffer=new $n,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this),this.addEventListener("drain",()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()}),this.addEventListener("close",e=>{this.onDrainPromise?.reject(e.error??new jd)})}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return!0!==this.writableNeedsDrain?Promise.resolve():(null==this.onDrainPromise&&(this.onDrainPromise=Promise.withResolvers()),$d(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if("readable"!==this.readStatus&&"paused"!==this.readStatus)return;const e=Md(),t=t=>{e.push(t.data)};this.addEventListener("message",t);const n=t=>{e.end(t.error)};this.addEventListener("close",n);const r=()=>{e.end()};this.addEventListener("remoteCloseWrite",r);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",r)}}isReadable(){return"open"===this.status}send(e){if("closed"===this.writeStatus||"closing"===this.writeStatus)throw new et(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if("aborted"!==this.status&&"reset"!==this.status&&"closed"!==this.status){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(e){this.log("failed to send reset to remote - %e",e)}this.dispatchEvent(new wt(e))}}pause(){if("closed"===this.readStatus||"closing"===this.readStatus)throw new et("Cannot pause a stream that is closing/closed");"paused"!==this.readStatus&&(this.readStatus="paused",this.sendPause())}resume(){if("closed"===this.readStatus||"closing"===this.readStatus)throw new et("Cannot resume a stream that is closing/closed");"readable"!==this.readStatus&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if("closed"===this.readStatus||"closing"===this.readStatus)throw new et(`Cannot push data onto a stream that is ${this.readStatus}`);0!==e.byteLength&&(this.readBuffer.append(e),"paused"!==this.readStatus&&0!==this.listenerCount("message")?setTimeout(()=>{this.dispatchReadBuffer()},0):this.checkReadBufferLength())}unshift(e){if("closed"===this.readStatus||"closing"===this.readStatus)throw new et(`Cannot push data onto a stream that is ${this.readStatus}`);0!==e.byteLength&&(this.readBuffer.prepend(e),"paused"!==this.readStatus&&0!==this.listenerCount("message")?setTimeout(()=>{this.dispatchReadBuffer()},0):this.checkReadBufferLength())}onData(e){0!==e.byteLength&&("closing"!==this.readStatus&&"closed"!==this.readStatus?(this.readBuffer.append(e),this.dispatchReadBuffer()):this.log("ignoring data - read status %s",this.readStatus))}addEventListener(...e){super.addEventListener.apply(this,e),"message"===e[0]&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),0===this.readBuffer.byteLength&&(this.readStatus="closed");const e=new Xe;this.dispatchEvent(new Tt(e))}onTransportClosed(e){this.log("transport closed"),"readable"===this.readStatus&&0===this.readBuffer.byteLength&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),"closed"!==this.remoteReadStatus&&(this.remoteReadStatus="closed"),"closed"!==this.remoteWriteStatus&&(this.remoteWriteStatus="closed"),"closed"!==this.writeStatus&&(this.writeStatus="closed"),null!=e?this.abort(e):"open"!==this.status&&"closing"!==this.status||(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new vt))}onRemoteCloseWrite(){"closed"!==this.remoteWriteStatus&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),"closed"===this.writeStatus&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(0===this.writeBuffer.byteLength)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const t=this.writeBuffer.byteLength;let n=0;for(;this.writeBuffer.byteLength>0;){const t=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(0===t){e=!1;break}const r=this.writeBuffer.sublist(0,t),i=new $n(r);this.writeBuffer.consume(r.byteLength);const s=this.sendData(r);if(e=s.canSendMore,n+=s.sentBytes,s.sentBytes!==i.byteLength&&(i.consume(s.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),0===this.writeBuffer.byteLength&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(0===this.listenerCount("message"))return void this.log.trace("not dispatching pause buffer as there are no listeners for the message event");if(0===this.readBuffer.byteLength)return void this.log.trace("not dispatching pause buffer as there is no data to dispatch");if("paused"===this.readStatus)return void this.log.trace("not dispatching pause buffer we are paused");if("closing"===this.readStatus||"closed"===this.readStatus)return this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),void this.readBuffer.consume(this.readBuffer.byteLength);const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new gt(e))}finally{0===this.readBuffer.byteLength&&"closed"===this.remoteWriteStatus&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new tt(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){null!=this.maxWriteBufferLength&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new tt(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}}class Wd extends Hd{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",e=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),this.metrics?.increment(null!=e.error?e.local?{[`${this.metricPrefix}abort`]:!0}:{[`${this.metricPrefix}reset`]:!0}:e.local?{[`${this.metricPrefix}_local_close`]:!0}:{[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){"open"===this.status&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await _d(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await _d(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}}class Qd extends Ft{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics,this.maConn.addEventListener("message",e=>{try{this.onData(e.data)}catch(e){this.abort(e),this.maConn.abort(e)}}),this.maConn.addEventListener("drain",()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(e=>{e.onMuxerDrain()})}),this.maConn.addEventListener("close",()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()})}send(e){const t=this.maConn.send(e);return!1===t&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(e=>{e.onMuxerNeedsDrain()})),t}async close(e){"closed"!==this.status&&"closing"!==this.status&&(this.status="closing",await $d(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){"closed"!==this.status&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(e){this.abort(e)}this.status="closed"}async createStream(e){if("open"!==this.status)throw new Ze;let t=this.onCreateStream({...this.streamOptions,...e});var n;return null!=(n=t)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),0===this.listenerCount("stream"))return this.earlyStreams.push(e),void(this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Ud(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`)));this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){e.addEventListener("close",t=>{const n=this.streams.findIndex(t=>t===e);-1!==n&&this.streams.splice(n,1),this.metrics?.increment(null!=t.error?t.local?{[`${e.direction}_stream_reset`]:!0}:{[`${e.direction}_stream_abort`]:!0}:{[`${e.direction}_stream_end`]:!0})}),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),"stream"===e[0]&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(e=>{this.safeDispatchEvent("stream",{detail:e})}),this.earlyStreams=[]})}}class Yd extends Hd{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await _d(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await _d(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),"closed"===this.remoteWriteStatus&&this.onTransportClosed())}async closeRead(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}}function Jd(e){const t=new globalThis.AbortController;function n(){const r=e.filter(e=>!0===e?.aborted).map(e=>e?.reason).pop();t.abort(r);for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",n)}for(const t of e){if(!0===t?.aborted){n();break}null!=t?.addEventListener&&t.addEventListener("abort",n)}const r=t.signal;return r.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",n)},r}class Zd{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(null!=this.previousTime){const n=this.alpha(t,this.previousTime),r=e-this.movingAverage,i=n*r;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+r*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*r}else this.movingAverage=e;this.previousTime=t}}class Xd{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new Zd(t),this.failure=new Zd(t),this.next=new Zd(t),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??5e3,this.maxTimeout=e.maxTimeout??6e4,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);const n=AbortSignal.timeout(t),r=Jd([e.signal,n]);return r.start=Date.now(),r.timeout=t,r}cleanUp(e){e.clear();const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class ec{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Cd(),this.haveNext=Cd()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Cd(),e}async throw(e){return this.ended=!0,this.error=e,null!=e&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Cd(),await $d(this.readNext.promise,t?.signal,t)}}function tc(...e){const t=[];for(const n of e)null==n[Symbol.asyncIterator]&&t.push(n);return t.length===e.length?function*(e){for(const t of e)yield*t}(t):async function*(e){const t=new AbortController,n=new ec;(async function(e,t,n){try{await Promise.all(e.map(async e=>{for await(const r of e)await t.push(r,{signal:n}),n.throwIfAborted()})),await t.end(void 0,{signal:n})}catch(e){await t.end(e,{signal:n}).catch(()=>{})}})(e,n,t.signal).catch(()=>{});try{yield*n}finally{t.abort()}}(e)}function nc(e,...t){if(null==e)throw new Error("Empty pipeline");if(ac(e)){const t=e;e=()=>t.source}else if(sc(e)||ic(e)){const t=e;e=()=>t}const n=[e,...t];if(n.length>1&&ac(n[n.length-1])&&(n[n.length-1]=n[n.length-1].sink),n.length>2)for(let e=1;e<n.length-1;e++)ac(n[e])&&(n[e]=oc(n[e]));return rc(...n)}const rc=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},ic=e=>null!=e?.[Symbol.asyncIterator],sc=e=>null!=e?.[Symbol.iterator],ac=e=>null!=e&&null!=e.sink&&null!=e.source,oc=e=>t=>{const n=e.sink(t);if(null!=n?.then){const t=Md({objectMode:!0});let r;n.then(()=>{t.end()},e=>{t.end(e)});const i=e.source;if(ic(i))r=async function*(){yield*i,t.end()};else{if(!sc(i))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");r=function*(){yield*i,t.end()}}return tc(t,r())}return e.source};class uc extends Error{static name="UnwrappedError";name="UnwrappedError"}class dc extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class cc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class lc extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function pc(e){return function(e){return"function"==typeof e?.closeRead}(e)?"writable"!==e.remoteWriteStatus&&0===e.readBufferLength:!!function(e){return"function"==typeof e?.close}(e)&&"open"!==e.status}function hc(e,t){const n=t?.maxBufferSize??4194304,r=new $n;let i,s=!1;if(a=e,null==a?.addEventListener||null==a?.removeEventListener||null==a?.send||null==a?.push||null==a?.log)throw new We("Argument should be a Stream or a Multiaddr");var a;const o=e=>{if(r.append(e.data),r.byteLength>n){const e=r.byteLength;r.consume(r.byteLength),i?.reject(new Error(`Read buffer overflow - ${e} > ${n}`))}i?.resolve()};e.addEventListener("message",o);const u=e=>{null!=e.error?i?.reject(e.error):i?.resolve()};e.addEventListener("close",u);const d=()=>{i?.resolve()};e.addEventListener("remoteCloseWrite",d);const c={readBuffer:r,async read(t){if(!0===s)throw new uc("Stream was unwrapped");if(pc(e)){if(0===r.byteLength&&null==t?.bytes)return null;if(null!=t?.bytes&&r.byteLength<t.bytes)throw e.log.error("closed after reading %d/%d bytes",r.byteLength,t.bytes),new Bd(`Unexpected EOF - stream closed after reading ${r.byteLength}/${t.bytes} bytes`)}const n=t?.bytes??1;for(i=Promise.withResolvers();;){if(r.byteLength>=n){i.resolve();break}if(await $d(i.promise,t?.signal),pc(e)){if(0===r.byteLength&&null==t?.bytes)return null;break}i=Promise.withResolvers()}const a=t?.bytes??r.byteLength;if(r.byteLength<a){if(pc(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,a),new Bd(`Unexpected EOF - stream closed while reading ${r.byteLength}/${a} bytes`);return c.read(t)}const o=r.sublist(0,a);return r.consume(a),o},async write(t,n){if(!0===s)throw new uc("Stream was unwrapped");e.send(t)||await _d(e,"drain",{signal:n?.signal,rejectionEvents:["close"]})},unwrap:()=>(s||(s=!0,e.removeEventListener("message",o),e.removeEventListener("close",u),e.removeEventListener("remoteCloseWrite",d),r.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",r.byteLength),e.push(r))),e)};return c}function fc(e,t={}){const n=hc(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=ma(t.maxDataLength));const r=t?.lengthDecoder??va,i=t?.lengthEncoder??ga;return{async read(i){let s=-1;const a=new $n;for(;;){const e=await n.read({...i,bytes:1});if(null==e)break;a.append(e);try{s=r(a)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new dc("Invalid message length");if(null!=t?.maxLengthLength&&a.byteLength>t.maxLengthLength)throw new lc(`Message length length too long - ${a.byteLength} > ${t.maxLengthLength}`);if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new cc(`Message length too long - ${s} > ${t.maxDataLength}`);const o=await n.read({...i,bytes:s});if(null==o)throw e.log.error("tried to read %d bytes but the stream closed",s),new Bd(`Unexpected EOF - tried to read ${s} bytes but the stream closed`);if(o.byteLength!==s)throw e.log.error("read %d/%d bytes before the stream closed",o.byteLength,s),new Bd(`Unexpected EOF - read ${o.byteLength}/${s} bytes before the stream closed`);return o},async write(e,t){await n.write(new $n(i(e.byteLength),e),t)},async writeV(e,t){const r=new $n(...e.flatMap(e=>[i(e.byteLength),e]));await n.write(r,t)},unwrap:()=>n.unwrap()}}function mc(e,t){const n=fc(e,t),r={read:async(e,t)=>{const r=await n.read(t);return e.decode(r)},write:async(e,t,r)=>{await n.write(t.encode(e),r)},writeV:async(e,t,r)=>{await n.writeV(e.map(e=>t.encode(e)),r)},pb:e=>({read:async t=>r.read(e,t),write:async(t,n)=>r.write(t,e,n),writeV:async(t,n)=>r.writeV(t,e,n),unwrap:()=>r}),unwrap:()=>n.unwrap()};return r}class yc{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new $n,this.maxBufferSize=e.maxBufferSize??4194304,this.maxDataLength=e.maxDataLength??4194304,this.lengthDecoder=e.lengthDecoder??va,this.encodingLength=e.encodingLength??ma}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new We(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let e;try{e=this.lengthDecoder(this.buffer)}catch(e){if(e instanceof RangeError)break;throw e}if(e<0||e>this.maxDataLength)throw new dc("Invalid message length");const t=this.encodingLength(e),n=t+e;if(!(this.buffer.byteLength>=n))break;{const e=this.buffer.sublist(t,n);this.buffer.consume(n),e.byteLength>0&&(yield e)}}}}const bc=4194304;class gc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}function vc(e,t){if(e.byteLength>t)throw new gc("Message length too long")}const wc=e=>{const t=ma(e),n=On(t);return ga(e,n),wc.bytes=t,n};function Tc(e,t){const n=(t=t??{}).lengthEncoder??wc,r=t?.maxDataLength??bc;function*i(e){vc(e,r);const t=n(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return null!=e[Symbol.asyncIterator]?async function*(){for await(const t of e)yield*i(t)}():function*(){for(const t of e)yield*i(t)}()}var Ec;wc.bytes=0,Tc.single=(e,t)=>{const n=(t=t??{}).lengthEncoder??wc;return vc(e,t?.maxDataLength??bc),new $n(n(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Ec||(Ec={}));class xc extends Gd{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}class Pc extends Gd{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}class Sc{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Ac}consume(e,t=1,n={}){const r=this.getKey(e),i=this._getKeySecDuration(n);let s=this.memoryStorage.incrby(r,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(r,s.consumedPoints,this.blockDuration)),new Nd("Rate limit exceeded",s);return s}penalty(e,t=1,n={}){const r=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(r,t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,n={}){const r=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(r,-t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){const n=1e3*t,r=this.points+1;return this.memoryStorage.set(this.getKey(e),r,t),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:r,isFirstInDuration:!1}}set(e,t,n=0){const r=1e3*(n>=0?n:this.duration);return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class Ac{storage;constructor(){this.storage=new Map}incrby(e,t,n){const r=this.storage.get(e);if(null!=r){const i=null!=r.expiresAt?r.expiresAt.getTime()-(new Date).getTime():-1;return null==r.expiresAt||i>0?(r.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:r.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){const r=1e3*n,i=this.storage.get(e);null!=i&&clearTimeout(i.timeoutId);const s={value:t,expiresAt:r>0?new Date(Date.now()+r):void 0};return this.storage.set(e,s),r>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},r),null!=s.timeoutId.unref&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:s.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}function Cc(e,t,n){let r,i,s=!1;function a(){const o={signal:i.signal};let u;null!=n?.timeout&&(u=Jd([i.signal,AbortSignal.timeout(n.timeout)]),o.signal=u),s=!0,Promise.resolve().then(async()=>{await e(o)}).catch(()=>{}).finally(()=>{null!=u&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),s=!1,i.signal.aborted||(r=setTimeout(a,t))})}const o=Ld(a,n?.debounce??100);let u=!1;return{setInterval:e=>{t!==e&&(t=e,null!=r&&(clearTimeout(r),r=setTimeout(a,t)))},setTimeout:e=>{n??={},n.timeout=e},run:()=>{s||(clearTimeout(r),o())},start:()=>{u||(u=!0,i=new AbortController,!0===n?.runImmediately?queueMicrotask(()=>{a()}):r=setTimeout(a,t))},stop:()=>{clearTimeout(r),i?.abort(),u=!1}}}class kc extends Map{metric;constructor(e){super();const{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function Ic(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new kc({name:t,metrics:n}):new Map,r}class Dc{filter;constructor(e,t){this.filter=pd(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}}function Mc(e,t=.001){return new Dc(e,t)}class Fc extends Xu{metric;constructor(e){super();const{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function Rc(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Fc({name:t,metrics:n}):new Xu,r}const _c=new Float32Array([-0]),Lc=new Uint8Array(_c.buffer);function Nc(e,t,n){_c[0]=e,t[n]=Lc[0],t[n+1]=Lc[1],t[n+2]=Lc[2],t[n+3]=Lc[3]}const Oc=new Float64Array([-0]),Bc=new Uint8Array(Oc.buffer);function Uc(e,t,n){Oc[0]=e,t[n]=Bc[0],t[n+1]=Bc[1],t[n+2]=Bc[2],t[n+3]=Bc[3],t[n+4]=Bc[4],t[n+5]=Bc[5],t[n+6]=Bc[6],t[n+7]=Bc[7]}const jc=BigInt(Number.MAX_SAFE_INTEGER),qc=BigInt(Number.MIN_SAFE_INTEGER);class $c{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(0n===e)return zc;if(e<jc&&e>qc)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let n=e>>32n,r=e-(n<<32n);return t&&(n=0n|~n,r=0n|~r,++r>Vc&&(r=0n,++n>Vc&&(n=0n))),new $c(Number(r),Number(n))}static fromNumber(e){if(0===e)return zc;const t=e<0;t&&(e=-e);let n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new $c(n,r)}static from(e){return"number"==typeof e?$c.fromNumber(e):"bigint"==typeof e?$c.fromBigInt(e):"string"==typeof e?$c.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new $c(e.low>>>0,e.high>>>0):zc}}const zc=new $c(0,0);zc.toBigInt=function(){return 0n},zc.zzEncode=zc.zzDecode=function(){return this},zc.length=function(){return 1};const Vc=4294967296n;function Gc(e,t,n){const r=n;let i,s;for(let r=0;r<e.length;++r)i=e.charCodeAt(r),i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-r}function Kc(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Hc(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Wc{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Kc(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Kc(this,4);return Hc(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Kc(this,4);return 0|Hc(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Kc(this,4);const e=(Lc[0]=(t=this.buf)[n=this.pos],Lc[1]=t[n+1],Lc[2]=t[n+2],Lc[3]=t[n+3],_c[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Kc(this,4);const e=(Bc[0]=(t=this.buf)[n=this.pos],Bc[1]=t[n+1],Bc[2]=t[n+2],Bc[3]=t[n+3],Bc[4]=t[n+4],Bc[5]=t[n+5],Bc[6]=t[n+6],Bc[7]=t[n+7],Oc[0]);var t,n;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Kc(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){const e=this.bytes();return function(e,t,n){if(n-t<1)return"";let r;const i=[];let s,a=0;for(;t<n;)s=e[t++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=r?(a>0&&r.push(String.fromCharCode.apply(String,i.slice(0,a))),r.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Kc(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Kc(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new $c(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Kc(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Kc(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Kc(this,8);const e=Hc(this.buf,this.pos+=4),t=Hc(this.buf,this.pos+=4);return new $c(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=ba(this.buf,this.pos);return this.pos+=ma(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Qc(e){return new Wc(e instanceof Uint8Array?e:e.subarray())}function Yc(e,t,n){const r=Qc(e);return t.decode(r,void 0,n)}class Jc{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Zc(){}class Xc{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const el=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return On(r);n+r>e&&(t=On(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class tl{len;head;tail;states;constructor(){this.len=0,this.head=new Jc(Zc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Jc(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new il((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(sl,10,$c.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=$c.fromBigInt(e);return this._push(sl,t.length(),t)}uint64Number(e){return this._push(ya,ma(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=$c.fromBigInt(e).zzEncode();return this._push(sl,t.length(),t)}sint64Number(e){const t=$c.fromNumber(e).zzEncode();return this._push(sl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(nl,1,e?1:0)}fixed32(e){return this._push(al,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=$c.fromBigInt(e);return this._push(al,4,t.lo)._push(al,4,t.hi)}fixed64Number(e){const t=$c.fromNumber(e);return this._push(al,4,t.lo)._push(al,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Nc,4,e)}double(e){return this._push(Uc,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(nl,1,0):this.uint32(t)._push(ol,t,e)}string(e){const t=function(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(Gc,t,e):this._push(nl,1,0)}fork(){return this.states=new Xc(this),this.head=this.tail=new Jc(Zc,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Jc(Zc,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next;const t=(n=this.len,null!=globalThis.Buffer?On(n):el(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function nl(e,t,n){t[n]=255&e}function rl(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class il extends Jc{next;constructor(e,t){super(rl,e,t),this.next=void 0}}function sl(e,t,n){for(;0!==e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function al(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function ol(e,t,n){t.set(e,n)}function ul(e,t,n){t.set(e,n)}function dl(e,t,n){e.length<40?Gc(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(fr(e),n)}function cl(e,t){const n=new tl;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*ll(e,t,n){const r=Qc(e);yield*t.stream(r,void 0,"$",n)}function pl(e,t,n){return function(e,t,n,r,i){return{name:"message",type:2,encode:n,decode:r,stream:i}}(0,0,e,t,n)}null!=globalThis.Buffer&&(tl.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(ul,t,e),this},tl.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(dl,t,e),this});class hl extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var fl;!function(e){let t;e.codec=()=>(null==t&&(t=pl((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={publicKey:Nn(0),payloadType:Nn(0),payload:Nn(0),signature:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.publicKey`,value:e.bytes()};break;case 2:yield{field:`${n}.payloadType`,value:e.bytes()};break;case 3:yield{field:`${n}.payload`,value:e.bytes()};break;case 5:yield{field:`${n}.signature`,value:e.bytes()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return cl(t,e.codec())},e.decode=function(t,n){return Yc(t,e.codec(),n)},e.stream=function(t,n){return ll(t,e.codec(),n)}}(fl||(fl={}));class ml extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class yl{static createFromProtobuf=e=>{const t=fl.decode(e),n=Mo(t.publicKey);return new yl({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(null==t)throw new Error("Missing private key");const r=e.domain,i=e.codec,s=e.marshal(),a=bl(r,i,s),o=await t.sign(a.subarray(),n);return new yl({publicKey:t.publicKey,payloadType:i,payload:s,signature:o})};static openAndCertify=async(e,t,n)=>{const r=yl.createFromProtobuf(e);if(!await r.validate(t,n))throw new ml("Envelope signature is not valid for the given domain");return r};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:n,payload:r,signature:i}=e;this.publicKey=t,this.payloadType=n,this.payload=r,this.signature=i}marshal(){return null==this.marshaled&&(this.marshaled=fl.encode({publicKey:Fo(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Ln(this.marshal(),e.marshal())}async validate(e,t){const n=bl(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}}const bl=(e,t,n)=>{const r=fr(e),i=ga(r.byteLength),s=ga(t.length),a=ga(n.length);return new $n(i,r,s,t,a,n)},gl=Uint8Array.from([3,1]);var vl;!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=pl((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={multiaddr:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();t>>>3==1?yield{field:`${n}.multiaddr`,value:e.bytes()}:e.skipType(7&t)}})),t),e.encode=function(t){return cl(t,e.codec())},e.decode=function(t,n){return Yc(t,e.codec(),n)},e.stream=function(t,n){return ll(t,e.codec(),n)}}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=pl((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(n.uint32(10),n.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(n.uint32(16),n.uint64(t.seq)),null!=t.addresses&&t.addresses.length>0)for(const r of t.addresses)n.uint32(26),e.AddressInfo.codec().encode(r,n);!1!==r.lengthDelimited&&n.ldelim()},(t,n,r={})=>{const i={peerId:Nn(0),seq:0n,addresses:[]},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:i.peerId=t.bytes();break;case 2:i.seq=t.uint64();break;case 3:if(null!=r.limits?.addresses&&i.addresses.length===r.limits.addresses)throw new hl('Decode error - repeated field "addresses" had too many elements');i.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:r.limits?.addresses$}));break;default:t.skipType(7&n)}}return i},function*(t,n,r,i={}){const s={addresses:0},a=null==n?t.len:t.pos+n;for(;t.pos<a;){const n=t.uint32();switch(n>>>3){case 1:yield{field:`${r}.peerId`,value:t.bytes()};break;case 2:yield{field:`${r}.seq`,value:t.uint64()};break;case 3:if(null!=i.limits?.addresses&&s.addresses===i.limits.addresses)throw new hl('Streaming decode error - repeated field "addresses" had too many elements');for(const n of e.AddressInfo.codec().stream(t,t.uint32(),`${r}.addresses[]`,{limits:i.limits?.addresses$}))yield{...n,index:s.addresses};s.addresses++;break;default:t.skipType(7&n)}}})),t),e.encode=function(t){return cl(t,e.codec())},e.decode=function(t,n){return Yc(t,e.codec(),n)},e.stream=function(t,n){return ll(t,e.codec(),n)}}(vl||(vl={}));class wl{static createFromProtobuf=e=>{const t=vl.decode(e),n=qo(xn(t.peerId)),r=(t.addresses??[]).map(e=>Pu(e.multiaddr));return new wl({peerId:n,multiaddrs:r,seqNumber:t.seq})};static DOMAIN="libp2p-peer-record";static CODEC=gl;peerId;multiaddrs;seqNumber;domain=wl.DOMAIN;codec=wl.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:n,seqNumber:r}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=r??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=vl.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return e instanceof wl&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const n=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(n),e.sort(n).every((e,n)=>t[n].equals(e)))}(this.multiaddrs,e.multiaddrs)}}function Tl(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const n of e)t.push(n);return t})();const t=[];for(const n of e)t.push(n);return t}class El extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}}async function xl(e,t,n,r){const i=new El(r?.errorMessage);null!=r?.errorCode&&(i.code=r.errorCode);const s=r?.errorEvent??"error";return!0===n?.aborted?Promise.reject(i):new Promise((a,o)=>{function u(){Sl(n,"abort",l),Sl(e,t,d),Sl(e,s,c)}const d=e=>{try{if(!1===r?.filter?.(e))return}catch(e){return u(),void o(e)}u(),a(e)},c=e=>{u(),e instanceof Error?o(e):o(e.detail??r?.error??new Error(`The "${r?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},l=()=>{u(),o(i)};Pl(n,"abort",l),Pl(e,t,d),Pl(e,s,c)})}function Pl(e,t,n){null!=e&&(Al(e)?e.addEventListener(t,n):e.addListener(t,n))}function Sl(e,t,n){null!=e&&(Al(e)?e.removeEventListener(t,n):e.removeListener(t,n))}function Al(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class Cl extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class kl{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new El)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Il{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((e,t)=>e&&!0===t.signal?.aborted,!0)&&(this.controller.abort(new El),this.cleanup())}async join(e={}){const t=new kl(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await $d(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}}function Dl(e,t){let n;const r=function(){clearTimeout(n),n=setTimeout(function(){n=void 0,e()},t)};return r.start=()=>{},r.stop=()=>{clearTimeout(n)},r}class Ml extends Ft{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Dl(this.emitEmpty.bind(this),1),this.emitIdle=Dl(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Cl;const n=new Il(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(e=>(this.safeDispatchEvent("success",{detail:{job:n,result:e}}),e)).catch(e=>{if("queued"===n.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===n){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:n,error:e}}),e})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new El)}),this.clear()}async onEmpty(e){0!==this.size&&await xl(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await xl(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await xl(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Md({objectMode:!0}),n=e=>{null!=e?this.abort():this.clear(),t.end(e)},r=e=>{null!=e.detail&&t.push(e.detail.result)},i=e=>{n(e.detail.error)},s=()=>{n()},a=()=>{n(new El("Queue aborted"))};this.addEventListener("success",r),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}}const Fl="lock:worker:request-read",Rl="lock:worker:abort-read-request",_l="lock:worker:release-read",Ll="lock:master:grant-read",Nl="lock:master:error-read",Ol="lock:worker:request-write",Bl="lock:worker:abort-write-request",Ul="lock:worker:release-write",jl="lock:master:grant-write",ql="lock:master:error-write",$l="lock:worker:finalize",zl="mortice",Vl={singleProcess:!1},Gl=(e,t,n,r,i,s,a,o,u)=>d=>{if(null==d.data)return;const c={type:d.data.type,name:d.data.name,identifier:d.data.identifier};c.type===i&&e.safeDispatchEvent(n,{detail:{name:c.name,identifier:c.identifier,handler:async()=>{t.postMessage({type:u,name:c.name,identifier:c.identifier}),await new Promise(e=>{const n=r=>{null!=r?.data&&r.data.type===o&&r.data.identifier===c.identifier&&(t.removeEventListener("message",n),e())};t.addEventListener("message",n)})},onError:e=>{t.postMessage({type:a,name:c.name,identifier:c.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),c.type===s&&e.safeDispatchEvent(r,{detail:{name:c.name,identifier:c.identifier}}),c.type===$l&&e.safeDispatchEvent("finalizeRequest",{detail:{name:c.name}})};class Kl{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(zl)}readLock(e){return this.sendRequest(Fl,Rl,Ll,Nl,_l,e)}writeLock(e){return this.sendRequest(Ol,Bl,jl,ql,Ul,e)}finalize(){this.channel.postMessage({type:$l,name:this.name}),this.channel.close()}async sendRequest(e,t,n,r,i,s){s?.signal?.throwIfAborted();const a=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((e,o)=>{const u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",u,{once:!0});const d=t=>{if(t.data?.identifier===a&&(t.data?.type===n&&(this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u),e(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),t.data.type===r)){this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u);const e=new Error;null!=t.data.error&&(e.message=t.data.error.message,e.name=t.data.error.name,e.stack=t.data.error.stack),o(e)}};this.channel.addEventListener("message",d)})}}const Hl=new Map;let Wl;function Ql(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}function Yl(e){if(null==Wl&&(Wl=(e=>{if(e=Object.assign({},Vl,e),Boolean(globalThis.document)||e.singleProcess){const e=new BroadcastChannel(zl),t=new Ft;return e.addEventListener("message",Gl(t,e,"requestReadLock","abortReadLockRequest",Fl,Rl,Nl,_l,Ll)),e.addEventListener("message",Gl(t,e,"requestWriteLock","abortWriteLockRequest",Ol,Bl,ql,Ul,jl)),t}return new Kl(e.name)})(e),!Ql(Wl))){const e=Wl;e.addEventListener("requestReadLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=Hl.get(n);if(null==i)return;const s=new AbortController,a=e=>{e.detail.name===n&&e.detail.identifier===r&&s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=Hl.get(n);if(null==i)return;const s=new AbortController,a=e=>{e.detail.name===n&&e.detail.identifier===r&&s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",e=>{const t=Hl.get(e.detail.name);null!=t&&t.finalize()})}return Wl}async function Jl(e,t){let n,r;const i=new Promise((e,t)=>{n=e,r=t}),s=()=>{r(new El)};return t?.signal?.addEventListener("abort",s,{once:!0}),e.add(async()=>{await new Promise(e=>{n(()=>{t?.signal?.removeEventListener("abort",s),e()})})},{signal:t?.signal}).catch(e=>{r(e)}),i}const Zl={name:"lock",concurrency:Infinity,singleProcess:!1,autoFinalize:!1};function Xl(e){const t=Object.assign({},Zl,e);return((e,t)=>{let n=Hl.get(e);if(null!=n)return n;const r=Yl(t);if(Ql(r))return n=r,Hl.set(e,n),n;const i=new Ml({concurrency:1});let s;return n={async readLock(e){if(null!=s)return Jl(s,e);s=new Ml({concurrency:t.concurrency,autoStart:!1});const n=s,r=Jl(s,e);return i.add(async()=>{n.start(),await n.onIdle().then(()=>{s===n&&(s=null)})}),r},writeLock:async e=>(s=null,Jl(i,e)),finalize:()=>{Hl.delete(e)},queue:i},Hl.set(e,n),!0===t.autoFinalize&&i.addEventListener("idle",()=>{n.finalize()},{once:!0}),n})(t.name,t)}const ep=new Float32Array([-0]),tp=new Uint8Array(ep.buffer);function np(e,t,n){ep[0]=e,t[n]=tp[0],t[n+1]=tp[1],t[n+2]=tp[2],t[n+3]=tp[3]}const rp=new Float64Array([-0]),ip=new Uint8Array(rp.buffer);function sp(e,t,n){rp[0]=e,t[n]=ip[0],t[n+1]=ip[1],t[n+2]=ip[2],t[n+3]=ip[3],t[n+4]=ip[4],t[n+5]=ip[5],t[n+6]=ip[6],t[n+7]=ip[7]}const ap=BigInt(Number.MAX_SAFE_INTEGER),op=BigInt(Number.MIN_SAFE_INTEGER);class up{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(0n===e)return dp;if(e<ap&&e>op)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let n=e>>32n,r=e-(n<<32n);return t&&(n=0n|~n,r=0n|~r,++r>cp&&(r=0n,++n>cp&&(n=0n))),new up(Number(r),Number(n))}static fromNumber(e){if(0===e)return dp;const t=e<0;t&&(e=-e);let n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new up(n,r)}static from(e){return"number"==typeof e?up.fromNumber(e):"bigint"==typeof e?up.fromBigInt(e):"string"==typeof e?up.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new up(e.low>>>0,e.high>>>0):dp}}const dp=new up(0,0);dp.toBigInt=function(){return 0n},dp.zzEncode=dp.zzDecode=function(){return this},dp.length=function(){return 1};const cp=4294967296n;function lp(e,t,n){const r=n;let i,s;for(let r=0;r<e.length;++r)i=e.charCodeAt(r),i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-r}function pp(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function hp(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class fp{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,pp(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw pp(this,4);return hp(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw pp(this,4);return 0|hp(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw pp(this,4);const e=(tp[0]=(t=this.buf)[n=this.pos],tp[1]=t[n+1],tp[2]=t[n+2],tp[3]=t[n+3],ep[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw pp(this,4);const e=(ip[0]=(t=this.buf)[n=this.pos],ip[1]=t[n+1],ip[2]=t[n+2],ip[3]=t[n+3],ip[4]=t[n+4],ip[5]=t[n+5],ip[6]=t[n+6],ip[7]=t[n+7],rp[0]);var t,n;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw pp(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){const e=this.bytes();return function(e,t,n){if(n-t<1)return"";let r;const i=[];let s,a=0;for(;t<n;)s=e[t++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=r?(a>0&&r.push(String.fromCharCode.apply(String,i.slice(0,a))),r.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw pp(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw pp(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new up(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw pp(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw pp(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw pp(this,8);const e=hp(this.buf,this.pos+=4),t=hp(this.buf,this.pos+=4);return new up(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=ba(this.buf,this.pos);return this.pos+=ma(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function mp(e,t,n){const r=function(e){return new fp(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(r,void 0,n)}class yp{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function bp(){}class gp{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const vp=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return On(r);n+r>e&&(t=On(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class wp{len;head;tail;states;constructor(){this.len=0,this.head=new yp(bp,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yp(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new xp((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Pp,10,up.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=up.fromBigInt(e);return this._push(Pp,t.length(),t)}uint64Number(e){return this._push(ya,ma(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=up.fromBigInt(e).zzEncode();return this._push(Pp,t.length(),t)}sint64Number(e){const t=up.fromNumber(e).zzEncode();return this._push(Pp,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Tp,1,e?1:0)}fixed32(e){return this._push(Sp,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=up.fromBigInt(e);return this._push(Sp,4,t.lo)._push(Sp,4,t.hi)}fixed64Number(e){const t=up.fromNumber(e);return this._push(Sp,4,t.lo)._push(Sp,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(np,4,e)}double(e){return this._push(sp,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Tp,1,0):this.uint32(t)._push(Ap,t,e)}string(e){const t=function(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(lp,t,e):this._push(Tp,1,0)}fork(){return this.states=new gp(this),this.head=this.tail=new yp(bp,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new yp(bp,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next;const t=(n=this.len,null!=globalThis.Buffer?On(n):vp(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function Tp(e,t,n){t[n]=255&e}function Ep(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class xp extends yp{next;constructor(e,t){super(Ep,e,t),this.next=void 0}}function Pp(e,t,n){for(;0!==e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function Sp(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function Ap(e,t,n){t.set(e,n)}function Cp(e,t,n){t.set(e,n)}function kp(e,t,n){e.length<40?lp(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(fr(e),n)}function Ip(e,t){const n=new wp;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var Dp,Mp,Fp,Rp,_p;function Lp(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function Np(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Lp("enum",Dp.VARINT,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())})}function Op(e,t){return Lp("message",Dp.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(wp.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Cp,t,e),this},wp.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(kp,t,e),this}),(_p=Dp||(Dp={}))[_p.VARINT=0]="VARINT",_p[_p.BIT64=1]="BIT64",_p[_p.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",_p[_p.START_GROUP=3]="START_GROUP",_p[_p.END_GROUP=4]="END_GROUP",_p[_p.BIT32=5]="BIT32";class Bp extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class Up extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function jp(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let n;return"RSA"===e.type&&(n=e.toMultihash()),jo(Mo(t.publicKey,n))}function qp(e,t,n){const r=new Map,i=BigInt(Date.now());for(const[e,n]of t.tags.entries())null!=n.expiry&&n.expiry<i||r.set(e,n);return{...t,id:jp(e,t),addresses:t.addresses.filter(({observed:e})=>null!=e&&e>Date.now()-n).map(({multiaddr:e,isCertified:t})=>({multiaddr:Pu(e),isCertified:t??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:r}}function $p(e,t){return null==e&&null==t||null!=e&&null!=t&&Ln(e,t)}function zp(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function Vp(e,t,n){if(e.size!==t.size)return!1;for(const[r,i]of e.entries()){const e=t.get(r);if(null==e)return!1;if(!n(i,e))return!1}return!0}!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={key:"",value:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),Rp.codec().encode(e.value,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={key:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=Rp.codec().decode(e,e.uint32(),{limits:n.limits?.value});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Op((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.addresses)for(const e of t.addresses)n.uint32(10),Fp.codec().encode(e,n);if(null!=t.protocols)for(const e of t.protocols)n.uint32(18),n.string(e);if(null!=t.publicKey&&(n.uint32(34),n.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(n.uint32(42),n.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[r,i]of t.metadata.entries())n.uint32(50),e.Peer$metadataEntry.codec().encode({key:r,value:i},n);if(null!=t.tags&&0!==t.tags.size)for(const[r,i]of t.tags.entries())n.uint32(58),e.Peer$tagsEntry.codec().encode({key:r,value:i},n);null!=t.updated&&(n.uint32(64),n.uint64Number(t.updated)),!1!==r.lengthDelimited&&n.ldelim()},(t,n,r={})=>{const i={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:if(null!=r.limits?.addresses&&i.addresses.length===r.limits.addresses)throw new Bp('Decode error - map field "addresses" had too many elements');i.addresses.push(Fp.codec().decode(t,t.uint32(),{limits:r.limits?.addresses$}));break;case 2:if(null!=r.limits?.protocols&&i.protocols.length===r.limits.protocols)throw new Bp('Decode error - map field "protocols" had too many elements');i.protocols.push(t.string());break;case 4:i.publicKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=r.limits?.metadata&&i.metadata.size===r.limits.metadata)throw new Up('Decode error - map field "metadata" had too many elements');const n=e.Peer$metadataEntry.codec().decode(t,t.uint32());i.metadata.set(n.key,n.value);break}case 7:{if(null!=r.limits?.tags&&i.tags.size===r.limits.tags)throw new Up('Decode error - map field "tags" had too many elements');const n=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:r.limits?.tags$value}});i.tags.set(n.key,n.value);break}case 8:i.updated=t.uint64Number();break;default:t.skipType(7&n)}}return i})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Mp||(Mp={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={multiaddr:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Fp||(Fp={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={value:0},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Rp||(Rp={}));const Gp="/",Kp=(new TextEncoder).encode(Gp),Hp=Kp[0];class Wp{_buf;constructor(e,t){if("string"==typeof e)this._buf=fr(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Hp)throw new Error("Invalid key")}toString(e="utf8"){return mr(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Wp(e.join(Gp))}static random(){return new Wp(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Wp(e):"function"==typeof e.uint8Array?new Wp(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Kp),this._buf[0]!==Hp){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Hp,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Hp;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),n=e.list();for(let e=0;e<t.length;e++){if(n.length<e+1)return!1;const r=t[e],i=n[e];if(r<i)return!0;if(r>i)return!1}return t.length<n.length}reverse(){return Wp.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Gp).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new Wp(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Gp)||(e+=Gp),e+=this.type(),new Wp(e)}parent(){const e=this.list();return new Wp(1===e.length?Gp:e.slice(0,-1).join(Gp))}child(e){return this.toString()===Gp?e:e.toString()===Gp?this:new Wp(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){return Wp.withNamespaces([...this.namespaces(),...(t=e.map(e=>e.namespaces()),[].concat(...t))]);var t}}const Qp="/peers/";function Yp(e){if(!Pt(e)||null==e.type)throw new We("Invalid PeerId");const t=e.toCID().toString();return new Wp(`${Qp}${t}`)}async function Jp(e,t,n,r,i){const s=new Map;for(const r of n){if(null==r)continue;if(r.multiaddr instanceof Uint8Array&&(r.multiaddr=Pu(r.multiaddr)),!xu(r.multiaddr))throw new We("Multiaddr was invalid");if(!await t(e,r.multiaddr,i))continue;const n=r.isCertified??!1,a=r.multiaddr.toString(),o=s.get(a);null!=o?r.isCertified=o.isCertified||n:s.set(a,{multiaddr:r.multiaddr,isCertified:n})}return[...s.values()].sort((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString())).map(({isCertified:t,multiaddr:n})=>{const r=n.getComponents().find(e=>e.code===eu)?.value;return e.equals(r)&&(n=n.decapsulate(Pu(`/p2p/${e}`))),{isCertified:t,multiaddr:n.bytes}})}async function Zp(e,t,n,r){if(null==t)throw new We("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new We("publicKey bytes do not match peer id publicKey bytes");const i=r.existingPeer?.peer;if(null!=i&&!e.equals(i.id))throw new We("peer id did not match existing peer id");let s,a=i?.addresses??[],o=new Set(i?.protocols??[]),u=i?.metadata??new Map,d=i?.tags??new Map,c=i?.peerRecordEnvelope;if("patch"===n&&(null==t.multiaddrs&&null==t.addresses||(a=[],null!=t.multiaddrs&&a.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&a.push(...t.addresses)),null!=t.protocols&&(o=new Set(t.protocols)),null!=t.metadata&&(u=Xp(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:eh})),null!=t.tags&&(d=Xp(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:th,map:nh})),null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)),"merge"===n){if(null!=t.multiaddrs&&a.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&a.push(...t.addresses),null!=t.protocols&&(o=new Set([...o,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,n]of e)null==n?u.delete(t):u.set(t,n);u=Xp([...u.entries()],{validate:eh})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),n=new Map(d);for(const[t,r]of e)null==r?n.delete(t):n.set(t,r);d=Xp([...n.entries()],{validate:th,map:nh})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}null!=i?.id.publicKey?s=Fo(i.id.publicKey):null!=t.publicKey?s=Fo(t.publicKey):null!=e.publicKey&&(s=Fo(e.publicKey));const l={addresses:await Jp(e,r.addressFilter??(async()=>!0),a,0,r),protocols:[...o.values()].sort((e,t)=>e.localeCompare(t)),metadata:u,tags:d,publicKey:s,peerRecordEnvelope:c};return l.addresses.forEach(e=>{e.observed=r.existingPeer?.peerPB.addresses?.find(e=>Ln(e.multiaddr,e.multiaddr))?.observed??Date.now()}),"RSA"!==e.type&&delete l.publicKey,l}function Xp(e,t){const n=new Map;for(const[n,r]of e)null!=r&&t.validate(n,r);for(const[r,i]of e.sort(([e],[t])=>e.localeCompare(t)))null!=i&&n.set(r,t.map?.(r,i)??i);return n}function eh(e,t){if("string"!=typeof e)throw new We("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new We("Metadata value must be a Uint8Array")}function th(e,t){if("string"!=typeof e)throw new We("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new We("Tag value must be an integer");if(t.value<0||t.value>100)throw new We("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new We("Tag ttl must be an integer");if(t.ttl<0)throw new We("Tag ttl must be between greater than 0")}}function nh(e,t){let n;null!=t.expiry&&(n=t.expiry),null!=t.ttl&&(n=BigInt(Date.now()+Number(t.ttl)));const r={value:t.value??0};return null!=n&&(r.expiry=n),r}function rh(e){const t=e.toString().split("/")[2];return $o(kn.parse(t,Ht))}function ih(e,t,n){return function(e,t,n){return qp(e,Mp.decode(t),n)}(rh(e),t,n)}class sh{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Rc({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return null==t&&(t={refs:0,lock:Xl({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,0===t.refs&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){const n=this.getLock(e);try{const r=await n.lock.readLock(t);return()=>{r(),this.maybeRemoveLock(e,n)}}catch(t){throw this.maybeRemoveLock(e,n),t}}async getWriteLock(e,t){const n=this.getLock(e);try{const r=await n.lock.writeLock(t);return()=>{r(),this.maybeRemoveLock(e,n)}}catch(t){throw this.maybeRemoveLock(e,n),t}}async has(e,t){try{return await this.load(e,t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Yp(e),t)}async load(e,t){const n=Yp(e),r=await this.datastore.get(n,t),i=Mp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new nt;return qp(e,i,this.peerId.equals(e)?Infinity:this.maxAddressAge)}async save(e,t,n){const r=await this.#s(e,n),i=await Zp(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#a(e,i,r)}async patch(e,t,n){const r=await this.#s(e,n),i=await Zp(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:r});return this.#a(e,i,r)}async merge(e,t,n){const r=await this.#s(e,n),i=await Zp(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:r});return this.#a(e,i,r)}async*all(e){for await(const{key:t,value:n}of this.datastore.query(function(e,t){return{prefix:Qp,filters:(e.filters??[]).map(e=>({key:n,value:r})=>e(ih(n,r,t))),orders:(e.orders??[]).map(e=>(n,r)=>e(ih(n.key,n.value,t),ih(r.key,r.value,t)))}}(e??{},this.maxAddressAge),e)){const r=rh(t);if(r.equals(this.peerId))continue;const i=Mp.decode(n);this.#i(r,i)?await this.datastore.delete(t,e):yield qp(r,i,this.peerId.equals(r)?Infinity:this.maxAddressAge)}}async#s(e,t){try{const n=Yp(e),r=await this.datastore.get(n,t),i=Mp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new nt;return{peerPB:i,peer:qp(e,i,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#a(e,t,n,r){t.updated=Date.now();const i=Mp.encode(t);return await this.datastore.put(Yp(e),i,r),{peer:qp(e,t,this.maxAddressAge),previous:n?.peer,updated:null==n||(s=t,a=n.peerPB,!(zp(s.addresses,a.addresses,(e,t)=>e.isCertified===t.isCertified&&!!Ln(e.multiaddr,t.multiaddr))&&zp(s.protocols,a.protocols,(e,t)=>e===t)&&$p(s.publicKey,a.publicKey)&&$p(s.peerRecordEnvelope,a.peerRecordEnvelope)&&Vp(s.metadata,a.metadata,(e,t)=>Ln(e,t))&&Vp(s.tags,a.tags,(e,t)=>e.value===t.value&&e.expiry===t.expiry)))};var s,a}#i(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;const n=t.updated<Date.now()-this.maxPeerAge,r=Date.now()-this.maxAddressAge,i=t.addresses.filter(e=>null!=e.observed&&e.observed>r);return n&&0===i.length}}class ah{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new sh(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(const n of this.store.all(t))e(n)}async all(e){return Tl(this.store.all(e))}async delete(e,t){const n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){const n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){const n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){const n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:e})=>e)}}async save(e,t,n){const r=await this.store.getWriteLock(e,n);try{const r=await this.store.save(e,t,n);return this.#o(e,r),r.peer}finally{r?.()}}async patch(e,t,n){const r=await this.store.getWriteLock(e,n);try{const r=await this.store.patch(e,t,n);return this.#o(e,r),r.peer}finally{r?.()}}async merge(e,t,n){const r=await this.store.getWriteLock(e,n);try{const r=await this.store.merge(e,t,n);return this.#o(e,r),r.peer}finally{r?.()}}async consumePeerRecord(e,t,n){const r=Pt(t)?t:Pt(t?.expectedPeer)?t.expectedPeer:void 0,i=Pt(t)||void 0===t?n:t,s=await yl.openAndCertify(e,wl.DOMAIN,i),a=$o(s.publicKey.toCID());if(!1===r?.equals(a))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",r,a),!1;const o=wl.createFromProtobuf(s.payload);let u;try{u=await this.get(a,i)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u?.peerRecordEnvelope){const e=yl.createFromProtobuf(u.peerRecordEnvelope),t=wl.createFromProtobuf(e.payload);if(t.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(e=>({isCertified:!0,multiaddr:e}))},i),!0}#o(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}class oh extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=oh.name;code=oh.code;constructor(e="Not Found"){super(e)}}function uh(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}function dh(e){const[t,n]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],r=[];return{peek:()=>t.next(),push:e=>{r.push(e)},next:()=>r.length>0?{done:!1,value:r.shift()}:t.next(),[n](){return this}}}function ch(e,t){let n=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const r of e)await t(r,n++)&&(yield r)}();const r=dh(e),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const a=t(i,n++);if("function"==typeof a.then)return async function*(){await a&&(yield i);for(const e of r)await t(e,n++)&&(yield e)}();const o=t;return function*(){!0===a&&(yield i);for(const e of r)o(e,n++)&&(yield e)}()}function lh(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const n=await Tl(e);yield*n.sort(t)}():function*(){const n=Tl(e);yield*n.sort(t)}()}function ph(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let n=0;if(!(t<1))for await(const r of e)if(yield r,n++,n===t)return}():function*(){let n=0;if(!(t<1))for(const r of e)if(yield r,n++,n===t)return}()}class hh{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:n,value:r}of e)await this.put(n,r,t),yield n}async*getMany(e,t={}){for await(const n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(const n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(t,n){e.push({key:t,value:n})},delete(e){t.push(e)},commit:async n=>{await uh(this.putMany(e,n)),e=[],await uh(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(null!=e.prefix){const t=e.prefix;n=ch(n,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>ch(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>lh(e,t),n)),null!=e.offset){let t=0;const r=e.offset;n=ch(n,()=>t++>=r)}return null!=e.limit&&(n=ph(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;n=ch(n,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>ch(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>lh(e,t),n)),null!=e.offset){const t=e.offset;let r=0;n=ch(n,()=>r++>=t)}return null!=e.limit&&(n=ph(n,e.limit)),n}}class fh extends hh{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();const n=this.data.get(e.toString());if(null==n)throw new oh;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(const[e,n]of this.data.entries())yield{key:new Wp(e),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(const e of this.data.keys())yield new Wp(e),t?.signal?.throwIfAborted()}}const mh=e=>({match:t=>{const n=t[0];return null!=n&&n.code===e&&null==n.value&&t.slice(1)}}),yh=(e,t)=>({match:n=>{const r=n[0];return r?.code===e&&null!=r.value&&(null==t||r.value===t)&&n.slice(1)}}),bh=e=>({match:t=>{const n=e.match(t);return!1===n?t:n}}),gh=(...e)=>({match:t=>{let n;for(const r of e){const e=r.match(t);!1!==e&&(null==n||e.length<n.length)&&(n=e)}return null!=n&&n}}),vh=(...e)=>({match:t=>{for(const n of e){const e=n.match(t);if(!1===e)return!1;t=e}return t}});function wh(...e){function t(t){if(null==t)return!1;let n=t.getComponents();for(const t of e){const e=t.match(n);if(!1===e)return!1;n=e}return n}return{matchers:e,matches:function(e){return!1!==t(e)},exactMatch:function(e){const n=t(e);return!1!==n&&0===n.length}}}const Th=wh(yh(eu)),Eh=yh(54),xh=yh(55),Ph=yh(56),Sh=yh(53),Ah=vh(yh(4),bh(yh(43))),Ch=vh(bh(yh(42)),yh(Xo),bh(yh(43))),kh=gh(Ah,Ch),Ih=gh(kh,Sh,Eh,xh,Ph),Dh=wh(gh(kh,vh(gh(Sh,Ph,Eh,xh),bh(yh(eu))))),Mh=wh(Ah),Fh=wh(Ch),Rh=vh(Ih,yh(6)),_h=vh(Ih,yh(273)),Lh=wh(vh(Rh,bh(yh(eu)))),Nh=vh(_h,mh(460),bh(yh(eu))),Oh=vh(_h,mh(461),bh(yh(eu))),Bh=gh(Nh,Oh),Uh=wh(Oh),jh=gh(Ih,Rh,_h,Nh,Oh),qh=gh(vh(jh,mh(477),bh(yh(eu)))),$h=wh(qh),zh=gh(vh(jh,mh(478),bh(yh(eu))),vh(jh,mh(tu),bh(yh(nu)),mh(477),bh(yh(eu)))),Vh=wh(zh),Gh=vh(_h,mh(280),bh(yh(ru)),bh(yh(ru)),bh(yh(eu))),Kh=wh(Gh),Hh=vh(Oh,mh(465),bh(yh(ru)),bh(yh(ru)),bh(yh(eu))),Wh=wh(Hh),Qh=gh(qh,zh,vh(Rh,bh(yh(eu))),vh(Bh,bh(yh(eu))),vh(Ih,bh(yh(eu))),Gh,Hh,yh(eu)),Yh=wh(Qh);var Jh;const Zh=wh(vh(bh(Qh),mh(su),(Jh=mh(iu),{match:e=>!1===Jh.match(e)&&e}),bh(yh(eu)))),Xh=wh(gh(vh(Qh,mh(su),mh(iu),bh(yh(eu))),vh(Qh,mh(iu),bh(yh(eu))),vh(mh(iu),bh(yh(eu))))),ef=864e13;class tf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ic({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=hd(e);let n=t.host;"ip4"!==t.type&&"ip6"!==t.type||null==t.sni||(n=t.sni);for(const e of this.mappings.values())if(e.domain===n)return!0;return!1}add(e,t){t.forEach(t=>{this.log("add DNS mapping %s to %s",t,e);const n=!0===Sd(t);this.mappings.set(t,{domain:e,verified:n,expires:n?ef-Date.now():0,lastVerified:n?ef-Date.now():void 0})})}remove(e){const t=hd(e);if("ip4"!==t.type&&"ip6"!==t.type)return!1;let n=!1;for(const[e,r]of this.mappings.entries())r.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",e,r.domain),this.mappings.delete(e),n=n||r.verified);return n}getAll(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n].multiaddr;if(!vd(r))continue;const i=hd(r);for(const[s,a]of this.mappings.entries()){if(i.host!==s)continue;const o=this.maybeAddSNIComponent(r,a.domain);null!=o&&(e.splice(n,1),n--,t.push({multiaddr:o,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){const n=e.getComponents();for(let e=0;e<n.length;e++)if(n[e].code===tu&&n[e+1]?.code!==nu)return n.splice(e+1,0,{name:"sni",code:nu,value:t}),Pu(n)}confirm(e,t){const n=hd(e);let r=n.host;"ip4"!==n.type&&"ip6"!==n.type||null==n.sni||(r=n.sni);let i=!1;for(const[e,n]of this.mappings.entries())n.domain===r&&(this.log("marking %s to %s DNS mapping as verified",e,n.domain),i=n.verified,n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now());return i}unconfirm(e,t){const n=hd(e);if("ip4"!==n.type&&"ip6"!==n.type)return!1;const r=n.sni??n.host;let i=!1;for(const[e,n]of this.mappings.entries())n.domain===r&&(this.log("removing verification of %s to %s DNS mapping",e,n.domain),i=i||n.verified,n.verified=!1,n.expires=Date.now()+t);return i}}class nf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ic({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=hd(e);if("ip4"!==t.type&&"ip6"!==t.type)return!1;for(const e of this.mappings.values())for(const n of e)if(n.externalIp===t.host)return!0;return!1}add(e,t,n,r=t,i="tcp"){const s=`${e}-${t}-${i}`,a=this.mappings.get(s)??[],o={internalIp:e,internalPort:t,externalIp:n,externalPort:r,externalFamily:Jo(n)?4:6,protocol:i,verified:!1,expires:0};a.push(o),this.mappings.set(s,a)}remove(e){const t=hd(e);if("ip4"!==t.type&&"ip6"!==t.type)return!1;let n=!1;for(const[e,r]of this.mappings.entries()){for(let e=0;e<r.length;e++){const i=r[e];i.externalIp===t.host&&i.externalPort===t.port&&i.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",i.externalIp,i.externalPort,t.host,t.port,t.protocol),n=n||i.verified,r.splice(e,1),e--)}0===r.length&&this.mappings.delete(e)}return n}getAll(e){const t=[];for(const{multiaddr:n}of e){if(!vd(n))continue;const e=hd(n);if("ip4"!==e.type&&"ip6"!==e.type)continue;let r;if("tcp"===e.protocol?r=`${e.host}-${e.port}-tcp`:"udp"===e.protocol&&(r=`${e.host}-${e.port}-udp`),null==r)continue;const i=this.mappings.get(r);if(null!=i)for(const e of i)t.push({multiaddr:this.maybeOverrideIp(n,e.externalIp,e.externalFamily,e.protocol,e.externalPort),verified:e.verified,type:"ip-mapping",expires:e.expires,lastVerified:e.lastVerified})}return t}maybeOverrideIp(e,t,n,r,i){const s=e.getComponents(),a=s.findIndex(e=>4===e.code||e.code===Xo),o=s.findIndex(e=>e.name===r);return a>-1&&o>-1?(s[a].value=t,s[a].code=4===n?4:Xo,s[o].value=`${i}`,Pu(s)):e}confirm(e,t){if(!vd(e))return!1;const n=hd(e);let r=!1;for(const e of this.mappings.values())for(const i of e)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),r=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return r}unconfirm(e,t){if(!vd(e))return!1;const n=hd(e);let r=!1;for(const e of this.mappings.values())for(let i=0;i<e.length;i++){const s=e[i];s.externalIp===n.host&&s.externalPort===n.port&&s.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",s.externalIp,s.externalPort,n.host,n.port,n.protocol),r=r||s.verified,s.verified=!1,s.expires=Date.now()+t)}return r}}class rf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ic({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(const t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Ad(e)||function(e){try{const t=hd(e);switch(t.type){case"ip4":return t.host.startsWith("169.254.");case"ip6":return t.host.toLowerCase().startsWith("fe80");default:return!1}}catch(e){return!1}}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:Pu(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){const t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){const n=e.toString(),r=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},i=r.verified;return r.verified=!0,r.expires=Date.now()+t,r.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,r),i}}class sf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ic({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(Ad(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};const n=this.toKey(e);let r=this.addresses.get(n);return null==r&&(r={verified:!vd(e),expires:0},this.addresses.set(n,r)),{multiaddr:e,verified:r.verified,type:"transport",expires:r.expires,lastVerified:r.lastVerified}}has(e){const t=this.toKey(e);return this.addresses.has(t)}remove(e){const t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){const n=this.toKey(e),r=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},i=r.verified;return r.verified=!0,r.expires=Date.now()+t,r.lastVerified=Date.now(),this.addresses.set(n,r),i}unconfirm(e,t){const n=this.toKey(e),r=this.addresses.get(n)??{verified:!1,expires:0},i=r.verified;return r.verified=!1,r.expires=Date.now()+t,this.addresses.set(n,r),i}toKey(e){if(!vd(e))return e.toString();const t=hd(e);return`${t.host}-${t.port}-${t.protocol}`}}const af=e=>e;function of(e,t){const n=e.getComponents().findLast(e=>e.code===eu)?.value;return null!=n&&Uo(n).equals(t)&&(e=e.decapsulate(Pu(`/p2p/${t.toString()}`))),e}class uf{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){const{listen:n=[],announce:r=[],appendAnnounce:i=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(e=>e.toString()),this.announce=new Set(r.map(e=>e.toString())),this.appendAnnounce=new Set(i.map(e=>e.toString())),this.observed=new rf(e,t),this.dnsMappings=new tf(e,t),this.ipMappings=new nf(e,t),this.transportAddresses=new sf(e,t),this.announceFilter=t.announceFilter??af,this.observedAddressFilter=pd(1024),this.addressVerificationTTL=t.addressVerificationTTL??6e5,this.addressVerificationRetry=t.addressVerificationRetry??3e5,this._updatePeerStoreAddresses=Ld(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAddresses().map(e=>e.getComponents().findLast(e=>e.code===eu)?.value===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(e=>{this.log.error("error updating addresses - %e",e)})}getListenAddrs(){return Array.from(this.listen).map(e=>Pu(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Pu(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Pu(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){const t=hd(e);let n;switch(t.type){case"ip4":n=`${t.host}:${t.port}`;break;case"ip6":n=`[${t.host}]:${t.port}`;break;default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=of(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=of(e,this.components.peerId);let n=!0;("transport"===t?.type||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("dns-mapping"===t?.type||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("ip-mapping"===t?.type||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("observed"===t?.type||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=of(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){const e=new Set,t=this.getAddressesWithMetadata().filter(t=>{if(!t.verified)return!1;const n=t.multiaddr.toString();return!e.has(n)&&(e.add(n),!0)}).map(e=>e.multiaddr);return this.announceFilter(t.map(e=>{const t=Pu(e),n=t.getComponents().pop();return n?.value===this.components.peerId.toString()?t:t.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(t=>{t.updateAnnounceAddrs(e)}),e.map(e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(e=>this.transportAddresses.get(e,this.addressVerificationTTL)));const n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(e=>{e.updateAnnounceAddrs(n)}),t=t.concat(n.map(e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Pu(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.add(e,t,n,r,i),this.observed.removePrefixed(`/ip${Jo(n)?4:6}/${n}/${i}/${r}`)}removePublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.remove(Pu(`/ip${Jo(n)?4:6}/${n}/${i}/${r}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;if(!vd(e))return!1;const t=hd(e);if("ip4"!==t.type||!0===Sd(t.host))return!1;const n=this.components.transportManager.getListeners(),r=[e=>$h.exactMatch(e)||Vh.exactMatch(e),e=>Lh.exactMatch(e),e=>Uh.exactMatch(e)];for(const i of r){if(!i(e))continue;const r=n.filter(e=>e.getAddrs().filter(e=>"ip4"===hd(e).type&&i(e)).length>0);if(1!==r.length)continue;const s=r[0].getAddrs().filter(e=>!gd(e)).pop();if(null==s)continue;const a=hd(s);return null!=a.port&&(this.observed.remove(e),this.ipMappings.add(a.host,a.port,t.host,t.port,t.protocol),!0)}return!1}}var df;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(df||(df={}));class cf extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class lf extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class pf extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class hf extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class ff extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class mf extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class yf extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class bf extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class gf extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class vf extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class wf extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Tf extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class Ef extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class xf extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class Pf extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class Sf extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class Af extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}class Cf{components={};_started=!1;constructor(e={}){this.components={};for(const[t,n]of Object.entries(e))this.components[t]=n;null==this.components.logger&&(this.components.logger=Wu())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>Ct(e)).map(async t=>{await(t[e]?.())}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const kf=["metrics","connectionProtector","dns"],If=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Df(e){return Array.isArray(e?.[Rt])?e[Rt]:[]}function Mf(e){return Array.isArray(e?.[_t])?e[_t]:[]}function Ff(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function Rf(e={}){return null==e.denyDialMultiaddr&&(e.denyDialMultiaddr=e=>!!$h.matches(e)||Ad(e)),e}class _f extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Lf(e){if(Pt(e))return{peerId:e,multiaddrs:[]};let t,n=Array.isArray(e)?e:[e];if(n.length>0){const e=n[0].getComponents().findLast(e=>e.code===eu)?.value;t=null==e?void 0:Uo(e),n.forEach(e=>{if(!xu(e))throw new it("Invalid multiaddr");const n=e.getComponents().findLast(e=>e.code===eu)?.value;if(null==n){if(null!=t)throw new We("Multiaddrs must all have the same peer id or have no peer id")}else{const e=Uo(n);if(!0!==t?.equals(e))throw new We("Multiaddrs must all have the same peer id or have no peer id")}})}return n=n.filter(e=>!Th.exactMatch(e)),{peerId:t,multiaddrs:n}}const Nf=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Of(e){const t=hd(e);let n=t.cidr;if("ip4"!==t.type&&"ip6"!==t.type)throw new We(`Multiaddr ${e} was not an IPv4 or IPv6 address`);if(null==n)switch(t.type){case"ip4":n=32;break;case"ip6":n=128;break;default:throw new We(`Multiaddr ${e} was not an IPv4 or IPv6 address`)}return new bd(t.host,n)}function Bf(e){return!Zh.exactMatch(e)}function Uf(e,t,n){if(null==e||null==t)return;const r=t.sort((e,t)=>e.direct?-1:t.direct?1:0).find(e=>null==e.limits);return null==r||r.direct||null==n?r:n.some(e=>Bf(e))?void 0:r}class jf{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(e=>Of(e)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;const r=new Xu;for(const t of e){const e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{const t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce((e,t)=>e+t.value,0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags - %e",e)}}}const i=this.sortConnections(e,r),s=Math.max(t-n,0),a=[];for(const e of i)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some(t=>{if(vd(e.remoteAddr)){const n=hd(e.remoteAddr);return t.contains(n.host)}return!0})||a.push(e),a.length===s)break;await Promise.all(a.map(async e=>{await async function(e,t){const n=e?.streams?.map(e=>e.protocol)??[],r=t?.closableProtocols??Nf;if(!(n.filter(e=>null!=e&&!r.includes(e)).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((e,t)=>{const n=e.timeline.open,r=t.timeline.open;return n<r?1:n>r?-1:0}).sort((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0).sort((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0).sort((e,n)=>{const r=t.get(e.remotePeer)??0,i=t.get(n.remotePeer)??0;return r>i?1:r<i?-1:0})}}const qf=1e4,$f="last-dial-failure",zf="last-dial-success";function Vf(e,t){const n=Lh.exactMatch(e.multiaddr),r=Lh.exactMatch(t.multiaddr);if(n&&!r)return-1;if(!n&&r)return 1;const i=Vh.exactMatch(e.multiaddr),s=Vh.exactMatch(t.multiaddr);if(i&&!s)return-1;if(!i&&s)return 1;const a=$h.exactMatch(e.multiaddr),o=$h.exactMatch(t.multiaddr);if(a&&!o)return-1;if(!a&&o)return 1;const u=Xh.exactMatch(e.multiaddr),d=Xh.exactMatch(t.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;const c=Kh.exactMatch(e.multiaddr),l=Kh.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const p=Wh.exactMatch(e.multiaddr),h=Wh.exactMatch(t.multiaddr);return p&&!h?-1:!p&&h?1:0}function Gf(e,t){const n=gd(e.multiaddr),r=gd(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function Kf(e,t){const n=Ad(e.multiaddr),r=Ad(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function Hf(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function Wf(e,t){const n=Zh.exactMatch(e.multiaddr),r=Zh.exactMatch(t.multiaddr);return n&&!r?1:!n&&r?-1:0}class Qf extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"}var Yf=Td(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new i(r,s||e,a),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],o]:e._events[u].push(o):(e._events[u]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),o.prototype.eventNames=function(){var e,r,i=[];if(0===this._eventsCount)return i;for(r in e=this._events)t.call(e,r)&&i.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,i=t.length,s=new Array(i);r<i;r++)s[r]=t[r].fn;return s},o.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},o.prototype.emit=function(e,t,r,i,s,a){var o=n?n+e:e;if(!this._events[o])return!1;var u,d,c=this._events[o],l=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,i),!0;case 5:return c.fn.call(c.context,t,r,i,s),!0;case 6:return c.fn.call(c.context,t,r,i,s,a),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var p,h=c.length;for(d=0;d<h;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,r);break;case 4:c[d].fn.call(c[d].context,t,r,i);break;default:if(!u)for(p=1,u=new Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},o.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},o.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},o.prototype.removeListener=function(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn!==t||i&&!o.once||r&&o.context!==r||a(this,s);else{for(var u=0,d=[],c=o.length;u<c;u++)(o[u].fn!==t||i&&!o[u].once||r&&o[u].context!==r)&&d.push(o[u]);d.length?this._events[s]=1===d.length?d[0]:d:a(this,s)}return this},o.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&a(this,t):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,e.exports=o}),Jf=Yf;class Zf extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Zf)}}const Xf=e=>e.reason??new DOMException("This operation was aborted.","AbortError");class em{#u=[];enqueue(e,t){const{priority:n=0,id:r}=t??{},i={priority:n,id:r,run:e};if(0===this.size||this.#u[this.size-1].priority>=n)return void this.#u.push(i);const s=function(e,t,n){let r=0,i=e.length;for(;i>0;){const s=Math.trunc(i/2);let a=r+s;n(e[a],t)<=0?(r=++a,i-=s+1):i=s}return r}(this.#u,i,(e,t)=>t.priority-e.priority);this.#u.splice(s,0,i)}setPriority(e,t){const n=this.#u.findIndex(t=>t.id===e);if(-1===n)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[r]=this.#u.splice(n,1);this.enqueue(r.run,{priority:t,id:e})}dequeue(){const e=this.#u.shift();return e?.run}filter(e){return this.#u.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this.#u.length}}class tm extends Jf{#d;#c;#l=0;#p;#h=!1;#f=!1;#m;#y=0;#b=0;#g;#v;#w;#T=[];#E=0;#u;#x;#P=0;#S;#A;#C=1n;#k=new Map;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:em,strict:!1,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&0===e.interval)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#d=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#c=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#p=e.intervalCap,this.#m=e.interval,this.#w=e.strict,this.#u=new e.queueClass,this.#x=e.queueClass,this.concurrency=e.concurrency,void 0!==e.timeout&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#A=!1===e.autoStart,this.#I()}#D(e){for(;this.#E<this.#T.length;){const t=this.#T[this.#E];if(!(void 0!==t&&e-t>=this.#m))break;this.#E++}(this.#E>100&&this.#E>this.#T.length/2||this.#E===this.#T.length)&&(this.#T=this.#T.slice(this.#E),this.#E=0)}#M(e){this.#w?this.#T.push(e):this.#l++}#F(){this.#w?this.#T.length>this.#E&&this.#T.pop():this.#l>0&&this.#l--}#R(){return this.#T.length-this.#E}get#_(){return!!this.#c||(this.#w?this.#R()<this.#p:this.#l<this.#p)}get#L(){return this.#P<this.#S}#N(){this.#P--,0===this.#P&&this.emit("pendingZero"),this.#O(),this.emit("next")}#B(){this.#v=void 0,this.#U(),this.#j()}#q(e){if(this.#w){if(this.#D(e),this.#R()>=this.#p){const t=this.#T[this.#E],n=this.#m-(e-t);return this.#$(n),!0}return!1}if(void 0===this.#g){const t=this.#y-e;if(!(t<0))return this.#$(t),!0;if(this.#b>0){const t=e-this.#b;if(t<this.#m)return this.#$(this.#m-t),!0}this.#l=this.#d?this.#P:0}return!1}#$(e){void 0===this.#v&&(this.#v=setTimeout(()=>{this.#B()},e))}#z(){this.#g&&(clearInterval(this.#g),this.#g=void 0)}#V(){this.#v&&(clearTimeout(this.#v),this.#v=void 0)}#O(){if(0===this.#u.size){if(this.#z(),this.emit("empty"),0===this.#P){if(this.#V(),this.#w&&this.#E>0){const e=Date.now();this.#D(e)}this.emit("idle")}return!1}let e=!1;if(!this.#A){const t=Date.now(),n=!this.#q(t);if(this.#_&&this.#L){const r=this.#u.dequeue();this.#c||(this.#M(t),this.#G()),this.emit("active"),r(),n&&this.#j(),e=!0}}return e}#j(){this.#c||void 0!==this.#g||this.#w||(this.#g=setInterval(()=>{this.#U()},this.#m),this.#y=Date.now()+this.#m)}#U(){this.#w||(0===this.#l&&0===this.#P&&this.#g&&this.#z(),this.#l=this.#d?this.#P:0),this.#K(),this.#G()}#K(){for(;this.#O(););}get concurrency(){return this.#S}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#S=e,this.#K()}setPriority(e,t){if("number"!=typeof t||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#u.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#C++).toString()},new Promise((n,r)=>{const i=Symbol(`task-${t.id}`);this.#u.enqueue(async()=>{let s;this.#P++,this.#k.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});try{try{t.signal?.throwIfAborted()}catch(e){throw this.#H(),this.#k.delete(i),e}this.#b=Date.now();let r=e({signal:t.signal});if(t.timeout&&(r=function(e,t){const{milliseconds:n,fallback:r,message:i,customTimers:s={setTimeout:setTimeout,clearTimeout:clearTimeout},signal:a}=t;let o,u;const d=new Promise((t,d)=>{if("number"!=typeof n||1!==Math.sign(n))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(a?.aborted)return void d(Xf(a));if(a&&(u=()=>{d(Xf(a))},a.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Zf;o=s.setTimeout.call(void 0,()=>{if(r)try{t(r())}catch(e){d(e)}else"function"==typeof e.cancel&&e.cancel(),!1===i?t():i instanceof Error?d(i):(c.message=i??`Promise timed out after ${n} milliseconds`,d(c))},n)}).finally(()=>{d.clear(),u&&a&&a.removeEventListener("abort",u)});return d.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},d}(Promise.resolve(r),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#P} running, ${this.#u.size} waiting)`})),t.signal){const{signal:e}=t;r=Promise.race([r,new Promise((t,n)=>{s=()=>{n(e.reason)},e.addEventListener("abort",s,{once:!0})})])}const a=await r;n(a),this.emit("completed",a)}catch(e){r(e),this.emit("error",e)}finally{s&&t.signal?.removeEventListener("abort",s),this.#k.delete(i),queueMicrotask(()=>{this.#N()})}},t),this.emit("add"),this.#O()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#A?(this.#A=!1,this.#K(),this):this}pause(){this.#A=!0}clear(){this.#u=new this.#x,this.#z(),this.#W(),this.emit("empty"),0===this.#P&&(this.#V(),this.emit("idle")),this.emit("next")}async onEmpty(){0!==this.#u.size&&await this.#Q("empty")}async onSizeLessThan(e){this.#u.size<e||await this.#Q("next",()=>this.#u.size<e)}async onIdle(){0===this.#P&&0===this.#u.size||await this.#Q("idle")}async onPendingZero(){0!==this.#P&&await this.#Q("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#Q("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#Q("rateLimitCleared")}onError(){return new Promise((e,t)=>{const n=e=>{this.off("error",n),t(e)};this.on("error",n)})}async#Q(e,t){return new Promise(n=>{const r=()=>{t&&!t()||(this.off(e,r),n())};this.on(e,r)})}get size(){return this.#u.size}sizeBy(e){return this.#u.filter(e).length}get pending(){return this.#P}get isPaused(){return this.#A}#I(){this.#c||(this.on("add",()=>{this.#u.size>0&&this.#G()}),this.on("next",()=>{this.#G()}))}#G(){this.#c||this.#f||(this.#f=!0,queueMicrotask(()=>{this.#f=!1,this.#W()}))}#H(){this.#c||(this.#F(),this.#G())}#W(){const e=this.#h;if(this.#c||0===this.#u.size)return void(e&&(this.#h=!1,this.emit("rateLimitCleared")));let t;if(this.#w){const e=Date.now();this.#D(e),t=this.#R()}else t=this.#l;const n=t>=this.#p;n!==e&&(this.#h=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#h}get isSaturated(){return this.#P===this.#S&&this.#u.size>0||this.isRateLimited&&this.#u.size>0}get runningTasks(){return[...this.#k.values()].map(e=>({...e}))}}function nm(e){const t=[om.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function rm(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map(e=>({name:e.name,type:om[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:om[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?mr(e.data):e.data}))}}function im(e,t={}){const n=new tm({concurrency:t.queryConcurrency??4});return async(t,r={})=>{const i=r?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",t),nm(r.types).forEach(e=>{s.append("type",om[e])}),r.onProgress?.(new _f("dns:query",t)),i?.("GET %s",`${e}?${s}`);const a=await n.add(async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:r?.signal});if(i?.("GET %s %d",t.url,t.status),200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const n=rm(await t.json());return r.onProgress?.(new _f("dns:response",n)),n},{signal:r.signal});if(null==a)throw new Error("No DNS response received");return a}}class sm{lru;constructor(e){this.lru=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,n=Object.create(null),r=Object.create(null);function i(i,s){n[i]=s,++t>=e&&(t=0,r=n,n=Object.create(null))}return{has:function(e){return void 0!==n[e]||void 0!==r[e]},remove:function(e){void 0!==n[e]&&(n[e]=void 0),void 0!==r[e]&&(r[e]=void 0)},get:function(e){var t=n[e];return void 0!==t?t:void 0!==(t=r[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==n[e]?n[e]=t:i(e,t)},clear:function(){n=Object.create(null),r=Object.create(null)}}}(e)}get(e,t){let n=!0;const r=[];for(const i of t){const t=this.getAnswers(e,i);if(0===t.length){n=!1;break}r.push(...t)}if(n)return rm({answers:r})}getAnswers(e,t){const n=`${e.toLowerCase()}-${t}`,r=this.lru.get(n);if(null!=r){const e=r.filter(e=>e.expires>Date.now()).map(({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:om[t.type]}));return 0===e.length&&this.lru.remove(n),e}return[]}add(e,t){const n=`${e.toLowerCase()}-${t.type}`,r=this.lru.get(n)??[];r.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(n,r)}remove(e,t){const n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}}class am{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=new sm(e.cacheSize??1e3),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=t}),null==this.resolvers["."]&&(this.resolvers["."]=[im("https://cloudflare-dns.com/dns-query"),im("https://dns.google/resolve")])}async query(e,t={}){const n=nm(t.types),r=!1!==t.cached?this.cache.get(e,n):void 0;if(null!=r)return t.onProgress?.(new _f("dns:cache",r)),r;const i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(const r of s){if(!0===t.signal?.aborted)break;try{const i=await r(e,{...t,logger:this.logger,types:n});for(const t of i.Answer)this.cache.add(e,t);return i}catch(e){a.push(e),t.onProgress?.(new _f("dns:error",e))}}throw new Qf(a,`DNS lookup of ${e} ${n} failed`)}}var om;!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(om||(om={}));const um=new class{dns;canResolve(e){return e.getComponents().some(({name:e})=>"dnsaddr"===e)}async resolve(e,t){const n=e.getComponents().find(e=>"dnsaddr"===e.name)?.value;if(null==n)return[e];const r=this.getDNS(t),i=await r.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[om.TXT]}),s=e.getComponents().find(e=>"p2p"===e.name)?.value,a=[];for(const e of i.Answer){const t=e.data.replace(/["']/g,"").trim().split("=")[1];null!=t&&(null==s||t.includes(s))&&a.push(Pu(t))}return a}getDNS(e){return null!=e.dns?e.dns:(null==this.dns&&(this.dns=function(e={}){return new am(e)}()),this.dns)}};async function dm(e,t,n){const r=n.depth??0;if(r>(n.maxRecursiveDepth??32))throw new Af("Max recursive depth reached");let i=!1;const s=[];for(const a of Object.values(t))if(a.canResolve(e)){i=!0;const o=await a.resolve(e,n);for(const e of o)s.push(...await dm(e,t,{...n,depth:r+1}))}return!1===i&&s.push(e),s}const cm={maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:um}};class lm{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??cm.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??cm.maxDialQueueLength,this.dialTimeout=t.dialTimeout??cm.dialTimeout,this.connections=t.connections??new Xu,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??cm.resolvers,this.shutDownController=new AbortController,this.queue=new Pc({concurrency:t.maxParallelDials??cm.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",e=>{e.detail?.error.name!==Ge.name&&this.log.error("error in dial queue - %e",e.detail.error)})}start(){this.shutDownController=new AbortController}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:n,multiaddrs:r}=Lf(e);if(null!=n&&!0!==t.force){const e=Uf(n,this.connections.get(n),r);if(null!=e)return this.log("already connected to %a",e.remoteAddr),t.onProgress?.(new _f("dial-queue:already-connected")),e}const i=this.queue.queue.find(e=>{if(!0===n?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of r)if(t.has(e.toString()))return!0;return!1});if(null!=i){this.log("joining existing dial target for %p",n);for(const e of r)i.options.multiaddrs.add(e.toString());return t.onProgress?.(new _f("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new pt("Dial queue is full");return this.log("creating dial target for %p",n,r.map(e=>e.toString())),t.onProgress?.(new _f("dial-queue:add-to-dial-queue")),this.queue.add(async e=>{e.onProgress?.(new _f("dial-queue:start-dial"));const t=Jd([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}},{peerId:n,priority:t.priority??wm,multiaddrs:new Set(r.map(e=>e.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){const n=e.peerId,r=e.multiaddrs,i=new Set;let s=0===e.multiaddrs.size,a=0,o=0;const u=[];for(this.log("starting dial to %p",n);s||r.size>0;){o++,s=!1;const d=[],c=new Set(e.multiaddrs);r.clear(),this.log("calculating addrs to dial %p from %s",n,[...c]);const l=await this.calculateMultiaddrs(n,c,{...e,signal:t});for(const e of l)i.has(e.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",e.multiaddr,n):d.push(e);this.log("%s dial to %p with %s",1===o?"starting":"continuing",n,d.map(e=>e.multiaddr.toString())),e?.onProgress?.(new _f("dial-queue:calculated-addresses",d));for(const r of d){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new pt("Peer had more than maxPeerAddrsToDial");a++;try{const i=await this.components.transportManager.dial(r.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",r.multiaddr);try{await this.components.peerStore.merge(i.remotePeer,{multiaddrs:[i.remoteAddr],metadata:{[zf]:fr(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p - %e",n,e)}return i}catch(e){if(this.log.error("dial failed to %a - %e",r.multiaddr,e),i.add(r.multiaddr.toString()),null!=n)try{await this.components.peerStore.merge(n,{metadata:{[$f]:fr(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p - %e",n,e)}if(t.aborted)throw new ct(e.message);u.push(e)}}}if(1===u.length)throw u[0];throw new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){const r=[...t].map(e=>({multiaddr:Pu(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new pt("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new bf("The dial request is blocked by gater.allowDialPeer");if(0===r.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);r.push(...t.addresses),this.log("loaded multiaddrs for %p",e,r.map(({multiaddr:e})=>e.toString()))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===r.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,r.map(({multiaddr:e})=>e.toString())),r.push(...t.multiaddrs.map(e=>({multiaddr:e,isCertified:!1})))}catch(t){"NoPeerRoutersError"===t.name?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}let i=(await Promise.all(r.map(async e=>{const t=await dm(e.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map(e=>({multiaddr:e,isCertified:!1}))}))).flat();if(null!=e){const t=`/p2p/${e.toString()}`;i=i.map(e=>{const n=e.multiaddr.getComponents().pop();return"p2p"!==n?.name?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e})}const s=i.filter(t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const n=t.multiaddr.getComponents().findLast(e=>e.code===eu)?.value;return null==e||null==n||e.equals(n)}),a=new Map;for(const e of s){const t=e.multiaddr.toString(),n=a.get(t);null==n?a.set(t,e):n.isCertified=n.isCertified||e.isCertified||!1}const o=[...a.values()];if(0===o.length)throw new wf("The dial request has no valid addresses");const u=[];for(const e of o)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||u.push(e);const d=null==this.addressSorter?u.sort(Vf).sort(Hf).sort(Wf).sort(Kf).sort(Gf):u.sort(this.addressSorter);if(0===d.length)throw new bf("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:e})=>e.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:e})=>e.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const n=await this.calculateMultiaddrs(void 0,new Set(e.map(e=>e.toString())),t);return!1!==t.runOnLimitedConnection||null!=n.find(e=>!Zh.matches(e.multiaddr))}catch{}return!1}}const pm=Object.prototype.toString,hm=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function fm(e,t,{min:n=0,allowInfinity:r=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be ≥ ${n}.`)}}class mm extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}function ym(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function bm({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){const s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof mm)throw s.originalError;const a=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,o=i.maxRetryTime??Number.POSITIVE_INFINITY,u=Object.freeze({error:s,attemptNumber:t,retriesLeft:a,retriesConsumed:n});if(await i.onFailedAttempt(u),ym(r,o)<=0)throw s;const d=await i.shouldConsumeRetry(u),c=ym(r,o);if(c<=0||a<=0)throw s;if(s instanceof TypeError&&!function(e){const t=e&&(e=>"[object Error]"===pm.call(e))(e)&&"TypeError"===e.name&&"string"==typeof e.message;if(!t)return!1;const{message:n,stack:r}=e;return"Load failed"===n?void 0===r||"__sentry_captured__"in e:!!n.startsWith("error sending request for url")||!!("Failed to fetch"===n||n.startsWith("Failed to fetch (")&&n.endsWith(")"))||hm.has(n)}(s)){if(d)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(u))throw s;if(!d)return i.signal?.throwIfAborted(),!1;const l=function(e,t){const n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1;let i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}(n,i),p=Math.min(l,c);return i.signal?.throwIfAborted(),p>0&&await new Promise((e,t)=>{const n=()=>{clearTimeout(r),i.signal?.removeEventListener("abort",n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener("abort",n),e()},p);i.unref&&r.unref?.(),i.signal?.addEventListener("abort",n,{once:!0})}),i.signal?.throwIfAborted(),!0}class gm{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new xc({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",e=>{this.maybeReconnect(e.detail).catch(t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)})})}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);vm(t)&&(this.queue.has(e)||this.queue.add(async t=>{await async function(e,t={}){if(function(e){if("number"==typeof e){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==e)throw new TypeError("Expected `retries` to be a number or Infinity.")}((t={...t}).retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,fm("factor",t.factor,{min:0,allowInfinity:!1}),fm("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),fm("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),fm("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0;const i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();const r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await bm({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}(async n=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,n,this.retries,t),t}},{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);const r={};[...t.tags.keys()].forEach(e=>{e.startsWith(At)&&(r[e]=void 0)}),await this.peerStore.merge(e,{tags:r}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{const e=await this.peerStore.all({filters:[e=>vm(e)]});await Promise.all(e.map(async e=>{await this.connectionManager.openConnection(e.id).catch(e=>{this.log.error("could not open connection to keepalive peer - %e",e)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}}function vm(e){for(const t of e.tags.keys())if(t.startsWith(At))return!0;return!1}const wm=50;class Tm{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new We("Connection Manager maxConnections must be greater than 0");this.connections=new Xu,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(e=>Of(Pu(e))),this.deny=(t.deny??[]).map(e=>Of(Pu(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Sc({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new jf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(e=>Pu(e))}),this.dialQueue=new lm(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:um},connections:this.connections}),this.reconnectQueue=new gm({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const n of t)for(const t of n.streams){const n=`${t.direction} ${t.protocol??"unnegotiated"}`;e[n]=(e[n]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const n of t){const t={};for(const e of n.streams){const n=`${e.direction} ${e.protocol??"unnegotiated"}`;t[n]=(t[n]??0)+1}for(const[n,r]of Object.entries(t))e[n]=e[n]??[],e[n].push(r)}const t={};for(let[n,r]of Object.entries(e)){r=r.sort((e,t)=>e-t);const e=Math.floor(.9*r.length);t[n]=r[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await kt(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await It(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const n of t)e.push(Promise.all([_d(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(e=>{n.abort(e)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new We("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(e=>{this.log.error("could not connect - %e",e)})}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const n=t.remotePeer,r=!this.connections.has(n),i=this.connections.get(n)??[];i.push(t),this.connections.set(n,i),null!=n.publicKey&&"RSA"===n.type&&await this.peerStore.patch(n,{publicKey:n.publicKey}),r&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,n=t.remotePeer,r=(this.connections.get(n)??[]).filter(e=>e.id!==t.id);this.connections.set(n,r),0===r.length&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new lt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:n,multiaddrs:r}=Lf(e);if(this.peerId.equals(n))throw new rt("Can not dial self");if(null!=n&&!0!==t.force){this.log("dial %p",n);const e=Uf(n,this.getConnections(n),r);if(null!=e)return this.log("had an existing connection to %p as %a",n,e.remoteAddr),t.onProgress?.(new _f("dial-queue:already-connected")),e}const i=await this.dialQueue.dial(e,{...t,priority:t.priority??wm});if("open"!==i.status)throw new Ye("Remote closed connection during opening");let s=this.connections.get(i.remotePeer);null==s&&(s=[],this.connections.set(i.remotePeer,s));let a=!1;for(const e of s)if(e.id===i.id&&(a=!0),!0!==t.force&&e.id!==i.id&&e.remoteAddr.equals(i.remoteAddr))return i.abort(new it("Duplicate multiaddr connection")),e;return a||s.push(i),i}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){const n=this.connections.get(e)??[];await Promise.all(n.map(async e=>{try{await Promise.all([_d(e,"close",t),e.close(t)])}catch(t){e.abort(t)}}))}acceptIncomingConnection(e){if(this.deny.some(t=>{if(vd(e.remoteAddr)){const n=hd(e.remoteAddr);return t.contains(n.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(t=>{if(vd(e.remoteAddr)){const n=hd(e.remoteAddr);return t.contains(n.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(vd(e.remoteAddr)){const t=hd(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(t.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(e=>Pu(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Em{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new Xd({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Rt]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();const n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal});try{const r=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),i=hc(r);t=Date.now(),await Promise.all([i.write(io(32),{signal:n}),i.read({bytes:32,signal:n})]),e.rtt=Date.now()-t,await r.close({signal:n})}catch(n){if("UnsupportedProtocolError"!==n.name)throw n;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class xm{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()}),getAttributesFromYieldedValue:(e,t)=>({...t,providers:[...Array.isArray(t.providers)?t.providers:[],e.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([e])=>({key:mr(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:mr(e,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new pf("No content routers available");const n=this,r=new ed;for await(const i of tc(...n.routers.filter(e=>e.findProviders instanceof Function).map(n=>n.findProviders(e,t))))null!=i&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),r.has(i.id)||(r.add(i.id),yield i))}async provide(e,t={}){if(0===this.routers.length)throw new pf("No content routers available");await Promise.all(this.routers.filter(e=>e.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(0===this.routers.length)throw new pf("No content routers available");await Promise.all(this.routers.filter(e=>e.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new lt;await Promise.all(this.routers.filter(e=>e.put instanceof Function).map(async r=>{await r.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new lt;return Promise.any(this.routers.filter(e=>e.get instanceof Function).map(async n=>n.get(e,t)))}}const Pm=globalThis.CustomEvent??Event;async function*Sm(e,t={}){let n=t.concurrency??Infinity;n<1&&(n=Infinity);const r=t.ordered??!1,i=new EventTarget,s=[];let a,o=Cd(),u=Cd(),d=!1,c=!1;function l(){return r?s[0]?.done:Boolean(s.find(e=>e.done))}function*p(){for(;s.length>0&&s[0].done;){const e=s[0];if(s.shift(),!e.ok)throw c=!0,o.resolve(),e.err;yield e.value,o.resolve()}}function*h(){for(;l();)for(let e=0;e<s.length;e++)if(s[e].done){const t=s[e];if(s.splice(e,1),e--,!t.ok)throw c=!0,o.resolve(),t.err;yield t.value,o.resolve()}}for(i.addEventListener("task-complete",()=>{u.resolve()}),Promise.resolve().then(async()=>{try{for await(const t of e){if(s.length===n&&(o=Cd(),await o.promise),c)break;const e={done:!1};s.push(e),t().then(t=>{e.done=!0,e.ok=!0,e.value=t,i.dispatchEvent(new Pm("task-complete"))},t=>{e.done=!0,e.err=t,i.dispatchEvent(new Pm("task-complete"))})}d=!0,i.dispatchEvent(new Pm("task-complete"))}catch(e){a=e,i.dispatchEvent(new Pm("task-complete"))}});;){if(l()||(u=Cd(),await u.promise),null!=a)throw a;if(r?yield*p():yield*h(),null!=a)throw a;if(d&&0===s.length)break}}class Am{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,peer:e.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,key:mr(e,"base36")}),getAttributesFromYieldedValue:(e,t)=>({...t,peers:[...Array.isArray(t.peers)?t.peers:[],e.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new hf("No peer routers available");if(e.toString()===this.peerId.toString())throw new ff("Should not try to find self");const n=this,r=tc(...this.routers.filter(e=>e.findPeer instanceof Function).map(r=>async function*(){try{yield await r.findPeer(e,t)}catch(e){n.log.error("router failed to find peer - %e",e)}}()));for await(const e of r)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs},t),e;throw new nt}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new hf("No peer routers available");const n=this,r=pd(1024);for await(const i of Sm(async function*(){const r=tc(...n.routers.filter(e=>e.getClosestPeers instanceof Function).map(n=>n.getClosestPeers(e,t)));for await(let e of r)yield async()=>{if(0===e.multiaddrs.length)try{e=await n.findPeer(e.id,{...t,useCache:!1})}catch(e){return void n.log.error("could not find peer multiaddrs - %e",e)}return e}}()))null!=i&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),r.has(i.id.toMultihash().bytes)||(r.add(i.id.toMultihash().bytes),yield i))}}class Cm extends Ft{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=Jd([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=Cd();const e=await _d(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]});yield e.detail}}catch(e){if(null!=e.detail)throw e.detail;throw e}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController;const e=Jd([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{const t=io(32);let r=Date.now();for await(const i of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-r,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await $d(this.needNext.promise,e)),r=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,n)}catch(e){this.log.error("random walk errored - %e",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")}).catch(e=>{this.log.error("random walk errored - %e",e)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}}class km{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const e={};for(const[t,n]of this.topologies)e[t]=n.size;return e}}),this.handlers=Ic({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new mf(`No handler registered for protocol ${e}`);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&!0!==n?.force)throw new yf(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:32,maxOutboundStreams:64,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(e=>{this.handlers.delete(e)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(null==t)throw new We("invalid topology");const n=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let r=this.topologies.get(e);return null==r&&(r=new Map,this.topologies.set(e,r)),r.set(n,t),n}unregister(e){for(const[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),0===n.size&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){const t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{const e=await this.components.peerStore.get(t,n);for(const n of e.protocols){const e=this.topologies.get(n);null!=e&&await Promise.all([...e.values()].map(async e=>{null!=e.filter&&!0!==e.filter.has(t)||(e.filter?.remove(t),await(e.onDisconnect?.(t)))}))}}catch(e){if("NotFoundError"===e.name)return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,e)}}async _onPeerUpdate(e){const{peer:t,previous:n}=e.detail,r=(n?.protocols??[]).filter(e=>!t.protocols.includes(e));try{for(const e of r){const n=this.topologies.get(e);null!=n&&await Promise.all([...n.values()].map(async e=>{null!=e.filter&&!0!==e.filter.has(t.id)||(e.filter?.remove(t.id),await(e.onDisconnect?.(t.id)))}))}}catch(e){this.log.error("could not inform topologies of updated peer %p - %e",t.id,e)}}async _onPeerIdentify(e){const t=e.detail.protocols,n=e.detail.connection,r=e.detail.peerId;try{for(const e of t){const t=this.topologies.get(e);null!=t&&await Promise.all([...t.values()].map(async e=>{null!=n.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(r)&&(e.filter?.add(r),await(e.onConnect?.(r,n)))}))}}catch(e){this.log.error("could not inform topologies of updated peer after identify %p - %e",r,e)}}}class Im{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Ic({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ic({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Mt.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new We("Transport must have a valid tag");if(this.transports.has(t))throw new We(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){const t=n.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const n=this.dialTransportForMultiaddr(e);if(null==n)throw new Sf(`No transport available for address ${String(e)}`);return t?.onProgress?.(new _f("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new lt("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(e=>{t.errors.set(e.toString(),new gf)});const n=[];for(const[r,i]of this.transports.entries()){const s=i.listenFilter(e);for(const e of s){this.log("creating listener for %s on %a",r,e);const s=i.createListener({upgrader:this.components.upgrader});let a=this.listeners.get(r)??[];null==a&&(a=[],this.listeners.set(r,a)),a.push(s),s.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:s})}),s.addEventListener("close",()=>{const e=a.findIndex(e=>e===s);a.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:s})}),Mh.matches(e)?t.ipv4.attempts++:Fh.matches(e)&&t.ipv6.attempts++,n.push(s.listen(e).then(()=>{t.errors.delete(e.toString()),Mh.matches(e)&&t.ipv4.success++,Fh.matches(e)&&t.ipv6.success++},n=>{throw this.log.error("transport %s could not listen on address %a - %e",r,e,n),t.errors.set(e.toString(),n),n}))}}const r=await Promise.allSettled(n);if(!(r.length>0&&r.every(e=>"fulfilled"===e.status)))if(this.ipv6Unsupported(t))this.log("all IPv4 addresses succeed but all IPv6 failed");else{if(this.faultTolerance!==Mt.NO_FATAL)throw new vf(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:\n${[...t.errors.entries()].map(([e,t])=>`\n ${e}: ${`${function(e){return null!=e.stack&&""!==e.stack.trim()?e.stack:null!=e.message?e.message:e.toString()}(t)}`.split("\n").join("\n ")}\n`).join("")}`);this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(e){return 0!==e.ipv4.attempts&&0!==e.ipv6.attempts&&e.ipv4.attempts===e.ipv4.success&&0===e.ipv6.success}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&n.push(e.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const Dm="/multistream/1.0.0",Mm=fr("\n");async function Fm(e,t){const n=(await e.read(t)).subarray();if(0===n.byteLength||n[n.length-1]!==Mm[0])throw new ut("Missing newline");return mr(n).trimEnd()}async function Rm(e,t,n={}){if(0===(t=Array.isArray(t)?[...t]:[t]).length)throw new Error("At least one protocol must be specified");const r=e.log.newScope("mss:select"),i=fc(e,{...n,maxDataLength:1024});for(let e=0;e<t.length;e++){const s=t[e];let a;if(0===e){r.trace('write ["%s", "%s"]',Dm,s);const e=fr(`${Dm}\n`),t=fr(`${s}\n`);if(await i.writeV([e,t],n),r.trace("reading multistream-select header"),a=await Fm(i,n),r.trace('read "%s"',a),a!==Dm){r.error("did not read multistream-select header from response");break}}else r.trace('write "%s"',s),await i.write(fr(`${s}\n`),n);if(r.trace("reading protocol response"),a=await Fm(i,n),r.trace('read "%s"',a),a===s)return r.trace('selected "%s" after negotiation',a),i.unwrap(),s}throw new ot(`Protocol selection failed - could not negotiate ${t}`)}async function _m(e,t,n={}){t=Array.isArray(t)?t:[t];const r=e.log.newScope("mss:handle"),i=fc(e,{...n,maxDataLength:1024,maxLengthLength:2});for(;;){r.trace("reading incoming string");const e=await Fm(i,n);if(r.trace('read "%s"',e),e!==Dm){if(t.includes(e))return r.trace('respond with "%s" for "%s"',e,e),await i.write(fr(`${e}\n`),n),r.trace('responded with "%s" for "%s"',e,e),i.unwrap(),e;if("ls"!==e)r.trace('respond with "na" for "%s"',e),await i.write(fr("na\n"),n),r('responded with "na" for "%s"',e);else{const s=new $n(...t.map(e=>Tc.single(fr(`${e}\n`))),fr("\n"));r.trace('respond with "%s" for %s',t,e),await i.write(s,n),r.trace('responded with "%s" for %s',t,e)}}else r.trace('respond with "%s" for "%s"',Dm,e),await i.write(fr(`${Dm}\n`),n),r.trace('responded with "%s" for "%s"',Dm,e)}}class Lm extends Ft{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??qf,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??qf,this.closeTimeout=t.closeTimeout??1e3,this.direct=Bf(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),null==this.remoteAddr.getComponents().find(e=>e.code===eu)&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),null!=t.muxer&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",e=>{this.dispatchEvent(new vt(e.local,e.error))})}[Symbol.toStringTag]="Connection";[ze]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(null==this.muxer)throw new xf("Connection is not multiplexed");if("open"!==this.muxer.status)throw new Ye(`The connection muxer is "${this.muxer.status}" and not "open"`);if("open"!==this.maConn.status)throw new Ye(`The connection is "${this.status}" and not "open"`);if(null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new ft("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);const n=await this.muxer.createStream({...t,protocol:1===e.length?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(null==t.signal){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);const r=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:r}}""===n.protocol?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Rm(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);const r=function(e,t,n={}){try{const{options:n}=t.getHandler(e);if(null!=n.maxOutboundStreams)return n.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return n.maxOutboundStreams??64}(n.protocol,this.components.registrar,t),i=Nm(n.protocol,"outbound",this);if(i>r){const e=new yt(`Too many outbound protocol streams for protocol "${n.protocol}" - ${i}/${r}`);throw n.abort(e),e}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);const s=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,s)}catch(t){throw"open"===n.status?n.abort(t):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===this.direction?"from":"to",this.remoteAddr,e,t),t}};async onIncomingStream(e){const t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(""===t.protocol){const e=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",e),t.protocol=await _m(t,e,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);const e=function(e,t){try{const{options:n}=t.getHandler(e);if(null!=n.maxInboundStreams)return n.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(t.protocol,this.components.registrar);if(Nm(t.protocol,"inbound",this)>e)throw new mt(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${e}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);const{handler:r,options:i}=this.components.registrar.getHandler(t.protocol);if(null!=this.limits&&!0!==i.runOnLimitedConnection)throw new ft("Cannot open protocol stream on limited connection");const s=this.components.registrar.getMiddleware(t.protocol);s.push(async(e,t,n)=>{await r(e,t),n(e,t)}),await this.runMiddlewareChain(t,this,s)}catch(e){t.abort(e)}}async runMiddlewareChain(e,t,n){for(let r=0;r<n.length;r++){const i=n[r];e.log.trace("running middleware",r,i),await new Promise((n,r)=>{try{const s=i(e,t,(r,i)=>{e=r,t=i,n()});s instanceof Promise&&s.catch(r)}catch(e){r(e)}}),e.log.trace("ran middleware",r,i)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),null==e.signal){const t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await(this.muxer?.close(e)),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}}function Nm(e,t,n){let r=0;return n.streams.forEach(n=>{n.direction===t&&n.protocol===e&&r++}),r}class Om{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ic({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(e=>{this.connectionEncrypters.set(e.protocol,e)}),this.streamMuxers=Ic({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(e=>{this.streamMuxers.set(e.protocol,e)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??qf,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??qf,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const n=this.components.connectionGater[e];if(null!=n&&!0===await n.apply(this.components.connectionGater,t))throw new Tf(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){return Jd([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,t){let n=!1;const r=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Ef("Connection denied");await $d(this.shouldBlockConnection("denyInboundConnection",e),r),await this._performUpgrade(e,"inbound",{...t,signal:r})}catch(e){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[e.name??"Error"]:!0}),e}finally{r.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});const n=e.remoteAddr.getComponents().findLast(e=>e.code===eu)?.value;let r;null!=n&&(r=Uo(n),await $d(this.shouldBlockConnection("denyOutboundConnection",r,e),t.signal));let i="outbound";return!1===t.initiator&&(i="inbound"),await this._performUpgrade(e,i,t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[e.name??"Error"]:!0}),e}}async _performUpgrade(e,t,n){let r,i,s,a,o=e;const u=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${u}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),!0!==n?.skipProtection){const r=this.components.connectionProtector;null!=r&&(e.log("protecting the %s connection",t),o=await r.protect(o,n))}try{if(function(e){return!0===e.skipEncryption}(n)){if(null==n.remotePeer)throw new it(`${t} connection that skipped encryption must have a peer id`);a="native",r=n.remotePeer}else{const s=e.remoteAddr.getComponents().findLast(e=>e.code===eu)?.value;let u;null!=s&&(u=Uo(s)),n?.onProgress?.(new _f(`upgrader:encrypt-${t}-connection`)),({connection:o,remotePeer:r,protocol:a,streamMuxer:i}=await("inbound"===t?this._encryptInbound(o,{...n,remotePeer:u}):this._encryptOutbound(o,{...n,remotePeer:u})))}if(r.equals(this.components.peerId)){const t=new rt("Can not dial self");throw e.abort(t),t}await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",r,e),null!=n?.muxerFactory?i=n.muxerFactory:null==i&&this.streamMuxers.size>0&&(n?.onProgress?.(new _f(`upgrader:multiplex-${t}-connection`)),i=await("inbound"===t?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(n){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,"inbound"===t?"from":"to",e.remoteAddr,n),n}null!=i&&(e.log("create muxer %s",i.protocol),s=i.createStreamMuxer(o)),await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",r,e);const d=this._createConnection({id:u,cryptoProtocol:a,direction:t,maConn:e,stream:o,muxer:s,remotePeer:r,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return d.log("successfully upgraded connection"),d}_createConnection(e){const t=(n={...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout},new Lm(this.components,n));var n;return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){const n=Array.from(this.connectionEncrypters.keys());try{const r=await _m(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new Pf(`no crypto module found for ${r}`);return e.log("encrypting inbound connection using %s",r),{...await i.secureInbound(e,t),protocol:r}}catch(e){throw new Pf(e.message)}}async _encryptOutbound(e,t){const n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);const r=await Rm(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new Pf(`no crypto module found for ${r}`);return e.log("encrypting outbound connection using %s",r),{...await i.secureOutbound(e,t),protocol:r}}catch(e){throw new Pf(e.message)}}async _multiplexOutbound(e,t,n){const r=Array.from(t.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);const i=await Rm(e,r,n),s=t.get(i);if(null==s)throw new xf(`No muxer configured for protocol "${i}"`);return e.log("selected %s as muxer protocol",i),s}catch(t){throw e.log.error("error multiplexing outbound connection - %e",t),new xf(String(t))}}async _multiplexInbound(e,t,n){const r=Array.from(t.keys());e.log("inbound handling muxers %s",r);try{e.log.trace("selecting stream muxer from %s",r);const i=await _m(e,r,n),s=t.get(i);if(null==s)throw new xf(`No muxer configured for protocol "${i}"`);return e.log("selected %s as muxer protocol",i),s}catch(t){throw e.log.error("error multiplexing inbound connection - %e",t),t}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const Bm="3.1.6",Um="js-libp2p";class jm extends Ft{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Ft,n=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=n(e),r=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||r},this.peerId=e.peerId,this.logger=e.logger??Wu(),this.log=this.logger.forComponent("libp2p"),this.services={};const r=e.nodeInfo?.name??Um,i=e.nodeInfo?.version??Bm,s=this.components=function(e={}){const t=new Cf(e),n=new Proxy(t,{get(e,n,r){if("string"==typeof n&&!If.includes(n)){const e=t.components[n];if(null==e&&!kf.includes(n))throw new cf(`${n} not set`);return e}return Reflect.get(e,n,r)},set:(e,n,r)=>("string"==typeof n?t.components[n]=r:Reflect.set(e,n,r),!0)});return n}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:r,version:i,userAgent:e.nodeInfo?.userAgent??(a=r,o=i,`${a??Um}/${o??Bm} browser/${globalThis.navigator.userAgent}`)},logger:this.logger,events:t,datastore:e.datastore??new fh,connectionGater:Rf(e.connectionGater),dns:e.dns});var a,o;null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new ah(e,t)}(s,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),s.events.addEventListener("peer:update",e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map(e=>e.multiaddr)};s.events.safeDispatchEvent("peer:discovery",{detail:t})}}),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(s)),this.components.upgrader=new Om(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components))),streamMuxers:(e.streamMuxers??[]).map((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Im(this.components,e.transportManager)),this.configureComponent("connectionManager",new Tm(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Em(this.components,e.connectionMonitor)),this.configureComponent("registrar",new km(this.components)),this.configureComponent("addressManager",new uf(this.components,e.addresses));const u=(e.peerRouters??[]).map((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Am(this.components,{routers:u}));const d=(e.contentRouters??[]).map((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new xm(this.components,{routers:d})),this.configureComponent("randomWalk",new Cm(this.components)),(e.peerDiscovery??[]).forEach((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",e=>{this.#Y(e)})}),e.transports?.forEach((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))}),null!=e.services)for(const t of Object.keys(e.services)){const n=(0,e.services[t])(this.components);null!=n?(this.services[t]=n,this.configureComponent(t,n),null!=n[Ve]&&(this.log("registering service %s for content routing",t),d.push(n[Ve])),null!=n[St]&&(this.log("registering service %s for peer routing",t),u.push(n[St])),null!=n[Et]&&(this.log("registering service %s for peer discovery",t),n[Et].addEventListener?.("peer",e=>{this.#Y(e)}))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const n of Object.values(e.components))for(const e of Df(n))t[e]=!0;for(const n of Object.values(e.components))for(const e of Mf(n))if(!0!==t[e])throw new lf(`Service "${Ff(n)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(s)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new ed;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(null==t)throw new We("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new We("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){xu(e)&&(e=Uo(e.getComponents().findLast(e=>e.code===eu)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const n=await this.peerStore.get(e,t);if(null!=n.id.publicKey)return n.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const n=Bn([fr("/pk/"),e.toMultihash().bytes]),r=Mo(await this.contentRouting.get(n,t));return await this.peerStore.patch(e,{publicKey:r},t),r}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.handle(e,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.unhandle(e,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#Y(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(e=>{this.log.error("could not update multiaddrs of discovered peer - %e",e)}):this.log.error("peer discovery mechanism discovered self")}}const qm=65535,$m=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function zm(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Vm(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Gm(e,t,n=""){const r=function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e),i=e?.length,s=void 0!==t;if(!r||s&&i!==t)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e));return e}function Km(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Hm(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Wm(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Qm=/* @__PURE__ */(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])(),Ym=(e,t)=>{function n(n,...r){if(Gm(n,void 0,"key"),!Qm)throw new Error("Non little-endian hardware is not yet supported");void 0!==e.nonceLength&&Gm(r[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");const i=e.tagLength;i&&void 0!==r[1]&&Gm(r[1],void 0,"AAD");const s=t(n,...r),a=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Gm(t,void 0,"output")}};let o=!1;return{encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Gm(e),a(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(Gm(e),i&&e.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(n,e),n};function Jm(e,t,n=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(n&&t.byteOffset%4!=0)throw new Error("invalid output, must be aligned");return t}function Zm(e){return Uint8Array.from(e)}const Xm=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),ey=Xm("expand 16-byte k"),ty=Xm("expand 32-byte k"),ny=Hm(ey),ry=Hm(ty);function iy(e,t){return e<<t|e>>>32-t}function sy(e){return e.byteOffset%4==0}const ay=2**32-1,oy=Uint32Array.of();function uy(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:a}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Vm(i),Vm(a),zm(s),zm(n),(t,o,u,d,c=0)=>{Gm(t,void 0,"key"),Gm(o,void 0,"nonce"),Gm(u,void 0,"data");const l=u.length;if(void 0===d&&(d=new Uint8Array(l)),Gm(d,void 0,"output"),Vm(c),c<0||c>=ay)throw new Error("arx: counter overflow");if(d.length<l)throw new Error(`arx: output (${d.length}) is shorter than data (${l})`);const p=[];let h,f,m=t.length;if(32===m)p.push(h=Zm(t)),f=ry;else{if(16!==m||!n)throw Gm(t,32,"arx key"),new Error("invalid key size");h=new Uint8Array(32),h.set(t),h.set(t,16),f=ny,p.push(h)}sy(o)||p.push(o=Zm(o));const y=Hm(h);if(r){if(24!==o.length)throw new Error("arx: extended nonce must be 24 bytes");r(f,y,Hm(o.subarray(0,16)),y),o=o.subarray(16)}const b=16-i;if(b!==o.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(12!==b){const e=new Uint8Array(12);e.set(o,s?0:12-o.length),p.push(o=e)}const g=Hm(o);return function(e,t,n,r,i,s,a,o){const u=i.length,d=new Uint8Array(64),c=Hm(d),l=sy(i)&&sy(s),p=l?Hm(i):oy,h=l?Hm(s):oy;for(let f=0;f<u;a++){if(e(t,n,r,c,a,o),a>=ay)throw new Error("arx: counter overflow");const m=Math.min(64,u-f);if(l&&64===m){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,n=0;n<16;n++)t=e+n,h[t]=p[t]^c[n];f+=64}else{for(let e,t=0;t<m;t++)e=f+t,s[e]=i[e]^d[t];f+=m}}}(e,f,y,g,u,d,c,a),Wm(...p),d}}function dy(e,t){return 255&e[t++]|(255&e[t++])<<8}class cy{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){const t=dy(e=Zm(Gm(e,32,"key")),0),n=dy(e,2),r=dy(e,4),i=dy(e,6),s=dy(e,8),a=dy(e,10),o=dy(e,12),u=dy(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|n<<3),this.r[2]=7939&(n>>>10|r<<6),this.r[3]=8191&(r>>>7|i<<9),this.r[4]=255&(i>>>4|s<<12),this.r[5]=s>>>1&8190,this.r[6]=8191&(s>>>14|a<<2),this.r[7]=8065&(a>>>11|o<<5),this.r[8]=8191&(o>>>8|u<<8),this.r[9]=u>>>5&127;for(let t=0;t<8;t++)this.pad[t]=dy(e,16+2*t)}process(e,t,n=!1){const r=n?0:2048,{h:i,r:s}=this,a=s[0],o=s[1],u=s[2],d=s[3],c=s[4],l=s[5],p=s[6],h=s[7],f=s[8],m=s[9],y=dy(e,t+0),b=dy(e,t+2),g=dy(e,t+4),v=dy(e,t+6),w=dy(e,t+8),T=dy(e,t+10),E=dy(e,t+12),x=dy(e,t+14);let P=i[0]+(8191&y),S=i[1]+(8191&(y>>>13|b<<3)),A=i[2]+(8191&(b>>>10|g<<6)),C=i[3]+(8191&(g>>>7|v<<9)),k=i[4]+(8191&(v>>>4|w<<12)),I=i[5]+(w>>>1&8191),D=i[6]+(8191&(w>>>14|T<<2)),M=i[7]+(8191&(T>>>11|E<<5)),F=i[8]+(8191&(E>>>8|x<<8)),R=i[9]+(x>>>5|r),_=0,L=_+P*a+S*(5*m)+A*(5*f)+C*(5*h)+k*(5*p);_=L>>>13,L&=8191,L+=I*(5*l)+D*(5*c)+M*(5*d)+F*(5*u)+R*(5*o),_+=L>>>13,L&=8191;let N=_+P*o+S*a+A*(5*m)+C*(5*f)+k*(5*h);_=N>>>13,N&=8191,N+=I*(5*p)+D*(5*l)+M*(5*c)+F*(5*d)+R*(5*u),_+=N>>>13,N&=8191;let O=_+P*u+S*o+A*a+C*(5*m)+k*(5*f);_=O>>>13,O&=8191,O+=I*(5*h)+D*(5*p)+M*(5*l)+F*(5*c)+R*(5*d),_+=O>>>13,O&=8191;let B=_+P*d+S*u+A*o+C*a+k*(5*m);_=B>>>13,B&=8191,B+=I*(5*f)+D*(5*h)+M*(5*p)+F*(5*l)+R*(5*c),_+=B>>>13,B&=8191;let U=_+P*c+S*d+A*u+C*o+k*a;_=U>>>13,U&=8191,U+=I*(5*m)+D*(5*f)+M*(5*h)+F*(5*p)+R*(5*l),_+=U>>>13,U&=8191;let j=_+P*l+S*c+A*d+C*u+k*o;_=j>>>13,j&=8191,j+=I*a+D*(5*m)+M*(5*f)+F*(5*h)+R*(5*p),_+=j>>>13,j&=8191;let q=_+P*p+S*l+A*c+C*d+k*u;_=q>>>13,q&=8191,q+=I*o+D*a+M*(5*m)+F*(5*f)+R*(5*h),_+=q>>>13,q&=8191;let $=_+P*h+S*p+A*l+C*c+k*d;_=$>>>13,$&=8191,$+=I*u+D*o+M*a+F*(5*m)+R*(5*f),_+=$>>>13,$&=8191;let z=_+P*f+S*h+A*p+C*l+k*c;_=z>>>13,z&=8191,z+=I*d+D*u+M*o+F*a+R*(5*m),_+=z>>>13,z&=8191;let V=_+P*m+S*f+A*h+C*p+k*l;_=V>>>13,V&=8191,V+=I*c+D*d+M*u+F*o+R*a,_+=V>>>13,V&=8191,_=(_<<2)+_|0,_=_+L|0,L=8191&_,_>>>=13,N+=_,i[0]=L,i[1]=N,i[2]=O,i[3]=B,i[4]=U,i[5]=j,i[6]=q,i[7]=$,i[8]=z,i[9]=V}finalize(){const{h:e,pad:t}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=5*r,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(1^r)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let s=e[0]+t[0];e[0]=65535&s;for(let n=1;n<8;n++)s=(e[n]+t[n]|0)+(s>>>16)|0,e[n]=65535&s;Wm(n)}update(e){Km(this),Gm(e),e=Zm(e);const{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const s=Math.min(n-this.pos,r-i);if(s!==n)t.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(t,0,!1),this.pos=0);else for(;n<=r-i;i+=n)this.process(e,i)}return this}destroy(){Wm(this.h,this.r,this.buffer,this.pad)}digestInto(e){Km(this),function(e,t){Gm(e,void 0,"output");const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,h:n}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}}const ly=/** @__PURE__ */(()=>function(e){const t=(t,n)=>e(n).update(t).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}(e=>new cy(e)))();function py(e,t,n,r,i,s=20){let a=e[0],o=e[1],u=e[2],d=e[3],c=t[0],l=t[1],p=t[2],h=t[3],f=t[4],m=t[5],y=t[6],b=t[7],g=i,v=n[0],w=n[1],T=n[2],E=a,x=o,P=u,S=d,A=c,C=l,k=p,I=h,D=f,M=m,F=y,R=b,_=g,L=v,N=w,O=T;for(let e=0;e<s;e+=2)E=E+A|0,_=iy(_^E,16),D=D+_|0,A=iy(A^D,12),E=E+A|0,_=iy(_^E,8),D=D+_|0,A=iy(A^D,7),x=x+C|0,L=iy(L^x,16),M=M+L|0,C=iy(C^M,12),x=x+C|0,L=iy(L^x,8),M=M+L|0,C=iy(C^M,7),P=P+k|0,N=iy(N^P,16),F=F+N|0,k=iy(k^F,12),P=P+k|0,N=iy(N^P,8),F=F+N|0,k=iy(k^F,7),S=S+I|0,O=iy(O^S,16),R=R+O|0,I=iy(I^R,12),S=S+I|0,O=iy(O^S,8),R=R+O|0,I=iy(I^R,7),E=E+C|0,O=iy(O^E,16),F=F+O|0,C=iy(C^F,12),E=E+C|0,O=iy(O^E,8),F=F+O|0,C=iy(C^F,7),x=x+k|0,_=iy(_^x,16),R=R+_|0,k=iy(k^R,12),x=x+k|0,_=iy(_^x,8),R=R+_|0,k=iy(k^R,7),P=P+I|0,L=iy(L^P,16),D=D+L|0,I=iy(I^D,12),P=P+I|0,L=iy(L^P,8),D=D+L|0,I=iy(I^D,7),S=S+A|0,N=iy(N^S,16),M=M+N|0,A=iy(A^M,12),S=S+A|0,N=iy(N^S,8),M=M+N|0,A=iy(A^M,7);let B=0;r[B++]=a+E|0,r[B++]=o+x|0,r[B++]=u+P|0,r[B++]=d+S|0,r[B++]=c+A|0,r[B++]=l+C|0,r[B++]=p+k|0,r[B++]=h+I|0,r[B++]=f+D|0,r[B++]=m+M|0,r[B++]=y+F|0,r[B++]=b+R|0,r[B++]=g+_|0,r[B++]=v+L|0,r[B++]=w+N|0,r[B++]=T+O|0}const hy=/* @__PURE__ */uy(py,{counterRight:!1,counterLength:4,allowShortKeys:!1}),fy=/* @__PURE__ */new Uint8Array(16),my=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(fy.subarray(n))},yy=/* @__PURE__ */new Uint8Array(32);function by(e,t,n,r,i){void 0!==i&&Gm(i,void 0,"AAD");const s=e(t,n,yy),a=function(e,t,n){zm(n);const r=new Uint8Array(16),i=(s=r,new DataView(s.buffer,s.byteOffset,s.byteLength));var s;return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}(r.length,i?i.length:0,!0),o=ly.create(s);i&&my(o,i),my(o,r),o.update(a);const u=o.digest();return Wm(s,a),u}const gy=/* @__PURE__ */Ym({blockSize:64,nonceLength:12,tagLength:16},(vy=hy,(e,t,n)=>({encrypt(r,i){const s=r.length;(i=Jm(s+16,i,!1)).set(r);const a=i.subarray(0,-16);vy(e,t,a,a,1);const o=by(vy,e,t,a,n);return i.set(o,s),Wm(o),i},decrypt(r,i){i=Jm(r.length-16,i,!1);const s=r.subarray(0,-16),a=r.subarray(-16),o=by(vy,e,t,s,n);if(!function(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(a,o))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),vy(e,t,i,i,1),Wm(o),i}})));var vy;function wy(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Ty(e,t,n=""){const r=function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e),i=e?.length,s=void 0!==t;if(!r||s&&i!==t)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e));return e}function Ey(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");wy(e.outputLen),wy(e.blockLen)}function xy(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Py(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Sy(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ay(e,t){return e<<32-t|e>>>t}const Cy=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),ky=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Iy(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Dy(e,t={}){const n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}function My(e=32){const t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}const Fy=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ry(e,t,n){return e&t^~e&n}function _y(e,t,n){return e&t^e&n^t&n}class Ly{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Sy(this.buffer)}update(e){xy(this),Ty(e);const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const a=Math.min(r-this.pos,i-s);if(a!==r)n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=Sy(e);for(;r<=i-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){xy(this),function(e,t){Ty(e,void 0,"digestInto() output");const n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;t[s++]=128,Py(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(8*this.length),i),this.process(n,0);const a=Sy(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=o/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<u;e++)a.setUint32(4*e,d[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=a,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Ny=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oy=/* @__PURE__ */Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),By=/* @__PURE__ */new Uint32Array(64);class Uy extends Ly{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:a,H:o}=this;return[e,t,n,r,i,s,a,o]}set(e,t,n,r,i,s,a,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|a,this.H=0|o}process(e,t){for(let n=0;n<16;n++,t+=4)By[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=By[e-15],n=By[e-2],r=Ay(t,7)^Ay(t,18)^t>>>3,i=Ay(n,17)^Ay(n,19)^n>>>10;By[e]=i+By[e-7]+r+By[e-16]|0}let{A:n,B:r,C:i,D:s,E:a,F:o,G:u,H:d}=this;for(let e=0;e<64;e++){const t=d+(Ay(a,6)^Ay(a,11)^Ay(a,25))+Ry(a,o,u)+Oy[e]+By[e]|0,c=(Ay(n,2)^Ay(n,13)^Ay(n,22))+_y(n,r,i)|0;d=u,u=o,o=a,a=s+t|0,s=i,i=r,r=n,n=t+c|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,r,i,s,a,o,u,d)}roundClean(){Py(By)}destroy(){this.set(0,0,0,0,0,0,0,0),Py(this.buffer)}}class jy extends Uy{A=0|Ny[0];B=0|Ny[1];C=0|Ny[2];D=0|Ny[3];E=0|Ny[4];F=0|Ny[5];G=0|Ny[6];H=0|Ny[7];constructor(){super(32)}}const qy=/* @__PURE__ */Dy(()=>new jy
|
|
4
|
-
/* @__PURE__ */,Fy(1)),$y=/* @__PURE__ */BigInt(0);function zy(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?$y:BigInt("0x"+e)}(function(e){if(Ty(e),Cy)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ky[e[n]];return t}(Vy(Ty(e)).reverse()))}function Vy(e){return Uint8Array.from(e)}const Gy=e=>"bigint"==typeof e&&$y<=e;function Ky(e,t,n,r){if(!function(e,t,n){return Gy(e)&&Gy(t)&&Gy(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const Hy=/* @__PURE__ */BigInt(0);function Wy(e,t){const n=e%t;return n>=Hy?n:t+n}function Qy(e,t,n){let r=e;for(;t-- >Hy;)r*=r,r%=n;return r}function Yy(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}new WeakMap,new WeakMap,BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Jy=BigInt(0),Zy=BigInt(1),Xy=BigInt(2),eb=BigInt(1),tb=BigInt(2),nb=/* @__PURE__ */BigInt(3),rb=BigInt(5),ib=(BigInt(8),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"));function sb(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const ab=/* @__PURE__ */(()=>{const e=ib;return function(e){const t=(function(e,t={},n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");const r=(t,n)=>Object.entries(t).forEach(([t,r])=>function(t,n,r){const i=e[t];if(r&&void 0===i)return;const s=typeof i;if(s!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${s}`)}(t,r,n));r(t,!1),r(n,!0)}(n=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...n}));var n;const{P:r,type:i,adjustScalarBytes:s,powPminus2:a,randomBytes:o}=t,u="x25519"===i;if(!u&&"x448"!==i)throw new Error("invalid type");const d=o||My,c=u?255:448,l=u?32:56,p=u?BigInt(9):BigInt(5),h=u?BigInt(121665):BigInt(39081),f=u?Xy**BigInt(254):Xy**BigInt(447),m=u?BigInt(8)*Xy**BigInt(251)-Zy:BigInt(4)*Xy**BigInt(445)-Zy,y=f+m+Zy,b=e=>Wy(e,r),g=v(p);function v(e){return function(e,t){return function(e,t){wy(t);const n=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Cy)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=Iy(e.charCodeAt(i)),s=Iy(e.charCodeAt(i+1));if(void 0===n||void 0===s)throw new Error('hex string expected, got non-hex character "'+(e[i]+e[i+1])+'" at index '+i);r[t]=16*n+s}return r}((e=function(e){if("bigint"==typeof e){if(!Gy(e))throw new Error("positive bigint expected, got "+e)}else wy(e);return e}(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}(e,t).reverse()}(b(e),l)}function w(e,t){const n=function(e,t){Ky("u",e,Jy,r),Ky("scalar",t,f,y);const n=t,i=e;let s=Zy,o=Jy,u=e,d=Zy,l=Jy;for(let e=BigInt(c-1);e>=Jy;e--){const t=n>>e&Zy;l^=t,({x_2:s,x_3:u}=P(l,s,u)),({x_2:o,x_3:d}=P(l,o,d)),l=t;const r=s+o,a=b(r*r),c=s-o,p=b(c*c),f=a-p,m=u+d,y=b((u-d)*r),g=b(m*c),v=y+g,w=y-g;u=b(v*v),d=b(i*b(w*w)),s=b(a*p),o=b(f*(a+b(h*f)))}({x_2:s,x_3:u}=P(l,s,u)),({x_2:o,x_3:d}=P(l,o,d));const p=a(o);return b(s*p)}(function(e){const t=Vy(Ty(e,l,"uCoordinate"));return u&&(t[31]&=127),b(zy(t))}(t),function(e){return zy(s(Vy(Ty(e,l,"scalar"))))}(e));if(n===Jy)throw new Error("invalid private or public key received");return v(n)}function T(e){return w(e,g)}const E=T,x=w;function P(e,t,n){const r=b(e*(t-n));return{x_2:t=b(t-r),x_3:n=b(n+r)}}const S={secretKey:l,publicKey:l,seed:l},A=(e=d(l))=>(Ty(e,S.seed,"seed"),e),C={randomSecretKey:A};return Object.freeze({keygen:Yy(A,E),getSharedSecret:x,getPublicKey:E,scalarMult:w,scalarMultBase:T,utils:C,GuBytes:g.slice(),lengths:S})}({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:n,b2:r}=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=ib,a=e*e%s*e%s,o=Qy(a,tb,s)*a%s,u=Qy(o,eb,s)*e%s,d=Qy(u,rb,s)*u%s,c=Qy(d,t,s)*d%s,l=Qy(c,n,s)*c%s,p=Qy(l,r,s)*l%s,h=Qy(p,i,s)*p%s,f=Qy(h,i,s)*p%s,m=Qy(f,t,s)*d%s;return{pow_p_5_8:Qy(m,tb,s)*e%s,b2:a}}(t);return Wy(Qy(n,nb,e)*r,e)},adjustScalarBytes:sb})})();class ob{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ey(e),Ty(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Py(r)}update(e){return xy(this),this.iHash.update(e),this}digestInto(e){xy(this),Ty(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:s,outputLen:a}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ub=(e,t,n)=>new ob(e,t).update(n).digest();ub.create=(e,t)=>new ob(e,t);const db=/* @__PURE__ */Uint8Array.of(0),cb=/* @__PURE__ */Uint8Array.of(),lb={hashSHA256:e=>qy(e.subarray()),getHKDF(e,t){const n=function(e,t,n){return Ey(e),void 0===n&&(n=new Uint8Array(e.outputLen)),ub(e,n,t)}(qy,t,e),r=function(e,t,n,r=32){Ey(e),wy(r,"length");const i=e.outputLen;if(r>255*i)throw new Error("Length must be <= 255*HashLen");const s=Math.ceil(r/i);void 0===n?n=cb:Ty(n,void 0,"info");const a=new Uint8Array(s*i),o=ub.create(e,t),u=o._cloneInto(),d=new Uint8Array(o.outputLen);for(let e=0;e<s;e++)db[0]=e+1,u.update(0===e?cb:d).update(n).update(db).digestInto(d),a.set(d,i*e),o._cloneInto(u);return o.destroy(),u.destroy(),Py(d,db),a.slice(0,r)}(qy,n,void 0,96),i=r;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){const e=ab.utils.randomSecretKey();return{publicKey:ab.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:ab.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>ab.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,n,r)=>gy(r,t,n).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,n,r,i)=>gy(r,t,n).decrypt(e.subarray(),i)},pb=lb,hb=e=>{const t=On(2);return t[0]=e>>8,t[1]=e,t};hb.bytes=2;const fb=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function mb(e,t){t.enabled&&$m&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${mr(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${mr(e.privateKey,"hex")}`)):t("Missing local static keys."))}function yb(e,t){t.enabled&&$m&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${mr(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${mr(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function bb(e,t){t.enabled&&$m&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${mr(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function gb(e,t,n){n.enabled&&$m&&(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&mr(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&mr(t.k,"hex")}`))}function vb(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");const n=On(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}fb.bytes=2;class wb extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=wb.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Tb{n;bytes;view;constructor(e=0){this.n=e,this.bytes=Nn(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const Eb=Nn(0);class xb{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Tb(n)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),r}}class Pb{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const n=fr(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=Nn(32);return e.set(t),e}return e.hash(t)}(e,n),this.ck=this.h,this.cs=new xb(e)}mixKey(e){const[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new xb(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new $n(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,Eb);return[new xb(this.crypto,e),new xb(this.crypto,t)]}}class Sb{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:n,prologue:r,initiator:i,s:s,e:a,rs:o,re:u}=e;this.crypto=t,this.ss=new Pb(t,n),this.ss.mixHash(r),this.initiator=i,this.s=s,this.e=a,this.rs=o,this.re=u}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");const n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");const r=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(r),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Ab extends Sb{writeMessageA(e){return new $n(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new $n(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new $n(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new wb(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new wb(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new wb(`handshake stage 2 validation fail: ${e.message}`)}}}var Cb,kb,Ib,Db,Mb;async function Fb(e,t,n){const r=await e.sign(_b(t));return kb.encode({identityKey:Fo(e.publicKey),identitySig:r,extensions:n})}async function Rb(e,t,n){try{const r=kb.decode(e),i=Mo(r.identityKey);if(!1===n?.equals(i))throw new Error(`Payload identity key ${i} does not match expected remote identity key ${n}`);if(!t)throw new Error("Remote static does not exist");const s=_b(t);if(!await i.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(e){throw new Ke(e.message)}}function _b(e){const t=fr("noise-libp2p-static-key:");return e instanceof Uint8Array?Bn([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const n of e.webtransportCerthashes)t.uint32(10),t.bytes(n);if(null!=e.streamMuxers)for(const n of e.streamMuxers)t.uint32(18),t.string(n);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={webtransportCerthashes:[],streamMuxers:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:if(null!=n.limits?.webtransportCerthashes&&r.webtransportCerthashes.length===n.limits.webtransportCerthashes)throw new Bp('Decode error - map field "webtransportCerthashes" had too many elements');r.webtransportCerthashes.push(e.bytes());break;case 2:if(null!=n.limits?.streamMuxers&&r.streamMuxers.length===n.limits.streamMuxers)throw new Bp('Decode error - map field "streamMuxers" had too many elements');r.streamMuxers.push(e.string());break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Cb||(Cb={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),Cb.codec().encode(e.extensions,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={identityKey:Nn(0),identitySig:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=Cb.codec().decode(e,e.uint32(),{limits:n.limits?.extensions});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(kb||(kb={}));class Lb extends Hd{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new yc({lengthDecoder:fb,maxBufferSize:16777216,encodingLength:()=>2}),this.stream.addEventListener("message",e=>{try{for(const t of this.decoder.decode(e.data))this.onData(this.decrypt(t))}catch(e){this.abort(e)}}),this.stream.addEventListener("close",e=>{null!=e.error?!0===e.local?this.abort(e.error):this.onRemoteReset():this.onTransportClosed()}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")}),this.stream.addEventListener("remoteCloseWrite",()=>{this.onRemoteCloseWrite()})}encrypt(e){const t=new $n;for(let n=0;n<e.byteLength;n+=65519){let r,i=n+65519;i>e.byteLength&&(i=e.byteLength),r=e instanceof Uint8Array?this.handshake.encrypt(e.subarray(n,i)):this.handshake.encrypt(e.sublist(n,i)),this.metrics?.encryptedPackets.increment(),t.append(hb(r.byteLength)),t.append(r)}return t}decrypt(e){const t=new $n;for(let n=0;n<e.byteLength;n+=qm){let r,i=n+qm;if(i>e.byteLength&&(i=e.byteLength),i-16<n)throw new Error("Invalid chunk");r=e instanceof Uint8Array?e.subarray(n,i):e.sublist(n,i);const s=e.subarray(n,i-16);try{const e=this.handshake.decrypt(r,s);this.metrics?.decryptedPackets.increment(),t.append(e)}catch(e){throw this.metrics?.decryptErrors.increment(),e}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function Nb(e,t,n){return new Lb(e,t,n)}class Ob{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){const{staticNoiseKey:n,extensions:r,crypto:i,prologueBytes:s}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const o=i??pb;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,n)=>e.generateX25519SharedKey(t.privateKey,n).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(o),this.extensions={webtransportCerthashes:[],...r},this.metrics=a?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(a):void 0,this.staticKey=n?o.generateX25519KeyPairFromSeed(n):o.generateX25519KeyPair(),this.prologue=s??Nn(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Rt]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const n=e.log?.newScope("noise")??this.log,r=fc(e,{lengthEncoder:hb,lengthDecoder:fb,maxDataLength:qm}),i=await this.performHandshakeInitiator(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Mo(i.payload.identityKey);return{connection:Nb(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:jo(s),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(null==e||0===e.length)return;const t=this.components.upgrader.getStreamMuxers();if(null!=t)for(const n of e){const e=t.get(n);if(null!=e)return e}if(e.length)throw new He("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){const n=e.log?.newScope("noise")??this.log,r=fc(e,{lengthEncoder:hb,lengthDecoder:fb,maxDataLength:qm}),i=await this.performHandshakeResponder(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Mo(i.payload.identityKey);return{connection:Nb(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:jo(s),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,r,i){let s;const a=!0===i?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:n,connection:r,crypto:i,privateKey:s,prologue:a,s:o,remoteIdentityKey:u,extensions:d}=e,c=await Fb(s,o.publicKey,d),l=new Ab({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:a,s:o});mb(l.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(l.writeMessageA(Eb),t),n.trace("Stage 0 - Initiator finished sending first message."),yb(l.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const p=l.readMessageB(await r.read(t));var h,f;n.trace("Stage 1 - Initiator received the message."),bb(l.re,n),h=l.rs,(f=n).enabled&&$m&&f(h?`REMOTE_STATIC_PUBLIC_KEY ${mr(h.subarray(),"hex")}`:"Missing remote static public key."),n.trace("Initiator going to check remote's signature...");const m=await Rb(p,l.rs,u);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(l.writeMessageC(c),t),n.trace("Stage 2 - Initiator sent message with signed payload.");const[y,b]=l.ss.split();return gb(y,b,n),{payload:m,encrypt:e=>y.encryptWithAd(Eb,e),decrypt:(e,t)=>b.decryptWithAd(Eb,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,n,r,i){let s;const a=!0===i?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:n,connection:r,crypto:i,privateKey:s,prologue:a,s:o,remoteIdentityKey:u,extensions:d}=e,c=await Fb(s,o.publicKey,d),l=new Ab({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:a,s:o});mb(l.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await r.read(t)),n.trace("Stage 0 - Responder received first message."),bb(l.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(l.writeMessageB(c),t),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),yb(l.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const p=l.readMessageC(await r.read(t));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await Rb(p,l.rs,u),[f,m]=l.ss.split();return gb(f,m,n),{payload:h,encrypt:e=>m.encryptWithAd(Eb,e),decrypt:(e,t)=>f.decryptWithAd(Eb,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}}function Bb(e={}){return t=>new Ob(t,e)}!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(Ib||(Ib={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(Db||(Db={})),Object.values(Db).filter(e=>"string"!=typeof e),function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(Mb||(Mb={}));const Ub=12;class jb extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}}class qb extends jb{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Mb.ProtocolError),this.name="InvalidFrameError"}}class $b extends jb{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Mb.ProtocolError),this.name="UnRequestedPingError"}}class zb extends jb{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Mb.ProtocolError),this.name="NotMatchingPingError"}}class Vb extends jb{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Mb.ProtocolError),this.name="ReceiveWindowExceededError"}}const Gb=262144,Kb=2**24;class Hb{buffer;constructor(){this.buffer=new $n}*emitFrames(e){for(this.buffer.append(e);;){const e=this.readFrame();if(void 0===e)break;yield e}}readFrame(){let e=Ub;if(this.buffer.byteLength<Ub)return;const t=function(e){if(0!==e[0])throw new qb("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*Kb+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*Kb+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,Ub));if(t.type===Ib.Data){if(e+=t.length,this.buffer.byteLength<e)return;const n=this.buffer.sublist(Ub,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}}function Wb(e){const t=new Uint8Array(Ub);return t[1]=e.type,t[2]=e.flag>>>8,t[3]=e.flag,t[4]=e.streamID>>>24,t[5]=e.streamID>>>16,t[6]=e.streamID>>>8,t[7]=e.streamID,t[8]=e.length>>>24,t[9]=e.length>>>16,t[10]=e.length>>>8,t[11]=e.length,t}var Qb;!function(e){e[e.Init=0]="Init",e[e.SYNSent=1]="SYNSent",e[e.SYNReceived=2]="SYNReceived",e[e.Established=3]="Established",e[e.Finished=4]="Finished",e[e.Paused=5]="Paused"}(Qb||(Qb={}));class Yb extends Yd{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){const t=e.initialStreamWindowSize??Gb;super({...e,maxMessageSize:t-Ub}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??16777216,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame,this.addEventListener("close",()=>{this.state=Qb.Finished})}sendData(e){const t=e.byteLength;let n=0,r=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(0===this.sendWindowCapacity){r=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}const i=Math.min(this.sendWindowCapacity,e.byteLength),s=this.getSendFlags(),a=e.sublist(0,i);e.consume(i);const o=this.sendFrame({type:Ib.Data,flag:s,streamID:this.streamId,length:i},a);if(this.sendWindowCapacity-=i,n+=i,!o){r=o,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:r}}sendReset(){this.sendFrame({type:Ib.WindowUpdate,flag:Db.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){const e=this.getSendFlags()|Db.FIN;this.sendFrame({type:Ib.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Qb.Paused}sendResume(){this.state=Qb.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-Ub,this.maxMessageSize<0&&(this.maxMessageSize=0),0!==this.maxMessageSize&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!function(e){return e.header.type===Ib.Data&&null!==e.data}(e))throw new qb("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Vb("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&Db.ACK)===Db.ACK&&this.state===Qb.SYNSent&&(this.state=Qb.Established),(e&Db.FIN)===Db.FIN&&this.onRemoteCloseWrite(),(e&Db.RST)===Db.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Qb.Init:return this.state=Qb.SYNSent,Db.SYN;case Qb.SYNReceived:return this.state=Qb.Established,Db.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Qb.Paused)return void(this.epochStart=Date.now());const e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(0===e&&n>-1&&t-this.epochStart<=4*n&&(this.recvWindow=Math.min(2*this.recvWindow,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&0===e)return;const r=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Ib.WindowUpdate,flag:e,streamID:this.streamId,length:r})}}function Jb(e){return{type:Ib[e.type],flags:[(e.flag&Db.SYN)===Db.SYN?"SYN":void 0,(e.flag&Db.ACK)===Db.ACK?"ACK":void 0,(e.flag&Db.FIN)===Db.FIN?"FIN":void 0,(e.flag&Db.RST)===Db.RST?"RST":void 0].filter(Boolean),streamID:e.streamID,length:e.length}}const Zb="/yamux/1.0.0";class Xb{protocol=Zb;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[Rt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new eg(e,{...this._init})}}class eg extends Qd{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:Zb,name:"yamux"}),this.client="outbound"===e.direction,function(e){if(null!=e.keepAliveInterval&&e.keepAliveInterval<=0)throw new We("keep-alive interval must be positive");if(null!=e.maxInboundStreams&&e.maxInboundStreams<0)throw new We("max inbound streams must be larger or equal 0");if(null!=e.maxOutboundStreams&&e.maxOutboundStreams<0)throw new We("max outbound streams must be larger or equal 0");if(null!=e.maxMessageSize&&e.maxMessageSize<1024)throw new We("MaxMessageSize must be greater than a kilobyte");if(null!=e.streamOptions?.initialStreamWindowSize&&e.streamOptions?.initialStreamWindowSize<Gb)throw new We("InitialStreamWindowSize must be larger or equal 256 kB");if(null!=e.streamOptions?.maxStreamWindowSize&&null!=e.streamOptions?.initialStreamWindowSize&&e.streamOptions?.maxStreamWindowSize<e.streamOptions?.initialStreamWindowSize)throw new We("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(null!=e.streamOptions?.maxStreamWindowSize&&e.streamOptions?.maxStreamWindowSize>2**32-1)throw new We("MaxStreamWindowSize must be less than equal MAX_UINT32")}(t),this.enableKeepAlive=t.enableKeepAlive??!0,this.keepAliveInterval=t.keepAliveInterval??3e4,this.maxInboundStreams=t.maxInboundStreams??1e3,this.maxOutboundStreams=t.maxOutboundStreams??1e3,this.decoder=new Hb,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Cc(async e=>{try{await this.ping(e)}catch(e){this.log.error("ping error: %s",e)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(const t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(void 0!==this.remoteGoAway)throw new Ze("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Ze("Muxer closed locally");const e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new yt("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);const t=this._newStream(e,Qb.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(void 0!==this.remoteGoAway)throw new Ze("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Ze("Muxer closed locally");if(null!=this.activePing)return $d(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await $d(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if("open"===this.status)try{const t=e?.reason??Mb.NormalTermination;this.log.trace("muxer close reason=%s",Mb[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if("open"===this.status)try{super.abort(e);let t=Mb.InternalError;(function(e){return null!==e?.reason})(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(null!=this.streams.find(t=>t.streamId===e))throw new We("Stream already exists with that id");const r=new Yb({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return r.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),r}closeStream(e){this.client===(e%2==0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){const{streamID:t,type:n,length:r}=e.header;if(this.log.trace("received frame %o",Jb(e.header)),0===t)switch(n){case Ib.Ping:return void this.handlePing(e.header);case Ib.GoAway:return void this.handleGoAway(r);default:throw new qb("Invalid frame type")}else switch(e.header.type){case Ib.Data:case Ib.WindowUpdate:return void this.handleStreamMessage(e);default:throw new qb("Invalid frame type")}}handlePing(e){if(e.flag===Db.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Db.ACK);else{if(e.flag!==Db.ACK)throw new qb("Invalid frame flag");this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length)}}handlePingResponse(e){if(void 0===this.activePing)throw new $b("ping not requested");if(this.activePing.id!==e)throw new zb("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Mb[e]??"unknown"),this.remoteGoAway=e,e===Mb.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){const{streamID:t,flag:n,type:r}=e.header;(n&Db.SYN)===Db.SYN&&this.incomingStream(t);const i=this.streams.find(e=>e.streamId===t);if(void 0!==i)switch(r){case Ib.WindowUpdate:return void i.handleWindowUpdate(e);case Ib.Data:return void i.handleData(e);default:throw new Error("unreachable")}else this.log.trace("frame for missing stream id=%s",t)}incomingStream(e){if(this.client!==(e%2==0))throw new We("Both endpoints are clients");if(this.streams.find(t=>t.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),void 0!==this.localGoAway)return void this.sendFrame({type:Ib.WindowUpdate,flag:Db.RST,streamID:e,length:0});if(this.numInboundStreams>=this.maxInboundStreams)return this.log("maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:Ib.WindowUpdate,flag:Db.RST,streamID:e,length:0});const t=this._newStream(e,Qb.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Ib.Data){if(null==t)throw new qb("Invalid frame");n=new $n(Wb(e),t)}else n=Wb(e);return this.log.trace("sending frame %o",Jb(e)),this.send(n)}sendPing(e,t=Db.SYN){this.log.trace(t===Db.SYN?"sending ping request pingId=%s":"sending ping response pingId=%s",e),this.sendFrame({type:Ib.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Mb.NormalTermination){this.log("sending GoAway reason=%s",Mb[e]),this.localGoAway=e,this.sendFrame({type:Ib.GoAway,flag:0,streamID:0,length:e})}}function tg(e={}){return()=>new Xb(e)}const ng=[6,53,56,54,55];function rg(e){return sg("sni",e)?.value}function ig(e){const t=sg("tcp",e)?.value;return null==t?"":`:${t}`}function sg(e,t){return t.find(t=>t.name===e)}function ag(e){return e.some(({code:e})=>e===tu)}function og(e,t){const n=ug[e.name];if(null==n)throw new Error(`Can't interpret protocol ${e.name}`);const r=n(e,t);return e.code===Xo?`[${r}]`:r}const ug={ip4:(e,t)=>e.value,ip6:(e,t)=>0===t.length?e.value:`[${e.value}]`,tcp:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`tcp://${og(n,t)}:${e.value}`},udp:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`udp://${og(n,t)}:${e.value}`},dnsaddr:(e,t)=>e.value,dns4:(e,t)=>e.value,dns6:(e,t)=>e.value,dns:(e,t)=>e.value,ipfs:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${og(n,t)}`},p2p:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${og(n,t)}`},http:(e,t)=>{const n=ag(t),r=rg(t),i=ig(t);if(n&&null!=r)return`https://${r}${i}`;const s=n?"https://":"http://",a=t.pop();if(null==a)throw new Error("Unexpected end of multiaddr");let o=og(a,t);return o=o?.replace("tcp://",""),`${s}${o}`},"http-path":(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${og(n,t)}${decodeURIComponent(e.value??"")}`},tls:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return og(n,t)},sni:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return og(n,t)},https:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=og(n,t);return r=r?.replace("tcp://",""),`https://${r}`},ws:(e,t)=>{const n=ag(t),r=rg(t),i=ig(t);if(n&&null!=r)return`wss://${r}${i}`;const s=n?"wss://":"ws://",a=t.pop();if(null==a)throw new Error("Unexpected end of multiaddr");let o=og(a,t);return o=o?.replace("tcp://",""),`${s}${o}`},wss:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=og(n,t);return r=r?.replace("tcp://",""),`wss://${r}`}};class dg extends Wd{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??4194304,this.checkBufferedAmountTask=Cc(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??10),this.websocket.addEventListener("close",e=>{this.log('closed - code %d, reason "%s", wasClean %s',e.code,e.reason,e.wasClean),this.checkBufferedAmountTask.stop(),e.wasClean?this.onTransportClosed():this.onRemoteReset()},{once:!0}),this.websocket.addEventListener("message",e=>{try{let t;if("string"==typeof e.data)t=fr(e.data);else{if(!(e.data instanceof ArrayBuffer))return void this.abort(new Error("Incorrect binary type"));t=new Uint8Array(e.data,0,e.data.byteLength)}this.onData(t)}catch(e){this.log.error("error receiving data - %e",e)}})}sendData(e){for(const t of e)this.websocket.send(t);const t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),0===this.websocket.bufferedAmount&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}}class cg{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Dt]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Rt]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const n=(r={websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval},new dg(r));var r;this.log("new outbound connection %s",n.remoteAddr);const i=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),i}async _connect(e,t){t?.signal?.throwIfAborted();const n=function(e){const t=Pu(e).getComponents(),n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");const r=ug[n.name];if(null==r)throw new Error(`No interpreter found for ${n.name}`);let i=r(n,t)??"";return ng.includes(n.code)&&(i=i.replace(/^.*:\/\//,""),i="443"===n.value?`https://${i}`:`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}(e);this.log("create websocket connection to %s",n);const r=new WebSocket(n);r.binaryType="arraybuffer";try{t.onProgress?.(new _f("websockets:open-connection")),await _d(r,"open",t)}catch(e){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Je(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{r.close()}catch{}throw e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),r}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}()}listenFilter(e){return e.filter(e=>$h.exactMatch(e)||Vh.exactMatch(e))}dialFilter(e){return this.listenFilter(e)}}function lg(e={}){return t=>new cg(t,e)}class pg{constructor(){throw new Error("TCP connections are not possible in browsers")}[Dt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Rt]=["@libp2p/transport"];async dial(){throw new Error("TCP connections are not possible in browsers")}createListener(){throw new Error("TCP connections are not possible in browsers")}listenFilter(){return[]}dialFilter(){return[]}}function hg(e={}){return t=>new pg(t,e)}const fg=`${At}-circuit-relay`;BigInt(1<<17);const mg="/libp2p/circuit/relay/0.2.0/hop",yg="/libp2p/circuit/relay/0.2.0/stop",bg=new Float32Array([-0]),gg=new Uint8Array(bg.buffer);function vg(e,t,n){bg[0]=e,t[n]=gg[0],t[n+1]=gg[1],t[n+2]=gg[2],t[n+3]=gg[3]}const wg=new Float64Array([-0]),Tg=new Uint8Array(wg.buffer);function Eg(e,t,n){wg[0]=e,t[n]=Tg[0],t[n+1]=Tg[1],t[n+2]=Tg[2],t[n+3]=Tg[3],t[n+4]=Tg[4],t[n+5]=Tg[5],t[n+6]=Tg[6],t[n+7]=Tg[7]}const xg=BigInt(Number.MAX_SAFE_INTEGER),Pg=BigInt(Number.MIN_SAFE_INTEGER);class Sg{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(0n===e)return Ag;if(e<xg&&e>Pg)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let n=e>>32n,r=e-(n<<32n);return t&&(n=0n|~n,r=0n|~r,++r>Cg&&(r=0n,++n>Cg&&(n=0n))),new Sg(Number(r),Number(n))}static fromNumber(e){if(0===e)return Ag;const t=e<0;t&&(e=-e);let n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new Sg(n,r)}static from(e){return"number"==typeof e?Sg.fromNumber(e):"bigint"==typeof e?Sg.fromBigInt(e):"string"==typeof e?Sg.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Sg(e.low>>>0,e.high>>>0):Ag}}const Ag=new Sg(0,0);Ag.toBigInt=function(){return 0n},Ag.zzEncode=Ag.zzDecode=function(){return this},Ag.length=function(){return 1};const Cg=4294967296n;function kg(e,t,n){const r=n;let i,s;for(let r=0;r<e.length;++r)i=e.charCodeAt(r),i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-r}function Ig(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Dg(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Mg{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ig(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Ig(this,4);return Dg(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ig(this,4);return 0|Dg(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Ig(this,4);const e=(gg[0]=(t=this.buf)[n=this.pos],gg[1]=t[n+1],gg[2]=t[n+2],gg[3]=t[n+3],bg[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ig(this,4);const e=(Tg[0]=(t=this.buf)[n=this.pos],Tg[1]=t[n+1],Tg[2]=t[n+2],Tg[3]=t[n+3],Tg[4]=t[n+4],Tg[5]=t[n+5],Tg[6]=t[n+6],Tg[7]=t[n+7],wg[0]);var t,n;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Ig(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){const e=this.bytes();return function(e,t,n){if(n-t<1)return"";let r;const i=[];let s,a=0;for(;t<n;)s=e[t++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=r?(a>0&&r.push(String.fromCharCode.apply(String,i.slice(0,a))),r.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Ig(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Ig(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Sg(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Ig(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ig(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ig(this,8);const e=Dg(this.buf,this.pos+=4),t=Dg(this.buf,this.pos+=4);return new Sg(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=ba(this.buf,this.pos);return this.pos+=ma(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Fg(e){return new Mg(e instanceof Uint8Array?e:e.subarray())}function Rg(e,t,n){const r=Fg(e);return t.decode(r,void 0,n)}class _g{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Lg(){}class Ng{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Og=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return On(r);n+r>e&&(t=On(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class Bg{len;head;tail;states;constructor(){this.len=0,this.head=new _g(Lg,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new _g(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new qg((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push($g,10,Sg.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Sg.fromBigInt(e);return this._push($g,t.length(),t)}uint64Number(e){return this._push(ya,ma(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=Sg.fromBigInt(e).zzEncode();return this._push($g,t.length(),t)}sint64Number(e){const t=Sg.fromNumber(e).zzEncode();return this._push($g,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ug,1,e?1:0)}fixed32(e){return this._push(zg,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Sg.fromBigInt(e);return this._push(zg,4,t.lo)._push(zg,4,t.hi)}fixed64Number(e){const t=Sg.fromNumber(e);return this._push(zg,4,t.lo)._push(zg,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(vg,4,e)}double(e){return this._push(Eg,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Ug,1,0):this.uint32(t)._push(Vg,t,e)}string(e){const t=function(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(kg,t,e):this._push(Ug,1,0)}fork(){return this.states=new Ng(this),this.head=this.tail=new _g(Lg,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new _g(Lg,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next;const t=(n=this.len,null!=globalThis.Buffer?On(n):Og(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function Ug(e,t,n){t[n]=255&e}function jg(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class qg extends _g{next;constructor(e,t){super(jg,e,t),this.next=void 0}}function $g(e,t,n){for(;0!==e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function zg(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function Vg(e,t,n){t.set(e,n)}function Gg(e,t,n){t.set(e,n)}function Kg(e,t,n){e.length<40?kg(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(fr(e),n)}function Hg(e,t){const n=new Bg;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*Wg(e,t,n){const r=Fg(e);yield*t.stream(r,void 0,"$",n)}function Qg(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function Yg(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Qg("enum",0,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())},function*(e){const n=e.int32();yield t(n)})}function Jg(e,t,n){return Qg("message",2,e,t,n)}null!=globalThis.Buffer&&(Bg.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Gg,t,e),this},Bg.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Kg,t,e),this});class Zg extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var Xg,ev,tv,nv,rv,iv,sv,av,ov;!function(e){var t;let n,r;(t=e.Type||(e.Type={})).RESERVE="RESERVE",t.CONNECT="CONNECT",t.STATUS="STATUS",function(e){e[e.RESERVE=0]="RESERVE",e[e.CONNECT=1]="CONNECT",e[e.STATUS=2]="STATUS"}(n||(n={})),function(e){e.codec=()=>Yg(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Jg((t,n,r={})=>{!1!==r.lengthDelimited&&n.fork(),null!=t.type&&(n.uint32(8),e.Type.codec().encode(t.type,n)),null!=t.peer&&(n.uint32(18),tv.codec().encode(t.peer,n)),null!=t.reservation&&(n.uint32(26),nv.codec().encode(t.reservation,n)),null!=t.limit&&(n.uint32(34),rv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(40),iv.codec().encode(t.status,n)),!1!==r.lengthDelimited&&n.ldelim()},(t,n,r={})=>{const i={},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:i.peer=tv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.reservation=nv.codec().decode(t,t.uint32(),{limits:r.limits?.reservation});break;case 4:i.limit=rv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 5:i.status=iv.codec().decode(t);break;default:t.skipType(7&n)}}return i},function*(t,n,r,i={}){const s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:yield{field:`${r}.type`,value:e.Type.codec().decode(t)};break;case 2:yield*tv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*nv.codec().stream(t,t.uint32(),`${r}.reservation`,{limits:i.limits?.reservation});break;case 4:yield*rv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 5:yield{field:`${r}.status`,value:iv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(Xg||(Xg={})),function(e){var t;let n,r;(t=e.Type||(e.Type={})).CONNECT="CONNECT",t.STATUS="STATUS",function(e){e[e.CONNECT=0]="CONNECT",e[e.STATUS=1]="STATUS"}(n||(n={})),function(e){e.codec=()=>Yg(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Jg((t,n,r={})=>{!1!==r.lengthDelimited&&n.fork(),null!=t.type&&(n.uint32(8),e.Type.codec().encode(t.type,n)),null!=t.peer&&(n.uint32(18),tv.codec().encode(t.peer,n)),null!=t.limit&&(n.uint32(26),rv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(32),iv.codec().encode(t.status,n)),!1!==r.lengthDelimited&&n.ldelim()},(t,n,r={})=>{const i={},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:i.peer=tv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.limit=rv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 4:i.status=iv.codec().decode(t);break;default:t.skipType(7&n)}}return i},function*(t,n,r,i={}){const s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:yield{field:`${r}.type`,value:e.Type.codec().decode(t)};break;case 2:yield*tv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*rv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 4:yield{field:`${r}.status`,value:iv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(ev||(ev={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.addrs&&e.addrs.length>0)for(const n of e.addrs)t.uint32(18),t.bytes(n);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={id:Nn(0),addrs:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.id=e.bytes();break;case 2:if(null!=n.limits?.addrs&&r.addrs.length===n.limits.addrs)throw new Zg('Decode error - repeated field "addrs" had too many elements');r.addrs.push(e.bytes());break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i={addrs:0},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.id`,value:e.bytes()};break;case 2:if(null!=r.limits?.addrs&&i.addrs===r.limits.addrs)throw new Zg('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${n}.addrs[]`,index:i.addrs,value:e.bytes()},i.addrs++;break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(tv||(tv={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.expire&&0n!==e.expire&&(t.uint32(8),t.uint64(e.expire)),null!=e.addrs&&e.addrs.length>0)for(const n of e.addrs)t.uint32(18),t.bytes(n);null!=e.voucher&&(t.uint32(26),ov.codec().encode(e.voucher,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={expire:0n,addrs:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.expire=e.uint64();break;case 2:if(null!=n.limits?.addrs&&r.addrs.length===n.limits.addrs)throw new Zg('Decode error - repeated field "addrs" had too many elements');r.addrs.push(e.bytes());break;case 3:r.voucher=ov.codec().decode(e,e.uint32(),{limits:n.limits?.voucher});break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i={addrs:0},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.expire`,value:e.uint64()};break;case 2:if(null!=r.limits?.addrs&&i.addrs===r.limits.addrs)throw new Zg('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${n}.addrs[]`,index:i.addrs,value:e.bytes()},i.addrs++;break;case 3:yield*ov.codec().stream(e,e.uint32(),`${n}.voucher`,{limits:r.limits?.voucher});break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(nv||(nv={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.duration&&(t.uint32(8),t.uint32(e.duration)),null!=e.data&&(t.uint32(16),t.uint64(e.data)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.duration=e.uint32();break;case 2:r.data=e.uint64();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.duration`,value:e.uint32()};break;case 2:yield{field:`${n}.data`,value:e.uint64()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(rv||(rv={})),function(e){e.UNUSED="UNUSED",e.OK="OK",e.RESERVATION_REFUSED="RESERVATION_REFUSED",e.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.NO_RESERVATION="NO_RESERVATION",e.MALFORMED_MESSAGE="MALFORMED_MESSAGE",e.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"}(iv||(iv={})),function(e){e[e.UNUSED=0]="UNUSED",e[e.OK=100]="OK",e[e.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",e[e.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",e[e.PERMISSION_DENIED=202]="PERMISSION_DENIED",e[e.CONNECTION_FAILED=203]="CONNECTION_FAILED",e[e.NO_RESERVATION=204]="NO_RESERVATION",e[e.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",e[e.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"}(sv||(sv={})),function(e){e.codec=()=>Yg(sv)}(iv||(iv={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.relay&&e.relay.byteLength>0&&(t.uint32(10),t.bytes(e.relay)),null!=e.peer&&e.peer.byteLength>0&&(t.uint32(18),t.bytes(e.peer)),null!=e.expiration&&0n!==e.expiration&&(t.uint32(24),t.uint64(e.expiration)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={relay:Nn(0),peer:Nn(0),expiration:0n},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.relay=e.bytes();break;case 2:r.peer=e.bytes();break;case 3:r.expiration=e.uint64();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.relay`,value:e.bytes()};break;case 2:yield{field:`${n}.peer`,value:e.bytes()};break;case 3:yield{field:`${n}.expiration`,value:e.uint64()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(av||(av={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&(t.uint32(26),av.codec().encode(e.payload,t)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={publicKey:Nn(0),payloadType:Nn(0),signature:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=av.codec().decode(e,e.uint32(),{limits:n.limits?.payload});break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.publicKey`,value:e.bytes()};break;case 2:yield{field:`${n}.payloadType`,value:e.bytes()};break;case 3:yield*av.codec().stream(e,e.uint32(),`${n}.payload`,{limits:r.limits?.payload});break;case 5:yield{field:`${n}.signature`,value:e.bytes()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(ov||(ov={}));class uv extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"}class dv extends Error{static name="DoubleRelayError";name="DoubleRelayError"}class cv extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"}function lv(e){const t=e*BigInt(1e3),n=(new Date).getTime();return Number(t-BigInt(n))}class pv{expires;bytes;constructor(e){null!=e?.duration&&0!==e?.duration&&(this.expires=Date.now()+1e3*e.duration),this.bytes=e?.data,0n===this.bytes&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){null!=this.bytes&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(null==this.expires&&null==this.bytes)return;const e={};if(null!=this.bytes){const t=this;Object.defineProperty(e,"bytes",{get:()=>t.bytes})}if(null!=this.expires){const t=this;Object.defineProperty(e,"seconds",{get:()=>Math.round(((t.expires??0)-Date.now())/1e3)})}return e}}const hv=wh(vh(Yh.matchers[0],mh(su))),fv=wh(mh(su));class mv extends Ft{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(mg,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){null!=this.topologyId&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");const e=await this.components.peerStore.all({filters:[e=>e.protocols.includes(mg)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{const n=yv(e),r=yv(t);return n>r?-1:r>n?1:0}]});for(const t of e)this.log.trace("found relay peer %p in peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});this.log("found %d relay peers in peer store",e.length);const t=this.queue=new xc({concurrency:5});this.log("start random walk");for await(const e of this.components.randomWalk.walk({signal:this.discoveryController.signal}))this.log.trace("found random peer %p",e.id),t.has(e.id)?this.log.trace("random peer %p was already in queue",e.id):this.components.connectionManager.getConnections(e.id)?.length>0?this.log.trace("random peer %p was already connected",e.id):await this.components.connectionManager.isDialable(e.multiaddrs)?(t.queued>10&&(this.log.trace("wait for space in queue for %p",e.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",e.id,t.size,t.running),t.add(this.dialPeer,{peerId:e.id,signal:this.discoveryController.signal}).catch(t=>{this.log.error("error opening connection to random peer %p - %e",e.id,t)})):this.log.trace("random peer %p was not dialable",e.id,e.multiaddrs.map(e=>e.toString()));this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(null==this.queue)return;const t=e.detail.id,n=e.detail.multiaddrs;this.queue.has(t)?this.log.trace("random peer %p was already in queue",t):this.components.connectionManager.getConnections(t)?.length>0?this.log.trace("random peer %p was already connected",t):await this.components.connectionManager.isDialable(n)?this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(t=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,t)}):this.log.trace("random peer %p was not dialable",t)}async dialPeer({peerId:e,signal:t}){const n=Jd([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}}function yv(e){const t=e.metadata.get("last-dial-success");return null==t?0:new Date(mr(t)).getTime()}class bv extends Ft{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??5e3,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),!0===this.relay?.equals(e.detail.relay)&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(e=>{this.addressManager.removeObservedAddr(e)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{const{details:t}=e.detail;"configured"!==t.type&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(fv.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else{if(!hv.exactMatch(e))throw new ht(`Could not listen on p2p-circuit address "${e}"`);{this.log("listen on specific relay server %a",e);const t=AbortSignal.timeout(this.listenTimeout),n=e.decapsulate("/p2p-circuit"),r=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(r.remotePeer)){this.log("making reservation on peer %p",r.remotePeer);const e=await this.reservationStore.addRelay(r.remotePeer,"configured");this.addedRelay(e)}}}}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(e=>Pu(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}}class gv extends Ft{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Xu,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??5e3,this.started=!1,this.relayFilter=pd(100),this.reserveQueue=new xc({concurrency:t?.reservationConcurrency??1,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",e=>{null!=[...this.reservations.values()].find(t=>t.connection===e.detail.id)&&this.#J(e.detail.remotePeer).catch(t=>{this.log("could not remove relay %p - %e",e.detail,t)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{const e=await this.peerStore.all({filters:[e=>e.tags.has(fg)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async e=>{await this.peerStore.merge(e.id,{tags:{[fg]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async e=>this.addRelay(e.id,"discovered"))),this.#Z()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){const e=((e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t})();return this.pendingReservations.push(e),this.#Z(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new ht("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new cv("The reservation queue is full");const n=this.reserveQueue.find(e);if(null!=n)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new ht("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{const n=Date.now();try{const n=this.reservations.get(e);if(null!=n){const t=this.connectionManager.getConnections(e);let r=!1;if(0===t.length&&this.log("already have relay reservation with %p but we are no longer connected",e),t.map(e=>e.id).includes(n.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),r=!0),r&&lv(n.reservation.expire)>6e5)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:n};await this.#J(e)}if("discovered"===t&&0===this.pendingReservations.length)throw new uv("Not making reservation on discovered relay because we do not need any more relays");const r=AbortSignal.timeout(this.reservationCompletionTimeout),i=await this.connectionManager.openConnection(e,{signal:r});if(Zh.matches(i.remoteAddr))throw new dv("not creating reservation over relayed connection");const s=await this.#X(i,{signal:r}),a=lv(s.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+a).toString());const o=Math.min(Math.max(a-3e5,3e4),Math.pow(2,31)-1),u=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async t=>{this.log.error("could not refresh reservation to relay %p - %e",e,t),await this.#J(e)}).catch(t=>{this.log.error("could not remove expired reservation to relay %p - %e",e,t)})},o);let d;if("discovered"===t){const e=this.pendingReservations.pop();if(null==e)throw new uv("Made reservation on relay but did not need any more discovered relays");d={timeout:u,reservation:s,type:t,connection:i.id,id:e}}else d={timeout:u,reservation:s,type:t,connection:i.id};this.reservations.set(e,d),await this.peerStore.merge(e,{tags:{[fg]:{value:1,ttl:a}}}),this.#Z();const c={relay:e,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:c}),c}catch(r){throw"discovered"===t&&"HadEnoughRelaysError"===r.name||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-n,r),"DialError"!==r.name&&"UnsupportedProtocolError"!==r.name||this.relayFilter.add(e.toMultihash().bytes),this.#J(e).catch(t=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,t)}),r}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return null==e?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#X(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);const n=await e.newStream(mg,t),r=mc(n).pb(Xg);let i;this.log.trace("send RESERVE to %p",e.remotePeer),await r.write({type:Xg.Type.RESERVE},t);try{this.log.trace("reading response from %p",e.remotePeer),i=await r.read(t)}catch(e){throw n.abort(e),e}finally{"closed"!==n.status&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===iv.OK&&null!=i.reservation){const t=new Set;t.add(e.remoteAddr.toString());for(const n of i.reservation.addrs){let r=Pu(n);null==r.getComponents().find(e=>e.code===eu)&&(r=r.encapsulate(`/p2p/${e.remotePeer}`)),r=Pu(r.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),t.add(r.toString())}return i.reservation.addrs=[...t].map(e=>Pu(e).bytes),i.reservation}const s=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(s),new Error(s)}async#J(e){const t=this.reservations.get(e);null!=t&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),"discovered"===t.type&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[fg]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#Z())}#Z(){if(0===this.pendingReservations.length)return this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),void this.safeDispatchEvent("relay:found-enough-relays");this.relayFilter=pd(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}}class vv extends Wd{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",e=>{this.onTransportClosed(e.error)}),this.stream.addEventListener("remoteCloseWrite",e=>{this.onRemoteCloseWrite(),this.close().catch(e=>{this.abort(e)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}}function wv(e){return new vv(e)}class Tv{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??300,this.maxOutboundStopStreams=t.maxOutboundStopStreams??300,this.shutdownController=new AbortController,this.discovery=new mv(e,{filter:t.discoveryFilter??Mc(4096,.001)}),this.discovery.addEventListener("relay:discover",e=>{this.reservationStore.addRelay(e.detail,"discovered").catch(t=>{"HadEnoughRelaysError"!==t.name&&"RelayQueueFullError"!==t.name&&this.log.error("could not add discovered relay %p - %e",e.detail,t)})}),this.reservationStore=new gv(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Rt]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[_t](){return null!=this.discovery?["@libp2p/identify"]:[]}[Dt]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.components.registrar.handle(yg,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await kt(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await It(this.discovery,this.reservationStore),await this.components.registrar.unhandle(yg),this.started=!1}async dial(e,t){const n=e.toString().split("/p2p-circuit"),r=Pu(n[0]),i=Pu(n[n.length-1]),s=r.getComponents().find(e=>e.code===eu)?.value,a=i.getComponents().find(e=>e.code===eu)?.value;if(null==s||null==a){const t=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${t}`),new pt(`C${t}`)}const o=Uo(s),u=Uo(a);let d,c=this.components.connectionManager.getConnections(o)[0];null==c?(await this.components.peerStore.merge(o,{multiaddrs:[r]}),t.onProgress?.(new _f("circuit-relay:open-connection")),c=await this.components.connectionManager.openConnection(o,t)):t.onProgress?.(new _f("circuit-relay:reuse-connection"));try{t.onProgress?.(new _f("circuit-relay:open-hop-stream")),d=await c.newStream(mg,t);const n=mc(d).pb(Xg);t.onProgress?.(new _f("circuit-relay:write-connect-message")),await n.write({type:Xg.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Pu(i).bytes]}},t),t.onProgress?.(new _f("circuit-relay:read-connect-response"));const s=await n.read(t);if(s.status!==iv.OK)throw new ut(`failed to connect via relay with status ${s?.status?.toString()??"undefined"}`);const a=new pv(s.limit),o=wv({stream:n.unwrap().unwrap(),remoteAddr:e,localAddr:r.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:a.onData,onDataWrite:a.onData,log:d.log.newScope("circuit-relay:connection")}),l=await this.components.upgrader.upgradeOutbound(o,{...t,limits:a.getLimits()});return l.log("outbound relayed connection established to %p with limits %o, over connection %s",l.remotePeer,s.limit??"none",c.id),l}catch(e){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",u,o,e),d?.abort(e),e}}createListener(e){return function(e){return new bv(e)}({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return(e=Array.isArray(e)?e:[e]).filter(e=>hv.exactMatch(e)||fv.exactMatch(e))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter(e=>Zh.exactMatch(e))}async onStop(e,t){const n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(e){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",e)}const r=mc(e).pb(ev),i=await r.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),void 0===i?.type)return this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});if(i.type!==ev.Type.CONNECT)return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.UNEXPECTED_MESSAGE},{signal:n}),void await e.close({signal:n});if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(Pu)}catch{return!1}return!0})(i))return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});const s=qo(xn(i.peer.id));if(!0===await(this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)))return this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.PERMISSION_DENIED},{signal:n}),void await e.close({signal:n});this.log.trace("sending success response to %p",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.OK},{signal:n});const a=new pv(i.limit),o=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),u=this.components.addressManager.getAddresses()[0],d=wv({stream:r.unwrap().unwrap(),remoteAddr:o,localAddr:u,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(d,{limits:a.getLimits(),signal:n}),d.log("inbound relayed connection established to %p with limits %o, over connection %s",s,i.limit??"none",t.id)}finally{n?.clear()}}}function Ev(e={}){return t=>new Tv(t,e)}class xv extends Ft{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=t.list.map(e=>Pu(e)).filter(e=>{if(!Yh.matches(e))return this.log.error("invalid multiaddr %a",e),!1;const t=e.getComponents().findLast(e=>e.code===eu)?.value;return null!=t||(this.log.error("invalid bootstrap multiaddr without peer id"),!1)}).map(e=>({id:Uo(e.getComponents().findLast(e=>e.code===eu)?.value??""),multiaddrs:[e]})),this._init=t}[Et]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Rt]=["@libp2p/peer-discovery"];isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}var Pv;!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const n of e.listenAddrs)t.uint32(18),t.bytes(n);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const n of e.protocols)t.uint32(26),t.string(n);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={listenAddrs:[],protocols:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 5:r.protocolVersion=e.string();break;case 6:r.agentVersion=e.string();break;case 1:r.publicKey=e.bytes();break;case 2:if(null!=n.limits?.listenAddrs&&r.listenAddrs.length===n.limits.listenAddrs)throw new Bp('Decode error - map field "listenAddrs" had too many elements');r.listenAddrs.push(e.bytes());break;case 4:r.observedAddr=e.bytes();break;case 3:if(null!=n.limits?.protocols&&r.protocols.length===n.limits.protocols)throw new Bp('Decode error - map field "protocols" had too many elements');r.protocols.push(e.string());break;case 8:r.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Pv||(Pv={}));const Sv="ipfs";class Av{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??5e3,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.maxMessageSize=t.maxMessageSize??8192,this.maxObservedAddresses=t.maxObservedAddresses??10,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.host={protocolVersion:`${t.protocolPrefix??Sv}/0.1.0`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:fr(this.host.agentVersion),ProtocolVersion:fr(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}}class Cv extends Av{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Sv}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??1)&&e.events.addEventListener("connection:open",e=>{this.identify(e.detail).catch(()=>{})})}[Rt]=["@libp2p/identify"];async _identify(e,t={}){let n,r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),r=n.log.newScope("identify");const i=mc(n,{maxDataLength:this.maxMessageSize}).pb(Pv),s=await i.read(t);return await i.unwrap().unwrap().close(t),s}catch(e){throw r?.error("identify failed - %e",e),n?.abort(e),e}}async identify(e,t={}){const n=await this._identify(e,t),{publicKey:r,protocols:i,observedAddr:s}=n;if(null==r)throw new ut("Public key was missing from identify message");const a=$o(Mo(r).toCID());if(!e.remotePeer.equals(a))throw new ut("Identified peer does not match the expected peer");if(this.components.peerId.equals(a))throw new ut("Identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("completed for peer %p and protocols %o",a,i),async function(e,t,n,r,i){if(n("received identify from %p",r.remotePeer),null==i)throw new ut("message was null or undefined");const s={};if(i.listenAddrs.length>0&&(s.addresses=i.listenAddrs.map(e=>({isCertified:!1,multiaddr:Pu(e)}))),i.protocols.length>0&&(s.protocols=i.protocols),null!=i.publicKey){const e=Mo(i.publicKey);if(!jo(e).equals(r.remotePeer))throw new ut("public key did not match remote PeerId");s.publicKey=e}let a;if(null!=i.signedPeerRecord){n.trace("received signedPeerRecord from %p",r.remotePeer);let t=i.signedPeerRecord;const o=await yl.openAndCertify(t,wl.DOMAIN);let u=wl.createFromProtobuf(o.payload);const d=$o(o.publicKey.toCID());if(!u.peerId.equals(d))throw new ut("signing key does not match PeerId in the PeerRecord");if(!r.remotePeer.equals(u.peerId))throw new ut("signing key does not match remote PeerId");let c;try{c=await e.get(u.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=c&&(s.metadata=c.metadata,null!=c.peerRecordEnvelope)){const e=yl.createFromProtobuf(c.peerRecordEnvelope),r=wl.createFromProtobuf(e.payload);r.seqNumber>=u.seqNumber&&(n("sequence number was lower or equal to existing sequence number - stored: %d received: %d",r.seqNumber,u.seqNumber),u=r,t=c.peerRecordEnvelope)}s.peerRecordEnvelope=t,s.addresses=u.multiaddrs.map(e=>({isCertified:!0,multiaddr:e})),a={seq:u.seqNumber,addresses:u.multiaddrs}}else n("%p did not send a signed peer record",r.remotePeer);if(n.trace("patching %p with",r.remotePeer,s),await e.patch(r.remotePeer,s),null!=i.agentVersion||null!=i.protocolVersion){const t={};null!=i.agentVersion&&(t.AgentVersion=fr(i.agentVersion)),null!=i.protocolVersion&&(t.ProtocolVersion=fr(i.protocolVersion)),n.trace("merging %p metadata",r.remotePeer,t),await e.merge(r.remotePeer,{metadata:t})}const o={peerId:r.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map(e=>Pu(e)),observedAddr:null==i.observedAddr?void 0:Pu(i.observedAddr),protocols:i.protocols,signedPeerRecord:a,connection:r};return t.safeDispatchEvent("peer:identify",{detail:o}),o}(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Pu(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),Ad(t))return;const n=t.getComponents();n[0].code!==Xo&&(42!==n[0].code||n[1].code!==Xo)||function(e){try{const n=hd(e);return"ip6"===n.type&&(t=n.host,new bd("2000::/3").contains(t))}catch{return!1}var t}(t)?Lh.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(e,t){const n=e.log.newScope("identify");n("responding to identify");const r=AbortSignal.timeout(this.timeout),i=await this.components.peerStore.get(this.components.peerId,{signal:r}),s=this.components.addressManager.getAddresses().map(e=>e.decapsulateCode(eu));let a=i.peerRecordEnvelope;if(s.length>0&&null==a){const e=new wl({peerId:this.components.peerId,multiaddrs:s});a=(await yl.seal(e,this.components.privateKey,{signal:r})).marshal().subarray()}let o=t.remoteAddr.bytes;Dh.matches(t.remoteAddr)||(o=void 0);const u=mc(e).pb(Pv);n("send response"),await u.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Fo(this.components.privateKey.publicKey),listenAddrs:s.map(e=>e.bytes),signedPeerRecord:a,observedAddr:o,protocols:i.protocols},{signal:r}),n("close write"),await u.unwrap().unwrap().close({signal:r})}}function kv(e={}){return t=>new Cv(t,e)}const Iv=36e5,Dv=48*Iv,Mv=Iv,Fv=Iv,Rv=`${At}-kad-dht`;var _v,Lv,Nv,Ov,Bv,Uv,jv,qv;function $v(e){const t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0"),i=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0"),o=e.getUTCMilliseconds();return`${t}-${n}-${r}T${i}:${s}:${a}.${String(1e3*o*1e3).padStart(9,"0")}Z`}!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&e.key.byteLength>0&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),null!=e.timeReceived&&""!==e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={key:Nn(0),value:Nn(0),timeReceived:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(_v||(_v={}));class zv{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return _v.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:$v(this.timeReceived)}}static deserialize(e){const t=_v.decode(e);return new zv(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){const t=function(e){const t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),n=String(e).trim().match(t);if(null==n)throw new Error("Invalid format");const r=parseInt(n[1],10),i=parseInt(n[2],10)-1,s=parseInt(n[3],10),a=parseInt(n[4],10),o=parseInt(n[5],10),u=parseInt(n[6],10),d=parseInt(n[7].slice(0,-6),10);return new Date(Date.UTC(r,i,s,a,o,u,d))}(e.timeReceived);if(null==e.key)throw new Error("key missing from deserialized object");if(null==e.value)throw new Error("value missing from deserialized object");return new zv(e.key,e.value,t)}}function Vv(e,t){let n=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const r of e)yield t(r,n++)}();const r=dh(e),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const a=t(i,n++);if("function"==typeof a.then)return async function*(){yield await a;for(const e of r)yield t(e,n++)}();const o=t;return function*(){yield a;for(const e of r)yield o(e,n++)}()}class Gv extends Error{constructor(e="Query error"){super(e),this.name="QueryError"}}class Kv extends Error{constructor(e="Invalid record"){super(e),this.name="InvalidRecordError"}}class Hv extends Error{constructor(e="No selector function configured for prefix"){super(e),this.name="MissingSelectorError"}}function Wv(e,t={}){const n={...e,name:"SEND_QUERY",type:0,messageName:e.type,messageType:e.type};return t.onProgress?.(new CustomEvent("kad-dht:query:send-query",{detail:n})),n}function Qv(e,t={}){const n={...e,name:"PEER_RESPONSE",type:1,messageName:e.messageType,closer:e.closer??[],providers:e.providers??[]};return t.onProgress?.(new CustomEvent("kad-dht:query:peer-response",{detail:n})),n}function Yv(e,t={}){const n={...e,name:"FINAL_PEER",type:2};return t.onProgress?.(new CustomEvent("kad-dht:query:final-peer",{detail:n})),n}function Jv(e,t={}){const n={...e,name:"QUERY_ERROR",type:3};return t.onProgress?.(new CustomEvent("kad-dht:query:query-error",{detail:n})),n}function Zv(e,t={}){const n={...e,name:"PROVIDER",type:4};return t.onProgress?.(new CustomEvent("kad-dht:query:provider",{detail:n})),n}function Xv(e,t={}){const n={...e,name:"VALUE",type:5};return t.onProgress?.(new CustomEvent("kad-dht:query:value",{detail:n})),n}function ew(e,t={}){const n={...e,name:"DIAL_PEER",type:7};return t.onProgress?.(new CustomEvent("kad-dht:query:dial-peer",{detail:n})),n}!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&(t.uint32(18),t.bytes(e.value)),null!=e.author&&(t.uint32(26),t.bytes(e.author)),null!=e.signature&&(t.uint32(34),t.bytes(e.signature)),null!=e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 3:r.author=e.bytes();break;case 4:r.signature=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Lv||(Lv={})),function(e){e.PUT_VALUE="PUT_VALUE",e.GET_VALUE="GET_VALUE",e.ADD_PROVIDER="ADD_PROVIDER",e.GET_PROVIDERS="GET_PROVIDERS",e.FIND_NODE="FIND_NODE",e.PING="PING"}(Nv||(Nv={})),function(e){e[e.PUT_VALUE=0]="PUT_VALUE",e[e.GET_VALUE=1]="GET_VALUE",e[e.ADD_PROVIDER=2]="ADD_PROVIDER",e[e.GET_PROVIDERS=3]="GET_PROVIDERS",e[e.FIND_NODE=4]="FIND_NODE",e[e.PING=5]="PING"}(Ov||(Ov={})),function(e){e.codec=()=>Np(Ov)}(Nv||(Nv={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(Bv||(Bv={})),function(e){e[e.NOT_CONNECTED=0]="NOT_CONNECTED",e[e.CONNECTED=1]="CONNECTED",e[e.CAN_CONNECT=2]="CAN_CONNECT",e[e.CANNOT_CONNECT=3]="CANNOT_CONNECT"}(Uv||(Uv={})),function(e){e.codec=()=>Np(Uv)}(Bv||(Bv={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.multiaddrs)for(const n of e.multiaddrs)t.uint32(18),t.bytes(n);null!=e.connection&&(t.uint32(24),Bv.codec().encode(e.connection,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={id:Nn(0),multiaddrs:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.id=e.bytes();break;case 2:if(null!=n.limits?.multiaddrs&&r.multiaddrs.length===n.limits.multiaddrs)throw new Bp('Decode error - map field "multiaddrs" had too many elements');r.multiaddrs.push(e.bytes());break;case 3:r.connection=Bv.codec().decode(e);break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(jv||(jv={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.type&&0!==Ov[e.type]&&(t.uint32(8),Nv.codec().encode(e.type,t)),null!=e.clusterLevel&&(t.uint32(80),t.int32(e.clusterLevel)),null!=e.key&&(t.uint32(18),t.bytes(e.key)),null!=e.record&&(t.uint32(26),t.bytes(e.record)),null!=e.closer)for(const n of e.closer)t.uint32(66),jv.codec().encode(n,t);if(null!=e.providers)for(const n of e.providers)t.uint32(74),jv.codec().encode(n,t);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={type:Nv.PUT_VALUE,closer:[],providers:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.type=Nv.codec().decode(e);break;case 10:r.clusterLevel=e.int32();break;case 2:r.key=e.bytes();break;case 3:r.record=e.bytes();break;case 8:if(null!=n.limits?.closer&&r.closer.length===n.limits.closer)throw new Bp('Decode error - map field "closer" had too many elements');r.closer.push(jv.codec().decode(e,e.uint32(),{limits:n.limits?.closer$}));break;case 9:if(null!=n.limits?.providers&&r.providers.length===n.limits.providers)throw new Bp('Decode error - map field "providers" had too many elements');r.providers.push(jv.codec().decode(e,e.uint32(),{limits:n.limits?.providers$}));break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(qv||(qv={}));const tw={pk:function(e,t){return 0}};async function nw(e,t,n){const r=t.key,i=mr(r).split("/");if(i.length<3)return;const s=e[i[1].toString()];if(null==s)throw new We(`No validator available for key type "${i[1]}"`);await s(r,t.value,n)}const rw={pk:async(e,t,n)=>{if(!(e instanceof Uint8Array))throw new We('"key" must be a Uint8Array');if(e.byteLength<5)throw new We("Invalid public key record");if("/pk/"!==mr(e.subarray(0,4)))throw new We("key was not prefixed with /pk/");const r=Mo(t);if(!Ln(e.slice(4),r.toMultihash().bytes))throw new We("public key does not match passed in key")}},iw=fr("/pk/");function sw(e){return{...e,multiaddrs:e.multiaddrs.filter(e=>!Ad(e))}}async function aw(e,t){const n=await ur.digest(e);return t?.signal?.throwIfAborted(),n.digest}async function ow(e,t){return aw(e.toMultihash().bytes,t)}function uw(e,t){return new Wp(`${e}/${mr(t,"base32")}`,!1)}function dw(e,t){const n=new Date;return new zv(e,t,n).serialize()}function cw(e){const t=e.toString().split("/"),n=t.pop(),r=t.pop();if(null==n||null==r)throw new Error(`incorrectly formatted provider entry key in datastore: ${e.toString()}`);return{cid:kn.createV1(85,xn(fr(r,"base32"))),peerId:Uo(n)}}function lw(e,t,n){const r=[e,"string"==typeof t?t:mr(t.multihash.bytes,"base32")];return null!=n&&r.push(n.toString()),new Wp(r.join("/"))}function pw(e){return new Date(va(e))}function hw(e,t,n){return async function*(...r){const i=t.queryTime?.timer(n),s=t.errorTime?.timer(n);let a=!1;try{t.queries?.increment({[n]:!0}),yield*e(...r)}catch(e){throw a=!0,s?.(),t.errors?.increment({[n]:!0}),e}finally{t.queries?.decrement({[n]:!0}),a||i?.()}}}function fw(e,t,n){return async function(...r){const i=t?.queryTime?.timer(n),s=t?.errorTime?.timer(n);let a=!1;try{return t.queries?.increment({[n]:!0}),await e(...r)}catch(e){throw a=!0,s?.(),t.errors?.increment({[n]:!0}),e}finally{t.queries?.decrement({[n]:!0}),a||i?.()}}}class mw{log;components;validators;selectors;peerRouting;queryManager;network;datastorePrefix;constructor(e,t){const{validators:n,selectors:r,peerRouting:i,queryManager:s,network:a,logPrefix:o}=t;this.components=e,this.log=e.logger.forComponent(`${o}:content-fetching`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n,this.selectors=r,this.peerRouting=i,this.queryManager=s,this.network=a,this.get=e.metrics?.traceFunction("libp2p.kadDHT.get",this.get.bind(this),{optionsIndex:1})??this.get,this.put=e.metrics?.traceFunction("libp2p.kadDHT.put",this.put.bind(this),{optionsIndex:2})??this.put}async getLocal(e,t){this.log("getLocal %b",e);const n=uw(this.datastorePrefix,e);this.log("fetching record for key %k",n);const r=await this.components.datastore.get(n,t);this.log("found %k in local datastore",n);const i=zv.deserialize(r);return await nw(this.validators,i,t),i}async*sendCorrectionRecord(e,t,n,r){this.log("sendCorrection for %b",e);const i=dw(e,n);for(const{value:s,from:a}of t){if(Ln(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{const t=uw(this.datastorePrefix,e);this.log(`Storing corrected record for key ${t.toString()}`),await this.components.datastore.put(t,i.subarray(),r)}catch(e){this.log.error("failed error correcting self - %e",e)}continue}let t=!1;const o={type:Nv.PUT_VALUE,key:e,record:i};for await(const e of this.network.sendRequest(a,o,r))"PEER_RESPONSE"===e.name&&null!=e.record&&Ln(e.record.value,zv.deserialize(i).value)&&(t=!0),yield e;if(!t)throw new Gv("Could not send correction");this.log.error("failed error correcting entry")}}async*put(e,t,n){this.log("put key %b value %b",e,t);const r=dw(e,t),i=uw(this.datastorePrefix,e);this.log(`storing record for key ${i.toString()}`),await this.components.datastore.put(i,r.subarray(),n),yield*nc(this.peerRouting.getClosestPeers(e,{...n,signal:n.signal}),t=>Vv(t,t=>async()=>{if("FINAL_PEER"!==t.name)return[t];const i=[],s={type:Nv.PUT_VALUE,key:e,record:r};this.log("send put to %p",t.peer.id);for await(const e of this.network.sendRequest(t.peer.id,s,{...n,path:t.path}))i.push(e),"PEER_RESPONSE"===e.name&&(null!=e.record&&Ln(e.record.value,zv.deserialize(r).value)||i.push(Jv({from:t.peer.id,error:new Gv("Value not put correctly"),path:e.path},n)));return i}),e=>Sm(e,{ordered:!1,concurrency:10}),async function*(e){for await(const t of e)yield*t})}async*get(e,t){this.log("get %b",e);const n=[];for await(const r of this.getMany(e,t))"VALUE"!==r.name?yield r:n.push(r);if(0===n.length)return;const r=n.map(e=>e.value);let i=0;try{i=function(e,t,n){if(0===n.length)throw new We("No records given");const r=mr(t).split("/");if(r.length<3)throw new We("Record key does not have a selector function");const i=e[r[1].toString()];if(null==i)throw new Hv(`No selector function configured for key type "${r[1]}"`);return 1===n.length?0:i(t,n)}(this.selectors,e,r)}catch(e){if("InvalidParametersError"!==e.name)throw e}const s=r[i];if(this.log("GetValue %b %b",e,s),null==s)throw new nt("Best value was not found");yield*this.sendCorrectionRecord(e,n,s,{...t,path:{index:-1,queued:0,running:0,total:0}}),yield n[i]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{const n=await this.getLocal(e,t);yield Xv({value:n.value,from:this.components.peerId,path:{index:-1,running:0,queued:0,total:0}},t)}catch(t){this.log("error getting local value for %b",e,t)}const n=this;yield*this.queryManager.run(e,async function*({peer:r,signal:i,path:s}){for await(const a of n.peerRouting.getValueOrPeers(r.id,e,{...t,signal:i,path:s}))yield a,"PEER_RESPONSE"===a.name&&null!=a.record&&(yield Xv({from:r.id,value:a.record.value,path:s},t))},t)}}function yw(e,t){const n={id:e.id.toMultihash().bytes,multiaddrs:(e.multiaddrs??[]).map(e=>e.bytes),connection:t};return n}function bw(e){if(null==e.id)throw new Error("Invalid peer in message");return{id:qo(xn(e.id)),multiaddrs:(e.multiaddrs??[]).map(e=>Pu(e))}}class gw{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){const{network:n,peerRouting:r,queryManager:i,routingTable:s,providers:a,logPrefix:o}=t;this.components=e,this.log=e.logger.forComponent(`${o}:content-routing`),this.network=n,this.peerRouting=r,this.queryManager=i,this.routingTable=s,this.providers=a,this.findProviders=e.metrics?.traceFunction("libp2p.kadDHT.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>("PROVIDER"===e.name&&(t.providers??=[],t.providers.push(...e.providers.map(e=>e.id.toString()))),t)})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.kadDHT.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&"ADD_PROVIDER"===e.messageName&&(t.providers??=[],t.providers.push(e.from.toString())),t)})??this.provide}async*provide(e,t,n={}){this.log("provide %s",e);const r=e.multihash.bytes;await this.providers.addProvider(e,this.components.peerId,n);const i={type:Nv.ADD_PROVIDER,key:r,providers:[yw({id:this.components.peerId,multiaddrs:t})]};let s=0;const a=this,o=Md({objectMode:!0}),u=new Gd({concurrency:10});u.addEventListener("idle",()=>{o.end()}),u.addEventListener("failure",e=>{this.log.error("error publishing provider record to peer - %e",e.detail.error)}),u.add(async()=>{const t=[];for await(const e of this.peerRouting.getClosestPeers(r,n))o.push(e),"FINAL_PEER"===e.name&&t.push(e);t.forEach(t=>{u.add(async()=>{for await(const r of async function*(t){try{a.log("sending provider record for %s to %p",e,t.peer.id);for await(const r of a.network.sendMessage(t.peer.id,i,{...n,path:t.path}))"PEER_RESPONSE"===r.name&&(a.log("sent provider record for %s to %p",e,t.peer.id),s++),yield r}catch(e){a.log.error("error sending provide record to peer %p - %e",t.peer.id,e),yield Jv({from:t.peer.id,error:e,path:t.path},n)}}(t))o.push(r)}).catch(e=>{this.log.error("error publishing provider record to peer - %e",e)})})}).catch(e=>{o.end(e)}),yield*o,this.log("sent provider records to %d peers",s)}async*findProviders(e,t){const n=this.routingTable.kBucketSize;let r=0;const i=e.multihash.bytes,s=this;this.log("findProviders %c",e);const a=await this.providers.getProviders(e,t);if(a.length>0){const e=[];for(const r of a.slice(0,n))try{const n=await this.components.peerStore.get(r,t);e.push({id:r,multiaddrs:n.addresses.map(({multiaddr:e})=>e)})}catch(e){if("NotFoundError"!==e.name)throw e;this.log("no peer store entry for %p",r)}if(yield Qv({from:this.components.peerId,messageType:Nv.GET_PROVIDERS,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),yield Zv({from:this.components.peerId,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),r+=e.length,r>=n)return}const o=async function*({peer:e,signal:n,path:r}){const a={type:Nv.GET_PROVIDERS,key:i};yield*s.network.sendRequest(e.id,a,{...t,signal:n,path:r})},u=new ed(a);for await(const s of this.queryManager.run(i,o,t))if(yield s,"PEER_RESPONSE"===s.name){this.log("Found %d provider entries for %c and %d closer peers",s.providers.length,e,s.closer.length);const i=[];for(const e of s.providers)u.has(e.id)||(u.add(e.id),i.push(e));if(i.length>0&&(yield Zv({from:s.from,providers:i,path:s.path},t),r+=i.length,r>=n))return}}}class vw extends Ft{log;protocol;running;components;timeout;metrics;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:network`),this.running=!1,this.protocol=t.protocol,this.timeout=new Xd({...t.timeout??{},metrics:e.metrics,metricName:`${t.metricsPrefix}_network_message_send_times_milliseconds`}),this.metrics={operations:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_outbound_rpc_requests_total`),errors:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_outbound_rpc_errors_total`)},this.sendRequest=e.metrics?.traceFunction("libp2p.kadDHT.sendRequest",this.sendRequest.bind(this),{optionsIndex:2,getAttributesFromArgs:([e,t],n)=>({...n,to:e.toString(),"message type":`${t.type}`}),getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach((e,n)=>{t[`providers-${n}`]=e.id.toString()}),e.closer.length>0&&e.closer.forEach((e,n)=>{t[`closer-${n}`]=e.id.toString()})),t)})??this.sendRequest,this.sendMessage=e.metrics?.traceFunction("libp2p.kadDHT.sendMessage",this.sendMessage.bind(this),{optionsIndex:2,getAttributesFromArgs:([e,t],n)=>({...n,to:e.toString(),"message type":`${t.type}`}),getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach((e,n)=>{t[`providers-${n}`]=e.id.toString()}),e.closer.length>0&&e.closer.forEach((e,n)=>{t[`closer-${n}`]=e.id.toString()})),t)})??this.sendMessage}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}isStarted(){return this.running}async*sendRequest(e,t,n){if(!this.running)return;const r=t.type;if(null==r)throw new We("Message type was missing");let i;const s=this.timeout.getTimeoutSignal(n);n={...n,signal:s};try{this.metrics.operations?.increment({[r]:!0}),this.log("dialling %p",e),yield ew({peer:e,path:n.path},n),i=await this.components.connectionManager.openStream(e,this.protocol,n),this.log("sending %s to %p",t.type,e),yield Wv({to:e,type:r,path:n.path},n);const s=await this._writeReadMessage(i,t,n);i.close(n).catch(t=>{this.log.error("error closing stream to %p - %e",e,t),i?.abort(t)}),yield Qv({from:e,messageType:s.type,closer:s.closer.map(bw),providers:s.providers.map(bw),record:null==s.record?void 0:zv.deserialize(s.record),path:n.path},n)}catch(s){this.metrics.errors?.increment({[r]:!0}),i?.abort(s),!0!==n.signal?.aborted&&this.log.error("could not send %s to %p - %e",t.type,e,s),yield Jv({from:e,error:s,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async*sendMessage(e,t,n){if(!this.running)return;const r=t.type;if(null==r)throw new We("Message type was missing");let i;const s=this.timeout.getTimeoutSignal(n);n={...n,signal:s};try{this.metrics.operations?.increment({[r]:!0}),this.log("dialling %p",e),yield ew({peer:e,path:n.path},n),i=await this.components.connectionManager.openStream(e,this.protocol,n),this.log("sending %s to %p",t.type,e),yield Wv({to:e,type:r,path:n.path},n),await this._writeMessage(i,t,n),i.close(n).catch(t=>{this.log.error("error closing stream to %p - %e",e,t),i?.abort(t)}),yield Qv({from:e,messageType:r,path:n.path},n)}catch(t){this.metrics.errors?.increment({[r]:!0}),i?.abort(t),yield Jv({from:e,error:t,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async _writeMessage(e,t,n){const r=mc(e);await r.write(t,qv,n)}async _writeReadMessage(e,t,n){const r=mc(e);await r.write(t,qv,n);const i=await r.read(qv,n);return i.closer.forEach(e=>{this.safeDispatchEvent("peer",{detail:bw(e)})}),i.providers.forEach(e=>{this.safeDispatchEvent("peer",{detail:bw(e)})}),i}}function ww(e,t){if(e.byteLength!==t.byteLength)throw new Error("Inputs should have the same length");for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}class Tw{originDhtKey;capacity;peerDistances;constructor(e,t){this.originDhtKey=e,this.capacity=t,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return[...this.peerDistances]}async add(e,t={index:-1,queued:0,running:0,total:0},n){const r=await ow(e.id,n);this.addWithKadId(e,r,t)}addWithKadId(e,t,n={index:-1,queued:0,running:0,total:0}){if(null!=this.peerDistances.find(t=>t.peer.id.equals(e.id)))return;const r={peer:e,distance:vb(this.originDhtKey,t),path:n};if(this.peerDistances.length===this.capacity){const e=this.peerDistances[this.peerDistances.length-1];if(null!=e&&-1!==ww(r.distance,e.distance))return}let i=!1;for(let e=0;e<this.peerDistances.length;e++){const t=ww(this.peerDistances[e].distance,r.distance);if(0===t||1===t){i=!0,this.peerDistances.splice(e,0,r);break}}i||this.peerDistances.push(r),this.peerDistances=this.peerDistances.slice(0,this.capacity)}async isCloser(e,t){return 0===this.length||-1===ww(vb(await ow(e,t),this.originDhtKey),this.peerDistances[this.peerDistances.length-1].distance)}async anyCloser(e,t){return 0!==e.length&&Promise.any(e.map(async e=>this.isCloser(e,t)))}}class Ew{log;routingTable;network;validators;queryManager;components;constructor(e,t){this.routingTable=t.routingTable,this.network=t.network,this.validators=t.validators,this.queryManager=t.queryManager,this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:peer-routing`),this.findPeer=e.metrics?.traceFunction("libp2p.kadDHT.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.kadDHT.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async findPeerLocal(e,t){let n;const r=await this.routingTable.find(e,t);if(null!=r){this.log("findPeerLocal found %p in routing table",e);try{n=await this.components.peerStore.get(r,t)}catch(e){if("NotFoundError"!==e.name)throw e}}if(null==n)try{n=await this.components.peerStore.get(e,t)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=n)return this.log("findPeerLocal found %p in peer store",e),{id:n.id,multiaddrs:n.addresses.map(e=>e.multiaddr)}}async*_getValueSingle(e,t,n){const r={type:Nv.GET_VALUE,key:t};yield*this.network.sendRequest(e,r,n)}async*getPublicKeyFromNode(e,t={}){const n=Bn([iw,e.toMultihash().bytes]),r={index:-1,queued:0,running:0,total:0};for await(const i of this._getValueSingle(e,n,{...t,path:r}))if(yield i,"PEER_RESPONSE"===i.name&&null!=i.record){const n=jo(Mo(i.record.value));if(!n.equals(e))throw new Qe("public key does not match id");if(null==n.publicKey)throw new Qe("public key missing");yield Xv({from:e,value:i.record.value,path:r},t)}throw new Gv(`Node not responding with its public key: ${e.toString()}`)}async*findPeer(e,t={}){if(this.log("findPeer %p",e),!1!==t.useCache){const n=await this.findPeerLocal(e,t);if(null!=n)return this.log("found local"),void(yield Yv({from:this.components.peerId,peer:n,path:{index:-1,queued:0,running:0,total:0}},t))}let n=!1;if(!1!==t.useNetwork){const r=this,i=async function*({peer:n,signal:i,path:s}){const a={type:Nv.FIND_NODE,key:e.toMultihash().bytes};for await(const o of r.network.sendRequest(n.id,a,{...t,signal:i,path:s}))if(yield o,"PEER_RESPONSE"===o.name){const n=o.closer.find(t=>t.id.equals(e));null!=n&&(yield Yv({from:o.from,peer:n,path:o.path},t))}};for await(const r of this.queryManager.run(e.toMultihash().bytes,i,t))"FINAL_PEER"===r.name&&(n=!0),yield r}if(!n)throw new nt("Not found")}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);const n=await aw(e,t),r=new Tw(n,this.routingTable.kBucketSize),i=this;yield*this.queryManager.run(e,async function*({peer:n,path:s,peerKadId:a,signal:o}){i.log("getClosestPeers asking %p",n.id);const u={type:Nv.FIND_NODE,key:e};yield*i.network.sendRequest(n.id,u,{...t,signal:o,path:s}),r.addWithKadId(n,a,s)},t),this.log("found %d peers close to %b",r.length,e);for(let{peer:e,path:n}of r.peers)try{if(0===e.multiaddrs.length&&(e=await i.components.peerStore.getInfo(e.id,t)),0===e.multiaddrs.length)continue;yield Yv({from:this.components.peerId,peer:await i.components.peerStore.getInfo(e.id,t),path:{index:n.index,queued:0,running:0,total:0}},t)}catch{continue}}async*getValueOrPeers(e,t,n){for await(const r of this._getValueSingle(e,t,n)){if("PEER_RESPONSE"===r.name&&null!=r.record)try{await this._verifyRecordOnline(r.record,n)}catch(e){const t="invalid record received, discarded";this.log(t),yield Jv({from:r.from,error:new Gv(t),path:n.path},n);continue}yield r}}async _verifyRecordOnline(e,t){if(null==e.timeReceived)throw new Kv("invalid record received");await nw(this.validators,new zv(e.key,e.value,e.timeReceived),t)}async getClosestPeersOffline(e,t){const n=[];try{const r=qo(xn(e)),i=await this.components.peerStore.get(r,t);n.push({id:i.id,multiaddrs:i.addresses.map(({multiaddr:e})=>e)})}catch{}const r=await aw(e,t),i=this.routingTable.closestPeers(r,t);for(const e of i)try{n.push(await this.components.peerStore.getInfo(e,t))}catch(e){if("NotFoundError"!==e.name)throw e}return n.length>0?this.log("getClosestPeersOffline returning the %d closest peer(s) we know to %b",n.length,e):this.log("getClosestPeersOffline could not any peers close to %b with %d peers in the routing table",e,this.routingTable.size),n}}class xw{log;datastore;datastorePrefix;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:providers`),this.datastorePrefix=`${t.datastorePrefix}/provider`,this.datastore=e.datastore}async addProvider(e,t,n){this.log.trace("%p provides %s",t,e),await this.writeProviderEntry(e,t,n)}async removeProvider(e,t,n){const r=lw(this.datastorePrefix,e,t);this.log.trace("%p no longer provides %s",t,e),await this.datastore.delete(r,n)}async getProviders(e,t){this.log.trace("get providers for %c",e);const n=await this.loadProviders(e,t);return this.log.trace("got %d providers for %c",n.size,e),[...n.keys()]}async writeProviderEntry(e,t,n){const r=lw(this.datastorePrefix,e,t),i=ga(n?.time?.getTime()??Date.now());await this.datastore.put(r,i,n)}async loadProviders(e,t){const n=new Xu,r=lw(this.datastorePrefix,e);for await(const e of this.datastore.query({prefix:r.toString()},t)){const{peerId:t}=cw(e.key);n.set(t,pw(e.value))}return n}}async function*Pw(e){const{key:t,startingPeers:n,ourPeerId:r,query:i,alpha:s,path:a,numPaths:o,log:u,peersSeen:d,connectionManager:c,signal:l}=e,p=Md({objectMode:!0}),h=new Gd({concurrency:s,sort:(e,t)=>ww(e.options.distance,t.options.distance)});h.addEventListener("idle",()=>{p.push(function(e,t={}){const n={...e,name:"PATH_ENDED",type:8};return t.onProgress?.(new CustomEvent("kad-dht:query:path-ended",{detail:n})),n}({path:{index:a,queued:h.queued,running:h.running,total:h.size}},e)),p.end()}),h.addEventListener("failure",e=>{u.error("error during query - %e",e.detail.error)});const f=()=>{h.abort(),p.end(new Ge)};l.addEventListener("abort",f);try{const y=await aw(t,{signal:l});function m(n,s){if(null==n)return;d.add(n.id.toMultihash().bytes);const f=vb(s,y);h.add(async()=>{try{for await(const b of i({...e,key:t,peer:n,path:{index:a,queued:h.queued,running:h.running,total:h.size},numPaths:o,peerKadId:s,signal:l})){if("PEER_RESPONSE"===b.name)for(const e of b.closer){if(d.has(e.id.toMultihash().bytes)){u("already seen %p in query",e.id);continue}if(r.equals(e.id)){u("not querying ourselves");continue}if(!await c.isDialable(e.multiaddrs)){u("not querying undialable peer");continue}const i=await ow(e.id,{signal:l});-1===ww(vb(i,y),f)?(u("querying closer peer %p",e.id),m(e,i)):u("skipping %p as they are not closer to %b than %p",e.id,t,n.id)}p.push({...b,path:{index:a,queued:h.queued,running:h.running,total:h.size}})}}catch(t){p.push(Jv({from:n.id,error:t,path:{index:a,queued:h.queued,running:h.running-1,total:h.size-1}},e))}},{distance:f}).catch(e=>{u.error("error during query - %e",e)})}await Promise.all(n.map(async e=>{m({id:e,multiaddrs:[]},await ow(e,{signal:l}))})),yield*p}finally{l.removeEventListener("abort",f)}}class Sw{disjointPaths;alpha;shutDownController;running;logger;peerId;connectionManager;routingTable;initialQuerySelfHasRun;logPrefix;allowQueryWithZeroPeers;constructor(e,t){this.logPrefix=t.logPrefix,this.disjointPaths=t.disjointPaths??20,this.alpha=t.alpha??10,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.routingTable=t.routingTable,this.logger=e.logger,this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.allowQueryWithZeroPeers=t.allowQueryWithZeroPeers??!1,this.shutDownController=new AbortController,this.running=!1}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.shutDownController=new AbortController)}async stop(){this.running=!1,this.shutDownController.abort()}async*run(e,t,n={}){if(!this.running)throw new Error("QueryManager not started");if(null==n.signal){const e=AbortSignal.timeout(18e4);n={...n,signal:e}}const r=new AbortController,i=Jd([this.shutDownController.signal,r.signal,n.signal]),s=this.logger.forComponent(`${this.logPrefix}:query:`+mr(e,"base58btc"));let a=!1;try{0!==this.routingTable.size||this.allowQueryWithZeroPeers||(s("routing table was empty, waiting for some peers before running%s query",!0===n.isSelfQuery?" self":""),await _d(this.routingTable,"peer:add",{signal:i,filter:e=>!this.peerId.equals(e.detail)}),s("routing table has peers, continuing with%s query",!0===n.isSelfQuery?" self":"")),!0!==n.isSelfQuery&&null!=this.initialQuerySelfHasRun&&(s("waiting for initial self query before continuing"),await $d(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),s("query:start");const r=await aw(e,{signal:i}),o=this.routingTable.closestPeers(r,{count:this.routingTable.kBucketSize}),u=o.sort(()=>Math.random()>.5?1:-1).reduce((e,t,n)=>(e[n%this.disjointPaths].push(t),e),new Array(this.disjointPaths).fill(0).map(()=>[])).filter(e=>e.length>0);if(0===o.length)return void s.error("running query with no peers");const d=pd(1024),c=u.map((r,a)=>Pw({...n,key:e,startingPeers:r,ourPeerId:this.peerId,signal:i,query:t,path:a,numPaths:u.length,alpha:this.alpha,log:s,peersSeen:d,onProgress:n.onProgress,connectionManager:this.connectionManager}));for await(const e of tc(...c)){if("QUERY_ERROR"===e.name&&s.error("query error - %e",e.error),"PEER_RESPONSE"===e.name)for(const t of[...e.closer,...e.providers])await this.connectionManager.isDialable(t.multiaddrs,{signal:i})&&await this.routingTable.add(t.id,{signal:i});i.throwIfAborted(),yield e}a=!0}catch(e){if(this.running)throw e}finally{a||(s("query exited early"),r.abort()),i.clear(),s("query finished")}}}function Aw(e){if(null!=e[Symbol.asyncIterator])return(async()=>{let t=0;for await(const n of e)t++;return t})();{let t=0;for(const n of e)t++;return t}}class Cw{log;peerId;peerRouting;events;count;interval;initialInterval;queryTimeout;running;timeoutId;controller;initialQuerySelfHasRun;querySelfPromise;constructor(e,t){this.peerId=e.peerId,this.log=e.logger.forComponent(`${t.logPrefix}:query-self`),this.events=e.events,this.running=!1,this.peerRouting=t.peerRouting,this.count=t.count??20,this.interval=t.interval??3e5,this.initialInterval=t.initialInterval??1e3,this.queryTimeout=t.queryTimeout??5e3,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.querySelf=fw(this.querySelf.bind(this),t.operationMetrics,"SELF_QUERY")}isStarted(){return this.running}start(){this.running||(this.running=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query - %e",e)})},this.initialInterval))}stop(){this.running=!1,null!=this.timeoutId&&clearTimeout(this.timeoutId),null!=this.controller&&this.controller.abort()}async querySelf(){if(this.running){if(null!=this.querySelfPromise)return this.log("joining existing self query"),this.querySelfPromise.promise;if(this.querySelfPromise=Cd(),this.running){this.controller=new AbortController;const e=[this.controller.signal];if(null==this.initialQuerySelfHasRun){const t=AbortSignal.timeout(this.queryTimeout);e.push(t)}const t=Jd(e);try{this.log("run self-query, look for %d peers timing out after %dms",this.count,this.queryTimeout);const e=Date.now(),n=await nc(this.peerRouting.getClosestPeers(this.peerId.toMultihash().bytes,{signal:t,isSelfQuery:!0}),e=>ph(e,this.count),async e=>Aw(e));t?.throwIfAborted();const r=Date.now()-e;this.log("self-query found %d peers in %dms",n,r),this.events.dispatchEvent(new CustomEvent("kad-dht:query:self",{detail:{peers:n,duration:r}}))}catch(e){this.log.error("self-query error - %e",e)}finally{t.clear(),null!=this.initialQuerySelfHasRun&&(this.initialQuerySelfHasRun.resolve(),this.initialQuerySelfHasRun=void 0)}}this.querySelfPromise.resolve(),this.querySelfPromise=void 0,this.running&&(this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query - %e",e)})},this.interval))}else this.log("skip self-query because we are not started")}}class kw extends Ft{log;reprovideQueue;maxQueueSize;datastore;timeout;reprovideTimeout;running;shutdownController;reprovideThreshold;contentRouting;datastorePrefix;addressManager;validity;interval;peerId;constructor(e,t){super(),this.log=e.logger.forComponent(`${t.logPrefix}:reprovider`),this.peerId=e.peerId,this.reprovideQueue=new Gd({concurrency:t.concurrency??10,metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_queue`}),this.reprovideTimeout=new Xd({...t.timeout??{},metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_timeout_milliseconds`}),this.datastore=e.datastore,this.addressManager=e.addressManager,this.datastorePrefix=`${t.datastorePrefix}/provider`,this.reprovideThreshold=t.threshold??864e5,this.maxQueueSize=t.maxQueueSize??16384,this.validity=t.validity??Dv,this.interval=t.interval??Mv,this.contentRouting=t.contentRouting,this.running=!1,this.reprovide=fw(this.reprovide.bind(this),t.operationMetrics,"PROVIDE")}start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.timeout=setTimeout(()=>{this.processRecords({signal:AbortSignal.timeout(Fv)}).catch(e=>{this.log.error("error running process to reprovide/cleanup - %e",e)})},this.interval))}stop(){this.running=!1,this.reprovideQueue.clear(),clearTimeout(this.timeout),this.shutdownController?.abort()}async processRecords(e){try{this.safeDispatchEvent("reprovide:start"),this.log("starting reprovide/cleanup");for await(const t of this.datastore.query({prefix:this.datastorePrefix},e))try{const{cid:n,peerId:r}=cw(t.key),i=pw(t.value).getTime()+this.validity,s=Date.now(),a=s>i,o=this.peerId.equals(r);this.log.trace("comparing: %d (now) < %d (expires) = %s %s",s,i,a,a?"(expired)":"(valid)"),a&&!o&&await this.datastore.delete(t.key,e),this.shouldReprovide(o,i)&&(this.log("reproviding %c as it is within the reprovide threshold (%d)",n,this.reprovideThreshold),this.queueReprovide(n).catch(e=>{this.log.error("could not reprovide %c - %e",n,e)}))}catch(e){this.log.error("error processing datastore key %s - %s",t.key,e.message)}this.log("reprovide/cleanup successful")}finally{this.safeDispatchEvent("reprovide:end"),this.running&&(this.log("queuing next re-provide/cleanup run in %d ms",this.interval),this.timeout=setTimeout(()=>{this.processRecords({signal:AbortSignal.timeout(Fv)}).catch(e=>{this.log.error("error running re-provide - %e",e)})},this.interval))}}shouldReprovide(e,t){if(!e)return!1;const n=Date.now();return t<n||t-n<this.reprovideThreshold}async queueReprovide(e,t){if(!this.running)return;this.log.trace("waiting for queue capacity before adding %c to re-provide queue",e),await this.reprovideQueue.onSizeLessThan(this.maxQueueSize,t);const n=this.reprovideQueue.queue.find(t=>t.options.cid.equals(e));if(null!=n)return this.log.trace("not adding %c to re-provide queue - already in queue",e),n.join();this.log.trace("adding %c to re-provide queue",e),this.reprovideQueue.add(async t=>{if(t.signal?.throwIfAborted(),!this.running)return;this.log.trace("re-providing %c",e);const n=this.reprovideTimeout.getTimeoutSignal(t);try{await this.reprovide(t.cid,t)}finally{this.reprovideTimeout.cleanUp(n)}this.log.trace("re-provided %c",e)},{signal:this.shutdownController?.signal,cid:e}).catch(t=>{this.log.error("could not re-provide key %c - %e",e,t)})}async reprovide(e,t){await uh(this.contentRouting.provide(e,this.addressManager.getAddresses(),t))}}class Iw{routingTable;components;closestPeers;newPeers;refreshInterval;peerSetSize;timeout;closeTagName;closeTagValue;log;running;constructor(e,t){this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.routingTable=t.routingTable,this.refreshInterval=t.refreshInterval??5e3,this.peerSetSize=t.peerSetSize??20,this.closeTagName=t.closeTagName??"kad-close",this.closeTagValue=t.closeTagValue??50,this.closestPeers=new ed,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}async start(){if(this.running)return;this.running=!0;const e=await ow(this.components.peerId);this.newPeers=new Tw(e,this.peerSetSize),this.routingTable.addEventListener("peer:ping",this.onPeerPing),this.timeout=setInterval(()=>{this.updatePeerTags().catch(e=>{this.log.error("error updating peer tags - %e",e)})},this.refreshInterval)}stop(){this.running=!1,this.routingTable.removeEventListener("peer:ping",this.onPeerPing),clearTimeout(this.timeout)}onPeerPing(e){this.newPeers?.add({id:e.detail,multiaddrs:[]}).catch(e=>{this.log.error("error adding peer to distance list - %e",e)})}async updatePeerTags(){const e=new ed(this.newPeers?.peers.map(({peer:e})=>e.id)),t=e.difference(this.closestPeers),n=this.closestPeers.difference(e);this.closestPeers=e,await Promise.all([...[...t].map(async e=>{await this.components.peerStore.merge(e,{tags:{[this.closeTagName]:{value:this.closeTagValue},[Rv]:{value:1}}})}),...[...n].map(async e=>{await this.components.peerStore.merge(e,{tags:{[this.closeTagName]:void 0,[Rv]:void 0}})})])}}function Dw(e){return Array.isArray(e?.peers)}class Mw{peerId;root;localPeer;prefixLength;splitThreshold;kBucketSize;numberOfNodesToPing;lastPingThreshold;ping;verify;onAdd;onRemove;onMove;addingPeerMap;constructor(e,t){this.peerId=e.peerId,this.prefixLength=t.prefixLength??Rw,this.kBucketSize=t.kBucketSize??Fw,this.splitThreshold=t.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=t.numberOfOldContactsToPing??_w,this.lastPingThreshold=t.lastPingThreshold??Nw,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=Rc({name:`${t.metricsPrefix}_adding_peer_map`,metrics:e.metrics}),this.root={prefix:"",depth:0,peers:[]}}async start(){await this.addSelfPeer(this.peerId)}stop(){this.addingPeerMap.clear(),this.root={prefix:"",depth:0,peers:[]}}async addSelfPeer(e,t){this.localPeer={peerId:e,kadId:await ow(e,t),lastPing:Date.now()}}async add(e,t){const n={peerId:e,kadId:await ow(e,t),lastPing:0},r=this.addingPeerMap.get(e);if(null!=r)return r;try{const r=this._add(n,t);this.addingPeerMap.set(e,r),await r}finally{this.addingPeerMap.delete(e)}}async _add(e,t){const n=this._determineBucket(e.kadId);if(this._indexOf(n,e.kadId)>-1)return;if(n.peers.length===this.splitThreshold&&n.depth<this.prefixLength)return await this._split(n,t),void await this._add(e,t);if(n.peers.length<this.kBucketSize)return function(e,t){return e.lastPing<Date.now()-t}(e,this.lastPingThreshold)?void(await this.verify(e,t)&&(e.lastPing=Date.now(),await this._add(e,t))):(n.peers.push(e),void await(this.onAdd?.(e,n,t)));const r=n.peers.filter(e=>!(e.peerId.equals(this.localPeer?.peerId)||e.lastPing>Date.now()-this.lastPingThreshold)).sort((e,t)=>e.lastPing<t.lastPing?-1:e.lastPing>t.lastPing?1:0).slice(0,this.numberOfNodesToPing);let i=!1;for await(const e of this.ping(r,t))i=!0,await this.remove(e.kadId,t);i&&await this._add(e,t)}*closest(e,t){const n=new Tw(e,t?.count??this.kBucketSize);for(const e of this.toIterable())!0!==t?.exclude?.some(t=>t.equals(e.peerId))&&n.addWithKadId({id:e.peerId,multiaddrs:[]},e.kadId);yield*Vv(n.peers,({peer:e})=>e.id)}count(){return function e(t){if(Dw(t))return t.peers.length;let n=0;return null!=t.left&&(n+=e(t.left)),null!=t.right&&(n+=e(t.right)),n}(this.root)}get(e){const t=this._determineBucket(e),n=this._indexOf(t,e);return t.peers[n]}async remove(e,t){const n=this._determineBucket(e),r=this._indexOf(n,e);if(r>-1){const e=n.peers.splice(r,1)[0];await(this.onRemove?.(e,n,t))}}*toIterable(){yield*function*e(t){Dw(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+mr(vb(e,t),"base16"))}_determineBucket(e){const t=mr(e,"base2");return function e(n,r=0){return Dw(n)?n:e("0"===t[r]?n.left:n.right,r+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex(e=>Ln(e.kadId,t))}async _split(e,t){const n={prefix:"0",depth:e.depth+1,peers:[]},r={prefix:"1",depth:e.depth+1,peers:[]};for(const i of e.peers)"0"===mr(i.kadId,"base2")[e.depth]?(n.peers.push(i),await(this.onMove?.(i,e,n,t))):(r.peers.push(i),await(this.onMove?.(i,e,r,t)));!function(e,t,n){delete e.peers,e.left=t,e.right=n,""===e.prefix&&(delete e.depth,delete e.prefix)}(e,n,r)}}const Fw=20,Rw=6,_w=3,Lw="kad-peer",Nw=6e5;class Ow extends Ft{kBucketSize;kb;network;closestPeerTagger;log;components;running;pingNewContactTimeout;pingNewContactQueue;pingOldContactTimeout;pingOldContactQueue;populateFromDatastoreOnStart;populateFromDatastoreLimit;protocol;peerTagName;peerTagValue;metrics;shutdownController;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.kBucketSize=t.kBucketSize??Fw,this.running=!1,this.protocol=t.protocol,this.network=t.network,this.peerTagName=t.peerTagName??Lw,this.peerTagValue=t.peerTagValue??1,this.pingOldContacts=this.pingOldContacts.bind(this),this.verifyNewContact=this.verifyNewContact.bind(this),this.peerAdded=this.peerAdded.bind(this),this.peerRemoved=this.peerRemoved.bind(this),this.populateFromDatastoreOnStart=t.populateFromDatastoreOnStart??!0,this.populateFromDatastoreLimit=t.populateFromDatastoreLimit??1e3,this.shutdownController=new AbortController,this.pingOldContactQueue=new xc({concurrency:t.pingOldContactConcurrency??20,metricName:`${t.metricsPrefix}_ping_old_contact_queue`,metrics:this.components.metrics,maxSize:t.pingOldContactMaxQueueSize??100}),this.pingOldContactTimeout=new Xd({...t.pingOldContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_old_contact_time_milliseconds`}),this.pingNewContactQueue=new xc({concurrency:t.pingNewContactConcurrency??20,metricName:`${t.metricsPrefix}_ping_new_contact_queue`,metrics:this.components.metrics,maxSize:t.pingNewContactMaxQueueSize??100}),this.pingNewContactTimeout=new Xd({...t.pingNewContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_new_contact_time_milliseconds`}),this.kb=new Mw(e,{kBucketSize:t.kBucketSize,prefixLength:t.prefixLength,splitThreshold:t.splitThreshold,numberOfOldContactsToPing:t.numberOfOldContactsToPing,lastPingThreshold:t.lastPingThreshold,ping:this.pingOldContacts,verify:this.verifyNewContact,onAdd:this.peerAdded,onRemove:this.peerRemoved,metricsPrefix:t.metricsPrefix}),this.closestPeerTagger=new Iw(this.components,{logPrefix:t.logPrefix,routingTable:this,peerSetSize:t.closestPeerSetSize,refreshInterval:t.closestPeerSetRefreshInterval,closeTagName:t.closeTagName,closeTagValue:t.closeTagValue}),null!=this.components.metrics&&(this.metrics={routingTableSize:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_size`),routingTableKadBucketTotal:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_total`),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_average_occupancy`),routingTableKadBucketMinOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_min_occupancy`),routingTableKadBucketMaxOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_max_occupancy`),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_max_depth`),kadBucketEvents:this.components.metrics.registerCounterGroup(`${t.metricsPrefix}_kad_bucket_events_total`)})}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.shutdownController=new AbortController,await kt(this.closestPeerTagger,this.kb))}async afterStart(){let e=0;Promise.resolve().then(async()=>{if(!this.populateFromDatastoreOnStart)return;const t=Jd([this.shutdownController.signal,AbortSignal.timeout(2e4)]);try{for(const n of await this.components.peerStore.all({filters:[e=>e.protocols.includes(this.protocol)&&e.tags.has(Lw)],limit:this.populateFromDatastoreLimit,signal:t})){if(!this.running)return;try{await this.add(n.id,{signal:t}),e++}catch(e){this.log("failed to add peer %p to routing table, removing kad-dht peer tags - %e"),await this.components.peerStore.merge(n.id,{tags:{[this.peerTagName]:void 0}})}}}finally{t.clear()}this.log("added %d peer store peers to the routing table",e)}).catch(t=>{this.log.error("error adding %d, peer store peers to the routing table - %e",e,t)})}async stop(){this.running=!1,await It(this.closestPeerTagger,this.kb),this.pingOldContactQueue.abort(),this.pingNewContactQueue.abort(),this.shutdownController.abort()}async peerAdded(e,t,n){this.components.peerId.equals(e.peerId)||await this.components.peerStore.merge(e.peerId,{tags:{[this.peerTagName]:{value:this.peerTagValue}}},n),this.updateMetrics(),this.metrics?.kadBucketEvents.increment({peer_added:!0}),this.safeDispatchEvent("peer:add",{detail:e.peerId})}async peerRemoved(e,t,n){this.components.peerId.equals(e.peerId)||await this.components.peerStore.merge(e.peerId,{tags:{[this.peerTagName]:void 0}},n),this.updateMetrics(),this.metrics?.kadBucketEvents.increment({peer_removed:!0}),this.safeDispatchEvent("peer:remove",{detail:e.peerId})}async*pingOldContacts(e,t){if(!this.running)return;const n=[];for(const r of e)null!=this.kb.get(r.kadId)?(this.metrics?.kadBucketEvents.increment({ping_old_contact:!0}),n.push(async()=>{const e=this.pingOldContactQueue.find(r.peerId);return null!=e?(this.log("asked to ping contact %p was already being pinged",r.peerId),await e.join(t)?void 0:r):await this.pingOldContactQueue.add(async e=>{const t=this.pingOldContactTimeout.getTimeoutSignal(),n=Jd([t,this.shutdownController.signal,e?.signal]);try{return await this.pingContact(r,e)}catch{return this.metrics?.kadBucketEvents.increment({ping_old_contact_error:!0}),!0}finally{this.pingOldContactTimeout.cleanUp(t),n.clear()}},{peerId:r.peerId,signal:t?.signal})?void 0:r})):this.log("asked to ping contact %p that was not in routing table",r.peerId);for await(const e of Sm(n))null!=e&&(yield e)}async verifyNewContact(e,t){const n=this.pingNewContactTimeout.getTimeoutSignal(),r=Jd([n,this.shutdownController.signal,t?.signal]);try{const t=this.pingNewContactQueue.find(e.peerId);return null!=t?(this.log("joining existing ping to add new peer %p to routing table",e.peerId),await t.join({signal:r})):await this.pingNewContactQueue.add(async t=>(this.metrics?.kadBucketEvents.increment({ping_new_contact:!0}),this.log("pinging new peer %p before adding to routing table",e.peerId),this.pingContact(e,t)),{peerId:e.peerId,signal:r})}catch(t){return this.log.trace("tried to add peer %p but they were not online",e.peerId),this.metrics?.kadBucketEvents.increment({ping_new_contact_error:!0}),!1}finally{this.pingNewContactTimeout.cleanUp(n),r.clear()}}async pingContact(e,t){try{return this.log("pinging contact %p",e.peerId),await this.components.ping.ping(e.peerId,t),this.log("contact %p ping ok",e.peerId),this.safeDispatchEvent("peer:ping",{detail:e.peerId}),!0}catch(t){return this.log("error pinging old contact %p - %e",e.peerId,t),!1}}get size(){return null==this.kb?0:this.kb.count()}async find(e,t){const n=await ow(e,t);return this.kb.get(n)?.peerId}closestPeer(e){const t=this.closestPeers(e,{count:1});if(t.length>0)return t[0]}closestPeers(e,t){return null==this.kb?[]:[...this.kb.closest(e,t)]}async add(e,t){if(null==this.kb)throw new Error("RoutingTable is not started");await this.kb.add(e,t)}async remove(e,t){if(null==this.kb)throw new Error("RoutingTable is not started");const n=await ow(e,t);await this.kb.remove(n,t)}updateMetrics(){if(null==this.metrics||null==this.kb)return;let e=0,t=0,n=0,r=20,i=0;!function s(a){if(Dw(a))return a.depth>n&&(n=a.depth),t++,e+=a.peers.length,a.peers.length<r&&(r=a.peers.length),void(a.peers.length>i&&(i=a.peers.length));s(a.left),s(a.right)}(this.kb.root),this.metrics.routingTableSize.update(e),this.metrics.routingTableKadBucketTotal.update(t),this.metrics.routingTableKadBucketAverageOccupancy.update(Math.round(e/t)),this.metrics.routingTableKadBucketMinOccupancy.update(r),this.metrics.routingTableKadBucketMaxOccupancy.update(i),this.metrics.routingTableKadBucketMaxDepth.update(n)}}var Bw,Uw=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];class jw{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e,t){const{peerRouting:n,routingTable:r,refreshInterval:i,refreshQueryTimeout:s,logPrefix:a}=t;this.log=e.logger.forComponent(`${a}:routing-table:refresh`),this.peerRouting=n,this.routingTable=r,this.refreshInterval=i??3e5,this.refreshQueryTimeout=s??3e4,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}async afterStart(){this.log(`refreshing routing table every ${this.refreshInterval}ms`),this.refreshTable(!0)}async stop(){null!=this.refreshTimeoutId&&clearTimeout(this.refreshTimeoutId)}refreshTable(e=!1,t){this.log("refreshing routing table");const n=this._maxCommonPrefix(),r=this._getTrackedCommonPrefixLengthsForRefresh(n);this.log(`max common prefix length ${n}`),this.log(`tracked CPLs [ ${r.map(e=>e.toISOString()).join(", ")} ]`),Promise.all(r.map(async(i,s)=>{try{if(await this._refreshCommonPrefixLength(s,i,e,t),0===this._numPeersForCpl(n)){const n=Math.min(2*(s+1),r.length-1);for(let r=s+1;r<n+1;r++)try{await this._refreshCommonPrefixLength(r,i,e,t)}catch(e){this.log.error("failed to refresh entries with common prefix length %d - %e",r,e)}}}catch(e){this.log.error("failed to refresh entries with common prefix length - %e",e)}})).catch(e=>{this.log.error("failed to refresh table - %e",e)}).then(()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),null!=this.refreshTimeoutId.unref&&this.refreshTimeoutId.unref()}).catch(e=>{this.log.error("failed to set refresh timeout - %e",e)})}async _refreshCommonPrefixLength(e,t,n,r){if(!n&&t.getTime()>Date.now()-this.refreshInterval)return void this.log("not running refresh for cpl %s as time since last refresh not above interval",e);const i=this._generateRandomPeerId(e);this.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,i,this.routingTable.size);const s=Jd([r?.signal,AbortSignal.timeout(this.refreshQueryTimeout)]);try{const t=await Aw(this.peerRouting.getClosestPeers(i.toMultihash().bytes,{signal:s}));this.log(`found ${t} peers that were close to imaginary peer %p`,i),this.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,i,this.routingTable.size)}finally{s.clear()}}_getTrackedCommonPrefixLengthsForRefresh(e){e>15&&(e=15);const t=[];for(let n=0;n<=e;n++)t[n]=this.commonPrefixLengthRefreshedAt[n]??new Date;return t}_generateRandomPeerId(e){if(null==this.routingTable.kb)throw new Error("Routing table not started");if(null==this.routingTable.kb.localPeer)throw new Error("Local peer not set");const t=io(2);return qo(xn(this._makePeerId(this.routingTable.kb.localPeer.kadId,(t[1]<<8)+t[0],e)))}_makePeerId(e,t,n){if(n>15)throw new Error("Cannot generate peer ID for common prefix length greater than 15");const r=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1),i=65535<<16-(n+1),s=Uw[(r^32768>>n)&i|t&~i],a=new ArrayBuffer(34),o=new DataView(a,0,a.byteLength);return o.setUint8(0,ur.code),o.setUint8(1,32),o.setUint32(2,s,!1),new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}_maxCommonPrefix(){let e=0;for(const t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){let t=0;for(const n of this._prefixLengths())n===e&&t++;return t}*_prefixLengths(){if(null!=this.routingTable.kb?.localPeer)for(const{kadId:e}of this.routingTable.kb.toIterable()){const t=vb(this.routingTable.kb.localPeer.kadId,e);let n=0;for(const e of t){if(0!==e)break;n++}yield n}}}class qw{peerId;providers;peerStore;log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:add-provider`),this.peerId=e.peerId,this.providers=t.providers,this.peerStore=e.peerStore}async handle(e,t){if(null==t.key||0===t.key.length)throw new ut("Missing key");let n;try{n=kn.decode(t.key)}catch(e){throw new ut("Invalid CID")}null!=t.providers&&0!==t.providers.length||this.log.error("no providers found in message"),this.log("%p asked us, %p to store provider record for for %c",e,this.peerId,n),await Promise.all(t.providers.map(async t=>{const r=qo(xn(t.id)),i=t.multiaddrs.map(e=>Pu(e));e.equals(r)?t.multiaddrs.length<1?this.log("no valid addresses for provider %p. Ignore",e):(this.log.trace("received provider %p for %s (addrs %s)",e,n,i),await this.providers.addProvider(n,r),await this.peerStore.merge(r,{multiaddrs:i})):this.log("invalid provider peer %p from %p",t.id,e)}))}}class $w{peerRouting;peerInfoMapper;peerId;addressManager;log;constructor(e,t){const{peerRouting:n,logPrefix:r}=t;this.log=e.logger.forComponent(`${r}:rpc:handlers:find-node`),this.peerId=e.peerId,this.addressManager=e.addressManager,this.peerRouting=n,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){this.log("incoming request from %p for peers close to %b",e,t.key);try{if(null==t.key)throw new ut("Invalid FIND_NODE message received - key was missing");const n=await this.peerRouting.getClosestPeersOffline(t.key,{exclude:[e,this.peerId]});Ln(this.peerId.toMultihash().bytes,t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map(e=>e.decapsulateCode(eu))});const r={type:Nv.FIND_NODE,clusterLevel:t.clusterLevel,closer:n.map(this.peerInfoMapper).filter(({multiaddrs:e})=>e.length).map(e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map(e=>e.bytes)})),providers:[]};return 0===r.closer.length?this.log("could not find any peers closer to %b for %p",t.key,e):this.log("found %d peers close to %b for %p",r.closer.length,t.key,e),r}catch(n){throw this.log("error during finding peers closer to %b for %p - %e",t.key,e,n),n}}}class zw{peerId;peerRouting;providers;peerStore;peerInfoMapper;log;constructor(e,t){const{peerRouting:n,providers:r,logPrefix:i}=t;this.log=e.logger.forComponent(`${i}:rpc:handlers:get-providers`),this.peerId=e.peerId,this.peerStore=e.peerStore,this.peerRouting=n,this.providers=r,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){if(null==t.key)throw new ut("Invalid GET_PROVIDERS message received - key was missing");let n;try{n=kn.decode(t.key)}catch(e){throw new ut("Invalid CID")}this.log("%p asking for providers for %s",e,n);const[r,i]=await Promise.all([Tl(Vv(await this.providers.getProviders(n),async e=>{const t=await this.peerStore.get(e),n={id:t.id,multiaddrs:t.addresses.map(({multiaddr:e})=>e)};return n})),this.peerRouting.getClosestPeersOffline(t.key)]),s={type:Nv.GET_PROVIDERS,key:t.key,clusterLevel:t.clusterLevel,closer:i.map(this.peerInfoMapper).filter(({multiaddrs:e})=>e.length>0).map(e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map(e=>e.bytes)})),providers:r.map(this.peerInfoMapper).filter(({multiaddrs:e})=>e.length>0).map(e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map(e=>e.bytes)}))};return this.log("got %s providers %s closerPeers",s.providers.length,s.closer.length),s}async _getAddresses(e){return[]}}class Vw{peerStore;datastore;peerRouting;log;datastorePrefix;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:get-value`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.peerStore=e.peerStore,this.datastore=e.datastore,this.peerRouting=t.peerRouting}async handle(e,t){const n=t.key;if(this.log("%p asked for key %b",e,n),null==n||0===n.length)throw new ut("Invalid key");const r={type:Nv.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===mr(e.subarray(0,4))}(n)){this.log("is public key");const e=function(e){return qo(xn(e.subarray(4)))}(n);let t;try{const n=await this.peerStore.get(e);if(null==n.id.publicKey)throw new nt("No public key found in key book");t=Fo(n.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=t)return this.log("returning found public key"),r.record=new zv(n,t,new Date).serialize(),r}const[i,s]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getClosestPeersOffline(n)]);return null!=i&&(this.log("had record for %b in local datastore",n),r.record=i.serialize()),s.length>0&&(this.log("had %s closer peers in routing table",s.length),r.closer=s.map(e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map(e=>e.bytes)}))),r}async _checkLocalDatastore(e){this.log("checkLocalDatastore looking for %b",e);const t=uw(this.datastorePrefix,e);let n;try{n=await this.datastore.get(t)}catch(e){if("NotFoundError"===e.name)return;throw e}const r=zv.deserialize(n);if(!(null==r.timeReceived||Date.now()-r.timeReceived.getTime()>Dv))return r;await this.datastore.delete(t)}}class Gw{log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:ping`)}async handle(e,t){return this.log("ping from %p",e),t}}class Kw{components;validators;log;datastorePrefix;constructor(e,t){const{validators:n}=t;this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:put-value`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n}async handle(e,t){const n=t.key;if(this.log("%p asked us to store value for key %b",e,n),null==t.record)throw this.log.error("empty record from %p",e),new ut(`Empty record from: ${e}`);try{const e=zv.deserialize(t.record);await nw(this.validators,e),e.timeReceived=new Date;const r=uw(this.datastorePrefix,e.key);await this.components.datastore.put(r,e.serialize().subarray()),this.log("put record for %b into datastore under key %k",n,r)}catch(e){this.log("did not put record for key %b into datastore %o",n,e)}return t}}class Hw{handlers;log;metrics;incomingMessageTimeout;constructor(e,t){this.metrics={operations:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_inbound_rpc_requests_total`),errors:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_inbound_rpc_errors_total`),rpcTime:e.metrics?.registerMetricGroup(`${t.metricsPrefix}_inbound_rpc_time_seconds`,{label:"operation"})},this.log=e.logger.forComponent(`${t.logPrefix}:rpc`),this.incomingMessageTimeout=t.incomingMessageTimeout??1e4,this.handlers={[Nv.GET_VALUE.toString()]:new Vw(e,t),[Nv.PUT_VALUE.toString()]:new Kw(e,t),[Nv.FIND_NODE.toString()]:new $w(e,t),[Nv.ADD_PROVIDER.toString()]:new qw(e,t),[Nv.GET_PROVIDERS.toString()]:new zw(e,t),[Nv.PING.toString()]:new Gw(e,t)}}async handleMessage(e,t){const n=this.handlers[t.type];if(null!=n)try{return this.metrics.operations?.increment({[t.type]:!0}),await n.handle(e,t)}catch{this.metrics.errors?.increment({[t.type]:!0})}else this.log.error(`no handler found for message type: ${t.type}`)}async onIncomingStream(e,t){const n=()=>{e.abort(new ct)};let r=AbortSignal.timeout(this.incomingMessageTimeout);r.addEventListener("abort",n);const i=mc(e).pb(qv);for(;;){if("readable"!==e.readStatus){await e.close({signal:r});break}const s=await i.read({signal:r}),a=this.metrics?.rpcTime?.timer(s.type.toString()),o=this.metrics?.rpcTime?.timer(s.type.toString());let u=!1;try{this.log("incoming %s from %p",s.type,t.remotePeer);const e=await this.handleMessage(t.remotePeer,s);null!=e&&await i.write(e,{signal:r})}catch(e){throw u=!0,o?.(),e}finally{u||a?.()}r.removeEventListener("abort",n),r=AbortSignal.timeout(this.incomingMessageTimeout),r.addEventListener("abort",n)}}}class Ww extends Ft{log;components;protocol;running;registrarId;constructor(e,t){super();const{protocol:n,logPrefix:r}=t;this.components=e,this.log=e.logger.forComponent(`${r}:topology-listener`),this.running=!1,this.protocol=n}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.registrarId=await this.components.registrar.register(this.protocol,{onConnect:e=>{this.log("observed peer %p with protocol %s",e,this.protocol),this.dispatchEvent(new CustomEvent("peer",{detail:e}))}}))}async stop(){this.running=!1,null!=this.registrarId&&(this.components.registrar.unregister(this.registrarId),this.registrarId=void 0)}}class Qw{dht;constructor(e){this.dht=e}async provide(e,t={}){await uh(this.dht.provide(e,t))}async cancelReprovide(e){await this.dht.cancelReprovide(e)}async*findProviders(e,t={}){for await(const n of this.dht.findProviders(e,t))"PROVIDER"===n.name&&(yield*n.providers.map(e=>({...e,routing:"kad-dht"})))}async put(e,t,n){await uh(this.dht.put(e,t,n))}async get(e,t){for await(const n of this.dht.get(e,t))if("VALUE"===n.name)return n.value;throw new nt("Could not find value for key")}}class Yw{dht;constructor(e){this.dht=e}async findPeer(e,t={}){for await(const n of this.dht.findPeer(e,t))if("FINAL_PEER"===n.name)return n.peer;throw new nt("Peer not found")}async*getClosestPeers(e,t={}){for await(const n of this.dht.getClosestPeers(e,t))"FINAL_PEER"===n.name&&(yield n.peer)}}class Jw extends Ft{k;a;d;protocol;routingTable;providers;network;peerRouting;components;log;running;clientMode;validators;selectors;queryManager;contentFetching;contentRouting;routingTableRefresh;rpc;topologyListener;querySelf;maxInboundStreams;maxOutboundStreams;dhtContentRouting;dhtPeerRouting;peerInfoMapper;reprovider;onPeerConnectTimeout;constructor(e,t={}){super();const n=t.logPrefix??"libp2p:kad-dht",r=t.datastorePrefix??"/dht",i=t.metricsPrefix??"libp2p_kad_dht",s={queries:e.metrics?.registerMetricGroup(`${i}_operations_total`,{label:"operation"}),errors:e.metrics?.registerCounterGroup(`${i}_operation_errors_total`,{label:"operation"}),queryTime:e.metrics?.registerMetricGroup(`${i}_operation_time_seconds`,{label:"operation"}),errorTime:e.metrics?.registerMetricGroup(`${i}_operation_error_time_seconds`,{label:"operation"})};this.running=!1,this.components=e,this.log=e.logger.forComponent(n),this.k=t.kBucketSize??Fw,this.a=t.alpha??10,this.d=t.disjointPaths??this.a,this.protocol=t.protocol??"/ipfs/kad/1.0.0",this.clientMode=t.clientMode??!0,this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.peerInfoMapper=t.peerInfoMapper??sw,this.onPeerConnectTimeout=t.onPeerConnectTimeout??1e4,this.providers=new xw(e,{...t.providers,logPrefix:n,datastorePrefix:r}),this.validators={...rw,...t.validators},this.selectors={...tw,...t.selectors},this.network=new vw(e,{protocol:this.protocol,logPrefix:n,metricsPrefix:i}),this.routingTable=new Ow(e,{kBucketSize:this.k,pingOldContactTimeout:t.pingOldContactTimeout,pingOldContactConcurrency:t.pingOldContactConcurrency,pingOldContactMaxQueueSize:t.pingOldContactMaxQueueSize,pingNewContactTimeout:t.pingNewContactTimeout,pingNewContactConcurrency:t.pingNewContactConcurrency,pingNewContactMaxQueueSize:t.pingNewContactMaxQueueSize,protocol:this.protocol,logPrefix:n,metricsPrefix:i,prefixLength:t.prefixLength,splitThreshold:t.kBucketSplitThreshold,network:this.network});const a=Cd();!0===t.allowQueryWithZeroPeers&&a.resolve(),this.queryManager=new Sw(e,{disjointPaths:this.d,alpha:this.a,logPrefix:n,metricsPrefix:i,initialQuerySelfHasRun:a,routingTable:this.routingTable,allowQueryWithZeroPeers:t.allowQueryWithZeroPeers}),this.peerRouting=new Ew(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:n}),this.contentFetching=new mw(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:n,datastorePrefix:r}),this.contentRouting=new gw(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:n}),this.routingTableRefresh=new jw(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:n}),this.rpc=new Hw(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:n,metricsPrefix:i,datastorePrefix:r,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new Ww(e,{protocol:this.protocol,logPrefix:n}),this.querySelf=new Cw(e,{peerRouting:this.peerRouting,interval:t.querySelfInterval,initialInterval:t.initialQuerySelfInterval,logPrefix:n,initialQuerySelfHasRun:a,operationMetrics:s}),this.reprovider=new kw(e,{...t.reprovide,logPrefix:n,metricsPrefix:i,datastorePrefix:r,contentRouting:this.contentRouting,operationMetrics:s}),this.network.addEventListener("peer",e=>{const t=e.detail;this.onPeerConnect(t).catch(e=>{this.log.error("could not add %p to routing table - %e",t.id,e)}),this.dispatchEvent(new CustomEvent("peer",{detail:t}))}),this.topologyListener.addEventListener("peer",e=>{const t=e.detail;Promise.resolve().then(async()=>{const e=await this.components.peerStore.get(t),n={id:t,multiaddrs:e.addresses.map(({multiaddr:e})=>e),protocols:e.protocols};await this.onPeerConnect(n)}).catch(e=>{this.log.error("could not add %p to routing table - %e",t,e)})}),this.dhtPeerRouting=new Yw(this),this.dhtContentRouting=new Qw(this),null==t.clientMode&&e.events.addEventListener("self:peer:update",e=>{this.log("received update of self-peer info"),Promise.resolve().then(async()=>{const t=e.detail.peer.addresses.some(({multiaddr:e})=>!Ad(e)&&!Zh.exactMatch(e)),n=this.getMode();t&&"client"===n?await this.setMode("server"):"server"!==n||t||await this.setMode("client")}).catch(e=>{this.log.error("error setting dht server mode - %e",e)})}),this.get=hw(this.get.bind(this),s,"GET_VALUE"),this.findProviders=hw(this.findProviders.bind(this),s,"FIND_PROVIDERS"),this.findPeer=hw(this.findPeer.bind(this),s,"FIND_PEER"),this.getClosestPeers=hw(this.getClosestPeers.bind(this),s,"GET_CLOSEST_PEERS"),this.provide=hw(this.provide.bind(this),s,"PROVIDE"),this.put=hw(this.put.bind(this),s,"PUT_VALUE")}[Symbol.toStringTag]="@libp2p/kad-dht";[Rt]=["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery","@libp2p/kad-dht"];[_t]=["@libp2p/identify","@libp2p/ping"];get[Ve](){return this.dhtContentRouting}get[St](){return this.dhtPeerRouting}get[Et](){return this}async onPeerConnect(e){if(this.log.trace("peer %p connected",e.id,e.multiaddrs),0===(e=this.peerInfoMapper(e)).multiaddrs.length)return void this.log.trace("ignoring %p as there were no valid addresses in %s after filtering",e.id,e.multiaddrs.map(e=>e.toString()));const t=AbortSignal.timeout(this.onPeerConnectTimeout);try{await this.routingTable.add(e.id,{signal:t})}catch(t){this.log.error("could not add %p to routing table - %e",e.id,t)}}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}async setMode(e,t){e!==this.getMode()||!0===t?.force?(await this.components.registrar.unhandle(this.protocol,t),e!==this.getMode()||!0===t?.force?"client"===e?(this.log("enabling client mode while in %s mode",this.getMode()),this.clientMode=!0):(this.log("enabling server mode while in %s mode",this.getMode()),this.clientMode=!1,await this.components.registrar.handle(this.protocol,this.rpc.onIncomingStream.bind(this.rpc),{signal:t?.signal,maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams})):this.log("already in %s mode",e)):this.log("already in %s mode",e)}async start(){this.running||(this.running=!0,await this.setMode(this.clientMode?"client":"server",{force:!0}),await kt(this.routingTable,this.queryManager,this.network,this.topologyListener,this.routingTableRefresh,this.reprovider),await kt(this.querySelf))}async stop(){this.running=!1,await It(this.querySelf,this.queryManager,this.network,this.routingTable,this.routingTableRefresh,this.topologyListener,this.reprovider)}async*put(e,t,n={}){yield*this.contentFetching.put(e,t,n)}async*get(e,t={}){yield*this.contentFetching.get(e,t)}async*provide(e,t={}){yield*this.contentRouting.provide(e,this.components.addressManager.getAddresses(),t)}async cancelReprovide(e,t){await this.providers.removeProvider(e,this.components.peerId,t)}async*findProviders(e,t={}){yield*this.contentRouting.findProviders(e,t)}async*findPeer(e,t={}){yield*this.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t={}){yield*this.peerRouting.getClosestPeers(e,t)}async refreshRoutingTable(e){this.routingTableRefresh.refreshTable(!0,e)}}function Zw(e={}){return t=>new Jw(t,e)}!function(e){e[e.SEND_QUERY=0]="SEND_QUERY",e[e.PEER_RESPONSE=1]="PEER_RESPONSE",e[e.FINAL_PEER=2]="FINAL_PEER",e[e.QUERY_ERROR=3]="QUERY_ERROR",e[e.PROVIDER=4]="PROVIDER",e[e.VALUE=5]="VALUE",e[e.ADD_PEER=6]="ADD_PEER",e[e.DIAL_PEER=7]="DIAL_PEER",e[e.PATH_ENDED=8]="PATH_ENDED"}(Bw||(Bw={}));class Xw{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[Rt]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(e,t){const n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);const r=AbortSignal.timeout(this.timeout);r.addEventListener("abort",()=>{e.abort(new ct("Ping timed out"))});const i=Date.now();for await(const t of e){if("open"!==e.status){n("stream status changed to %s",e.status);break}e.send(t)||(n("waiting for stream to drain"),await _d(e,"drain",{rejectionEvents:["close"],signal:r}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-i),await e.close({signal:r})}async ping(e,t={}){const n=io(32),r=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),i=r.log.newScope("ping");try{const e=Date.now(),i=Promise.withResolvers(),s=new $n,a=o=>{if(s.append(o.data),32===s.byteLength){r.removeEventListener("message",a);const o=Date.now()-e;Promise.all([r.closeRead(t)]).then(()=>{if(!Ln(n,s.subarray()))throw new dt(`Received wrong ping ack after ${o}ms`);i.resolve(o)}).catch(e=>{r.abort(e),i.reject(e)})}};return r.addEventListener("message",a),r.send(n),await r.close(t),await $d(i.promise,t.signal)}catch(t){throw i.error("error while pinging %o - %e",e,t),r?.abort(t),t}finally{r?.close()}}}function eT(e={}){return t=>new Xw(t,e)}function tT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function nT(e,t,n){if(!e.s){if(n instanceof rT){if(!n.s)return void(n.o=nT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(nT.bind(null,e,t),nT.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var rT=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var s=1&i?t:n;if(s){try{nT(r,1,s(this.v))}catch(e){nT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?nT(r,1,t?t(i):i):n?nT(r,1,n(i)):nT(r,2,i)}catch(e){nT(r,2,e)}},r},e}();function iT(e){return e instanceof rT&&1&e.s}function sT(e,t,n){for(var r;;){var i=e();if(iT(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!iT(s)){r=1;break}s=s.s}if(t){var a=t();if(a&&a.then&&!iT(a)){r=2;break}}}var o=new rT,u=nT.bind(null,o,2);return(0===r?i.then(c):1===r?s.then(d):a.then(l)).then(void 0,u),o;function d(r){s=r;do{if(t&&(a=t())&&a.then&&!iT(a))return void a.then(l).then(void 0,u);if(!(i=e())||iT(i)&&!i.v)return void nT(o,1,s);if(i.then)return void i.then(c).then(void 0,u);iT(s=n())&&(s=s.v)}while(!s||!s.then);s.then(d).then(void 0,u)}function c(e){e?(s=n())&&s.then?s.then(d).then(void 0,u):d(s):nT(o,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):nT(o,1,s)}}function aT(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var oT="/ocean/nodes/1.0.0",uT=1e4,dT=["/dns4/bootstrap1.oncompute.ai/tcp/9001/ws/p2p/16Uiu2HAmLhRDqfufZiQnxvQs2XHhd6hwkLSPfjAQg1gH8wgRixiP","/dns4/bootstrap2.oncompute.ai/tcp/9001/ws/p2p/16Uiu2HAmHwzeVw7RpGopjZe6qNBJbzDDBdqtrSk7Gcx1emYsfgL4","/dns4/bootstrap3.oncompute.ai/tcp/9001/ws/p2p/16Uiu2HAmBKSeEP3v4tYEPsZsZv9VELinyMCsrVTJW9BvQeFXx28U","/dns4/bootstrap4.oncompute.ai/tcp/9001/ws/p2p/16Uiu2HAmSTVTArioKm2wVcyeASHYEsnx2ZNq467Z4GMDU4ErEPom"],cT=/*#__PURE__*/function(){function e(){this.p2pConfig={},this.libp2pNode=null}var t=e.prototype;return t.setupP2P=function(e){try{var t=this;return t.p2pConfig=e,t.libp2pNode&&(Promise.resolve(t.libp2pNode.stop()).catch(function(){}),t.libp2pNode=null),Promise.resolve(t.getOrCreateLibp2pNode()).then(function(){})}catch(e){return Promise.reject(e)}},t.getMultiaddrFromPeerId=function(e){try{var t,n,r=function(e){return e.includes("/p2p/")?e:e+"/p2p/"+e};return Promise.resolve(this.getOrCreateLibp2pNode()).then(function(i){var s;function a(a){var o;if(s)return a;function u(t){if(o)return t;throw new Error("No multiaddrs found for peer id "+e)}var d,c=i.services.dht,l=!1,p=!1,h=aT(function(){return tT(function(){return t=P(c.findPeer(Uo(e),{signal:AbortSignal.timeout(2e4)})),sT(function(){function e(e){return!o&&(l=!(n=e).done)}return o?!!e(!o&&t.next()):Promise.resolve(!o&&t.next()).then(e)},function(){return!!(l=!1)},function(){var e=n.value;if(e.type===Bw.FINAL_PEER&&e.peer.multiaddrs.length>0){var t=e.peer.multiaddrs[0].toString(),i=r(t);return o=1,i}})},function(e){p=!0,d=e})},function(e,n){function r(t){if(o)return t;if(e)throw n;return n}var i=aT(function(){var e=function(){if(l&&null!=t.return)return Promise.resolve(t.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,t){if(p)throw d;if(e)throw t;return t});return i&&i.then?i.then(r):r(i)});return h&&h.then?h.then(u):u(h)}var o=i.getConnections().find(function(t){return t.remotePeer.toString()===e});if(null!=o&&o.remoteAddr){var u=o.remoteAddr.toString();return r(u)}var d=tT(function(){return Promise.resolve(i.peerStore.get(Uo(e))).then(function(e){var t;if((null==e||null==(t=e.addresses)?void 0:t.length)>0){var n=e.addresses[0].multiaddr.toString(),i=r(n);return s=1,i}})},function(){});return d&&d.then?d.then(a):a(d)})}catch(e){return Promise.reject(e)}},t.getLibp2pNode=function(){var e;return null!=(e=this.libp2pNode)?e:null},t.getDiscoveredNodes=function(){try{return this.libp2pNode?Promise.resolve(this.libp2pNode.peerStore.all()).then(function(e){return e.map(function(e){return{peerId:e.id.toString(),multiaddrs:e.addresses.map(function(e){return e.multiaddr.toString()})}})}):Promise.resolve([])}catch(e){return Promise.reject(e)}},t.bufToHex=function(e){var t;if("string"==typeof e)try{e=JSON.parse(e)}catch(t){return e}return"Buffer"===(null==(t=e)?void 0:t.type)&&Array.isArray(e.data)?(new TextDecoder).decode(new Uint8Array(e.data)):e instanceof Uint8Array?(new TextDecoder).decode(e):e},t.handleProtocolCommands=function(e,t){return Promise.resolve()},t.getOrCreateLibp2pNode=function(){try{var e,t=this;if(t.libp2pNode)return Promise.resolve(t.libp2pNode);var n=(null!=(e=t.p2pConfig.bootstrapPeers)?e:dT).map(Pu);return Promise.resolve(async function(e={}){e.privateKey??=await async function(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=Qs.utils.randomSecretKey(),t=Qs.getPublicKey(e),n=function(e,t){const n=new Uint8Array(64);for(let r=0;r<32;r++)n[r]=e[r],n[32+r]=t[r];return n}(e,t);return{privateKey:n,publicKey:t}}();return new ra(e,t)}()}();const t=new jm({...await Du(e),peerId:(n=e.privateKey,jo(n.publicKey))});var n;return!1!==e.start&&await t.start(),t}(k({addresses:{listen:[]},transports:[lg(),Ev()].concat(t.p2pConfig.enableTcp?[hg()]:[]),connectionEncrypters:[Bb()],streamMuxers:[tg()],peerDiscovery:[].concat(n.length>0?[(r={list:n.map(String),timeout:1e4},e=>new xv(e,r))]:[]),services:{identify:kv(),ping:eT(),dht:Zw({protocol:"/ocean/nodes/1.0.0/kad/1.0.0",clientMode:!0})},connectionGater:{denyDialMultiaddr:function(){return!1}},connectionManager:{maxConnections:100},connectionMonitor:{abortConnectionOnPingFailure:!1}},t.p2pConfig.libp2p))).then(function(e){return Promise.resolve(e.start()).then(function(){var n;e.addEventListener("peer:discovery",function(t){var n=t.detail;if(null!=n&&n.id){var r=n.id.toString();e.getConnections().length<100&&0===e.getConnections(n.id).length&&e.dial(n.id,{signal:AbortSignal.timeout(1e4)}).catch(function(e){O.debug("Failed to dial discovered peer "+r+": "+e.message)})}}),t.libp2pNode=e,t.libp2pNode.handle("/ocean/client/1.0.0",t.handleProtocolCommands);for(var r,i=C(null!=(n=t.p2pConfig.additionalRoles)?n:[]);!(r=i()).done;)t.libp2pNode.handle("/ocean/client/"+r.value+"/1.0.0",t.handleProtocolCommands);return e})})}catch(e){return Promise.reject(e)}var r},t.toUint8Array=function(e){return e instanceof Uint8Array?e:e.subarray()},t.isDialable=function(e){return"undefined"==typeof window||e.toString().includes("/tls/sni")},t.peerIdFromMultiaddr=function(e){var t=e.toString().split("/p2p/");return t.length<=1?null:t[t.length-1].split("/")[0]||null},t.getConnection=function(e,t){try{var n=this;return Promise.resolve(n.getOrCreateLibp2pNode()).then(function(r){var i;function s(s){var a;if(i)return s;function o(i){return a?i:(O.debug("[P2P] bare peerId -> dialByPeerId "+e),n.dialByPeerId(r,e,t))}var u=tT(function(){function i(i){if(a)return i;var o=n.peerIdFromMultiaddr(s);if(o){O.debug("[P2P] single fallback -> dialByPeerId "+o);var u=n.dialByPeerId(r,o,t);return a=1,u}throw new Error("Cannot dial address: "+e)}var s=Pu(e),o=function(){if(n.isDialable(s))return O.debug("[P2P] dial single addr: "+s),tT(function(){return Promise.resolve(r.dial(s,{signal:t})).then(function(e){return O.debug("[P2P] dial single SUCCESS via "+e.remoteAddr),a=1,e})},function(e){O.debug("[P2P] dial single failed: "+e.message)})}();return o&&o.then?o.then(i):i(o)},function(e){var t;if(null!=(t=e.message)&&t.includes("Cannot dial"))throw e});return u&&u.then?u.then(o):o(u)}var a=function(){if(Array.isArray(e)){var s=function(s){if(i)return s;for(var a,o=C(e);!(a=o()).done;){var u=n.peerIdFromMultiaddr(a.value);if(u){O.debug("[P2P] Not multiaddrs, fallback to peerId: "+u);var d=n.dialByPeerId(r,u,t);return i=1,d}}throw new Error("No valid addresses and no peer ID in multiaddrs")},a=e.filter(function(e){return n.isDialable(e)}),o=function(){if(a.length>0)return O.debug("[P2P] dial array: "+a.length+" dialable addrs"),tT(function(){return Promise.resolve(r.dial(a,{signal:t})).then(function(e){return O.debug("[P2P] dial array SUCCESS via "+e.remoteAddr),i=1,e})},function(e){O.debug("[P2P] dial array failed: "+e.message)})}();return o&&o.then?o.then(s):s(o)}}();return a&&a.then?a.then(s):s(a)})}catch(e){return Promise.reject(e)}},t.dialByPeerId=function(e,t,n){try{var r,i=function(i){if(r)return i;function o(){function r(){var r;function i(n){return r?n:(O.debug("[P2P] "+t+": last resort dial by peerId"),tT(function(){return Promise.resolve(e.dial(a,{signal:AbortSignal.timeout(1e4)})).then(function(e){return O.debug("[P2P] "+t+": peerId dial SUCCESS via "+e.remoteAddr+" (limited="+(null!=e.limits)+")"),e})},function(){throw new Error("Cannot reach peer "+t+". "+(d.length>0?"Found addrs: "+d.map(String).join(", ")+" (none dialable). ":"No addresses found. ")+"Active connections: "+e.getConnections().length+".")}))}var o=d.filter(function(e){return s.isDialable(e)}).map(function(e){var n=e.toString();return n.includes("/p2p/")?e:Pu(n+"/p2p/"+t)});O.debug("[P2P] "+t+": "+o.length+"/"+d.length+" addrs are dialable");var u=function(){if(o.length>0)return O.debug("[P2P] "+t+": dialing "+o.map(String)),tT(function(){return Promise.resolve(e.dial(o,{signal:n})).then(function(e){return O.debug("[P2P] "+t+": SUCCESS via "+e.remoteAddr+" (limited="+(null!=e.limits)+")"),r=1,e})},function(e){O.debug("[P2P] "+t+": direct dial failed: "+e.message)})}();return u&&u.then?u.then(i):i(u)}var i=d.filter(function(e){return s.isDialable(e)}),o=function(){if(0===i.length){O.debug("[P2P] "+t+": no dialable addrs in peerStore, querying DHT...");var n=tT(function(){var n,r=AbortSignal.timeout(null!=(n=s.p2pConfig.dhtLookupTimeout)?n:6e4);return Promise.resolve(e.peerRouting.findPeer(a,{signal:r})).then(function(e){for(var n,r=C(e.multiaddrs);!(n=r()).done;)c(n.value);O.debug("[P2P] "+t+": DHT returned "+e.multiaddrs.length+" addrs")})},function(e){O.debug("[P2P] "+t+": DHT findPeer failed: "+e.message)});if(n&&n.then)return n.then(function(){})}else O.debug("[P2P] "+t+": "+i.length+" dialable addrs from peerStore, skipping DHT")}();return o&&o.then?o.then(r):r()}var u=new Set,d=[],c=function(e){var t=e.toString();u.has(t)||(u.add(t),d.push(e))},l=tT(function(){return Promise.resolve(e.peerStore.get(a)).then(function(e){if(null!=e&&e.addresses){for(var n,r=C(e.addresses);!(n=r()).done;)c(n.value.multiaddr);O.debug("[P2P] "+t+": "+e.addresses.length+" peerStore addrs")}})},function(){O.debug("[P2P] "+t+": not in peerStore")});return l&&l.then?l.then(o):o()},s=this,a=Uo(t),o=e.getConnections(a).filter(function(e){return"open"===e.status});if(o.length>0)return O.debug("[P2P] "+t+": reusing existing connection via "+o[0].remoteAddr),Promise.resolve(o[0]);var u=function(){if(0===e.getConnections().length)return O.debug("[P2P] "+t+": no connections yet, waiting for bootstrap..."),Promise.resolve(qe(3e3)).then(function(){var n=e.getConnections(a);if(n.length>0)return O.debug("[P2P] "+t+": connected during bootstrap wait"),r=1,n[0]})}();return Promise.resolve(u&&u.then?u.then(i):i(u))}catch(e){return Promise.reject(e)}},t.getConsumerAddress=function(e){return pT(e)},t.getSignature=function(e,t,n){return lT(e,t,n)},t.getNodePublicKey=function(e){try{return Promise.resolve(this.getEndpoints(e)).then(function(e){return null==e?void 0:e.nodePublicKey})}catch(e){return Promise.reject(e)}},t.getAuthorization=function(e){return hT(e)},t.dialAndStream=function(e,t,n,r){try{var i,s=this,a=null!=n?n:AbortSignal.timeout(null!=(i=s.p2pConfig.dialTimeout)?i:uT);return Promise.resolve(s.getConnection(e,a)).then(function(e){return tT(function(){return Promise.resolve(e.newStream(oT,{signal:a,runOnLimitedConnection:!0})).then(function(n){var i=fc(n),o=t;return r&&(o=k({},t,{p2pStreamBody:!0})),Promise.resolve(i.write((new TextEncoder).encode(JSON.stringify(o)),{signal:a})).then(function(){function t(){return Promise.resolve(n.close()).then(function(){return Promise.resolve(i.read({signal:a})).then(function(t){var n=s.toUint8Array(t);return{lp:i,firstBytes:n,connection:e}})})}var o=function(){if(r)return Promise.resolve(function(e,t,n){try{var r,i,s,a=function(t){return Promise.resolve(e.write(new Uint8Array(0),{signal:n})).then(function(){})},o=!1,u=!1,d=aT(function(){return tT(function(){r=P(t);var s=sT(function(){return Promise.resolve(r.next()).then(function(e){return o=!(i=e).done})},function(){return!!(o=!1)},function(){return Promise.resolve(e.write(function(e){if(e instanceof Uint8Array)return e;if("string"==typeof e)return(new TextEncoder).encode(e);if(e&&"object"==typeof e&&ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type for P2P request body")}(i.value),{signal:n})).then(function(){})});if(s&&s.then)return s.then(function(){})},function(e){u=!0,s=e})},function(e,t){function n(n){if(e)throw t;return t}var i=aT(function(){var e=function(){if(o&&null!=r.return)return Promise.resolve(r.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,t){if(u)throw s;if(e)throw t;return t});return i&&i.then?i.then(n):n()});return Promise.resolve(d&&d.then?d.then(a):a())}catch(e){return Promise.reject(e)}}(i,r,a)).then(function(){})}();return o&&o.then?o.then(t):t()})})},function(t){try{e.abort(new Error("stream failed"))}catch(e){}throw t})})}catch(e){return Promise.reject(e)}},t.sendP2pCommand=function(e,t,n,r,i,s,a){void 0===s&&(s=0);try{var o=this;return Promise.resolve(tT(function(){var u=k({command:t,authorization:r?o.getAuthorization(r):void 0},n);return Promise.resolve(o.dialAndStream(e,u,i,a)).then(function(u){var d=u.lp,c=u.firstBytes;function l(u){for(var d,c,l,p=0;p<m.length;p++){var h=(new TextDecoder).decode(m[p]);try{l=JSON.parse(h)}catch(e){l=m[p]}}var f=l;if("number"==typeof(null==f?void 0:f.httpStatus)&&f.httpStatus>=400)throw new Error("string"==typeof f.error?f.error:JSON.stringify(f.error));var y=null!=(d="string"==typeof l?l:null==f?void 0:f.error)?d:"",b=function(u){if(y.includes("Cannot connect to peer")&&s<(null!=(u=o.p2pConfig.maxRetries)?u:5))return Promise.resolve(new Promise(function(e){var t;return setTimeout(e,null!=(t=o.p2pConfig.retryDelay)?t:1e3)})).then(function(){var u=o.sendP2pCommand(e,t,n,r,i,s+1,a);return c=1,u})}();return b&&b.then?b.then(function(e){return c?e:l}):c?b:l}if(!c.length)throw new Error("Gateway node error: no response from peer");var p=(new TextDecoder).decode(c);try{var h,f=JSON.parse(p);if("number"==typeof(null==f?void 0:f.httpStatus)&&f.httpStatus>=400)throw new Error(null!=(h=f.error)?h:"Gateway node error: "+f.httpStatus)}catch(e){}if(t===T.COMPUTE_GET_STREAMABLE_LOGS||t===T.COMPUTE_GET_RESULT)return F(/*#__PURE__*/D().mark(function e(){var t;return D().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,A(d.read({signal:AbortSignal.timeout(uT)}));case 4:return t=e.sent,e.next=7,t instanceof Uint8Array?t:t.subarray();case 7:e.next=1;break;case 9:e.next=15;break;case 11:if(e.prev=11,e.t0=e.catch(0),e.t0 instanceof Bd){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))();var m=[c],y=tT(function(){var e=sT(function(){return!0},void 0,function(){var e;return Promise.resolve(d.read({signal:AbortSignal.timeout(null!=(e=o.p2pConfig.dialTimeout)?e:uT)})).then(function(e){m.push(o.toUint8Array(e))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof Bd))throw e});return y&&y.then?y.then(l):l()})},function(u){var d,c;function l(e){if(c)return e;throw new Error("P2P command error: "+p)}var p=null!=(d=null==u?void 0:u.message)?d:"",h=function(u){if((p.includes("closed")||p.includes("reset"))&&s<(null!=(u=o.p2pConfig.maxRetries)?u:5))return O.debug("[P2P] Stream reset/closed on attempt "+(s+1)+", retrying..."),Promise.resolve(qe(1e3)).then(function(){var u=o.sendP2pCommand(e,t,n,r,i,s+1,a);return c=1,u})}();return h&&h.then?h.then(l):l(h)}))}catch(e){return Promise.reject(e)}},t.getEndpoints=function(e){try{var t=this;return Promise.resolve(tT(function(){return Promise.resolve(t.sendP2pCommand(e,T.STATUS,{}))},function(e){throw O.error("P2P getEndpoints (STATUS) failed:",e),e}))}catch(e){return Promise.reject(e)}},t.getNodeStatus=function(e,t){try{return Promise.resolve(this.getEndpoints(e))}catch(e){return Promise.reject(e)}},t.getNodeJobs=function(e,t,n){try{var r=this;return Promise.resolve(tT(function(){var i={};return t&&(i.fromTimestamp=t.toString()),Promise.resolve(r.sendP2pCommand(e,T.JOBS,i,null,n)).then(function(e){return Array.isArray(e)?e:[]})},function(e){return O.error("P2P getNodeJobs failed:",e),[]}))}catch(e){return Promise.reject(e)}},t.getNonce=function(e,t,n){try{var r=this;return Promise.resolve(tT(function(){return Promise.resolve(r.sendP2pCommand(e,T.NONCE,{address:t},null,n)).then(function(e){var t,n,r="number"==typeof e?e:null!=(t=null!=(n=null==e?void 0:e.nonce)?n:e)?t:0;return r&&null!==r?Number(r):0})},function(e){throw O.error("P2P getNonce failed:",e),e}))}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getConsumerAddress(r)).then(function(i){return Promise.resolve(a.getNonce(n,i,s)).then(function(o){var u=(o+1).toString();return Promise.resolve(a.getSignature(r,u,T.ENCRYPT)).then(function(o){return Promise.resolve(a.sendP2pCommand(n,T.ENCRYPT,{chainId:t,nonce:u,consumerAddress:i,signature:o,blob:"string"==typeof e?e:JSON.stringify(e)},r,s)).then(function(e){return a.bufToHex(e)})})})})}catch(e){return Promise.reject(e)}},t.checkDidFiles=function(e,t,n,r,i){void 0===r&&(r=!1);try{return Promise.resolve(this.sendP2pCommand(n,T.FILE_INFO,{did:e,serviceId:t,checksum:r},null,i)).then(function(e){return Array.isArray(e)?e:[e]})}catch(e){return Promise.reject(e)}},t.getFileInfo=function(e,t,n,r){void 0===n&&(n=!1);try{return Promise.resolve(this.sendP2pCommand(t,T.FILE_INFO,{file:e,type:e.type,checksum:n},null,r)).then(function(e){return Array.isArray(e)?e:[e]})}catch(e){return Promise.reject(e)}},t.getComputeEnvironments=function(e,t){try{return Promise.resolve(this.sendP2pCommand(e,T.COMPUTE_GET_ENVIRONMENTS,{},null,t)).then(function(e){return Array.isArray(e)?e:[e]})}catch(e){return Promise.reject(e)}},t.initialize=function(e,t,n,r,i,s,a,o,u){try{var d={ddoId:e,serviceId:t,consumerAddress:r};return a&&(d.userdata=a),o&&(d.environment=o),u&&(d.validUntil=u),Promise.resolve(this.sendP2pCommand(i,T.GET_FEES,d,null,s))}catch(e){return Promise.reject(e)}},t.initializeCompute=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h){try{var f=function(){function e(){return m.sendP2pCommand(s,T.COMPUTE_INITIALIZE,y,null,c)}var t=function(){if(h)return Promise.resolve(m.getNodePublicKey(s)).then(function(e){e&&(y.output=Cu(e,JSON.stringify(h)))})}();return t&&t.then?t.then(e):e()},m=this,y={datasets:e,algorithm:t,environment:n,payment:{chainId:u,token:r,resources:o},maxJobDuration:i,consumerAddress:a};d&&(y.policyServer=d),l&&(y.queueMaxWaitTime=l);var b=function(){if(p)return Promise.resolve(m.getNodePublicKey(s)).then(function(e){e&&(y.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(p)))})}();return Promise.resolve(b&&b.then?b.then(f):f())}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,a,o){try{var u=this;return Promise.resolve(u.getConsumerAddress(s)).then(function(d){return Promise.resolve(u.getNonce(i,d)).then(function(c){var l=(c+1).toString();return Promise.resolve(u.getSignature(s,l,T.DOWNLOAD)).then(function(c){var p={command:T.DOWNLOAD,authorization:u.getAuthorization(s),fileIndex:n,documentId:e,transferTxId:r,serviceId:t,consumerAddress:d,nonce:l,signature:c};return a&&(p.policyServer=a),o&&(p.userData=o),Promise.resolve(u.dialAndStream(i,p)).then(function(e){var t=e.lp,r=e.firstBytes;function i(e){var t=Au(d);return{data:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),filename:"file"+n}}var s,a=(new TextDecoder).decode(r),o=null;try{o=JSON.parse(a)}catch(e){}if(o&&"number"==typeof o.httpStatus&&o.httpStatus>=400)throw new Error(null!=(s=o.error)?s:"P2P download error: "+o.httpStatus);var d=null===o?[new Uint8Array(r)]:[],c=tT(function(){var e=sT(function(){return!0},void 0,function(){var e;return Promise.resolve(t.read({signal:AbortSignal.timeout(null!=(e=u.p2pConfig.dialTimeout)?e:uT)})).then(function(e){d.push(new Uint8Array(u.toUint8Array(e)))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof Bd))throw e});return c&&c.then?c.then(i):i()})})})})}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m){try{var y=this;return Promise.resolve(y.getConsumerAddress(t)).then(function(b){return Promise.resolve(y.getNonce(e,b,h)).then(function(g){var v=(g+1).toString();return Promise.resolve(y.getSignature(t,v,T.COMPUTE_START)).then(function(g){function w(){function n(){return Promise.resolve(y.sendP2pCommand(e,T.COMPUTE_START,E,t,h)).then(function(e){return Array.isArray(e),e})}var r=function(){if(l)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(E.output=Cu(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var E={environment:n,dataset:r[0],datasets:r,algorithm:i,maxJobDuration:s,feeToken:a,resources:o,chainId:u,payment:{chainId:u,token:a,maxJobDuration:s,resources:o},consumerAddress:b,nonce:v,signature:g};d&&(E.metadata=d),c&&(E.additionalViewers=c),p&&(E.policyServer=p),f&&(E.queueMaxWaitTime=f);var x=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(E.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(m)))})}();return x&&x.then?x.then(w):w()})})})}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p){try{var h=this;return Promise.resolve(h.getConsumerAddress(t)).then(function(f){return Promise.resolve(h.getNonce(e,f,c)).then(function(m){var y=(m+1).toString();return Promise.resolve(h.getSignature(t,y,T.FREE_COMPUTE_START)).then(function(m){function b(){function n(){return Promise.resolve(h.sendP2pCommand(e,T.FREE_COMPUTE_START,g,t,c)).then(function(e){return Array.isArray(e),e})}var r=function(){if(u)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(g.output=Cu(e,JSON.stringify(u)))})}();return r&&r.then?r.then(n):n()}var g={environment:n,dataset:r[0],datasets:r,algorithm:i,resources:s,consumerAddress:f,nonce:y,signature:m};a&&(g.metadata=a),o&&(g.additionalViewers=o),d&&(g.policyServer=d),l&&(g.queueMaxWaitTime=l);var v=function(){if(p)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(g.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(p)))})}();return v&&v.then?v.then(b):b()})})})}catch(e){return Promise.reject(e)}},t.computeStreamableLogs=function(e,t,n,r){try{var i=this;return"string"==typeof t?Promise.resolve(i.sendP2pCommand(e,T.COMPUTE_GET_STREAMABLE_LOGS,{jobId:n},t,r)):Promise.resolve(i.getConsumerAddress(t)).then(function(s){return Promise.resolve(i.getNonce(e,s,r)).then(function(a){var o=(a+1).toString();return Promise.resolve(i.getSignature(t,o,T.COMPUTE_GET_STREAMABLE_LOGS)).then(function(a){return i.sendP2pCommand(e,T.COMPUTE_GET_STREAMABLE_LOGS,{jobId:n,consumerAddress:s,nonce:o,signature:a},t,r)})})})}catch(e){return Promise.reject(e)}},t.computeStop=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getConsumerAddress(n)).then(function(a){return Promise.resolve(s.getNonce(t,a,i)).then(function(o){var u=(o+1).toString();return Promise.resolve(s.getSignature(n,u,T.COMPUTE_STOP)).then(function(o){var d={jobId:e,consumerAddress:a,nonce:u,signature:o};return r&&(d.agreementId=r),s.sendP2pCommand(t,T.COMPUTE_STOP,d,n,i)})})})}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getConsumerAddress(t)).then(function(a){var o={consumerAddress:a};return n&&(o.jobId=n),r&&(o.agreementId=r),s.sendP2pCommand(e,T.COMPUTE_GET_STATUS,o,t,i)})}catch(e){return Promise.reject(e)}},t.getComputeResult=function(e,t,n,r,i){void 0===i&&(i=0);try{var s=this;return Promise.resolve(s.getConsumerAddress(t)).then(function(a){function o(){return Promise.resolve(s.dialAndStream(e,u)).then(function(e){var t,n,r=e.lp,i=e.firstBytes,a=JSON.parse((new TextDecoder).decode(i));if("number"==typeof(null==a?void 0:a.httpStatus)&&a.httpStatus>=400)throw new Error(null!=(n=a.error)?n:"P2P compute result error: "+a.httpStatus);var o=null!=(t=s.p2pConfig.dialTimeout)?t:uT;return F(/*#__PURE__*/D().mark(function e(){var t;return D().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,A(r.read({signal:AbortSignal.timeout(o)}));case 4:return t=e.sent,e.next=7,t instanceof Uint8Array?t:t.subarray();case 7:e.next=1;break;case 9:e.next=15;break;case 11:if(e.prev=11,e.t0=e.catch(0),e.t0 instanceof Bd){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))()})}var u={command:T.COMPUTE_GET_RESULT,jobId:n,index:r,offset:i,consumerAddress:a},d=function(){if("string"!=typeof t)return Promise.resolve(s.getNonce(e,a)).then(function(e){var n=(e+1).toString();return u.nonce=n,Promise.resolve(s.getSignature(t,n,T.COMPUTE_GET_RESULT)).then(function(e){u.signature=e})});u.authorization=t}();return d&&d.then?d.then(o):o()})}catch(e){return Promise.reject(e)}},t.getComputeResultUrl=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getConsumerAddress(t)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,T.COMPUTE_GET_RESULT,{jobId:n,index:r,consumerAddress:s},t))})}catch(e){return Promise.reject(e)}},t.generateAuthToken=function(e,t,n){try{var r=this;return Promise.resolve(e.getAddress()).then(function(i){return Promise.resolve(r.getNonce(t,i,n)).then(function(s){var a=(s+1).toString();return Promise.resolve(r.getSignature(e,a,T.CREATE_AUTH_TOKEN)).then(function(e){return Promise.resolve(r.sendP2pCommand(t,T.CREATE_AUTH_TOKEN,{address:i,signature:e,nonce:a},null,n)).then(function(e){var t;return null!=(t=null==e?void 0:e.token)?t:e})})})})}catch(e){return Promise.reject(e)}},t.generateSignedAuthToken=function(e,t,n,r,i){try{return Promise.resolve(this.sendP2pCommand(r,T.CREATE_AUTH_TOKEN,{address:e,signature:t,nonce:n},null,i)).then(function(e){var t;return null!=(t=null==e?void 0:e.token)?t:e})}catch(e){return Promise.reject(e)}},t.resolveDdo=function(e,t,n){try{return Promise.resolve(this.sendP2pCommand(e,T.GET_DDO,{id:t},null,n))}catch(e){return Promise.reject(e)}},t.validateDdo=function(e,t,n,r){try{var i=this;return Promise.resolve(n.getAddress()).then(function(s){return Promise.resolve(i.getNonce(e,s,r)).then(function(a){var o=(a+1).toString();return Promise.resolve($e(n,s+o+T.VALIDATE_DDO)).then(function(n){return Promise.resolve(i.sendP2pCommand(e,T.VALIDATE_DDO,{ddo:t,publisherAddress:s,nonce:o,signature:n},null,r)).then(function(e){var t,n,r,s;return!e||e.error?null:{valid:!0,hash:i.bufToHex(e.hash),proof:{validatorAddress:i.bufToHex(e.publicKey),r:i.bufToHex(null!=(t=null==(n=e.r)?void 0:n[0])?t:e.r),s:i.bufToHex(null!=(r=null==(s=e.s)?void 0:s[0])?r:e.s),v:e.v}}})})})})}catch(e){return Promise.reject(e)}},t.invalidateAuthToken=function(e,t,n,r){try{var i=this;return Promise.resolve(e.getAddress()).then(function(s){return Promise.resolve(i.getNonce(n,s,r)).then(function(a){var o=(a+1).toString();return Promise.resolve($e(e,s+o)).then(function(e){return i.sendP2pCommand(n,T.INVALIDATE_AUTH_TOKEN,{address:s,signature:e,token:t,nonce:o},null,r)})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){var n=this;return Promise.resolve(tT(function(){return Promise.resolve(n.sendP2pCommand(e,T.STATUS,{},null,t)).then(function(e){return!(!e||!(e.address||e.providerAddress||e.providerAddresses))})},function(){return!1}))},t.PolicyServerPassthrough=function(e,t,n){try{return Promise.resolve(this.sendP2pCommand(e,T.POLICY_SERVER_PASSTHROUGH,k({},t),null,n))}catch(e){return Promise.reject(e)}},t.initializePSVerification=function(e,t,n){try{return Promise.resolve(this.sendP2pCommand(e,T.POLICY_SERVER_PASSTHROUGH,k({},t),null,n))}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,a,o,u){try{var d=this;return Promise.resolve(t.getAddress()).then(function(c){return Promise.resolve(d.getNonce(e,c,u)).then(function(l){var p=(l+1).toString();return Promise.resolve(d.getSignature(t,p,T.GET_LOGS)).then(function(l){var h={startTime:n,endTime:r,signature:l,nonce:p,address:c};return i&&(h.maxLogs=i),s&&(h.moduleName=s),a&&(h.level=a),o&&(h.page=o),d.sendP2pCommand(e,T.GET_LOGS,h,t,u)})})})}catch(e){return Promise.reject(e)}},t.fetchNodeLogs=function(e,t,n,r,i){try{return Promise.resolve(this.sendP2pCommand(e,T.GET_LOGS,k({address:t,signature:n,nonce:r},i)))}catch(e){return Promise.reject(e)}},t.fetchConfig=function(e,t){try{return Promise.resolve(this.sendP2pCommand(e,T.FETCH_CONFIG,t))}catch(e){return Promise.reject(e)}},t.pushConfig=function(e,t){try{return Promise.resolve(this.sendP2pCommand(e,T.PUSH_CONFIG,t))}catch(e){return Promise.reject(e)}},t.getPersistentStorageSignaturePayload=function(e,t,n,r){try{var i=this;if("string"==typeof t)throw new Error("Persistent storage operations require a Signer because these commands require nonce/signature.");return Promise.resolve(i.getConsumerAddress(t)).then(function(s){return Promise.resolve(i.getNonce(e,s,r)).then(function(e){var r=(e+1).toString();return Promise.resolve(i.getSignature(t,r,n)).then(function(e){if(!e)throw new Error("Could not sign persistent storage request.");return{consumerAddress:s,nonce:r,signature:e}})})})}catch(e){return Promise.reject(e)}},t.createPersistentStorageBucket=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(s){var a;return i.sendP2pCommand(e,T.PERSISTENT_STORAGE_CREATE_BUCKET,k({},s,{accessLists:null!=(a=n.accessLists)?a:[]}),t,r)})}catch(e){return Promise.reject(e)}},t.getPersistentStorageBuckets=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_GET_BUCKETS,i)).then(function(a){return Promise.resolve(s.sendP2pCommand(e,T.PERSISTENT_STORAGE_GET_BUCKETS,k({},a,{owner:n,chainId:r}),t,i)).then(function(e){return Array.isArray(e)?e:[]})})}catch(e){return Promise.reject(e)}},t.listPersistentStorageFiles=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,T.PERSISTENT_STORAGE_LIST_FILES,k({},s,{bucketId:n}),t,r)).then(function(e){return Array.isArray(e)?e:[]})})}catch(e){return Promise.reject(e)}},t.getPersistentStorageFileObject=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(a){return s.sendP2pCommand(e,T.PERSISTENT_STORAGE_GET_FILE_OBJECT,k({},a,{bucketId:n,fileName:r}),t,i)})}catch(e){return Promise.reject(e)}},t.uploadPersistentStorageFile=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(o){return a.sendP2pCommand(e,T.PERSISTENT_STORAGE_UPLOAD_FILE,k({},o,{bucketId:n,fileName:r}),t,s,0,i)})}catch(e){return Promise.reject(e)}},t.deletePersistentStorageFile=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_DELETE_FILE,s)).then(function(o){return a.sendP2pCommand(e,T.PERSISTENT_STORAGE_DELETE_FILE,k({},o,{bucketId:n,fileName:r,chainId:i}),t,s)})}catch(e){return Promise.reject(e)}},e}(),lT=function(e,t,n){try{if("string"==typeof e)return Promise.resolve(null);var r=String,i=String;return Promise.resolve(e.getAddress()).then(function(s){var a=r(i(s)+String(t)+String(n));return $e(e,a)})}catch(e){return Promise.reject(e)}},pT=function(e){try{return Promise.resolve("string"==typeof e?function(e){try{return v.default.decode(e,{json:!0})}catch(e){throw new Error("Error decoding JWT")}}(e).address:e.getAddress())}catch(e){return Promise.reject(e)}};function hT(e){return"string"==typeof e?e:void 0}function fT(e){if(Array.isArray(e))return!0;if(!e)return!1;try{return Pu(e),!0}catch(e){}try{return Uo(e),!0}catch(e){return!1}}var mT=/*#__PURE__*/function(){function e(){this.httpProvider=new Iu,this.p2pProvider=new cT}var t=e.prototype;return t.getImpl=function(e){return Array.isArray(e)||fT(e)?this.p2pProvider:this.httpProvider},t.getNonce=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).getNonce(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{return Promise.resolve(this.getImpl(n).encrypt(e,t,n,r,i,s))}catch(e){return Promise.reject(e)}},t.checkDidFiles=function(e,t,n,r,i){void 0===r&&(r=!1);try{return Promise.resolve(this.getImpl(n).checkDidFiles(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.getFileInfo=function(e,t,n,r){void 0===n&&(n=!1);try{return Promise.resolve(this.getImpl(t).getFileInfo(e,t,n,r))}catch(e){return Promise.reject(e)}},t.getComputeEnvironments=function(e,t){try{return Promise.resolve(this.getImpl(e).getComputeEnvironments(e,t))}catch(e){return Promise.reject(e)}},t.initialize=function(e,t,n,r,i,s,a,o,u){try{return Promise.resolve(this.getImpl(i).initialize(e,t,n,r,i,s,a,o,u))}catch(e){return Promise.reject(e)}},t.initializeCompute=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h){try{return Promise.resolve(this.getImpl(s).initializeCompute(e,t,n,r,i,s,a,o,u,d,c,l,p,h))}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,a,o){try{return Promise.resolve(this.getImpl(i).getDownloadUrl(e,t,n,r,i,s,a,o))}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m){try{return Promise.resolve(this.getImpl(e).computeStart(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m))}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p){try{return Promise.resolve(this.getImpl(e).freeComputeStart(e,t,n,r,i,s,a,o,u,d,c,l,p))}catch(e){return Promise.reject(e)}},t.computeStreamableLogs=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).computeStreamableLogs(e,t,n,r))}catch(e){return Promise.reject(e)}},t.computeStop=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(t).computeStop(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).computeStatus(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.getComputeResultUrl=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).getComputeResultUrl(e,t,n,r))}catch(e){return Promise.reject(e)}},t.getComputeResult=function(e,t,n,r,i){void 0===i&&(i=0);try{return Promise.resolve(this.getImpl(e).getComputeResult(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.generateAuthToken=function(e,t,n){try{return Promise.resolve(this.getImpl(t).generateAuthToken(e,t,n))}catch(e){return Promise.reject(e)}},t.generateSignedAuthToken=function(e,t,n,r,i){try{return Promise.resolve(this.p2pProvider.generateSignedAuthToken(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.invalidateAuthToken=function(e,t,n,r){try{return Promise.resolve(this.getImpl(n).invalidateAuthToken(e,t,n,r))}catch(e){return Promise.reject(e)}},t.resolveDdo=function(e,t,n){try{return Promise.resolve(this.getImpl(e).resolveDdo(e,t,n))}catch(e){return Promise.reject(e)}},t.validateDdo=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).validateDdo(e,t,n,r))}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){try{return Promise.resolve(this.getImpl(e).isValidProvider(e,t))}catch(e){return Promise.reject(e)}},t.PolicyServerPassthrough=function(e,t,n){try{return Promise.resolve(this.getImpl(e).PolicyServerPassthrough(e,t,n))}catch(e){return Promise.reject(e)}},t.initializePSVerification=function(e,t,n){try{return Promise.resolve(this.getImpl(e).initializePSVerification(e,t,n))}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,a,o,u){try{return Promise.resolve(this.getImpl(e).downloadNodeLogs(e,t,n,r,i,s,a,o,u))}catch(e){return Promise.reject(e)}},t.getNodeStatus=function(e,t){try{return Promise.resolve(this.getImpl(e).getNodeStatus(e,t))}catch(e){return Promise.reject(e)}},t.getNodeJobs=function(e,t,n){try{return Promise.resolve(this.getImpl(e).getNodeJobs(e,t,n))}catch(e){return Promise.reject(e)}},t.setupP2P=function(e){try{return Promise.resolve(this.p2pProvider.setupP2P(e))}catch(e){return Promise.reject(e)}},t.getLibp2pNode=function(){return this.p2pProvider.getLibp2pNode()},t.getDiscoveredNodes=function(){try{return Promise.resolve(this.p2pProvider.getDiscoveredNodes())}catch(e){return Promise.reject(e)}},t.getMultiaddrFromPeerId=function(e){try{return Promise.resolve(this.p2pProvider.getMultiaddrFromPeerId(e))}catch(e){return Promise.reject(e)}},t.fetchNodeLogs=function(e,t,n,r,i){try{return Promise.resolve(this.p2pProvider.fetchNodeLogs(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.createPersistentStorageBucket=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).createPersistentStorageBucket(e,t,n,r))}catch(e){return Promise.reject(e)}},t.getPersistentStorageBuckets=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).getPersistentStorageBuckets(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.listPersistentStorageFiles=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).listPersistentStorageFiles(e,t,n,r))}catch(e){return Promise.reject(e)}},t.getPersistentStorageFileObject=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).getPersistentStorageFileObject(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.uploadPersistentStorageFile=function(e,t,n,r,i,s){try{return Promise.resolve(this.getImpl(e).uploadPersistentStorageFile(e,t,n,r,i,s))}catch(e){return Promise.reject(e)}},t.deletePersistentStorageFile=function(e,t,n,r,i,s){try{return Promise.resolve(this.getImpl(e).deletePersistentStorageFile(e,t,n,r,i,s))}catch(e){return Promise.reject(e)}},t.fetchConfig=function(e,t){try{return Promise.resolve(this.p2pProvider.fetchConfig(e,t))}catch(e){return Promise.reject(e)}},t.pushConfig=function(e,t){try{return Promise.resolve(this.p2pProvider.pushConfig(e,t))}catch(e){return Promise.reject(e)}},e}(),yT=new mT;function bT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function gT(e,t,n){if(!e.s){if(n instanceof vT){if(!n.s)return void(n.o=gT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(gT.bind(null,e,t),gT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var vT=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var s=1&i?t:n;if(s){try{gT(r,1,s(this.v))}catch(e){gT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?gT(r,1,t?t(i):i):n?gT(r,1,n(i)):gT(r,2,i)}catch(e){gT(r,2,e)}},r},e}();function wT(e){return e instanceof vT&&1&e.s}var TT=/*#__PURE__*/function(){function e(e){this.aquariusURL=void 0,this.aquariusURL=e}var t=e.prototype;return t.resolve=function(e,t,n){try{var r,i=function(i){if(r)return i;var a=s.aquariusURL+"/api/aquarius/assets/ddo/"+e;return bT(function(){return Promise.resolve(g.default(a,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:t})).then(function(e){if(e.ok)return Promise.resolve(e.json());throw new Error("HTTP request failed with status "+e.status)})},function(e){throw O.error(e),new Error("HTTP request failed")})},s=this,a=function(){if(fT(s.aquariusURL))return Promise.resolve(yT.resolveDdo(s.aquariusURL,e,t)).then(function(e){if(e)return r=1,e;throw new Error("P2P request failed")})}();return Promise.resolve(a&&a.then?a.then(i):i(a))}catch(e){return Promise.reject(e)}},t.waitForIndexer=function(e,t,n,r,i,s){void 0===r&&(r=3e4),void 0===i&&(i=100);try{var o,u=this,d=0;i>500&&(O.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);var c=fT(u.aquariusURL),l=function(e,t){var n;do{var r=e();if(r&&r.then){if(!wT(r)){n=!0;break}r=r.v}var i=t();if(wT(i)&&(i=i.v),!i)return r}while(!i.then);var s=new vT,a=gT.bind(null,s,2);return(n?r.then(o):i.then(u)).then(void 0,a),s;function o(n){for(r=n;wT(i=t())&&(i=i.v),i;){if(i.then)return void i.then(u).then(void 0,a);if((r=e())&&r.then){if(!wT(r))return void r.then(o).then(void 0,a);r=r.v}}gT(s,1,r)}function u(n){if(n){do{if((r=e())&&r.then){if(!wT(r))return void r.then(o).then(void 0,a);r=r.v}if(wT(n=t())&&(n=n.v),!n)return void gT(s,1,r)}while(!n.then);n.then(u).then(void 0,a)}else gT(s,1,r)}}(function(){function i(e){return o?e:Promise.resolve(qe(r)).then(function(){d++})}var l=bT(function(){function r(){if(i){var e=a.DDOManager.getDDOClass(i).getAssetFields().indexedMetadata;if(!t)return o=1,i;if(e.event&&e.event.txid===t)return o=1,i}}var i,d=c?Promise.resolve(yT.resolveDdo(u.aquariusURL,e,n)).then(function(e){i=e}):Promise.resolve(g.default(u.aquariusURL+"/api/aquarius/assets/ddo/"+e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:s},signal:n})).then(function(e){var t=function(){if(e.ok)return Promise.resolve(e.json()).then(function(e){i=e})}();if(t&&t.then)return t.then(function(){})});return d&&d.then?d.then(r):r()},function(){});return l&&l.then?l.then(i):i(l)},function(){return!o&&d<i});return Promise.resolve(l&&l.then?l.then(function(e){return o?e:null}):o?l:null)}catch(e){return Promise.reject(e)}},t.validate=function(e,t,n,r,i){try{if(fT(n))return Promise.resolve(yT.validateDdo(n,e,t,r));var s=n+"/api/aquarius/assets/ddo/validate",a=n+"/api/services/nonce";return Promise.resolve(bT(function(){return Promise.resolve(t.getAddress()).then(function(n){return Promise.resolve(g.default(a+"?userAddress="+n,{method:"GET",headers:{"Content-Type":"application/json",Authorization:i},signal:r})).then(function(i){return Promise.resolve(i.json()).then(function(i){var a=i.nonce;a&&null!==a||(a="0");var o=(Number(a)+1).toString(),u=String,d=String;return Promise.resolve(t.getAddress()).then(function(i){var a=u(d(i)+String(o)+String(T.VALIDATE_DDO));return Promise.resolve($e(t,a)).then(function(i){return Promise.resolve(g.default(s,{method:"POST",body:JSON.stringify({ddo:e,publisherAddress:n,nonce:o,signature:i}),headers:{"Content-Type":"application/json",Authorization:hT(t)},signal:r})).then(function(e){return Promise.resolve(e.json()).then(function(t){if(200!==e.status)throw new Error("Metadata validation failed");return{valid:!0,hash:t.hash,proof:{validatorAddress:t.publicKey,r:t.r[0],s:t.s[0],v:t.v}}})})})})})})})},function(e){O.error("Metadata validation failed",e.message)}))}catch(e){return Promise.reject(e)}},t.getAssetMetadata=function(e,t,n){try{var r=this.aquariusURL+"/api/aquarius/assets/metadata/"+e;return Promise.resolve(bT(function(){return Promise.resolve(g.default(r,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:t})).then(function(e){if(e.ok)return e.json();throw new Error("getAssetMetadata failed: "+e.status+e.statusText)})},function(e){throw O.error("Error getting metadata: ",e),new Error("Error getting metadata: "+e)}))}catch(e){return Promise.reject(e)}},t.querySearch=function(e,t,n){try{var r=this.aquariusURL+"/api/aquarius/assets/query";return Promise.resolve(bT(function(){return Promise.resolve(g.default(r,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:n},signal:t})).then(function(e){if(e.ok)return e.json();throw new Error("querySearch failed: "+e.status+e.statusText)})},function(e){throw O.error("Error querying metadata: ",e),new Error("Error querying metadata: "+e)}))}catch(e){return Promise.reject(e)}},e}(),ET=function(e,n,r,i){try{var s=new t.ethers.Contract(n,z,e);return Promise.resolve(s.allowance(r,i))}catch(e){return Promise.reject(e)}},xT=function(e,n,r,i,s){try{var a=new t.ethers.Contract(n,z,e);return Promise.resolve(a.allowance(r,i)).then(function(t){return Promise.resolve(K(e,n,t,s))})}catch(e){return Promise.reject(e)}},PT=function(e,n,r,i,s,a,o,u){void 0===o&&(o=!1);try{var d,c=function(t){if(d)return t;var r=null;return Promise.resolve(l.approve.estimateGas(s,a)).then(function(t){if(u)return t;var i=function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(function(){return Promise.resolve(V(t,e,null==n?void 0:n.gasFeeMultiplier,l.approve,s,a)).then(function(e){r=e})},function(e){O.error("ERROR: Failed to approve spender to spend tokens : "+e.message)});return i&&i.then?i.then(function(){return r}):r})},l=new t.ethers.Contract(i,z,e),p=function(){if(!o)return Promise.resolve(ET(e,i,r,s)).then(function(e){if(new y.default(e).isGreaterThan(new y.default(a))){var t=BigInt(e);return d=1,t}})}();return Promise.resolve(p&&p.then?p.then(c):c(p))}catch(e){return Promise.reject(e)}},ST=function(e,n,r,i,s,a,o,u,d){void 0===o&&(o=!1);try{var c,l=function(t){return c?t:Promise.resolve(G(e,i,a,u)).then(function(t){return Promise.resolve(p.approve.estimateGas(s,t)).then(function(r){return d?new b.default(r.toString()):Promise.resolve(V(r,e,null==n?void 0:n.gasFeeMultiplier,p.approve,s,t))})})},p=new t.ethers.Contract(i,z,e),h=function(){if(!o)return Promise.resolve(xT(e,i,r,s)).then(function(e){if(new b.default(e).greaterThanOrEqualTo(new b.default(a))){var t=new b.default(e).toNumber();return c=1,t}})}();return Promise.resolve(h&&h.then?h.then(l):l(h))}catch(e){return Promise.reject(e)}},AT={datasets:{invalid:"Datasets is not a list, as expected"},algorithm:{serviceId:{missing:"The serviceId key is missing from the algorithm s DDO.",not_found:"The provided serviceId does not exist.",service_not_access_compute:"Service type is neither access, nor compute.",main_service_compute:"If the main service is not compute for this asset when calling initialize endpoint.",compute_services_not_in_same_provider:"Files attached to the compute service are not decrypted by the correct provider. This occurs when both asset and algorithm are requested by their compute service which cannot be decrypted by a single provider as how it is supposed to be."},container:{checksum_prefix:"Container checksum does not start with the prefix sha256:.",mising_entrypoint_image_checksum:"Either entrypoint, either image, or either checksum are missing from the container dictionary from the algorithm s DDO."},documentId:{did_not_found:"The algorithm s DID could not be retrieved from the metadata store, because the algorithm asset does not exist.",missing:"The documentId key is missing from the algorithm s DDO."},transferTxId:{missing:"The transferTxId key is missing from the algorithm s DDO."},missing_meta_documentId:"Either algorithm metadata, or algorithm DID are missing.",did_not_found:"Either algorithm metadata, or algorithm DID are missing.",not_algo:"Either algorithm metadata, or algorithm DID are missing.",in_use_or_not_on_chain:"Either algorithm metadata, or algorithm DID are missing.",meta_oneof_url_rawcode_remote:"Either algorithm metadata, or algorithm DID are missing.",file_unavailable:"One possibility is that the asset could not be retrieved from Aquariuss database. Otherwise, there are issues related to services"},error:{not_trusted_algo_publisher:"The owner of the algorithm's DDO is not a trusted algorithms publishers list.",not_trusted_algo:"The algorithm's DID is not in the asset's trusted algorithms dictionary. ",no_publisherTrustedAlgorithms:"The algorithm's key publisherTrustedAlgorithms does not exist in the algorithm's DDO.",algorithm_file_checksum_mismatch:"filesChecksum from the algorithm's DDO is invalid.",algorithm_container_checksum_mismatch:"The containerChecksum from the algorithm's DDO is invalid.",no_raw_algo_allowed:"The asset does not allow raw algorithms to be run on it.","Asset malformed":"The asset published on chain is malformed, missing some required keys or not compliant with our schemas.","Asset is not consumable.":"Assets metadata status is not in the range of valid status codes for assets. The recognized states for the metadata are defined on our docs.","DID is not a valid algorithm.":"Either the algorithm assets DID is incorrectly typed, either the algorithm timeout expired.","Compute environment does not exist.":"The compute environment provided by the user does not exist, it is not served by our compute-to-data feature. The user can use get_c2d_environments to check the list of available compute environments.","The validUntil value is not correct.":"validUntil value is most probably expired.","Cannot resolve DID":"The dataset DID does not exist in the Metadata store.","Invalid serviceId":"The serviceId of that dataset is not correct.","Unable to get dataset files":"The files of that dataset could not be decrypted or retrieved","cannot decrypt files for this service.":"The files of that dataset could not be decrypted due to the fact that file object, which contains the structure and the type of specific file, is missing from the validation part.","Unsupported type ":"The file object type is not supported by Provider.","malformed file object":"The file object structure is invalid and does not contain the wanted information for the specific file."},order:{fees_not_paid:" Provider fees are not paid."},output:{invalid:"The algorithms validation after the build stage has not been decoded properly as a dictionary."}};function CT(e,t,n){if(!e.s){if(n instanceof kT){if(!n.s)return void(n.o=CT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(CT.bind(null,e,t),CT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var kT=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var s=1&i?t:n;if(s){try{CT(r,1,s(this.v))}catch(e){CT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?CT(r,1,t?t(i):i):n?CT(r,1,n(i)):CT(r,2,i)}catch(e){CT(r,2,e)}},r},e}();function IT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}exports.AccessListContract=Fe,exports.AccesslistFactory=_e,exports.Aquarius=TT,exports.Config=function(){this.nodeUri=void 0,this.providerAddress=void 0,this.oceanNodeUri=void 0,this.web3Provider=void 0,this.oceanTokenAddress=void 0,this.nftFactoryAddress=void 0,this.routerFactoryAddress=void 0,this.datatokensABI=void 0,this.fixedRateExchangeAddress=void 0,this.fixedRateExchangeAddressABI=void 0,this.dispenserAddress=void 0,this.dispenserABI=void 0,this.opfCommunityFeeCollector=void 0,this.EnterpriseFeeCollector=void 0,this.sideStakingAddress=void 0,this.startBlock=void 0,this.verbose=void 0,this.authMessage=void 0,this.authTokenExpiration=void 0,this.parityUri=void 0,this.threshold=void 0,this.chainId=void 0,this.network=void 0,this.explorerUri=void 0,this.oceanTokenSymbol=void 0,this.transactionBlockTimeout=void 0,this.transactionConfirmationBlocks=void 0,this.transactionPollingTimeout=void 0,this.gasFeeMultiplier=void 0,this.sdk=void 0,this.accessListFactory=void 0,this.escrow=void 0},exports.ConfigHelper=$,exports.DEVELOPMENT_CHAIN_ID=8996,exports.Datatoken=ke,exports.Datatoken4=De,exports.Dispenser=ae,exports.EnterpriseFeeCollectorContract=je,exports.EscrowContract=Be,exports.FEE_HISTORY_NOT_SUPPORTED="Returned error: Method eth_feeHistory not supported.",exports.FixedRateExchange=de,exports.GASLIMIT_DEFAULT=1e6,exports.KNOWN_CONFIDENTIAL_EVMS=j,exports.Logger=N,exports.LoggerInstance=O,exports.MAX_UINT_256="115792089237316195423570985008687907853269984665640564039457584007913129639934",exports.Nft=Ce,exports.NftFactory=ve,exports.OCEAN_P2P_PROTOCOL=oT,exports.PROTOCOL_COMMANDS=T,exports.Provider=mT,exports.ProviderInstance=yT,exports.Router=le,exports.SmartContract=re,exports.SmartContractWithAddress=ie,exports.ZERO_ADDRESS=ue,exports.allowance=xT,exports.allowanceWei=ET,exports.amountToUnits=G,exports.approve=ST,exports.approveWei=PT,exports.balance=function(e,n,r,i){try{var s=new t.ethers.Contract(n,z,e);return Promise.resolve(s.balanceOf(r)).then(function(t){return Promise.resolve(K(e,n,t,i))})}catch(e){return Promise.reject(e)}},exports.bytesToHex=Su,exports.calculateActiveTemplateIndex=Pe,exports.concatUint8Arrays=Au,exports.configHelperNetworks=U,exports.createAccessListFactory=function(e,n,r){try{var i=new t.ethers.Contract(e,Re,n);return Promise.resolve(n.getAddress()).then(function(e){var t,n=IT(function(){return Promise.resolve(i.deployAccessListContract("AllowList","ALLOW",!0,e,r||[e],["https://oceanprotocol.com/nft/"])).then(function(e){return function(){if(e&&e.wait)return Promise.resolve(e.wait()).then(function(e){var n=ne(e,"NewAccessList");return t=1,n.args[0]})}()})},function(e){console.log("ERROR createAccessListFactory(): ",e)});return n&&n.then?n.then(function(e){return t?e:null}):t?n:null})}catch(e){return Promise.reject(e)}},exports.createAsset=function(e,n,r,i,s,o,u,d,c,l,p,h,f,m,y){void 0===u&&(u=!0);try{var b,g,v=this,T=a.DDOManager.getDDOClass(o),E=T.getAssetFields().indexedMetadata,x=(null==(b=T.getDDOData())||null==(b=b.stats)||null==(b=b.price)?void 0:b.value)||(null==E||null==(g=E.stats[0])||null==(g=g.prices[0])?void 0:g.price),P=T.getDDOFields(),S=P.chainId,A=P.nftAddress,C=T.getDDOFields().services;if("string"!=typeof s&&"number"!=typeof s)throw new Error('Invalid template! Must be a "number" or a "string"');return Promise.resolve(r.provider.getNetwork()).then(function(a){var b=a.chainId;if(S&&S!==Number(b))throw new Error("Chain ID from DDO is different than the configured network.");var g=(new $).getConfig(parseInt(String(b)));return Promise.resolve(Pe(r,g.nftFactoryAddress,s,Number(b))).then(function(s){if(s<1){if(8996!==Number(b))throw new Error("Invalid template index: "+s);s=1}var a=new Ce(r,Number(b)),E=new ve(g.nftFactoryAddress,r,Number(b));return Promise.resolve(r.getAddress()).then(function(P){var k;function I(e){return k?e:Promise.resolve(D.wait()).then(function(e){var n;function i(e){if(n)return e;function i(){function e(){var e=a.setMetadata,u=A;return Promise.resolve(r.getAddress()).then(function(r){return Promise.resolve(e.call(a,u,r,0,d,"",t.toBeHex(s),n,i)).then(function(){return o.id})})}C[0].datatokenAddress=h,C[0].serviceEndpoint=d;var n,i,s,c=T.makeDid(A=p,S.toString());o=T.updateFields({id:c,nftAddress:A});var f=function(){if(u)return Promise.resolve(yT.encrypt(o,Number(b),d,r,null)).then(function(e){return n=e,Promise.resolve(l.validate(o,r,d)).then(function(e){i=e.hash,s=2})});var e=JSON.stringify(o);n=t.hexlify(t.toUtf8Bytes(e)),i="0x"+w.default(n).toString(),s=0}();return f&&f.then?f.then(e):e()}var s=function(){if("oasis"!==g.sdk)return Promise.resolve(yT.encrypt(R,Number(b),d,r,null)).then(function(e){C[0].files=e});C[0].files=""}();return s&&s.then?s.then(i):i()}var s=ne(e,"NFTCreated"),c=ne(e,"TokenCreated"),p=s.args.newTokenAddress,h=c.args.newTokenAddress;R.datatokenAddress=h,R.nftAddress=p;var f=function(){if("oasis"===g.sdk){var e=new t.ethers.Contract(h,Ie,r);return IT(function(){return Promise.resolve(e.setFilesObject(t.toUtf8Bytes(JSON.stringify(R)))).then(function(e){var t=function(){if(e.wait)return Promise.resolve(e.wait()).then(function(){})}();if(t&&t.then)return t.then(function(){})})},function(e){return console.log("Error updating files object with data token and nft addresses: ",e),n=1,null})}}();return f&&f.then?f.then(i):i(f)})}var D,M={name:e,symbol:n,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:P},F={templateIndex:s,cap:"100000",feeAmount:"0",paymentCollector:P,feeToken:c||g.oceanTokenAddress,minter:P,mpFeeAddress:ue},R={nftAddress:"0x0",datatokenAddress:"0x0",files:i};"oasis"===g.sdk&&(F.filesObject=R,F.accessListFactory=p||g.accessListFactory,F.allowAccessList=h,F.denyAccessList=f);var _=IT(function(){var e=function(){if(!x)return Promise.resolve(E.createNftWithDatatoken(M,F)).then(function(e){D=e});var e=function(){if("0"===x.toString())return Promise.resolve(E.createNftWithDatatokenWithDispenser(M,F,{dispenserAddress:g.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:ue})).then(function(e){D=e});var e=m||g.oceanTokenAddress;return Promise.resolve(H(v.signer,e)).then(function(t){y||(y=t);var n={fixedRateAddress:g.fixedRateExchangeAddress,baseTokenAddress:e,owner:P,marketFeeCollector:P,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:x.toString(),marketFee:"0",allowedConsumer:P,withMint:!0};return Promise.resolve(E.createNftWithDatatokenWithFixedRate(M,F,n)).then(function(e){D=e})})}();return e&&e.then?e.then(function(){}):void 0}();if(e&&e.then)return e.then(function(){})},function(e){return console.log("ERROR creating NFT bundle",e),k=1,null});return _&&_.then?_.then(I):I(_)})})})}catch(e){return Promise.reject(e)}},exports.decimals=function(e,n){try{var r=new t.ethers.Contract(n,z,e);return Promise.resolve(r.decimals()).then(Number)}catch(e){return Promise.reject(e)}},exports.downloadFile=function(e,t){try{return"string"!=typeof e?Promise.resolve(e):Promise.resolve(fetch(e)).then(function(n){if(!n.ok)throw new Error("Response error.");var r;try{r=n.headers.get("content-disposition").match(/attachment;filename=(.+)/)[1]}catch(n){try{r=e.split("/").pop()}catch(e){r="file"+t}}return Promise.resolve(n.arrayBuffer()).then(function(e){return{data:e,filename:r}})})}catch(e){return Promise.reject(e)}},exports.downloadFileBrowser=function(e){var t=new XMLHttpRequest;t.responseType="blob",t.open("GET",e),t.onload=function(){var e=t.getResponseHeader("content-disposition"),n=null==e?void 0:e.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/),r=n&&n[1]?n[1]:"file",i=window.URL.createObjectURL(t.response),s=document.createElement("a");s.href=i,s.setAttribute("download",r),document.body.appendChild(s),s.click(),s.remove(),window.URL.revokeObjectURL(i)},t.send()},exports.generateDid=function(e,n){return e=t.getAddress(e),"did:op:"+w.default(e+n.toString(10)).toString()},exports.generateDtName=ye,exports.getErrorMessage=function(e){try{var t=JSON.parse(e),n=Object.keys(t)[0];if("error"===n){var r,i=t[n];return(null==(r=AT[n])?void 0:r[i])||"Provider request failed: "+i}var s=t[n];return t[Object.keys(t)[1]]+" : "+s}catch(t){return O.error("[getErrorMessage] error: ",t),e}},exports.getEventFromTx=ne,exports.getFairGasPrice=W,exports.getHash=function(e){return w.default(e).toString()},exports.getNodeEndpointConfig=q,exports.getOceanArtifactsAddresses=Se,exports.getOceanArtifactsAddressesByChainId=Ae,exports.getTokenDecimals=H,exports.isDefined=function(e){return null!=e},exports.isP2pUri=fT,exports.minAbi=z,exports.orderAsset=function(e,t,n,r,i,s,o,u,d,c,l,p){void 0===d&&(d="0"),void 0===c&&(c=0),void 0===l&&(l=0),void 0===p&&(p=0);try{var h=a.DDOManager.getDDOClass(e),f=h.getAssetFields().datatokens,m=h.getDDOFields(),y=m.chainId,g=m.services;return o||(o={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"}),Promise.resolve(t.provider.getNetwork()).then(function(a){if(y!==Number(a.chainId))throw new Error("Chain ID from DDO is different than the configured network.");if(!f[c].address)throw new Error("The datatoken with index: "+c+" does not exist for the asset with did: "+e.id);if(!g[l].id)throw new Error("There is no service with index: "+l+" defined for the asset with did: "+e.id);return Promise.resolve(r.getId(f[c].address)).then(function(a){return Promise.resolve(r.getFixedRates(f[c].address)).then(function(h){return Promise.resolve(r.getDispensers(f[c].address)).then(function(m){return Promise.resolve(r.getPublishingMarketFee(f[c].address)).then(function(y){function v(e){return u?e:Promise.resolve(E.call(yT,P,x,0,e,i||n.oceanNodeUri)).then(w)}function w(i){function m(i){function u(i){var s,u={consumer:i,serviceIndex:l,_providerFee:v,_consumeMarketFee:o};return function(e,t){var n,r=-1;e:{for(var i=0;i<t.length;i++){var s=t[i][0];if(s){var a=s();if(a&&a.then)break e;if(a===e){r=i;break}}else r=i}if(-1!==r){do{for(var o=t[r][1];!o;)r++,o=t[r][1];var u=o();if(u&&u.then){n=!0;break e}var d=t[r][2];r++}while(d&&!d());return u}}var c=new kT,l=CT.bind(null,c,2);return(n?u.then(p):a.then(function n(a){for(;;){if(a===e){r=i;break}if(++i===t.length){if(-1!==r)break;return void CT(c,1,u)}if(s=t[i][0]){if((a=s())&&a.then)return void a.then(n).then(void 0,l)}else r=i}do{for(var o=t[r][1];!o;)r++,o=t[r][1];var u=o();if(u&&u.then)return void u.then(p).then(void 0,l);var d=t[r][2];r++}while(d&&!d());CT(c,1,u)})).then(void 0,l),c;function p(e){for(;;){var n=t[r][2];if(!n||n())break;r++;for(var i=t[r][1];!i;)r++,i=t[r][1];if((e=i())&&e.then)return void e.then(p).then(void 0,l)}CT(c,1,e)}}(T,[[function(){return"free"},function(){var e=function(e){var t;if(s)return e;function i(e){if(t)return e}var o=function(){if(2===a||4===a)return Promise.resolve(r.buyFromDispenserAndOrder(g[l].datatokenAddress,u,n.dispenserAddress)).then(function(e){return t=1,e})}();return o&&o.then?o.then(i):i(o)},i=function(){if(1===a){var e=new ae(n.dispenserAddress,t),i=e.dispense,o=f[c].address;return Promise.resolve(t.getAddress()).then(function(t){return Promise.resolve(i.call(e,o,"1",t)).then(function(e){if(!e)throw new Error("Failed to dispense !");return Promise.resolve(e.wait()).then(function(){return Promise.resolve(r.startOrder(f[c].address,u.consumer,u.serviceIndex,u._providerFee,u._consumeMarketFee)).then(function(e){return s=1,e})})})})}}();return i&&i.then?i.then(e):e(i)}],[function(){return"fixed"},function(){var i=new de(n.fixedRateExchangeAddress,t);if(!h[p].id)throw new Error("There is no fixed rate exchange with index: "+l+" for the asset with did: "+e.id);return Promise.resolve(i.getFeesInfo(h[p].id)).then(function(e){return Promise.resolve(i.getExchange(h[p].id)).then(function(s){return Promise.resolve(i.calcBaseInGivenDatatokensOut(e.exchangeId,"1",o.consumeMarketFeeAmount)).then(function(l){var p;function h(e){var i;if(p)return e;function o(e){if(i)return e}var d=function(){if(2===a||4===a)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(ST(t,n,e,s.baseToken,f[c].address,m,!1)).then(function(e){function t(e){if(!e)throw new Error("Failed to confirm/mine approval transaction!");return Promise.resolve(r.buyFromFreAndOrder(f[c].address,u,g)).then(function(e){return i=1,e})}if(!e)throw new Error("Failed to approve "+s.baseToken+" !");return"number"!=typeof e?Promise.resolve("number"!=typeof e?e.wait():e).then(t):t("number"!=typeof e?e.wait():e)})})}();return d&&d.then?d.then(o):o(d)}var m=new b.default(+l.baseTokenAmount||0).add(new b.default(o.consumeMarketFeeAmount||0)).add(new b.default(+y.publishMarketFeeAmount||0)).toString(),g={exchangeContract:n.fixedRateExchangeAddress,exchangeId:e.exchangeId,maxBaseTokenAmount:m,baseTokenAddress:s.baseToken,baseTokenDecimals:parseInt(s.btDecimals)||18,swapMarketFee:d,marketFeeAddress:y.publishMarketFeeAddress},v=function(){if(1===a)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(ST(t,n,e,s.baseToken,n.fixedRateExchangeAddress,m,!1)).then(function(e){function t(e){if(!e)throw new Error("Failed to approve "+s.baseToken+" !");return Promise.resolve(i.buyDatatokens(s.exchangeId,"1",m,y.publishMarketFeeAddress,d)).then(function(e){return Promise.resolve(e.wait()).then(function(e){if(!e)throw new Error("Failed to buy datatoken from fixed rate!");return Promise.resolve(r.startOrder(f[c].address,u.consumer,u.serviceIndex,u._providerFee,u._consumeMarketFee)).then(function(e){return p=1,e})})})}return"number"!=typeof e?Promise.resolve("number"!=typeof e?e.wait():e).then(t):t("number"!=typeof e?e.wait():e)})})}();return v&&v.then?v.then(h):h(v)})})})}],[void 0,function(){throw new Error("Pricing schema not supported !")}]])}return s?u(s):Promise.resolve(t.getAddress()).then(u)}var v=u||i.providerFee,w=function(){if(v&&v.providerFeeAddress!==ue&&v.providerFeeAmount&&parseInt(v.providerFeeAmount)>0)return function(e,r){try{var i=Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(PT(t,n,e,v.providerFeeToken,g[0].datatokenAddress,v.providerFeeAmount)).then(function(){})})}catch(e){return r()}return i&&i.then?i.then(void 0,r):i}(0,function(){throw new Error("Failed to approve provider fee token "+v.providerFeeToken)})}();return w&&w.then?w.then(m):m()}var T=h.length>0?"fixed":m.length>0?"free":"NOT_ALLOWED",E=u||yT.initialize,x=u||g[l].id,P=u||e.id;return u?v(w(u)):Promise.resolve(t.getAddress()).then(v)})})})})})}catch(e){return Promise.reject(e)}},exports.sendTx=V,exports.setContractDefaults=te,exports.signHash=function(e,n){try{var r=t.getBytes(n);return Promise.resolve(e._legacySignMessage(r)).then(function(e){var t="0x"+(e=e.substr(2)).slice(0,64),n="0x"+e.slice(64,128),r="0x"+e.slice(128,130);return"0x00"===r&&(r="0x1b"),"0x01"===r&&(r="0x1c"),{v:r,r:t,s:n}})}catch(e){return Promise.reject(e)}},exports.signRequest=$e,exports.sleep=qe,exports.transfer=function(e,n,r,i,s,a,o){try{var u=new t.ethers.Contract(r,z,e);return Promise.resolve(G(e,r,s,a)).then(function(t){return Promise.resolve(u.transfer.estimateGas(i,t)).then(function(r){return o?r:Promise.resolve(V(r,e,null==n?void 0:n.gasFeeMultiplier,u.transfer,i,t))})})}catch(e){return Promise.reject(e)}},exports.unitsToAmount=K,exports.useOasisSDK=function(e){var t=(new $).getConfig(e);return t&&"oasis"===t.sdk};
|
|
3
|
+
/* @__PURE__ */,Zr(3)),Ri=/* @__PURE__ */BigInt(0),_i=/* @__PURE__ */BigInt(1);function Li(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e);return e}function Ni(e){if("bigint"==typeof e){if(!Vi(e))throw new Error("positive bigint expected, got "+e)}else Or(e);return e}function Oi(e){const t=Ni(e).toString(16);return 1&t.length?"0"+t:t}function Bi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Ri:BigInt("0x"+e)}function Ui(e){return Bi(Kr(e))}function ji(e){return Bi(Kr(zi(Br(e)).reverse()))}function qi(e,t){Or(t);const n=Wr((e=Ni(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}function $i(e,t){return qi(e,t).reverse()}function zi(e){return Uint8Array.from(e)}const Vi=e=>"bigint"==typeof e&&Ri<=e;function Gi(e,t,n,r){if(!function(e,t,n){return Vi(e)&&Vi(t)&&Vi(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const Ki=e=>(_i<<BigInt(e))-_i;function Hi(e,t={},n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");const r=(t,n)=>Object.entries(t).forEach(([t,r])=>function(t,n,r){const i=e[t];if(r&&void 0===i)return;const s=typeof i;if(s!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${s}`)}(t,r,n));r(t,!1),r(n,!0)}function Wi(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const s=e(n,...r);return t.set(n,s),s}}const Qi=/* @__PURE__ */BigInt(0),Yi=/* @__PURE__ */BigInt(1),Ji=/* @__PURE__ */BigInt(2),Zi=/* @__PURE__ */BigInt(3),Xi=/* @__PURE__ */BigInt(4),es=/* @__PURE__ */BigInt(5),ts=/* @__PURE__ */BigInt(7),ns=/* @__PURE__ */BigInt(8),rs=/* @__PURE__ */BigInt(9),is=/* @__PURE__ */BigInt(16);function ss(e,t){const n=e%t;return n>=Qi?n:t+n}function as(e,t,n){let r=e;for(;t-- >Qi;)r*=r,r%=n;return r}function os(e,t){if(e===Qi)throw new Error("invert: expected non-zero number");if(t<=Qi)throw new Error("invert: expected positive modulus, got "+t);let n=ss(e,t),r=t,i=Qi,s=Yi;for(;n!==Qi;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==Yi)throw new Error("invert: does not exist");return ss(i,t)}function us(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function ds(e,t){const n=e.pow(t,(e.ORDER+Yi)/Xi);return us(e,n,t),n}function cs(e,t){const n=(e.ORDER-es)/ns,r=e.mul(t,Ji),i=e.pow(r,n),s=e.mul(t,i),a=e.mul(e.mul(s,Ji),i),o=e.mul(s,e.sub(a,e.ONE));return us(e,o,t),o}function ls(e){if(e<Zi)throw new Error("sqrt is not defined for small field");let t=e-Yi,n=0;for(;t%Ji===Qi;)t/=Ji,n++;let r=Ji;const i=ys(e);for(;1===fs(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return ds;let s=i.pow(r,t);const a=(t+Yi)/Ji;return function(e,r){if(e.is0(r))return r;if(1!==fs(e,r))throw new Error("Cannot find square root");let i=n,o=e.mul(e.ONE,s),u=e.pow(r,t),d=e.pow(r,a);for(;!e.eql(u,e.ONE);){if(e.is0(u))return e.ZERO;let t=1,n=e.sqr(u);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw new Error("Cannot find square root");const r=Yi<<BigInt(i-t-1),s=e.pow(o,r);i=t,o=e.sqr(s),u=e.mul(u,o),d=e.mul(d,s)}return d}}const ps=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hs(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),s=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),s),r}function fs(e,t){const n=e.pow(t,(e.ORDER-Yi)/Ji),r=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!r&&!i&&!s)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}class ms{ORDER;BITS;BYTES;isLE;ZERO=Qi;ONE=Yi;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Qi)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,null!=t&&"object"==typeof t&&("number"==typeof t.BITS&&(n=t.BITS),"function"==typeof t.sqrt&&(this.sqrt=t.sqrt),"boolean"==typeof t.isLE&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),"boolean"==typeof t.modFromBytes&&(this._mod=t.modFromBytes));const{nBitLength:r,nByteLength:i}=function(e,t){void 0!==t&&Or(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ss(e,this.ORDER)}isValid(e){if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return Qi<=e&&e<this.ORDER}is0(e){return e===Qi}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Yi)===Yi}neg(e){return ss(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ss(e*e,this.ORDER)}add(e,t){return ss(e+t,this.ORDER)}sub(e,t){return ss(e-t,this.ORDER)}mul(e,t){return ss(e*t,this.ORDER)}pow(e,t){return function(e,t,n){if(n<Qi)throw new Error("invalid exponent, negatives unsupported");if(n===Qi)return e.ONE;if(n===Yi)return t;let r=e.ONE,i=t;for(;n>Qi;)n&Yi&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Yi;return r}(this,e,t)}div(e,t){return ss(e*os(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return os(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=(t=this.ORDER)%Xi===Zi?ds:t%ns===es?cs:t%is===rs?function(e){const t=ys(e),n=ls(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),a=(e+ts)/is;return(e,t)=>{let n=e.pow(t,a),o=e.mul(n,r);const u=e.mul(n,i),d=e.mul(n,s),c=e.eql(e.sqr(o),t),l=e.eql(e.sqr(u),t);n=e.cmov(n,o,c),o=e.cmov(d,u,l);const p=e.eql(e.sqr(o),t),h=e.cmov(n,o,p);return us(e,h,t),h}}(t):ls(t)),this._sqrt(this,e);var t}toBytes(e){return this.isLE?$i(e,this.BYTES):qi(e,this.BYTES)}fromBytes(e,t=!1){Br(e);const{_lengths:n,BYTES:r,isLE:i,ORDER:s,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);const t=new Uint8Array(r);t.set(e,i?0:t.length-e.length),e=t}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let o=i?ji(e):Ui(e);if(a&&(o=ss(o,s)),!t&&!this.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o}invertBatch(e){return hs(this,e)}cmov(e,t,n){return n?t:e}}function ys(e,t={}){return new ms(e,t)}function bs(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function gs(e){const t=bs(e);return t+Math.ceil(t/2)}const vs=/* @__PURE__ */BigInt(0),ws=/* @__PURE__ */BigInt(1);function Ts(e,t){const n=t.negate();return e?n:t}function Es(e,t){const n=hs(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function xs(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ps(e,t){xs(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Ki(e),maxNumber:n,shiftBy:BigInt(e)}}function Ss(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:a}=n;let o=Number(e&i),u=e>>a;o>r&&(o-=s,u+=ws);const d=t*r;return{nextN:u,offset:d+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:d}}const As=new WeakMap,Cs=new WeakMap;function ks(e){return Cs.get(e)||1}function Is(e){if(e!==vs)throw new Error("invalid wNAF")}class Ds{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>vs;)t&ws&&(n=n.add(r)),r=r.double(),t>>=ws;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Ps(t,this.bits),i=[];let s=e,a=s;for(let e=0;e<n;e++){a=s,i.push(a);for(let e=1;e<r;e++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const s=Ps(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:a,offset:o,isZero:u,isNeg:d,isNegF:c,offsetF:l}=Ss(n,e,s);n=a,u?i=i.add(Ts(c,t[l])):r=r.add(Ts(d,t[o]))}return Is(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Ps(e,this.bits);for(let e=0;e<i.windows&&n!==vs;e++){const{nextN:s,offset:a,isZero:o,isNeg:u}=Ss(n,e,i);if(n=s,!o){const e=t[a];r=r.add(u?e.negate():e)}}return Is(n),r}getPrecomputes(e,t,n){let r=As.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),As.set(t,r))),r}cached(e,t,n){const r=ks(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=ks(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){xs(t,this.bits),Cs.set(e,t),As.delete(e)}hasCache(e){return 1!==ks(e)}}function Ms(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=ps.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",BYTES:"number",BITS:"number"});Hi(e,t)}(t),t}return ys(e,{isLE:n})}function Fs(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>vs))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Ms(t.p,n.Fp,r),s=Ms(t.n,n.Fn,r),a=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of a)if(!i.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:i,Fn:s}}function Rs(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}const _s=BigInt(0),Ls=BigInt(1),Ns=BigInt(2),Os=BigInt(8);function Bs(e,t={}){const n=Fs("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a}=s;Hi(t,{},{uvRatio:"function"});const o=Ns<<BigInt(8*i.BYTES)-Ls,u=e=>r.create(e),d=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:_s}}});if(!function(e,t,n,r){const i=e.sqr(n),s=e.sqr(r),a=e.add(e.mul(t.a,i),s),o=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(a,o)}(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function c(e,t,n=!1){return Gi("coordinate "+e,t,n?Ls:_s,o),t}function l(e){if(!(e instanceof f))throw new Error("EdwardsPoint expected")}const p=Wi((e,t)=>{const{X:n,Y:i,Z:s}=e,a=e.is0();null==t&&(t=a?Os:r.inv(s));const o=u(n*t),d=u(i*t),c=r.mul(s,t);if(a)return{x:_s,y:Ls};if(c!==Ls)throw new Error("invZ was invalid");return{x:o,y:d}}),h=Wi(e=>{const{a:t,d:n}=s;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:a,T:o}=e,d=u(r*r),c=u(i*i),l=u(a*a),p=u(l*l),h=u(d*t);if(u(l*u(h+c))!==u(p+u(n*u(d*c))))throw new Error("bad point: equation left != right (1)");if(u(r*i)!==u(a*o))throw new Error("bad point: equation left != right (2)");return!0});class f{static BASE=new f(s.Gx,s.Gy,Ls,u(s.Gx*s.Gy));static ZERO=new f(_s,Ls,Ls,_s);static Fp=r;static Fn=i;X;Y;Z;T;constructor(e,t,n,r){this.X=c("x",e),this.Y=c("y",t),this.Z=c("z",n,!0),this.T=c("t",r),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){if(e instanceof f)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return c("x",t),c("y",n),new f(t,n,Ls,u(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:a}=s;e=zi(Br(e,n,"point")),Li(t,"zip215");const c=zi(e),l=e[n-1];c[n-1]=-129&l;const p=ji(c);Gi("point.y",p,_s,t?o:r.ORDER);const h=u(p*p),m=u(h-Ls),y=u(a*h-i);let{isValid:b,value:g}=d(m,y);if(!b)throw new Error("bad point: invalid y coordinate");const v=(g&Ls)===Ls,w=!!(128&l);if(!t&&g===_s&&w)throw new Error("bad point: x=0 and x_0=1");return w!==v&&(g=u(-g)),f.fromAffine({x:g,y:p})}static fromHex(e,t=!1){return f.fromBytes(Wr(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return m.createCache(this,e),t||this.multiply(Ns),this}assertValidity(){h(this)}equals(e){l(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:s,Z:a}=e,o=u(t*a),d=u(i*r),c=u(n*a),p=u(s*r);return o===d&&c===p}is0(){return this.equals(f.ZERO)}negate(){return new f(u(-this.X),this.Y,this.Z,u(-this.T))}double(){const{a:e}=s,{X:t,Y:n,Z:r}=this,i=u(t*t),a=u(n*n),o=u(Ns*u(r*r)),d=u(e*i),c=t+n,l=u(u(c*c)-i-a),p=d+a,h=p-o,m=d-a,y=u(l*h),b=u(p*m),g=u(l*m),v=u(h*p);return new f(y,b,v,g)}add(e){l(e);const{a:t,d:n}=s,{X:r,Y:i,Z:a,T:o}=this,{X:d,Y:c,Z:p,T:h}=e,m=u(r*d),y=u(i*c),b=u(o*n*h),g=u(a*p),v=u((r+i)*(d+c)-m-y),w=g-b,T=g+b,E=u(y-t*m),x=u(v*w),P=u(T*E),S=u(v*E),A=u(w*T);return new f(x,P,A,S)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=m.cached(this,e,e=>Es(f,e));return Es(f,[t,n])[0]}multiplyUnsafe(e,t=f.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===_s?f.ZERO:this.is0()||e===Ls?this:m.unsafe(this,e,e=>Es(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(e){return p(this,e)}clearCofactor(){return a===Ls?this:this.multiplyUnsafe(a)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Ls?128:0,n}toHex(){return Kr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const m=new Ds(f,i.BITS);return f.BASE.precompute(8),f}const Us=BigInt(1),js=BigInt(2),qs=BigInt(5),$s=BigInt(8),zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Vs=/* @__PURE__ */(()=>({p:zs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:$s,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Gs(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ks=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Hs=/* @__PURE__ */Bs(Vs,{uvRatio:function(e,t){const n=zs,r=ss(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=zs,a=e*e%s*e%s,o=as(a,js,s)*a%s,u=as(o,Us,s)*e%s,d=as(u,qs,s)*u%s,c=as(d,t,s)*d%s,l=as(c,n,s)*c%s,p=as(l,r,s)*l%s,h=as(p,i,s)*p%s,f=as(h,i,s)*p%s,m=as(f,t,s)*d%s;return{pow_p_5_8:as(m,js,s)*e%s,b2:a}}(e*ss(r*r*t,n)).pow_p_5_8;let s=ss(e*r*i,n);const a=ss(t*s*s,n),o=s,u=ss(s*Ks,n),d=a===e,c=a===ss(-e,n),l=a===ss(-e*Ks,n);return d&&(s=o),(c||l)&&(s=u),(ss(s,n)&Yi)===Yi&&(s=ss(-s,n)),{isValid:d||c,value:s}}});function Ws(e){return function(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Hi(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:a}=e,o=n.randomBytes||Jr,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Li(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function c(e){return a.create(ji(e))}function l(e){const{head:n,prefix:r,scalar:s}=function(e){const n=y.secretKey;Br(e,y.secretKey,"secretKey");const r=Br(t(e),2*n,"hashedSecretKey"),i=u(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:c(i)}}(e),a=i.multiply(s),o=a.toBytes();return{head:n,prefix:r,scalar:s,point:a,pointBytes:o}}function p(e){return l(e).pointBytes}function h(e=Uint8Array.of(),...n){const i=Qr(...n);return c(t(d(i,Br(e,void 0,"context"),!!r)))}const f={zip215:!0},m=s.BYTES,y={secretKey:m,publicKey:m,signature:2*m,seed:m};function b(e=o(y.seed)){return Br(e,y.seed,"seed")}const g={getExtendedPublicKey:l,randomSecretKey:b,isValidSecretKey:function(e){return Nr(e)&&e.length===a.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=y.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const a=i?s.div(Ls+n,Ls-n):s.div(n-Ls,n+Ls);return s.toBytes(a)},toMontgomerySecret(e){const n=y.secretKey;Br(e,n);const r=t(e.subarray(0,n));return u(r).subarray(0,n)}};return Object.freeze({keygen:Rs(b,p),getPublicKey:p,sign:function(e,t,n={}){e=Br(e,void 0,"message"),r&&(e=r(e));const{prefix:s,scalar:o,pointBytes:u}=l(t),d=h(n.context,s,e),c=i.multiply(d).toBytes(),p=h(n.context,c,u,e),f=a.create(d+p*o);if(!a.isValid(f))throw new Error("sign failed: invalid s");return Br(Qr(c,a.toBytes(f)),y.signature,"result")},verify:function(t,n,s,a=f){const{context:o,zip215:u}=a,d=y.signature;t=Br(t,d,"signature"),n=Br(n,void 0,"message"),s=Br(s,y.publicKey,"publicKey"),void 0!==u&&Li(u,"zip215"),r&&(n=r(n));const c=d/2,l=t.subarray(0,c),p=ji(t.subarray(c,d));let m,b,g;try{m=e.fromBytes(s,u),b=e.fromBytes(l,u),g=i.multiplyUnsafe(p)}catch(e){return!1}if(!u&&m.isSmallOrder())return!1;const v=h(o,b.toBytes(),m.toBytes(),n);return b.add(m.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()},utils:g,Point:e,lengths:y})}(Hs,Fi,Object.assign({adjustScalarBytes:Gs},e))}const Qs=/* @__PURE__ */Ws({});Error;class Ys extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Js extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var Zs={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Js("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let Xs;const ea=(async()=>{try{return await Zs.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function ta(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class na{type="Ed25519";raw;constructor(e){this.raw=sa(e,32)}toMultihash(){return _n(Fo(this))}toCID(){return kn.createV1(114,this.toMultihash())}toString(){return Vt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();const r=async function(e,t,n){return null==Xs&&(Xs=await ea),Xs?async function(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await Zs.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Zs.get().subtle.verify({name:"Ed25519"},r,t,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,n):function(e,t,n){return Qs.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}(e,t,n)}(this.raw,t,e);return ta(r)?r.then(e=>(n?.signal?.throwIfAborted(),e)):r}}class ra{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=sa(e,64),this.publicKey=new na(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const n=async function(e,t){return null==Xs&&(Xs=await ea),Xs?async function(e,t){let n;n=64===e.length?e.subarray(0,32):e;const r={crv:"Ed25519",kty:"OKP",x:mr(e.subarray(32),"base64url"),d:mr(n,"base64url"),ext:!0,key_ops:["sign"]},i=await Zs.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await Zs.get().subtle.sign({name:"Ed25519"},i,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(s,0,s.byteLength)}(e,t):function(e,t){const n=e.subarray(0,32);return Qs.sign(t instanceof Uint8Array?t:t.subarray(),n)}(e,t)}(this.raw,e);return ta(n)?n.then(e=>(t?.signal?.throwIfAborted(),e)):(t?.signal?.throwIfAborted(),n)}}function ia(e){return e=sa(e,32),new na(e)}function sa(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new We(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const aa=Math.pow(2,7),oa=Math.pow(2,14),ua=Math.pow(2,21),da=Math.pow(2,28),ca=Math.pow(2,35),la=Math.pow(2,42),pa=Math.pow(2,49),ha=128,fa=127;function ma(e){if(e<aa)return 1;if(e<oa)return 2;if(e<ua)return 3;if(e<da)return 4;if(e<ca)return 5;if(e<la)return 6;if(e<pa)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ya(e,t,n=0){switch(ma(e)){case 8:t[n++]=255&e|ha,e/=128;case 7:t[n++]=255&e|ha,e/=128;case 6:t[n++]=255&e|ha,e/=128;case 5:t[n++]=255&e|ha,e/=128;case 4:t[n++]=255&e|ha,e>>>=7;case 3:t[n++]=255&e|ha,e>>>=7;case 2:t[n++]=255&e|ha,e>>>=7;case 1:t[n++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function ba(e,t){let n=e[t],r=0;if(r+=n&fa,n<ha)return r;if(n=e[t+1],r+=(n&fa)<<7,n<ha)return r;if(n=e[t+2],r+=(n&fa)<<14,n<ha)return r;if(n=e[t+3],r+=(n&fa)<<21,n<ha)return r;if(n=e[t+4],r+=(n&fa)*da,n<ha)return r;if(n=e[t+5],r+=(n&fa)*ca,n<ha)return r;if(n=e[t+6],r+=(n&fa)*la,n<ha)return r;if(n=e[t+7],r+=(n&fa)*pa,n<ha)return r;throw new RangeError("Could not decode varint")}function ga(e,t,n=0){return null==t&&(t=On(ma(e))),t instanceof Uint8Array?ya(e,t,n):function(e,t,n=0){switch(ma(e)){case 8:t.set(n++,255&e|ha),e/=128;case 7:t.set(n++,255&e|ha),e/=128;case 6:t.set(n++,255&e|ha),e/=128;case 5:t.set(n++,255&e|ha),e/=128;case 4:t.set(n++,255&e|ha),e>>>=7;case 3:t.set(n++,255&e|ha),e>>>=7;case 2:t.set(n++,255&e|ha),e>>>=7;case 1:t.set(n++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,n)}function va(e,t=0){return e instanceof Uint8Array?ba(e,t):function(e,t){let n=e.get(t),r=0;if(r+=n&fa,n<ha)return r;if(n=e.get(t+1),r+=(n&fa)<<7,n<ha)return r;if(n=e.get(t+2),r+=(n&fa)<<14,n<ha)return r;if(n=e.get(t+3),r+=(n&fa)<<21,n<ha)return r;if(n=e.get(t+4),r+=(n&fa)*da,n<ha)return r;if(n=e.get(t+5),r+=(n&fa)*ca,n<ha)return r;if(n=e.get(t+6),r+=(n&fa)*la,n<ha)return r;if(n=e.get(t+7),r+=(n&fa)*pa,n<ha)return r;throw new RangeError("Could not decode varint")}(e,t)}const wa=new Float32Array([-0]),Ta=new Uint8Array(wa.buffer);function Ea(e,t,n){wa[0]=e,t[n]=Ta[0],t[n+1]=Ta[1],t[n+2]=Ta[2],t[n+3]=Ta[3]}const xa=new Float64Array([-0]),Pa=new Uint8Array(xa.buffer);function Sa(e,t,n){xa[0]=e,t[n]=Pa[0],t[n+1]=Pa[1],t[n+2]=Pa[2],t[n+3]=Pa[3],t[n+4]=Pa[4],t[n+5]=Pa[5],t[n+6]=Pa[6],t[n+7]=Pa[7]}const Aa=BigInt(Number.MAX_SAFE_INTEGER),Ca=BigInt(Number.MIN_SAFE_INTEGER);class ka{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(0n===e)return Ia;if(e<Aa&&e>Ca)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let n=e>>32n,r=e-(n<<32n);return t&&(n=0n|~n,r=0n|~r,++r>Da&&(r=0n,++n>Da&&(n=0n))),new ka(Number(r),Number(n))}static fromNumber(e){if(0===e)return Ia;const t=e<0;t&&(e=-e);let n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new ka(n,r)}static from(e){return"number"==typeof e?ka.fromNumber(e):"bigint"==typeof e?ka.fromBigInt(e):"string"==typeof e?ka.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new ka(e.low>>>0,e.high>>>0):Ia}}const Ia=new ka(0,0);Ia.toBigInt=function(){return 0n},Ia.zzEncode=Ia.zzDecode=function(){return this},Ia.length=function(){return 1};const Da=4294967296n;function Ma(e,t,n){const r=n;let i,s;for(let r=0;r<e.length;++r)i=e.charCodeAt(r),i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-r}function Fa(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Ra(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class _a{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Fa(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Fa(this,4);return Ra(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Fa(this,4);return 0|Ra(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Fa(this,4);const e=(Ta[0]=(t=this.buf)[n=this.pos],Ta[1]=t[n+1],Ta[2]=t[n+2],Ta[3]=t[n+3],wa[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Fa(this,4);const e=(Pa[0]=(t=this.buf)[n=this.pos],Pa[1]=t[n+1],Pa[2]=t[n+2],Pa[3]=t[n+3],Pa[4]=t[n+4],Pa[5]=t[n+5],Pa[6]=t[n+6],Pa[7]=t[n+7],xa[0]);var t,n;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Fa(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){const e=this.bytes();return function(e,t,n){if(n-t<1)return"";let r;const i=[];let s,a=0;for(;t<n;)s=e[t++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=r?(a>0&&r.push(String.fromCharCode.apply(String,i.slice(0,a))),r.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Fa(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Fa(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new ka(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Fa(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Fa(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Fa(this,8);const e=Ra(this.buf,this.pos+=4),t=Ra(this.buf,this.pos+=4);return new ka(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=ba(this.buf,this.pos);return this.pos+=ma(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function La(e){return new _a(e instanceof Uint8Array?e:e.subarray())}function Na(e,t,n){const r=La(e);return t.decode(r,void 0,n)}class Oa{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Ba(){}class Ua{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const ja=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return On(r);n+r>e&&(t=On(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class qa{len;head;tail;states;constructor(){this.len=0,this.head=new Oa(Ba,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Oa(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Va((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ga,10,ka.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=ka.fromBigInt(e);return this._push(Ga,t.length(),t)}uint64Number(e){return this._push(ya,ma(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=ka.fromBigInt(e).zzEncode();return this._push(Ga,t.length(),t)}sint64Number(e){const t=ka.fromNumber(e).zzEncode();return this._push(Ga,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push($a,1,e?1:0)}fixed32(e){return this._push(Ka,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=ka.fromBigInt(e);return this._push(Ka,4,t.lo)._push(Ka,4,t.hi)}fixed64Number(e){const t=ka.fromNumber(e);return this._push(Ka,4,t.lo)._push(Ka,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ea,4,e)}double(e){return this._push(Sa,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push($a,1,0):this.uint32(t)._push(Ha,t,e)}string(e){const t=function(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(Ma,t,e):this._push($a,1,0)}fork(){return this.states=new Ua(this),this.head=this.tail=new Oa(Ba,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Oa(Ba,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next;const t=(n=this.len,null!=globalThis.Buffer?On(n):ja(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function $a(e,t,n){t[n]=255&e}function za(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class Va extends Oa{next;constructor(e,t){super(za,e,t),this.next=void 0}}function Ga(e,t,n){for(;0!==e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function Ka(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function Ha(e,t,n){t.set(e,n)}function Wa(e,t,n){t.set(e,n)}function Qa(e,t,n){e.length<40?Ma(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(fr(e),n)}function Ya(e,t){const n=new qa;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*Ja(e,t,n){const r=La(e);yield*t.stream(r,void 0,"$",n)}function Za(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function Xa(e,t,n){return Za("message",2,e,t,n)}var eo,to,no,ro;function io(e){if(isNaN(e)||e<=0)throw new We("random bytes length must be a Number bigger than 0");return Jr(e)}null!=globalThis.Buffer&&(qa.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Wa,t,e),this},qa.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Qa,t,e),this}),function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(eo||(eo={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(to||(to={})),function(e){e.codec=()=>function(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Za("enum",0,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())},function*(e){const n=e.int32();yield t(n)})}(to)}(eo||(eo={})),function(e){let t;e.codec=()=>(null==t&&(t=Xa((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eo.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.Type=eo.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.Type`,value:eo.codec().decode(e)};break;case 2:yield{field:`${n}.Data`,value:e.bytes()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Ya(t,e.codec())},e.decode=function(t,n){return Na(t,e.codec(),n)},e.stream=function(t,n){return Ja(t,e.codec(),n)}}(no||(no={})),function(e){let t;e.codec=()=>(null==t&&(t=Xa((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),eo.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.Type=eo.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.Type`,value:eo.codec().decode(e)};break;case 2:yield{field:`${n}.Data`,value:e.bytes()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Ya(t,e.codec())},e.decode=function(t,n){return Na(t,e.codec(),n)},e.stream=function(t,n){return Ja(t,e.codec(),n)}}(ro||(ro={}));class so{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new We("JWK was missing components");return Ar([ao,Sr(Ar([Pr(fr(e.n,"base64url")),Pr(fr(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return kn.createV1(114,this._multihash)}toString(){return Vt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}verify(e,t,n){return async function(e,t,n,r){const i=await Zs.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Zs.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,t,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}(this.jwk,t,e,n)}}const ao=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class oo{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ur(e),Br(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),qr(r)}update(e){return jr(this),this.iHash.update(e),this}digestInto(e){jr(this),Br(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:s,outputLen:a}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const uo=(e,t,n)=>new oo(e,t).update(n).digest();uo.create=(e,t)=>new oo(e,t);const co=(e,t)=>(e+(e>=0?t:-t)/bo)/t;function lo(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function po(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Li(n.lowS,"lowS"),Li(n.prehash,"prehash"),void 0!==n.format&&lo(n.format),n}class ho extends Error{constructor(e=""){super(e)}}const fo={Err:ho,_tlv:{encode:(e,t)=>{const{Err:n}=fo;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,i=Oi(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Oi(i.length/2|128):"";return Oi(e)+s+i+t},decode(e,t){const{Err:n}=fo;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const i=t[r++];let s=0;if(128&i){const e=127&i;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const a=t.subarray(r,r+e);if(a.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===a[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of a)s=s<<8|e;if(r+=e,s<128)throw new n("tlv.decode(long): not minimal encoding")}else s=i;const a=t.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+s)}}},_int:{encode(e){const{Err:t}=fo;if(e<mo)throw new t("integer: negative integers are not allowed");let n=Oi(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=fo;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Ui(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=fo,i=Br(e,void 0,"signature"),{v:s,l:a}=r.decode(48,i);if(a.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:u}=r.decode(2,s),{v:d,l:c}=r.decode(2,u);if(c.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(o),s:n.decode(d)}},hexFromSig(e){const{_tlv:t,_int:n}=fo,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s));return t.encode(48,r+i)}},mo=BigInt(0),yo=BigInt(1),bo=BigInt(2),go=BigInt(3),vo=BigInt(4);function wo(e,t={}){const n=Fs("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a,n:o}=s;Hi(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:u}=t;if(u&&(!r.is0(s.a)||"bigint"!=typeof u.beta||!Array.isArray(u.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const d=Eo(r,i);function c(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const l=t.toBytes||function(e,t,n){const{x:i,y:s}=t.toAffine(),a=r.toBytes(i);return Li(n,"isCompressed"),n?(c(),Qr(To(!r.isOdd(s)),a)):Qr(Uint8Array.of(4),a,r.toBytes(s))},p=t.fromBytes||function(e){Br(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=d,i=e.length,s=e[0],a=e.subarray(1);if(i!==t||2!==s&&3!==s){if(i===n&&4===s){const e=r.BYTES,t=r.fromBytes(a.subarray(0,e)),n=r.fromBytes(a.subarray(e,2*e));if(!f(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(a);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=h(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}return c(),!(1&~s)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function h(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,s.a)),s.b)}function f(e,t){const n=r.sqr(t),i=h(e);return r.eql(n,i)}if(!f(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const m=r.mul(r.pow(s.a,go),vo),y=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(m,y)))throw new Error("bad curve params: a or b");function b(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function g(e){if(!(e instanceof x))throw new Error("Weierstrass Point expected")}function v(e){if(!u||!u.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[s,a]]=t,o=co(a*e,n),u=co(-i*e,n);let d=e-o*r-u*s,c=-o*i-u*a;const l=d<mo,p=c<mo;l&&(d=-d),p&&(c=-c);const h=Ki(Math.ceil(function(e){let t;for(t=0;e>Ri;e>>=_i,t+=1);return t}(n)/2))+yo;if(d<mo||d>=h||c<mo||c>=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:d,k2neg:p,k2:c}}(e,u.basises,i.ORDER)}const w=Wi((e,t)=>{const{X:n,Y:i,Z:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const a=e.is0();null==t&&(t=a?r.ONE:r.inv(s));const o=r.mul(n,t),u=r.mul(i,t),d=r.mul(s,t);if(a)return{x:r.ZERO,y:r.ZERO};if(!r.eql(d,r.ONE))throw new Error("invZ was invalid");return{x:o,y:u}}),T=Wi(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw new Error("bad point: x or y not field elements");if(!f(n,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(e,t,n,i,s){return n=new x(r.mul(n.X,e),n.Y,n.Z),t=Ts(i,t),n=Ts(s,n),t.add(n)}class x{static BASE=new x(s.Gx,s.Gy,r.ONE);static ZERO=new x(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=i;X;Y;Z;constructor(e,t,n){this.X=b("x",e),this.Y=b("y",t,!0),this.Z=b("z",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof x)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?x.ZERO:new x(t,n,r.ONE)}static fromBytes(e){const t=x.fromAffine(p(Br(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return x.fromBytes(Wr(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return S.createCache(this,e),t||this.multiply(go),this}assertValidity(){T(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){g(e);const{X:t,Y:n,Z:i}=this,{X:s,Y:a,Z:o}=e,u=r.eql(r.mul(t,o),r.mul(s,i)),d=r.eql(r.mul(n,o),r.mul(a,i));return u&&d}negate(){return new x(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,go),{X:i,Y:a,Z:o}=this;let u=r.ZERO,d=r.ZERO,c=r.ZERO,l=r.mul(i,i),p=r.mul(a,a),h=r.mul(o,o),f=r.mul(i,a);return f=r.add(f,f),c=r.mul(i,o),c=r.add(c,c),u=r.mul(e,c),d=r.mul(n,h),d=r.add(u,d),u=r.sub(p,d),d=r.add(p,d),d=r.mul(u,d),u=r.mul(f,u),c=r.mul(n,c),h=r.mul(e,h),f=r.sub(l,h),f=r.mul(e,f),f=r.add(f,c),c=r.add(l,l),l=r.add(c,l),l=r.add(l,h),l=r.mul(l,f),d=r.add(d,l),h=r.mul(a,o),h=r.add(h,h),l=r.mul(h,f),u=r.sub(u,l),c=r.mul(h,p),c=r.add(c,c),c=r.add(c,c),new x(u,d,c)}add(e){g(e);const{X:t,Y:n,Z:i}=this,{X:a,Y:o,Z:u}=e;let d=r.ZERO,c=r.ZERO,l=r.ZERO;const p=s.a,h=r.mul(s.b,go);let f=r.mul(t,a),m=r.mul(n,o),y=r.mul(i,u),b=r.add(t,n),v=r.add(a,o);b=r.mul(b,v),v=r.add(f,m),b=r.sub(b,v),v=r.add(t,i);let w=r.add(a,u);return v=r.mul(v,w),w=r.add(f,y),v=r.sub(v,w),w=r.add(n,i),d=r.add(o,u),w=r.mul(w,d),d=r.add(m,y),w=r.sub(w,d),l=r.mul(p,v),d=r.mul(h,y),l=r.add(d,l),d=r.sub(m,l),l=r.add(m,l),c=r.mul(d,l),m=r.add(f,f),m=r.add(m,f),y=r.mul(p,y),v=r.mul(h,v),m=r.add(m,y),y=r.sub(f,y),y=r.mul(p,y),v=r.add(v,y),f=r.mul(m,v),c=r.add(c,f),f=r.mul(w,v),d=r.mul(b,d),d=r.sub(d,f),f=r.mul(b,m),l=r.mul(w,l),l=r.add(l,f),new x(d,c,l)}subtract(e){return this.add(e.negate())}is0(){return this.equals(x.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,s;const a=e=>S.cached(this,e,e=>Es(x,e));if(n){const{k1neg:t,k1:i,k2neg:o,k2:u}=v(e),{p:d,f:c}=a(i),{p:l,f:p}=a(u);s=c.add(p),r=E(n.beta,d,l,t,o)}else{const{p:t,f:n}=a(e);r=t,s=n}return Es(x,[r,s])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===mo||r.is0())return x.ZERO;if(e===yo)return r;if(S.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:s,k2:a}=v(e),{p1:o,p2:u}=function(e,t,n,r){let i=t,s=e.ZERO,a=e.ZERO;for(;n>vs||r>vs;)n&ws&&(s=s.add(i)),r&ws&&(a=a.add(i)),i=i.double(),n>>=ws,r>>=ws;return{p1:s,p2:a}}(x,r,i,a);return E(n.beta,o,u,t,s)}return S.unsafe(r,e)}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return a===yo||(e?e(x,this):S.unsafe(this,o).is0())}clearCofactor(){const{clearCofactor:e}=t;return a===yo?this:e?e(x,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return Li(e,"isCompressed"),this.assertValidity(),l(x,this,e)}toHex(e=!0){return Kr(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const P=i.BITS,S=new Ds(x,t.endo?Math.ceil(P/2):P);return x.BASE.precompute(8),x}function To(e){return Uint8Array.of(e?2:3)}function Eo(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function xo(e,t,n={}){Ur(t),Hi(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=(n=Object.assign({},n)).randomBytes||Jr,i=n.hmac||((e,n)=>uo(t,e,n)),{Fp:s,Fn:a}=e,{ORDER:o,BITS:u}=a,{keygen:d,getPublicKey:c,getSharedSecret:l,utils:p,lengths:h}=function(e,t={}){const{Fn:n}=e,r=t.randomBytes||Jr,i=Object.assign(Eo(e.Fp,n),{seed:gs(n.ORDER)});function s(e=r(i.seed)){return function(e,t,n=!1){Br(e);const r=e.length,i=bs(t),s=gs(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const a=ss(n?ji(e):Ui(e),t-Yi)+Yi;return n?$i(a,i):qi(a,i)}(Br(e,i.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(n.fromBytes(t)).toBytes(r)}function o(e){const{secretKey:t,publicKey:r,publicKeyUncompressed:s}=i;if(!Nr(e))return;if("_lengths"in n&&n._lengths||t===r)return;const a=Br(e,void 0,"key").length;return a===r||a===s}const u={isValidSecretKey:function(e){try{const t=n.fromBytes(e);return n.isValidNot0(t)}catch(e){return!1}},isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:s}=i;try{const i=t.length;return!(!0===n&&i!==r||!1===n&&i!==s||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s},d=Rs(s,a);return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,i=!0){if(!0===o(t))throw new Error("first arg must be private key");if(!1===o(r))throw new Error("second arg must be public key");const s=n.fromBytes(t);return e.fromBytes(r).multiply(s).toBytes(i)},keygen:d,Point:e,utils:u,lengths:i})}(e,n),f={prehash:!0,lowS:"boolean"!=typeof n.lowS||n.lowS,format:"compact",extraEntropy:!1},m=o*bo<s.ORDER;function y(e){return e>o>>yo}function b(e,t){if(!a.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function g(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function v(e,t){lo(t);const n=h.signature;return Br(e,"compact"===t?n:"recovered"===t?n+1:void 0)}class w{r;s;recovery;constructor(e,t,n){if(this.r=b("r",e),this.s=b("s",t),null!=n){if(g(),![0,1,2,3].includes(n))throw new Error("invalid recovery id");this.recovery=n}Object.freeze(this)}static fromBytes(e,t=f.format){let n;if(v(e,t),"der"===t){const{r:t,s:n}=fo.toSig(Br(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=h.signature/2,i=e.subarray(0,r),s=e.subarray(r,2*r);return new w(a.fromBytes(i),a.fromBytes(s),n)}static fromHex(e,t){return this.fromBytes(Wr(e),t)}assertRecovery(){const{recovery:e}=this;if(null==e)throw new Error("invalid recovery id: must be present");return e}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const{r:n,s:r}=this,i=this.assertRecovery(),u=2===i||3===i?n+o:n;if(!s.isValid(u))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const d=s.toBytes(u),c=e.fromBytes(Qr(To(!(1&i)),d)),l=a.inv(u),p=E(Br(t,void 0,"msgHash")),h=a.create(-p*l),f=a.create(r*l),m=e.BASE.multiplyUnsafe(h).add(c.multiplyUnsafe(f));if(m.is0())throw new Error("invalid recovery: point at infinify");return m.assertValidity(),m}hasHighS(){return y(this.s)}toBytes(e=f.format){if(lo(e),"der"===e)return Wr(fo.hexFromSig(this));const{r:t,s:n}=this,r=a.toBytes(t),i=a.toBytes(n);return"recovered"===e?(g(),Qr(Uint8Array.of(this.assertRecovery()),r,i)):Qr(r,i)}toHex(e){return Kr(this.toBytes(e))}}const T=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Ui(e),n=8*e.length-u;return n>0?t>>BigInt(n):t},E=n.bits2int_modN||function(e){return a.create(T(e))},x=Ki(u);function P(e){return Gi("num < 2^"+u,e,mo,x),a.toBytes(e)}function S(e,n){return Br(e,void 0,"message"),n?Br(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:d,getPublicKey:c,getSharedSecret:l,utils:p,lengths:h,Point:e,sign:function(n,s,o={}){const{seed:u,k2sig:d}=function(t,n,i){const{lowS:s,prehash:o,extraEntropy:u}=po(i,f);t=S(t,o);const d=E(t),c=a.fromBytes(n);if(!a.isValidNot0(c))throw new Error("invalid private key");const l=[P(c),P(d)];if(null!=u&&!1!==u){const e=!0===u?r(h.secretKey):u;l.push(Br(e,void 0,"extraEntropy"))}const p=Qr(...l),b=d;return{seed:p,k2sig:function(t){const n=T(t);if(!a.isValidNot0(n))return;const r=a.inv(n),i=e.BASE.multiply(n).toAffine(),o=a.create(i.x);if(o===mo)return;const u=a.create(r*a.create(b+o*c));if(u===mo)return;let d=(i.x===o?0:2)|Number(i.y&yo),l=u;return s&&y(u)&&(l=a.neg(u),d^=1),new w(o,l,m?void 0:d)}}}(n,s,o),c=function(e,t,n){if(Or(e,"hashLen"),Or(t,"qByteLen"),"function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),i=Uint8Array.of(),s=Uint8Array.of(0),a=Uint8Array.of(1);let o=r(e),u=r(e),d=0;const c=()=>{o.fill(1),u.fill(0),d=0},l=(...e)=>n(u,Qr(o,...e)),p=(e=i)=>{u=l(s,e),o=l(),0!==e.length&&(u=l(a,e),o=l())},h=()=>{if(d++>=1e3)throw new Error("drbg: tried max amount of iterations");let e=0;const n=[];for(;e<t;){o=l();const t=o.slice();n.push(t),e+=o.length}return Qr(...n)};return(e,t)=>{let n;for(c(),p(e);!(n=t(h()));)p();return c(),n}}(t.outputLen,a.BYTES,i);return c(u,d).toBytes(o.format)},verify:function(t,n,r,i={}){const{lowS:s,prehash:o,format:u}=po(i,f);if(r=Br(r,void 0,"publicKey"),n=S(n,o),!Nr(t))throw new Error("verify expects Uint8Array signature"+(t instanceof w?", use sig.toBytes()":""));v(t,u);try{const i=w.fromBytes(t,u),o=e.fromBytes(r);if(s&&i.hasHighS())return!1;const{r:d,s:c}=i,l=E(n),p=a.inv(c),h=a.create(l*p),f=a.create(d*p),m=e.BASE.multiplyUnsafe(h).add(o.multiplyUnsafe(f));return!m.is0()&&a.create(m.x)===d}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=po(n,f);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}const Po={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},So={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ao=/* @__PURE__ */BigInt(2),Co=ys(Po.p,{sqrt:function(e){const t=Po.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),u=BigInt(88),d=e*e*e%t,c=d*d*e%t,l=as(c,n,t)*c%t,p=as(l,n,t)*c%t,h=as(p,Ao,t)*d%t,f=as(h,i,t)*h%t,m=as(f,s,t)*f%t,y=as(m,o,t)*m%t,b=as(y,u,t)*y%t,g=as(b,o,t)*m%t,v=as(g,n,t)*c%t,w=as(v,a,t)*f%t,T=as(w,r,t)*d%t,E=as(T,Ao,t);if(!Co.eql(Co.sqr(E),e))throw new Error("Cannot find square root");return E}}),ko=/* @__PURE__ */xo(/* @__PURE__ */wo(Po,{Fp:Co,endo:So}),Mi);class Io{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return ko.Point.fromBytes(e),e}catch(e){throw new Qe(String(e))}}(e),this.raw=function(e){return ko.Point.fromBytes(e).toBytes()}(this._key)}toMultihash(){return _n(Fo(this))}toCID(){return kn.createV1(114,this.toMultihash())}toString(){return Vt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Ln(this.raw,e.raw)}verify(e,t,n){return function(e,t,n,r){const i=ur.digest(n instanceof Uint8Array?n:n.subarray());if(ta(i))return i.then(({digest:n})=>(r?.signal?.throwIfAborted(),ko.verify(t,n,e,{prehash:!1,format:"der"}))).catch(e=>{if("AbortError"===e.name)throw e;throw new Ys(String(e))});try{return r?.signal?.throwIfAborted(),ko.verify(t,i.digest,e,{prehash:!1,format:"der"})}catch(e){throw new Ys(String(e))}}(this._key,t,e,n)}}function Do(e){return new Io(e)}function Mo(e,t){const{Type:n,Data:r}=no.decode(e),i=r??new Uint8Array;switch(n){case eo.RSA:return function(e,t){if(e.byteLength>=1062)throw new Qe("Key size is too large");return function(e,t,n){const r=function(e){const t=wr(e[1],{offset:0});return{kty:"RSA",n:mr(t[0],"base64url"),e:mr(t[1],"base64url")}}(e);return null==n&&(n=En(18,Mi(no.encode({Type:eo.RSA,Data:t})))),new so(r,n)}(wr(e,{offset:0}),e,t)}(i,t);case eo.Ed25519:return ia(i);case eo.secp256k1:return Do(i);case eo.ECDSA:return Rr(i);default:throw new bt}}function Fo(e){return no.encode({Type:eo[e.type],Data:e.raw})}const Ro=Symbol.for("nodejs.util.inspect.custom");class _o{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[xt]=!0;toString(){return null==this.string&&(this.string=Vt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return kn.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Ln(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Ln(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ro](){return`PeerId(${this.toString()})`}}class Lo extends _o{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class No extends _o{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Oo extends _o{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class Bo{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=_n(fr(this.url))}[Ro](){return`PeerId(${this.url})`}[xt]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return kn.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=mr(e)),e.toString()===this.toString())}}function Uo(e,t){let n;if("1"===e.charAt(0)||"Q"===e.charAt(0))n=xn(Vt.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return $o(kn.parse(e));if(null==t)throw new We('Please pass a multibase decoder for strings that do not start with "1" or "Q"');n=xn(t.decode(e))}return qo(n)}function jo(e){if("Ed25519"===e.type)return new No({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Oo({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Lo({multihash:e.toCID().multihash,publicKey:e});throw new bt}function qo(e){if(function(e){return e.code===ur.code}(e))return new Lo({multihash:e});if(function(e){return 0===e.code}(e))try{const t=function(e){const{Type:t,Data:n}=no.decode(e.digest),r=n??new Uint8Array;switch(t){case eo.Ed25519:return ia(r);case eo.secp256k1:return Do(r);case eo.ECDSA:return Rr(r);default:throw new bt}}(e);if("Ed25519"===t.type)return new No({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Oo({multihash:e,publicKey:t})}catch(t){const n=mr(e.digest);return new Bo(new URL(n))}throw new at("Supplied PeerID Multihash is invalid")}function $o(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new st("Supplied PeerID CID is invalid");if(2336===e.code){const t=mr(e.multihash.digest);return new Bo(new URL(t))}return qo(e.multihash)}class zo extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Vo extends Error{static name="ValidationError";name="ValidationError"}class Go extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Ko extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const Ho=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,n=e();return void 0===n&&(this.index=t),n}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{const t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return n()})}readNumber(e,t,n,r){return this.readAtomically(()=>{let i=0,s=0;const a=this.peekChar();if(void 0===a)return;const o="0"===a,u=2**(8*r)-1;for(;;){const n=this.readAtomically(()=>{const t=this.readChar();if(void 0===t)return;const n=Number.parseInt(t,e);return Number.isNaN(n)?void 0:n});if(void 0===n)break;if(i*=e,i+=n,i>u)return;if(s+=1,void 0!==t&&s>t)return}return 0===s||!n&&o&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(void 0===n)return;e[t]=n}return e})}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const n=2*t;if(t<e.length-3){const r=this.readSeparator(":",t,()=>this.readIPv4Addr());if(void 0!==r)return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],[n+4,!0]}const r=this.readSeparator(":",t,()=>this.readNumber(16,4,!0,2));if(void 0===r)return[n,!1];e[n]=r>>8,e[n+1]=255&r}return[e.length,!1]};return this.readAtomically(()=>{const t=new Uint8Array(16),[n,r]=e(t);if(16===n)return t;if(r)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Wo(e){if(!(e.length>15))return Ho.new(e).parseWith(()=>Ho.readIPv4Addr())}function Qo(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Ho.new(e).parseWith(()=>Ho.readIPv6Addr())}function Yo(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const n=Ho.new(e).parseWith(()=>Ho.readIPAddr());return n?t&&4===n.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,n[0],n[1],n[2],n[3]]):n:void 0}function Jo(e){return Boolean(Wo(e))}function Zo(e){return Boolean(Qo(e))}const Xo=41,eu=421,tu=448,nu=449,ru=466,iu=281,su=290;function au(e){return t=>mr(t,e)}function ou(e){return t=>fr(t,e)}function uu(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function du(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function cu(e){const t=e.subarray(0,e.length-2),n=e.subarray(e.length-2);return`${mr(t,"base32")}:${uu(n)}`}const lu=function(e){e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach((e,n)=>{const r=parseInt(e,10);if(isNaN(r)||r<0||r>255)throw new zo("Invalid byte value in IP address");t[n]=r}),t},pu=Object.values(dr).map(e=>e.decoder),hu=function(){let e=pu[0].or(pu[1]);return pu.slice(2).forEach(t=>e=e.or(t)),e}(),fu=function(...e){return t=>{for(const n of e)n(t)}}(function(e){if(parseInt(e).toString()!==e)throw new Vo("Value must be an integer")},function(e){if(e<0)throw new Vo("Value must be a positive integer, or zero")},e=>{if(e>65535)throw new Vo("Value must be smaller than or equal to 65535")}),mu=-1,yu=new class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new Ko(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){const t=this.protocolsByCode.get(e);null!=t&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(e=>{this.protocolsByName.delete(e)}))}},bu=[{code:4,name:"ip4",size:32,valueToBytes:lu,bytesToValue:function(e){if(4!==e.byteLength)throw new zo("IPv4 address was incorrect length");const t=[];for(let n=0;n<e.byteLength;n++)t.push(e[n]);return t.join(".")},validate:e=>{if(!Jo(e))throw new Vo(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:du,bytesToValue:uu,validate:fu},{code:273,name:"udp",size:16,valueToBytes:du,bytesToValue:uu,validate:fu},{code:33,name:"dccp",size:16,valueToBytes:du,bytesToValue:uu,validate:fu},{code:Xo,name:"ip6",size:128,valueToBytes:function(e){let t=0;const n=(e=e.toString().trim()).split(":",8);let r;for(r=0;r<n.length;r++){let e;Jo(n[r])&&(e=lu(n[r]),n[r]=mr(e.subarray(0,2),"base16")),null!=e&&++r<8&&n.splice(r,0,mr(e.subarray(2,4),"base16"))}if(""===n[0])for(;n.length<8;)n.unshift("0");else if(""===n[n.length-1])for(;n.length<8;)n.push("0");else if(n.length<8){for(r=0;r<n.length&&""!==n[r];r++);const e=[r,1];for(r=9-n.length;r>0;r--)e.push("0");n.splice.apply(n,e)}const i=new Uint8Array(t+16);for(r=0;r<n.length;r++){""===n[r]&&(n[r]="0");const e=parseInt(n[r],16);if(isNaN(e)||e<0||e>65535)throw new zo("Invalid byte value in IP address");i[t++]=e>>8&255,i[t++]=255&e}return i},bytesToValue:function(e){if(16!==e.byteLength)throw new zo("IPv6 address was incorrect length");const t=[];for(let n=0;n<e.byteLength;n+=2){const r=e[n+1],i=`${e[n].toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`;t.push(i)}const n=t.join(":");try{const e=new URL(`http://[${n}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new zo(`Invalid IPv6 address "${n}"`)}},stringToValue:function(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new zo(`Invalid IPv6 address "${e}"`)}},validate:e=>{if(!Zo(e))throw new Vo(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:mu},{code:43,name:"ipcidr",size:8,bytesToValue:au("base10"),valueToBytes:ou("base10")},{code:53,name:"dns",size:mu},{code:54,name:"dns4",size:mu},{code:55,name:"dns6",size:mu},{code:56,name:"dnsaddr",size:mu},{code:132,name:"sctp",size:16,valueToBytes:du,bytesToValue:uu,validate:fu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mu,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:eu,name:"p2p",aliases:["ipfs"],size:mu,bytesToValue:au("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?ou("base58btc")(e):kn.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:cu,valueToBytes:function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const n=fr(t[0],"base32"),r=parseInt(t[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const i=du(r);return Bn([n,i],n.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:cu,valueToBytes:function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const n=Ht.decode(`b${t[0]}`),r=parseInt(t[1],10);if(r<1||r>65536)throw new Error("Port number is not in range(1, 65536)");const i=du(r);return Bn([n,i],n.length+i.length)}},{code:446,name:"garlic64",size:mu},{code:447,name:"garlic32",size:mu},{code:tu,name:"tls"},{code:nu,name:"sni",size:mu},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:ru,name:"certhash",size:mu,bytesToValue:(gu=Xn,e=>gu.encoder.encode(e)),valueToBytes:function(e){return hu.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:mu,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:iu,name:"webrtc"},{code:su,name:"p2p-circuit"},{code:777,name:"memory",size:mu}];var gu;function vu(e,t,n){return null==e.size||0===e.size?0:e.size>0?e.size/8:va(t,n)}bu.forEach(e=>{yu.addProtocol(e)});const wu=Symbol.for("nodejs.util.inspect.custom"),Tu=Symbol.for("@multiformats/multiaddr");class Eu{[Tu]=!0;#t;#n;#r;constructor(e="/",t={}){this.#t=function(e){if(null==e&&(e="/"),xu(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let n=0;for(;n<e.length;){const r=va(e,n),i=yu.getProtocol(r),s=ma(r),a=vu(i,e,n+s);let o=0;a>0&&i.size===mu&&(o=ma(a));const u=s+o+a,d={code:r,name:i.name,bytes:e.subarray(n,n+u)};if(a>0){const t=n+s+o,r=e.subarray(t,t+a);d.value=i.bytesToValue?.(r)??mr(r)}t.push(d),n+=u}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new zo('String multiaddr must start with "/"');const t=[];let n="protocol",r="",i="";for(let s=1;s<e.length;s++){const a=e.charAt(s);"/"!==a&&("protocol"===n?i+=e.charAt(s):r+=e.charAt(s));const o=s===e.length-1;if("/"===a||o){const e=yu.getProtocol(i);if("protocol"===n){if(null==e.size||0===e.size){t.push({code:e.code,name:e.name}),r="",i="",n="protocol";continue}if(o)throw new zo(`Component ${i} was missing value`);n="value"}else if("value"===n){const s={code:e.code,name:e.name};if(null!=e.size&&0!==e.size){if(""===r)throw new zo(`Component ${i} was missing value`);s.value=e.stringToValue?.(r)??r}t.push(s),r="",i="",n="protocol"}}}if(""!==i&&""!==r)throw new zo("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new zo("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach(e=>{const t=yu.getProtocol(e.code);null!=e.value&&t.validate?.(e.value)})}(this)}get bytes(){return null==this.#r&&(this.#r=function(e){let t=0;const n=[];for(const r of e){if(null==r.bytes){const e=yu.getProtocol(r.code),t=ma(r.code);let n,i=0,s=0;null!=r.value&&(n=e.valueToBytes?.(r.value)??fr(r.value),i=n.byteLength,e.size===mu&&(s=ma(i)));const a=new Uint8Array(t+s+i);let o=0;ya(r.code,a,o),o+=t,null!=n&&(e.size===mu&&(ya(i,a,o),o+=s),a.set(n,o)),r.bytes=a}n.push(r.bytes),t+=r.bytes.byteLength}return Bn(n,t)}(this.#t)),this.#r}toString(){return null==this.#n&&(this.#n=`/${this.#t.flatMap(e=>{if(null==e.value)return e.name;const t=yu.getProtocol(e.code);if(null==t)throw new zo(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`),this.#n}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(e=>({...e}))]}encapsulate(e){const t=new Eu(e);return new Eu([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),n=this.toString(),r=n.lastIndexOf(t);if(r<0)throw new Go(`Address ${this.toString()} does not contain subaddress: ${t}`);return new Eu(n.slice(0,r),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===e){t=n;break}return new Eu(this.#t.slice(0,t),{validate:!1})}equals(e){return Ln(this.bytes,e.bytes)}[wu](){return`Multiaddr(${this.toString()})`}}function xu(e){return Boolean(e?.[Tu])}function Pu(e){return new Eu(e)}function Su(e){return Array.from(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function Au(e){for(var t,n=e.reduce(function(e,t){return e+t.length},0),r=new Uint8Array(n),i=0,s=C(e);!(t=s()).done;){var a=t.value;r.set(a,i),i+=a.length}return r}function Cu(e,t){var n=u.PublicKey.fromHex(function(e){if("string"==typeof e)return e.startsWith("0x")?e:"0x"+e;var t=e instanceof Uint8Array?e:Array.isArray(e)?Uint8Array.from(e):Uint8Array.from(Object.keys(e).sort(function(e,t){return Number(e)-Number(t)}).map(function(t){return e[Number(t)]}));return"0x"+Su(t)}(e)),r=u.encrypt(n.toHex(),(new TextEncoder).encode(t));return Su(new Uint8Array(r))}function ku(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Iu=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getConsumerAddress=function(e){return pT(e)},t.getSignature=function(e,t,n){return lT(e,t,n)},t.getAuthorization=function(e){return hT(e)},t.getPersistentStorageSignaturePayload=function(e,t,n,r){try{var i=this;return"string"==typeof t?Promise.resolve({}):Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(a){return Promise.resolve(i.getConsumerAddress(t)).then(function(o){return Promise.resolve(i.getNonce(e,o,r,s,a)).then(function(e){var r=(e+1).toString();return Promise.resolve(i.getSignature(t,r,n)).then(function(e){if(!e)throw new Error("Could not sign persistent storage request.");return{consumerAddress:o,nonce:r,signature:e}})})})})})}catch(e){return Promise.reject(e)}},t.resolvePersistentStorageRoute=function(e,t,n,r){for(var i,s=C(n);!(i=s()).done;){var a=this.getEndpointURL(t,i.value);if(null!=a&&a.urlPath)return a.urlPath}return e.replace(/\/+$/,"")+r},t.getEndpoints=function(e,t){try{var n=this;return Promise.resolve(ku(function(){return Promise.resolve(n.getData(e,t)).then(function(e){return Promise.resolve(e.json())})},function(e){throw O.error("Finding the service endpoints failed:",e),new Error("HTTP request failed calling Provider")}))}catch(e){return Promise.reject(e)}},t.getNodeStatus=function(e,t){try{var n=this;return Promise.resolve(n.getEndpoints(e)).then(function(r){return Promise.resolve(n.getServiceEndpoints(e,r)).then(function(e){var r=n.getEndpointURL(e,"directCommand");return null!=r&&r.urlPath?ku(function(){return Promise.resolve(g.default(r.urlPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:T.STATUS}),signal:t})).then(function(e){return null!=e&&e.ok?e.json():null})},function(e){return O.error("getNodeStatus failed:",e),null}):null})})}catch(e){return Promise.reject(e)}},t.getNodeJobs=function(e,t,n){try{var r=this;return Promise.resolve(r.getEndpoints(e)).then(function(i){return Promise.resolve(r.getServiceEndpoints(e,i)).then(function(e){var i=r.getEndpointURL(e,"jobs");if(null==i||!i.urlPath)return[];var s=i.urlPath;return t&&(s+="?fromTimestamp="+t),ku(function(){return Promise.resolve(g.default(s,{method:"GET",headers:{"Content-Type":"application/json"},signal:n})).then(function(e){var t;function n(e){return t?e:[]}var r=function(){if(null!=e&&e.ok)return Promise.resolve(e.json()).then(function(e){var n=Array.isArray(null==e?void 0:e.jobs)?e.jobs:[];return t=1,n})}();return r&&r.then?r.then(n):n(r)})},function(e){return O.error("getNodeJobs failed:",e),[]})})})}catch(e){return Promise.reject(e)}},t.getNodePublicKey=function(e){try{return Promise.resolve(this.getEndpoints(e)).then(function(e){return e.nodePublicKey})}catch(e){return Promise.reject(e)}},t.getEndpointURL=function(e,t){return e?e.find(function(e){return e.serviceName.toLowerCase()===t.toLowerCase()}):null},t.getServiceEndpoints=function(e,t){try{var n=[];for(var r in t.serviceEndpoints){var i={serviceName:r,method:t.serviceEndpoints[r][0],urlPath:e.replace(/\/+$/,"")+"/"+t.serviceEndpoints[r][1].replace(/^\/+/,"")};n.push(i)}return Promise.resolve(n)}catch(e){return Promise.reject(e)}},t.getNonce=function(e,t,n,r,i){try{var s=function(){function s(){var e=a.getEndpointURL(i,"nonce")?a.getEndpointURL(i,"nonce").urlPath:null;return e?ku(function(){return Promise.resolve(g.default(e+"?userAddress="+t,{method:"GET",headers:{"Content-Type":"application/json"},signal:n})).then(function(e){return Promise.resolve(e.json()).then(function(e){var t=e.nonce;return t&&null!==t?Number(t):0})})},function(e){throw O.error(e),new Error(e.message)}):null}var o=function(){if(!i)return Promise.resolve(a.getServiceEndpoints(e,r)).then(function(e){i=e})}();return o&&o.then?o.then(s):s()},a=this,o=function(){if(!r)return Promise.resolve(a.getEndpoints(e)).then(function(e){r=e})}();return Promise.resolve(o&&o.then?o.then(s):s())}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getEndpoints(n)).then(function(i){return Promise.resolve(a.getServiceEndpoints(n,i)).then(function(o){return Promise.resolve(a.getConsumerAddress(r)).then(function(u){return Promise.resolve(a.getNonce(n,u,s,i,o)).then(function(n){var i=(n+1).toString();return Promise.resolve(a.getSignature(r,i,T.ENCRYPT)).then(function(n){var r=(a.getEndpointURL(o,"encrypt")?a.getEndpointURL(o,"encrypt").urlPath:null)+"?chainId="+t;return r?(r+="&nonce="+i,r+="&consumerAddress="+u,r+="&signature="+n,ku(function(){return Promise.resolve(g.default(r,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/octet-stream"},signal:s})).then(function(e){return Promise.resolve(e.text())})},function(e){throw O.error(e),new Error("HTTP request failed calling Provider")})):null})})})})})}catch(e){return Promise.reject(e)}},t.checkDidFiles=function(e,t,n,r,i){void 0===r&&(r=!1);try{var s=this;return Promise.resolve(s.getEndpoints(n)).then(function(a){return Promise.resolve(s.getServiceEndpoints(n,a)).then(function(n){function a(e){var t;function n(e){return t?e:Promise.resolve(o.json()).then(function(e){throw O.error("File info call failed: ",o.status,o.statusText,e),new Error(JSON.stringify(e))})}var r=function(e){if(null!=(e=o)&&e.ok)return Promise.resolve(o.json()).then(function(e){for(var n,r=C(e);!(n=r()).done;)d.push(n.value);return t=1,d})}();return r&&r.then?r.then(n):n(r)}var o,u={did:e,serviceId:t,checksum:r},d=[],c=s.getEndpointURL(n,"fileinfo")?s.getEndpointURL(n,"fileinfo").urlPath:null;if(!c)return null;var l=ku(function(){return Promise.resolve(g.default(c,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json"},signal:i})).then(function(e){o=e})},function(e){throw O.error("File info call failed: "),O.error(e),new Error(e)});return l&&l.then?l.then(a):a()})})}catch(e){return Promise.reject(e)}},t.getFileInfo=function(e,t,n,r){void 0===n&&(n=!1);try{var i=this;return Promise.resolve(i.getEndpoints(t)).then(function(s){return Promise.resolve(i.getServiceEndpoints(t,s)).then(function(t){function s(e){var t;function n(e){return t?e:Promise.resolve(a.json()).then(function(e){throw O.error("File info call failed: ",a.status,a.statusText,e),new Error(JSON.stringify(e))})}var r=function(e){if(null!=(e=a)&&e.ok)return Promise.resolve(a.json()).then(function(e){for(var n,r=C(e);!(n=r()).done;)u.push(n.value);return t=1,u})}();return r&&r.then?r.then(n):n(r)}var a,o=k({},e,{checksum:n}),u=[],d=i.getEndpointURL(t,"fileinfo")?i.getEndpointURL(t,"fileinfo").urlPath:null;if(!d)return null;var c=ku(function(){return Promise.resolve(g.default(d,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){a=e})},function(e){throw O.error("File info call failed: "),O.error(e),new Error(e)});return c&&c.then?c.then(s):s()})})}catch(e){return Promise.reject(e)}},t.getComputeEnvironments=function(e,t){try{var n=this;return Promise.resolve(n.getEndpoints(e)).then(function(r){return Promise.resolve(n.getServiceEndpoints(e,r)).then(function(e){var r;function i(e){var t;return null!=(t=s)&&t.ok?s.json():Promise.resolve(s.json()).then(function(e){throw O.error("Fetch compute env failed: ",s.status,s.statusText,e),new Error(JSON.stringify(e))})}var s,a=null==(r=n.getEndpointURL(e,"computeEnvironments"))?void 0:r.urlPath;if(!a)return null;var o=ku(function(){return Promise.resolve(g.default(a,{method:"GET",headers:{"Content-Type":"application/json"},signal:t})).then(function(e){s=e})},function(e){throw O.error("Fetch compute env failed: "),O.error(e),new Error(e)});return o&&o.then?o.then(i):i()})})}catch(e){return Promise.reject(e)}},t.initialize=function(e,t,n,r,i,s,a,o,u){try{var d=this;return Promise.resolve(d.getEndpoints(i)).then(function(c){return Promise.resolve(d.getServiceEndpoints(i,c)).then(function(i){function c(e){var t;function n(e){return t?e:Promise.resolve(l.json()).then(function(e){throw O.error("Provider initialized failed: ",l.status,l.statusText,e),new Error(JSON.stringify(e))})}var r=function(e){if(200===(null==(e=l)?void 0:e.status))return Promise.resolve(l.json()).then(function(e){return t=1,e})}();return r&&r.then?r.then(n):n(r)}var l,p=d.getEndpointURL(i,"initialize")?d.getEndpointURL(i,"initialize").urlPath:null;if(!p)return null;p+="?documentId="+e,p+="&serviceId="+t,p+="&fileIndex="+n,p+="&consumerAddress="+r,a&&(p+="&userdata="+encodeURI(JSON.stringify(a))),o&&(p+="&environment="+encodeURI(o)),u&&(p+="&validUntil="+u);var h=ku(function(){return Promise.resolve(g.default(p,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})).then(function(e){l=e})},function(e){throw O.error("Provider initialized failed: "),O.error(e),new Error("Provider initialize failed url: "+p+" ")});return h&&h.then?h.then(c):c()})})}catch(e){return Promise.reject(e)}},t.initializeCompute=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h){try{var f=this;return Promise.resolve(f.getEndpoints(s)).then(function(m){return Promise.resolve(f.getServiceEndpoints(s,m)).then(function(m){function y(){function e(){var e;function t(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw O.error("Initialize compute failed: ",e.status,e.statusText,t),O.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(t))})}var i=function(t){if(null!=(t=e)&&t.ok)return Promise.resolve(e.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var n=ku(function(){return Promise.resolve(g.default(b,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json"},signal:c})).then(function(t){return e=t,function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(""+e)})}()})},function(e){throw O.error("Initialize compute failed: "),O.error(e),new Error("ComputeJob cannot be initialized: "+e.message+".")});return n&&n.then?n.then(t):t()}var t=function(){if(h)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(v.output=Cu(e,JSON.stringify(h)))})}();return t&&t.then?t.then(e):e()}var b=f.getEndpointURL(m,"initializeCompute")?f.getEndpointURL(m,"initializeCompute").urlPath:null;if(!b)return null;var v={datasets:e,algorithm:t,environment:n,payment:{chainId:u,token:r,resources:o},maxJobDuration:i,consumerAddress:a};d&&(v.policyServer=d),l&&(v.queueMaxWaitTime=l);var w=function(){if(p)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(v.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(p)))})}();return w&&w.then?w.then(y):y()})})}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,a,o){try{var u=this;return Promise.resolve(u.getEndpoints(i)).then(function(d){return Promise.resolve(u.getServiceEndpoints(i,d)).then(function(c){var l=u.getEndpointURL(c,"download")?u.getEndpointURL(c,"download").urlPath:null;return l?Promise.resolve(u.getConsumerAddress(s)).then(function(p){return Promise.resolve(u.getNonce(i,p,null,d,c)).then(function(i){var d=(i+1).toString();return Promise.resolve(u.getSignature(s,d,T.DOWNLOAD)).then(function(i){var s=l;return s+="?fileIndex="+n,s+="&documentId="+e,s+="&transferTxId="+r,s+="&serviceId="+t,s+="&consumerAddress="+p,s+="&nonce="+d,a&&(s+="&policyServer="+encodeURI(JSON.stringify(a))),s+="&signature="+i,o&&(s+="&userdata="+encodeURI(JSON.stringify(o))),s})})}):null})})}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m){try{var y=this;return Promise.resolve(y.getEndpoints(e)).then(function(b){return Promise.resolve(y.getServiceEndpoints(e,b)).then(function(v){var w=y.getEndpointURL(v,"computeStart")?y.getEndpointURL(v,"computeStart").urlPath:null;return w?Promise.resolve(y.getConsumerAddress(t)).then(function(E){return Promise.resolve(y.getNonce(e,E,h,b,v)).then(function(b){var v=(b+1).toString();return Promise.resolve(y.getSignature(t,v,T.COMPUTE_START)).then(function(b){function T(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw O.error("Compute start failed: ",e.status,e.statusText,t),O.error("Payload was:",x),new Error(JSON.stringify(t))})}var i=function(t){if(null!=(t=e)&&t.ok)return Promise.resolve(e.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}p&&(x.policyServer=p),f&&(x.queueMaxWaitTime=f);var r=ku(function(){return Promise.resolve(g.default(w,{method:"POST",body:JSON.stringify(x),headers:{"Content-Type":"application/json",Authorization:y.getAuthorization(t)},signal:h})).then(function(t){e=t})},function(e){throw O.error("Compute start failed:"),O.error(e),O.error("Payload was:",x),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}o&&(x.resources=o),d&&(x.metadata=d),c&&(x.additionalViewers=c);var r=function(){if(l)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(x.output=Cu(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var x=Object();x.consumerAddress=E,x.signature=b,x.nonce=v,x.environment=n,x.maxJobDuration=s,x.resources=o,x.dataset=r[0],x.datasets=r,x.algorithm=i,x.chainId=u,x.payment={chainId:u,token:a,maxJobDuration:s,resources:o};var P=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(x.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(m)))})}();return P&&P.then?P.then(T):T()})})}):(O.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null)})})}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p){try{var h=this;return Promise.resolve(h.getEndpoints(e)).then(function(f){return Promise.resolve(h.getServiceEndpoints(e,f)).then(function(m){var y=h.getEndpointURL(m,"freeCompute")?h.getEndpointURL(m,"freeCompute").urlPath:null;return y?Promise.resolve(h.getConsumerAddress(t)).then(function(b){return Promise.resolve(h.getNonce(e,b,c,f,m)).then(function(f){var m=(f+1).toString();return Promise.resolve(h.getSignature(t,m,T.FREE_COMPUTE_START)).then(function(f){function v(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw O.error("Compute start failed: ",e.status,e.statusText,t),O.error("Payload was:",w),new Error(JSON.stringify(t))})}var i=function(t){if(null!=(t=e)&&t.ok)return Promise.resolve(e.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}d&&(w.policyServer=d),l&&(w.queueMaxWaitTime=l);var r=ku(function(){return Promise.resolve(g.default(y,{method:"POST",body:JSON.stringify(w),headers:{"Content-Type":"application/json",Authorization:h.getAuthorization(t)},signal:c})).then(function(t){e=t})},function(e){throw O.error("Compute start failed:"),O.error(e),O.error("Payload was:",w),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}var r=function(){if(u)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(w.output=Cu(e,JSON.stringify(u)))})}();return r&&r.then?r.then(n):n()}var w=Object();w.consumerAddress=b,w.signature=f,w.nonce=m,w.environment=n,w.resources=s,w.dataset=r[0],w.datasets=r,w.algorithm=i,a&&(w.metadata=a),o&&(w.additionalViewers=o);var T=function(){if(p)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(w.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(p)))})}();return T&&T.then?T.then(v):v()})})}):(O.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null)})})}catch(e){return Promise.reject(e)}},t.computeStreamableLogs=function(e,t,n,r){try{var i=this,s="string"==typeof t;return Promise.resolve(i.getEndpoints(e)).then(function(a){return Promise.resolve(i.getServiceEndpoints(e,a)).then(function(o){var u=i.getEndpointURL(o,"computeStreamableLogs")?i.getEndpointURL(o,"computeStreamableLogs").urlPath:null;return u?Promise.resolve(i.getConsumerAddress(t)).then(function(d){return Promise.resolve(i.getNonce(e,d,r,a,o)).then(function(e){function a(){var e;function n(t){var n,r;if(null!=(n=e)&&n.ok||200===(null==(r=e)?void 0:r.status))return e.body;var i=O.error,s=e.statusText,a=e.status;return Promise.resolve(e.json()).then(function(e){return i.call(O,"computeStreamableLogs failed: ",a,s,e),null})}var s=ku(function(){return Promise.resolve(g.default(u+c,{method:"GET",headers:{"Content-Type":"application/json",Authorization:i.getAuthorization(t)},signal:r})).then(function(t){e=t})},function(e){throw O.error("computeStreamableLogs failed:"),O.error(e),new Error("HTTP request failed calling Provider")});return s&&s.then?s.then(n):n()}var o=(e+1).toString(),c="?consumerAddress="+d+"&jobId="+n,l=function(){if(!s)return Promise.resolve(i.getSignature(t,o,T.COMPUTE_GET_STREAMABLE_LOGS)).then(function(e){c+="&signature="+e,c+="&nonce="+o})}();return l&&l.then?l.then(a):a()})}):(O.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null)})})}catch(e){return Promise.reject(e)}},t.computeStop=function(e,t,n,r,i){try{var s=this,a="string"==typeof n;return Promise.resolve(s.getEndpoints(t)).then(function(o){return Promise.resolve(s.getServiceEndpoints(t,o)).then(function(u){var d=s.getEndpointURL(u,"computeStop")?s.getEndpointURL(u,"computeStop").urlPath:null;return Promise.resolve(s.getConsumerAddress(n)).then(function(c){return Promise.resolve(s.getNonce(t,c,i,o,u)).then(function(t){var o=(t+1).toString();return Promise.resolve(s.getSignature(n,o,T.COMPUTE_STOP)).then(function(t){function u(e){var t;function n(e){return t?e:Promise.resolve(p.json()).then(function(e){throw O.error("Compute stop failed: ",p.status,p.statusText,e),new Error(JSON.stringify(e))})}var r=function(e){if(null!=(e=p)&&e.ok)return Promise.resolve(p.json()).then(function(e){return t=1,e})}();return r&&r.then?r.then(n):n(r)}var l=new URLSearchParams;l.set("consumerAddress",c),l.set("nonce",o),l.set("jobId",e),a||l.set("signature",t),r&&l.set("agreementId",r);var p,h=l.toString();if(!h)return null;var f=ku(function(){return Promise.resolve(g.default(d+"?"+h,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:s.getAuthorization(n)},signal:i})).then(function(e){p=e})},function(e){throw O.error("Compute stop failed:"),O.error(e),new Error("HTTP request failed calling Provider")});return f&&f.then?f.then(u):u()})})})})})}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{var s=this;return Promise.resolve(pT(t)).then(function(a){var o=hT(t);return Promise.resolve(s.getEndpoints(e)).then(function(t){return Promise.resolve(s.getServiceEndpoints(e,t)).then(function(e){function t(e){var t;function n(e){var n;if(t)return e;function r(e){return n?e:Promise.resolve(u.json()).then(function(e){throw O.error("Get compute status failed:",u.status,u.statusText,e),new Error(JSON.stringify(e))})}O.error("Get compute status failed:",u.status,u.statusText);var i=function(e){if(null!=(e=u)&&e.ok)return Promise.resolve(u.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var r=function(e){if(null!=(e=u)&&e.ok)return Promise.resolve(u.json()).then(function(e){return t=1,e})}();return r&&r.then?r.then(n):n(r)}var u,d=s.getEndpointURL(e,"computeStatus")?s.getEndpointURL(e,"computeStatus").urlPath:null,c="?consumerAddress="+a;if(c+=r&&"&agreementId="+r||"",c+=n&&"&jobId="+n||"",!d)return null;var l=ku(function(){return Promise.resolve(g.default(d+c,{method:"GET",headers:{"Content-Type":"application/json",Authorization:o},signal:i})).then(function(e){u=e})},function(e){throw O.error("Get compute status failed"),O.error(e),new Error(e)});return l&&l.then?l.then(t):t()})})})}catch(e){return Promise.reject(e)}},t.getComputeResultUrl=function(e,t,n,r){try{var i=this,s="string"==typeof t;return Promise.resolve(i.getEndpoints(e)).then(function(a){return Promise.resolve(i.getServiceEndpoints(e,a)).then(function(o){var u=i.getEndpointURL(o,"computeResult")?i.getEndpointURL(o,"computeResult").urlPath:null;return Promise.resolve(i.getConsumerAddress(t)).then(function(d){return Promise.resolve(i.getNonce(e,d,null,a,o)).then(function(e){var a=(e+1).toString();return Promise.resolve(i.getSignature(t,a,T.COMPUTE_GET_RESULT)).then(function(e){if(!u)return null;var t=u;return t+="?consumerAddress="+d,t+="&jobId="+n,t+="&index="+r.toString(),s||(t+="&nonce="+a,t+="&signature="+e),t})})})})})}catch(e){return Promise.reject(e)}},t.getComputeResult=function(e,t,n,r,i){void 0===i&&(i=0);try{return Promise.resolve(this.getComputeResultUrl(e,t,n,r)).then(function(e){if(!e)throw new Error("Could not retrieve compute result URL");return Promise.resolve(g.default(e,{headers:i>0?{Range:"bytes="+i+"-"}:{}})).then(function(e){if(!e.ok)throw new Error("Failed to fetch compute result: "+e.status);return e.body})})}catch(e){return Promise.reject(e)}},t.generateAuthToken=function(e,t,n){try{var r=this;return Promise.resolve(e.getAddress()).then(function(i){return Promise.resolve(r.getEndpoints(t)).then(function(s){return Promise.resolve(r.getServiceEndpoints(t,s)).then(function(a){var o=r.getEndpointURL(a,"generateAuthToken").urlPath||null;return Promise.resolve(r.getNonce(t,i,n,s,a)).then(function(t){var s=(t+1).toString();return Promise.resolve(r.getSignature(e,s,T.CREATE_AUTH_TOKEN)).then(function(e){return ku(function(){return Promise.resolve(g.default(o,{method:"POST",body:JSON.stringify({address:i,signature:e,nonce:s}),headers:{"Content-Type":"application/json"},signal:n})).then(function(e){if(null==e||!e.ok)throw new Error("Failed to generate auth token: "+e.status+" "+e.statusText);return Promise.resolve(e.json()).then(function(e){return null==e?void 0:e.token})})},function(e){throw O.error("Generate auth token failed:"),O.error(e),new Error("HTTP request failed calling Provider")})})})})})})}catch(e){return Promise.reject(e)}},t.invalidateAuthToken=function(e,t,n,r){try{var i=this;return Promise.resolve(e.getAddress()).then(function(s){return Promise.resolve(i.getEndpoints(n)).then(function(a){return Promise.resolve(i.getServiceEndpoints(n,a)).then(function(o){var u=i.getEndpointURL(o,"invalidateAuthToken").urlPath||null;return Promise.resolve(i.getNonce(n,s,r,a,o)).then(function(n){var i=(n+1).toString();return Promise.resolve($e(e,s+i)).then(function(e){return ku(function(){return Promise.resolve(g.default(u,{method:"POST",body:JSON.stringify({address:s,signature:e,token:t,nonce:i}),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){if(null==e||!e.ok)throw new Error("Failed to invalidate auth token: "+e.status+" "+e.statusText);return Promise.resolve(e.json())})},function(e){throw O.error("Generate auth token failed:"),O.error(e),new Error("HTTP request failed calling Provider")})})})})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){try{return Promise.resolve(ku(function(){return Promise.resolve(g.default(e,{method:"GET",headers:{"Content-Type":"application/json"},signal:t})).then(function(e){var t,n=function(){if(null!=e&&e.ok)return Promise.resolve(e.json()).then(function(e){if(e&&(e.providerAddress||e.providerAddresses))return t=!0})}();return n&&n.then?n.then(function(e){return!!t&&e}):!!t&&n})},function(e){return O.error("Error validating provider: "+e.message),!1}))}catch(e){return Promise.reject(e)}},t.PolicyServerPassthrough=function(e,t,n){try{var r=this;return Promise.resolve(r.getEndpoints(e)).then(function(i){return Promise.resolve(r.getServiceEndpoints(e,i)).then(function(e){function i(e){var n;function r(e){return n?e:Promise.resolve(s.json()).then(function(e){throw O.error("PolicyServerPassthrough failed: ",s.status,s.statusText,e),O.error("Payload was:",JSON.stringify(t)),new Error(JSON.stringify(e))})}var i=function(e){if(null!=(e=s)&&e.ok)return Promise.resolve(s.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var s,a=r.getEndpointURL(e,"PolicyServerPassthrough")?r.getEndpointURL(e,"PolicyServerPassthrough").urlPath:null;if(!a)return null;var o=ku(function(){return Promise.resolve(g.default(a,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"},signal:n})).then(function(e){return s=e,function(){if(!s.ok)return Promise.resolve(s.text()).then(function(e){throw new Error(""+e)})}()})},function(e){throw O.error("PolicyServerPassthrough failed: "),O.error(e),new Error("PolicyServerPassthrough failed: "+e.message+".")});return o&&o.then?o.then(i):i()})})}catch(e){return Promise.reject(e)}},t.initializePSVerification=function(e,t,n){try{var r=this;return Promise.resolve(r.getEndpoints(e)).then(function(i){return Promise.resolve(r.getServiceEndpoints(e,i)).then(function(e){function i(e){var n;function r(e){return n?e:Promise.resolve(s.json()).then(function(e){throw O.error("initializePSVerification failed: ",s.status,s.statusText,e),O.error("Payload was:",JSON.stringify(t)),new Error(JSON.stringify(e))})}var i=function(e){if(null!=(e=s)&&e.ok)return Promise.resolve(s.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var s,a=r.getEndpointURL(e,"initializePSVerification")?r.getEndpointURL(e,"initializePSVerification").urlPath:null;if(!a)return null;var o=ku(function(){return Promise.resolve(g.default(a,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json"},signal:n})).then(function(e){return s=e,function(){if(!s.ok)return Promise.resolve(s.text()).then(function(e){throw new Error(""+e)})}()})},function(e){throw O.error("initializePSVerification failed: "),O.error(e),new Error("initializePSVerification failed: "+e.message+".")});return o&&o.then?o.then(i):i()})})}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,a,o,u){try{var d=this;return Promise.resolve(d.getEndpoints(e)).then(function(c){return Promise.resolve(d.getServiceEndpoints(e,c)).then(function(l){var p=d.getEndpointURL(l,"logs")?d.getEndpointURL(l,"logs").urlPath:null;return p?Promise.resolve(t.getAddress()).then(function(h){return Promise.resolve(d.getNonce(e,h,u,c,l)).then(function(e){var c=(e+1).toString();return Promise.resolve(d.getSignature(t,c,T.GET_LOGS)).then(function(e){function t(e){var t;return null!=(t=d)&&t.ok?d.body:Promise.resolve(d.json()).then(function(e){throw O.error("Download node logs failed: ",d.status,d.statusText,e),new Error(JSON.stringify(e))})}var d,l=p+"?startTime="+n+"&endTime="+r;i&&(l+="&maxLogs="+i),s&&(l+="&moduleName="+s),a&&(l+="&level="+a),o&&(l+="&page="+o);var f=ku(function(){return Promise.resolve(g.default(l,{method:"POST",body:JSON.stringify({signature:e,nonce:c,address:h}),headers:{"Content-Type":"application/json"},signal:u})).then(function(e){d=e})},function(e){throw O.error("Download node logs failed:"),O.error(e),new Error("HTTP request failed calling Provider")});return f&&f.then?f.then(t):t()})})}):(O.error("Download node logs failed: Cannot get proper logs route (perhaps not implemented on provider?)"),null)})})}catch(e){return Promise.reject(e)}},t.noZeroX=function(e){return this.zeroXTransformer(e,!1)},t.zeroXTransformer=function(e,t){void 0===e&&(e="");var n=this.inputMatch(e,/^(?:0x)*([a-f0-9]+)$/i,"zeroXTransformer");return(t&&n.valid?"0x":"")+n.output},t.inputMatch=function(e,t,n){if("string"!=typeof e)throw O.debug("Not input string:"),O.debug(e),new Error("["+n+"] Expected string, input type: "+typeof e);var r=e.match(t);return r?{valid:!0,output:r[1]}:(O.warn("["+n+"] Input transformation failed."),{valid:!1,output:e})},t.resolveDdo=function(e,t,n){try{return Promise.resolve(g.default(e+"/api/aquarius/assets/ddo/"+t,{method:"GET",headers:{"Content-Type":"application/json"},signal:n})).then(function(e){return e.ok?e.json():null})}catch(e){return Promise.reject(e)}},t.validateDdo=function(e,t,n,r){try{var i=this;return Promise.resolve(n.getAddress()).then(function(s){return Promise.resolve(i.getData(e+"/api/services/nonce?userAddress="+s)).then(function(i){return Promise.resolve(i.json()).then(function(i){var a,o=(Number(null!=(a=i.nonce)?a:0)+1).toString();return Promise.resolve($e(n,s+o+T.VALIDATE_DDO)).then(function(n){return Promise.resolve(g.default(e+"/api/aquarius/assets/ddo/validate",{method:"POST",body:JSON.stringify({ddo:t,publisherAddress:s,nonce:o,signature:n}),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){return e.ok?Promise.resolve(e.json()).then(function(e){return{valid:!0,hash:e.hash,proof:{validatorAddress:e.publicKey,r:e.r[0],s:e.s[0],v:e.v}}}):null})})})})})}catch(e){return Promise.reject(e)}},t.getData=function(e,t){try{return Promise.resolve(g.default(e,{method:"GET",headers:{"Content-type":"application/json",Authorization:t}}))}catch(e){return Promise.reject(e)}},t.createPersistentStorageBucket=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(s){var a=i.resolvePersistentStorageRoute(e,s,["persistentStorageCreateBucket"],"/api/services/persistentStorage/buckets");return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(e){var i,s={"Content-Type":"application/json"};return"string"==typeof t&&(s.Authorization=t),Promise.resolve(g.default(a,{method:"POST",headers:s,body:JSON.stringify(k({},e,{accessLists:null!=(i=n.accessLists)?i:[]})),signal:r})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},t.getPersistentStorageBuckets=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(s){var a=i.resolvePersistentStorageRoute(e,s,["persistentStorageGetBuckets"],"/api/services/persistentStorage/buckets");return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_GET_BUCKETS,r)).then(function(e){var i={};"string"==typeof t&&(i.Authorization=t);var s=new URLSearchParams(k({},e,{owner:n}));return Promise.resolve(g.default(a+"?"+s.toString(),{method:"GET",headers:i,signal:r})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},t.listPersistentStorageFiles=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(s){var a=i.resolvePersistentStorageRoute(e,s,["persistentStorageListFiles"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files");return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(e){var n={};"string"==typeof t&&(n.Authorization=t);var i=new URLSearchParams(k({},e));return Promise.resolve(g.default(a+"?"+i.toString(),{method:"GET",headers:n,signal:r})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},t.getPersistentStorageFileObject=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getEndpoints(e)).then(function(a){return Promise.resolve(s.getServiceEndpoints(e,a)).then(function(a){var o=s.resolvePersistentStorageRoute(e,a,["persistentStorageGetFileObject"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r)+"/object");return Promise.resolve(s.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(e){var n=new URLSearchParams(k({},e)),r={};return"string"==typeof t&&(r.Authorization=t),Promise.resolve(g.default(o+"?"+n.toString(),{method:"GET",headers:r,signal:i})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},t.uploadPersistentStorageFile=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getEndpoints(e)).then(function(o){return Promise.resolve(a.getServiceEndpoints(e,o)).then(function(o){var u=a.resolvePersistentStorageRoute(e,o,["persistentStorageUploadFile"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r));return Promise.resolve(a.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(e){function n(e){var n={"Content-Type":"application/octet-stream"},i=a.getAuthorization(t);return i&&(n.Authorization=i),Promise.resolve(g.default(u+"?"+o.toString(),{method:"POST",body:r,headers:k({},n),signal:s})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})}var r,o=new URLSearchParams(k({},e)),d=function(){if("undefined"==typeof window)return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return l(require("stream"))})).then(function(e){var t=e.Readable,n=new TextEncoder,s=F(/*#__PURE__*/D().mark(function e(){var t,r,s,a,o,u,d;return D().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=!1,r=!1,e.prev=2,a=P(i);case 4:return e.next=6,A(a.next());case 6:if(!(t=!(o=e.sent).done)){e.next=25;break}if(!((u=o.value)instanceof Uint8Array)){e.next=12;break}return e.next=11,u;case 11:return e.abrupt("continue",22);case 12:if("string"!=typeof u){e.next=16;break}return e.next=15,n.encode(u);case 15:return e.abrupt("continue",22);case 16:if(!u||"object"!=typeof u||!ArrayBuffer.isView(u)){e.next=21;break}return d=u,e.next=20,new Uint8Array(d.buffer,d.byteOffset,d.byteLength);case 20:return e.abrupt("continue",22);case 21:throw new Error("Unsupported chunk type for HTTP persistent storage upload");case 22:t=!1,e.next=4;break;case 25:e.next=31;break;case 27:e.prev=27,e.t0=e.catch(2),r=!0,s=e.t0;case 31:if(e.prev=31,e.prev=32,!t||null==a.return){e.next=36;break}return e.next=36,A(a.return());case 36:if(e.prev=36,!r){e.next=39;break}throw s;case 39:return e.finish(36);case 40:return e.finish(31);case 41:case"end":return e.stop()}},e,null,[[2,27,31,41],[32,,36,40]])}))();r=t.from(s)});var e=globalThis.ReadableStream;if("function"!=typeof e)throw new Error("ReadableStream is not available in this environment");var t=new TextEncoder,n=i[Symbol.asyncIterator]();r=new e({pull:function(e){try{return Promise.resolve(n.next()).then(function(n){var r=n.value;if(n.done)e.close();else if(r instanceof Uint8Array)e.enqueue(r);else if("string"!=typeof r){if(!r||"object"!=typeof r||!ArrayBuffer.isView(r))throw new Error("Unsupported chunk type for HTTP persistent storage upload");e.enqueue(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}else e.enqueue(t.encode(r))})}catch(e){return Promise.reject(e)}},cancel:function(){try{var e=function(){if("function"==typeof n.return)return Promise.resolve(n.return()).then(function(){})}();return Promise.resolve(e&&e.then?e.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}})}();return d&&d.then?d.then(n):n()})})})}catch(e){return Promise.reject(e)}},t.deletePersistentStorageFile=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getEndpoints(e)).then(function(a){return Promise.resolve(s.getServiceEndpoints(e,a)).then(function(a){var o=s.resolvePersistentStorageRoute(e,a,["persistentStorageDeleteFile"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r));return Promise.resolve(s.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_DELETE_FILE,i)).then(function(e){var n={"Content-Type":"application/json"};"string"==typeof t&&(n.Authorization=t);var r=new URLSearchParams(k({},e));return Promise.resolve(g.default(o+"?"+r.toString(),{method:"DELETE",headers:n,signal:i})).then(function(e){function t(t){return e.json()}var n=function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(e)})}();return n&&n.then?n.then(t):t()})})})})}catch(e){return Promise.reject(e)}},e}();async function Du(e){if(null===e.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new We("Private network is enforced, but no protector was provided");return e}const Mu=1e3,Fu=60*Mu,Ru=60*Fu,_u=24*Ru,Lu=7*_u,Nu=365.25*_u,Ou=Nu/12;var Bu=function(e,t){if("string"==typeof e)return Uu(e);if("number"==typeof e)return function(e,t){if("number"!=typeof e||!Number.isFinite(e))throw Error("Value provided to ms.format() must be of type number.");return t?.long?qu(e):ju(e)}(e,t);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(e)}`)};function Uu(e){if("string"!=typeof e||0===e.length||e.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(e)}`);let t=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(e);if(!t?.groups)return NaN;let{value:n,unit:r="ms"}=t.groups,i=parseFloat(n),s=r.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return i*Nu;case"months":case"month":case"mo":return i*Ou;case"weeks":case"week":case"w":return i*Lu;case"days":case"day":case"d":return i*_u;case"hours":case"hour":case"hrs":case"hr":case"h":return i*Ru;case"minutes":case"minute":case"mins":case"min":case"m":return i*Fu;case"seconds":case"second":case"secs":case"sec":case"s":return i*Mu;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(e)}`)}}function ju(e){let t=Math.abs(e);return t>=Nu?`${Math.round(e/Nu)}y`:t>=Ou?`${Math.round(e/Ou)}mo`:t>=Lu?`${Math.round(e/Lu)}w`:t>=_u?`${Math.round(e/_u)}d`:t>=Ru?`${Math.round(e/Ru)}h`:t>=Fu?`${Math.round(e/Fu)}m`:t>=Mu?`${Math.round(e/Mu)}s`:`${e}ms`}function qu(e){let t=Math.abs(e);return t>=Nu?$u(e,t,Nu,"year"):t>=Ou?$u(e,t,Ou,"month"):t>=Lu?$u(e,t,Lu,"week"):t>=_u?$u(e,t,_u,"day"):t>=Ru?$u(e,t,Ru,"hour"):t>=Fu?$u(e,t,Fu,"minute"):t>=Mu?$u(e,t,Mu,"second"):`${e} ms`}function $u(e,t,n,r){let i=t>=1.5*n;return`${Math.round(e/n)} ${r}${i?"s":""}`}const zu=function(){try{return localStorage}catch(e){}}(),Vu=console.debug??console.log??(()=>{});var Gu=function(e){function t(e,r){let i,s,a,o=null;function u(...e){if(!u.enabled)return;const n=u,s=Number(new Date);n.diff=s-(i||s),n.prev=i,n.curr=s,i=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";a++;const s=t.formatters[i];return"function"==typeof s&&(r=s.call(n,e[a]),e.splice(a,1),a--),r}),t.formatArgs.call(n,e),null!=r?.onLog&&r.onLog(...e),(n.log||t.log).apply(n,e)}return u.namespace=e,u.useColors=t.useColors(),u.color=t.selectColor(e),u.extend=n,u.destroy=t.destroy,Object.defineProperty(u,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,a=t.enabled(e)),a),set:e=>{o=e}}),"function"==typeof t.init&&t.init(u),u}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=Bu,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(n=>{t[n]=e[n]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs:function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Bu(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let n=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(r=n))}),e.splice(r,0,t)},save:function(e){try{e?zu?.setItem("debug",e):zu?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=zu?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/))},setupFormatters:function(e){e.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:zu,log:Vu});function Ku(e,t=""){const n=Yu(e.message),r=Yu(e.stack);return null!=n&&null!=r?r.includes(n)?`${r.split("\n").join(`\n${t}`)}`:`${n}\n${t}${r.split("\n").join(`\n${t}`)}`:null!=r?`${r.split("\n").join(`\n${t}`)}`:null!=n?`${n}`:`${e.toString()}`}function Hu(e,t=""){if(function(e){return e instanceof AggregateError||"AggregateError"===e?.name&&Array.isArray(e.errors)}(e)){let n=Ku(e,t);return n+=e.errors.length>0?`\n${t=`${t} `}${e.errors.map(e=>`${Hu(e,`${t}`)}`).join(`\n${t}`)}`:`\n${t}[Error list was empty]`,n.trim()}return Ku(e,t)}function Wu(e){return{forComponent:t=>Qu(t,e)}}function Qu(e,t){let n=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`);return Gu.enabled(`${e}:trace`)&&null!=Gu.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(n=Gu(`${e}:trace`,t)),Object.assign(Gu(e,t),{error:Gu(`${e}:error`,t),trace:n,newScope:n=>Qu(`${e}:${n}`,t)})}function Yu(e){if(null!=e&&0!==(e=e.trim()).length)return e}function Ju(e,t){const n={[Symbol.iterator]:()=>n,next:()=>{const n=e.next(),r=n.value;return!0===n.done||null==r?{done:!0,value:void 0}:{done:!1,value:t(r)}}};return n}function Zu(e){return qo(xn(Vt.decode(`z${e}`)))}Gu.formatters.b=e=>null==e?"undefined":Vt.baseEncode(e),Gu.formatters.t=e=>null==e?"undefined":Ht.baseEncode(e),Gu.formatters.m=e=>null==e?"undefined":Jn.baseEncode(e),Gu.formatters.p=e=>null==e?"undefined":e.toString(),Gu.formatters.c=e=>null==e?"undefined":e.toString(),Gu.formatters.k=e=>null==e?"undefined":e.toString(),Gu.formatters.a=e=>null==e?"undefined":e.toString(),Gu.formatters.e=e=>null==e?"undefined":Hu(e);class Xu{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Ju(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Ju(this.map.values(),e=>e.key)}values(){return Ju(this.map.values(),e=>e.value)}get size(){return this.map.size}}class ed{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Ju(this.set.entries(),e=>{const t=Zu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{const n=Zu(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ju(this.set.values(),e=>Zu(e))}intersection(e){const t=new ed;for(const n of e)this.has(n)&&t.add(n);return t}difference(e){const t=new ed;for(const n of this)e.has(n)||t.add(n);return t}union(e){const t=new ed;for(const n of e)t.add(n);for(const e of this)t.add(e);return t}}const td={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},nd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},rd=new globalThis.TextEncoder,id={hash:e=>Number(function(e,{size:t=32,utf8Buffer:n}={}){if(!td[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(n)return function(e,t,n){if(0===n.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const r=td[t];let i=nd[t],s=e;for(;s.length>0;){const e=rd.encodeInto(s,n);s=s.slice(e.read);for(let s=0;s<e.written;s++)i^=BigInt(n[s]),i=BigInt.asUintN(t,i*r)}return i}(e,t,n);e=rd.encode(e)}return function(e,t){const n=td[t];let r=nd[t];for(let i=0;i<e.length;i++)r^=BigInt(e[i]),r=BigInt.asUintN(t,r*n);return r}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),fr(t,"base16")}(id.hash(e,t))};class sd{fp;h;seed;constructor(e,t,n,r=2){if(r>64)throw new TypeError("Invalid Fingerprint Size");const i=t.hashV(e,n),s=Nn(r);for(let e=0;e<s.length;e++)s[e]=i[e];0===s.length&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&Ln(this.fp,e.fp)}}function ad(e,t){return Math.floor(Math.random()*(t-e))+e}class od{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof sd))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof sd))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof sd))throw new TypeError("Invalid Fingerprint");const t=ad(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof sd))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex(t=>e.equals(t));return t>-1&&(this.contents[t]=null,!0)}}class ud{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??id,this.seed=e.seed??ad(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=fr(e));const t=new sd(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,r=(n^t.hash())%this.filterSize;if(null==this.buckets[n]&&(this.buckets[n]=new od(this.bucketSize)),null==this.buckets[r]&&(this.buckets[r]=new od(this.bucketSize)),this.buckets[n].add(t)||this.buckets[r].add(t))return this.count++,!0;const i=[n,r];let s=i[ad(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new od(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[s].swap(t);if(null!=e&&(s=(s^e.hash())%this.filterSize,null==this.buckets[s]&&(this.buckets[s]=new od(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=fr(e));const t=new sd(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,r=this.buckets[n]?.has(t)??!1;if(r)return r;const i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){"string"==typeof e&&(e=fr(e));const t=new sd(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,r=this.buckets[n]?.remove(t)??!1;if(r)return this.count--,r;const i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const dd={1:.5,2:.84,4:.95,8:.98};function cd(e,t=.001){const n=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/dd[n]),bucketSize:n,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*n)),64)}}class ld{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??id,this.seed=e.seed??ad(0,Math.pow(2,10)),this.filterSeries=[new ud({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=fr(e)),this.has(e))return!0;let t=this.filterSeries.find(e=>e.reliable);if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new ud({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=fr(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=fr(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}}function pd(e,t=.001,n){return new ld({...cd(e,t),...n??{}})}function hd(e){const t=e.getComponents(),n={};let r=0;if("ip6zone"===t[r]?.name&&(n.zone=`${t[r].value}`,r++),"ip4"===t[r].name||"ip6"===t[r].name||"dns"===t[r].name||"dns4"===t[r].name||"dns6"===t[r].name?(n.type=t[r].name,n.host=t[r].value,r++):"dnsaddr"===t[r].name&&(n.type=t[r].name,n.host=`_dnsaddr.${t[r].value}`,r++),"tcp"!==t[r]?.name&&"udp"!==t[r]?.name||(n.protocol="tcp"===t[r].name?"tcp":"udp",n.port=parseInt(`${t[r].value}`),r++),"ipcidr"===t[r]?.name&&("ip4"===n.type?n.cidr=parseInt(`${t[r].value}`):"ip6"===n.type&&(n.cidr=`${t[r].value}`),r++),null==n.type||null==n.host)throw new We(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return"tls"===t[r]?.name&&"sni"===t[r+1]?.name&&(n.sni=t[r+1].value,r+=2),n}const fd=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function md(e,t){16===t.length&&4===e.length&&function(e){let t=0;for(const n of e)if(!(t<0)){if(t>11)break;if(255!==n)return!1;t++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t){let n=0;for(const r of e)if(!(n<0)){if(n>11)break;if(r!==t[n])return!1;n++}return!0}(e,fd)&&(e=e.slice(12));const n=e.length;if(n!=t.length)throw new Error("Failed to mask ip");const r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=e[i]&t[i];return r}function yd(e,t){if(32!==t&&128!==t)throw new Error("Invalid CIDR mask");if(e<0||e>t)throw new Error("Invalid CIDR mask");const n=t/8,r=new Uint8Array(n);for(let t=0;t<n;t++)e>=8?(r[t]=255,e-=8):(r[t]=255-(255>>e),e=0);return r}class bd{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,n]=e.split("/");if(!t||!n)throw new Error("Failed to parse given CIDR: "+e);let r=4,i=Wo(t);if(null==i&&(r=16,i=Qo(t),null==i))throw new Error("Failed to parse given CIDR: "+e);const s=parseInt(n,10);if(Number.isNaN(s)||String(s).length!==n.length||s<0||s>8*r)throw new Error("Failed to parse given CIDR: "+e);const a=yd(s,8*r);return{network:md(i,a),mask:a}}(e));else{const n=Yo(e);if(null==n)throw new Error("Failed to parse network");t=String(t);const r=parseInt(t,10);if(Number.isNaN(r)||String(r).length!==t.length||r<0||r>8*n.length){const e=Yo(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=yd(r,8*n.length);this.network=md(n,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Yo(t)),null==t)throw new Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let n=0;n<t.length;n++)if((e.network[n]&e.mask[n])!=(t[n]&e.mask[n]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[n,r]of e.entries()){if(255!==r){for(;128&r;)t++,r<<=1;if(128&r)return-1;for(let t=n+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?String(e):function(e){let t="0x";for(const n of e)t+=(n>>4).toString(16)+(15&n).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let n=0;n<e.length;n++)n%2==0&&t.push(e[n].toString(16).padStart(2,"0")+e[n+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}(this.network)+"/"+t}}function gd(e){try{const n=hd(e);switch(n.type){case"ip4":case"ip6":return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t=n.host)||/^::1$/.test(t);default:return!1}}catch{return!1}var t}function vd(e){try{return hd(e),!0}catch{return!1}}var wd="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Td(e){var t={exports:{}};return e(t,t.exports),t.exports}var Ed=Td(function(e,t){(function(){var e,n,r,i,s,a,o,u;u=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},o=function(e){var t,r,i,s,a;for(t=[],r=i=0;i<=3&&0!==e.length;r=++i){if(r>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}s=(a=n(e))[0],e=e.substring(a[1]),t.push(s)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},i=(r=function(e){return e.charCodeAt(0)})("0"),a=r("a"),s=r("A"),n=function(e){var t,n,o,u,d;for(u=0,t=10,n="9",o=0,e.length>1&&"0"===e[o]&&("x"===e[o+1]||"X"===e[o+1]?(o+=2,t=16):"0"<=e[o+1]&&e[o+1]<="9"&&(o++,t=8,n="7")),d=o;o<e.length;){if("0"<=e[o]&&e[o]<=n)u=u*t+(r(e[o])-i)>>>0;else{if(16!==t)break;if("a"<=e[o]&&e[o]<="f")u=u*t+(10+r(e[o])-a)>>>0;else{if(!("A"<=e[o]&&e[o]<="F"))break;u=u*t+(10+r(e[o])-s)>>>0}}if(u>4294967295)throw new Error("too large");o++}if(o===d)throw new Error("empty octet");return[u,o]},e=function(){function e(e,t){var n,r,i;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=o(t)}catch(e){throw new Error("Invalid mask: "+t)}for(n=r=32;r>=0;n=--r)if(this.maskLong===4294967295<<32-n>>>0){this.bitmask=n;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(o(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=u(this.netLong),this.mask=u(this.maskLong),this.hostmask=u(~this.maskLong),this.first=this.bitmask<=30?u(this.netLong+1):this.base,this.last=u(this.bitmask<=30?this.netLong+this.size-2:this.netLong+this.size-1),this.broadcast=this.bitmask<=30?u(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(o(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(u(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,n,r;for(r=o(this.first),n=o(this.last),t=0;r<=n;)e(u(r),r,t),t++,r++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=o,t.long2ip=u,t.Netmask=e}).call(wd)});const xd=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map(e=>new Ed.Netmask(e));function Pd(e){for(const t of xd)if(t.contains(e))return!0;return!1}function Sd(e){return Jo(e)?Pd(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const n=t[t.length-1].padStart(4,"0"),r=t[t.length-2].padStart(4,"0");return Pd(`${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}.${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}`)}(e):/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)?function(e){const t=e.split(":");return Pd(t[t.length-1])}(e):Zo(e)?/^::$/.test(t=e)||/^::1$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t):void 0;var t}function Ad(e){try{const t=hd(e);switch(t.type){case"ip4":case"ip6":return Sd(t.host)??!1;default:return"localhost"===t.host}}catch{return!1}}function Cd(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class kd{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class Id{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new kd(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){null!=e?.value&&(this.size+=this.calculateSize(e.value)),this.head.push(e)||(this.head=this.head.next=new kd(2*this.head.buffer.length),this.head.push(e))}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class Dd extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Md(e={}){return function(e,t){let n,r,i,s=(t=t??{}).onEnd,a=new Id,o=Cd();const u=e=>null!=r?r(e):(a.push(e),n),d=e=>{if(i)return n;if(!0!==t?.objectMode&&null==e?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:e})},c=e=>i?n:(i=!0,null!=e?(e=>(a=new Id,null!=r?r({error:e}):(a.push({error:e}),n)))(e):u({done:!0}));if(n={[Symbol.asyncIterator](){return this},next:async()=>{try{return a.isEmpty()?i?{done:!0}:await new Promise((t,i)=>{r=s=>{r=null,a.push(s);try{t(e(a))}catch(e){i(e)}return n}}):e(a)}finally{a.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=Cd()})}},return:()=>(a=new Id,c(),{done:!0}),throw:e=>(c(e),{done:!0}),push:d,end:c,get readableLength(){return a.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),a.isEmpty())return;let n,r;null!=t&&(n=new Promise((e,n)=>{r=()=>{n(new Dd)},t.addEventListener("abort",r)}));try{await Promise.race([o.promise,n])}finally{null!=r&&null!=t&&t?.removeEventListener("abort",r)}}},null==s)return n;const l=n;return n={[Symbol.asyncIterator](){return this},next:()=>l.next(),throw:e=>(l.throw(e),null!=s&&(s(e),s=void 0),{done:!0}),return:()=>(l.return(),null!=s&&(s(),s=void 0),{done:!0}),push:d,end:e=>(l.end(e),null!=s&&(s(e),s=void 0),n),get readableLength(){return l.readableLength},onEmpty:e=>l.onEmpty(e)},n}(e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}},e)}class Fd extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Fd)}}const Rd=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function _d(e,t,n){"function"==typeof n&&(n={filter:n});const r=function(e,t,n){let r;const i=new Promise((i,s)=>{if(!((n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n}).count>=0)||n.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(n.count))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[t].flat(),o=[],{addListener:u,removeListener:d}=(e=>{const t=e.addEventListener||e.on||e.addListener,n=e.removeEventListener||e.off||e.removeListener;if(!t||!n)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:n.bind(e)}})(e),c=async(...e)=>{const t=n.multiArgs?e:e[0];if(n.filter)try{if(!await n.filter(t))return}catch(e){return r(),void s(e)}o.push(t),n.count===o.length&&(r(),i(o))},l=(...e)=>{r(),s(n.rejectionMultiArgs?e:e[0])};r=()=>{for(const e of a)d(e,c);for(const e of n.rejectionEvents)a.includes(e)||d(e,l)};for(const e of a)u(e,c);for(const e of n.rejectionEvents)a.includes(e)||u(e,l);n.signal&&n.signal.addEventListener("abort",()=>{l(n.signal.reason)},{once:!0}),n.resolveImmediately&&i(o)});if(i.cancel=r,"number"==typeof n.timeout){const e=function(e,t){const{milliseconds:n,fallback:r,message:i,customTimers:s={setTimeout:setTimeout,clearTimeout:clearTimeout},signal:a}=t;let o,u;const d=new Promise((t,d)=>{if("number"!=typeof n||1!==Math.sign(n))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(a?.aborted)return void d(Rd(a));if(a&&(u=()=>{d(Rd(a))},a.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Fd;o=s.setTimeout.call(void 0,()=>{if(r)try{t(r())}catch(e){d(e)}else"function"==typeof e.cancel&&e.cancel(),!1===i?t():i instanceof Error?d(i):(c.message=i??`Promise timed out after ${n} milliseconds`,d(c))},n)}).finally(()=>{d.clear(),u&&a&&a.removeEventListener("abort",u)});return d.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},d}(i,{milliseconds:n.timeout});return e.cancel=()=>{r(),e.clear()},e}return i}(e,t,n={...n,count:1,resolveImmediately:!1}),i=r.then(e=>e[0]);return i.cancel=r.cancel,i}function Ld(e,t){let n;const r=function(){clearTimeout(n),n=setTimeout(function(){n=void 0,e()},t)};return r.start=()=>{},r.stop=()=>{clearTimeout(n)},r}class Nd extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}class Od extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Bd extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class Ud extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"}class jd extends Error{static name="StreamClosedError";name="StreamClosedError"}function qd(e){return e.reason}async function $d(e,t,n){if(null==t)return e;const r=n?.translateError??qd;if(t.aborted)return e.catch(()=>{}),Promise.reject(r(t));let i;try{return await Promise.race([e,new Promise((e,n)=>{i=()=>{n(r(t))},t.addEventListener("abort",i)})])}finally{null!=i&&t.removeEventListener("abort",i)}}class zd{deferred;signal;constructor(e){this.signal=e,this.deferred=Cd(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ge)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Vd{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((e,t)=>e&&!0===t.signal?.aborted,!0)&&(this.controller.abort(new Ge),this.cleanup())}async join(e={}){const t=new zd(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await $d(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}}class Gd extends Ft{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ld(this.emitEmpty.bind(this),1),this.emitIdle=Ld(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Od;const n=new Vd(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:n,result:e}}),e)).catch(e=>{if("queued"===n.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===n){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:n,error:e}}),e})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ge)}),this.clear()}async onEmpty(e){0!==this.size&&await _d(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await _d(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await _d(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Md({objectMode:!0}),n=e=>{null!=e?this.abort():this.clear(),t.end(e)},r=e=>{null!=e.detail&&t.push(e.detail)},i=e=>{n(e.detail.error)},s=()=>{n()},a=()=>{n(new Ge("Queue aborted"))};this.addEventListener("completed",r),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}}const Kd=4*Math.pow(2,20);class Hd extends Ft{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Kd,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new $n,this.writeBuffer=new $n,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this),this.addEventListener("drain",()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()}),this.addEventListener("close",e=>{this.onDrainPromise?.reject(e.error??new jd)})}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return!0!==this.writableNeedsDrain?Promise.resolve():(null==this.onDrainPromise&&(this.onDrainPromise=Promise.withResolvers()),$d(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if("readable"!==this.readStatus&&"paused"!==this.readStatus)return;const e=Md(),t=t=>{e.push(t.data)};this.addEventListener("message",t);const n=t=>{e.end(t.error)};this.addEventListener("close",n);const r=()=>{e.end()};this.addEventListener("remoteCloseWrite",r);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",r)}}isReadable(){return"open"===this.status}send(e){if("closed"===this.writeStatus||"closing"===this.writeStatus)throw new et(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if("aborted"!==this.status&&"reset"!==this.status&&"closed"!==this.status){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(e){this.log("failed to send reset to remote - %e",e)}this.dispatchEvent(new wt(e))}}pause(){if("closed"===this.readStatus||"closing"===this.readStatus)throw new et("Cannot pause a stream that is closing/closed");"paused"!==this.readStatus&&(this.readStatus="paused",this.sendPause())}resume(){if("closed"===this.readStatus||"closing"===this.readStatus)throw new et("Cannot resume a stream that is closing/closed");"readable"!==this.readStatus&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if("closed"===this.readStatus||"closing"===this.readStatus)throw new et(`Cannot push data onto a stream that is ${this.readStatus}`);0!==e.byteLength&&(this.readBuffer.append(e),"paused"!==this.readStatus&&0!==this.listenerCount("message")?setTimeout(()=>{this.dispatchReadBuffer()},0):this.checkReadBufferLength())}unshift(e){if("closed"===this.readStatus||"closing"===this.readStatus)throw new et(`Cannot push data onto a stream that is ${this.readStatus}`);0!==e.byteLength&&(this.readBuffer.prepend(e),"paused"!==this.readStatus&&0!==this.listenerCount("message")?setTimeout(()=>{this.dispatchReadBuffer()},0):this.checkReadBufferLength())}onData(e){0!==e.byteLength&&("closing"!==this.readStatus&&"closed"!==this.readStatus?(this.readBuffer.append(e),this.dispatchReadBuffer()):this.log("ignoring data - read status %s",this.readStatus))}addEventListener(...e){super.addEventListener.apply(this,e),"message"===e[0]&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),0===this.readBuffer.byteLength&&(this.readStatus="closed");const e=new Xe;this.dispatchEvent(new Tt(e))}onTransportClosed(e){this.log("transport closed"),"readable"===this.readStatus&&0===this.readBuffer.byteLength&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),"closed"!==this.remoteReadStatus&&(this.remoteReadStatus="closed"),"closed"!==this.remoteWriteStatus&&(this.remoteWriteStatus="closed"),"closed"!==this.writeStatus&&(this.writeStatus="closed"),null!=e?this.abort(e):"open"!==this.status&&"closing"!==this.status||(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new vt))}onRemoteCloseWrite(){"closed"!==this.remoteWriteStatus&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),"closed"===this.writeStatus&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(0===this.writeBuffer.byteLength)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const t=this.writeBuffer.byteLength;let n=0;for(;this.writeBuffer.byteLength>0;){const t=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(0===t){e=!1;break}const r=this.writeBuffer.sublist(0,t),i=new $n(r);this.writeBuffer.consume(r.byteLength);const s=this.sendData(r);if(e=s.canSendMore,n+=s.sentBytes,s.sentBytes!==i.byteLength&&(i.consume(s.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),0===this.writeBuffer.byteLength&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(0===this.listenerCount("message"))return void this.log.trace("not dispatching pause buffer as there are no listeners for the message event");if(0===this.readBuffer.byteLength)return void this.log.trace("not dispatching pause buffer as there is no data to dispatch");if("paused"===this.readStatus)return void this.log.trace("not dispatching pause buffer we are paused");if("closing"===this.readStatus||"closed"===this.readStatus)return this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),void this.readBuffer.consume(this.readBuffer.byteLength);const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new gt(e))}finally{0===this.readBuffer.byteLength&&"closed"===this.remoteWriteStatus&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new tt(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){null!=this.maxWriteBufferLength&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new tt(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}}class Wd extends Hd{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",e=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),this.metrics?.increment(null!=e.error?e.local?{[`${this.metricPrefix}abort`]:!0}:{[`${this.metricPrefix}reset`]:!0}:e.local?{[`${this.metricPrefix}_local_close`]:!0}:{[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){"open"===this.status&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await _d(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await _d(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}}class Qd extends Ft{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics,this.maConn.addEventListener("message",e=>{try{this.onData(e.data)}catch(e){this.abort(e),this.maConn.abort(e)}}),this.maConn.addEventListener("drain",()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(e=>{e.onMuxerDrain()})}),this.maConn.addEventListener("close",()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()})}send(e){const t=this.maConn.send(e);return!1===t&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(e=>{e.onMuxerNeedsDrain()})),t}async close(e){"closed"!==this.status&&"closing"!==this.status&&(this.status="closing",await $d(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){"closed"!==this.status&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(e){this.abort(e)}this.status="closed"}async createStream(e){if("open"!==this.status)throw new Ze;let t=this.onCreateStream({...this.streamOptions,...e});var n;return null!=(n=t)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),0===this.listenerCount("stream"))return this.earlyStreams.push(e),void(this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Ud(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`)));this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){e.addEventListener("close",t=>{const n=this.streams.findIndex(t=>t===e);-1!==n&&this.streams.splice(n,1),this.metrics?.increment(null!=t.error?t.local?{[`${e.direction}_stream_reset`]:!0}:{[`${e.direction}_stream_abort`]:!0}:{[`${e.direction}_stream_end`]:!0})}),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),"stream"===e[0]&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(e=>{this.safeDispatchEvent("stream",{detail:e})}),this.earlyStreams=[]})}}class Yd extends Hd{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await _d(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await _d(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),"closed"===this.remoteWriteStatus&&this.onTransportClosed())}async closeRead(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}}function Jd(e){const t=new globalThis.AbortController;function n(){const r=e.filter(e=>!0===e?.aborted).map(e=>e?.reason).pop();t.abort(r);for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",n)}for(const t of e){if(!0===t?.aborted){n();break}null!=t?.addEventListener&&t.addEventListener("abort",n)}const r=t.signal;return r.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",n)},r}class Zd{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(null!=this.previousTime){const n=this.alpha(t,this.previousTime),r=e-this.movingAverage,i=n*r;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+r*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*r}else this.movingAverage=e;this.previousTime=t}}class Xd{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new Zd(t),this.failure=new Zd(t),this.next=new Zd(t),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??5e3,this.maxTimeout=e.maxTimeout??6e4,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);const n=AbortSignal.timeout(t),r=Jd([e.signal,n]);return r.start=Date.now(),r.timeout=t,r}cleanUp(e){e.clear();const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class ec{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Cd(),this.haveNext=Cd()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Cd(),e}async throw(e){return this.ended=!0,this.error=e,null!=e&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Cd(),await $d(this.readNext.promise,t?.signal,t)}}function tc(...e){const t=[];for(const n of e)null==n[Symbol.asyncIterator]&&t.push(n);return t.length===e.length?function*(e){for(const t of e)yield*t}(t):async function*(e){const t=new AbortController,n=new ec;(async function(e,t,n){try{await Promise.all(e.map(async e=>{for await(const r of e)await t.push(r,{signal:n}),n.throwIfAborted()})),await t.end(void 0,{signal:n})}catch(e){await t.end(e,{signal:n}).catch(()=>{})}})(e,n,t.signal).catch(()=>{});try{yield*n}finally{t.abort()}}(e)}function nc(e,...t){if(null==e)throw new Error("Empty pipeline");if(ac(e)){const t=e;e=()=>t.source}else if(sc(e)||ic(e)){const t=e;e=()=>t}const n=[e,...t];if(n.length>1&&ac(n[n.length-1])&&(n[n.length-1]=n[n.length-1].sink),n.length>2)for(let e=1;e<n.length-1;e++)ac(n[e])&&(n[e]=oc(n[e]));return rc(...n)}const rc=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},ic=e=>null!=e?.[Symbol.asyncIterator],sc=e=>null!=e?.[Symbol.iterator],ac=e=>null!=e&&null!=e.sink&&null!=e.source,oc=e=>t=>{const n=e.sink(t);if(null!=n?.then){const t=Md({objectMode:!0});let r;n.then(()=>{t.end()},e=>{t.end(e)});const i=e.source;if(ic(i))r=async function*(){yield*i,t.end()};else{if(!sc(i))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");r=function*(){yield*i,t.end()}}return tc(t,r())}return e.source};class uc extends Error{static name="UnwrappedError";name="UnwrappedError"}class dc extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class cc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class lc extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function pc(e){return function(e){return"function"==typeof e?.closeRead}(e)?"writable"!==e.remoteWriteStatus&&0===e.readBufferLength:!!function(e){return"function"==typeof e?.close}(e)&&"open"!==e.status}function hc(e,t){const n=t?.maxBufferSize??4194304,r=new $n;let i,s=!1;if(a=e,null==a?.addEventListener||null==a?.removeEventListener||null==a?.send||null==a?.push||null==a?.log)throw new We("Argument should be a Stream or a Multiaddr");var a;const o=e=>{if(r.append(e.data),r.byteLength>n){const e=r.byteLength;r.consume(r.byteLength),i?.reject(new Error(`Read buffer overflow - ${e} > ${n}`))}i?.resolve()};e.addEventListener("message",o);const u=e=>{null!=e.error?i?.reject(e.error):i?.resolve()};e.addEventListener("close",u);const d=()=>{i?.resolve()};e.addEventListener("remoteCloseWrite",d);const c={readBuffer:r,async read(t){if(!0===s)throw new uc("Stream was unwrapped");if(pc(e)){if(0===r.byteLength&&null==t?.bytes)return null;if(null!=t?.bytes&&r.byteLength<t.bytes)throw e.log.error("closed after reading %d/%d bytes",r.byteLength,t.bytes),new Bd(`Unexpected EOF - stream closed after reading ${r.byteLength}/${t.bytes} bytes`)}const n=t?.bytes??1;for(i=Promise.withResolvers();;){if(r.byteLength>=n){i.resolve();break}if(await $d(i.promise,t?.signal),pc(e)){if(0===r.byteLength&&null==t?.bytes)return null;break}i=Promise.withResolvers()}const a=t?.bytes??r.byteLength;if(r.byteLength<a){if(pc(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,a),new Bd(`Unexpected EOF - stream closed while reading ${r.byteLength}/${a} bytes`);return c.read(t)}const o=r.sublist(0,a);return r.consume(a),o},async write(t,n){if(!0===s)throw new uc("Stream was unwrapped");e.send(t)||await _d(e,"drain",{signal:n?.signal,rejectionEvents:["close"]})},unwrap:()=>(s||(s=!0,e.removeEventListener("message",o),e.removeEventListener("close",u),e.removeEventListener("remoteCloseWrite",d),r.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",r.byteLength),e.push(r))),e)};return c}function fc(e,t={}){const n=hc(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=ma(t.maxDataLength));const r=t?.lengthDecoder??va,i=t?.lengthEncoder??ga;return{async read(i){let s=-1;const a=new $n;for(;;){const e=await n.read({...i,bytes:1});if(null==e)break;a.append(e);try{s=r(a)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new dc("Invalid message length");if(null!=t?.maxLengthLength&&a.byteLength>t.maxLengthLength)throw new lc(`Message length length too long - ${a.byteLength} > ${t.maxLengthLength}`);if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new cc(`Message length too long - ${s} > ${t.maxDataLength}`);const o=await n.read({...i,bytes:s});if(null==o)throw e.log.error("tried to read %d bytes but the stream closed",s),new Bd(`Unexpected EOF - tried to read ${s} bytes but the stream closed`);if(o.byteLength!==s)throw e.log.error("read %d/%d bytes before the stream closed",o.byteLength,s),new Bd(`Unexpected EOF - read ${o.byteLength}/${s} bytes before the stream closed`);return o},async write(e,t){await n.write(new $n(i(e.byteLength),e),t)},async writeV(e,t){const r=new $n(...e.flatMap(e=>[i(e.byteLength),e]));await n.write(r,t)},unwrap:()=>n.unwrap()}}function mc(e,t){const n=fc(e,t),r={read:async(e,t)=>{const r=await n.read(t);return e.decode(r)},write:async(e,t,r)=>{await n.write(t.encode(e),r)},writeV:async(e,t,r)=>{await n.writeV(e.map(e=>t.encode(e)),r)},pb:e=>({read:async t=>r.read(e,t),write:async(t,n)=>r.write(t,e,n),writeV:async(t,n)=>r.writeV(t,e,n),unwrap:()=>r}),unwrap:()=>n.unwrap()};return r}class yc{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new $n,this.maxBufferSize=e.maxBufferSize??4194304,this.maxDataLength=e.maxDataLength??4194304,this.lengthDecoder=e.lengthDecoder??va,this.encodingLength=e.encodingLength??ma}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new We(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let e;try{e=this.lengthDecoder(this.buffer)}catch(e){if(e instanceof RangeError)break;throw e}if(e<0||e>this.maxDataLength)throw new dc("Invalid message length");const t=this.encodingLength(e),n=t+e;if(!(this.buffer.byteLength>=n))break;{const e=this.buffer.sublist(t,n);this.buffer.consume(n),e.byteLength>0&&(yield e)}}}}const bc=4194304;class gc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}function vc(e,t){if(e.byteLength>t)throw new gc("Message length too long")}const wc=e=>{const t=ma(e),n=On(t);return ga(e,n),wc.bytes=t,n};function Tc(e,t){const n=(t=t??{}).lengthEncoder??wc,r=t?.maxDataLength??bc;function*i(e){vc(e,r);const t=n(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return null!=e[Symbol.asyncIterator]?async function*(){for await(const t of e)yield*i(t)}():function*(){for(const t of e)yield*i(t)}()}var Ec;wc.bytes=0,Tc.single=(e,t)=>{const n=(t=t??{}).lengthEncoder??wc;return vc(e,t?.maxDataLength??bc),new $n(n(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Ec||(Ec={}));class xc extends Gd{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}class Pc extends Gd{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}class Sc{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Ac}consume(e,t=1,n={}){const r=this.getKey(e),i=this._getKeySecDuration(n);let s=this.memoryStorage.incrby(r,t,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(r,s.consumedPoints,this.blockDuration)),new Nd("Rate limit exceeded",s);return s}penalty(e,t=1,n={}){const r=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(r,t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,n={}){const r=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(r,-t,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){const n=1e3*t,r=this.points+1;return this.memoryStorage.set(this.getKey(e),r,t),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:r,isFirstInDuration:!1}}set(e,t,n=0){const r=1e3*(n>=0?n:this.duration);return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class Ac{storage;constructor(){this.storage=new Map}incrby(e,t,n){const r=this.storage.get(e);if(null!=r){const i=null!=r.expiresAt?r.expiresAt.getTime()-(new Date).getTime():-1;return null==r.expiresAt||i>0?(r.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:r.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){const r=1e3*n,i=this.storage.get(e);null!=i&&clearTimeout(i.timeoutId);const s={value:t,expiresAt:r>0?new Date(Date.now()+r):void 0};return this.storage.set(e,s),r>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},r),null!=s.timeoutId.unref&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:s.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}function Cc(e,t,n){let r,i,s=!1;function a(){const o={signal:i.signal};let u;null!=n?.timeout&&(u=Jd([i.signal,AbortSignal.timeout(n.timeout)]),o.signal=u),s=!0,Promise.resolve().then(async()=>{await e(o)}).catch(()=>{}).finally(()=>{null!=u&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),s=!1,i.signal.aborted||(r=setTimeout(a,t))})}const o=Ld(a,n?.debounce??100);let u=!1;return{setInterval:e=>{t!==e&&(t=e,null!=r&&(clearTimeout(r),r=setTimeout(a,t)))},setTimeout:e=>{n??={},n.timeout=e},run:()=>{s||(clearTimeout(r),o())},start:()=>{u||(u=!0,i=new AbortController,!0===n?.runImmediately?queueMicrotask(()=>{a()}):r=setTimeout(a,t))},stop:()=>{clearTimeout(r),i?.abort(),u=!1}}}class kc extends Map{metric;constructor(e){super();const{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function Ic(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new kc({name:t,metrics:n}):new Map,r}class Dc{filter;constructor(e,t){this.filter=pd(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}}function Mc(e,t=.001){return new Dc(e,t)}class Fc extends Xu{metric;constructor(e){super();const{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function Rc(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Fc({name:t,metrics:n}):new Xu,r}const _c=new Float32Array([-0]),Lc=new Uint8Array(_c.buffer);function Nc(e,t,n){_c[0]=e,t[n]=Lc[0],t[n+1]=Lc[1],t[n+2]=Lc[2],t[n+3]=Lc[3]}const Oc=new Float64Array([-0]),Bc=new Uint8Array(Oc.buffer);function Uc(e,t,n){Oc[0]=e,t[n]=Bc[0],t[n+1]=Bc[1],t[n+2]=Bc[2],t[n+3]=Bc[3],t[n+4]=Bc[4],t[n+5]=Bc[5],t[n+6]=Bc[6],t[n+7]=Bc[7]}const jc=BigInt(Number.MAX_SAFE_INTEGER),qc=BigInt(Number.MIN_SAFE_INTEGER);class $c{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(0n===e)return zc;if(e<jc&&e>qc)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let n=e>>32n,r=e-(n<<32n);return t&&(n=0n|~n,r=0n|~r,++r>Vc&&(r=0n,++n>Vc&&(n=0n))),new $c(Number(r),Number(n))}static fromNumber(e){if(0===e)return zc;const t=e<0;t&&(e=-e);let n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new $c(n,r)}static from(e){return"number"==typeof e?$c.fromNumber(e):"bigint"==typeof e?$c.fromBigInt(e):"string"==typeof e?$c.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new $c(e.low>>>0,e.high>>>0):zc}}const zc=new $c(0,0);zc.toBigInt=function(){return 0n},zc.zzEncode=zc.zzDecode=function(){return this},zc.length=function(){return 1};const Vc=4294967296n;function Gc(e,t,n){const r=n;let i,s;for(let r=0;r<e.length;++r)i=e.charCodeAt(r),i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-r}function Kc(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Hc(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Wc{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Kc(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Kc(this,4);return Hc(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Kc(this,4);return 0|Hc(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Kc(this,4);const e=(Lc[0]=(t=this.buf)[n=this.pos],Lc[1]=t[n+1],Lc[2]=t[n+2],Lc[3]=t[n+3],_c[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Kc(this,4);const e=(Bc[0]=(t=this.buf)[n=this.pos],Bc[1]=t[n+1],Bc[2]=t[n+2],Bc[3]=t[n+3],Bc[4]=t[n+4],Bc[5]=t[n+5],Bc[6]=t[n+6],Bc[7]=t[n+7],Oc[0]);var t,n;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Kc(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){const e=this.bytes();return function(e,t,n){if(n-t<1)return"";let r;const i=[];let s,a=0;for(;t<n;)s=e[t++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=r?(a>0&&r.push(String.fromCharCode.apply(String,i.slice(0,a))),r.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Kc(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Kc(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new $c(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Kc(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Kc(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Kc(this,8);const e=Hc(this.buf,this.pos+=4),t=Hc(this.buf,this.pos+=4);return new $c(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=ba(this.buf,this.pos);return this.pos+=ma(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Qc(e){return new Wc(e instanceof Uint8Array?e:e.subarray())}function Yc(e,t,n){const r=Qc(e);return t.decode(r,void 0,n)}class Jc{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Zc(){}class Xc{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const el=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return On(r);n+r>e&&(t=On(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class tl{len;head;tail;states;constructor(){this.len=0,this.head=new Jc(Zc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Jc(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new il((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(sl,10,$c.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=$c.fromBigInt(e);return this._push(sl,t.length(),t)}uint64Number(e){return this._push(ya,ma(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=$c.fromBigInt(e).zzEncode();return this._push(sl,t.length(),t)}sint64Number(e){const t=$c.fromNumber(e).zzEncode();return this._push(sl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(nl,1,e?1:0)}fixed32(e){return this._push(al,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=$c.fromBigInt(e);return this._push(al,4,t.lo)._push(al,4,t.hi)}fixed64Number(e){const t=$c.fromNumber(e);return this._push(al,4,t.lo)._push(al,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Nc,4,e)}double(e){return this._push(Uc,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(nl,1,0):this.uint32(t)._push(ol,t,e)}string(e){const t=function(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(Gc,t,e):this._push(nl,1,0)}fork(){return this.states=new Xc(this),this.head=this.tail=new Jc(Zc,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Jc(Zc,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next;const t=(n=this.len,null!=globalThis.Buffer?On(n):el(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function nl(e,t,n){t[n]=255&e}function rl(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class il extends Jc{next;constructor(e,t){super(rl,e,t),this.next=void 0}}function sl(e,t,n){for(;0!==e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function al(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function ol(e,t,n){t.set(e,n)}function ul(e,t,n){t.set(e,n)}function dl(e,t,n){e.length<40?Gc(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(fr(e),n)}function cl(e,t){const n=new tl;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*ll(e,t,n){const r=Qc(e);yield*t.stream(r,void 0,"$",n)}function pl(e,t,n){return function(e,t,n,r,i){return{name:"message",type:2,encode:n,decode:r,stream:i}}(0,0,e,t,n)}null!=globalThis.Buffer&&(tl.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(ul,t,e),this},tl.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(dl,t,e),this});class hl extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var fl;!function(e){let t;e.codec=()=>(null==t&&(t=pl((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={publicKey:Nn(0),payloadType:Nn(0),payload:Nn(0),signature:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.publicKey`,value:e.bytes()};break;case 2:yield{field:`${n}.payloadType`,value:e.bytes()};break;case 3:yield{field:`${n}.payload`,value:e.bytes()};break;case 5:yield{field:`${n}.signature`,value:e.bytes()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return cl(t,e.codec())},e.decode=function(t,n){return Yc(t,e.codec(),n)},e.stream=function(t,n){return ll(t,e.codec(),n)}}(fl||(fl={}));class ml extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class yl{static createFromProtobuf=e=>{const t=fl.decode(e),n=Mo(t.publicKey);return new yl({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(null==t)throw new Error("Missing private key");const r=e.domain,i=e.codec,s=e.marshal(),a=bl(r,i,s),o=await t.sign(a.subarray(),n);return new yl({publicKey:t.publicKey,payloadType:i,payload:s,signature:o})};static openAndCertify=async(e,t,n)=>{const r=yl.createFromProtobuf(e);if(!await r.validate(t,n))throw new ml("Envelope signature is not valid for the given domain");return r};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:n,payload:r,signature:i}=e;this.publicKey=t,this.payloadType=n,this.payload=r,this.signature=i}marshal(){return null==this.marshaled&&(this.marshaled=fl.encode({publicKey:Fo(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Ln(this.marshal(),e.marshal())}async validate(e,t){const n=bl(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}}const bl=(e,t,n)=>{const r=fr(e),i=ga(r.byteLength),s=ga(t.length),a=ga(n.length);return new $n(i,r,s,t,a,n)},gl=Uint8Array.from([3,1]);var vl;!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=pl((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={multiaddr:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();t>>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();t>>>3==1?yield{field:`${n}.multiaddr`,value:e.bytes()}:e.skipType(7&t)}})),t),e.encode=function(t){return cl(t,e.codec())},e.decode=function(t,n){return Yc(t,e.codec(),n)},e.stream=function(t,n){return ll(t,e.codec(),n)}}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=pl((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(n.uint32(10),n.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(n.uint32(16),n.uint64(t.seq)),null!=t.addresses&&t.addresses.length>0)for(const r of t.addresses)n.uint32(26),e.AddressInfo.codec().encode(r,n);!1!==r.lengthDelimited&&n.ldelim()},(t,n,r={})=>{const i={peerId:Nn(0),seq:0n,addresses:[]},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:i.peerId=t.bytes();break;case 2:i.seq=t.uint64();break;case 3:if(null!=r.limits?.addresses&&i.addresses.length===r.limits.addresses)throw new hl('Decode error - repeated field "addresses" had too many elements');i.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:r.limits?.addresses$}));break;default:t.skipType(7&n)}}return i},function*(t,n,r,i={}){const s={addresses:0},a=null==n?t.len:t.pos+n;for(;t.pos<a;){const n=t.uint32();switch(n>>>3){case 1:yield{field:`${r}.peerId`,value:t.bytes()};break;case 2:yield{field:`${r}.seq`,value:t.uint64()};break;case 3:if(null!=i.limits?.addresses&&s.addresses===i.limits.addresses)throw new hl('Streaming decode error - repeated field "addresses" had too many elements');for(const n of e.AddressInfo.codec().stream(t,t.uint32(),`${r}.addresses[]`,{limits:i.limits?.addresses$}))yield{...n,index:s.addresses};s.addresses++;break;default:t.skipType(7&n)}}})),t),e.encode=function(t){return cl(t,e.codec())},e.decode=function(t,n){return Yc(t,e.codec(),n)},e.stream=function(t,n){return ll(t,e.codec(),n)}}(vl||(vl={}));class wl{static createFromProtobuf=e=>{const t=vl.decode(e),n=qo(xn(t.peerId)),r=(t.addresses??[]).map(e=>Pu(e.multiaddr));return new wl({peerId:n,multiaddrs:r,seqNumber:t.seq})};static DOMAIN="libp2p-peer-record";static CODEC=gl;peerId;multiaddrs;seqNumber;domain=wl.DOMAIN;codec=wl.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:n,seqNumber:r}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=r??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=vl.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return e instanceof wl&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const n=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(n),e.sort(n).every((e,n)=>t[n].equals(e)))}(this.multiaddrs,e.multiaddrs)}}function Tl(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const n of e)t.push(n);return t})();const t=[];for(const n of e)t.push(n);return t}class El extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}}async function xl(e,t,n,r){const i=new El(r?.errorMessage);null!=r?.errorCode&&(i.code=r.errorCode);const s=r?.errorEvent??"error";return!0===n?.aborted?Promise.reject(i):new Promise((a,o)=>{function u(){Sl(n,"abort",l),Sl(e,t,d),Sl(e,s,c)}const d=e=>{try{if(!1===r?.filter?.(e))return}catch(e){return u(),void o(e)}u(),a(e)},c=e=>{u(),e instanceof Error?o(e):o(e.detail??r?.error??new Error(`The "${r?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},l=()=>{u(),o(i)};Pl(n,"abort",l),Pl(e,t,d),Pl(e,s,c)})}function Pl(e,t,n){null!=e&&(Al(e)?e.addEventListener(t,n):e.addListener(t,n))}function Sl(e,t,n){null!=e&&(Al(e)?e.removeEventListener(t,n):e.removeListener(t,n))}function Al(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class Cl extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class kl{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new El)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Il{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((e,t)=>e&&!0===t.signal?.aborted,!0)&&(this.controller.abort(new El),this.cleanup())}async join(e={}){const t=new kl(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await $d(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}}function Dl(e,t){let n;const r=function(){clearTimeout(n),n=setTimeout(function(){n=void 0,e()},t)};return r.start=()=>{},r.stop=()=>{clearTimeout(n)},r}class Ml extends Ft{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Dl(this.emitEmpty.bind(this),1),this.emitIdle=Dl(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Cl;const n=new Il(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(e=>(this.safeDispatchEvent("success",{detail:{job:n,result:e}}),e)).catch(e=>{if("queued"===n.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===n){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:n,error:e}}),e})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new El)}),this.clear()}async onEmpty(e){0!==this.size&&await xl(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await xl(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await xl(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Md({objectMode:!0}),n=e=>{null!=e?this.abort():this.clear(),t.end(e)},r=e=>{null!=e.detail&&t.push(e.detail.result)},i=e=>{n(e.detail.error)},s=()=>{n()},a=()=>{n(new El("Queue aborted"))};this.addEventListener("success",r),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}}const Fl="lock:worker:request-read",Rl="lock:worker:abort-read-request",_l="lock:worker:release-read",Ll="lock:master:grant-read",Nl="lock:master:error-read",Ol="lock:worker:request-write",Bl="lock:worker:abort-write-request",Ul="lock:worker:release-write",jl="lock:master:grant-write",ql="lock:master:error-write",$l="lock:worker:finalize",zl="mortice",Vl={singleProcess:!1},Gl=(e,t,n,r,i,s,a,o,u)=>d=>{if(null==d.data)return;const c={type:d.data.type,name:d.data.name,identifier:d.data.identifier};c.type===i&&e.safeDispatchEvent(n,{detail:{name:c.name,identifier:c.identifier,handler:async()=>{t.postMessage({type:u,name:c.name,identifier:c.identifier}),await new Promise(e=>{const n=r=>{null!=r?.data&&r.data.type===o&&r.data.identifier===c.identifier&&(t.removeEventListener("message",n),e())};t.addEventListener("message",n)})},onError:e=>{t.postMessage({type:a,name:c.name,identifier:c.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),c.type===s&&e.safeDispatchEvent(r,{detail:{name:c.name,identifier:c.identifier}}),c.type===$l&&e.safeDispatchEvent("finalizeRequest",{detail:{name:c.name}})};class Kl{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(zl)}readLock(e){return this.sendRequest(Fl,Rl,Ll,Nl,_l,e)}writeLock(e){return this.sendRequest(Ol,Bl,jl,ql,Ul,e)}finalize(){this.channel.postMessage({type:$l,name:this.name}),this.channel.close()}async sendRequest(e,t,n,r,i,s){s?.signal?.throwIfAborted();const a=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((e,o)=>{const u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",u,{once:!0});const d=t=>{if(t.data?.identifier===a&&(t.data?.type===n&&(this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u),e(()=>{this.channel.postMessage({type:i,identifier:a,name:this.name})})),t.data.type===r)){this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u);const e=new Error;null!=t.data.error&&(e.message=t.data.error.message,e.name=t.data.error.name,e.stack=t.data.error.stack),o(e)}};this.channel.addEventListener("message",d)})}}const Hl=new Map;let Wl;function Ql(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}function Yl(e){if(null==Wl&&(Wl=(e=>{if(e=Object.assign({},Vl,e),Boolean(globalThis.document)||e.singleProcess){const e=new BroadcastChannel(zl),t=new Ft;return e.addEventListener("message",Gl(t,e,"requestReadLock","abortReadLockRequest",Fl,Rl,Nl,_l,Ll)),e.addEventListener("message",Gl(t,e,"requestWriteLock","abortWriteLockRequest",Ol,Bl,ql,Ul,jl)),t}return new Kl(e.name)})(e),!Ql(Wl))){const e=Wl;e.addEventListener("requestReadLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=Hl.get(n);if(null==i)return;const s=new AbortController,a=e=>{e.detail.name===n&&e.detail.identifier===r&&s.abort()};e.addEventListener("abortReadLockRequest",a),i.readLock({signal:s.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=Hl.get(n);if(null==i)return;const s=new AbortController,a=e=>{e.detail.name===n&&e.detail.identifier===r&&s.abort()};e.addEventListener("abortWriteLockRequest",a),i.writeLock({signal:s.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",e=>{const t=Hl.get(e.detail.name);null!=t&&t.finalize()})}return Wl}async function Jl(e,t){let n,r;const i=new Promise((e,t)=>{n=e,r=t}),s=()=>{r(new El)};return t?.signal?.addEventListener("abort",s,{once:!0}),e.add(async()=>{await new Promise(e=>{n(()=>{t?.signal?.removeEventListener("abort",s),e()})})},{signal:t?.signal}).catch(e=>{r(e)}),i}const Zl={name:"lock",concurrency:Infinity,singleProcess:!1,autoFinalize:!1};function Xl(e){const t=Object.assign({},Zl,e);return((e,t)=>{let n=Hl.get(e);if(null!=n)return n;const r=Yl(t);if(Ql(r))return n=r,Hl.set(e,n),n;const i=new Ml({concurrency:1});let s;return n={async readLock(e){if(null!=s)return Jl(s,e);s=new Ml({concurrency:t.concurrency,autoStart:!1});const n=s,r=Jl(s,e);return i.add(async()=>{n.start(),await n.onIdle().then(()=>{s===n&&(s=null)})}),r},writeLock:async e=>(s=null,Jl(i,e)),finalize:()=>{Hl.delete(e)},queue:i},Hl.set(e,n),!0===t.autoFinalize&&i.addEventListener("idle",()=>{n.finalize()},{once:!0}),n})(t.name,t)}const ep=new Float32Array([-0]),tp=new Uint8Array(ep.buffer);function np(e,t,n){ep[0]=e,t[n]=tp[0],t[n+1]=tp[1],t[n+2]=tp[2],t[n+3]=tp[3]}const rp=new Float64Array([-0]),ip=new Uint8Array(rp.buffer);function sp(e,t,n){rp[0]=e,t[n]=ip[0],t[n+1]=ip[1],t[n+2]=ip[2],t[n+3]=ip[3],t[n+4]=ip[4],t[n+5]=ip[5],t[n+6]=ip[6],t[n+7]=ip[7]}const ap=BigInt(Number.MAX_SAFE_INTEGER),op=BigInt(Number.MIN_SAFE_INTEGER);class up{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(0n===e)return dp;if(e<ap&&e>op)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let n=e>>32n,r=e-(n<<32n);return t&&(n=0n|~n,r=0n|~r,++r>cp&&(r=0n,++n>cp&&(n=0n))),new up(Number(r),Number(n))}static fromNumber(e){if(0===e)return dp;const t=e<0;t&&(e=-e);let n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new up(n,r)}static from(e){return"number"==typeof e?up.fromNumber(e):"bigint"==typeof e?up.fromBigInt(e):"string"==typeof e?up.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new up(e.low>>>0,e.high>>>0):dp}}const dp=new up(0,0);dp.toBigInt=function(){return 0n},dp.zzEncode=dp.zzDecode=function(){return this},dp.length=function(){return 1};const cp=4294967296n;function lp(e,t,n){const r=n;let i,s;for(let r=0;r<e.length;++r)i=e.charCodeAt(r),i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-r}function pp(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function hp(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class fp{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,pp(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw pp(this,4);return hp(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw pp(this,4);return 0|hp(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw pp(this,4);const e=(tp[0]=(t=this.buf)[n=this.pos],tp[1]=t[n+1],tp[2]=t[n+2],tp[3]=t[n+3],ep[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw pp(this,4);const e=(ip[0]=(t=this.buf)[n=this.pos],ip[1]=t[n+1],ip[2]=t[n+2],ip[3]=t[n+3],ip[4]=t[n+4],ip[5]=t[n+5],ip[6]=t[n+6],ip[7]=t[n+7],rp[0]);var t,n;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw pp(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){const e=this.bytes();return function(e,t,n){if(n-t<1)return"";let r;const i=[];let s,a=0;for(;t<n;)s=e[t++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=r?(a>0&&r.push(String.fromCharCode.apply(String,i.slice(0,a))),r.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw pp(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw pp(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new up(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw pp(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw pp(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw pp(this,8);const e=hp(this.buf,this.pos+=4),t=hp(this.buf,this.pos+=4);return new up(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=ba(this.buf,this.pos);return this.pos+=ma(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function mp(e,t,n){const r=function(e){return new fp(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(r,void 0,n)}class yp{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function bp(){}class gp{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const vp=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return On(r);n+r>e&&(t=On(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class wp{len;head;tail;states;constructor(){this.len=0,this.head=new yp(bp,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yp(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new xp((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Pp,10,up.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=up.fromBigInt(e);return this._push(Pp,t.length(),t)}uint64Number(e){return this._push(ya,ma(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=up.fromBigInt(e).zzEncode();return this._push(Pp,t.length(),t)}sint64Number(e){const t=up.fromNumber(e).zzEncode();return this._push(Pp,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Tp,1,e?1:0)}fixed32(e){return this._push(Sp,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=up.fromBigInt(e);return this._push(Sp,4,t.lo)._push(Sp,4,t.hi)}fixed64Number(e){const t=up.fromNumber(e);return this._push(Sp,4,t.lo)._push(Sp,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(np,4,e)}double(e){return this._push(sp,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Tp,1,0):this.uint32(t)._push(Ap,t,e)}string(e){const t=function(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(lp,t,e):this._push(Tp,1,0)}fork(){return this.states=new gp(this),this.head=this.tail=new yp(bp,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new yp(bp,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next;const t=(n=this.len,null!=globalThis.Buffer?On(n):vp(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function Tp(e,t,n){t[n]=255&e}function Ep(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class xp extends yp{next;constructor(e,t){super(Ep,e,t),this.next=void 0}}function Pp(e,t,n){for(;0!==e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function Sp(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function Ap(e,t,n){t.set(e,n)}function Cp(e,t,n){t.set(e,n)}function kp(e,t,n){e.length<40?lp(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(fr(e),n)}function Ip(e,t){const n=new wp;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var Dp,Mp,Fp,Rp,_p;function Lp(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function Np(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Lp("enum",Dp.VARINT,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())})}function Op(e,t){return Lp("message",Dp.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(wp.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Cp,t,e),this},wp.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(kp,t,e),this}),(_p=Dp||(Dp={}))[_p.VARINT=0]="VARINT",_p[_p.BIT64=1]="BIT64",_p[_p.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",_p[_p.START_GROUP=3]="START_GROUP",_p[_p.END_GROUP=4]="END_GROUP",_p[_p.BIT32=5]="BIT32";class Bp extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class Up extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function jp(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let n;return"RSA"===e.type&&(n=e.toMultihash()),jo(Mo(t.publicKey,n))}function qp(e,t,n){const r=new Map,i=BigInt(Date.now());for(const[e,n]of t.tags.entries())null!=n.expiry&&n.expiry<i||r.set(e,n);return{...t,id:jp(e,t),addresses:t.addresses.filter(({observed:e})=>null!=e&&e>Date.now()-n).map(({multiaddr:e,isCertified:t})=>({multiaddr:Pu(e),isCertified:t??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:r}}function $p(e,t){return null==e&&null==t||null!=e&&null!=t&&Ln(e,t)}function zp(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function Vp(e,t,n){if(e.size!==t.size)return!1;for(const[r,i]of e.entries()){const e=t.get(r);if(null==e)return!1;if(!n(i,e))return!1}return!0}!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={key:"",value:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),Rp.codec().encode(e.value,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={key:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.string();break;case 2:r.value=Rp.codec().decode(e,e.uint32(),{limits:n.limits?.value});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Op((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.addresses)for(const e of t.addresses)n.uint32(10),Fp.codec().encode(e,n);if(null!=t.protocols)for(const e of t.protocols)n.uint32(18),n.string(e);if(null!=t.publicKey&&(n.uint32(34),n.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(n.uint32(42),n.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[r,i]of t.metadata.entries())n.uint32(50),e.Peer$metadataEntry.codec().encode({key:r,value:i},n);if(null!=t.tags&&0!==t.tags.size)for(const[r,i]of t.tags.entries())n.uint32(58),e.Peer$tagsEntry.codec().encode({key:r,value:i},n);null!=t.updated&&(n.uint32(64),n.uint64Number(t.updated)),!1!==r.lengthDelimited&&n.ldelim()},(t,n,r={})=>{const i={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:if(null!=r.limits?.addresses&&i.addresses.length===r.limits.addresses)throw new Bp('Decode error - map field "addresses" had too many elements');i.addresses.push(Fp.codec().decode(t,t.uint32(),{limits:r.limits?.addresses$}));break;case 2:if(null!=r.limits?.protocols&&i.protocols.length===r.limits.protocols)throw new Bp('Decode error - map field "protocols" had too many elements');i.protocols.push(t.string());break;case 4:i.publicKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=r.limits?.metadata&&i.metadata.size===r.limits.metadata)throw new Up('Decode error - map field "metadata" had too many elements');const n=e.Peer$metadataEntry.codec().decode(t,t.uint32());i.metadata.set(n.key,n.value);break}case 7:{if(null!=r.limits?.tags&&i.tags.size===r.limits.tags)throw new Up('Decode error - map field "tags" had too many elements');const n=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:r.limits?.tags$value}});i.tags.set(n.key,n.value);break}case 8:i.updated=t.uint64Number();break;default:t.skipType(7&n)}}return i})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Mp||(Mp={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={multiaddr:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Fp||(Fp={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={value:0},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Rp||(Rp={}));const Gp="/",Kp=(new TextEncoder).encode(Gp),Hp=Kp[0];class Wp{_buf;constructor(e,t){if("string"==typeof e)this._buf=fr(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Hp)throw new Error("Invalid key")}toString(e="utf8"){return mr(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Wp(e.join(Gp))}static random(){return new Wp(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Wp(e):"function"==typeof e.uint8Array?new Wp(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Kp),this._buf[0]!==Hp){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Hp,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Hp;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),n=e.list();for(let e=0;e<t.length;e++){if(n.length<e+1)return!1;const r=t[e],i=n[e];if(r<i)return!0;if(r>i)return!1}return t.length<n.length}reverse(){return Wp.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Gp).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new Wp(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Gp)||(e+=Gp),e+=this.type(),new Wp(e)}parent(){const e=this.list();return new Wp(1===e.length?Gp:e.slice(0,-1).join(Gp))}child(e){return this.toString()===Gp?e:e.toString()===Gp?this:new Wp(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){return Wp.withNamespaces([...this.namespaces(),...(t=e.map(e=>e.namespaces()),[].concat(...t))]);var t}}const Qp="/peers/";function Yp(e){if(!Pt(e)||null==e.type)throw new We("Invalid PeerId");const t=e.toCID().toString();return new Wp(`${Qp}${t}`)}async function Jp(e,t,n,r,i){const s=new Map;for(const r of n){if(null==r)continue;if(r.multiaddr instanceof Uint8Array&&(r.multiaddr=Pu(r.multiaddr)),!xu(r.multiaddr))throw new We("Multiaddr was invalid");if(!await t(e,r.multiaddr,i))continue;const n=r.isCertified??!1,a=r.multiaddr.toString(),o=s.get(a);null!=o?r.isCertified=o.isCertified||n:s.set(a,{multiaddr:r.multiaddr,isCertified:n})}return[...s.values()].sort((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString())).map(({isCertified:t,multiaddr:n})=>{const r=n.getComponents().find(e=>e.code===eu)?.value;return e.equals(r)&&(n=n.decapsulate(Pu(`/p2p/${e}`))),{isCertified:t,multiaddr:n.bytes}})}async function Zp(e,t,n,r){if(null==t)throw new We("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new We("publicKey bytes do not match peer id publicKey bytes");const i=r.existingPeer?.peer;if(null!=i&&!e.equals(i.id))throw new We("peer id did not match existing peer id");let s,a=i?.addresses??[],o=new Set(i?.protocols??[]),u=i?.metadata??new Map,d=i?.tags??new Map,c=i?.peerRecordEnvelope;if("patch"===n&&(null==t.multiaddrs&&null==t.addresses||(a=[],null!=t.multiaddrs&&a.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&a.push(...t.addresses)),null!=t.protocols&&(o=new Set(t.protocols)),null!=t.metadata&&(u=Xp(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:eh})),null!=t.tags&&(d=Xp(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:th,map:nh})),null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)),"merge"===n){if(null!=t.multiaddrs&&a.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&a.push(...t.addresses),null!=t.protocols&&(o=new Set([...o,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,n]of e)null==n?u.delete(t):u.set(t,n);u=Xp([...u.entries()],{validate:eh})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),n=new Map(d);for(const[t,r]of e)null==r?n.delete(t):n.set(t,r);d=Xp([...n.entries()],{validate:th,map:nh})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}null!=i?.id.publicKey?s=Fo(i.id.publicKey):null!=t.publicKey?s=Fo(t.publicKey):null!=e.publicKey&&(s=Fo(e.publicKey));const l={addresses:await Jp(e,r.addressFilter??(async()=>!0),a,0,r),protocols:[...o.values()].sort((e,t)=>e.localeCompare(t)),metadata:u,tags:d,publicKey:s,peerRecordEnvelope:c};return l.addresses.forEach(e=>{e.observed=r.existingPeer?.peerPB.addresses?.find(e=>Ln(e.multiaddr,e.multiaddr))?.observed??Date.now()}),"RSA"!==e.type&&delete l.publicKey,l}function Xp(e,t){const n=new Map;for(const[n,r]of e)null!=r&&t.validate(n,r);for(const[r,i]of e.sort(([e],[t])=>e.localeCompare(t)))null!=i&&n.set(r,t.map?.(r,i)??i);return n}function eh(e,t){if("string"!=typeof e)throw new We("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new We("Metadata value must be a Uint8Array")}function th(e,t){if("string"!=typeof e)throw new We("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new We("Tag value must be an integer");if(t.value<0||t.value>100)throw new We("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new We("Tag ttl must be an integer");if(t.ttl<0)throw new We("Tag ttl must be between greater than 0")}}function nh(e,t){let n;null!=t.expiry&&(n=t.expiry),null!=t.ttl&&(n=BigInt(Date.now()+Number(t.ttl)));const r={value:t.value??0};return null!=n&&(r.expiry=n),r}function rh(e){const t=e.toString().split("/")[2];return $o(kn.parse(t,Ht))}function ih(e,t,n){return function(e,t,n){return qp(e,Mp.decode(t),n)}(rh(e),t,n)}class sh{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Rc({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return null==t&&(t={refs:0,lock:Xl({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,0===t.refs&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){const n=this.getLock(e);try{const r=await n.lock.readLock(t);return()=>{r(),this.maybeRemoveLock(e,n)}}catch(t){throw this.maybeRemoveLock(e,n),t}}async getWriteLock(e,t){const n=this.getLock(e);try{const r=await n.lock.writeLock(t);return()=>{r(),this.maybeRemoveLock(e,n)}}catch(t){throw this.maybeRemoveLock(e,n),t}}async has(e,t){try{return await this.load(e,t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Yp(e),t)}async load(e,t){const n=Yp(e),r=await this.datastore.get(n,t),i=Mp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new nt;return qp(e,i,this.peerId.equals(e)?Infinity:this.maxAddressAge)}async save(e,t,n){const r=await this.#s(e,n),i=await Zp(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#a(e,i,r)}async patch(e,t,n){const r=await this.#s(e,n),i=await Zp(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:r});return this.#a(e,i,r)}async merge(e,t,n){const r=await this.#s(e,n),i=await Zp(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:r});return this.#a(e,i,r)}async*all(e){for await(const{key:t,value:n}of this.datastore.query(function(e,t){return{prefix:Qp,filters:(e.filters??[]).map(e=>({key:n,value:r})=>e(ih(n,r,t))),orders:(e.orders??[]).map(e=>(n,r)=>e(ih(n.key,n.value,t),ih(r.key,r.value,t)))}}(e??{},this.maxAddressAge),e)){const r=rh(t);if(r.equals(this.peerId))continue;const i=Mp.decode(n);this.#i(r,i)?await this.datastore.delete(t,e):yield qp(r,i,this.peerId.equals(r)?Infinity:this.maxAddressAge)}}async#s(e,t){try{const n=Yp(e),r=await this.datastore.get(n,t),i=Mp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new nt;return{peerPB:i,peer:qp(e,i,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#a(e,t,n,r){t.updated=Date.now();const i=Mp.encode(t);return await this.datastore.put(Yp(e),i,r),{peer:qp(e,t,this.maxAddressAge),previous:n?.peer,updated:null==n||(s=t,a=n.peerPB,!(zp(s.addresses,a.addresses,(e,t)=>e.isCertified===t.isCertified&&!!Ln(e.multiaddr,t.multiaddr))&&zp(s.protocols,a.protocols,(e,t)=>e===t)&&$p(s.publicKey,a.publicKey)&&$p(s.peerRecordEnvelope,a.peerRecordEnvelope)&&Vp(s.metadata,a.metadata,(e,t)=>Ln(e,t))&&Vp(s.tags,a.tags,(e,t)=>e.value===t.value&&e.expiry===t.expiry)))};var s,a}#i(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;const n=t.updated<Date.now()-this.maxPeerAge,r=Date.now()-this.maxAddressAge,i=t.addresses.filter(e=>null!=e.observed&&e.observed>r);return n&&0===i.length}}class ah{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new sh(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(const n of this.store.all(t))e(n)}async all(e){return Tl(this.store.all(e))}async delete(e,t){const n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){const n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){const n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){const n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:e})=>e)}}async save(e,t,n){const r=await this.store.getWriteLock(e,n);try{const r=await this.store.save(e,t,n);return this.#o(e,r),r.peer}finally{r?.()}}async patch(e,t,n){const r=await this.store.getWriteLock(e,n);try{const r=await this.store.patch(e,t,n);return this.#o(e,r),r.peer}finally{r?.()}}async merge(e,t,n){const r=await this.store.getWriteLock(e,n);try{const r=await this.store.merge(e,t,n);return this.#o(e,r),r.peer}finally{r?.()}}async consumePeerRecord(e,t,n){const r=Pt(t)?t:Pt(t?.expectedPeer)?t.expectedPeer:void 0,i=Pt(t)||void 0===t?n:t,s=await yl.openAndCertify(e,wl.DOMAIN,i),a=$o(s.publicKey.toCID());if(!1===r?.equals(a))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",r,a),!1;const o=wl.createFromProtobuf(s.payload);let u;try{u=await this.get(a,i)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u?.peerRecordEnvelope){const e=yl.createFromProtobuf(u.peerRecordEnvelope),t=wl.createFromProtobuf(e.payload);if(t.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(e=>({isCertified:!0,multiaddr:e}))},i),!0}#o(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}class oh extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=oh.name;code=oh.code;constructor(e="Not Found"){super(e)}}function uh(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}function dh(e){const[t,n]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],r=[];return{peek:()=>t.next(),push:e=>{r.push(e)},next:()=>r.length>0?{done:!1,value:r.shift()}:t.next(),[n](){return this}}}function ch(e,t){let n=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const r of e)await t(r,n++)&&(yield r)}();const r=dh(e),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const a=t(i,n++);if("function"==typeof a.then)return async function*(){await a&&(yield i);for(const e of r)await t(e,n++)&&(yield e)}();const o=t;return function*(){!0===a&&(yield i);for(const e of r)o(e,n++)&&(yield e)}()}function lh(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const n=await Tl(e);yield*n.sort(t)}():function*(){const n=Tl(e);yield*n.sort(t)}()}function ph(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let n=0;if(!(t<1))for await(const r of e)if(yield r,n++,n===t)return}():function*(){let n=0;if(!(t<1))for(const r of e)if(yield r,n++,n===t)return}()}class hh{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:n,value:r}of e)await this.put(n,r,t),yield n}async*getMany(e,t={}){for await(const n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(const n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(t,n){e.push({key:t,value:n})},delete(e){t.push(e)},commit:async n=>{await uh(this.putMany(e,n)),e=[],await uh(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(null!=e.prefix){const t=e.prefix;n=ch(n,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>ch(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>lh(e,t),n)),null!=e.offset){let t=0;const r=e.offset;n=ch(n,()=>t++>=r)}return null!=e.limit&&(n=ph(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;n=ch(n,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>ch(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>lh(e,t),n)),null!=e.offset){const t=e.offset;let r=0;n=ch(n,()=>r++>=t)}return null!=e.limit&&(n=ph(n,e.limit)),n}}class fh extends hh{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();const n=this.data.get(e.toString());if(null==n)throw new oh;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(const[e,n]of this.data.entries())yield{key:new Wp(e),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(const e of this.data.keys())yield new Wp(e),t?.signal?.throwIfAborted()}}const mh=e=>({match:t=>{const n=t[0];return null!=n&&n.code===e&&null==n.value&&t.slice(1)}}),yh=(e,t)=>({match:n=>{const r=n[0];return r?.code===e&&null!=r.value&&(null==t||r.value===t)&&n.slice(1)}}),bh=e=>({match:t=>{const n=e.match(t);return!1===n?t:n}}),gh=(...e)=>({match:t=>{let n;for(const r of e){const e=r.match(t);!1!==e&&(null==n||e.length<n.length)&&(n=e)}return null!=n&&n}}),vh=(...e)=>({match:t=>{for(const n of e){const e=n.match(t);if(!1===e)return!1;t=e}return t}});function wh(...e){function t(t){if(null==t)return!1;let n=t.getComponents();for(const t of e){const e=t.match(n);if(!1===e)return!1;n=e}return n}return{matchers:e,matches:function(e){return!1!==t(e)},exactMatch:function(e){const n=t(e);return!1!==n&&0===n.length}}}const Th=wh(yh(eu)),Eh=yh(54),xh=yh(55),Ph=yh(56),Sh=yh(53),Ah=vh(yh(4),bh(yh(43))),Ch=vh(bh(yh(42)),yh(Xo),bh(yh(43))),kh=gh(Ah,Ch),Ih=gh(kh,Sh,Eh,xh,Ph),Dh=wh(gh(kh,vh(gh(Sh,Ph,Eh,xh),bh(yh(eu))))),Mh=wh(Ah),Fh=wh(Ch),Rh=vh(Ih,yh(6)),_h=vh(Ih,yh(273)),Lh=wh(vh(Rh,bh(yh(eu)))),Nh=vh(_h,mh(460),bh(yh(eu))),Oh=vh(_h,mh(461),bh(yh(eu))),Bh=gh(Nh,Oh),Uh=wh(Oh),jh=gh(Ih,Rh,_h,Nh,Oh),qh=gh(vh(jh,mh(477),bh(yh(eu)))),$h=wh(qh),zh=gh(vh(jh,mh(478),bh(yh(eu))),vh(jh,mh(tu),bh(yh(nu)),mh(477),bh(yh(eu)))),Vh=wh(zh),Gh=vh(_h,mh(280),bh(yh(ru)),bh(yh(ru)),bh(yh(eu))),Kh=wh(Gh),Hh=vh(Oh,mh(465),bh(yh(ru)),bh(yh(ru)),bh(yh(eu))),Wh=wh(Hh),Qh=gh(qh,zh,vh(Rh,bh(yh(eu))),vh(Bh,bh(yh(eu))),vh(Ih,bh(yh(eu))),Gh,Hh,yh(eu)),Yh=wh(Qh);var Jh;const Zh=wh(vh(bh(Qh),mh(su),(Jh=mh(iu),{match:e=>!1===Jh.match(e)&&e}),bh(yh(eu)))),Xh=wh(gh(vh(Qh,mh(su),mh(iu),bh(yh(eu))),vh(Qh,mh(iu),bh(yh(eu))),vh(mh(iu),bh(yh(eu))))),ef=864e13;class tf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ic({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=hd(e);let n=t.host;"ip4"!==t.type&&"ip6"!==t.type||null==t.sni||(n=t.sni);for(const e of this.mappings.values())if(e.domain===n)return!0;return!1}add(e,t){t.forEach(t=>{this.log("add DNS mapping %s to %s",t,e);const n=!0===Sd(t);this.mappings.set(t,{domain:e,verified:n,expires:n?ef-Date.now():0,lastVerified:n?ef-Date.now():void 0})})}remove(e){const t=hd(e);if("ip4"!==t.type&&"ip6"!==t.type)return!1;let n=!1;for(const[e,r]of this.mappings.entries())r.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",e,r.domain),this.mappings.delete(e),n=n||r.verified);return n}getAll(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n].multiaddr;if(!vd(r))continue;const i=hd(r);for(const[s,a]of this.mappings.entries()){if(i.host!==s)continue;const o=this.maybeAddSNIComponent(r,a.domain);null!=o&&(e.splice(n,1),n--,t.push({multiaddr:o,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){const n=e.getComponents();for(let e=0;e<n.length;e++)if(n[e].code===tu&&n[e+1]?.code!==nu)return n.splice(e+1,0,{name:"sni",code:nu,value:t}),Pu(n)}confirm(e,t){const n=hd(e);let r=n.host;"ip4"!==n.type&&"ip6"!==n.type||null==n.sni||(r=n.sni);let i=!1;for(const[e,n]of this.mappings.entries())n.domain===r&&(this.log("marking %s to %s DNS mapping as verified",e,n.domain),i=n.verified,n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now());return i}unconfirm(e,t){const n=hd(e);if("ip4"!==n.type&&"ip6"!==n.type)return!1;const r=n.sni??n.host;let i=!1;for(const[e,n]of this.mappings.entries())n.domain===r&&(this.log("removing verification of %s to %s DNS mapping",e,n.domain),i=i||n.verified,n.verified=!1,n.expires=Date.now()+t);return i}}class nf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ic({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=hd(e);if("ip4"!==t.type&&"ip6"!==t.type)return!1;for(const e of this.mappings.values())for(const n of e)if(n.externalIp===t.host)return!0;return!1}add(e,t,n,r=t,i="tcp"){const s=`${e}-${t}-${i}`,a=this.mappings.get(s)??[],o={internalIp:e,internalPort:t,externalIp:n,externalPort:r,externalFamily:Jo(n)?4:6,protocol:i,verified:!1,expires:0};a.push(o),this.mappings.set(s,a)}remove(e){const t=hd(e);if("ip4"!==t.type&&"ip6"!==t.type)return!1;let n=!1;for(const[e,r]of this.mappings.entries()){for(let e=0;e<r.length;e++){const i=r[e];i.externalIp===t.host&&i.externalPort===t.port&&i.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",i.externalIp,i.externalPort,t.host,t.port,t.protocol),n=n||i.verified,r.splice(e,1),e--)}0===r.length&&this.mappings.delete(e)}return n}getAll(e){const t=[];for(const{multiaddr:n}of e){if(!vd(n))continue;const e=hd(n);if("ip4"!==e.type&&"ip6"!==e.type)continue;let r;if("tcp"===e.protocol?r=`${e.host}-${e.port}-tcp`:"udp"===e.protocol&&(r=`${e.host}-${e.port}-udp`),null==r)continue;const i=this.mappings.get(r);if(null!=i)for(const e of i)t.push({multiaddr:this.maybeOverrideIp(n,e.externalIp,e.externalFamily,e.protocol,e.externalPort),verified:e.verified,type:"ip-mapping",expires:e.expires,lastVerified:e.lastVerified})}return t}maybeOverrideIp(e,t,n,r,i){const s=e.getComponents(),a=s.findIndex(e=>4===e.code||e.code===Xo),o=s.findIndex(e=>e.name===r);return a>-1&&o>-1?(s[a].value=t,s[a].code=4===n?4:Xo,s[o].value=`${i}`,Pu(s)):e}confirm(e,t){if(!vd(e))return!1;const n=hd(e);let r=!1;for(const e of this.mappings.values())for(const i of e)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),r=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return r}unconfirm(e,t){if(!vd(e))return!1;const n=hd(e);let r=!1;for(const e of this.mappings.values())for(let i=0;i<e.length;i++){const s=e[i];s.externalIp===n.host&&s.externalPort===n.port&&s.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",s.externalIp,s.externalPort,n.host,n.port,n.protocol),r=r||s.verified,s.verified=!1,s.expires=Date.now()+t)}return r}}class rf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ic({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(const t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Ad(e)||function(e){try{const t=hd(e);switch(t.type){case"ip4":return t.host.startsWith("169.254.");case"ip6":return t.host.toLowerCase().startsWith("fe80");default:return!1}}catch(e){return!1}}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:Pu(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){const t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){const n=e.toString(),r=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},i=r.verified;return r.verified=!0,r.expires=Date.now()+t,r.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,r),i}}class sf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ic({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(Ad(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};const n=this.toKey(e);let r=this.addresses.get(n);return null==r&&(r={verified:!vd(e),expires:0},this.addresses.set(n,r)),{multiaddr:e,verified:r.verified,type:"transport",expires:r.expires,lastVerified:r.lastVerified}}has(e){const t=this.toKey(e);return this.addresses.has(t)}remove(e){const t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){const n=this.toKey(e),r=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},i=r.verified;return r.verified=!0,r.expires=Date.now()+t,r.lastVerified=Date.now(),this.addresses.set(n,r),i}unconfirm(e,t){const n=this.toKey(e),r=this.addresses.get(n)??{verified:!1,expires:0},i=r.verified;return r.verified=!1,r.expires=Date.now()+t,this.addresses.set(n,r),i}toKey(e){if(!vd(e))return e.toString();const t=hd(e);return`${t.host}-${t.port}-${t.protocol}`}}const af=e=>e;function of(e,t){const n=e.getComponents().findLast(e=>e.code===eu)?.value;return null!=n&&Uo(n).equals(t)&&(e=e.decapsulate(Pu(`/p2p/${t.toString()}`))),e}class uf{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){const{listen:n=[],announce:r=[],appendAnnounce:i=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(e=>e.toString()),this.announce=new Set(r.map(e=>e.toString())),this.appendAnnounce=new Set(i.map(e=>e.toString())),this.observed=new rf(e,t),this.dnsMappings=new tf(e,t),this.ipMappings=new nf(e,t),this.transportAddresses=new sf(e,t),this.announceFilter=t.announceFilter??af,this.observedAddressFilter=pd(1024),this.addressVerificationTTL=t.addressVerificationTTL??6e5,this.addressVerificationRetry=t.addressVerificationRetry??3e5,this._updatePeerStoreAddresses=Ld(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAddresses().map(e=>e.getComponents().findLast(e=>e.code===eu)?.value===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(e=>{this.log.error("error updating addresses - %e",e)})}getListenAddrs(){return Array.from(this.listen).map(e=>Pu(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Pu(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Pu(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){const t=hd(e);let n;switch(t.type){case"ip4":n=`${t.host}:${t.port}`;break;case"ip6":n=`[${t.host}]:${t.port}`;break;default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=of(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=of(e,this.components.peerId);let n=!0;("transport"===t?.type||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("dns-mapping"===t?.type||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("ip-mapping"===t?.type||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),("observed"===t?.type||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=of(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){const e=new Set,t=this.getAddressesWithMetadata().filter(t=>{if(!t.verified)return!1;const n=t.multiaddr.toString();return!e.has(n)&&(e.add(n),!0)}).map(e=>e.multiaddr);return this.announceFilter(t.map(e=>{const t=Pu(e),n=t.getComponents().pop();return n?.value===this.components.peerId.toString()?t:t.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(t=>{t.updateAnnounceAddrs(e)}),e.map(e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(e=>this.transportAddresses.get(e,this.addressVerificationTTL)));const n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(e=>{e.updateAnnounceAddrs(n)}),t=t.concat(n.map(e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Pu(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.add(e,t,n,r,i),this.observed.removePrefixed(`/ip${Jo(n)?4:6}/${n}/${i}/${r}`)}removePublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.remove(Pu(`/ip${Jo(n)?4:6}/${n}/${i}/${r}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;if(!vd(e))return!1;const t=hd(e);if("ip4"!==t.type||!0===Sd(t.host))return!1;const n=this.components.transportManager.getListeners(),r=[e=>$h.exactMatch(e)||Vh.exactMatch(e),e=>Lh.exactMatch(e),e=>Uh.exactMatch(e)];for(const i of r){if(!i(e))continue;const r=n.filter(e=>e.getAddrs().filter(e=>"ip4"===hd(e).type&&i(e)).length>0);if(1!==r.length)continue;const s=r[0].getAddrs().filter(e=>!gd(e)).pop();if(null==s)continue;const a=hd(s);return null!=a.port&&(this.observed.remove(e),this.ipMappings.add(a.host,a.port,t.host,t.port,t.protocol),!0)}return!1}}var df;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(df||(df={}));class cf extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class lf extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class pf extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class hf extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class ff extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class mf extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class yf extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class bf extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class gf extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class vf extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class wf extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Tf extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class Ef extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class xf extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class Pf extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class Sf extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class Af extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}class Cf{components={};_started=!1;constructor(e={}){this.components={};for(const[t,n]of Object.entries(e))this.components[t]=n;null==this.components.logger&&(this.components.logger=Wu())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>Ct(e)).map(async t=>{await(t[e]?.())}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const kf=["metrics","connectionProtector","dns"],If=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Df(e){return Array.isArray(e?.[Rt])?e[Rt]:[]}function Mf(e){return Array.isArray(e?.[_t])?e[_t]:[]}function Ff(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function Rf(e={}){return null==e.denyDialMultiaddr&&(e.denyDialMultiaddr=e=>!!$h.matches(e)||Ad(e)),e}class _f extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Lf(e){if(Pt(e))return{peerId:e,multiaddrs:[]};let t,n=Array.isArray(e)?e:[e];if(n.length>0){const e=n[0].getComponents().findLast(e=>e.code===eu)?.value;t=null==e?void 0:Uo(e),n.forEach(e=>{if(!xu(e))throw new it("Invalid multiaddr");const n=e.getComponents().findLast(e=>e.code===eu)?.value;if(null==n){if(null!=t)throw new We("Multiaddrs must all have the same peer id or have no peer id")}else{const e=Uo(n);if(!0!==t?.equals(e))throw new We("Multiaddrs must all have the same peer id or have no peer id")}})}return n=n.filter(e=>!Th.exactMatch(e)),{peerId:t,multiaddrs:n}}const Nf=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Of(e){const t=hd(e);let n=t.cidr;if("ip4"!==t.type&&"ip6"!==t.type)throw new We(`Multiaddr ${e} was not an IPv4 or IPv6 address`);if(null==n)switch(t.type){case"ip4":n=32;break;case"ip6":n=128;break;default:throw new We(`Multiaddr ${e} was not an IPv4 or IPv6 address`)}return new bd(t.host,n)}function Bf(e){return!Zh.exactMatch(e)}function Uf(e,t,n){if(null==e||null==t)return;const r=t.sort((e,t)=>e.direct?-1:t.direct?1:0).find(e=>null==e.limits);return null==r||r.direct||null==n?r:n.some(e=>Bf(e))?void 0:r}class jf{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(e=>Of(e)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;const r=new Xu;for(const t of e){const e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{const t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce((e,t)=>e+t.value,0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags - %e",e)}}}const i=this.sortConnections(e,r),s=Math.max(t-n,0),a=[];for(const e of i)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some(t=>{if(vd(e.remoteAddr)){const n=hd(e.remoteAddr);return t.contains(n.host)}return!0})||a.push(e),a.length===s)break;await Promise.all(a.map(async e=>{await async function(e,t){const n=e?.streams?.map(e=>e.protocol)??[],r=t?.closableProtocols??Nf;if(!(n.filter(e=>null!=e&&!r.includes(e)).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((e,t)=>{const n=e.timeline.open,r=t.timeline.open;return n<r?1:n>r?-1:0}).sort((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0).sort((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0).sort((e,n)=>{const r=t.get(e.remotePeer)??0,i=t.get(n.remotePeer)??0;return r>i?1:r<i?-1:0})}}const qf=1e4,$f="last-dial-failure",zf="last-dial-success";function Vf(e,t){const n=Lh.exactMatch(e.multiaddr),r=Lh.exactMatch(t.multiaddr);if(n&&!r)return-1;if(!n&&r)return 1;const i=Vh.exactMatch(e.multiaddr),s=Vh.exactMatch(t.multiaddr);if(i&&!s)return-1;if(!i&&s)return 1;const a=$h.exactMatch(e.multiaddr),o=$h.exactMatch(t.multiaddr);if(a&&!o)return-1;if(!a&&o)return 1;const u=Xh.exactMatch(e.multiaddr),d=Xh.exactMatch(t.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;const c=Kh.exactMatch(e.multiaddr),l=Kh.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const p=Wh.exactMatch(e.multiaddr),h=Wh.exactMatch(t.multiaddr);return p&&!h?-1:!p&&h?1:0}function Gf(e,t){const n=gd(e.multiaddr),r=gd(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function Kf(e,t){const n=Ad(e.multiaddr),r=Ad(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function Hf(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function Wf(e,t){const n=Zh.exactMatch(e.multiaddr),r=Zh.exactMatch(t.multiaddr);return n&&!r?1:!n&&r?-1:0}class Qf extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"}var Yf=Td(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new i(r,s||e,a),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],o]:e._events[u].push(o):(e._events[u]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),o.prototype.eventNames=function(){var e,r,i=[];if(0===this._eventsCount)return i;for(r in e=this._events)t.call(e,r)&&i.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,i=t.length,s=new Array(i);r<i;r++)s[r]=t[r].fn;return s},o.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},o.prototype.emit=function(e,t,r,i,s,a){var o=n?n+e:e;if(!this._events[o])return!1;var u,d,c=this._events[o],l=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,i),!0;case 5:return c.fn.call(c.context,t,r,i,s),!0;case 6:return c.fn.call(c.context,t,r,i,s,a),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var p,h=c.length;for(d=0;d<h;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,r);break;case 4:c[d].fn.call(c[d].context,t,r,i);break;default:if(!u)for(p=1,u=new Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},o.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},o.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},o.prototype.removeListener=function(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn!==t||i&&!o.once||r&&o.context!==r||a(this,s);else{for(var u=0,d=[],c=o.length;u<c;u++)(o[u].fn!==t||i&&!o[u].once||r&&o[u].context!==r)&&d.push(o[u]);d.length?this._events[s]=1===d.length?d[0]:d:a(this,s)}return this},o.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&a(this,t):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,e.exports=o}),Jf=Yf;class Zf extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Zf)}}const Xf=e=>e.reason??new DOMException("This operation was aborted.","AbortError");class em{#u=[];enqueue(e,t){const{priority:n=0,id:r}=t??{},i={priority:n,id:r,run:e};if(0===this.size||this.#u[this.size-1].priority>=n)return void this.#u.push(i);const s=function(e,t,n){let r=0,i=e.length;for(;i>0;){const s=Math.trunc(i/2);let a=r+s;n(e[a],t)<=0?(r=++a,i-=s+1):i=s}return r}(this.#u,i,(e,t)=>t.priority-e.priority);this.#u.splice(s,0,i)}setPriority(e,t){const n=this.#u.findIndex(t=>t.id===e);if(-1===n)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[r]=this.#u.splice(n,1);this.enqueue(r.run,{priority:t,id:e})}dequeue(){const e=this.#u.shift();return e?.run}filter(e){return this.#u.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this.#u.length}}class tm extends Jf{#d;#c;#l=0;#p;#h=!1;#f=!1;#m;#y=0;#b=0;#g;#v;#w;#T=[];#E=0;#u;#x;#P=0;#S;#A;#C=1n;#k=new Map;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:em,strict:!1,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&0===e.interval)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#d=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#c=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#p=e.intervalCap,this.#m=e.interval,this.#w=e.strict,this.#u=new e.queueClass,this.#x=e.queueClass,this.concurrency=e.concurrency,void 0!==e.timeout&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#A=!1===e.autoStart,this.#I()}#D(e){for(;this.#E<this.#T.length;){const t=this.#T[this.#E];if(!(void 0!==t&&e-t>=this.#m))break;this.#E++}(this.#E>100&&this.#E>this.#T.length/2||this.#E===this.#T.length)&&(this.#T=this.#T.slice(this.#E),this.#E=0)}#M(e){this.#w?this.#T.push(e):this.#l++}#F(){this.#w?this.#T.length>this.#E&&this.#T.pop():this.#l>0&&this.#l--}#R(){return this.#T.length-this.#E}get#_(){return!!this.#c||(this.#w?this.#R()<this.#p:this.#l<this.#p)}get#L(){return this.#P<this.#S}#N(){this.#P--,0===this.#P&&this.emit("pendingZero"),this.#O(),this.emit("next")}#B(){this.#v=void 0,this.#U(),this.#j()}#q(e){if(this.#w){if(this.#D(e),this.#R()>=this.#p){const t=this.#T[this.#E],n=this.#m-(e-t);return this.#$(n),!0}return!1}if(void 0===this.#g){const t=this.#y-e;if(!(t<0))return this.#$(t),!0;if(this.#b>0){const t=e-this.#b;if(t<this.#m)return this.#$(this.#m-t),!0}this.#l=this.#d?this.#P:0}return!1}#$(e){void 0===this.#v&&(this.#v=setTimeout(()=>{this.#B()},e))}#z(){this.#g&&(clearInterval(this.#g),this.#g=void 0)}#V(){this.#v&&(clearTimeout(this.#v),this.#v=void 0)}#O(){if(0===this.#u.size){if(this.#z(),this.emit("empty"),0===this.#P){if(this.#V(),this.#w&&this.#E>0){const e=Date.now();this.#D(e)}this.emit("idle")}return!1}let e=!1;if(!this.#A){const t=Date.now(),n=!this.#q(t);if(this.#_&&this.#L){const r=this.#u.dequeue();this.#c||(this.#M(t),this.#G()),this.emit("active"),r(),n&&this.#j(),e=!0}}return e}#j(){this.#c||void 0!==this.#g||this.#w||(this.#g=setInterval(()=>{this.#U()},this.#m),this.#y=Date.now()+this.#m)}#U(){this.#w||(0===this.#l&&0===this.#P&&this.#g&&this.#z(),this.#l=this.#d?this.#P:0),this.#K(),this.#G()}#K(){for(;this.#O(););}get concurrency(){return this.#S}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#S=e,this.#K()}setPriority(e,t){if("number"!=typeof t||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#u.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#C++).toString()},new Promise((n,r)=>{const i=Symbol(`task-${t.id}`);this.#u.enqueue(async()=>{let s;this.#P++,this.#k.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});try{try{t.signal?.throwIfAborted()}catch(e){throw this.#H(),this.#k.delete(i),e}this.#b=Date.now();let r=e({signal:t.signal});if(t.timeout&&(r=function(e,t){const{milliseconds:n,fallback:r,message:i,customTimers:s={setTimeout:setTimeout,clearTimeout:clearTimeout},signal:a}=t;let o,u;const d=new Promise((t,d)=>{if("number"!=typeof n||1!==Math.sign(n))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(a?.aborted)return void d(Xf(a));if(a&&(u=()=>{d(Xf(a))},a.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Zf;o=s.setTimeout.call(void 0,()=>{if(r)try{t(r())}catch(e){d(e)}else"function"==typeof e.cancel&&e.cancel(),!1===i?t():i instanceof Error?d(i):(c.message=i??`Promise timed out after ${n} milliseconds`,d(c))},n)}).finally(()=>{d.clear(),u&&a&&a.removeEventListener("abort",u)});return d.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},d}(Promise.resolve(r),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#P} running, ${this.#u.size} waiting)`})),t.signal){const{signal:e}=t;r=Promise.race([r,new Promise((t,n)=>{s=()=>{n(e.reason)},e.addEventListener("abort",s,{once:!0})})])}const a=await r;n(a),this.emit("completed",a)}catch(e){r(e),this.emit("error",e)}finally{s&&t.signal?.removeEventListener("abort",s),this.#k.delete(i),queueMicrotask(()=>{this.#N()})}},t),this.emit("add"),this.#O()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#A?(this.#A=!1,this.#K(),this):this}pause(){this.#A=!0}clear(){this.#u=new this.#x,this.#z(),this.#W(),this.emit("empty"),0===this.#P&&(this.#V(),this.emit("idle")),this.emit("next")}async onEmpty(){0!==this.#u.size&&await this.#Q("empty")}async onSizeLessThan(e){this.#u.size<e||await this.#Q("next",()=>this.#u.size<e)}async onIdle(){0===this.#P&&0===this.#u.size||await this.#Q("idle")}async onPendingZero(){0!==this.#P&&await this.#Q("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#Q("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#Q("rateLimitCleared")}onError(){return new Promise((e,t)=>{const n=e=>{this.off("error",n),t(e)};this.on("error",n)})}async#Q(e,t){return new Promise(n=>{const r=()=>{t&&!t()||(this.off(e,r),n())};this.on(e,r)})}get size(){return this.#u.size}sizeBy(e){return this.#u.filter(e).length}get pending(){return this.#P}get isPaused(){return this.#A}#I(){this.#c||(this.on("add",()=>{this.#u.size>0&&this.#G()}),this.on("next",()=>{this.#G()}))}#G(){this.#c||this.#f||(this.#f=!0,queueMicrotask(()=>{this.#f=!1,this.#W()}))}#H(){this.#c||(this.#F(),this.#G())}#W(){const e=this.#h;if(this.#c||0===this.#u.size)return void(e&&(this.#h=!1,this.emit("rateLimitCleared")));let t;if(this.#w){const e=Date.now();this.#D(e),t=this.#R()}else t=this.#l;const n=t>=this.#p;n!==e&&(this.#h=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#h}get isSaturated(){return this.#P===this.#S&&this.#u.size>0||this.isRateLimited&&this.#u.size>0}get runningTasks(){return[...this.#k.values()].map(e=>({...e}))}}function nm(e){const t=[om.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function rm(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map(e=>({name:e.name,type:om[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:om[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?mr(e.data):e.data}))}}function im(e,t={}){const n=new tm({concurrency:t.queryConcurrency??4});return async(t,r={})=>{const i=r?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",t),nm(r.types).forEach(e=>{s.append("type",om[e])}),r.onProgress?.(new _f("dns:query",t)),i?.("GET %s",`${e}?${s}`);const a=await n.add(async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:r?.signal});if(i?.("GET %s %d",t.url,t.status),200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const n=rm(await t.json());return r.onProgress?.(new _f("dns:response",n)),n},{signal:r.signal});if(null==a)throw new Error("No DNS response received");return a}}class sm{lru;constructor(e){this.lru=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,n=Object.create(null),r=Object.create(null);function i(i,s){n[i]=s,++t>=e&&(t=0,r=n,n=Object.create(null))}return{has:function(e){return void 0!==n[e]||void 0!==r[e]},remove:function(e){void 0!==n[e]&&(n[e]=void 0),void 0!==r[e]&&(r[e]=void 0)},get:function(e){var t=n[e];return void 0!==t?t:void 0!==(t=r[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==n[e]?n[e]=t:i(e,t)},clear:function(){n=Object.create(null),r=Object.create(null)}}}(e)}get(e,t){let n=!0;const r=[];for(const i of t){const t=this.getAnswers(e,i);if(0===t.length){n=!1;break}r.push(...t)}if(n)return rm({answers:r})}getAnswers(e,t){const n=`${e.toLowerCase()}-${t}`,r=this.lru.get(n);if(null!=r){const e=r.filter(e=>e.expires>Date.now()).map(({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:om[t.type]}));return 0===e.length&&this.lru.remove(n),e}return[]}add(e,t){const n=`${e.toLowerCase()}-${t.type}`,r=this.lru.get(n)??[];r.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(n,r)}remove(e,t){const n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}}class am{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=new sm(e.cacheSize??1e3),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=t}),null==this.resolvers["."]&&(this.resolvers["."]=[im("https://cloudflare-dns.com/dns-query"),im("https://dns.google/resolve")])}async query(e,t={}){const n=nm(t.types),r=!1!==t.cached?this.cache.get(e,n):void 0;if(null!=r)return t.onProgress?.(new _f("dns:cache",r)),r;const i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(const r of s){if(!0===t.signal?.aborted)break;try{const i=await r(e,{...t,logger:this.logger,types:n});for(const t of i.Answer)this.cache.add(e,t);return i}catch(e){a.push(e),t.onProgress?.(new _f("dns:error",e))}}throw new Qf(a,`DNS lookup of ${e} ${n} failed`)}}var om;!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(om||(om={}));const um=new class{dns;canResolve(e){return e.getComponents().some(({name:e})=>"dnsaddr"===e)}async resolve(e,t){const n=e.getComponents().find(e=>"dnsaddr"===e.name)?.value;if(null==n)return[e];const r=this.getDNS(t),i=await r.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[om.TXT]}),s=e.getComponents().find(e=>"p2p"===e.name)?.value,a=[];for(const e of i.Answer){const t=e.data.replace(/["']/g,"").trim().split("=")[1];null!=t&&(null==s||t.includes(s))&&a.push(Pu(t))}return a}getDNS(e){return null!=e.dns?e.dns:(null==this.dns&&(this.dns=function(e={}){return new am(e)}()),this.dns)}};async function dm(e,t,n){const r=n.depth??0;if(r>(n.maxRecursiveDepth??32))throw new Af("Max recursive depth reached");let i=!1;const s=[];for(const a of Object.values(t))if(a.canResolve(e)){i=!0;const o=await a.resolve(e,n);for(const e of o)s.push(...await dm(e,t,{...n,depth:r+1}))}return!1===i&&s.push(e),s}const cm={maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:um}};class lm{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??cm.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??cm.maxDialQueueLength,this.dialTimeout=t.dialTimeout??cm.dialTimeout,this.connections=t.connections??new Xu,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??cm.resolvers,this.shutDownController=new AbortController,this.queue=new Pc({concurrency:t.maxParallelDials??cm.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",e=>{e.detail?.error.name!==Ge.name&&this.log.error("error in dial queue - %e",e.detail.error)})}start(){this.shutDownController=new AbortController}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:n,multiaddrs:r}=Lf(e);if(null!=n&&!0!==t.force){const e=Uf(n,this.connections.get(n),r);if(null!=e)return this.log("already connected to %a",e.remoteAddr),t.onProgress?.(new _f("dial-queue:already-connected")),e}const i=this.queue.queue.find(e=>{if(!0===n?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of r)if(t.has(e.toString()))return!0;return!1});if(null!=i){this.log("joining existing dial target for %p",n);for(const e of r)i.options.multiaddrs.add(e.toString());return t.onProgress?.(new _f("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new pt("Dial queue is full");return this.log("creating dial target for %p",n,r.map(e=>e.toString())),t.onProgress?.(new _f("dial-queue:add-to-dial-queue")),this.queue.add(async e=>{e.onProgress?.(new _f("dial-queue:start-dial"));const t=Jd([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}},{peerId:n,priority:t.priority??wm,multiaddrs:new Set(r.map(e=>e.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){const n=e.peerId,r=e.multiaddrs,i=new Set;let s=0===e.multiaddrs.size,a=0,o=0;const u=[];for(this.log("starting dial to %p",n);s||r.size>0;){o++,s=!1;const d=[],c=new Set(e.multiaddrs);r.clear(),this.log("calculating addrs to dial %p from %s",n,[...c]);const l=await this.calculateMultiaddrs(n,c,{...e,signal:t});for(const e of l)i.has(e.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",e.multiaddr,n):d.push(e);this.log("%s dial to %p with %s",1===o?"starting":"continuing",n,d.map(e=>e.multiaddr.toString())),e?.onProgress?.(new _f("dial-queue:calculated-addresses",d));for(const r of d){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new pt("Peer had more than maxPeerAddrsToDial");a++;try{const i=await this.components.transportManager.dial(r.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",r.multiaddr);try{await this.components.peerStore.merge(i.remotePeer,{multiaddrs:[i.remoteAddr],metadata:{[zf]:fr(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p - %e",n,e)}return i}catch(e){if(this.log.error("dial failed to %a - %e",r.multiaddr,e),i.add(r.multiaddr.toString()),null!=n)try{await this.components.peerStore.merge(n,{metadata:{[$f]:fr(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p - %e",n,e)}if(t.aborted)throw new ct(e.message);u.push(e)}}}if(1===u.length)throw u[0];throw new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){const r=[...t].map(e=>({multiaddr:Pu(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new pt("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new bf("The dial request is blocked by gater.allowDialPeer");if(0===r.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);r.push(...t.addresses),this.log("loaded multiaddrs for %p",e,r.map(({multiaddr:e})=>e.toString()))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===r.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,r.map(({multiaddr:e})=>e.toString())),r.push(...t.multiaddrs.map(e=>({multiaddr:e,isCertified:!1})))}catch(t){"NoPeerRoutersError"===t.name?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}let i=(await Promise.all(r.map(async e=>{const t=await dm(e.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map(e=>({multiaddr:e,isCertified:!1}))}))).flat();if(null!=e){const t=`/p2p/${e.toString()}`;i=i.map(e=>{const n=e.multiaddr.getComponents().pop();return"p2p"!==n?.name?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e})}const s=i.filter(t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const n=t.multiaddr.getComponents().findLast(e=>e.code===eu)?.value;return null==e||null==n||e.equals(n)}),a=new Map;for(const e of s){const t=e.multiaddr.toString(),n=a.get(t);null==n?a.set(t,e):n.isCertified=n.isCertified||e.isCertified||!1}const o=[...a.values()];if(0===o.length)throw new wf("The dial request has no valid addresses");const u=[];for(const e of o)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||u.push(e);const d=null==this.addressSorter?u.sort(Vf).sort(Hf).sort(Wf).sort(Kf).sort(Gf):u.sort(this.addressSorter);if(0===d.length)throw new bf("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:e})=>e.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:e})=>e.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const n=await this.calculateMultiaddrs(void 0,new Set(e.map(e=>e.toString())),t);return!1!==t.runOnLimitedConnection||null!=n.find(e=>!Zh.matches(e.multiaddr))}catch{}return!1}}const pm=Object.prototype.toString,hm=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function fm(e,t,{min:n=0,allowInfinity:r=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be ≥ ${n}.`)}}class mm extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}function ym(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function bm({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){const s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof mm)throw s.originalError;const a=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,o=i.maxRetryTime??Number.POSITIVE_INFINITY,u=Object.freeze({error:s,attemptNumber:t,retriesLeft:a,retriesConsumed:n});if(await i.onFailedAttempt(u),ym(r,o)<=0)throw s;const d=await i.shouldConsumeRetry(u),c=ym(r,o);if(c<=0||a<=0)throw s;if(s instanceof TypeError&&!function(e){const t=e&&(e=>"[object Error]"===pm.call(e))(e)&&"TypeError"===e.name&&"string"==typeof e.message;if(!t)return!1;const{message:n,stack:r}=e;return"Load failed"===n?void 0===r||"__sentry_captured__"in e:!!n.startsWith("error sending request for url")||!!("Failed to fetch"===n||n.startsWith("Failed to fetch (")&&n.endsWith(")"))||hm.has(n)}(s)){if(d)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(u))throw s;if(!d)return i.signal?.throwIfAborted(),!1;const l=function(e,t){const n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1;let i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}(n,i),p=Math.min(l,c);return i.signal?.throwIfAborted(),p>0&&await new Promise((e,t)=>{const n=()=>{clearTimeout(r),i.signal?.removeEventListener("abort",n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener("abort",n),e()},p);i.unref&&r.unref?.(),i.signal?.addEventListener("abort",n,{once:!0})}),i.signal?.throwIfAborted(),!0}class gm{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new xc({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",e=>{this.maybeReconnect(e.detail).catch(t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)})})}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);vm(t)&&(this.queue.has(e)||this.queue.add(async t=>{await async function(e,t={}){if(function(e){if("number"==typeof e){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==e)throw new TypeError("Expected `retries` to be a number or Infinity.")}((t={...t}).retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,fm("factor",t.factor,{min:0,allowInfinity:!1}),fm("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),fm("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),fm("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0;const i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();const r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await bm({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}(async n=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,n,this.retries,t),t}},{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);const r={};[...t.tags.keys()].forEach(e=>{e.startsWith(At)&&(r[e]=void 0)}),await this.peerStore.merge(e,{tags:r}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{const e=await this.peerStore.all({filters:[e=>vm(e)]});await Promise.all(e.map(async e=>{await this.connectionManager.openConnection(e.id).catch(e=>{this.log.error("could not open connection to keepalive peer - %e",e)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}}function vm(e){for(const t of e.tags.keys())if(t.startsWith(At))return!0;return!1}const wm=50;class Tm{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new We("Connection Manager maxConnections must be greater than 0");this.connections=new Xu,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(e=>Of(Pu(e))),this.deny=(t.deny??[]).map(e=>Of(Pu(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Sc({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new jf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(e=>Pu(e))}),this.dialQueue=new lm(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:um},connections:this.connections}),this.reconnectQueue=new gm({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const n of t)for(const t of n.streams){const n=`${t.direction} ${t.protocol??"unnegotiated"}`;e[n]=(e[n]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const n of t){const t={};for(const e of n.streams){const n=`${e.direction} ${e.protocol??"unnegotiated"}`;t[n]=(t[n]??0)+1}for(const[n,r]of Object.entries(t))e[n]=e[n]??[],e[n].push(r)}const t={};for(let[n,r]of Object.entries(e)){r=r.sort((e,t)=>e-t);const e=Math.floor(.9*r.length);t[n]=r[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await kt(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await It(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const n of t)e.push(Promise.all([_d(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(e=>{n.abort(e)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new We("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(e=>{this.log.error("could not connect - %e",e)})}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const n=t.remotePeer,r=!this.connections.has(n),i=this.connections.get(n)??[];i.push(t),this.connections.set(n,i),null!=n.publicKey&&"RSA"===n.type&&await this.peerStore.patch(n,{publicKey:n.publicKey}),r&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,n=t.remotePeer,r=(this.connections.get(n)??[]).filter(e=>e.id!==t.id);this.connections.set(n,r),0===r.length&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new lt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:n,multiaddrs:r}=Lf(e);if(this.peerId.equals(n))throw new rt("Can not dial self");if(null!=n&&!0!==t.force){this.log("dial %p",n);const e=Uf(n,this.getConnections(n),r);if(null!=e)return this.log("had an existing connection to %p as %a",n,e.remoteAddr),t.onProgress?.(new _f("dial-queue:already-connected")),e}const i=await this.dialQueue.dial(e,{...t,priority:t.priority??wm});if("open"!==i.status)throw new Ye("Remote closed connection during opening");let s=this.connections.get(i.remotePeer);null==s&&(s=[],this.connections.set(i.remotePeer,s));let a=!1;for(const e of s)if(e.id===i.id&&(a=!0),!0!==t.force&&e.id!==i.id&&e.remoteAddr.equals(i.remoteAddr))return i.abort(new it("Duplicate multiaddr connection")),e;return a||s.push(i),i}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){const n=this.connections.get(e)??[];await Promise.all(n.map(async e=>{try{await Promise.all([_d(e,"close",t),e.close(t)])}catch(t){e.abort(t)}}))}acceptIncomingConnection(e){if(this.deny.some(t=>{if(vd(e.remoteAddr)){const n=hd(e.remoteAddr);return t.contains(n.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(t=>{if(vd(e.remoteAddr)){const n=hd(e.remoteAddr);return t.contains(n.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(vd(e.remoteAddr)){const t=hd(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(t.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(e=>Pu(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Em{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new Xd({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Rt]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();const n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal});try{const r=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),i=hc(r);t=Date.now(),await Promise.all([i.write(io(32),{signal:n}),i.read({bytes:32,signal:n})]),e.rtt=Date.now()-t,await r.close({signal:n})}catch(n){if("UnsupportedProtocolError"!==n.name)throw n;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class xm{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()}),getAttributesFromYieldedValue:(e,t)=>({...t,providers:[...Array.isArray(t.providers)?t.providers:[],e.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([e])=>({key:mr(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:mr(e,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new pf("No content routers available");const n=this,r=new ed;for await(const i of tc(...n.routers.filter(e=>e.findProviders instanceof Function).map(n=>n.findProviders(e,t))))null!=i&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),r.has(i.id)||(r.add(i.id),yield i))}async provide(e,t={}){if(0===this.routers.length)throw new pf("No content routers available");await Promise.all(this.routers.filter(e=>e.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(0===this.routers.length)throw new pf("No content routers available");await Promise.all(this.routers.filter(e=>e.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new lt;await Promise.all(this.routers.filter(e=>e.put instanceof Function).map(async r=>{await r.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new lt;return Promise.any(this.routers.filter(e=>e.get instanceof Function).map(async n=>n.get(e,t)))}}const Pm=globalThis.CustomEvent??Event;async function*Sm(e,t={}){let n=t.concurrency??Infinity;n<1&&(n=Infinity);const r=t.ordered??!1,i=new EventTarget,s=[];let a,o=Cd(),u=Cd(),d=!1,c=!1;function l(){return r?s[0]?.done:Boolean(s.find(e=>e.done))}function*p(){for(;s.length>0&&s[0].done;){const e=s[0];if(s.shift(),!e.ok)throw c=!0,o.resolve(),e.err;yield e.value,o.resolve()}}function*h(){for(;l();)for(let e=0;e<s.length;e++)if(s[e].done){const t=s[e];if(s.splice(e,1),e--,!t.ok)throw c=!0,o.resolve(),t.err;yield t.value,o.resolve()}}for(i.addEventListener("task-complete",()=>{u.resolve()}),Promise.resolve().then(async()=>{try{for await(const t of e){if(s.length===n&&(o=Cd(),await o.promise),c)break;const e={done:!1};s.push(e),t().then(t=>{e.done=!0,e.ok=!0,e.value=t,i.dispatchEvent(new Pm("task-complete"))},t=>{e.done=!0,e.err=t,i.dispatchEvent(new Pm("task-complete"))})}d=!0,i.dispatchEvent(new Pm("task-complete"))}catch(e){a=e,i.dispatchEvent(new Pm("task-complete"))}});;){if(l()||(u=Cd(),await u.promise),null!=a)throw a;if(r?yield*p():yield*h(),null!=a)throw a;if(d&&0===s.length)break}}class Am{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,peer:e.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,key:mr(e,"base36")}),getAttributesFromYieldedValue:(e,t)=>({...t,peers:[...Array.isArray(t.peers)?t.peers:[],e.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new hf("No peer routers available");if(e.toString()===this.peerId.toString())throw new ff("Should not try to find self");const n=this,r=tc(...this.routers.filter(e=>e.findPeer instanceof Function).map(r=>async function*(){try{yield await r.findPeer(e,t)}catch(e){n.log.error("router failed to find peer - %e",e)}}()));for await(const e of r)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs},t),e;throw new nt}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new hf("No peer routers available");const n=this,r=pd(1024);for await(const i of Sm(async function*(){const r=tc(...n.routers.filter(e=>e.getClosestPeers instanceof Function).map(n=>n.getClosestPeers(e,t)));for await(let e of r)yield async()=>{if(0===e.multiaddrs.length)try{e=await n.findPeer(e.id,{...t,useCache:!1})}catch(e){return void n.log.error("could not find peer multiaddrs - %e",e)}return e}}()))null!=i&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),r.has(i.id.toMultihash().bytes)||(r.add(i.id.toMultihash().bytes),yield i))}}class Cm extends Ft{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=Jd([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=Cd();const e=await _d(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]});yield e.detail}}catch(e){if(null!=e.detail)throw e.detail;throw e}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController;const e=Jd([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{const t=io(32);let r=Date.now();for await(const i of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-r,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await $d(this.needNext.promise,e)),r=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,n)}catch(e){this.log.error("random walk errored - %e",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")}).catch(e=>{this.log.error("random walk errored - %e",e)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}}class km{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const e={};for(const[t,n]of this.topologies)e[t]=n.size;return e}}),this.handlers=Ic({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new mf(`No handler registered for protocol ${e}`);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&!0!==n?.force)throw new yf(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:32,maxOutboundStreams:64,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(e=>{this.handlers.delete(e)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(null==t)throw new We("invalid topology");const n=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let r=this.topologies.get(e);return null==r&&(r=new Map,this.topologies.set(e,r)),r.set(n,t),n}unregister(e){for(const[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),0===n.size&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){const t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{const e=await this.components.peerStore.get(t,n);for(const n of e.protocols){const e=this.topologies.get(n);null!=e&&await Promise.all([...e.values()].map(async e=>{null!=e.filter&&!0!==e.filter.has(t)||(e.filter?.remove(t),await(e.onDisconnect?.(t)))}))}}catch(e){if("NotFoundError"===e.name)return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,e)}}async _onPeerUpdate(e){const{peer:t,previous:n}=e.detail,r=(n?.protocols??[]).filter(e=>!t.protocols.includes(e));try{for(const e of r){const n=this.topologies.get(e);null!=n&&await Promise.all([...n.values()].map(async e=>{null!=e.filter&&!0!==e.filter.has(t.id)||(e.filter?.remove(t.id),await(e.onDisconnect?.(t.id)))}))}}catch(e){this.log.error("could not inform topologies of updated peer %p - %e",t.id,e)}}async _onPeerIdentify(e){const t=e.detail.protocols,n=e.detail.connection,r=e.detail.peerId;try{for(const e of t){const t=this.topologies.get(e);null!=t&&await Promise.all([...t.values()].map(async e=>{null!=n.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(r)&&(e.filter?.add(r),await(e.onConnect?.(r,n)))}))}}catch(e){this.log.error("could not inform topologies of updated peer after identify %p - %e",r,e)}}}class Im{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Ic({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ic({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Mt.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new We("Transport must have a valid tag");if(this.transports.has(t))throw new We(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){const t=n.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const n=this.dialTransportForMultiaddr(e);if(null==n)throw new Sf(`No transport available for address ${String(e)}`);return t?.onProgress?.(new _f("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new lt("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(e=>{t.errors.set(e.toString(),new gf)});const n=[];for(const[r,i]of this.transports.entries()){const s=i.listenFilter(e);for(const e of s){this.log("creating listener for %s on %a",r,e);const s=i.createListener({upgrader:this.components.upgrader});let a=this.listeners.get(r)??[];null==a&&(a=[],this.listeners.set(r,a)),a.push(s),s.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:s})}),s.addEventListener("close",()=>{const e=a.findIndex(e=>e===s);a.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:s})}),Mh.matches(e)?t.ipv4.attempts++:Fh.matches(e)&&t.ipv6.attempts++,n.push(s.listen(e).then(()=>{t.errors.delete(e.toString()),Mh.matches(e)&&t.ipv4.success++,Fh.matches(e)&&t.ipv6.success++},n=>{throw this.log.error("transport %s could not listen on address %a - %e",r,e,n),t.errors.set(e.toString(),n),n}))}}const r=await Promise.allSettled(n);if(!(r.length>0&&r.every(e=>"fulfilled"===e.status)))if(this.ipv6Unsupported(t))this.log("all IPv4 addresses succeed but all IPv6 failed");else{if(this.faultTolerance!==Mt.NO_FATAL)throw new vf(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:\n${[...t.errors.entries()].map(([e,t])=>`\n ${e}: ${`${function(e){return null!=e.stack&&""!==e.stack.trim()?e.stack:null!=e.message?e.message:e.toString()}(t)}`.split("\n").join("\n ")}\n`).join("")}`);this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(e){return 0!==e.ipv4.attempts&&0!==e.ipv6.attempts&&e.ipv4.attempts===e.ipv4.success&&0===e.ipv6.success}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&n.push(e.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const Dm="/multistream/1.0.0",Mm=fr("\n");async function Fm(e,t){const n=(await e.read(t)).subarray();if(0===n.byteLength||n[n.length-1]!==Mm[0])throw new ut("Missing newline");return mr(n).trimEnd()}async function Rm(e,t,n={}){if(0===(t=Array.isArray(t)?[...t]:[t]).length)throw new Error("At least one protocol must be specified");const r=e.log.newScope("mss:select"),i=fc(e,{...n,maxDataLength:1024});for(let e=0;e<t.length;e++){const s=t[e];let a;if(0===e){r.trace('write ["%s", "%s"]',Dm,s);const e=fr(`${Dm}\n`),t=fr(`${s}\n`);if(await i.writeV([e,t],n),r.trace("reading multistream-select header"),a=await Fm(i,n),r.trace('read "%s"',a),a!==Dm){r.error("did not read multistream-select header from response");break}}else r.trace('write "%s"',s),await i.write(fr(`${s}\n`),n);if(r.trace("reading protocol response"),a=await Fm(i,n),r.trace('read "%s"',a),a===s)return r.trace('selected "%s" after negotiation',a),i.unwrap(),s}throw new ot(`Protocol selection failed - could not negotiate ${t}`)}async function _m(e,t,n={}){t=Array.isArray(t)?t:[t];const r=e.log.newScope("mss:handle"),i=fc(e,{...n,maxDataLength:1024,maxLengthLength:2});for(;;){r.trace("reading incoming string");const e=await Fm(i,n);if(r.trace('read "%s"',e),e!==Dm){if(t.includes(e))return r.trace('respond with "%s" for "%s"',e,e),await i.write(fr(`${e}\n`),n),r.trace('responded with "%s" for "%s"',e,e),i.unwrap(),e;if("ls"!==e)r.trace('respond with "na" for "%s"',e),await i.write(fr("na\n"),n),r('responded with "na" for "%s"',e);else{const s=new $n(...t.map(e=>Tc.single(fr(`${e}\n`))),fr("\n"));r.trace('respond with "%s" for %s',t,e),await i.write(s,n),r.trace('responded with "%s" for %s',t,e)}}else r.trace('respond with "%s" for "%s"',Dm,e),await i.write(fr(`${Dm}\n`),n),r.trace('responded with "%s" for "%s"',Dm,e)}}class Lm extends Ft{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??qf,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??qf,this.closeTimeout=t.closeTimeout??1e3,this.direct=Bf(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),null==this.remoteAddr.getComponents().find(e=>e.code===eu)&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),null!=t.muxer&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",e=>{this.dispatchEvent(new vt(e.local,e.error))})}[Symbol.toStringTag]="Connection";[ze]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(null==this.muxer)throw new xf("Connection is not multiplexed");if("open"!==this.muxer.status)throw new Ye(`The connection muxer is "${this.muxer.status}" and not "open"`);if("open"!==this.maConn.status)throw new Ye(`The connection is "${this.status}" and not "open"`);if(null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new ft("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);const n=await this.muxer.createStream({...t,protocol:1===e.length?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(null==t.signal){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);const r=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:r}}""===n.protocol?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Rm(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);const r=function(e,t,n={}){try{const{options:n}=t.getHandler(e);if(null!=n.maxOutboundStreams)return n.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return n.maxOutboundStreams??64}(n.protocol,this.components.registrar,t),i=Nm(n.protocol,"outbound",this);if(i>r){const e=new yt(`Too many outbound protocol streams for protocol "${n.protocol}" - ${i}/${r}`);throw n.abort(e),e}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);const s=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,s)}catch(t){throw"open"===n.status?n.abort(t):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===this.direction?"from":"to",this.remoteAddr,e,t),t}};async onIncomingStream(e){const t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(""===t.protocol){const e=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",e),t.protocol=await _m(t,e,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);const e=function(e,t){try{const{options:n}=t.getHandler(e);if(null!=n.maxInboundStreams)return n.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(t.protocol,this.components.registrar);if(Nm(t.protocol,"inbound",this)>e)throw new mt(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${e}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);const{handler:r,options:i}=this.components.registrar.getHandler(t.protocol);if(null!=this.limits&&!0!==i.runOnLimitedConnection)throw new ft("Cannot open protocol stream on limited connection");const s=this.components.registrar.getMiddleware(t.protocol);s.push(async(e,t,n)=>{await r(e,t),n(e,t)}),await this.runMiddlewareChain(t,this,s)}catch(e){t.abort(e)}}async runMiddlewareChain(e,t,n){for(let r=0;r<n.length;r++){const i=n[r];e.log.trace("running middleware",r,i),await new Promise((n,r)=>{try{const s=i(e,t,(r,i)=>{e=r,t=i,n()});s instanceof Promise&&s.catch(r)}catch(e){r(e)}}),e.log.trace("ran middleware",r,i)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),null==e.signal){const t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await(this.muxer?.close(e)),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}}function Nm(e,t,n){let r=0;return n.streams.forEach(n=>{n.direction===t&&n.protocol===e&&r++}),r}class Om{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ic({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(e=>{this.connectionEncrypters.set(e.protocol,e)}),this.streamMuxers=Ic({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(e=>{this.streamMuxers.set(e.protocol,e)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??qf,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??qf,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const n=this.components.connectionGater[e];if(null!=n&&!0===await n.apply(this.components.connectionGater,t))throw new Tf(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){return Jd([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,t){let n=!1;const r=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Ef("Connection denied");await $d(this.shouldBlockConnection("denyInboundConnection",e),r),await this._performUpgrade(e,"inbound",{...t,signal:r})}catch(e){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[e.name??"Error"]:!0}),e}finally{r.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});const n=e.remoteAddr.getComponents().findLast(e=>e.code===eu)?.value;let r;null!=n&&(r=Uo(n),await $d(this.shouldBlockConnection("denyOutboundConnection",r,e),t.signal));let i="outbound";return!1===t.initiator&&(i="inbound"),await this._performUpgrade(e,i,t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[e.name??"Error"]:!0}),e}}async _performUpgrade(e,t,n){let r,i,s,a,o=e;const u=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${u}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),!0!==n?.skipProtection){const r=this.components.connectionProtector;null!=r&&(e.log("protecting the %s connection",t),o=await r.protect(o,n))}try{if(function(e){return!0===e.skipEncryption}(n)){if(null==n.remotePeer)throw new it(`${t} connection that skipped encryption must have a peer id`);a="native",r=n.remotePeer}else{const s=e.remoteAddr.getComponents().findLast(e=>e.code===eu)?.value;let u;null!=s&&(u=Uo(s)),n?.onProgress?.(new _f(`upgrader:encrypt-${t}-connection`)),({connection:o,remotePeer:r,protocol:a,streamMuxer:i}=await("inbound"===t?this._encryptInbound(o,{...n,remotePeer:u}):this._encryptOutbound(o,{...n,remotePeer:u})))}if(r.equals(this.components.peerId)){const t=new rt("Can not dial self");throw e.abort(t),t}await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",r,e),null!=n?.muxerFactory?i=n.muxerFactory:null==i&&this.streamMuxers.size>0&&(n?.onProgress?.(new _f(`upgrader:multiplex-${t}-connection`)),i=await("inbound"===t?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(n){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,"inbound"===t?"from":"to",e.remoteAddr,n),n}null!=i&&(e.log("create muxer %s",i.protocol),s=i.createStreamMuxer(o)),await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",r,e);const d=this._createConnection({id:u,cryptoProtocol:a,direction:t,maConn:e,stream:o,muxer:s,remotePeer:r,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return d.log("successfully upgraded connection"),d}_createConnection(e){const t=(n={...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout},new Lm(this.components,n));var n;return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){const n=Array.from(this.connectionEncrypters.keys());try{const r=await _m(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new Pf(`no crypto module found for ${r}`);return e.log("encrypting inbound connection using %s",r),{...await i.secureInbound(e,t),protocol:r}}catch(e){throw new Pf(e.message)}}async _encryptOutbound(e,t){const n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);const r=await Rm(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new Pf(`no crypto module found for ${r}`);return e.log("encrypting outbound connection using %s",r),{...await i.secureOutbound(e,t),protocol:r}}catch(e){throw new Pf(e.message)}}async _multiplexOutbound(e,t,n){const r=Array.from(t.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);const i=await Rm(e,r,n),s=t.get(i);if(null==s)throw new xf(`No muxer configured for protocol "${i}"`);return e.log("selected %s as muxer protocol",i),s}catch(t){throw e.log.error("error multiplexing outbound connection - %e",t),new xf(String(t))}}async _multiplexInbound(e,t,n){const r=Array.from(t.keys());e.log("inbound handling muxers %s",r);try{e.log.trace("selecting stream muxer from %s",r);const i=await _m(e,r,n),s=t.get(i);if(null==s)throw new xf(`No muxer configured for protocol "${i}"`);return e.log("selected %s as muxer protocol",i),s}catch(t){throw e.log.error("error multiplexing inbound connection - %e",t),t}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const Bm="3.1.6",Um="js-libp2p";class jm extends Ft{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Ft,n=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=n(e),r=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||r},this.peerId=e.peerId,this.logger=e.logger??Wu(),this.log=this.logger.forComponent("libp2p"),this.services={};const r=e.nodeInfo?.name??Um,i=e.nodeInfo?.version??Bm,s=this.components=function(e={}){const t=new Cf(e),n=new Proxy(t,{get(e,n,r){if("string"==typeof n&&!If.includes(n)){const e=t.components[n];if(null==e&&!kf.includes(n))throw new cf(`${n} not set`);return e}return Reflect.get(e,n,r)},set:(e,n,r)=>("string"==typeof n?t.components[n]=r:Reflect.set(e,n,r),!0)});return n}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:r,version:i,userAgent:e.nodeInfo?.userAgent??(a=r,o=i,`${a??Um}/${o??Bm} browser/${globalThis.navigator.userAgent}`)},logger:this.logger,events:t,datastore:e.datastore??new fh,connectionGater:Rf(e.connectionGater),dns:e.dns});var a,o;null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new ah(e,t)}(s,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),s.events.addEventListener("peer:update",e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map(e=>e.multiaddr)};s.events.safeDispatchEvent("peer:discovery",{detail:t})}}),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(s)),this.components.upgrader=new Om(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components))),streamMuxers:(e.streamMuxers??[]).map((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Im(this.components,e.transportManager)),this.configureComponent("connectionManager",new Tm(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Em(this.components,e.connectionMonitor)),this.configureComponent("registrar",new km(this.components)),this.configureComponent("addressManager",new uf(this.components,e.addresses));const u=(e.peerRouters??[]).map((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Am(this.components,{routers:u}));const d=(e.contentRouters??[]).map((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new xm(this.components,{routers:d})),this.configureComponent("randomWalk",new Cm(this.components)),(e.peerDiscovery??[]).forEach((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",e=>{this.#Y(e)})}),e.transports?.forEach((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))}),null!=e.services)for(const t of Object.keys(e.services)){const n=(0,e.services[t])(this.components);null!=n?(this.services[t]=n,this.configureComponent(t,n),null!=n[Ve]&&(this.log("registering service %s for content routing",t),d.push(n[Ve])),null!=n[St]&&(this.log("registering service %s for peer routing",t),u.push(n[St])),null!=n[Et]&&(this.log("registering service %s for peer discovery",t),n[Et].addEventListener?.("peer",e=>{this.#Y(e)}))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const n of Object.values(e.components))for(const e of Df(n))t[e]=!0;for(const n of Object.values(e.components))for(const e of Mf(n))if(!0!==t[e])throw new lf(`Service "${Ff(n)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(s)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new ed;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(null==t)throw new We("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new We("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){xu(e)&&(e=Uo(e.getComponents().findLast(e=>e.code===eu)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const n=await this.peerStore.get(e,t);if(null!=n.id.publicKey)return n.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const n=Bn([fr("/pk/"),e.toMultihash().bytes]),r=Mo(await this.contentRouting.get(n,t));return await this.peerStore.patch(e,{publicKey:r},t),r}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.handle(e,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.unhandle(e,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#Y(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(e=>{this.log.error("could not update multiaddrs of discovered peer - %e",e)}):this.log.error("peer discovery mechanism discovered self")}}const qm=65535,$m=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function zm(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Vm(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Gm(e,t,n=""){const r=function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e),i=e?.length,s=void 0!==t;if(!r||s&&i!==t)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e));return e}function Km(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Hm(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Wm(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Qm=/* @__PURE__ */(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])(),Ym=(e,t)=>{function n(n,...r){if(Gm(n,void 0,"key"),!Qm)throw new Error("Non little-endian hardware is not yet supported");void 0!==e.nonceLength&&Gm(r[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");const i=e.tagLength;i&&void 0!==r[1]&&Gm(r[1],void 0,"AAD");const s=t(n,...r),a=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Gm(t,void 0,"output")}};let o=!1;return{encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Gm(e),a(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(Gm(e),i&&e.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(n,e),n};function Jm(e,t,n=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(n&&t.byteOffset%4!=0)throw new Error("invalid output, must be aligned");return t}function Zm(e){return Uint8Array.from(e)}const Xm=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),ey=Xm("expand 16-byte k"),ty=Xm("expand 32-byte k"),ny=Hm(ey),ry=Hm(ty);function iy(e,t){return e<<t|e>>>32-t}function sy(e){return e.byteOffset%4==0}const ay=2**32-1,oy=Uint32Array.of();function uy(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:a}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Vm(i),Vm(a),zm(s),zm(n),(t,o,u,d,c=0)=>{Gm(t,void 0,"key"),Gm(o,void 0,"nonce"),Gm(u,void 0,"data");const l=u.length;if(void 0===d&&(d=new Uint8Array(l)),Gm(d,void 0,"output"),Vm(c),c<0||c>=ay)throw new Error("arx: counter overflow");if(d.length<l)throw new Error(`arx: output (${d.length}) is shorter than data (${l})`);const p=[];let h,f,m=t.length;if(32===m)p.push(h=Zm(t)),f=ry;else{if(16!==m||!n)throw Gm(t,32,"arx key"),new Error("invalid key size");h=new Uint8Array(32),h.set(t),h.set(t,16),f=ny,p.push(h)}sy(o)||p.push(o=Zm(o));const y=Hm(h);if(r){if(24!==o.length)throw new Error("arx: extended nonce must be 24 bytes");r(f,y,Hm(o.subarray(0,16)),y),o=o.subarray(16)}const b=16-i;if(b!==o.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(12!==b){const e=new Uint8Array(12);e.set(o,s?0:12-o.length),p.push(o=e)}const g=Hm(o);return function(e,t,n,r,i,s,a,o){const u=i.length,d=new Uint8Array(64),c=Hm(d),l=sy(i)&&sy(s),p=l?Hm(i):oy,h=l?Hm(s):oy;for(let f=0;f<u;a++){if(e(t,n,r,c,a,o),a>=ay)throw new Error("arx: counter overflow");const m=Math.min(64,u-f);if(l&&64===m){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,n=0;n<16;n++)t=e+n,h[t]=p[t]^c[n];f+=64}else{for(let e,t=0;t<m;t++)e=f+t,s[e]=i[e]^d[t];f+=m}}}(e,f,y,g,u,d,c,a),Wm(...p),d}}function dy(e,t){return 255&e[t++]|(255&e[t++])<<8}class cy{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){const t=dy(e=Zm(Gm(e,32,"key")),0),n=dy(e,2),r=dy(e,4),i=dy(e,6),s=dy(e,8),a=dy(e,10),o=dy(e,12),u=dy(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|n<<3),this.r[2]=7939&(n>>>10|r<<6),this.r[3]=8191&(r>>>7|i<<9),this.r[4]=255&(i>>>4|s<<12),this.r[5]=s>>>1&8190,this.r[6]=8191&(s>>>14|a<<2),this.r[7]=8065&(a>>>11|o<<5),this.r[8]=8191&(o>>>8|u<<8),this.r[9]=u>>>5&127;for(let t=0;t<8;t++)this.pad[t]=dy(e,16+2*t)}process(e,t,n=!1){const r=n?0:2048,{h:i,r:s}=this,a=s[0],o=s[1],u=s[2],d=s[3],c=s[4],l=s[5],p=s[6],h=s[7],f=s[8],m=s[9],y=dy(e,t+0),b=dy(e,t+2),g=dy(e,t+4),v=dy(e,t+6),w=dy(e,t+8),T=dy(e,t+10),E=dy(e,t+12),x=dy(e,t+14);let P=i[0]+(8191&y),S=i[1]+(8191&(y>>>13|b<<3)),A=i[2]+(8191&(b>>>10|g<<6)),C=i[3]+(8191&(g>>>7|v<<9)),k=i[4]+(8191&(v>>>4|w<<12)),I=i[5]+(w>>>1&8191),D=i[6]+(8191&(w>>>14|T<<2)),M=i[7]+(8191&(T>>>11|E<<5)),F=i[8]+(8191&(E>>>8|x<<8)),R=i[9]+(x>>>5|r),_=0,L=_+P*a+S*(5*m)+A*(5*f)+C*(5*h)+k*(5*p);_=L>>>13,L&=8191,L+=I*(5*l)+D*(5*c)+M*(5*d)+F*(5*u)+R*(5*o),_+=L>>>13,L&=8191;let N=_+P*o+S*a+A*(5*m)+C*(5*f)+k*(5*h);_=N>>>13,N&=8191,N+=I*(5*p)+D*(5*l)+M*(5*c)+F*(5*d)+R*(5*u),_+=N>>>13,N&=8191;let O=_+P*u+S*o+A*a+C*(5*m)+k*(5*f);_=O>>>13,O&=8191,O+=I*(5*h)+D*(5*p)+M*(5*l)+F*(5*c)+R*(5*d),_+=O>>>13,O&=8191;let B=_+P*d+S*u+A*o+C*a+k*(5*m);_=B>>>13,B&=8191,B+=I*(5*f)+D*(5*h)+M*(5*p)+F*(5*l)+R*(5*c),_+=B>>>13,B&=8191;let U=_+P*c+S*d+A*u+C*o+k*a;_=U>>>13,U&=8191,U+=I*(5*m)+D*(5*f)+M*(5*h)+F*(5*p)+R*(5*l),_+=U>>>13,U&=8191;let j=_+P*l+S*c+A*d+C*u+k*o;_=j>>>13,j&=8191,j+=I*a+D*(5*m)+M*(5*f)+F*(5*h)+R*(5*p),_+=j>>>13,j&=8191;let q=_+P*p+S*l+A*c+C*d+k*u;_=q>>>13,q&=8191,q+=I*o+D*a+M*(5*m)+F*(5*f)+R*(5*h),_+=q>>>13,q&=8191;let $=_+P*h+S*p+A*l+C*c+k*d;_=$>>>13,$&=8191,$+=I*u+D*o+M*a+F*(5*m)+R*(5*f),_+=$>>>13,$&=8191;let z=_+P*f+S*h+A*p+C*l+k*c;_=z>>>13,z&=8191,z+=I*d+D*u+M*o+F*a+R*(5*m),_+=z>>>13,z&=8191;let V=_+P*m+S*f+A*h+C*p+k*l;_=V>>>13,V&=8191,V+=I*c+D*d+M*u+F*o+R*a,_+=V>>>13,V&=8191,_=(_<<2)+_|0,_=_+L|0,L=8191&_,_>>>=13,N+=_,i[0]=L,i[1]=N,i[2]=O,i[3]=B,i[4]=U,i[5]=j,i[6]=q,i[7]=$,i[8]=z,i[9]=V}finalize(){const{h:e,pad:t}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=5*r,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(1^r)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let s=e[0]+t[0];e[0]=65535&s;for(let n=1;n<8;n++)s=(e[n]+t[n]|0)+(s>>>16)|0,e[n]=65535&s;Wm(n)}update(e){Km(this),Gm(e),e=Zm(e);const{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const s=Math.min(n-this.pos,r-i);if(s!==n)t.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(t,0,!1),this.pos=0);else for(;n<=r-i;i+=n)this.process(e,i)}return this}destroy(){Wm(this.h,this.r,this.buffer,this.pad)}digestInto(e){Km(this),function(e,t){Gm(e,void 0,"output");const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,h:n}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}}const ly=/** @__PURE__ */(()=>function(e){const t=(t,n)=>e(n).update(t).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}(e=>new cy(e)))();function py(e,t,n,r,i,s=20){let a=e[0],o=e[1],u=e[2],d=e[3],c=t[0],l=t[1],p=t[2],h=t[3],f=t[4],m=t[5],y=t[6],b=t[7],g=i,v=n[0],w=n[1],T=n[2],E=a,x=o,P=u,S=d,A=c,C=l,k=p,I=h,D=f,M=m,F=y,R=b,_=g,L=v,N=w,O=T;for(let e=0;e<s;e+=2)E=E+A|0,_=iy(_^E,16),D=D+_|0,A=iy(A^D,12),E=E+A|0,_=iy(_^E,8),D=D+_|0,A=iy(A^D,7),x=x+C|0,L=iy(L^x,16),M=M+L|0,C=iy(C^M,12),x=x+C|0,L=iy(L^x,8),M=M+L|0,C=iy(C^M,7),P=P+k|0,N=iy(N^P,16),F=F+N|0,k=iy(k^F,12),P=P+k|0,N=iy(N^P,8),F=F+N|0,k=iy(k^F,7),S=S+I|0,O=iy(O^S,16),R=R+O|0,I=iy(I^R,12),S=S+I|0,O=iy(O^S,8),R=R+O|0,I=iy(I^R,7),E=E+C|0,O=iy(O^E,16),F=F+O|0,C=iy(C^F,12),E=E+C|0,O=iy(O^E,8),F=F+O|0,C=iy(C^F,7),x=x+k|0,_=iy(_^x,16),R=R+_|0,k=iy(k^R,12),x=x+k|0,_=iy(_^x,8),R=R+_|0,k=iy(k^R,7),P=P+I|0,L=iy(L^P,16),D=D+L|0,I=iy(I^D,12),P=P+I|0,L=iy(L^P,8),D=D+L|0,I=iy(I^D,7),S=S+A|0,N=iy(N^S,16),M=M+N|0,A=iy(A^M,12),S=S+A|0,N=iy(N^S,8),M=M+N|0,A=iy(A^M,7);let B=0;r[B++]=a+E|0,r[B++]=o+x|0,r[B++]=u+P|0,r[B++]=d+S|0,r[B++]=c+A|0,r[B++]=l+C|0,r[B++]=p+k|0,r[B++]=h+I|0,r[B++]=f+D|0,r[B++]=m+M|0,r[B++]=y+F|0,r[B++]=b+R|0,r[B++]=g+_|0,r[B++]=v+L|0,r[B++]=w+N|0,r[B++]=T+O|0}const hy=/* @__PURE__ */uy(py,{counterRight:!1,counterLength:4,allowShortKeys:!1}),fy=/* @__PURE__ */new Uint8Array(16),my=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(fy.subarray(n))},yy=/* @__PURE__ */new Uint8Array(32);function by(e,t,n,r,i){void 0!==i&&Gm(i,void 0,"AAD");const s=e(t,n,yy),a=function(e,t,n){zm(n);const r=new Uint8Array(16),i=(s=r,new DataView(s.buffer,s.byteOffset,s.byteLength));var s;return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}(r.length,i?i.length:0,!0),o=ly.create(s);i&&my(o,i),my(o,r),o.update(a);const u=o.digest();return Wm(s,a),u}const gy=/* @__PURE__ */Ym({blockSize:64,nonceLength:12,tagLength:16},(vy=hy,(e,t,n)=>({encrypt(r,i){const s=r.length;(i=Jm(s+16,i,!1)).set(r);const a=i.subarray(0,-16);vy(e,t,a,a,1);const o=by(vy,e,t,a,n);return i.set(o,s),Wm(o),i},decrypt(r,i){i=Jm(r.length-16,i,!1);const s=r.subarray(0,-16),a=r.subarray(-16),o=by(vy,e,t,s,n);if(!function(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(a,o))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),vy(e,t,i,i,1),Wm(o),i}})));var vy;function wy(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Ty(e,t,n=""){const r=function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e),i=e?.length,s=void 0!==t;if(!r||s&&i!==t)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e));return e}function Ey(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");wy(e.outputLen),wy(e.blockLen)}function xy(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Py(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Sy(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ay(e,t){return e<<32-t|e>>>t}const Cy=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),ky=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Iy(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Dy(e,t={}){const n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}function My(e=32){const t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}const Fy=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ry(e,t,n){return e&t^~e&n}function _y(e,t,n){return e&t^e&n^t&n}class Ly{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Sy(this.buffer)}update(e){xy(this),Ty(e);const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const a=Math.min(r-this.pos,i-s);if(a!==r)n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=Sy(e);for(;r<=i-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){xy(this),function(e,t){Ty(e,void 0,"digestInto() output");const n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;t[s++]=128,Py(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(8*this.length),i),this.process(n,0);const a=Sy(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=o/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<u;e++)a.setUint32(4*e,d[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=a,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Ny=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oy=/* @__PURE__ */Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),By=/* @__PURE__ */new Uint32Array(64);class Uy extends Ly{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:a,H:o}=this;return[e,t,n,r,i,s,a,o]}set(e,t,n,r,i,s,a,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|a,this.H=0|o}process(e,t){for(let n=0;n<16;n++,t+=4)By[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=By[e-15],n=By[e-2],r=Ay(t,7)^Ay(t,18)^t>>>3,i=Ay(n,17)^Ay(n,19)^n>>>10;By[e]=i+By[e-7]+r+By[e-16]|0}let{A:n,B:r,C:i,D:s,E:a,F:o,G:u,H:d}=this;for(let e=0;e<64;e++){const t=d+(Ay(a,6)^Ay(a,11)^Ay(a,25))+Ry(a,o,u)+Oy[e]+By[e]|0,c=(Ay(n,2)^Ay(n,13)^Ay(n,22))+_y(n,r,i)|0;d=u,u=o,o=a,a=s+t|0,s=i,i=r,r=n,n=t+c|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,r,i,s,a,o,u,d)}roundClean(){Py(By)}destroy(){this.set(0,0,0,0,0,0,0,0),Py(this.buffer)}}class jy extends Uy{A=0|Ny[0];B=0|Ny[1];C=0|Ny[2];D=0|Ny[3];E=0|Ny[4];F=0|Ny[5];G=0|Ny[6];H=0|Ny[7];constructor(){super(32)}}const qy=/* @__PURE__ */Dy(()=>new jy
|
|
4
|
+
/* @__PURE__ */,Fy(1)),$y=/* @__PURE__ */BigInt(0);function zy(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?$y:BigInt("0x"+e)}(function(e){if(Ty(e),Cy)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ky[e[n]];return t}(Vy(Ty(e)).reverse()))}function Vy(e){return Uint8Array.from(e)}const Gy=e=>"bigint"==typeof e&&$y<=e;function Ky(e,t,n,r){if(!function(e,t,n){return Gy(e)&&Gy(t)&&Gy(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const Hy=/* @__PURE__ */BigInt(0);function Wy(e,t){const n=e%t;return n>=Hy?n:t+n}function Qy(e,t,n){let r=e;for(;t-- >Hy;)r*=r,r%=n;return r}function Yy(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}new WeakMap,new WeakMap,BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Jy=BigInt(0),Zy=BigInt(1),Xy=BigInt(2),eb=BigInt(1),tb=BigInt(2),nb=/* @__PURE__ */BigInt(3),rb=BigInt(5),ib=(BigInt(8),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"));function sb(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const ab=/* @__PURE__ */(()=>{const e=ib;return function(e){const t=(function(e,t={},n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");const r=(t,n)=>Object.entries(t).forEach(([t,r])=>function(t,n,r){const i=e[t];if(r&&void 0===i)return;const s=typeof i;if(s!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${s}`)}(t,r,n));r(t,!1),r(n,!0)}(n=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...n}));var n;const{P:r,type:i,adjustScalarBytes:s,powPminus2:a,randomBytes:o}=t,u="x25519"===i;if(!u&&"x448"!==i)throw new Error("invalid type");const d=o||My,c=u?255:448,l=u?32:56,p=u?BigInt(9):BigInt(5),h=u?BigInt(121665):BigInt(39081),f=u?Xy**BigInt(254):Xy**BigInt(447),m=u?BigInt(8)*Xy**BigInt(251)-Zy:BigInt(4)*Xy**BigInt(445)-Zy,y=f+m+Zy,b=e=>Wy(e,r),g=v(p);function v(e){return function(e,t){return function(e,t){wy(t);const n=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Cy)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=Iy(e.charCodeAt(i)),s=Iy(e.charCodeAt(i+1));if(void 0===n||void 0===s)throw new Error('hex string expected, got non-hex character "'+(e[i]+e[i+1])+'" at index '+i);r[t]=16*n+s}return r}((e=function(e){if("bigint"==typeof e){if(!Gy(e))throw new Error("positive bigint expected, got "+e)}else wy(e);return e}(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}(e,t).reverse()}(b(e),l)}function w(e,t){const n=function(e,t){Ky("u",e,Jy,r),Ky("scalar",t,f,y);const n=t,i=e;let s=Zy,o=Jy,u=e,d=Zy,l=Jy;for(let e=BigInt(c-1);e>=Jy;e--){const t=n>>e&Zy;l^=t,({x_2:s,x_3:u}=P(l,s,u)),({x_2:o,x_3:d}=P(l,o,d)),l=t;const r=s+o,a=b(r*r),c=s-o,p=b(c*c),f=a-p,m=u+d,y=b((u-d)*r),g=b(m*c),v=y+g,w=y-g;u=b(v*v),d=b(i*b(w*w)),s=b(a*p),o=b(f*(a+b(h*f)))}({x_2:s,x_3:u}=P(l,s,u)),({x_2:o,x_3:d}=P(l,o,d));const p=a(o);return b(s*p)}(function(e){const t=Vy(Ty(e,l,"uCoordinate"));return u&&(t[31]&=127),b(zy(t))}(t),function(e){return zy(s(Vy(Ty(e,l,"scalar"))))}(e));if(n===Jy)throw new Error("invalid private or public key received");return v(n)}function T(e){return w(e,g)}const E=T,x=w;function P(e,t,n){const r=b(e*(t-n));return{x_2:t=b(t-r),x_3:n=b(n+r)}}const S={secretKey:l,publicKey:l,seed:l},A=(e=d(l))=>(Ty(e,S.seed,"seed"),e),C={randomSecretKey:A};return Object.freeze({keygen:Yy(A,E),getSharedSecret:x,getPublicKey:E,scalarMult:w,scalarMultBase:T,utils:C,GuBytes:g.slice(),lengths:S})}({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:n,b2:r}=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=ib,a=e*e%s*e%s,o=Qy(a,tb,s)*a%s,u=Qy(o,eb,s)*e%s,d=Qy(u,rb,s)*u%s,c=Qy(d,t,s)*d%s,l=Qy(c,n,s)*c%s,p=Qy(l,r,s)*l%s,h=Qy(p,i,s)*p%s,f=Qy(h,i,s)*p%s,m=Qy(f,t,s)*d%s;return{pow_p_5_8:Qy(m,tb,s)*e%s,b2:a}}(t);return Wy(Qy(n,nb,e)*r,e)},adjustScalarBytes:sb})})();class ob{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ey(e),Ty(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Py(r)}update(e){return xy(this),this.iHash.update(e),this}digestInto(e){xy(this),Ty(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:s,outputLen:a}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ub=(e,t,n)=>new ob(e,t).update(n).digest();ub.create=(e,t)=>new ob(e,t);const db=/* @__PURE__ */Uint8Array.of(0),cb=/* @__PURE__ */Uint8Array.of(),lb={hashSHA256:e=>qy(e.subarray()),getHKDF(e,t){const n=function(e,t,n){return Ey(e),void 0===n&&(n=new Uint8Array(e.outputLen)),ub(e,n,t)}(qy,t,e),r=function(e,t,n,r=32){Ey(e),wy(r,"length");const i=e.outputLen;if(r>255*i)throw new Error("Length must be <= 255*HashLen");const s=Math.ceil(r/i);void 0===n?n=cb:Ty(n,void 0,"info");const a=new Uint8Array(s*i),o=ub.create(e,t),u=o._cloneInto(),d=new Uint8Array(o.outputLen);for(let e=0;e<s;e++)db[0]=e+1,u.update(0===e?cb:d).update(n).update(db).digestInto(d),a.set(d,i*e),o._cloneInto(u);return o.destroy(),u.destroy(),Py(d,db),a.slice(0,r)}(qy,n,void 0,96),i=r;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){const e=ab.utils.randomSecretKey();return{publicKey:ab.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:ab.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>ab.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,n,r)=>gy(r,t,n).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,n,r,i)=>gy(r,t,n).decrypt(e.subarray(),i)},pb=lb,hb=e=>{const t=On(2);return t[0]=e>>8,t[1]=e,t};hb.bytes=2;const fb=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function mb(e,t){t.enabled&&$m&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${mr(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${mr(e.privateKey,"hex")}`)):t("Missing local static keys."))}function yb(e,t){t.enabled&&$m&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${mr(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${mr(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function bb(e,t){t.enabled&&$m&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${mr(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function gb(e,t,n){n.enabled&&$m&&(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&mr(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&mr(t.k,"hex")}`))}function vb(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");const n=On(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}fb.bytes=2;class wb extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=wb.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Tb{n;bytes;view;constructor(e=0){this.n=e,this.bytes=Nn(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const Eb=Nn(0);class xb{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Tb(n)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),r}}class Pb{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const n=fr(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=Nn(32);return e.set(t),e}return e.hash(t)}(e,n),this.ck=this.h,this.cs=new xb(e)}mixKey(e){const[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new xb(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new $n(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,Eb);return[new xb(this.crypto,e),new xb(this.crypto,t)]}}class Sb{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:n,prologue:r,initiator:i,s:s,e:a,rs:o,re:u}=e;this.crypto=t,this.ss=new Pb(t,n),this.ss.mixHash(r),this.initiator=i,this.s=s,this.e=a,this.rs=o,this.re=u}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");const n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");const r=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(r),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Ab extends Sb{writeMessageA(e){return new $n(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new $n(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new $n(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new wb(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new wb(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new wb(`handshake stage 2 validation fail: ${e.message}`)}}}var Cb,kb,Ib,Db,Mb;async function Fb(e,t,n){const r=await e.sign(_b(t));return kb.encode({identityKey:Fo(e.publicKey),identitySig:r,extensions:n})}async function Rb(e,t,n){try{const r=kb.decode(e),i=Mo(r.identityKey);if(!1===n?.equals(i))throw new Error(`Payload identity key ${i} does not match expected remote identity key ${n}`);if(!t)throw new Error("Remote static does not exist");const s=_b(t);if(!await i.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(e){throw new Ke(e.message)}}function _b(e){const t=fr("noise-libp2p-static-key:");return e instanceof Uint8Array?Bn([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const n of e.webtransportCerthashes)t.uint32(10),t.bytes(n);if(null!=e.streamMuxers)for(const n of e.streamMuxers)t.uint32(18),t.string(n);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={webtransportCerthashes:[],streamMuxers:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:if(null!=n.limits?.webtransportCerthashes&&r.webtransportCerthashes.length===n.limits.webtransportCerthashes)throw new Bp('Decode error - map field "webtransportCerthashes" had too many elements');r.webtransportCerthashes.push(e.bytes());break;case 2:if(null!=n.limits?.streamMuxers&&r.streamMuxers.length===n.limits.streamMuxers)throw new Bp('Decode error - map field "streamMuxers" had too many elements');r.streamMuxers.push(e.string());break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Cb||(Cb={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),Cb.codec().encode(e.extensions,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={identityKey:Nn(0),identitySig:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=Cb.codec().decode(e,e.uint32(),{limits:n.limits?.extensions});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(kb||(kb={}));class Lb extends Hd{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new yc({lengthDecoder:fb,maxBufferSize:16777216,encodingLength:()=>2}),this.stream.addEventListener("message",e=>{try{for(const t of this.decoder.decode(e.data))this.onData(this.decrypt(t))}catch(e){this.abort(e)}}),this.stream.addEventListener("close",e=>{null!=e.error?!0===e.local?this.abort(e.error):this.onRemoteReset():this.onTransportClosed()}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")}),this.stream.addEventListener("remoteCloseWrite",()=>{this.onRemoteCloseWrite()})}encrypt(e){const t=new $n;for(let n=0;n<e.byteLength;n+=65519){let r,i=n+65519;i>e.byteLength&&(i=e.byteLength),r=e instanceof Uint8Array?this.handshake.encrypt(e.subarray(n,i)):this.handshake.encrypt(e.sublist(n,i)),this.metrics?.encryptedPackets.increment(),t.append(hb(r.byteLength)),t.append(r)}return t}decrypt(e){const t=new $n;for(let n=0;n<e.byteLength;n+=qm){let r,i=n+qm;if(i>e.byteLength&&(i=e.byteLength),i-16<n)throw new Error("Invalid chunk");r=e instanceof Uint8Array?e.subarray(n,i):e.sublist(n,i);const s=e.subarray(n,i-16);try{const e=this.handshake.decrypt(r,s);this.metrics?.decryptedPackets.increment(),t.append(e)}catch(e){throw this.metrics?.decryptErrors.increment(),e}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function Nb(e,t,n){return new Lb(e,t,n)}class Ob{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){const{staticNoiseKey:n,extensions:r,crypto:i,prologueBytes:s}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const o=i??pb;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,n)=>e.generateX25519SharedKey(t.privateKey,n).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(o),this.extensions={webtransportCerthashes:[],...r},this.metrics=a?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(a):void 0,this.staticKey=n?o.generateX25519KeyPairFromSeed(n):o.generateX25519KeyPair(),this.prologue=s??Nn(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Rt]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const n=e.log?.newScope("noise")??this.log,r=fc(e,{lengthEncoder:hb,lengthDecoder:fb,maxDataLength:qm}),i=await this.performHandshakeInitiator(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Mo(i.payload.identityKey);return{connection:Nb(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:jo(s),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(null==e||0===e.length)return;const t=this.components.upgrader.getStreamMuxers();if(null!=t)for(const n of e){const e=t.get(n);if(null!=e)return e}if(e.length)throw new He("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){const n=e.log?.newScope("noise")??this.log,r=fc(e,{lengthEncoder:hb,lengthDecoder:fb,maxDataLength:qm}),i=await this.performHandshakeResponder(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Mo(i.payload.identityKey);return{connection:Nb(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:jo(s),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,r,i){let s;const a=!0===i?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:n,connection:r,crypto:i,privateKey:s,prologue:a,s:o,remoteIdentityKey:u,extensions:d}=e,c=await Fb(s,o.publicKey,d),l=new Ab({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:a,s:o});mb(l.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(l.writeMessageA(Eb),t),n.trace("Stage 0 - Initiator finished sending first message."),yb(l.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const p=l.readMessageB(await r.read(t));var h,f;n.trace("Stage 1 - Initiator received the message."),bb(l.re,n),h=l.rs,(f=n).enabled&&$m&&f(h?`REMOTE_STATIC_PUBLIC_KEY ${mr(h.subarray(),"hex")}`:"Missing remote static public key."),n.trace("Initiator going to check remote's signature...");const m=await Rb(p,l.rs,u);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(l.writeMessageC(c),t),n.trace("Stage 2 - Initiator sent message with signed payload.");const[y,b]=l.ss.split();return gb(y,b,n),{payload:m,encrypt:e=>y.encryptWithAd(Eb,e),decrypt:(e,t)=>b.decryptWithAd(Eb,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,n,r,i){let s;const a=!0===i?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:n,connection:r,crypto:i,privateKey:s,prologue:a,s:o,remoteIdentityKey:u,extensions:d}=e,c=await Fb(s,o.publicKey,d),l=new Ab({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:a,s:o});mb(l.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await r.read(t)),n.trace("Stage 0 - Responder received first message."),bb(l.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(l.writeMessageB(c),t),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),yb(l.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const p=l.readMessageC(await r.read(t));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await Rb(p,l.rs,u),[f,m]=l.ss.split();return gb(f,m,n),{payload:h,encrypt:e=>m.encryptWithAd(Eb,e),decrypt:(e,t)=>f.decryptWithAd(Eb,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}}function Bb(e={}){return t=>new Ob(t,e)}!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(Ib||(Ib={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(Db||(Db={})),Object.values(Db).filter(e=>"string"!=typeof e),function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(Mb||(Mb={}));const Ub=12;class jb extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}}class qb extends jb{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Mb.ProtocolError),this.name="InvalidFrameError"}}class $b extends jb{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Mb.ProtocolError),this.name="UnRequestedPingError"}}class zb extends jb{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Mb.ProtocolError),this.name="NotMatchingPingError"}}class Vb extends jb{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Mb.ProtocolError),this.name="ReceiveWindowExceededError"}}const Gb=262144,Kb=2**24;class Hb{buffer;constructor(){this.buffer=new $n}*emitFrames(e){for(this.buffer.append(e);;){const e=this.readFrame();if(void 0===e)break;yield e}}readFrame(){let e=Ub;if(this.buffer.byteLength<Ub)return;const t=function(e){if(0!==e[0])throw new qb("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*Kb+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*Kb+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,Ub));if(t.type===Ib.Data){if(e+=t.length,this.buffer.byteLength<e)return;const n=this.buffer.sublist(Ub,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}}function Wb(e){const t=new Uint8Array(Ub);return t[1]=e.type,t[2]=e.flag>>>8,t[3]=e.flag,t[4]=e.streamID>>>24,t[5]=e.streamID>>>16,t[6]=e.streamID>>>8,t[7]=e.streamID,t[8]=e.length>>>24,t[9]=e.length>>>16,t[10]=e.length>>>8,t[11]=e.length,t}var Qb;!function(e){e[e.Init=0]="Init",e[e.SYNSent=1]="SYNSent",e[e.SYNReceived=2]="SYNReceived",e[e.Established=3]="Established",e[e.Finished=4]="Finished",e[e.Paused=5]="Paused"}(Qb||(Qb={}));class Yb extends Yd{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){const t=e.initialStreamWindowSize??Gb;super({...e,maxMessageSize:t-Ub}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??16777216,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame,this.addEventListener("close",()=>{this.state=Qb.Finished})}sendData(e){const t=e.byteLength;let n=0,r=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(0===this.sendWindowCapacity){r=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}const i=Math.min(this.sendWindowCapacity,e.byteLength),s=this.getSendFlags(),a=e.sublist(0,i);e.consume(i);const o=this.sendFrame({type:Ib.Data,flag:s,streamID:this.streamId,length:i},a);if(this.sendWindowCapacity-=i,n+=i,!o){r=o,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:r}}sendReset(){this.sendFrame({type:Ib.WindowUpdate,flag:Db.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){const e=this.getSendFlags()|Db.FIN;this.sendFrame({type:Ib.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Qb.Paused}sendResume(){this.state=Qb.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-Ub,this.maxMessageSize<0&&(this.maxMessageSize=0),0!==this.maxMessageSize&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!function(e){return e.header.type===Ib.Data&&null!==e.data}(e))throw new qb("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Vb("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&Db.ACK)===Db.ACK&&this.state===Qb.SYNSent&&(this.state=Qb.Established),(e&Db.FIN)===Db.FIN&&this.onRemoteCloseWrite(),(e&Db.RST)===Db.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Qb.Init:return this.state=Qb.SYNSent,Db.SYN;case Qb.SYNReceived:return this.state=Qb.Established,Db.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Qb.Paused)return void(this.epochStart=Date.now());const e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(0===e&&n>-1&&t-this.epochStart<=4*n&&(this.recvWindow=Math.min(2*this.recvWindow,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&0===e)return;const r=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Ib.WindowUpdate,flag:e,streamID:this.streamId,length:r})}}function Jb(e){return{type:Ib[e.type],flags:[(e.flag&Db.SYN)===Db.SYN?"SYN":void 0,(e.flag&Db.ACK)===Db.ACK?"ACK":void 0,(e.flag&Db.FIN)===Db.FIN?"FIN":void 0,(e.flag&Db.RST)===Db.RST?"RST":void 0].filter(Boolean),streamID:e.streamID,length:e.length}}const Zb="/yamux/1.0.0";class Xb{protocol=Zb;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[Rt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new eg(e,{...this._init})}}class eg extends Qd{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:Zb,name:"yamux"}),this.client="outbound"===e.direction,function(e){if(null!=e.keepAliveInterval&&e.keepAliveInterval<=0)throw new We("keep-alive interval must be positive");if(null!=e.maxInboundStreams&&e.maxInboundStreams<0)throw new We("max inbound streams must be larger or equal 0");if(null!=e.maxOutboundStreams&&e.maxOutboundStreams<0)throw new We("max outbound streams must be larger or equal 0");if(null!=e.maxMessageSize&&e.maxMessageSize<1024)throw new We("MaxMessageSize must be greater than a kilobyte");if(null!=e.streamOptions?.initialStreamWindowSize&&e.streamOptions?.initialStreamWindowSize<Gb)throw new We("InitialStreamWindowSize must be larger or equal 256 kB");if(null!=e.streamOptions?.maxStreamWindowSize&&null!=e.streamOptions?.initialStreamWindowSize&&e.streamOptions?.maxStreamWindowSize<e.streamOptions?.initialStreamWindowSize)throw new We("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(null!=e.streamOptions?.maxStreamWindowSize&&e.streamOptions?.maxStreamWindowSize>2**32-1)throw new We("MaxStreamWindowSize must be less than equal MAX_UINT32")}(t),this.enableKeepAlive=t.enableKeepAlive??!0,this.keepAliveInterval=t.keepAliveInterval??3e4,this.maxInboundStreams=t.maxInboundStreams??1e3,this.maxOutboundStreams=t.maxOutboundStreams??1e3,this.decoder=new Hb,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Cc(async e=>{try{await this.ping(e)}catch(e){this.log.error("ping error: %s",e)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(const t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(void 0!==this.remoteGoAway)throw new Ze("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Ze("Muxer closed locally");const e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new yt("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);const t=this._newStream(e,Qb.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(void 0!==this.remoteGoAway)throw new Ze("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Ze("Muxer closed locally");if(null!=this.activePing)return $d(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await $d(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if("open"===this.status)try{const t=e?.reason??Mb.NormalTermination;this.log.trace("muxer close reason=%s",Mb[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if("open"===this.status)try{super.abort(e);let t=Mb.InternalError;(function(e){return null!==e?.reason})(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(null!=this.streams.find(t=>t.streamId===e))throw new We("Stream already exists with that id");const r=new Yb({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return r.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),r}closeStream(e){this.client===(e%2==0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){const{streamID:t,type:n,length:r}=e.header;if(this.log.trace("received frame %o",Jb(e.header)),0===t)switch(n){case Ib.Ping:return void this.handlePing(e.header);case Ib.GoAway:return void this.handleGoAway(r);default:throw new qb("Invalid frame type")}else switch(e.header.type){case Ib.Data:case Ib.WindowUpdate:return void this.handleStreamMessage(e);default:throw new qb("Invalid frame type")}}handlePing(e){if(e.flag===Db.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Db.ACK);else{if(e.flag!==Db.ACK)throw new qb("Invalid frame flag");this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length)}}handlePingResponse(e){if(void 0===this.activePing)throw new $b("ping not requested");if(this.activePing.id!==e)throw new zb("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Mb[e]??"unknown"),this.remoteGoAway=e,e===Mb.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){const{streamID:t,flag:n,type:r}=e.header;(n&Db.SYN)===Db.SYN&&this.incomingStream(t);const i=this.streams.find(e=>e.streamId===t);if(void 0!==i)switch(r){case Ib.WindowUpdate:return void i.handleWindowUpdate(e);case Ib.Data:return void i.handleData(e);default:throw new Error("unreachable")}else this.log.trace("frame for missing stream id=%s",t)}incomingStream(e){if(this.client!==(e%2==0))throw new We("Both endpoints are clients");if(this.streams.find(t=>t.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),void 0!==this.localGoAway)return void this.sendFrame({type:Ib.WindowUpdate,flag:Db.RST,streamID:e,length:0});if(this.numInboundStreams>=this.maxInboundStreams)return this.log("maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:Ib.WindowUpdate,flag:Db.RST,streamID:e,length:0});const t=this._newStream(e,Qb.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Ib.Data){if(null==t)throw new qb("Invalid frame");n=new $n(Wb(e),t)}else n=Wb(e);return this.log.trace("sending frame %o",Jb(e)),this.send(n)}sendPing(e,t=Db.SYN){this.log.trace(t===Db.SYN?"sending ping request pingId=%s":"sending ping response pingId=%s",e),this.sendFrame({type:Ib.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Mb.NormalTermination){this.log("sending GoAway reason=%s",Mb[e]),this.localGoAway=e,this.sendFrame({type:Ib.GoAway,flag:0,streamID:0,length:e})}}function tg(e={}){return()=>new Xb(e)}const ng=[6,53,56,54,55];function rg(e){return sg("sni",e)?.value}function ig(e){const t=sg("tcp",e)?.value;return null==t?"":`:${t}`}function sg(e,t){return t.find(t=>t.name===e)}function ag(e){return e.some(({code:e})=>e===tu)}function og(e,t){const n=ug[e.name];if(null==n)throw new Error(`Can't interpret protocol ${e.name}`);const r=n(e,t);return e.code===Xo?`[${r}]`:r}const ug={ip4:(e,t)=>e.value,ip6:(e,t)=>0===t.length?e.value:`[${e.value}]`,tcp:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`tcp://${og(n,t)}:${e.value}`},udp:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`udp://${og(n,t)}:${e.value}`},dnsaddr:(e,t)=>e.value,dns4:(e,t)=>e.value,dns6:(e,t)=>e.value,dns:(e,t)=>e.value,ipfs:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${og(n,t)}`},p2p:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${og(n,t)}`},http:(e,t)=>{const n=ag(t),r=rg(t),i=ig(t);if(n&&null!=r)return`https://${r}${i}`;const s=n?"https://":"http://",a=t.pop();if(null==a)throw new Error("Unexpected end of multiaddr");let o=og(a,t);return o=o?.replace("tcp://",""),`${s}${o}`},"http-path":(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${og(n,t)}${decodeURIComponent(e.value??"")}`},tls:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return og(n,t)},sni:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return og(n,t)},https:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=og(n,t);return r=r?.replace("tcp://",""),`https://${r}`},ws:(e,t)=>{const n=ag(t),r=rg(t),i=ig(t);if(n&&null!=r)return`wss://${r}${i}`;const s=n?"wss://":"ws://",a=t.pop();if(null==a)throw new Error("Unexpected end of multiaddr");let o=og(a,t);return o=o?.replace("tcp://",""),`${s}${o}`},wss:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=og(n,t);return r=r?.replace("tcp://",""),`wss://${r}`}};class dg extends Wd{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??4194304,this.checkBufferedAmountTask=Cc(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??10),this.websocket.addEventListener("close",e=>{this.log('closed - code %d, reason "%s", wasClean %s',e.code,e.reason,e.wasClean),this.checkBufferedAmountTask.stop(),e.wasClean?this.onTransportClosed():this.onRemoteReset()},{once:!0}),this.websocket.addEventListener("message",e=>{try{let t;if("string"==typeof e.data)t=fr(e.data);else{if(!(e.data instanceof ArrayBuffer))return void this.abort(new Error("Incorrect binary type"));t=new Uint8Array(e.data,0,e.data.byteLength)}this.onData(t)}catch(e){this.log.error("error receiving data - %e",e)}})}sendData(e){for(const t of e)this.websocket.send(t);const t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),0===this.websocket.bufferedAmount&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}}class cg{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Dt]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Rt]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const n=(r={websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval},new dg(r));var r;this.log("new outbound connection %s",n.remoteAddr);const i=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),i}async _connect(e,t){t?.signal?.throwIfAborted();const n=function(e){const t=Pu(e).getComponents(),n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");const r=ug[n.name];if(null==r)throw new Error(`No interpreter found for ${n.name}`);let i=r(n,t)??"";return ng.includes(n.code)&&(i=i.replace(/^.*:\/\//,""),i="443"===n.value?`https://${i}`:`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}(e);this.log("create websocket connection to %s",n);const r=new WebSocket(n);r.binaryType="arraybuffer";try{t.onProgress?.(new _f("websockets:open-connection")),await _d(r,"open",t)}catch(e){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Je(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{r.close()}catch{}throw e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),r}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}()}listenFilter(e){return e.filter(e=>$h.exactMatch(e)||Vh.exactMatch(e))}dialFilter(e){return this.listenFilter(e)}}function lg(e={}){return t=>new cg(t,e)}class pg{constructor(){throw new Error("TCP connections are not possible in browsers")}[Dt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Rt]=["@libp2p/transport"];async dial(){throw new Error("TCP connections are not possible in browsers")}createListener(){throw new Error("TCP connections are not possible in browsers")}listenFilter(){return[]}dialFilter(){return[]}}function hg(e={}){return t=>new pg(t,e)}const fg=`${At}-circuit-relay`;BigInt(1<<17);const mg="/libp2p/circuit/relay/0.2.0/hop",yg="/libp2p/circuit/relay/0.2.0/stop",bg=new Float32Array([-0]),gg=new Uint8Array(bg.buffer);function vg(e,t,n){bg[0]=e,t[n]=gg[0],t[n+1]=gg[1],t[n+2]=gg[2],t[n+3]=gg[3]}const wg=new Float64Array([-0]),Tg=new Uint8Array(wg.buffer);function Eg(e,t,n){wg[0]=e,t[n]=Tg[0],t[n+1]=Tg[1],t[n+2]=Tg[2],t[n+3]=Tg[3],t[n+4]=Tg[4],t[n+5]=Tg[5],t[n+6]=Tg[6],t[n+7]=Tg[7]}const xg=BigInt(Number.MAX_SAFE_INTEGER),Pg=BigInt(Number.MIN_SAFE_INTEGER);class Sg{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(0n===e)return Ag;if(e<xg&&e>Pg)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let n=e>>32n,r=e-(n<<32n);return t&&(n=0n|~n,r=0n|~r,++r>Cg&&(r=0n,++n>Cg&&(n=0n))),new Sg(Number(r),Number(n))}static fromNumber(e){if(0===e)return Ag;const t=e<0;t&&(e=-e);let n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new Sg(n,r)}static from(e){return"number"==typeof e?Sg.fromNumber(e):"bigint"==typeof e?Sg.fromBigInt(e):"string"==typeof e?Sg.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Sg(e.low>>>0,e.high>>>0):Ag}}const Ag=new Sg(0,0);Ag.toBigInt=function(){return 0n},Ag.zzEncode=Ag.zzDecode=function(){return this},Ag.length=function(){return 1};const Cg=4294967296n;function kg(e,t,n){const r=n;let i,s;for(let r=0;r<e.length;++r)i=e.charCodeAt(r),i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=e.charCodeAt(r+1)))?(i=65536+((1023&i)<<10)+(1023&s),++r,t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128);return n-r}function Ig(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Dg(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Mg{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ig(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Ig(this,4);return Dg(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ig(this,4);return 0|Dg(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Ig(this,4);const e=(gg[0]=(t=this.buf)[n=this.pos],gg[1]=t[n+1],gg[2]=t[n+2],gg[3]=t[n+3],bg[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ig(this,4);const e=(Tg[0]=(t=this.buf)[n=this.pos],Tg[1]=t[n+1],Tg[2]=t[n+2],Tg[3]=t[n+3],Tg[4]=t[n+4],Tg[5]=t[n+5],Tg[6]=t[n+6],Tg[7]=t[n+7],wg[0]);var t,n;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Ig(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){const e=this.bytes();return function(e,t,n){if(n-t<1)return"";let r;const i=[];let s,a=0;for(;t<n;)s=e[t++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=r?(a>0&&r.push(String.fromCharCode.apply(String,i.slice(0,a))),r.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Ig(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Ig(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Sg(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Ig(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ig(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ig(this,8);const e=Dg(this.buf,this.pos+=4),t=Dg(this.buf,this.pos+=4);return new Sg(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=ba(this.buf,this.pos);return this.pos+=ma(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Fg(e){return new Mg(e instanceof Uint8Array?e:e.subarray())}function Rg(e,t,n){const r=Fg(e);return t.decode(r,void 0,n)}class _g{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Lg(){}class Ng{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Og=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return On(r);n+r>e&&(t=On(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class Bg{len;head;tail;states;constructor(){this.len=0,this.head=new _g(Lg,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new _g(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new qg((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push($g,10,Sg.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Sg.fromBigInt(e);return this._push($g,t.length(),t)}uint64Number(e){return this._push(ya,ma(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=Sg.fromBigInt(e).zzEncode();return this._push($g,t.length(),t)}sint64Number(e){const t=Sg.fromNumber(e).zzEncode();return this._push($g,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ug,1,e?1:0)}fixed32(e){return this._push(zg,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Sg.fromBigInt(e);return this._push(zg,4,t.lo)._push(zg,4,t.hi)}fixed64Number(e){const t=Sg.fromNumber(e);return this._push(zg,4,t.lo)._push(zg,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(vg,4,e)}double(e){return this._push(Eg,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Ug,1,0):this.uint32(t)._push(Vg,t,e)}string(e){const t=function(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(kg,t,e):this._push(Ug,1,0)}fork(){return this.states=new Ng(this),this.head=this.tail=new _g(Lg,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new _g(Lg,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),0!==n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next;const t=(n=this.len,null!=globalThis.Buffer?On(n):Og(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function Ug(e,t,n){t[n]=255&e}function jg(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class qg extends _g{next;constructor(e,t){super(jg,e,t),this.next=void 0}}function $g(e,t,n){for(;0!==e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function zg(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function Vg(e,t,n){t.set(e,n)}function Gg(e,t,n){t.set(e,n)}function Kg(e,t,n){e.length<40?kg(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(fr(e),n)}function Hg(e,t){const n=new Bg;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*Wg(e,t,n){const r=Fg(e);yield*t.stream(r,void 0,"$",n)}function Qg(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function Yg(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Qg("enum",0,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())},function*(e){const n=e.int32();yield t(n)})}function Jg(e,t,n){return Qg("message",2,e,t,n)}null!=globalThis.Buffer&&(Bg.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Gg,t,e),this},Bg.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Kg,t,e),this});class Zg extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var Xg,ev,tv,nv,rv,iv,sv,av,ov;!function(e){var t;let n,r;(t=e.Type||(e.Type={})).RESERVE="RESERVE",t.CONNECT="CONNECT",t.STATUS="STATUS",function(e){e[e.RESERVE=0]="RESERVE",e[e.CONNECT=1]="CONNECT",e[e.STATUS=2]="STATUS"}(n||(n={})),function(e){e.codec=()=>Yg(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Jg((t,n,r={})=>{!1!==r.lengthDelimited&&n.fork(),null!=t.type&&(n.uint32(8),e.Type.codec().encode(t.type,n)),null!=t.peer&&(n.uint32(18),tv.codec().encode(t.peer,n)),null!=t.reservation&&(n.uint32(26),nv.codec().encode(t.reservation,n)),null!=t.limit&&(n.uint32(34),rv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(40),iv.codec().encode(t.status,n)),!1!==r.lengthDelimited&&n.ldelim()},(t,n,r={})=>{const i={},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:i.peer=tv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.reservation=nv.codec().decode(t,t.uint32(),{limits:r.limits?.reservation});break;case 4:i.limit=rv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 5:i.status=iv.codec().decode(t);break;default:t.skipType(7&n)}}return i},function*(t,n,r,i={}){const s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:yield{field:`${r}.type`,value:e.Type.codec().decode(t)};break;case 2:yield*tv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*nv.codec().stream(t,t.uint32(),`${r}.reservation`,{limits:i.limits?.reservation});break;case 4:yield*rv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 5:yield{field:`${r}.status`,value:iv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(Xg||(Xg={})),function(e){var t;let n,r;(t=e.Type||(e.Type={})).CONNECT="CONNECT",t.STATUS="STATUS",function(e){e[e.CONNECT=0]="CONNECT",e[e.STATUS=1]="STATUS"}(n||(n={})),function(e){e.codec=()=>Yg(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Jg((t,n,r={})=>{!1!==r.lengthDelimited&&n.fork(),null!=t.type&&(n.uint32(8),e.Type.codec().encode(t.type,n)),null!=t.peer&&(n.uint32(18),tv.codec().encode(t.peer,n)),null!=t.limit&&(n.uint32(26),rv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(32),iv.codec().encode(t.status,n)),!1!==r.lengthDelimited&&n.ldelim()},(t,n,r={})=>{const i={},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:i.peer=tv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.limit=rv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 4:i.status=iv.codec().decode(t);break;default:t.skipType(7&n)}}return i},function*(t,n,r,i={}){const s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:yield{field:`${r}.type`,value:e.Type.codec().decode(t)};break;case 2:yield*tv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*rv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 4:yield{field:`${r}.status`,value:iv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(ev||(ev={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.addrs&&e.addrs.length>0)for(const n of e.addrs)t.uint32(18),t.bytes(n);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={id:Nn(0),addrs:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.id=e.bytes();break;case 2:if(null!=n.limits?.addrs&&r.addrs.length===n.limits.addrs)throw new Zg('Decode error - repeated field "addrs" had too many elements');r.addrs.push(e.bytes());break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i={addrs:0},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.id`,value:e.bytes()};break;case 2:if(null!=r.limits?.addrs&&i.addrs===r.limits.addrs)throw new Zg('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${n}.addrs[]`,index:i.addrs,value:e.bytes()},i.addrs++;break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(tv||(tv={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.expire&&0n!==e.expire&&(t.uint32(8),t.uint64(e.expire)),null!=e.addrs&&e.addrs.length>0)for(const n of e.addrs)t.uint32(18),t.bytes(n);null!=e.voucher&&(t.uint32(26),ov.codec().encode(e.voucher,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={expire:0n,addrs:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.expire=e.uint64();break;case 2:if(null!=n.limits?.addrs&&r.addrs.length===n.limits.addrs)throw new Zg('Decode error - repeated field "addrs" had too many elements');r.addrs.push(e.bytes());break;case 3:r.voucher=ov.codec().decode(e,e.uint32(),{limits:n.limits?.voucher});break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i={addrs:0},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.expire`,value:e.uint64()};break;case 2:if(null!=r.limits?.addrs&&i.addrs===r.limits.addrs)throw new Zg('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${n}.addrs[]`,index:i.addrs,value:e.bytes()},i.addrs++;break;case 3:yield*ov.codec().stream(e,e.uint32(),`${n}.voucher`,{limits:r.limits?.voucher});break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(nv||(nv={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.duration&&(t.uint32(8),t.uint32(e.duration)),null!=e.data&&(t.uint32(16),t.uint64(e.data)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.duration=e.uint32();break;case 2:r.data=e.uint64();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.duration`,value:e.uint32()};break;case 2:yield{field:`${n}.data`,value:e.uint64()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(rv||(rv={})),function(e){e.UNUSED="UNUSED",e.OK="OK",e.RESERVATION_REFUSED="RESERVATION_REFUSED",e.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.NO_RESERVATION="NO_RESERVATION",e.MALFORMED_MESSAGE="MALFORMED_MESSAGE",e.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"}(iv||(iv={})),function(e){e[e.UNUSED=0]="UNUSED",e[e.OK=100]="OK",e[e.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",e[e.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",e[e.PERMISSION_DENIED=202]="PERMISSION_DENIED",e[e.CONNECTION_FAILED=203]="CONNECTION_FAILED",e[e.NO_RESERVATION=204]="NO_RESERVATION",e[e.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",e[e.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"}(sv||(sv={})),function(e){e.codec=()=>Yg(sv)}(iv||(iv={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.relay&&e.relay.byteLength>0&&(t.uint32(10),t.bytes(e.relay)),null!=e.peer&&e.peer.byteLength>0&&(t.uint32(18),t.bytes(e.peer)),null!=e.expiration&&0n!==e.expiration&&(t.uint32(24),t.uint64(e.expiration)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={relay:Nn(0),peer:Nn(0),expiration:0n},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.relay=e.bytes();break;case 2:r.peer=e.bytes();break;case 3:r.expiration=e.uint64();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.relay`,value:e.bytes()};break;case 2:yield{field:`${n}.peer`,value:e.bytes()};break;case 3:yield{field:`${n}.expiration`,value:e.uint64()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(av||(av={})),function(e){let t;e.codec=()=>(null==t&&(t=Jg((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&(t.uint32(26),av.codec().encode(e.payload,t)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={publicKey:Nn(0),payloadType:Nn(0),signature:Nn(0)},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=av.codec().decode(e,e.uint32(),{limits:n.limits?.payload});break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r},function*(e,t,n,r={}){const i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:yield{field:`${n}.publicKey`,value:e.bytes()};break;case 2:yield{field:`${n}.payloadType`,value:e.bytes()};break;case 3:yield*av.codec().stream(e,e.uint32(),`${n}.payload`,{limits:r.limits?.payload});break;case 5:yield{field:`${n}.signature`,value:e.bytes()};break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Hg(t,e.codec())},e.decode=function(t,n){return Rg(t,e.codec(),n)},e.stream=function(t,n){return Wg(t,e.codec(),n)}}(ov||(ov={}));class uv extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"}class dv extends Error{static name="DoubleRelayError";name="DoubleRelayError"}class cv extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"}function lv(e){const t=e*BigInt(1e3),n=(new Date).getTime();return Number(t-BigInt(n))}class pv{expires;bytes;constructor(e){null!=e?.duration&&0!==e?.duration&&(this.expires=Date.now()+1e3*e.duration),this.bytes=e?.data,0n===this.bytes&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){null!=this.bytes&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(null==this.expires&&null==this.bytes)return;const e={};if(null!=this.bytes){const t=this;Object.defineProperty(e,"bytes",{get:()=>t.bytes})}if(null!=this.expires){const t=this;Object.defineProperty(e,"seconds",{get:()=>Math.round(((t.expires??0)-Date.now())/1e3)})}return e}}const hv=wh(vh(Yh.matchers[0],mh(su))),fv=wh(mh(su));class mv extends Ft{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(mg,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){null!=this.topologyId&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");const e=await this.components.peerStore.all({filters:[e=>e.protocols.includes(mg)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{const n=yv(e),r=yv(t);return n>r?-1:r>n?1:0}]});for(const t of e)this.log.trace("found relay peer %p in peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});this.log("found %d relay peers in peer store",e.length);const t=this.queue=new xc({concurrency:5});this.log("start random walk");for await(const e of this.components.randomWalk.walk({signal:this.discoveryController.signal}))this.log.trace("found random peer %p",e.id),t.has(e.id)?this.log.trace("random peer %p was already in queue",e.id):this.components.connectionManager.getConnections(e.id)?.length>0?this.log.trace("random peer %p was already connected",e.id):await this.components.connectionManager.isDialable(e.multiaddrs)?(t.queued>10&&(this.log.trace("wait for space in queue for %p",e.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",e.id,t.size,t.running),t.add(this.dialPeer,{peerId:e.id,signal:this.discoveryController.signal}).catch(t=>{this.log.error("error opening connection to random peer %p - %e",e.id,t)})):this.log.trace("random peer %p was not dialable",e.id,e.multiaddrs.map(e=>e.toString()));this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(null==this.queue)return;const t=e.detail.id,n=e.detail.multiaddrs;this.queue.has(t)?this.log.trace("random peer %p was already in queue",t):this.components.connectionManager.getConnections(t)?.length>0?this.log.trace("random peer %p was already connected",t):await this.components.connectionManager.isDialable(n)?this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(t=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,t)}):this.log.trace("random peer %p was not dialable",t)}async dialPeer({peerId:e,signal:t}){const n=Jd([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}}function yv(e){const t=e.metadata.get("last-dial-success");return null==t?0:new Date(mr(t)).getTime()}class bv extends Ft{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??5e3,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),!0===this.relay?.equals(e.detail.relay)&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(e=>{this.addressManager.removeObservedAddr(e)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{const{details:t}=e.detail;"configured"!==t.type&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(fv.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else{if(!hv.exactMatch(e))throw new ht(`Could not listen on p2p-circuit address "${e}"`);{this.log("listen on specific relay server %a",e);const t=AbortSignal.timeout(this.listenTimeout),n=e.decapsulate("/p2p-circuit"),r=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(r.remotePeer)){this.log("making reservation on peer %p",r.remotePeer);const e=await this.reservationStore.addRelay(r.remotePeer,"configured");this.addedRelay(e)}}}}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(e=>Pu(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}}class gv extends Ft{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Xu,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??5e3,this.started=!1,this.relayFilter=pd(100),this.reserveQueue=new xc({concurrency:t?.reservationConcurrency??1,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",e=>{null!=[...this.reservations.values()].find(t=>t.connection===e.detail.id)&&this.#J(e.detail.remotePeer).catch(t=>{this.log("could not remove relay %p - %e",e.detail,t)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{const e=await this.peerStore.all({filters:[e=>e.tags.has(fg)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async e=>{await this.peerStore.merge(e.id,{tags:{[fg]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async e=>this.addRelay(e.id,"discovered"))),this.#Z()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){const e=((e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t})();return this.pendingReservations.push(e),this.#Z(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new ht("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new cv("The reservation queue is full");const n=this.reserveQueue.find(e);if(null!=n)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new ht("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{const n=Date.now();try{const n=this.reservations.get(e);if(null!=n){const t=this.connectionManager.getConnections(e);let r=!1;if(0===t.length&&this.log("already have relay reservation with %p but we are no longer connected",e),t.map(e=>e.id).includes(n.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),r=!0),r&&lv(n.reservation.expire)>6e5)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:n};await this.#J(e)}if("discovered"===t&&0===this.pendingReservations.length)throw new uv("Not making reservation on discovered relay because we do not need any more relays");const r=AbortSignal.timeout(this.reservationCompletionTimeout),i=await this.connectionManager.openConnection(e,{signal:r});if(Zh.matches(i.remoteAddr))throw new dv("not creating reservation over relayed connection");const s=await this.#X(i,{signal:r}),a=lv(s.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+a).toString());const o=Math.min(Math.max(a-3e5,3e4),Math.pow(2,31)-1),u=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async t=>{this.log.error("could not refresh reservation to relay %p - %e",e,t),await this.#J(e)}).catch(t=>{this.log.error("could not remove expired reservation to relay %p - %e",e,t)})},o);let d;if("discovered"===t){const e=this.pendingReservations.pop();if(null==e)throw new uv("Made reservation on relay but did not need any more discovered relays");d={timeout:u,reservation:s,type:t,connection:i.id,id:e}}else d={timeout:u,reservation:s,type:t,connection:i.id};this.reservations.set(e,d),await this.peerStore.merge(e,{tags:{[fg]:{value:1,ttl:a}}}),this.#Z();const c={relay:e,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:c}),c}catch(r){throw"discovered"===t&&"HadEnoughRelaysError"===r.name||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-n,r),"DialError"!==r.name&&"UnsupportedProtocolError"!==r.name||this.relayFilter.add(e.toMultihash().bytes),this.#J(e).catch(t=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,t)}),r}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return null==e?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#X(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);const n=await e.newStream(mg,t),r=mc(n).pb(Xg);let i;this.log.trace("send RESERVE to %p",e.remotePeer),await r.write({type:Xg.Type.RESERVE},t);try{this.log.trace("reading response from %p",e.remotePeer),i=await r.read(t)}catch(e){throw n.abort(e),e}finally{"closed"!==n.status&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===iv.OK&&null!=i.reservation){const t=new Set;t.add(e.remoteAddr.toString());for(const n of i.reservation.addrs){let r=Pu(n);null==r.getComponents().find(e=>e.code===eu)&&(r=r.encapsulate(`/p2p/${e.remotePeer}`)),r=Pu(r.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),t.add(r.toString())}return i.reservation.addrs=[...t].map(e=>Pu(e).bytes),i.reservation}const s=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(s),new Error(s)}async#J(e){const t=this.reservations.get(e);null!=t&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),"discovered"===t.type&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[fg]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#Z())}#Z(){if(0===this.pendingReservations.length)return this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),void this.safeDispatchEvent("relay:found-enough-relays");this.relayFilter=pd(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}}class vv extends Wd{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",e=>{this.onTransportClosed(e.error)}),this.stream.addEventListener("remoteCloseWrite",e=>{this.onRemoteCloseWrite(),this.close().catch(e=>{this.abort(e)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}}function wv(e){return new vv(e)}class Tv{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??300,this.maxOutboundStopStreams=t.maxOutboundStopStreams??300,this.shutdownController=new AbortController,this.discovery=new mv(e,{filter:t.discoveryFilter??Mc(4096,.001)}),this.discovery.addEventListener("relay:discover",e=>{this.reservationStore.addRelay(e.detail,"discovered").catch(t=>{"HadEnoughRelaysError"!==t.name&&"RelayQueueFullError"!==t.name&&this.log.error("could not add discovered relay %p - %e",e.detail,t)})}),this.reservationStore=new gv(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Rt]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[_t](){return null!=this.discovery?["@libp2p/identify"]:[]}[Dt]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.components.registrar.handle(yg,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await kt(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await It(this.discovery,this.reservationStore),await this.components.registrar.unhandle(yg),this.started=!1}async dial(e,t){const n=e.toString().split("/p2p-circuit"),r=Pu(n[0]),i=Pu(n[n.length-1]),s=r.getComponents().find(e=>e.code===eu)?.value,a=i.getComponents().find(e=>e.code===eu)?.value;if(null==s||null==a){const t=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${t}`),new pt(`C${t}`)}const o=Uo(s),u=Uo(a);let d,c=this.components.connectionManager.getConnections(o)[0];null==c?(await this.components.peerStore.merge(o,{multiaddrs:[r]}),t.onProgress?.(new _f("circuit-relay:open-connection")),c=await this.components.connectionManager.openConnection(o,t)):t.onProgress?.(new _f("circuit-relay:reuse-connection"));try{t.onProgress?.(new _f("circuit-relay:open-hop-stream")),d=await c.newStream(mg,t);const n=mc(d).pb(Xg);t.onProgress?.(new _f("circuit-relay:write-connect-message")),await n.write({type:Xg.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Pu(i).bytes]}},t),t.onProgress?.(new _f("circuit-relay:read-connect-response"));const s=await n.read(t);if(s.status!==iv.OK)throw new ut(`failed to connect via relay with status ${s?.status?.toString()??"undefined"}`);const a=new pv(s.limit),o=wv({stream:n.unwrap().unwrap(),remoteAddr:e,localAddr:r.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:a.onData,onDataWrite:a.onData,log:d.log.newScope("circuit-relay:connection")}),l=await this.components.upgrader.upgradeOutbound(o,{...t,limits:a.getLimits()});return l.log("outbound relayed connection established to %p with limits %o, over connection %s",l.remotePeer,s.limit??"none",c.id),l}catch(e){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",u,o,e),d?.abort(e),e}}createListener(e){return function(e){return new bv(e)}({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return(e=Array.isArray(e)?e:[e]).filter(e=>hv.exactMatch(e)||fv.exactMatch(e))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter(e=>Zh.exactMatch(e))}async onStop(e,t){const n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(e){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",e)}const r=mc(e).pb(ev),i=await r.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),void 0===i?.type)return this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});if(i.type!==ev.Type.CONNECT)return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.UNEXPECTED_MESSAGE},{signal:n}),void await e.close({signal:n});if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(Pu)}catch{return!1}return!0})(i))return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});const s=qo(xn(i.peer.id));if(!0===await(this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)))return this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.PERMISSION_DENIED},{signal:n}),void await e.close({signal:n});this.log.trace("sending success response to %p",t.remotePeer),await r.write({type:ev.Type.STATUS,status:iv.OK},{signal:n});const a=new pv(i.limit),o=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),u=this.components.addressManager.getAddresses()[0],d=wv({stream:r.unwrap().unwrap(),remoteAddr:o,localAddr:u,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(d,{limits:a.getLimits(),signal:n}),d.log("inbound relayed connection established to %p with limits %o, over connection %s",s,i.limit??"none",t.id)}finally{n?.clear()}}}function Ev(e={}){return t=>new Tv(t,e)}class xv extends Ft{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=t.list.map(e=>Pu(e)).filter(e=>{if(!Yh.matches(e))return this.log.error("invalid multiaddr %a",e),!1;const t=e.getComponents().findLast(e=>e.code===eu)?.value;return null!=t||(this.log.error("invalid bootstrap multiaddr without peer id"),!1)}).map(e=>({id:Uo(e.getComponents().findLast(e=>e.code===eu)?.value??""),multiaddrs:[e]})),this._init=t}[Et]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Rt]=["@libp2p/peer-discovery"];isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}var Pv;!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const n of e.listenAddrs)t.uint32(18),t.bytes(n);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const n of e.protocols)t.uint32(26),t.string(n);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={listenAddrs:[],protocols:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 5:r.protocolVersion=e.string();break;case 6:r.agentVersion=e.string();break;case 1:r.publicKey=e.bytes();break;case 2:if(null!=n.limits?.listenAddrs&&r.listenAddrs.length===n.limits.listenAddrs)throw new Bp('Decode error - map field "listenAddrs" had too many elements');r.listenAddrs.push(e.bytes());break;case 4:r.observedAddr=e.bytes();break;case 3:if(null!=n.limits?.protocols&&r.protocols.length===n.limits.protocols)throw new Bp('Decode error - map field "protocols" had too many elements');r.protocols.push(e.string());break;case 8:r.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Pv||(Pv={}));const Sv="ipfs";class Av{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??5e3,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.maxMessageSize=t.maxMessageSize??8192,this.maxObservedAddresses=t.maxObservedAddresses??10,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.host={protocolVersion:`${t.protocolPrefix??Sv}/0.1.0`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:fr(this.host.agentVersion),ProtocolVersion:fr(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}}class Cv extends Av{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Sv}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??1)&&e.events.addEventListener("connection:open",e=>{this.identify(e.detail).catch(()=>{})})}[Rt]=["@libp2p/identify"];async _identify(e,t={}){let n,r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),r=n.log.newScope("identify");const i=mc(n,{maxDataLength:this.maxMessageSize}).pb(Pv),s=await i.read(t);return await i.unwrap().unwrap().close(t),s}catch(e){throw r?.error("identify failed - %e",e),n?.abort(e),e}}async identify(e,t={}){const n=await this._identify(e,t),{publicKey:r,protocols:i,observedAddr:s}=n;if(null==r)throw new ut("Public key was missing from identify message");const a=$o(Mo(r).toCID());if(!e.remotePeer.equals(a))throw new ut("Identified peer does not match the expected peer");if(this.components.peerId.equals(a))throw new ut("Identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("completed for peer %p and protocols %o",a,i),async function(e,t,n,r,i){if(n("received identify from %p",r.remotePeer),null==i)throw new ut("message was null or undefined");const s={};if(i.listenAddrs.length>0&&(s.addresses=i.listenAddrs.map(e=>({isCertified:!1,multiaddr:Pu(e)}))),i.protocols.length>0&&(s.protocols=i.protocols),null!=i.publicKey){const e=Mo(i.publicKey);if(!jo(e).equals(r.remotePeer))throw new ut("public key did not match remote PeerId");s.publicKey=e}let a;if(null!=i.signedPeerRecord){n.trace("received signedPeerRecord from %p",r.remotePeer);let t=i.signedPeerRecord;const o=await yl.openAndCertify(t,wl.DOMAIN);let u=wl.createFromProtobuf(o.payload);const d=$o(o.publicKey.toCID());if(!u.peerId.equals(d))throw new ut("signing key does not match PeerId in the PeerRecord");if(!r.remotePeer.equals(u.peerId))throw new ut("signing key does not match remote PeerId");let c;try{c=await e.get(u.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=c&&(s.metadata=c.metadata,null!=c.peerRecordEnvelope)){const e=yl.createFromProtobuf(c.peerRecordEnvelope),r=wl.createFromProtobuf(e.payload);r.seqNumber>=u.seqNumber&&(n("sequence number was lower or equal to existing sequence number - stored: %d received: %d",r.seqNumber,u.seqNumber),u=r,t=c.peerRecordEnvelope)}s.peerRecordEnvelope=t,s.addresses=u.multiaddrs.map(e=>({isCertified:!0,multiaddr:e})),a={seq:u.seqNumber,addresses:u.multiaddrs}}else n("%p did not send a signed peer record",r.remotePeer);if(n.trace("patching %p with",r.remotePeer,s),await e.patch(r.remotePeer,s),null!=i.agentVersion||null!=i.protocolVersion){const t={};null!=i.agentVersion&&(t.AgentVersion=fr(i.agentVersion)),null!=i.protocolVersion&&(t.ProtocolVersion=fr(i.protocolVersion)),n.trace("merging %p metadata",r.remotePeer,t),await e.merge(r.remotePeer,{metadata:t})}const o={peerId:r.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map(e=>Pu(e)),observedAddr:null==i.observedAddr?void 0:Pu(i.observedAddr),protocols:i.protocols,signedPeerRecord:a,connection:r};return t.safeDispatchEvent("peer:identify",{detail:o}),o}(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Pu(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),Ad(t))return;const n=t.getComponents();n[0].code!==Xo&&(42!==n[0].code||n[1].code!==Xo)||function(e){try{const n=hd(e);return"ip6"===n.type&&(t=n.host,new bd("2000::/3").contains(t))}catch{return!1}var t}(t)?Lh.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(e,t){const n=e.log.newScope("identify");n("responding to identify");const r=AbortSignal.timeout(this.timeout),i=await this.components.peerStore.get(this.components.peerId,{signal:r}),s=this.components.addressManager.getAddresses().map(e=>e.decapsulateCode(eu));let a=i.peerRecordEnvelope;if(s.length>0&&null==a){const e=new wl({peerId:this.components.peerId,multiaddrs:s});a=(await yl.seal(e,this.components.privateKey,{signal:r})).marshal().subarray()}let o=t.remoteAddr.bytes;Dh.matches(t.remoteAddr)||(o=void 0);const u=mc(e).pb(Pv);n("send response"),await u.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Fo(this.components.privateKey.publicKey),listenAddrs:s.map(e=>e.bytes),signedPeerRecord:a,observedAddr:o,protocols:i.protocols},{signal:r}),n("close write"),await u.unwrap().unwrap().close({signal:r})}}function kv(e={}){return t=>new Cv(t,e)}const Iv=36e5,Dv=48*Iv,Mv=Iv,Fv=Iv,Rv=`${At}-kad-dht`;var _v,Lv,Nv,Ov,Bv,Uv,jv,qv;function $v(e){const t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0"),i=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0"),o=e.getUTCMilliseconds();return`${t}-${n}-${r}T${i}:${s}:${a}.${String(1e3*o*1e3).padStart(9,"0")}Z`}!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&e.key.byteLength>0&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),null!=e.timeReceived&&""!==e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={key:Nn(0),value:Nn(0),timeReceived:""},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(_v||(_v={}));class zv{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return _v.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:$v(this.timeReceived)}}static deserialize(e){const t=_v.decode(e);return new zv(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){const t=function(e){const t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),n=String(e).trim().match(t);if(null==n)throw new Error("Invalid format");const r=parseInt(n[1],10),i=parseInt(n[2],10)-1,s=parseInt(n[3],10),a=parseInt(n[4],10),o=parseInt(n[5],10),u=parseInt(n[6],10),d=parseInt(n[7].slice(0,-6),10);return new Date(Date.UTC(r,i,s,a,o,u,d))}(e.timeReceived);if(null==e.key)throw new Error("key missing from deserialized object");if(null==e.value)throw new Error("value missing from deserialized object");return new zv(e.key,e.value,t)}}function Vv(e,t){let n=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const r of e)yield t(r,n++)}();const r=dh(e),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const a=t(i,n++);if("function"==typeof a.then)return async function*(){yield await a;for(const e of r)yield t(e,n++)}();const o=t;return function*(){yield a;for(const e of r)yield o(e,n++)}()}class Gv extends Error{constructor(e="Query error"){super(e),this.name="QueryError"}}class Kv extends Error{constructor(e="Invalid record"){super(e),this.name="InvalidRecordError"}}class Hv extends Error{constructor(e="No selector function configured for prefix"){super(e),this.name="MissingSelectorError"}}function Wv(e,t={}){const n={...e,name:"SEND_QUERY",type:0,messageName:e.type,messageType:e.type};return t.onProgress?.(new CustomEvent("kad-dht:query:send-query",{detail:n})),n}function Qv(e,t={}){const n={...e,name:"PEER_RESPONSE",type:1,messageName:e.messageType,closer:e.closer??[],providers:e.providers??[]};return t.onProgress?.(new CustomEvent("kad-dht:query:peer-response",{detail:n})),n}function Yv(e,t={}){const n={...e,name:"FINAL_PEER",type:2};return t.onProgress?.(new CustomEvent("kad-dht:query:final-peer",{detail:n})),n}function Jv(e,t={}){const n={...e,name:"QUERY_ERROR",type:3};return t.onProgress?.(new CustomEvent("kad-dht:query:query-error",{detail:n})),n}function Zv(e,t={}){const n={...e,name:"PROVIDER",type:4};return t.onProgress?.(new CustomEvent("kad-dht:query:provider",{detail:n})),n}function Xv(e,t={}){const n={...e,name:"VALUE",type:5};return t.onProgress?.(new CustomEvent("kad-dht:query:value",{detail:n})),n}function ew(e,t={}){const n={...e,name:"DIAL_PEER",type:7};return t.onProgress?.(new CustomEvent("kad-dht:query:dial-peer",{detail:n})),n}!function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&(t.uint32(18),t.bytes(e.value)),null!=e.author&&(t.uint32(26),t.bytes(e.author)),null!=e.signature&&(t.uint32(34),t.bytes(e.signature)),null!=e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 3:r.author=e.bytes();break;case 4:r.signature=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(Lv||(Lv={})),function(e){e.PUT_VALUE="PUT_VALUE",e.GET_VALUE="GET_VALUE",e.ADD_PROVIDER="ADD_PROVIDER",e.GET_PROVIDERS="GET_PROVIDERS",e.FIND_NODE="FIND_NODE",e.PING="PING"}(Nv||(Nv={})),function(e){e[e.PUT_VALUE=0]="PUT_VALUE",e[e.GET_VALUE=1]="GET_VALUE",e[e.ADD_PROVIDER=2]="ADD_PROVIDER",e[e.GET_PROVIDERS=3]="GET_PROVIDERS",e[e.FIND_NODE=4]="FIND_NODE",e[e.PING=5]="PING"}(Ov||(Ov={})),function(e){e.codec=()=>Np(Ov)}(Nv||(Nv={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(Bv||(Bv={})),function(e){e[e.NOT_CONNECTED=0]="NOT_CONNECTED",e[e.CONNECTED=1]="CONNECTED",e[e.CAN_CONNECT=2]="CAN_CONNECT",e[e.CANNOT_CONNECT=3]="CANNOT_CONNECT"}(Uv||(Uv={})),function(e){e.codec=()=>Np(Uv)}(Bv||(Bv={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.multiaddrs)for(const n of e.multiaddrs)t.uint32(18),t.bytes(n);null!=e.connection&&(t.uint32(24),Bv.codec().encode(e.connection,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={id:Nn(0),multiaddrs:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.id=e.bytes();break;case 2:if(null!=n.limits?.multiaddrs&&r.multiaddrs.length===n.limits.multiaddrs)throw new Bp('Decode error - map field "multiaddrs" had too many elements');r.multiaddrs.push(e.bytes());break;case 3:r.connection=Bv.codec().decode(e);break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(jv||(jv={})),function(e){let t;e.codec=()=>(null==t&&(t=Op((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.type&&0!==Ov[e.type]&&(t.uint32(8),Nv.codec().encode(e.type,t)),null!=e.clusterLevel&&(t.uint32(80),t.int32(e.clusterLevel)),null!=e.key&&(t.uint32(18),t.bytes(e.key)),null!=e.record&&(t.uint32(26),t.bytes(e.record)),null!=e.closer)for(const n of e.closer)t.uint32(66),jv.codec().encode(n,t);if(null!=e.providers)for(const n of e.providers)t.uint32(74),jv.codec().encode(n,t);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={type:Nv.PUT_VALUE,closer:[],providers:[]},i=null==t?e.len:e.pos+t;for(;e.pos<i;){const t=e.uint32();switch(t>>>3){case 1:r.type=Nv.codec().decode(e);break;case 10:r.clusterLevel=e.int32();break;case 2:r.key=e.bytes();break;case 3:r.record=e.bytes();break;case 8:if(null!=n.limits?.closer&&r.closer.length===n.limits.closer)throw new Bp('Decode error - map field "closer" had too many elements');r.closer.push(jv.codec().decode(e,e.uint32(),{limits:n.limits?.closer$}));break;case 9:if(null!=n.limits?.providers&&r.providers.length===n.limits.providers)throw new Bp('Decode error - map field "providers" had too many elements');r.providers.push(jv.codec().decode(e,e.uint32(),{limits:n.limits?.providers$}));break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Ip(t,e.codec()),e.decode=(t,n)=>mp(t,e.codec(),n)}(qv||(qv={}));const tw={pk:function(e,t){return 0}};async function nw(e,t,n){const r=t.key,i=mr(r).split("/");if(i.length<3)return;const s=e[i[1].toString()];if(null==s)throw new We(`No validator available for key type "${i[1]}"`);await s(r,t.value,n)}const rw={pk:async(e,t,n)=>{if(!(e instanceof Uint8Array))throw new We('"key" must be a Uint8Array');if(e.byteLength<5)throw new We("Invalid public key record");if("/pk/"!==mr(e.subarray(0,4)))throw new We("key was not prefixed with /pk/");const r=Mo(t);if(!Ln(e.slice(4),r.toMultihash().bytes))throw new We("public key does not match passed in key")}},iw=fr("/pk/");function sw(e){return{...e,multiaddrs:e.multiaddrs.filter(e=>!Ad(e))}}async function aw(e,t){const n=await ur.digest(e);return t?.signal?.throwIfAborted(),n.digest}async function ow(e,t){return aw(e.toMultihash().bytes,t)}function uw(e,t){return new Wp(`${e}/${mr(t,"base32")}`,!1)}function dw(e,t){const n=new Date;return new zv(e,t,n).serialize()}function cw(e){const t=e.toString().split("/"),n=t.pop(),r=t.pop();if(null==n||null==r)throw new Error(`incorrectly formatted provider entry key in datastore: ${e.toString()}`);return{cid:kn.createV1(85,xn(fr(r,"base32"))),peerId:Uo(n)}}function lw(e,t,n){const r=[e,"string"==typeof t?t:mr(t.multihash.bytes,"base32")];return null!=n&&r.push(n.toString()),new Wp(r.join("/"))}function pw(e){return new Date(va(e))}function hw(e,t,n){return async function*(...r){const i=t.queryTime?.timer(n),s=t.errorTime?.timer(n);let a=!1;try{t.queries?.increment({[n]:!0}),yield*e(...r)}catch(e){throw a=!0,s?.(),t.errors?.increment({[n]:!0}),e}finally{t.queries?.decrement({[n]:!0}),a||i?.()}}}function fw(e,t,n){return async function(...r){const i=t?.queryTime?.timer(n),s=t?.errorTime?.timer(n);let a=!1;try{return t.queries?.increment({[n]:!0}),await e(...r)}catch(e){throw a=!0,s?.(),t.errors?.increment({[n]:!0}),e}finally{t.queries?.decrement({[n]:!0}),a||i?.()}}}class mw{log;components;validators;selectors;peerRouting;queryManager;network;datastorePrefix;constructor(e,t){const{validators:n,selectors:r,peerRouting:i,queryManager:s,network:a,logPrefix:o}=t;this.components=e,this.log=e.logger.forComponent(`${o}:content-fetching`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n,this.selectors=r,this.peerRouting=i,this.queryManager=s,this.network=a,this.get=e.metrics?.traceFunction("libp2p.kadDHT.get",this.get.bind(this),{optionsIndex:1})??this.get,this.put=e.metrics?.traceFunction("libp2p.kadDHT.put",this.put.bind(this),{optionsIndex:2})??this.put}async getLocal(e,t){this.log("getLocal %b",e);const n=uw(this.datastorePrefix,e);this.log("fetching record for key %k",n);const r=await this.components.datastore.get(n,t);this.log("found %k in local datastore",n);const i=zv.deserialize(r);return await nw(this.validators,i,t),i}async*sendCorrectionRecord(e,t,n,r){this.log("sendCorrection for %b",e);const i=dw(e,n);for(const{value:s,from:a}of t){if(Ln(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{const t=uw(this.datastorePrefix,e);this.log(`Storing corrected record for key ${t.toString()}`),await this.components.datastore.put(t,i.subarray(),r)}catch(e){this.log.error("failed error correcting self - %e",e)}continue}let t=!1;const o={type:Nv.PUT_VALUE,key:e,record:i};for await(const e of this.network.sendRequest(a,o,r))"PEER_RESPONSE"===e.name&&null!=e.record&&Ln(e.record.value,zv.deserialize(i).value)&&(t=!0),yield e;if(!t)throw new Gv("Could not send correction");this.log.error("failed error correcting entry")}}async*put(e,t,n){this.log("put key %b value %b",e,t);const r=dw(e,t),i=uw(this.datastorePrefix,e);this.log(`storing record for key ${i.toString()}`),await this.components.datastore.put(i,r.subarray(),n),yield*nc(this.peerRouting.getClosestPeers(e,{...n,signal:n.signal}),t=>Vv(t,t=>async()=>{if("FINAL_PEER"!==t.name)return[t];const i=[],s={type:Nv.PUT_VALUE,key:e,record:r};this.log("send put to %p",t.peer.id);for await(const e of this.network.sendRequest(t.peer.id,s,{...n,path:t.path}))i.push(e),"PEER_RESPONSE"===e.name&&(null!=e.record&&Ln(e.record.value,zv.deserialize(r).value)||i.push(Jv({from:t.peer.id,error:new Gv("Value not put correctly"),path:e.path},n)));return i}),e=>Sm(e,{ordered:!1,concurrency:10}),async function*(e){for await(const t of e)yield*t})}async*get(e,t){this.log("get %b",e);const n=[];for await(const r of this.getMany(e,t))"VALUE"!==r.name?yield r:n.push(r);if(0===n.length)return;const r=n.map(e=>e.value);let i=0;try{i=function(e,t,n){if(0===n.length)throw new We("No records given");const r=mr(t).split("/");if(r.length<3)throw new We("Record key does not have a selector function");const i=e[r[1].toString()];if(null==i)throw new Hv(`No selector function configured for key type "${r[1]}"`);return 1===n.length?0:i(t,n)}(this.selectors,e,r)}catch(e){if("InvalidParametersError"!==e.name)throw e}const s=r[i];if(this.log("GetValue %b %b",e,s),null==s)throw new nt("Best value was not found");yield*this.sendCorrectionRecord(e,n,s,{...t,path:{index:-1,queued:0,running:0,total:0}}),yield n[i]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{const n=await this.getLocal(e,t);yield Xv({value:n.value,from:this.components.peerId,path:{index:-1,running:0,queued:0,total:0}},t)}catch(t){this.log("error getting local value for %b",e,t)}const n=this;yield*this.queryManager.run(e,async function*({peer:r,signal:i,path:s}){for await(const a of n.peerRouting.getValueOrPeers(r.id,e,{...t,signal:i,path:s}))yield a,"PEER_RESPONSE"===a.name&&null!=a.record&&(yield Xv({from:r.id,value:a.record.value,path:s},t))},t)}}function yw(e,t){const n={id:e.id.toMultihash().bytes,multiaddrs:(e.multiaddrs??[]).map(e=>e.bytes),connection:t};return n}function bw(e){if(null==e.id)throw new Error("Invalid peer in message");return{id:qo(xn(e.id)),multiaddrs:(e.multiaddrs??[]).map(e=>Pu(e))}}class gw{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){const{network:n,peerRouting:r,queryManager:i,routingTable:s,providers:a,logPrefix:o}=t;this.components=e,this.log=e.logger.forComponent(`${o}:content-routing`),this.network=n,this.peerRouting=r,this.queryManager=i,this.routingTable=s,this.providers=a,this.findProviders=e.metrics?.traceFunction("libp2p.kadDHT.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>("PROVIDER"===e.name&&(t.providers??=[],t.providers.push(...e.providers.map(e=>e.id.toString()))),t)})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.kadDHT.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&"ADD_PROVIDER"===e.messageName&&(t.providers??=[],t.providers.push(e.from.toString())),t)})??this.provide}async*provide(e,t,n={}){this.log("provide %s",e);const r=e.multihash.bytes;await this.providers.addProvider(e,this.components.peerId,n);const i={type:Nv.ADD_PROVIDER,key:r,providers:[yw({id:this.components.peerId,multiaddrs:t})]};let s=0;const a=this,o=Md({objectMode:!0}),u=new Gd({concurrency:10});u.addEventListener("idle",()=>{o.end()}),u.addEventListener("failure",e=>{this.log.error("error publishing provider record to peer - %e",e.detail.error)}),u.add(async()=>{const t=[];for await(const e of this.peerRouting.getClosestPeers(r,n))o.push(e),"FINAL_PEER"===e.name&&t.push(e);t.forEach(t=>{u.add(async()=>{for await(const r of async function*(t){try{a.log("sending provider record for %s to %p",e,t.peer.id);for await(const r of a.network.sendMessage(t.peer.id,i,{...n,path:t.path}))"PEER_RESPONSE"===r.name&&(a.log("sent provider record for %s to %p",e,t.peer.id),s++),yield r}catch(e){a.log.error("error sending provide record to peer %p - %e",t.peer.id,e),yield Jv({from:t.peer.id,error:e,path:t.path},n)}}(t))o.push(r)}).catch(e=>{this.log.error("error publishing provider record to peer - %e",e)})})}).catch(e=>{o.end(e)}),yield*o,this.log("sent provider records to %d peers",s)}async*findProviders(e,t){const n=this.routingTable.kBucketSize;let r=0;const i=e.multihash.bytes,s=this;this.log("findProviders %c",e);const a=await this.providers.getProviders(e,t);if(a.length>0){const e=[];for(const r of a.slice(0,n))try{const n=await this.components.peerStore.get(r,t);e.push({id:r,multiaddrs:n.addresses.map(({multiaddr:e})=>e)})}catch(e){if("NotFoundError"!==e.name)throw e;this.log("no peer store entry for %p",r)}if(yield Qv({from:this.components.peerId,messageType:Nv.GET_PROVIDERS,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),yield Zv({from:this.components.peerId,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),r+=e.length,r>=n)return}const o=async function*({peer:e,signal:n,path:r}){const a={type:Nv.GET_PROVIDERS,key:i};yield*s.network.sendRequest(e.id,a,{...t,signal:n,path:r})},u=new ed(a);for await(const s of this.queryManager.run(i,o,t))if(yield s,"PEER_RESPONSE"===s.name){this.log("Found %d provider entries for %c and %d closer peers",s.providers.length,e,s.closer.length);const i=[];for(const e of s.providers)u.has(e.id)||(u.add(e.id),i.push(e));if(i.length>0&&(yield Zv({from:s.from,providers:i,path:s.path},t),r+=i.length,r>=n))return}}}class vw extends Ft{log;protocol;running;components;timeout;metrics;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:network`),this.running=!1,this.protocol=t.protocol,this.timeout=new Xd({...t.timeout??{},metrics:e.metrics,metricName:`${t.metricsPrefix}_network_message_send_times_milliseconds`}),this.metrics={operations:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_outbound_rpc_requests_total`),errors:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_outbound_rpc_errors_total`)},this.sendRequest=e.metrics?.traceFunction("libp2p.kadDHT.sendRequest",this.sendRequest.bind(this),{optionsIndex:2,getAttributesFromArgs:([e,t],n)=>({...n,to:e.toString(),"message type":`${t.type}`}),getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach((e,n)=>{t[`providers-${n}`]=e.id.toString()}),e.closer.length>0&&e.closer.forEach((e,n)=>{t[`closer-${n}`]=e.id.toString()})),t)})??this.sendRequest,this.sendMessage=e.metrics?.traceFunction("libp2p.kadDHT.sendMessage",this.sendMessage.bind(this),{optionsIndex:2,getAttributesFromArgs:([e,t],n)=>({...n,to:e.toString(),"message type":`${t.type}`}),getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach((e,n)=>{t[`providers-${n}`]=e.id.toString()}),e.closer.length>0&&e.closer.forEach((e,n)=>{t[`closer-${n}`]=e.id.toString()})),t)})??this.sendMessage}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}isStarted(){return this.running}async*sendRequest(e,t,n){if(!this.running)return;const r=t.type;if(null==r)throw new We("Message type was missing");let i;const s=this.timeout.getTimeoutSignal(n);n={...n,signal:s};try{this.metrics.operations?.increment({[r]:!0}),this.log("dialling %p",e),yield ew({peer:e,path:n.path},n),i=await this.components.connectionManager.openStream(e,this.protocol,n),this.log("sending %s to %p",t.type,e),yield Wv({to:e,type:r,path:n.path},n);const s=await this._writeReadMessage(i,t,n);i.close(n).catch(t=>{this.log.error("error closing stream to %p - %e",e,t),i?.abort(t)}),yield Qv({from:e,messageType:s.type,closer:s.closer.map(bw),providers:s.providers.map(bw),record:null==s.record?void 0:zv.deserialize(s.record),path:n.path},n)}catch(s){this.metrics.errors?.increment({[r]:!0}),i?.abort(s),!0!==n.signal?.aborted&&this.log.error("could not send %s to %p - %e",t.type,e,s),yield Jv({from:e,error:s,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async*sendMessage(e,t,n){if(!this.running)return;const r=t.type;if(null==r)throw new We("Message type was missing");let i;const s=this.timeout.getTimeoutSignal(n);n={...n,signal:s};try{this.metrics.operations?.increment({[r]:!0}),this.log("dialling %p",e),yield ew({peer:e,path:n.path},n),i=await this.components.connectionManager.openStream(e,this.protocol,n),this.log("sending %s to %p",t.type,e),yield Wv({to:e,type:r,path:n.path},n),await this._writeMessage(i,t,n),i.close(n).catch(t=>{this.log.error("error closing stream to %p - %e",e,t),i?.abort(t)}),yield Qv({from:e,messageType:r,path:n.path},n)}catch(t){this.metrics.errors?.increment({[r]:!0}),i?.abort(t),yield Jv({from:e,error:t,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async _writeMessage(e,t,n){const r=mc(e);await r.write(t,qv,n)}async _writeReadMessage(e,t,n){const r=mc(e);await r.write(t,qv,n);const i=await r.read(qv,n);return i.closer.forEach(e=>{this.safeDispatchEvent("peer",{detail:bw(e)})}),i.providers.forEach(e=>{this.safeDispatchEvent("peer",{detail:bw(e)})}),i}}function ww(e,t){if(e.byteLength!==t.byteLength)throw new Error("Inputs should have the same length");for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}class Tw{originDhtKey;capacity;peerDistances;constructor(e,t){this.originDhtKey=e,this.capacity=t,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return[...this.peerDistances]}async add(e,t={index:-1,queued:0,running:0,total:0},n){const r=await ow(e.id,n);this.addWithKadId(e,r,t)}addWithKadId(e,t,n={index:-1,queued:0,running:0,total:0}){if(null!=this.peerDistances.find(t=>t.peer.id.equals(e.id)))return;const r={peer:e,distance:vb(this.originDhtKey,t),path:n};if(this.peerDistances.length===this.capacity){const e=this.peerDistances[this.peerDistances.length-1];if(null!=e&&-1!==ww(r.distance,e.distance))return}let i=!1;for(let e=0;e<this.peerDistances.length;e++){const t=ww(this.peerDistances[e].distance,r.distance);if(0===t||1===t){i=!0,this.peerDistances.splice(e,0,r);break}}i||this.peerDistances.push(r),this.peerDistances=this.peerDistances.slice(0,this.capacity)}async isCloser(e,t){return 0===this.length||-1===ww(vb(await ow(e,t),this.originDhtKey),this.peerDistances[this.peerDistances.length-1].distance)}async anyCloser(e,t){return 0!==e.length&&Promise.any(e.map(async e=>this.isCloser(e,t)))}}class Ew{log;routingTable;network;validators;queryManager;components;constructor(e,t){this.routingTable=t.routingTable,this.network=t.network,this.validators=t.validators,this.queryManager=t.queryManager,this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:peer-routing`),this.findPeer=e.metrics?.traceFunction("libp2p.kadDHT.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.kadDHT.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async findPeerLocal(e,t){let n;const r=await this.routingTable.find(e,t);if(null!=r){this.log("findPeerLocal found %p in routing table",e);try{n=await this.components.peerStore.get(r,t)}catch(e){if("NotFoundError"!==e.name)throw e}}if(null==n)try{n=await this.components.peerStore.get(e,t)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=n)return this.log("findPeerLocal found %p in peer store",e),{id:n.id,multiaddrs:n.addresses.map(e=>e.multiaddr)}}async*_getValueSingle(e,t,n){const r={type:Nv.GET_VALUE,key:t};yield*this.network.sendRequest(e,r,n)}async*getPublicKeyFromNode(e,t={}){const n=Bn([iw,e.toMultihash().bytes]),r={index:-1,queued:0,running:0,total:0};for await(const i of this._getValueSingle(e,n,{...t,path:r}))if(yield i,"PEER_RESPONSE"===i.name&&null!=i.record){const n=jo(Mo(i.record.value));if(!n.equals(e))throw new Qe("public key does not match id");if(null==n.publicKey)throw new Qe("public key missing");yield Xv({from:e,value:i.record.value,path:r},t)}throw new Gv(`Node not responding with its public key: ${e.toString()}`)}async*findPeer(e,t={}){if(this.log("findPeer %p",e),!1!==t.useCache){const n=await this.findPeerLocal(e,t);if(null!=n)return this.log("found local"),void(yield Yv({from:this.components.peerId,peer:n,path:{index:-1,queued:0,running:0,total:0}},t))}let n=!1;if(!1!==t.useNetwork){const r=this,i=async function*({peer:n,signal:i,path:s}){const a={type:Nv.FIND_NODE,key:e.toMultihash().bytes};for await(const o of r.network.sendRequest(n.id,a,{...t,signal:i,path:s}))if(yield o,"PEER_RESPONSE"===o.name){const n=o.closer.find(t=>t.id.equals(e));null!=n&&(yield Yv({from:o.from,peer:n,path:o.path},t))}};for await(const r of this.queryManager.run(e.toMultihash().bytes,i,t))"FINAL_PEER"===r.name&&(n=!0),yield r}if(!n)throw new nt("Not found")}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);const n=await aw(e,t),r=new Tw(n,this.routingTable.kBucketSize),i=this;yield*this.queryManager.run(e,async function*({peer:n,path:s,peerKadId:a,signal:o}){i.log("getClosestPeers asking %p",n.id);const u={type:Nv.FIND_NODE,key:e};yield*i.network.sendRequest(n.id,u,{...t,signal:o,path:s}),r.addWithKadId(n,a,s)},t),this.log("found %d peers close to %b",r.length,e);for(let{peer:e,path:n}of r.peers)try{if(0===e.multiaddrs.length&&(e=await i.components.peerStore.getInfo(e.id,t)),0===e.multiaddrs.length)continue;yield Yv({from:this.components.peerId,peer:await i.components.peerStore.getInfo(e.id,t),path:{index:n.index,queued:0,running:0,total:0}},t)}catch{continue}}async*getValueOrPeers(e,t,n){for await(const r of this._getValueSingle(e,t,n)){if("PEER_RESPONSE"===r.name&&null!=r.record)try{await this._verifyRecordOnline(r.record,n)}catch(e){const t="invalid record received, discarded";this.log(t),yield Jv({from:r.from,error:new Gv(t),path:n.path},n);continue}yield r}}async _verifyRecordOnline(e,t){if(null==e.timeReceived)throw new Kv("invalid record received");await nw(this.validators,new zv(e.key,e.value,e.timeReceived),t)}async getClosestPeersOffline(e,t){const n=[];try{const r=qo(xn(e)),i=await this.components.peerStore.get(r,t);n.push({id:i.id,multiaddrs:i.addresses.map(({multiaddr:e})=>e)})}catch{}const r=await aw(e,t),i=this.routingTable.closestPeers(r,t);for(const e of i)try{n.push(await this.components.peerStore.getInfo(e,t))}catch(e){if("NotFoundError"!==e.name)throw e}return n.length>0?this.log("getClosestPeersOffline returning the %d closest peer(s) we know to %b",n.length,e):this.log("getClosestPeersOffline could not any peers close to %b with %d peers in the routing table",e,this.routingTable.size),n}}class xw{log;datastore;datastorePrefix;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:providers`),this.datastorePrefix=`${t.datastorePrefix}/provider`,this.datastore=e.datastore}async addProvider(e,t,n){this.log.trace("%p provides %s",t,e),await this.writeProviderEntry(e,t,n)}async removeProvider(e,t,n){const r=lw(this.datastorePrefix,e,t);this.log.trace("%p no longer provides %s",t,e),await this.datastore.delete(r,n)}async getProviders(e,t){this.log.trace("get providers for %c",e);const n=await this.loadProviders(e,t);return this.log.trace("got %d providers for %c",n.size,e),[...n.keys()]}async writeProviderEntry(e,t,n){const r=lw(this.datastorePrefix,e,t),i=ga(n?.time?.getTime()??Date.now());await this.datastore.put(r,i,n)}async loadProviders(e,t){const n=new Xu,r=lw(this.datastorePrefix,e);for await(const e of this.datastore.query({prefix:r.toString()},t)){const{peerId:t}=cw(e.key);n.set(t,pw(e.value))}return n}}async function*Pw(e){const{key:t,startingPeers:n,ourPeerId:r,query:i,alpha:s,path:a,numPaths:o,log:u,peersSeen:d,connectionManager:c,signal:l}=e,p=Md({objectMode:!0}),h=new Gd({concurrency:s,sort:(e,t)=>ww(e.options.distance,t.options.distance)});h.addEventListener("idle",()=>{p.push(function(e,t={}){const n={...e,name:"PATH_ENDED",type:8};return t.onProgress?.(new CustomEvent("kad-dht:query:path-ended",{detail:n})),n}({path:{index:a,queued:h.queued,running:h.running,total:h.size}},e)),p.end()}),h.addEventListener("failure",e=>{u.error("error during query - %e",e.detail.error)});const f=()=>{h.abort(),p.end(new Ge)};l.addEventListener("abort",f);try{const y=await aw(t,{signal:l});function m(n,s){if(null==n)return;d.add(n.id.toMultihash().bytes);const f=vb(s,y);h.add(async()=>{try{for await(const b of i({...e,key:t,peer:n,path:{index:a,queued:h.queued,running:h.running,total:h.size},numPaths:o,peerKadId:s,signal:l})){if("PEER_RESPONSE"===b.name)for(const e of b.closer){if(d.has(e.id.toMultihash().bytes)){u("already seen %p in query",e.id);continue}if(r.equals(e.id)){u("not querying ourselves");continue}if(!await c.isDialable(e.multiaddrs)){u("not querying undialable peer");continue}const i=await ow(e.id,{signal:l});-1===ww(vb(i,y),f)?(u("querying closer peer %p",e.id),m(e,i)):u("skipping %p as they are not closer to %b than %p",e.id,t,n.id)}p.push({...b,path:{index:a,queued:h.queued,running:h.running,total:h.size}})}}catch(t){p.push(Jv({from:n.id,error:t,path:{index:a,queued:h.queued,running:h.running-1,total:h.size-1}},e))}},{distance:f}).catch(e=>{u.error("error during query - %e",e)})}await Promise.all(n.map(async e=>{m({id:e,multiaddrs:[]},await ow(e,{signal:l}))})),yield*p}finally{l.removeEventListener("abort",f)}}class Sw{disjointPaths;alpha;shutDownController;running;logger;peerId;connectionManager;routingTable;initialQuerySelfHasRun;logPrefix;allowQueryWithZeroPeers;constructor(e,t){this.logPrefix=t.logPrefix,this.disjointPaths=t.disjointPaths??20,this.alpha=t.alpha??10,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.routingTable=t.routingTable,this.logger=e.logger,this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.allowQueryWithZeroPeers=t.allowQueryWithZeroPeers??!1,this.shutDownController=new AbortController,this.running=!1}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.shutDownController=new AbortController)}async stop(){this.running=!1,this.shutDownController.abort()}async*run(e,t,n={}){if(!this.running)throw new Error("QueryManager not started");if(null==n.signal){const e=AbortSignal.timeout(18e4);n={...n,signal:e}}const r=new AbortController,i=Jd([this.shutDownController.signal,r.signal,n.signal]),s=this.logger.forComponent(`${this.logPrefix}:query:`+mr(e,"base58btc"));let a=!1;try{0!==this.routingTable.size||this.allowQueryWithZeroPeers||(s("routing table was empty, waiting for some peers before running%s query",!0===n.isSelfQuery?" self":""),await _d(this.routingTable,"peer:add",{signal:i,filter:e=>!this.peerId.equals(e.detail)}),s("routing table has peers, continuing with%s query",!0===n.isSelfQuery?" self":"")),!0!==n.isSelfQuery&&null!=this.initialQuerySelfHasRun&&(s("waiting for initial self query before continuing"),await $d(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),s("query:start");const r=await aw(e,{signal:i}),o=this.routingTable.closestPeers(r,{count:this.routingTable.kBucketSize}),u=o.sort(()=>Math.random()>.5?1:-1).reduce((e,t,n)=>(e[n%this.disjointPaths].push(t),e),new Array(this.disjointPaths).fill(0).map(()=>[])).filter(e=>e.length>0);if(0===o.length)return void s.error("running query with no peers");const d=pd(1024),c=u.map((r,a)=>Pw({...n,key:e,startingPeers:r,ourPeerId:this.peerId,signal:i,query:t,path:a,numPaths:u.length,alpha:this.alpha,log:s,peersSeen:d,onProgress:n.onProgress,connectionManager:this.connectionManager}));for await(const e of tc(...c)){if("QUERY_ERROR"===e.name&&s.error("query error - %e",e.error),"PEER_RESPONSE"===e.name)for(const t of[...e.closer,...e.providers])await this.connectionManager.isDialable(t.multiaddrs,{signal:i})&&await this.routingTable.add(t.id,{signal:i});i.throwIfAborted(),yield e}a=!0}catch(e){if(this.running)throw e}finally{a||(s("query exited early"),r.abort()),i.clear(),s("query finished")}}}function Aw(e){if(null!=e[Symbol.asyncIterator])return(async()=>{let t=0;for await(const n of e)t++;return t})();{let t=0;for(const n of e)t++;return t}}class Cw{log;peerId;peerRouting;events;count;interval;initialInterval;queryTimeout;running;timeoutId;controller;initialQuerySelfHasRun;querySelfPromise;constructor(e,t){this.peerId=e.peerId,this.log=e.logger.forComponent(`${t.logPrefix}:query-self`),this.events=e.events,this.running=!1,this.peerRouting=t.peerRouting,this.count=t.count??20,this.interval=t.interval??3e5,this.initialInterval=t.initialInterval??1e3,this.queryTimeout=t.queryTimeout??5e3,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.querySelf=fw(this.querySelf.bind(this),t.operationMetrics,"SELF_QUERY")}isStarted(){return this.running}start(){this.running||(this.running=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query - %e",e)})},this.initialInterval))}stop(){this.running=!1,null!=this.timeoutId&&clearTimeout(this.timeoutId),null!=this.controller&&this.controller.abort()}async querySelf(){if(this.running){if(null!=this.querySelfPromise)return this.log("joining existing self query"),this.querySelfPromise.promise;if(this.querySelfPromise=Cd(),this.running){this.controller=new AbortController;const e=[this.controller.signal];if(null==this.initialQuerySelfHasRun){const t=AbortSignal.timeout(this.queryTimeout);e.push(t)}const t=Jd(e);try{this.log("run self-query, look for %d peers timing out after %dms",this.count,this.queryTimeout);const e=Date.now(),n=await nc(this.peerRouting.getClosestPeers(this.peerId.toMultihash().bytes,{signal:t,isSelfQuery:!0}),e=>ph(e,this.count),async e=>Aw(e));t?.throwIfAborted();const r=Date.now()-e;this.log("self-query found %d peers in %dms",n,r),this.events.dispatchEvent(new CustomEvent("kad-dht:query:self",{detail:{peers:n,duration:r}}))}catch(e){this.log.error("self-query error - %e",e)}finally{t.clear(),null!=this.initialQuerySelfHasRun&&(this.initialQuerySelfHasRun.resolve(),this.initialQuerySelfHasRun=void 0)}}this.querySelfPromise.resolve(),this.querySelfPromise=void 0,this.running&&(this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query - %e",e)})},this.interval))}else this.log("skip self-query because we are not started")}}class kw extends Ft{log;reprovideQueue;maxQueueSize;datastore;timeout;reprovideTimeout;running;shutdownController;reprovideThreshold;contentRouting;datastorePrefix;addressManager;validity;interval;peerId;constructor(e,t){super(),this.log=e.logger.forComponent(`${t.logPrefix}:reprovider`),this.peerId=e.peerId,this.reprovideQueue=new Gd({concurrency:t.concurrency??10,metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_queue`}),this.reprovideTimeout=new Xd({...t.timeout??{},metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_timeout_milliseconds`}),this.datastore=e.datastore,this.addressManager=e.addressManager,this.datastorePrefix=`${t.datastorePrefix}/provider`,this.reprovideThreshold=t.threshold??864e5,this.maxQueueSize=t.maxQueueSize??16384,this.validity=t.validity??Dv,this.interval=t.interval??Mv,this.contentRouting=t.contentRouting,this.running=!1,this.reprovide=fw(this.reprovide.bind(this),t.operationMetrics,"PROVIDE")}start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.timeout=setTimeout(()=>{this.processRecords({signal:AbortSignal.timeout(Fv)}).catch(e=>{this.log.error("error running process to reprovide/cleanup - %e",e)})},this.interval))}stop(){this.running=!1,this.reprovideQueue.clear(),clearTimeout(this.timeout),this.shutdownController?.abort()}async processRecords(e){try{this.safeDispatchEvent("reprovide:start"),this.log("starting reprovide/cleanup");for await(const t of this.datastore.query({prefix:this.datastorePrefix},e))try{const{cid:n,peerId:r}=cw(t.key),i=pw(t.value).getTime()+this.validity,s=Date.now(),a=s>i,o=this.peerId.equals(r);this.log.trace("comparing: %d (now) < %d (expires) = %s %s",s,i,a,a?"(expired)":"(valid)"),a&&!o&&await this.datastore.delete(t.key,e),this.shouldReprovide(o,i)&&(this.log("reproviding %c as it is within the reprovide threshold (%d)",n,this.reprovideThreshold),this.queueReprovide(n).catch(e=>{this.log.error("could not reprovide %c - %e",n,e)}))}catch(e){this.log.error("error processing datastore key %s - %s",t.key,e.message)}this.log("reprovide/cleanup successful")}finally{this.safeDispatchEvent("reprovide:end"),this.running&&(this.log("queuing next re-provide/cleanup run in %d ms",this.interval),this.timeout=setTimeout(()=>{this.processRecords({signal:AbortSignal.timeout(Fv)}).catch(e=>{this.log.error("error running re-provide - %e",e)})},this.interval))}}shouldReprovide(e,t){if(!e)return!1;const n=Date.now();return t<n||t-n<this.reprovideThreshold}async queueReprovide(e,t){if(!this.running)return;this.log.trace("waiting for queue capacity before adding %c to re-provide queue",e),await this.reprovideQueue.onSizeLessThan(this.maxQueueSize,t);const n=this.reprovideQueue.queue.find(t=>t.options.cid.equals(e));if(null!=n)return this.log.trace("not adding %c to re-provide queue - already in queue",e),n.join();this.log.trace("adding %c to re-provide queue",e),this.reprovideQueue.add(async t=>{if(t.signal?.throwIfAborted(),!this.running)return;this.log.trace("re-providing %c",e);const n=this.reprovideTimeout.getTimeoutSignal(t);try{await this.reprovide(t.cid,t)}finally{this.reprovideTimeout.cleanUp(n)}this.log.trace("re-provided %c",e)},{signal:this.shutdownController?.signal,cid:e}).catch(t=>{this.log.error("could not re-provide key %c - %e",e,t)})}async reprovide(e,t){await uh(this.contentRouting.provide(e,this.addressManager.getAddresses(),t))}}class Iw{routingTable;components;closestPeers;newPeers;refreshInterval;peerSetSize;timeout;closeTagName;closeTagValue;log;running;constructor(e,t){this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.routingTable=t.routingTable,this.refreshInterval=t.refreshInterval??5e3,this.peerSetSize=t.peerSetSize??20,this.closeTagName=t.closeTagName??"kad-close",this.closeTagValue=t.closeTagValue??50,this.closestPeers=new ed,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}async start(){if(this.running)return;this.running=!0;const e=await ow(this.components.peerId);this.newPeers=new Tw(e,this.peerSetSize),this.routingTable.addEventListener("peer:ping",this.onPeerPing),this.timeout=setInterval(()=>{this.updatePeerTags().catch(e=>{this.log.error("error updating peer tags - %e",e)})},this.refreshInterval)}stop(){this.running=!1,this.routingTable.removeEventListener("peer:ping",this.onPeerPing),clearTimeout(this.timeout)}onPeerPing(e){this.newPeers?.add({id:e.detail,multiaddrs:[]}).catch(e=>{this.log.error("error adding peer to distance list - %e",e)})}async updatePeerTags(){const e=new ed(this.newPeers?.peers.map(({peer:e})=>e.id)),t=e.difference(this.closestPeers),n=this.closestPeers.difference(e);this.closestPeers=e,await Promise.all([...[...t].map(async e=>{await this.components.peerStore.merge(e,{tags:{[this.closeTagName]:{value:this.closeTagValue},[Rv]:{value:1}}})}),...[...n].map(async e=>{await this.components.peerStore.merge(e,{tags:{[this.closeTagName]:void 0,[Rv]:void 0}})})])}}function Dw(e){return Array.isArray(e?.peers)}class Mw{peerId;root;localPeer;prefixLength;splitThreshold;kBucketSize;numberOfNodesToPing;lastPingThreshold;ping;verify;onAdd;onRemove;onMove;addingPeerMap;constructor(e,t){this.peerId=e.peerId,this.prefixLength=t.prefixLength??Rw,this.kBucketSize=t.kBucketSize??Fw,this.splitThreshold=t.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=t.numberOfOldContactsToPing??_w,this.lastPingThreshold=t.lastPingThreshold??Nw,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=Rc({name:`${t.metricsPrefix}_adding_peer_map`,metrics:e.metrics}),this.root={prefix:"",depth:0,peers:[]}}async start(){await this.addSelfPeer(this.peerId)}stop(){this.addingPeerMap.clear(),this.root={prefix:"",depth:0,peers:[]}}async addSelfPeer(e,t){this.localPeer={peerId:e,kadId:await ow(e,t),lastPing:Date.now()}}async add(e,t){const n={peerId:e,kadId:await ow(e,t),lastPing:0},r=this.addingPeerMap.get(e);if(null!=r)return r;try{const r=this._add(n,t);this.addingPeerMap.set(e,r),await r}finally{this.addingPeerMap.delete(e)}}async _add(e,t){const n=this._determineBucket(e.kadId);if(this._indexOf(n,e.kadId)>-1)return;if(n.peers.length===this.splitThreshold&&n.depth<this.prefixLength)return await this._split(n,t),void await this._add(e,t);if(n.peers.length<this.kBucketSize)return function(e,t){return e.lastPing<Date.now()-t}(e,this.lastPingThreshold)?void(await this.verify(e,t)&&(e.lastPing=Date.now(),await this._add(e,t))):(n.peers.push(e),void await(this.onAdd?.(e,n,t)));const r=n.peers.filter(e=>!(e.peerId.equals(this.localPeer?.peerId)||e.lastPing>Date.now()-this.lastPingThreshold)).sort((e,t)=>e.lastPing<t.lastPing?-1:e.lastPing>t.lastPing?1:0).slice(0,this.numberOfNodesToPing);let i=!1;for await(const e of this.ping(r,t))i=!0,await this.remove(e.kadId,t);i&&await this._add(e,t)}*closest(e,t){const n=new Tw(e,t?.count??this.kBucketSize);for(const e of this.toIterable())!0!==t?.exclude?.some(t=>t.equals(e.peerId))&&n.addWithKadId({id:e.peerId,multiaddrs:[]},e.kadId);yield*Vv(n.peers,({peer:e})=>e.id)}count(){return function e(t){if(Dw(t))return t.peers.length;let n=0;return null!=t.left&&(n+=e(t.left)),null!=t.right&&(n+=e(t.right)),n}(this.root)}get(e){const t=this._determineBucket(e),n=this._indexOf(t,e);return t.peers[n]}async remove(e,t){const n=this._determineBucket(e),r=this._indexOf(n,e);if(r>-1){const e=n.peers.splice(r,1)[0];await(this.onRemove?.(e,n,t))}}*toIterable(){yield*function*e(t){Dw(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+mr(vb(e,t),"base16"))}_determineBucket(e){const t=mr(e,"base2");return function e(n,r=0){return Dw(n)?n:e("0"===t[r]?n.left:n.right,r+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex(e=>Ln(e.kadId,t))}async _split(e,t){const n={prefix:"0",depth:e.depth+1,peers:[]},r={prefix:"1",depth:e.depth+1,peers:[]};for(const i of e.peers)"0"===mr(i.kadId,"base2")[e.depth]?(n.peers.push(i),await(this.onMove?.(i,e,n,t))):(r.peers.push(i),await(this.onMove?.(i,e,r,t)));!function(e,t,n){delete e.peers,e.left=t,e.right=n,""===e.prefix&&(delete e.depth,delete e.prefix)}(e,n,r)}}const Fw=20,Rw=6,_w=3,Lw="kad-peer",Nw=6e5;class Ow extends Ft{kBucketSize;kb;network;closestPeerTagger;log;components;running;pingNewContactTimeout;pingNewContactQueue;pingOldContactTimeout;pingOldContactQueue;populateFromDatastoreOnStart;populateFromDatastoreLimit;protocol;peerTagName;peerTagValue;metrics;shutdownController;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.kBucketSize=t.kBucketSize??Fw,this.running=!1,this.protocol=t.protocol,this.network=t.network,this.peerTagName=t.peerTagName??Lw,this.peerTagValue=t.peerTagValue??1,this.pingOldContacts=this.pingOldContacts.bind(this),this.verifyNewContact=this.verifyNewContact.bind(this),this.peerAdded=this.peerAdded.bind(this),this.peerRemoved=this.peerRemoved.bind(this),this.populateFromDatastoreOnStart=t.populateFromDatastoreOnStart??!0,this.populateFromDatastoreLimit=t.populateFromDatastoreLimit??1e3,this.shutdownController=new AbortController,this.pingOldContactQueue=new xc({concurrency:t.pingOldContactConcurrency??20,metricName:`${t.metricsPrefix}_ping_old_contact_queue`,metrics:this.components.metrics,maxSize:t.pingOldContactMaxQueueSize??100}),this.pingOldContactTimeout=new Xd({...t.pingOldContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_old_contact_time_milliseconds`}),this.pingNewContactQueue=new xc({concurrency:t.pingNewContactConcurrency??20,metricName:`${t.metricsPrefix}_ping_new_contact_queue`,metrics:this.components.metrics,maxSize:t.pingNewContactMaxQueueSize??100}),this.pingNewContactTimeout=new Xd({...t.pingNewContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_new_contact_time_milliseconds`}),this.kb=new Mw(e,{kBucketSize:t.kBucketSize,prefixLength:t.prefixLength,splitThreshold:t.splitThreshold,numberOfOldContactsToPing:t.numberOfOldContactsToPing,lastPingThreshold:t.lastPingThreshold,ping:this.pingOldContacts,verify:this.verifyNewContact,onAdd:this.peerAdded,onRemove:this.peerRemoved,metricsPrefix:t.metricsPrefix}),this.closestPeerTagger=new Iw(this.components,{logPrefix:t.logPrefix,routingTable:this,peerSetSize:t.closestPeerSetSize,refreshInterval:t.closestPeerSetRefreshInterval,closeTagName:t.closeTagName,closeTagValue:t.closeTagValue}),null!=this.components.metrics&&(this.metrics={routingTableSize:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_size`),routingTableKadBucketTotal:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_total`),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_average_occupancy`),routingTableKadBucketMinOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_min_occupancy`),routingTableKadBucketMaxOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_max_occupancy`),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_max_depth`),kadBucketEvents:this.components.metrics.registerCounterGroup(`${t.metricsPrefix}_kad_bucket_events_total`)})}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.shutdownController=new AbortController,await kt(this.closestPeerTagger,this.kb))}async afterStart(){let e=0;Promise.resolve().then(async()=>{if(!this.populateFromDatastoreOnStart)return;const t=Jd([this.shutdownController.signal,AbortSignal.timeout(2e4)]);try{for(const n of await this.components.peerStore.all({filters:[e=>e.protocols.includes(this.protocol)&&e.tags.has(Lw)],limit:this.populateFromDatastoreLimit,signal:t})){if(!this.running)return;try{await this.add(n.id,{signal:t}),e++}catch(e){this.log("failed to add peer %p to routing table, removing kad-dht peer tags - %e"),await this.components.peerStore.merge(n.id,{tags:{[this.peerTagName]:void 0}})}}}finally{t.clear()}this.log("added %d peer store peers to the routing table",e)}).catch(t=>{this.log.error("error adding %d, peer store peers to the routing table - %e",e,t)})}async stop(){this.running=!1,await It(this.closestPeerTagger,this.kb),this.pingOldContactQueue.abort(),this.pingNewContactQueue.abort(),this.shutdownController.abort()}async peerAdded(e,t,n){this.components.peerId.equals(e.peerId)||await this.components.peerStore.merge(e.peerId,{tags:{[this.peerTagName]:{value:this.peerTagValue}}},n),this.updateMetrics(),this.metrics?.kadBucketEvents.increment({peer_added:!0}),this.safeDispatchEvent("peer:add",{detail:e.peerId})}async peerRemoved(e,t,n){this.components.peerId.equals(e.peerId)||await this.components.peerStore.merge(e.peerId,{tags:{[this.peerTagName]:void 0}},n),this.updateMetrics(),this.metrics?.kadBucketEvents.increment({peer_removed:!0}),this.safeDispatchEvent("peer:remove",{detail:e.peerId})}async*pingOldContacts(e,t){if(!this.running)return;const n=[];for(const r of e)null!=this.kb.get(r.kadId)?(this.metrics?.kadBucketEvents.increment({ping_old_contact:!0}),n.push(async()=>{const e=this.pingOldContactQueue.find(r.peerId);return null!=e?(this.log("asked to ping contact %p was already being pinged",r.peerId),await e.join(t)?void 0:r):await this.pingOldContactQueue.add(async e=>{const t=this.pingOldContactTimeout.getTimeoutSignal(),n=Jd([t,this.shutdownController.signal,e?.signal]);try{return await this.pingContact(r,e)}catch{return this.metrics?.kadBucketEvents.increment({ping_old_contact_error:!0}),!0}finally{this.pingOldContactTimeout.cleanUp(t),n.clear()}},{peerId:r.peerId,signal:t?.signal})?void 0:r})):this.log("asked to ping contact %p that was not in routing table",r.peerId);for await(const e of Sm(n))null!=e&&(yield e)}async verifyNewContact(e,t){const n=this.pingNewContactTimeout.getTimeoutSignal(),r=Jd([n,this.shutdownController.signal,t?.signal]);try{const t=this.pingNewContactQueue.find(e.peerId);return null!=t?(this.log("joining existing ping to add new peer %p to routing table",e.peerId),await t.join({signal:r})):await this.pingNewContactQueue.add(async t=>(this.metrics?.kadBucketEvents.increment({ping_new_contact:!0}),this.log("pinging new peer %p before adding to routing table",e.peerId),this.pingContact(e,t)),{peerId:e.peerId,signal:r})}catch(t){return this.log.trace("tried to add peer %p but they were not online",e.peerId),this.metrics?.kadBucketEvents.increment({ping_new_contact_error:!0}),!1}finally{this.pingNewContactTimeout.cleanUp(n),r.clear()}}async pingContact(e,t){try{return this.log("pinging contact %p",e.peerId),await this.components.ping.ping(e.peerId,t),this.log("contact %p ping ok",e.peerId),this.safeDispatchEvent("peer:ping",{detail:e.peerId}),!0}catch(t){return this.log("error pinging old contact %p - %e",e.peerId,t),!1}}get size(){return null==this.kb?0:this.kb.count()}async find(e,t){const n=await ow(e,t);return this.kb.get(n)?.peerId}closestPeer(e){const t=this.closestPeers(e,{count:1});if(t.length>0)return t[0]}closestPeers(e,t){return null==this.kb?[]:[...this.kb.closest(e,t)]}async add(e,t){if(null==this.kb)throw new Error("RoutingTable is not started");await this.kb.add(e,t)}async remove(e,t){if(null==this.kb)throw new Error("RoutingTable is not started");const n=await ow(e,t);await this.kb.remove(n,t)}updateMetrics(){if(null==this.metrics||null==this.kb)return;let e=0,t=0,n=0,r=20,i=0;!function s(a){if(Dw(a))return a.depth>n&&(n=a.depth),t++,e+=a.peers.length,a.peers.length<r&&(r=a.peers.length),void(a.peers.length>i&&(i=a.peers.length));s(a.left),s(a.right)}(this.kb.root),this.metrics.routingTableSize.update(e),this.metrics.routingTableKadBucketTotal.update(t),this.metrics.routingTableKadBucketAverageOccupancy.update(Math.round(e/t)),this.metrics.routingTableKadBucketMinOccupancy.update(r),this.metrics.routingTableKadBucketMaxOccupancy.update(i),this.metrics.routingTableKadBucketMaxDepth.update(n)}}var Bw,Uw=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];class jw{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e,t){const{peerRouting:n,routingTable:r,refreshInterval:i,refreshQueryTimeout:s,logPrefix:a}=t;this.log=e.logger.forComponent(`${a}:routing-table:refresh`),this.peerRouting=n,this.routingTable=r,this.refreshInterval=i??3e5,this.refreshQueryTimeout=s??3e4,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}async afterStart(){this.log(`refreshing routing table every ${this.refreshInterval}ms`),this.refreshTable(!0)}async stop(){null!=this.refreshTimeoutId&&clearTimeout(this.refreshTimeoutId)}refreshTable(e=!1,t){this.log("refreshing routing table");const n=this._maxCommonPrefix(),r=this._getTrackedCommonPrefixLengthsForRefresh(n);this.log(`max common prefix length ${n}`),this.log(`tracked CPLs [ ${r.map(e=>e.toISOString()).join(", ")} ]`),Promise.all(r.map(async(i,s)=>{try{if(await this._refreshCommonPrefixLength(s,i,e,t),0===this._numPeersForCpl(n)){const n=Math.min(2*(s+1),r.length-1);for(let r=s+1;r<n+1;r++)try{await this._refreshCommonPrefixLength(r,i,e,t)}catch(e){this.log.error("failed to refresh entries with common prefix length %d - %e",r,e)}}}catch(e){this.log.error("failed to refresh entries with common prefix length - %e",e)}})).catch(e=>{this.log.error("failed to refresh table - %e",e)}).then(()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),null!=this.refreshTimeoutId.unref&&this.refreshTimeoutId.unref()}).catch(e=>{this.log.error("failed to set refresh timeout - %e",e)})}async _refreshCommonPrefixLength(e,t,n,r){if(!n&&t.getTime()>Date.now()-this.refreshInterval)return void this.log("not running refresh for cpl %s as time since last refresh not above interval",e);const i=this._generateRandomPeerId(e);this.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,i,this.routingTable.size);const s=Jd([r?.signal,AbortSignal.timeout(this.refreshQueryTimeout)]);try{const t=await Aw(this.peerRouting.getClosestPeers(i.toMultihash().bytes,{signal:s}));this.log(`found ${t} peers that were close to imaginary peer %p`,i),this.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,i,this.routingTable.size)}finally{s.clear()}}_getTrackedCommonPrefixLengthsForRefresh(e){e>15&&(e=15);const t=[];for(let n=0;n<=e;n++)t[n]=this.commonPrefixLengthRefreshedAt[n]??new Date;return t}_generateRandomPeerId(e){if(null==this.routingTable.kb)throw new Error("Routing table not started");if(null==this.routingTable.kb.localPeer)throw new Error("Local peer not set");const t=io(2);return qo(xn(this._makePeerId(this.routingTable.kb.localPeer.kadId,(t[1]<<8)+t[0],e)))}_makePeerId(e,t,n){if(n>15)throw new Error("Cannot generate peer ID for common prefix length greater than 15");const r=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1),i=65535<<16-(n+1),s=Uw[(r^32768>>n)&i|t&~i],a=new ArrayBuffer(34),o=new DataView(a,0,a.byteLength);return o.setUint8(0,ur.code),o.setUint8(1,32),o.setUint32(2,s,!1),new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}_maxCommonPrefix(){let e=0;for(const t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){let t=0;for(const n of this._prefixLengths())n===e&&t++;return t}*_prefixLengths(){if(null!=this.routingTable.kb?.localPeer)for(const{kadId:e}of this.routingTable.kb.toIterable()){const t=vb(this.routingTable.kb.localPeer.kadId,e);let n=0;for(const e of t){if(0!==e)break;n++}yield n}}}class qw{peerId;providers;peerStore;log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:add-provider`),this.peerId=e.peerId,this.providers=t.providers,this.peerStore=e.peerStore}async handle(e,t){if(null==t.key||0===t.key.length)throw new ut("Missing key");let n;try{n=kn.decode(t.key)}catch(e){throw new ut("Invalid CID")}null!=t.providers&&0!==t.providers.length||this.log.error("no providers found in message"),this.log("%p asked us, %p to store provider record for for %c",e,this.peerId,n),await Promise.all(t.providers.map(async t=>{const r=qo(xn(t.id)),i=t.multiaddrs.map(e=>Pu(e));e.equals(r)?t.multiaddrs.length<1?this.log("no valid addresses for provider %p. Ignore",e):(this.log.trace("received provider %p for %s (addrs %s)",e,n,i),await this.providers.addProvider(n,r),await this.peerStore.merge(r,{multiaddrs:i})):this.log("invalid provider peer %p from %p",t.id,e)}))}}class $w{peerRouting;peerInfoMapper;peerId;addressManager;log;constructor(e,t){const{peerRouting:n,logPrefix:r}=t;this.log=e.logger.forComponent(`${r}:rpc:handlers:find-node`),this.peerId=e.peerId,this.addressManager=e.addressManager,this.peerRouting=n,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){this.log("incoming request from %p for peers close to %b",e,t.key);try{if(null==t.key)throw new ut("Invalid FIND_NODE message received - key was missing");const n=await this.peerRouting.getClosestPeersOffline(t.key,{exclude:[e,this.peerId]});Ln(this.peerId.toMultihash().bytes,t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map(e=>e.decapsulateCode(eu))});const r={type:Nv.FIND_NODE,clusterLevel:t.clusterLevel,closer:n.map(this.peerInfoMapper).filter(({multiaddrs:e})=>e.length).map(e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map(e=>e.bytes)})),providers:[]};return 0===r.closer.length?this.log("could not find any peers closer to %b for %p",t.key,e):this.log("found %d peers close to %b for %p",r.closer.length,t.key,e),r}catch(n){throw this.log("error during finding peers closer to %b for %p - %e",t.key,e,n),n}}}class zw{peerId;peerRouting;providers;peerStore;peerInfoMapper;log;constructor(e,t){const{peerRouting:n,providers:r,logPrefix:i}=t;this.log=e.logger.forComponent(`${i}:rpc:handlers:get-providers`),this.peerId=e.peerId,this.peerStore=e.peerStore,this.peerRouting=n,this.providers=r,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){if(null==t.key)throw new ut("Invalid GET_PROVIDERS message received - key was missing");let n;try{n=kn.decode(t.key)}catch(e){throw new ut("Invalid CID")}this.log("%p asking for providers for %s",e,n);const[r,i]=await Promise.all([Tl(Vv(await this.providers.getProviders(n),async e=>{const t=await this.peerStore.get(e),n={id:t.id,multiaddrs:t.addresses.map(({multiaddr:e})=>e)};return n})),this.peerRouting.getClosestPeersOffline(t.key)]),s={type:Nv.GET_PROVIDERS,key:t.key,clusterLevel:t.clusterLevel,closer:i.map(this.peerInfoMapper).filter(({multiaddrs:e})=>e.length>0).map(e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map(e=>e.bytes)})),providers:r.map(this.peerInfoMapper).filter(({multiaddrs:e})=>e.length>0).map(e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map(e=>e.bytes)}))};return this.log("got %s providers %s closerPeers",s.providers.length,s.closer.length),s}async _getAddresses(e){return[]}}class Vw{peerStore;datastore;peerRouting;log;datastorePrefix;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:get-value`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.peerStore=e.peerStore,this.datastore=e.datastore,this.peerRouting=t.peerRouting}async handle(e,t){const n=t.key;if(this.log("%p asked for key %b",e,n),null==n||0===n.length)throw new ut("Invalid key");const r={type:Nv.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===mr(e.subarray(0,4))}(n)){this.log("is public key");const e=function(e){return qo(xn(e.subarray(4)))}(n);let t;try{const n=await this.peerStore.get(e);if(null==n.id.publicKey)throw new nt("No public key found in key book");t=Fo(n.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=t)return this.log("returning found public key"),r.record=new zv(n,t,new Date).serialize(),r}const[i,s]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getClosestPeersOffline(n)]);return null!=i&&(this.log("had record for %b in local datastore",n),r.record=i.serialize()),s.length>0&&(this.log("had %s closer peers in routing table",s.length),r.closer=s.map(e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map(e=>e.bytes)}))),r}async _checkLocalDatastore(e){this.log("checkLocalDatastore looking for %b",e);const t=uw(this.datastorePrefix,e);let n;try{n=await this.datastore.get(t)}catch(e){if("NotFoundError"===e.name)return;throw e}const r=zv.deserialize(n);if(!(null==r.timeReceived||Date.now()-r.timeReceived.getTime()>Dv))return r;await this.datastore.delete(t)}}class Gw{log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:ping`)}async handle(e,t){return this.log("ping from %p",e),t}}class Kw{components;validators;log;datastorePrefix;constructor(e,t){const{validators:n}=t;this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:put-value`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n}async handle(e,t){const n=t.key;if(this.log("%p asked us to store value for key %b",e,n),null==t.record)throw this.log.error("empty record from %p",e),new ut(`Empty record from: ${e}`);try{const e=zv.deserialize(t.record);await nw(this.validators,e),e.timeReceived=new Date;const r=uw(this.datastorePrefix,e.key);await this.components.datastore.put(r,e.serialize().subarray()),this.log("put record for %b into datastore under key %k",n,r)}catch(e){this.log("did not put record for key %b into datastore %o",n,e)}return t}}class Hw{handlers;log;metrics;incomingMessageTimeout;constructor(e,t){this.metrics={operations:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_inbound_rpc_requests_total`),errors:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_inbound_rpc_errors_total`),rpcTime:e.metrics?.registerMetricGroup(`${t.metricsPrefix}_inbound_rpc_time_seconds`,{label:"operation"})},this.log=e.logger.forComponent(`${t.logPrefix}:rpc`),this.incomingMessageTimeout=t.incomingMessageTimeout??1e4,this.handlers={[Nv.GET_VALUE.toString()]:new Vw(e,t),[Nv.PUT_VALUE.toString()]:new Kw(e,t),[Nv.FIND_NODE.toString()]:new $w(e,t),[Nv.ADD_PROVIDER.toString()]:new qw(e,t),[Nv.GET_PROVIDERS.toString()]:new zw(e,t),[Nv.PING.toString()]:new Gw(e,t)}}async handleMessage(e,t){const n=this.handlers[t.type];if(null!=n)try{return this.metrics.operations?.increment({[t.type]:!0}),await n.handle(e,t)}catch{this.metrics.errors?.increment({[t.type]:!0})}else this.log.error(`no handler found for message type: ${t.type}`)}async onIncomingStream(e,t){const n=()=>{e.abort(new ct)};let r=AbortSignal.timeout(this.incomingMessageTimeout);r.addEventListener("abort",n);const i=mc(e).pb(qv);for(;;){if("readable"!==e.readStatus){await e.close({signal:r});break}const s=await i.read({signal:r}),a=this.metrics?.rpcTime?.timer(s.type.toString()),o=this.metrics?.rpcTime?.timer(s.type.toString());let u=!1;try{this.log("incoming %s from %p",s.type,t.remotePeer);const e=await this.handleMessage(t.remotePeer,s);null!=e&&await i.write(e,{signal:r})}catch(e){throw u=!0,o?.(),e}finally{u||a?.()}r.removeEventListener("abort",n),r=AbortSignal.timeout(this.incomingMessageTimeout),r.addEventListener("abort",n)}}}class Ww extends Ft{log;components;protocol;running;registrarId;constructor(e,t){super();const{protocol:n,logPrefix:r}=t;this.components=e,this.log=e.logger.forComponent(`${r}:topology-listener`),this.running=!1,this.protocol=n}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.registrarId=await this.components.registrar.register(this.protocol,{onConnect:e=>{this.log("observed peer %p with protocol %s",e,this.protocol),this.dispatchEvent(new CustomEvent("peer",{detail:e}))}}))}async stop(){this.running=!1,null!=this.registrarId&&(this.components.registrar.unregister(this.registrarId),this.registrarId=void 0)}}class Qw{dht;constructor(e){this.dht=e}async provide(e,t={}){await uh(this.dht.provide(e,t))}async cancelReprovide(e){await this.dht.cancelReprovide(e)}async*findProviders(e,t={}){for await(const n of this.dht.findProviders(e,t))"PROVIDER"===n.name&&(yield*n.providers.map(e=>({...e,routing:"kad-dht"})))}async put(e,t,n){await uh(this.dht.put(e,t,n))}async get(e,t){for await(const n of this.dht.get(e,t))if("VALUE"===n.name)return n.value;throw new nt("Could not find value for key")}}class Yw{dht;constructor(e){this.dht=e}async findPeer(e,t={}){for await(const n of this.dht.findPeer(e,t))if("FINAL_PEER"===n.name)return n.peer;throw new nt("Peer not found")}async*getClosestPeers(e,t={}){for await(const n of this.dht.getClosestPeers(e,t))"FINAL_PEER"===n.name&&(yield n.peer)}}class Jw extends Ft{k;a;d;protocol;routingTable;providers;network;peerRouting;components;log;running;clientMode;validators;selectors;queryManager;contentFetching;contentRouting;routingTableRefresh;rpc;topologyListener;querySelf;maxInboundStreams;maxOutboundStreams;dhtContentRouting;dhtPeerRouting;peerInfoMapper;reprovider;onPeerConnectTimeout;constructor(e,t={}){super();const n=t.logPrefix??"libp2p:kad-dht",r=t.datastorePrefix??"/dht",i=t.metricsPrefix??"libp2p_kad_dht",s={queries:e.metrics?.registerMetricGroup(`${i}_operations_total`,{label:"operation"}),errors:e.metrics?.registerCounterGroup(`${i}_operation_errors_total`,{label:"operation"}),queryTime:e.metrics?.registerMetricGroup(`${i}_operation_time_seconds`,{label:"operation"}),errorTime:e.metrics?.registerMetricGroup(`${i}_operation_error_time_seconds`,{label:"operation"})};this.running=!1,this.components=e,this.log=e.logger.forComponent(n),this.k=t.kBucketSize??Fw,this.a=t.alpha??10,this.d=t.disjointPaths??this.a,this.protocol=t.protocol??"/ipfs/kad/1.0.0",this.clientMode=t.clientMode??!0,this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.peerInfoMapper=t.peerInfoMapper??sw,this.onPeerConnectTimeout=t.onPeerConnectTimeout??1e4,this.providers=new xw(e,{...t.providers,logPrefix:n,datastorePrefix:r}),this.validators={...rw,...t.validators},this.selectors={...tw,...t.selectors},this.network=new vw(e,{protocol:this.protocol,logPrefix:n,metricsPrefix:i}),this.routingTable=new Ow(e,{kBucketSize:this.k,pingOldContactTimeout:t.pingOldContactTimeout,pingOldContactConcurrency:t.pingOldContactConcurrency,pingOldContactMaxQueueSize:t.pingOldContactMaxQueueSize,pingNewContactTimeout:t.pingNewContactTimeout,pingNewContactConcurrency:t.pingNewContactConcurrency,pingNewContactMaxQueueSize:t.pingNewContactMaxQueueSize,protocol:this.protocol,logPrefix:n,metricsPrefix:i,prefixLength:t.prefixLength,splitThreshold:t.kBucketSplitThreshold,network:this.network});const a=Cd();!0===t.allowQueryWithZeroPeers&&a.resolve(),this.queryManager=new Sw(e,{disjointPaths:this.d,alpha:this.a,logPrefix:n,metricsPrefix:i,initialQuerySelfHasRun:a,routingTable:this.routingTable,allowQueryWithZeroPeers:t.allowQueryWithZeroPeers}),this.peerRouting=new Ew(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:n}),this.contentFetching=new mw(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:n,datastorePrefix:r}),this.contentRouting=new gw(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:n}),this.routingTableRefresh=new jw(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:n}),this.rpc=new Hw(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:n,metricsPrefix:i,datastorePrefix:r,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new Ww(e,{protocol:this.protocol,logPrefix:n}),this.querySelf=new Cw(e,{peerRouting:this.peerRouting,interval:t.querySelfInterval,initialInterval:t.initialQuerySelfInterval,logPrefix:n,initialQuerySelfHasRun:a,operationMetrics:s}),this.reprovider=new kw(e,{...t.reprovide,logPrefix:n,metricsPrefix:i,datastorePrefix:r,contentRouting:this.contentRouting,operationMetrics:s}),this.network.addEventListener("peer",e=>{const t=e.detail;this.onPeerConnect(t).catch(e=>{this.log.error("could not add %p to routing table - %e",t.id,e)}),this.dispatchEvent(new CustomEvent("peer",{detail:t}))}),this.topologyListener.addEventListener("peer",e=>{const t=e.detail;Promise.resolve().then(async()=>{const e=await this.components.peerStore.get(t),n={id:t,multiaddrs:e.addresses.map(({multiaddr:e})=>e),protocols:e.protocols};await this.onPeerConnect(n)}).catch(e=>{this.log.error("could not add %p to routing table - %e",t,e)})}),this.dhtPeerRouting=new Yw(this),this.dhtContentRouting=new Qw(this),null==t.clientMode&&e.events.addEventListener("self:peer:update",e=>{this.log("received update of self-peer info"),Promise.resolve().then(async()=>{const t=e.detail.peer.addresses.some(({multiaddr:e})=>!Ad(e)&&!Zh.exactMatch(e)),n=this.getMode();t&&"client"===n?await this.setMode("server"):"server"!==n||t||await this.setMode("client")}).catch(e=>{this.log.error("error setting dht server mode - %e",e)})}),this.get=hw(this.get.bind(this),s,"GET_VALUE"),this.findProviders=hw(this.findProviders.bind(this),s,"FIND_PROVIDERS"),this.findPeer=hw(this.findPeer.bind(this),s,"FIND_PEER"),this.getClosestPeers=hw(this.getClosestPeers.bind(this),s,"GET_CLOSEST_PEERS"),this.provide=hw(this.provide.bind(this),s,"PROVIDE"),this.put=hw(this.put.bind(this),s,"PUT_VALUE")}[Symbol.toStringTag]="@libp2p/kad-dht";[Rt]=["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery","@libp2p/kad-dht"];[_t]=["@libp2p/identify","@libp2p/ping"];get[Ve](){return this.dhtContentRouting}get[St](){return this.dhtPeerRouting}get[Et](){return this}async onPeerConnect(e){if(this.log.trace("peer %p connected",e.id,e.multiaddrs),0===(e=this.peerInfoMapper(e)).multiaddrs.length)return void this.log.trace("ignoring %p as there were no valid addresses in %s after filtering",e.id,e.multiaddrs.map(e=>e.toString()));const t=AbortSignal.timeout(this.onPeerConnectTimeout);try{await this.routingTable.add(e.id,{signal:t})}catch(t){this.log.error("could not add %p to routing table - %e",e.id,t)}}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}async setMode(e,t){e!==this.getMode()||!0===t?.force?(await this.components.registrar.unhandle(this.protocol,t),e!==this.getMode()||!0===t?.force?"client"===e?(this.log("enabling client mode while in %s mode",this.getMode()),this.clientMode=!0):(this.log("enabling server mode while in %s mode",this.getMode()),this.clientMode=!1,await this.components.registrar.handle(this.protocol,this.rpc.onIncomingStream.bind(this.rpc),{signal:t?.signal,maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams})):this.log("already in %s mode",e)):this.log("already in %s mode",e)}async start(){this.running||(this.running=!0,await this.setMode(this.clientMode?"client":"server",{force:!0}),await kt(this.routingTable,this.queryManager,this.network,this.topologyListener,this.routingTableRefresh,this.reprovider),await kt(this.querySelf))}async stop(){this.running=!1,await It(this.querySelf,this.queryManager,this.network,this.routingTable,this.routingTableRefresh,this.topologyListener,this.reprovider)}async*put(e,t,n={}){yield*this.contentFetching.put(e,t,n)}async*get(e,t={}){yield*this.contentFetching.get(e,t)}async*provide(e,t={}){yield*this.contentRouting.provide(e,this.components.addressManager.getAddresses(),t)}async cancelReprovide(e,t){await this.providers.removeProvider(e,this.components.peerId,t)}async*findProviders(e,t={}){yield*this.contentRouting.findProviders(e,t)}async*findPeer(e,t={}){yield*this.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t={}){yield*this.peerRouting.getClosestPeers(e,t)}async refreshRoutingTable(e){this.routingTableRefresh.refreshTable(!0,e)}}function Zw(e={}){return t=>new Jw(t,e)}!function(e){e[e.SEND_QUERY=0]="SEND_QUERY",e[e.PEER_RESPONSE=1]="PEER_RESPONSE",e[e.FINAL_PEER=2]="FINAL_PEER",e[e.QUERY_ERROR=3]="QUERY_ERROR",e[e.PROVIDER=4]="PROVIDER",e[e.VALUE=5]="VALUE",e[e.ADD_PEER=6]="ADD_PEER",e[e.DIAL_PEER=7]="DIAL_PEER",e[e.PATH_ENDED=8]="PATH_ENDED"}(Bw||(Bw={}));class Xw{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[Rt]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(e,t){const n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);const r=AbortSignal.timeout(this.timeout);r.addEventListener("abort",()=>{e.abort(new ct("Ping timed out"))});const i=Date.now();for await(const t of e){if("open"!==e.status){n("stream status changed to %s",e.status);break}e.send(t)||(n("waiting for stream to drain"),await _d(e,"drain",{rejectionEvents:["close"],signal:r}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-i),await e.close({signal:r})}async ping(e,t={}){const n=io(32),r=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),i=r.log.newScope("ping");try{const e=Date.now(),i=Promise.withResolvers(),s=new $n,a=o=>{if(s.append(o.data),32===s.byteLength){r.removeEventListener("message",a);const o=Date.now()-e;Promise.all([r.closeRead(t)]).then(()=>{if(!Ln(n,s.subarray()))throw new dt(`Received wrong ping ack after ${o}ms`);i.resolve(o)}).catch(e=>{r.abort(e),i.reject(e)})}};return r.addEventListener("message",a),r.send(n),await r.close(t),await $d(i.promise,t.signal)}catch(t){throw i.error("error while pinging %o - %e",e,t),r?.abort(t),t}finally{r?.close()}}}function eT(e={}){return t=>new Xw(t,e)}function tT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function nT(e,t,n){if(!e.s){if(n instanceof rT){if(!n.s)return void(n.o=nT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(nT.bind(null,e,t),nT.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var rT=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var s=1&i?t:n;if(s){try{nT(r,1,s(this.v))}catch(e){nT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?nT(r,1,t?t(i):i):n?nT(r,1,n(i)):nT(r,2,i)}catch(e){nT(r,2,e)}},r},e}();function iT(e){return e instanceof rT&&1&e.s}function sT(e,t,n){for(var r;;){var i=e();if(iT(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!iT(s)){r=1;break}s=s.s}if(t){var a=t();if(a&&a.then&&!iT(a)){r=2;break}}}var o=new rT,u=nT.bind(null,o,2);return(0===r?i.then(c):1===r?s.then(d):a.then(l)).then(void 0,u),o;function d(r){s=r;do{if(t&&(a=t())&&a.then&&!iT(a))return void a.then(l).then(void 0,u);if(!(i=e())||iT(i)&&!i.v)return void nT(o,1,s);if(i.then)return void i.then(c).then(void 0,u);iT(s=n())&&(s=s.v)}while(!s||!s.then);s.then(d).then(void 0,u)}function c(e){e?(s=n())&&s.then?s.then(d).then(void 0,u):d(s):nT(o,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):nT(o,1,s)}}function aT(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var oT="/ocean/nodes/1.0.0",uT=1e4,dT=["/dns4/bootstrap1.oncompute.ai/tcp/9001/ws/p2p/16Uiu2HAmLhRDqfufZiQnxvQs2XHhd6hwkLSPfjAQg1gH8wgRixiP","/dns4/bootstrap2.oncompute.ai/tcp/9001/ws/p2p/16Uiu2HAmHwzeVw7RpGopjZe6qNBJbzDDBdqtrSk7Gcx1emYsfgL4","/dns4/bootstrap3.oncompute.ai/tcp/9001/ws/p2p/16Uiu2HAmBKSeEP3v4tYEPsZsZv9VELinyMCsrVTJW9BvQeFXx28U","/dns4/bootstrap4.oncompute.ai/tcp/9001/ws/p2p/16Uiu2HAmSTVTArioKm2wVcyeASHYEsnx2ZNq467Z4GMDU4ErEPom"],cT=/*#__PURE__*/function(){function e(){this.p2pConfig={},this.libp2pNode=null}var t=e.prototype;return t.setupP2P=function(e){try{var t=this;return t.p2pConfig=e,t.libp2pNode&&(Promise.resolve(t.libp2pNode.stop()).catch(function(){}),t.libp2pNode=null),Promise.resolve(t.getOrCreateLibp2pNode()).then(function(){})}catch(e){return Promise.reject(e)}},t.getMultiaddrFromPeerId=function(e){try{var t,n,r=function(e){return e.includes("/p2p/")?e:e+"/p2p/"+e};return Promise.resolve(this.getOrCreateLibp2pNode()).then(function(i){var s;function a(a){var o;if(s)return a;function u(t){if(o)return t;throw new Error("No multiaddrs found for peer id "+e)}var d,c=i.services.dht,l=!1,p=!1,h=aT(function(){return tT(function(){return t=P(c.findPeer(Uo(e),{signal:AbortSignal.timeout(2e4)})),sT(function(){function e(e){return!o&&(l=!(n=e).done)}return o?!!e(!o&&t.next()):Promise.resolve(!o&&t.next()).then(e)},function(){return!!(l=!1)},function(){var e=n.value;if(e.type===Bw.FINAL_PEER&&e.peer.multiaddrs.length>0){var t=e.peer.multiaddrs[0].toString(),i=r(t);return o=1,i}})},function(e){p=!0,d=e})},function(e,n){function r(t){if(o)return t;if(e)throw n;return n}var i=aT(function(){var e=function(){if(l&&null!=t.return)return Promise.resolve(t.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,t){if(p)throw d;if(e)throw t;return t});return i&&i.then?i.then(r):r(i)});return h&&h.then?h.then(u):u(h)}var o=i.getConnections().find(function(t){return t.remotePeer.toString()===e});if(null!=o&&o.remoteAddr){var u=o.remoteAddr.toString();return r(u)}var d=tT(function(){return Promise.resolve(i.peerStore.get(Uo(e))).then(function(e){var t;if((null==e||null==(t=e.addresses)?void 0:t.length)>0){var n=e.addresses[0].multiaddr.toString(),i=r(n);return s=1,i}})},function(){});return d&&d.then?d.then(a):a(d)})}catch(e){return Promise.reject(e)}},t.getLibp2pNode=function(){var e;return null!=(e=this.libp2pNode)?e:null},t.getDiscoveredNodes=function(){try{return this.libp2pNode?Promise.resolve(this.libp2pNode.peerStore.all()).then(function(e){return e.map(function(e){return{peerId:e.id.toString(),multiaddrs:e.addresses.map(function(e){return e.multiaddr.toString()})}})}):Promise.resolve([])}catch(e){return Promise.reject(e)}},t.bufToHex=function(e){var t;if("string"==typeof e)try{e=JSON.parse(e)}catch(t){return e}return"Buffer"===(null==(t=e)?void 0:t.type)&&Array.isArray(e.data)?(new TextDecoder).decode(new Uint8Array(e.data)):e instanceof Uint8Array?(new TextDecoder).decode(e):e},t.handleProtocolCommands=function(e,t){return Promise.resolve()},t.getOrCreateLibp2pNode=function(){try{var e,t=this;if(t.libp2pNode)return Promise.resolve(t.libp2pNode);var n=(null!=(e=t.p2pConfig.bootstrapPeers)?e:dT).map(Pu);return Promise.resolve(async function(e={}){e.privateKey??=await async function(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=Qs.utils.randomSecretKey(),t=Qs.getPublicKey(e),n=function(e,t){const n=new Uint8Array(64);for(let r=0;r<32;r++)n[r]=e[r],n[32+r]=t[r];return n}(e,t);return{privateKey:n,publicKey:t}}();return new ra(e,t)}()}();const t=new jm({...await Du(e),peerId:(n=e.privateKey,jo(n.publicKey))});var n;return!1!==e.start&&await t.start(),t}(k({addresses:{listen:[]},transports:[lg(),Ev()].concat(t.p2pConfig.enableTcp?[hg()]:[]),connectionEncrypters:[Bb()],streamMuxers:[tg()],peerDiscovery:[].concat(n.length>0?[(r={list:n.map(String),timeout:1e4},e=>new xv(e,r))]:[]),services:{identify:kv(),ping:eT(),dht:Zw({protocol:"/ocean/nodes/1.0.0/kad/1.0.0",clientMode:!0})},connectionGater:{denyDialMultiaddr:function(){return!1}},connectionManager:{maxConnections:100},connectionMonitor:{abortConnectionOnPingFailure:!1}},t.p2pConfig.libp2p))).then(function(e){return Promise.resolve(e.start()).then(function(){var n;e.addEventListener("peer:discovery",function(t){var n=t.detail;if(null!=n&&n.id){var r=n.id.toString();e.getConnections().length<100&&0===e.getConnections(n.id).length&&e.dial(n.id,{signal:AbortSignal.timeout(1e4)}).catch(function(e){O.debug("Failed to dial discovered peer "+r+": "+e.message)})}}),t.libp2pNode=e,t.libp2pNode.handle("/ocean/client/1.0.0",t.handleProtocolCommands);for(var r,i=C(null!=(n=t.p2pConfig.additionalRoles)?n:[]);!(r=i()).done;)t.libp2pNode.handle("/ocean/client/"+r.value+"/1.0.0",t.handleProtocolCommands);return e})})}catch(e){return Promise.reject(e)}var r},t.toUint8Array=function(e){return e instanceof Uint8Array?e:e.subarray()},t.isDialable=function(e){return"undefined"==typeof window||e.toString().includes("/tls/sni")},t.peerIdFromMultiaddr=function(e){var t=e.toString().split("/p2p/");return t.length<=1?null:t[t.length-1].split("/")[0]||null},t.getConnection=function(e,t){try{var n=this;return Promise.resolve(n.getOrCreateLibp2pNode()).then(function(r){var i;function s(s){var a;if(i)return s;function o(i){return a?i:(O.debug("[P2P] bare peerId -> dialByPeerId "+e),n.dialByPeerId(r,e,t))}var u=tT(function(){function i(i){if(a)return i;var o=n.peerIdFromMultiaddr(s);if(o){O.debug("[P2P] single fallback -> dialByPeerId "+o);var u=n.dialByPeerId(r,o,t);return a=1,u}throw new Error("Cannot dial address: "+e)}var s=Pu(e),o=function(){if(n.isDialable(s))return O.debug("[P2P] dial single addr: "+s),tT(function(){return Promise.resolve(r.dial(s,{signal:t})).then(function(e){return O.debug("[P2P] dial single SUCCESS via "+e.remoteAddr),a=1,e})},function(e){O.debug("[P2P] dial single failed: "+e.message)})}();return o&&o.then?o.then(i):i(o)},function(e){var t;if(null!=(t=e.message)&&t.includes("Cannot dial"))throw e});return u&&u.then?u.then(o):o(u)}var a=function(){if(Array.isArray(e)){var s=function(s){if(i)return s;for(var a,o=C(e);!(a=o()).done;){var u=n.peerIdFromMultiaddr(a.value);if(u){O.debug("[P2P] Not multiaddrs, fallback to peerId: "+u);var d=n.dialByPeerId(r,u,t);return i=1,d}}throw new Error("No valid addresses and no peer ID in multiaddrs")},a=e.filter(function(e){return n.isDialable(e)}),o=function(){if(a.length>0)return O.debug("[P2P] dial array: "+a.length+" dialable addrs"),tT(function(){return Promise.resolve(r.dial(a,{signal:t})).then(function(e){return O.debug("[P2P] dial array SUCCESS via "+e.remoteAddr),i=1,e})},function(e){O.debug("[P2P] dial array failed: "+e.message)})}();return o&&o.then?o.then(s):s(o)}}();return a&&a.then?a.then(s):s(a)})}catch(e){return Promise.reject(e)}},t.dialByPeerId=function(e,t,n){try{var r,i=function(i){if(r)return i;function o(){function r(){var r;function i(n){return r?n:(O.debug("[P2P] "+t+": last resort dial by peerId"),tT(function(){return Promise.resolve(e.dial(a,{signal:AbortSignal.timeout(1e4)})).then(function(e){return O.debug("[P2P] "+t+": peerId dial SUCCESS via "+e.remoteAddr+" (limited="+(null!=e.limits)+")"),e})},function(){throw new Error("Cannot reach peer "+t+". "+(d.length>0?"Found addrs: "+d.map(String).join(", ")+" (none dialable). ":"No addresses found. ")+"Active connections: "+e.getConnections().length+".")}))}var o=d.filter(function(e){return s.isDialable(e)}).map(function(e){var n=e.toString();return n.includes("/p2p/")?e:Pu(n+"/p2p/"+t)});O.debug("[P2P] "+t+": "+o.length+"/"+d.length+" addrs are dialable");var u=function(){if(o.length>0)return O.debug("[P2P] "+t+": dialing "+o.map(String)),tT(function(){return Promise.resolve(e.dial(o,{signal:n})).then(function(e){return O.debug("[P2P] "+t+": SUCCESS via "+e.remoteAddr+" (limited="+(null!=e.limits)+")"),r=1,e})},function(e){O.debug("[P2P] "+t+": direct dial failed: "+e.message)})}();return u&&u.then?u.then(i):i(u)}var i=d.filter(function(e){return s.isDialable(e)}),o=function(){if(0===i.length){O.debug("[P2P] "+t+": no dialable addrs in peerStore, querying DHT...");var n=tT(function(){var n,r=AbortSignal.timeout(null!=(n=s.p2pConfig.dhtLookupTimeout)?n:6e4);return Promise.resolve(e.peerRouting.findPeer(a,{signal:r})).then(function(e){for(var n,r=C(e.multiaddrs);!(n=r()).done;)c(n.value);O.debug("[P2P] "+t+": DHT returned "+e.multiaddrs.length+" addrs")})},function(e){O.debug("[P2P] "+t+": DHT findPeer failed: "+e.message)});if(n&&n.then)return n.then(function(){})}else O.debug("[P2P] "+t+": "+i.length+" dialable addrs from peerStore, skipping DHT")}();return o&&o.then?o.then(r):r()}var u=new Set,d=[],c=function(e){var t=e.toString();u.has(t)||(u.add(t),d.push(e))},l=tT(function(){return Promise.resolve(e.peerStore.get(a)).then(function(e){if(null!=e&&e.addresses){for(var n,r=C(e.addresses);!(n=r()).done;)c(n.value.multiaddr);O.debug("[P2P] "+t+": "+e.addresses.length+" peerStore addrs")}})},function(){O.debug("[P2P] "+t+": not in peerStore")});return l&&l.then?l.then(o):o()},s=this,a=Uo(t),o=e.getConnections(a).filter(function(e){return"open"===e.status});if(o.length>0)return O.debug("[P2P] "+t+": reusing existing connection via "+o[0].remoteAddr),Promise.resolve(o[0]);var u=function(){if(0===e.getConnections().length)return O.debug("[P2P] "+t+": no connections yet, waiting for bootstrap..."),Promise.resolve(qe(3e3)).then(function(){var n=e.getConnections(a);if(n.length>0)return O.debug("[P2P] "+t+": connected during bootstrap wait"),r=1,n[0]})}();return Promise.resolve(u&&u.then?u.then(i):i(u))}catch(e){return Promise.reject(e)}},t.getConsumerAddress=function(e){return pT(e)},t.getSignature=function(e,t,n){return lT(e,t,n)},t.getNodePublicKey=function(e){try{return Promise.resolve(this.getEndpoints(e)).then(function(e){return null==e?void 0:e.nodePublicKey})}catch(e){return Promise.reject(e)}},t.getAuthorization=function(e){return hT(e)},t.dialAndStream=function(e,t,n,r){try{var i,s=this,a=null!=n?n:AbortSignal.timeout(null!=(i=s.p2pConfig.dialTimeout)?i:uT);return Promise.resolve(s.getConnection(e,a)).then(function(e){return tT(function(){return Promise.resolve(e.newStream(oT,{signal:a,runOnLimitedConnection:!0})).then(function(n){var i=fc(n),o=t;return r&&(o=k({},t,{p2pStreamBody:!0})),Promise.resolve(i.write((new TextEncoder).encode(JSON.stringify(o)),{signal:a})).then(function(){function t(){return Promise.resolve(n.close()).then(function(){return Promise.resolve(i.read({signal:a})).then(function(t){var n=s.toUint8Array(t);return{lp:i,firstBytes:n,connection:e}})})}var o=function(){if(r)return Promise.resolve(function(e,t,n){try{var r,i,s,a=function(t){return Promise.resolve(e.write(new Uint8Array(0),{signal:n})).then(function(){})},o=!1,u=!1,d=aT(function(){return tT(function(){r=P(t);var s=sT(function(){return Promise.resolve(r.next()).then(function(e){return o=!(i=e).done})},function(){return!!(o=!1)},function(){return Promise.resolve(e.write(function(e){if(e instanceof Uint8Array)return e;if("string"==typeof e)return(new TextEncoder).encode(e);if(e&&"object"==typeof e&&ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type for P2P request body")}(i.value),{signal:n})).then(function(){})});if(s&&s.then)return s.then(function(){})},function(e){u=!0,s=e})},function(e,t){function n(n){if(e)throw t;return t}var i=aT(function(){var e=function(){if(o&&null!=r.return)return Promise.resolve(r.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,t){if(u)throw s;if(e)throw t;return t});return i&&i.then?i.then(n):n()});return Promise.resolve(d&&d.then?d.then(a):a())}catch(e){return Promise.reject(e)}}(i,r,a)).then(function(){})}();return o&&o.then?o.then(t):t()})})},function(t){try{e.abort(new Error("stream failed"))}catch(e){}throw t})})}catch(e){return Promise.reject(e)}},t.sendP2pCommand=function(e,t,n,r,i,s,a){void 0===s&&(s=0);try{var o=this;return Promise.resolve(tT(function(){var u=k({command:t,authorization:r?o.getAuthorization(r):void 0},n);return Promise.resolve(o.dialAndStream(e,u,i,a)).then(function(u){var d=u.lp,c=u.firstBytes;function l(u){for(var d,c,l,p=0;p<m.length;p++){var h=(new TextDecoder).decode(m[p]);try{l=JSON.parse(h)}catch(e){l=m[p]}}var f=l;if("number"==typeof(null==f?void 0:f.httpStatus)&&f.httpStatus>=400)throw new Error("string"==typeof f.error?f.error:JSON.stringify(f.error));var y=null!=(d="string"==typeof l?l:null==f?void 0:f.error)?d:"",b=function(u){if(y.includes("Cannot connect to peer")&&s<(null!=(u=o.p2pConfig.maxRetries)?u:5))return Promise.resolve(new Promise(function(e){var t;return setTimeout(e,null!=(t=o.p2pConfig.retryDelay)?t:1e3)})).then(function(){var u=o.sendP2pCommand(e,t,n,r,i,s+1,a);return c=1,u})}();return b&&b.then?b.then(function(e){return c?e:l}):c?b:l}if(!c.length)throw new Error("Gateway node error: no response from peer");var p=(new TextDecoder).decode(c);try{var h,f=JSON.parse(p);if("number"==typeof(null==f?void 0:f.httpStatus)&&f.httpStatus>=400)throw new Error(null!=(h=f.error)?h:"Gateway node error: "+f.httpStatus)}catch(e){}if(t===T.COMPUTE_GET_STREAMABLE_LOGS||t===T.COMPUTE_GET_RESULT)return F(/*#__PURE__*/D().mark(function e(){var t;return D().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,A(d.read({signal:AbortSignal.timeout(uT)}));case 4:return t=e.sent,e.next=7,t instanceof Uint8Array?t:t.subarray();case 7:e.next=1;break;case 9:e.next=15;break;case 11:if(e.prev=11,e.t0=e.catch(0),e.t0 instanceof Bd){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))();var m=[c],y=tT(function(){var e=sT(function(){return!0},void 0,function(){var e;return Promise.resolve(d.read({signal:AbortSignal.timeout(null!=(e=o.p2pConfig.dialTimeout)?e:uT)})).then(function(e){m.push(o.toUint8Array(e))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof Bd))throw e});return y&&y.then?y.then(l):l()})},function(u){var d,c;function l(e){if(c)return e;throw new Error("P2P command error: "+p)}var p=null!=(d=null==u?void 0:u.message)?d:"",h=function(u){if((p.includes("closed")||p.includes("reset"))&&s<(null!=(u=o.p2pConfig.maxRetries)?u:5))return O.debug("[P2P] Stream reset/closed on attempt "+(s+1)+", retrying..."),Promise.resolve(qe(1e3)).then(function(){var u=o.sendP2pCommand(e,t,n,r,i,s+1,a);return c=1,u})}();return h&&h.then?h.then(l):l(h)}))}catch(e){return Promise.reject(e)}},t.getEndpoints=function(e){try{var t=this;return Promise.resolve(tT(function(){return Promise.resolve(t.sendP2pCommand(e,T.STATUS,{}))},function(e){throw O.error("P2P getEndpoints (STATUS) failed:",e),e}))}catch(e){return Promise.reject(e)}},t.getNodeStatus=function(e,t){try{return Promise.resolve(this.getEndpoints(e))}catch(e){return Promise.reject(e)}},t.getNodeJobs=function(e,t,n){try{var r=this;return Promise.resolve(tT(function(){var i={};return t&&(i.fromTimestamp=t.toString()),Promise.resolve(r.sendP2pCommand(e,T.JOBS,i,null,n)).then(function(e){return Array.isArray(e)?e:[]})},function(e){return O.error("P2P getNodeJobs failed:",e),[]}))}catch(e){return Promise.reject(e)}},t.getNonce=function(e,t,n){try{var r=this;return Promise.resolve(tT(function(){return Promise.resolve(r.sendP2pCommand(e,T.NONCE,{address:t},null,n)).then(function(e){var t,n,r="number"==typeof e?e:null!=(t=null!=(n=null==e?void 0:e.nonce)?n:e)?t:0;return r&&null!==r?Number(r):0})},function(e){throw O.error("P2P getNonce failed:",e),e}))}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getConsumerAddress(r)).then(function(i){return Promise.resolve(a.getNonce(n,i,s)).then(function(o){var u=(o+1).toString();return Promise.resolve(a.getSignature(r,u,T.ENCRYPT)).then(function(o){return Promise.resolve(a.sendP2pCommand(n,T.ENCRYPT,{chainId:t,nonce:u,consumerAddress:i,signature:o,blob:"string"==typeof e?e:JSON.stringify(e)},r,s)).then(function(e){return a.bufToHex(e)})})})})}catch(e){return Promise.reject(e)}},t.checkDidFiles=function(e,t,n,r,i){void 0===r&&(r=!1);try{return Promise.resolve(this.sendP2pCommand(n,T.FILE_INFO,{did:e,serviceId:t,checksum:r},null,i)).then(function(e){return Array.isArray(e)?e:[e]})}catch(e){return Promise.reject(e)}},t.getFileInfo=function(e,t,n,r){void 0===n&&(n=!1);try{return Promise.resolve(this.sendP2pCommand(t,T.FILE_INFO,{file:e,type:e.type,checksum:n},null,r)).then(function(e){return Array.isArray(e)?e:[e]})}catch(e){return Promise.reject(e)}},t.getComputeEnvironments=function(e,t){try{return Promise.resolve(this.sendP2pCommand(e,T.COMPUTE_GET_ENVIRONMENTS,{},null,t)).then(function(e){return Array.isArray(e)?e:[e]})}catch(e){return Promise.reject(e)}},t.initialize=function(e,t,n,r,i,s,a,o,u){try{var d={ddoId:e,serviceId:t,consumerAddress:r};return a&&(d.userdata=a),o&&(d.environment=o),u&&(d.validUntil=u),Promise.resolve(this.sendP2pCommand(i,T.GET_FEES,d,null,s))}catch(e){return Promise.reject(e)}},t.initializeCompute=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h){try{var f=function(){function e(){return m.sendP2pCommand(s,T.COMPUTE_INITIALIZE,y,null,c)}var t=function(){if(h)return Promise.resolve(m.getNodePublicKey(s)).then(function(e){e&&(y.output=Cu(e,JSON.stringify(h)))})}();return t&&t.then?t.then(e):e()},m=this,y={datasets:e,algorithm:t,environment:n,payment:{chainId:u,token:r,resources:o},maxJobDuration:i,consumerAddress:a};d&&(y.policyServer=d),l&&(y.queueMaxWaitTime=l);var b=function(){if(p)return Promise.resolve(m.getNodePublicKey(s)).then(function(e){e&&(y.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(p)))})}();return Promise.resolve(b&&b.then?b.then(f):f())}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,a,o){try{var u=this;return Promise.resolve(u.getConsumerAddress(s)).then(function(d){return Promise.resolve(u.getNonce(i,d)).then(function(c){var l=(c+1).toString();return Promise.resolve(u.getSignature(s,l,T.DOWNLOAD)).then(function(c){var p={command:T.DOWNLOAD,authorization:u.getAuthorization(s),fileIndex:n,documentId:e,transferTxId:r,serviceId:t,consumerAddress:d,nonce:l,signature:c};return a&&(p.policyServer=a),o&&(p.userData=o),Promise.resolve(u.dialAndStream(i,p)).then(function(e){var t=e.lp,r=e.firstBytes;function i(e){var t=Au(d);return{data:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),filename:"file"+n}}var s,a=(new TextDecoder).decode(r),o=null;try{o=JSON.parse(a)}catch(e){}if(o&&"number"==typeof o.httpStatus&&o.httpStatus>=400)throw new Error(null!=(s=o.error)?s:"P2P download error: "+o.httpStatus);var d=null===o?[new Uint8Array(r)]:[],c=tT(function(){var e=sT(function(){return!0},void 0,function(){var e;return Promise.resolve(t.read({signal:AbortSignal.timeout(null!=(e=u.p2pConfig.dialTimeout)?e:uT)})).then(function(e){d.push(new Uint8Array(u.toUint8Array(e)))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof Bd))throw e});return c&&c.then?c.then(i):i()})})})})}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m){try{var y=this;return Promise.resolve(y.getConsumerAddress(t)).then(function(b){return Promise.resolve(y.getNonce(e,b,h)).then(function(g){var v=(g+1).toString();return Promise.resolve(y.getSignature(t,v,T.COMPUTE_START)).then(function(g){function w(){function n(){return Promise.resolve(y.sendP2pCommand(e,T.COMPUTE_START,E,t,h)).then(function(e){return Array.isArray(e),e})}var r=function(){if(l)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(E.output=Cu(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var E={environment:n,dataset:r[0],datasets:r,algorithm:i,maxJobDuration:s,feeToken:a,resources:o,chainId:u,payment:{chainId:u,token:a,maxJobDuration:s,resources:o},consumerAddress:b,nonce:v,signature:g};d&&(E.metadata=d),c&&(E.additionalViewers=c),p&&(E.policyServer=p),f&&(E.queueMaxWaitTime=f);var x=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(E.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(m)))})}();return x&&x.then?x.then(w):w()})})})}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p){try{var h=this;return Promise.resolve(h.getConsumerAddress(t)).then(function(f){return Promise.resolve(h.getNonce(e,f,c)).then(function(m){var y=(m+1).toString();return Promise.resolve(h.getSignature(t,y,T.FREE_COMPUTE_START)).then(function(m){function b(){function n(){return Promise.resolve(h.sendP2pCommand(e,T.FREE_COMPUTE_START,g,t,c)).then(function(e){return Array.isArray(e),e})}var r=function(){if(u)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(g.output=Cu(e,JSON.stringify(u)))})}();return r&&r.then?r.then(n):n()}var g={environment:n,dataset:r[0],datasets:r,algorithm:i,resources:s,consumerAddress:f,nonce:y,signature:m};a&&(g.metadata=a),o&&(g.additionalViewers=o),d&&(g.policyServer=d),l&&(g.queueMaxWaitTime=l);var v=function(){if(p)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(g.encryptedDockerRegistryAuth=Cu(e,JSON.stringify(p)))})}();return v&&v.then?v.then(b):b()})})})}catch(e){return Promise.reject(e)}},t.computeStreamableLogs=function(e,t,n,r){try{var i=this;return"string"==typeof t?Promise.resolve(i.sendP2pCommand(e,T.COMPUTE_GET_STREAMABLE_LOGS,{jobId:n},t,r)):Promise.resolve(i.getConsumerAddress(t)).then(function(s){return Promise.resolve(i.getNonce(e,s,r)).then(function(a){var o=(a+1).toString();return Promise.resolve(i.getSignature(t,o,T.COMPUTE_GET_STREAMABLE_LOGS)).then(function(a){return i.sendP2pCommand(e,T.COMPUTE_GET_STREAMABLE_LOGS,{jobId:n,consumerAddress:s,nonce:o,signature:a},t,r)})})})}catch(e){return Promise.reject(e)}},t.computeStop=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getConsumerAddress(n)).then(function(a){return Promise.resolve(s.getNonce(t,a,i)).then(function(o){var u=(o+1).toString();return Promise.resolve(s.getSignature(n,u,T.COMPUTE_STOP)).then(function(o){var d={jobId:e,consumerAddress:a,nonce:u,signature:o};return r&&(d.agreementId=r),s.sendP2pCommand(t,T.COMPUTE_STOP,d,n,i)})})})}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getConsumerAddress(t)).then(function(a){var o={consumerAddress:a};return n&&(o.jobId=n),r&&(o.agreementId=r),s.sendP2pCommand(e,T.COMPUTE_GET_STATUS,o,t,i)})}catch(e){return Promise.reject(e)}},t.getComputeResult=function(e,t,n,r,i){void 0===i&&(i=0);try{var s=this;return Promise.resolve(s.getConsumerAddress(t)).then(function(a){function o(){return Promise.resolve(s.dialAndStream(e,u)).then(function(e){var t,n,r=e.lp,i=e.firstBytes,a=JSON.parse((new TextDecoder).decode(i));if("number"==typeof(null==a?void 0:a.httpStatus)&&a.httpStatus>=400)throw new Error(null!=(n=a.error)?n:"P2P compute result error: "+a.httpStatus);var o=null!=(t=s.p2pConfig.dialTimeout)?t:uT;return F(/*#__PURE__*/D().mark(function e(){var t;return D().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,A(r.read({signal:AbortSignal.timeout(o)}));case 4:return t=e.sent,e.next=7,t instanceof Uint8Array?t:t.subarray();case 7:e.next=1;break;case 9:e.next=15;break;case 11:if(e.prev=11,e.t0=e.catch(0),e.t0 instanceof Bd){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))()})}var u={command:T.COMPUTE_GET_RESULT,jobId:n,index:r,offset:i,consumerAddress:a},d=function(){if("string"!=typeof t)return Promise.resolve(s.getNonce(e,a)).then(function(e){var n=(e+1).toString();return u.nonce=n,Promise.resolve(s.getSignature(t,n,T.COMPUTE_GET_RESULT)).then(function(e){u.signature=e})});u.authorization=t}();return d&&d.then?d.then(o):o()})}catch(e){return Promise.reject(e)}},t.getComputeResultUrl=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getConsumerAddress(t)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,T.COMPUTE_GET_RESULT,{jobId:n,index:r,consumerAddress:s},t))})}catch(e){return Promise.reject(e)}},t.generateAuthToken=function(e,t,n){try{var r=this;return Promise.resolve(e.getAddress()).then(function(i){return Promise.resolve(r.getNonce(t,i,n)).then(function(s){var a=(s+1).toString();return Promise.resolve(r.getSignature(e,a,T.CREATE_AUTH_TOKEN)).then(function(e){return Promise.resolve(r.sendP2pCommand(t,T.CREATE_AUTH_TOKEN,{address:i,signature:e,nonce:a},null,n)).then(function(e){var t;return null!=(t=null==e?void 0:e.token)?t:e})})})})}catch(e){return Promise.reject(e)}},t.generateSignedAuthToken=function(e,t,n,r,i){try{return Promise.resolve(this.sendP2pCommand(r,T.CREATE_AUTH_TOKEN,{address:e,signature:t,nonce:n},null,i)).then(function(e){var t;return null!=(t=null==e?void 0:e.token)?t:e})}catch(e){return Promise.reject(e)}},t.resolveDdo=function(e,t,n){try{return Promise.resolve(this.sendP2pCommand(e,T.GET_DDO,{id:t},null,n))}catch(e){return Promise.reject(e)}},t.validateDdo=function(e,t,n,r){try{var i=this;return Promise.resolve(n.getAddress()).then(function(s){return Promise.resolve(i.getNonce(e,s,r)).then(function(a){var o=(a+1).toString();return Promise.resolve($e(n,s+o+T.VALIDATE_DDO)).then(function(n){return Promise.resolve(i.sendP2pCommand(e,T.VALIDATE_DDO,{ddo:t,publisherAddress:s,nonce:o,signature:n},null,r)).then(function(e){var t,n,r,s;return!e||e.error?null:{valid:!0,hash:i.bufToHex(e.hash),proof:{validatorAddress:i.bufToHex(e.publicKey),r:i.bufToHex(null!=(t=null==(n=e.r)?void 0:n[0])?t:e.r),s:i.bufToHex(null!=(r=null==(s=e.s)?void 0:s[0])?r:e.s),v:e.v}}})})})})}catch(e){return Promise.reject(e)}},t.invalidateAuthToken=function(e,t,n,r){try{var i=this;return Promise.resolve(e.getAddress()).then(function(s){return Promise.resolve(i.getNonce(n,s,r)).then(function(a){var o=(a+1).toString();return Promise.resolve($e(e,s+o)).then(function(e){return i.sendP2pCommand(n,T.INVALIDATE_AUTH_TOKEN,{address:s,signature:e,token:t,nonce:o},null,r)})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){var n=this;return Promise.resolve(tT(function(){return Promise.resolve(n.sendP2pCommand(e,T.STATUS,{},null,t)).then(function(e){return!(!e||!(e.address||e.providerAddress||e.providerAddresses))})},function(){return!1}))},t.PolicyServerPassthrough=function(e,t,n){try{return Promise.resolve(this.sendP2pCommand(e,T.POLICY_SERVER_PASSTHROUGH,k({},t),null,n))}catch(e){return Promise.reject(e)}},t.initializePSVerification=function(e,t,n){try{return Promise.resolve(this.sendP2pCommand(e,T.POLICY_SERVER_PASSTHROUGH,k({},t),null,n))}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,a,o,u){try{var d=this;return Promise.resolve(t.getAddress()).then(function(c){return Promise.resolve(d.getNonce(e,c,u)).then(function(l){var p=(l+1).toString();return Promise.resolve(d.getSignature(t,p,T.GET_LOGS)).then(function(l){var h={startTime:n,endTime:r,signature:l,nonce:p,address:c};return i&&(h.maxLogs=i),s&&(h.moduleName=s),a&&(h.level=a),o&&(h.page=o),d.sendP2pCommand(e,T.GET_LOGS,h,t,u)})})})}catch(e){return Promise.reject(e)}},t.fetchNodeLogs=function(e,t,n,r,i){try{return Promise.resolve(this.sendP2pCommand(e,T.GET_LOGS,k({address:t,signature:n,nonce:r},i)))}catch(e){return Promise.reject(e)}},t.fetchConfig=function(e,t){try{return Promise.resolve(this.sendP2pCommand(e,T.FETCH_CONFIG,t))}catch(e){return Promise.reject(e)}},t.pushConfig=function(e,t){try{return Promise.resolve(this.sendP2pCommand(e,T.PUSH_CONFIG,t))}catch(e){return Promise.reject(e)}},t.getPersistentStorageSignaturePayload=function(e,t,n,r){try{var i=this;return"string"==typeof t?Promise.resolve({}):Promise.resolve(i.getConsumerAddress(t)).then(function(s){return Promise.resolve(i.getNonce(e,s,r)).then(function(e){var r=(e+1).toString();return Promise.resolve(i.getSignature(t,r,n)).then(function(e){if(!e)throw new Error("Could not sign persistent storage request.");return{consumerAddress:s,nonce:r,signature:e}})})})}catch(e){return Promise.reject(e)}},t.createPersistentStorageBucket=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(s){var a;return i.sendP2pCommand(e,T.PERSISTENT_STORAGE_CREATE_BUCKET,k({},s,{accessLists:null!=(a=n.accessLists)?a:[]}),t,r)})}catch(e){return Promise.reject(e)}},t.getPersistentStorageBuckets=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_GET_BUCKETS,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,T.PERSISTENT_STORAGE_GET_BUCKETS,k({},s,{owner:n}),t,r)).then(function(e){return Array.isArray(e)?e:[]})})}catch(e){return Promise.reject(e)}},t.listPersistentStorageFiles=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,T.PERSISTENT_STORAGE_LIST_FILES,k({},s,{bucketId:n}),t,r)).then(function(e){return Array.isArray(e)?e:[]})})}catch(e){return Promise.reject(e)}},t.getPersistentStorageFileObject=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(a){return s.sendP2pCommand(e,T.PERSISTENT_STORAGE_GET_FILE_OBJECT,k({},a,{bucketId:n,fileName:r}),t,i)})}catch(e){return Promise.reject(e)}},t.uploadPersistentStorageFile=function(e,t,n,r,i,s){try{var a=this;return Promise.resolve(a.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(o){return a.sendP2pCommand(e,T.PERSISTENT_STORAGE_UPLOAD_FILE,k({},o,{bucketId:n,fileName:r}),t,s,0,i)})}catch(e){return Promise.reject(e)}},t.deletePersistentStorageFile=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getPersistentStorageSignaturePayload(e,t,T.PERSISTENT_STORAGE_DELETE_FILE,i)).then(function(a){return s.sendP2pCommand(e,T.PERSISTENT_STORAGE_DELETE_FILE,k({},a,{bucketId:n,fileName:r}),t,i)})}catch(e){return Promise.reject(e)}},e}(),lT=function(e,t,n){try{if("string"==typeof e)return Promise.resolve(null);var r=String,i=String;return Promise.resolve(e.getAddress()).then(function(s){var a=r(i(s)+String(t)+String(n));return $e(e,a)})}catch(e){return Promise.reject(e)}},pT=function(e){try{return Promise.resolve("string"==typeof e?function(e){try{return v.default.decode(e,{json:!0})}catch(e){throw new Error("Error decoding JWT")}}(e).address:e.getAddress())}catch(e){return Promise.reject(e)}};function hT(e){return"string"==typeof e?e:void 0}function fT(e){if(Array.isArray(e))return!0;if(!e)return!1;try{return Pu(e),!0}catch(e){}try{return Uo(e),!0}catch(e){return!1}}var mT=/*#__PURE__*/function(){function e(){this.httpProvider=new Iu,this.p2pProvider=new cT}var t=e.prototype;return t.getImpl=function(e){return Array.isArray(e)||fT(e)?this.p2pProvider:this.httpProvider},t.getNonce=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).getNonce(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{return Promise.resolve(this.getImpl(n).encrypt(e,t,n,r,i,s))}catch(e){return Promise.reject(e)}},t.checkDidFiles=function(e,t,n,r,i){void 0===r&&(r=!1);try{return Promise.resolve(this.getImpl(n).checkDidFiles(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.getFileInfo=function(e,t,n,r){void 0===n&&(n=!1);try{return Promise.resolve(this.getImpl(t).getFileInfo(e,t,n,r))}catch(e){return Promise.reject(e)}},t.getComputeEnvironments=function(e,t){try{return Promise.resolve(this.getImpl(e).getComputeEnvironments(e,t))}catch(e){return Promise.reject(e)}},t.initialize=function(e,t,n,r,i,s,a,o,u){try{return Promise.resolve(this.getImpl(i).initialize(e,t,n,r,i,s,a,o,u))}catch(e){return Promise.reject(e)}},t.initializeCompute=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h){try{return Promise.resolve(this.getImpl(s).initializeCompute(e,t,n,r,i,s,a,o,u,d,c,l,p,h))}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,a,o){try{return Promise.resolve(this.getImpl(i).getDownloadUrl(e,t,n,r,i,s,a,o))}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m){try{return Promise.resolve(this.getImpl(e).computeStart(e,t,n,r,i,s,a,o,u,d,c,l,p,h,f,m))}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,a,o,u,d,c,l,p){try{return Promise.resolve(this.getImpl(e).freeComputeStart(e,t,n,r,i,s,a,o,u,d,c,l,p))}catch(e){return Promise.reject(e)}},t.computeStreamableLogs=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).computeStreamableLogs(e,t,n,r))}catch(e){return Promise.reject(e)}},t.computeStop=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(t).computeStop(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).computeStatus(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.getComputeResultUrl=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).getComputeResultUrl(e,t,n,r))}catch(e){return Promise.reject(e)}},t.getComputeResult=function(e,t,n,r,i){void 0===i&&(i=0);try{return Promise.resolve(this.getImpl(e).getComputeResult(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.generateAuthToken=function(e,t,n){try{return Promise.resolve(this.getImpl(t).generateAuthToken(e,t,n))}catch(e){return Promise.reject(e)}},t.generateSignedAuthToken=function(e,t,n,r,i){try{return Promise.resolve(this.p2pProvider.generateSignedAuthToken(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.invalidateAuthToken=function(e,t,n,r){try{return Promise.resolve(this.getImpl(n).invalidateAuthToken(e,t,n,r))}catch(e){return Promise.reject(e)}},t.resolveDdo=function(e,t,n){try{return Promise.resolve(this.getImpl(e).resolveDdo(e,t,n))}catch(e){return Promise.reject(e)}},t.validateDdo=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).validateDdo(e,t,n,r))}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){try{return Promise.resolve(this.getImpl(e).isValidProvider(e,t))}catch(e){return Promise.reject(e)}},t.PolicyServerPassthrough=function(e,t,n){try{return Promise.resolve(this.getImpl(e).PolicyServerPassthrough(e,t,n))}catch(e){return Promise.reject(e)}},t.initializePSVerification=function(e,t,n){try{return Promise.resolve(this.getImpl(e).initializePSVerification(e,t,n))}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,a,o,u){try{return Promise.resolve(this.getImpl(e).downloadNodeLogs(e,t,n,r,i,s,a,o,u))}catch(e){return Promise.reject(e)}},t.getNodeStatus=function(e,t){try{return Promise.resolve(this.getImpl(e).getNodeStatus(e,t))}catch(e){return Promise.reject(e)}},t.getNodeJobs=function(e,t,n){try{return Promise.resolve(this.getImpl(e).getNodeJobs(e,t,n))}catch(e){return Promise.reject(e)}},t.setupP2P=function(e){try{return Promise.resolve(this.p2pProvider.setupP2P(e))}catch(e){return Promise.reject(e)}},t.getLibp2pNode=function(){return this.p2pProvider.getLibp2pNode()},t.getDiscoveredNodes=function(){try{return Promise.resolve(this.p2pProvider.getDiscoveredNodes())}catch(e){return Promise.reject(e)}},t.getMultiaddrFromPeerId=function(e){try{return Promise.resolve(this.p2pProvider.getMultiaddrFromPeerId(e))}catch(e){return Promise.reject(e)}},t.fetchNodeLogs=function(e,t,n,r,i){try{return Promise.resolve(this.p2pProvider.fetchNodeLogs(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.createPersistentStorageBucket=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).createPersistentStorageBucket(e,t,n,r))}catch(e){return Promise.reject(e)}},t.getPersistentStorageBuckets=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).getPersistentStorageBuckets(e,t,n,r))}catch(e){return Promise.reject(e)}},t.listPersistentStorageFiles=function(e,t,n,r){try{return Promise.resolve(this.getImpl(e).listPersistentStorageFiles(e,t,n,r))}catch(e){return Promise.reject(e)}},t.getPersistentStorageFileObject=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).getPersistentStorageFileObject(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.uploadPersistentStorageFile=function(e,t,n,r,i,s){try{return Promise.resolve(this.getImpl(e).uploadPersistentStorageFile(e,t,n,r,i,s))}catch(e){return Promise.reject(e)}},t.deletePersistentStorageFile=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).deletePersistentStorageFile(e,t,n,r,i))}catch(e){return Promise.reject(e)}},t.fetchConfig=function(e,t){try{return Promise.resolve(this.p2pProvider.fetchConfig(e,t))}catch(e){return Promise.reject(e)}},t.pushConfig=function(e,t){try{return Promise.resolve(this.p2pProvider.pushConfig(e,t))}catch(e){return Promise.reject(e)}},e}(),yT=new mT;function bT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function gT(e,t,n){if(!e.s){if(n instanceof vT){if(!n.s)return void(n.o=gT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(gT.bind(null,e,t),gT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var vT=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var s=1&i?t:n;if(s){try{gT(r,1,s(this.v))}catch(e){gT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?gT(r,1,t?t(i):i):n?gT(r,1,n(i)):gT(r,2,i)}catch(e){gT(r,2,e)}},r},e}();function wT(e){return e instanceof vT&&1&e.s}var TT=/*#__PURE__*/function(){function e(e){this.aquariusURL=void 0,this.aquariusURL=e}var t=e.prototype;return t.resolve=function(e,t,n){try{var r,i=function(i){if(r)return i;var a=s.aquariusURL+"/api/aquarius/assets/ddo/"+e;return bT(function(){return Promise.resolve(g.default(a,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:t})).then(function(e){if(e.ok)return Promise.resolve(e.json());throw new Error("HTTP request failed with status "+e.status)})},function(e){throw O.error(e),new Error("HTTP request failed")})},s=this,a=function(){if(fT(s.aquariusURL))return Promise.resolve(yT.resolveDdo(s.aquariusURL,e,t)).then(function(e){if(e)return r=1,e;throw new Error("P2P request failed")})}();return Promise.resolve(a&&a.then?a.then(i):i(a))}catch(e){return Promise.reject(e)}},t.waitForIndexer=function(e,t,n,r,i,s){void 0===r&&(r=3e4),void 0===i&&(i=100);try{var o,u=this,d=0;i>500&&(O.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);var c=fT(u.aquariusURL),l=function(e,t){var n;do{var r=e();if(r&&r.then){if(!wT(r)){n=!0;break}r=r.v}var i=t();if(wT(i)&&(i=i.v),!i)return r}while(!i.then);var s=new vT,a=gT.bind(null,s,2);return(n?r.then(o):i.then(u)).then(void 0,a),s;function o(n){for(r=n;wT(i=t())&&(i=i.v),i;){if(i.then)return void i.then(u).then(void 0,a);if((r=e())&&r.then){if(!wT(r))return void r.then(o).then(void 0,a);r=r.v}}gT(s,1,r)}function u(n){if(n){do{if((r=e())&&r.then){if(!wT(r))return void r.then(o).then(void 0,a);r=r.v}if(wT(n=t())&&(n=n.v),!n)return void gT(s,1,r)}while(!n.then);n.then(u).then(void 0,a)}else gT(s,1,r)}}(function(){function i(e){return o?e:Promise.resolve(qe(r)).then(function(){d++})}var l=bT(function(){function r(){if(i){var e=a.DDOManager.getDDOClass(i).getAssetFields().indexedMetadata;if(!t)return o=1,i;if(e.event&&e.event.txid===t)return o=1,i}}var i,d=c?Promise.resolve(yT.resolveDdo(u.aquariusURL,e,n)).then(function(e){i=e}):Promise.resolve(g.default(u.aquariusURL+"/api/aquarius/assets/ddo/"+e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:s},signal:n})).then(function(e){var t=function(){if(e.ok)return Promise.resolve(e.json()).then(function(e){i=e})}();if(t&&t.then)return t.then(function(){})});return d&&d.then?d.then(r):r()},function(){});return l&&l.then?l.then(i):i(l)},function(){return!o&&d<i});return Promise.resolve(l&&l.then?l.then(function(e){return o?e:null}):o?l:null)}catch(e){return Promise.reject(e)}},t.validate=function(e,t,n,r,i){try{if(fT(n))return Promise.resolve(yT.validateDdo(n,e,t,r));var s=n+"/api/aquarius/assets/ddo/validate",a=n+"/api/services/nonce";return Promise.resolve(bT(function(){return Promise.resolve(t.getAddress()).then(function(n){return Promise.resolve(g.default(a+"?userAddress="+n,{method:"GET",headers:{"Content-Type":"application/json",Authorization:i},signal:r})).then(function(i){return Promise.resolve(i.json()).then(function(i){var a=i.nonce;a&&null!==a||(a="0");var o=(Number(a)+1).toString(),u=String,d=String;return Promise.resolve(t.getAddress()).then(function(i){var a=u(d(i)+String(o)+String(T.VALIDATE_DDO));return Promise.resolve($e(t,a)).then(function(i){return Promise.resolve(g.default(s,{method:"POST",body:JSON.stringify({ddo:e,publisherAddress:n,nonce:o,signature:i}),headers:{"Content-Type":"application/json",Authorization:hT(t)},signal:r})).then(function(e){return Promise.resolve(e.json()).then(function(t){if(200!==e.status)throw new Error("Metadata validation failed");return{valid:!0,hash:t.hash,proof:{validatorAddress:t.publicKey,r:t.r[0],s:t.s[0],v:t.v}}})})})})})})})},function(e){O.error("Metadata validation failed",e.message)}))}catch(e){return Promise.reject(e)}},t.getAssetMetadata=function(e,t,n){try{var r=this.aquariusURL+"/api/aquarius/assets/metadata/"+e;return Promise.resolve(bT(function(){return Promise.resolve(g.default(r,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:t})).then(function(e){if(e.ok)return e.json();throw new Error("getAssetMetadata failed: "+e.status+e.statusText)})},function(e){throw O.error("Error getting metadata: ",e),new Error("Error getting metadata: "+e)}))}catch(e){return Promise.reject(e)}},t.querySearch=function(e,t,n){try{var r=this.aquariusURL+"/api/aquarius/assets/query";return Promise.resolve(bT(function(){return Promise.resolve(g.default(r,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json",Authorization:n},signal:t})).then(function(e){if(e.ok)return e.json();throw new Error("querySearch failed: "+e.status+e.statusText)})},function(e){throw O.error("Error querying metadata: ",e),new Error("Error querying metadata: "+e)}))}catch(e){return Promise.reject(e)}},e}(),ET=function(e,n,r,i){try{var s=new t.ethers.Contract(n,z,e);return Promise.resolve(s.allowance(r,i))}catch(e){return Promise.reject(e)}},xT=function(e,n,r,i,s){try{var a=new t.ethers.Contract(n,z,e);return Promise.resolve(a.allowance(r,i)).then(function(t){return Promise.resolve(K(e,n,t,s))})}catch(e){return Promise.reject(e)}},PT=function(e,n,r,i,s,a,o,u){void 0===o&&(o=!1);try{var d,c=function(t){if(d)return t;var r=null;return Promise.resolve(l.approve.estimateGas(s,a)).then(function(t){if(u)return t;var i=function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(function(){return Promise.resolve(V(t,e,null==n?void 0:n.gasFeeMultiplier,l.approve,s,a)).then(function(e){r=e})},function(e){O.error("ERROR: Failed to approve spender to spend tokens : "+e.message)});return i&&i.then?i.then(function(){return r}):r})},l=new t.ethers.Contract(i,z,e),p=function(){if(!o)return Promise.resolve(ET(e,i,r,s)).then(function(e){if(new y.default(e).isGreaterThan(new y.default(a))){var t=BigInt(e);return d=1,t}})}();return Promise.resolve(p&&p.then?p.then(c):c(p))}catch(e){return Promise.reject(e)}},ST=function(e,n,r,i,s,a,o,u,d){void 0===o&&(o=!1);try{var c,l=function(t){return c?t:Promise.resolve(G(e,i,a,u)).then(function(t){return Promise.resolve(p.approve.estimateGas(s,t)).then(function(r){return d?new b.default(r.toString()):Promise.resolve(V(r,e,null==n?void 0:n.gasFeeMultiplier,p.approve,s,t))})})},p=new t.ethers.Contract(i,z,e),h=function(){if(!o)return Promise.resolve(xT(e,i,r,s)).then(function(e){if(new b.default(e).greaterThanOrEqualTo(new b.default(a))){var t=new b.default(e).toNumber();return c=1,t}})}();return Promise.resolve(h&&h.then?h.then(l):l(h))}catch(e){return Promise.reject(e)}},AT={datasets:{invalid:"Datasets is not a list, as expected"},algorithm:{serviceId:{missing:"The serviceId key is missing from the algorithm s DDO.",not_found:"The provided serviceId does not exist.",service_not_access_compute:"Service type is neither access, nor compute.",main_service_compute:"If the main service is not compute for this asset when calling initialize endpoint.",compute_services_not_in_same_provider:"Files attached to the compute service are not decrypted by the correct provider. This occurs when both asset and algorithm are requested by their compute service which cannot be decrypted by a single provider as how it is supposed to be."},container:{checksum_prefix:"Container checksum does not start with the prefix sha256:.",mising_entrypoint_image_checksum:"Either entrypoint, either image, or either checksum are missing from the container dictionary from the algorithm s DDO."},documentId:{did_not_found:"The algorithm s DID could not be retrieved from the metadata store, because the algorithm asset does not exist.",missing:"The documentId key is missing from the algorithm s DDO."},transferTxId:{missing:"The transferTxId key is missing from the algorithm s DDO."},missing_meta_documentId:"Either algorithm metadata, or algorithm DID are missing.",did_not_found:"Either algorithm metadata, or algorithm DID are missing.",not_algo:"Either algorithm metadata, or algorithm DID are missing.",in_use_or_not_on_chain:"Either algorithm metadata, or algorithm DID are missing.",meta_oneof_url_rawcode_remote:"Either algorithm metadata, or algorithm DID are missing.",file_unavailable:"One possibility is that the asset could not be retrieved from Aquariuss database. Otherwise, there are issues related to services"},error:{not_trusted_algo_publisher:"The owner of the algorithm's DDO is not a trusted algorithms publishers list.",not_trusted_algo:"The algorithm's DID is not in the asset's trusted algorithms dictionary. ",no_publisherTrustedAlgorithms:"The algorithm's key publisherTrustedAlgorithms does not exist in the algorithm's DDO.",algorithm_file_checksum_mismatch:"filesChecksum from the algorithm's DDO is invalid.",algorithm_container_checksum_mismatch:"The containerChecksum from the algorithm's DDO is invalid.",no_raw_algo_allowed:"The asset does not allow raw algorithms to be run on it.","Asset malformed":"The asset published on chain is malformed, missing some required keys or not compliant with our schemas.","Asset is not consumable.":"Assets metadata status is not in the range of valid status codes for assets. The recognized states for the metadata are defined on our docs.","DID is not a valid algorithm.":"Either the algorithm assets DID is incorrectly typed, either the algorithm timeout expired.","Compute environment does not exist.":"The compute environment provided by the user does not exist, it is not served by our compute-to-data feature. The user can use get_c2d_environments to check the list of available compute environments.","The validUntil value is not correct.":"validUntil value is most probably expired.","Cannot resolve DID":"The dataset DID does not exist in the Metadata store.","Invalid serviceId":"The serviceId of that dataset is not correct.","Unable to get dataset files":"The files of that dataset could not be decrypted or retrieved","cannot decrypt files for this service.":"The files of that dataset could not be decrypted due to the fact that file object, which contains the structure and the type of specific file, is missing from the validation part.","Unsupported type ":"The file object type is not supported by Provider.","malformed file object":"The file object structure is invalid and does not contain the wanted information for the specific file."},order:{fees_not_paid:" Provider fees are not paid."},output:{invalid:"The algorithms validation after the build stage has not been decoded properly as a dictionary."}};function CT(e,t,n){if(!e.s){if(n instanceof kT){if(!n.s)return void(n.o=CT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(CT.bind(null,e,t),CT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var kT=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var s=1&i?t:n;if(s){try{CT(r,1,s(this.v))}catch(e){CT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?CT(r,1,t?t(i):i):n?CT(r,1,n(i)):CT(r,2,i)}catch(e){CT(r,2,e)}},r},e}();function IT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}exports.AccessListContract=Fe,exports.AccesslistFactory=_e,exports.Aquarius=TT,exports.Config=function(){this.nodeUri=void 0,this.providerAddress=void 0,this.oceanNodeUri=void 0,this.web3Provider=void 0,this.oceanTokenAddress=void 0,this.nftFactoryAddress=void 0,this.routerFactoryAddress=void 0,this.datatokensABI=void 0,this.fixedRateExchangeAddress=void 0,this.fixedRateExchangeAddressABI=void 0,this.dispenserAddress=void 0,this.dispenserABI=void 0,this.opfCommunityFeeCollector=void 0,this.EnterpriseFeeCollector=void 0,this.sideStakingAddress=void 0,this.startBlock=void 0,this.verbose=void 0,this.authMessage=void 0,this.authTokenExpiration=void 0,this.parityUri=void 0,this.threshold=void 0,this.chainId=void 0,this.network=void 0,this.explorerUri=void 0,this.oceanTokenSymbol=void 0,this.transactionBlockTimeout=void 0,this.transactionConfirmationBlocks=void 0,this.transactionPollingTimeout=void 0,this.gasFeeMultiplier=void 0,this.sdk=void 0,this.accessListFactory=void 0,this.escrow=void 0},exports.ConfigHelper=$,exports.DEVELOPMENT_CHAIN_ID=8996,exports.Datatoken=ke,exports.Datatoken4=De,exports.Dispenser=ae,exports.EnterpriseFeeCollectorContract=je,exports.EscrowContract=Be,exports.FEE_HISTORY_NOT_SUPPORTED="Returned error: Method eth_feeHistory not supported.",exports.FixedRateExchange=de,exports.GASLIMIT_DEFAULT=1e6,exports.KNOWN_CONFIDENTIAL_EVMS=j,exports.Logger=N,exports.LoggerInstance=O,exports.MAX_UINT_256="115792089237316195423570985008687907853269984665640564039457584007913129639934",exports.Nft=Ce,exports.NftFactory=ve,exports.OCEAN_P2P_PROTOCOL=oT,exports.PROTOCOL_COMMANDS=T,exports.Provider=mT,exports.ProviderInstance=yT,exports.Router=le,exports.SmartContract=re,exports.SmartContractWithAddress=ie,exports.ZERO_ADDRESS=ue,exports.allowance=xT,exports.allowanceWei=ET,exports.amountToUnits=G,exports.approve=ST,exports.approveWei=PT,exports.balance=function(e,n,r,i){try{var s=new t.ethers.Contract(n,z,e);return Promise.resolve(s.balanceOf(r)).then(function(t){return Promise.resolve(K(e,n,t,i))})}catch(e){return Promise.reject(e)}},exports.bytesToHex=Su,exports.calculateActiveTemplateIndex=Pe,exports.concatUint8Arrays=Au,exports.configHelperNetworks=U,exports.createAccessListFactory=function(e,n,r){try{var i=new t.ethers.Contract(e,Re,n);return Promise.resolve(n.getAddress()).then(function(e){var t,n=IT(function(){return Promise.resolve(i.deployAccessListContract("AllowList","ALLOW",!0,e,r||[e],["https://oceanprotocol.com/nft/"])).then(function(e){return function(){if(e&&e.wait)return Promise.resolve(e.wait()).then(function(e){var n=ne(e,"NewAccessList");return t=1,n.args[0]})}()})},function(e){console.log("ERROR createAccessListFactory(): ",e)});return n&&n.then?n.then(function(e){return t?e:null}):t?n:null})}catch(e){return Promise.reject(e)}},exports.createAsset=function(e,n,r,i,s,o,u,d,c,l,p,h,f,m,y){void 0===u&&(u=!0);try{var b,g,v=this,T=a.DDOManager.getDDOClass(o),E=T.getAssetFields().indexedMetadata,x=(null==(b=T.getDDOData())||null==(b=b.stats)||null==(b=b.price)?void 0:b.value)||(null==E||null==(g=E.stats[0])||null==(g=g.prices[0])?void 0:g.price),P=T.getDDOFields(),S=P.chainId,A=P.nftAddress,C=T.getDDOFields().services;if("string"!=typeof s&&"number"!=typeof s)throw new Error('Invalid template! Must be a "number" or a "string"');return Promise.resolve(r.provider.getNetwork()).then(function(a){var b=a.chainId;if(S&&S!==Number(b))throw new Error("Chain ID from DDO is different than the configured network.");var g=(new $).getConfig(parseInt(String(b)));return Promise.resolve(Pe(r,g.nftFactoryAddress,s,Number(b))).then(function(s){if(s<1){if(8996!==Number(b))throw new Error("Invalid template index: "+s);s=1}var a=new Ce(r,Number(b)),E=new ve(g.nftFactoryAddress,r,Number(b));return Promise.resolve(r.getAddress()).then(function(P){var k;function I(e){return k?e:Promise.resolve(D.wait()).then(function(e){var n;function i(e){if(n)return e;function i(){function e(){var e=a.setMetadata,u=A;return Promise.resolve(r.getAddress()).then(function(r){return Promise.resolve(e.call(a,u,r,0,d,"",t.toBeHex(s),n,i)).then(function(){return o.id})})}C[0].datatokenAddress=h,C[0].serviceEndpoint=d;var n,i,s,c=T.makeDid(A=p,S.toString());o=T.updateFields({id:c,nftAddress:A});var f=function(){if(u)return Promise.resolve(yT.encrypt(o,Number(b),d,r,null)).then(function(e){return n=e,Promise.resolve(l.validate(o,r,d)).then(function(e){i=e.hash,s=2})});var e=JSON.stringify(o);n=t.hexlify(t.toUtf8Bytes(e)),i="0x"+w.default(n).toString(),s=0}();return f&&f.then?f.then(e):e()}var s=function(){if("oasis"!==g.sdk)return Promise.resolve(yT.encrypt(R,Number(b),d,r,null)).then(function(e){C[0].files=e});C[0].files=""}();return s&&s.then?s.then(i):i()}var s=ne(e,"NFTCreated"),c=ne(e,"TokenCreated"),p=s.args.newTokenAddress,h=c.args.newTokenAddress;R.datatokenAddress=h,R.nftAddress=p;var f=function(){if("oasis"===g.sdk){var e=new t.ethers.Contract(h,Ie,r);return IT(function(){return Promise.resolve(e.setFilesObject(t.toUtf8Bytes(JSON.stringify(R)))).then(function(e){var t=function(){if(e.wait)return Promise.resolve(e.wait()).then(function(){})}();if(t&&t.then)return t.then(function(){})})},function(e){return console.log("Error updating files object with data token and nft addresses: ",e),n=1,null})}}();return f&&f.then?f.then(i):i(f)})}var D,M={name:e,symbol:n,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:P},F={templateIndex:s,cap:"100000",feeAmount:"0",paymentCollector:P,feeToken:c||g.oceanTokenAddress,minter:P,mpFeeAddress:ue},R={nftAddress:"0x0",datatokenAddress:"0x0",files:i};"oasis"===g.sdk&&(F.filesObject=R,F.accessListFactory=p||g.accessListFactory,F.allowAccessList=h,F.denyAccessList=f);var _=IT(function(){var e=function(){if(!x)return Promise.resolve(E.createNftWithDatatoken(M,F)).then(function(e){D=e});var e=function(){if("0"===x.toString())return Promise.resolve(E.createNftWithDatatokenWithDispenser(M,F,{dispenserAddress:g.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:ue})).then(function(e){D=e});var e=m||g.oceanTokenAddress;return Promise.resolve(H(v.signer,e)).then(function(t){y||(y=t);var n={fixedRateAddress:g.fixedRateExchangeAddress,baseTokenAddress:e,owner:P,marketFeeCollector:P,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:x.toString(),marketFee:"0",allowedConsumer:P,withMint:!0};return Promise.resolve(E.createNftWithDatatokenWithFixedRate(M,F,n)).then(function(e){D=e})})}();return e&&e.then?e.then(function(){}):void 0}();if(e&&e.then)return e.then(function(){})},function(e){return console.log("ERROR creating NFT bundle",e),k=1,null});return _&&_.then?_.then(I):I(_)})})})}catch(e){return Promise.reject(e)}},exports.decimals=function(e,n){try{var r=new t.ethers.Contract(n,z,e);return Promise.resolve(r.decimals()).then(Number)}catch(e){return Promise.reject(e)}},exports.downloadFile=function(e,t){try{return"string"!=typeof e?Promise.resolve(e):Promise.resolve(fetch(e)).then(function(n){if(!n.ok)throw new Error("Response error.");var r;try{r=n.headers.get("content-disposition").match(/attachment;filename=(.+)/)[1]}catch(n){try{r=e.split("/").pop()}catch(e){r="file"+t}}return Promise.resolve(n.arrayBuffer()).then(function(e){return{data:e,filename:r}})})}catch(e){return Promise.reject(e)}},exports.downloadFileBrowser=function(e){var t=new XMLHttpRequest;t.responseType="blob",t.open("GET",e),t.onload=function(){var e=t.getResponseHeader("content-disposition"),n=null==e?void 0:e.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/),r=n&&n[1]?n[1]:"file",i=window.URL.createObjectURL(t.response),s=document.createElement("a");s.href=i,s.setAttribute("download",r),document.body.appendChild(s),s.click(),s.remove(),window.URL.revokeObjectURL(i)},t.send()},exports.generateDid=function(e,n){return e=t.getAddress(e),"did:op:"+w.default(e+n.toString(10)).toString()},exports.generateDtName=ye,exports.getErrorMessage=function(e){try{var t=JSON.parse(e),n=Object.keys(t)[0];if("error"===n){var r,i=t[n];return(null==(r=AT[n])?void 0:r[i])||"Provider request failed: "+i}var s=t[n];return t[Object.keys(t)[1]]+" : "+s}catch(t){return O.error("[getErrorMessage] error: ",t),e}},exports.getEventFromTx=ne,exports.getFairGasPrice=W,exports.getHash=function(e){return w.default(e).toString()},exports.getNodeEndpointConfig=q,exports.getOceanArtifactsAddresses=Se,exports.getOceanArtifactsAddressesByChainId=Ae,exports.getTokenDecimals=H,exports.isDefined=function(e){return null!=e},exports.isP2pUri=fT,exports.minAbi=z,exports.orderAsset=function(e,t,n,r,i,s,o,u,d,c,l,p){void 0===d&&(d="0"),void 0===c&&(c=0),void 0===l&&(l=0),void 0===p&&(p=0);try{var h=a.DDOManager.getDDOClass(e),f=h.getAssetFields().datatokens,m=h.getDDOFields(),y=m.chainId,g=m.services;return o||(o={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"}),Promise.resolve(t.provider.getNetwork()).then(function(a){if(y!==Number(a.chainId))throw new Error("Chain ID from DDO is different than the configured network.");if(!f[c].address)throw new Error("The datatoken with index: "+c+" does not exist for the asset with did: "+e.id);if(!g[l].id)throw new Error("There is no service with index: "+l+" defined for the asset with did: "+e.id);return Promise.resolve(r.getId(f[c].address)).then(function(a){return Promise.resolve(r.getFixedRates(f[c].address)).then(function(h){return Promise.resolve(r.getDispensers(f[c].address)).then(function(m){return Promise.resolve(r.getPublishingMarketFee(f[c].address)).then(function(y){function v(e){return u?e:Promise.resolve(E.call(yT,P,x,0,e,i||n.oceanNodeUri)).then(w)}function w(i){function m(i){function u(i){var s,u={consumer:i,serviceIndex:l,_providerFee:v,_consumeMarketFee:o};return function(e,t){var n,r=-1;e:{for(var i=0;i<t.length;i++){var s=t[i][0];if(s){var a=s();if(a&&a.then)break e;if(a===e){r=i;break}}else r=i}if(-1!==r){do{for(var o=t[r][1];!o;)r++,o=t[r][1];var u=o();if(u&&u.then){n=!0;break e}var d=t[r][2];r++}while(d&&!d());return u}}var c=new kT,l=CT.bind(null,c,2);return(n?u.then(p):a.then(function n(a){for(;;){if(a===e){r=i;break}if(++i===t.length){if(-1!==r)break;return void CT(c,1,u)}if(s=t[i][0]){if((a=s())&&a.then)return void a.then(n).then(void 0,l)}else r=i}do{for(var o=t[r][1];!o;)r++,o=t[r][1];var u=o();if(u&&u.then)return void u.then(p).then(void 0,l);var d=t[r][2];r++}while(d&&!d());CT(c,1,u)})).then(void 0,l),c;function p(e){for(;;){var n=t[r][2];if(!n||n())break;r++;for(var i=t[r][1];!i;)r++,i=t[r][1];if((e=i())&&e.then)return void e.then(p).then(void 0,l)}CT(c,1,e)}}(T,[[function(){return"free"},function(){var e=function(e){var t;if(s)return e;function i(e){if(t)return e}var o=function(){if(2===a||4===a)return Promise.resolve(r.buyFromDispenserAndOrder(g[l].datatokenAddress,u,n.dispenserAddress)).then(function(e){return t=1,e})}();return o&&o.then?o.then(i):i(o)},i=function(){if(1===a){var e=new ae(n.dispenserAddress,t),i=e.dispense,o=f[c].address;return Promise.resolve(t.getAddress()).then(function(t){return Promise.resolve(i.call(e,o,"1",t)).then(function(e){if(!e)throw new Error("Failed to dispense !");return Promise.resolve(e.wait()).then(function(){return Promise.resolve(r.startOrder(f[c].address,u.consumer,u.serviceIndex,u._providerFee,u._consumeMarketFee)).then(function(e){return s=1,e})})})})}}();return i&&i.then?i.then(e):e(i)}],[function(){return"fixed"},function(){var i=new de(n.fixedRateExchangeAddress,t);if(!h[p].id)throw new Error("There is no fixed rate exchange with index: "+l+" for the asset with did: "+e.id);return Promise.resolve(i.getFeesInfo(h[p].id)).then(function(e){return Promise.resolve(i.getExchange(h[p].id)).then(function(s){return Promise.resolve(i.calcBaseInGivenDatatokensOut(e.exchangeId,"1",o.consumeMarketFeeAmount)).then(function(l){var p;function h(e){var i;if(p)return e;function o(e){if(i)return e}var d=function(){if(2===a||4===a)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(ST(t,n,e,s.baseToken,f[c].address,m,!1)).then(function(e){function t(e){if(!e)throw new Error("Failed to confirm/mine approval transaction!");return Promise.resolve(r.buyFromFreAndOrder(f[c].address,u,g)).then(function(e){return i=1,e})}if(!e)throw new Error("Failed to approve "+s.baseToken+" !");return"number"!=typeof e?Promise.resolve("number"!=typeof e?e.wait():e).then(t):t("number"!=typeof e?e.wait():e)})})}();return d&&d.then?d.then(o):o(d)}var m=new b.default(+l.baseTokenAmount||0).add(new b.default(o.consumeMarketFeeAmount||0)).add(new b.default(+y.publishMarketFeeAmount||0)).toString(),g={exchangeContract:n.fixedRateExchangeAddress,exchangeId:e.exchangeId,maxBaseTokenAmount:m,baseTokenAddress:s.baseToken,baseTokenDecimals:parseInt(s.btDecimals)||18,swapMarketFee:d,marketFeeAddress:y.publishMarketFeeAddress},v=function(){if(1===a)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(ST(t,n,e,s.baseToken,n.fixedRateExchangeAddress,m,!1)).then(function(e){function t(e){if(!e)throw new Error("Failed to approve "+s.baseToken+" !");return Promise.resolve(i.buyDatatokens(s.exchangeId,"1",m,y.publishMarketFeeAddress,d)).then(function(e){return Promise.resolve(e.wait()).then(function(e){if(!e)throw new Error("Failed to buy datatoken from fixed rate!");return Promise.resolve(r.startOrder(f[c].address,u.consumer,u.serviceIndex,u._providerFee,u._consumeMarketFee)).then(function(e){return p=1,e})})})}return"number"!=typeof e?Promise.resolve("number"!=typeof e?e.wait():e).then(t):t("number"!=typeof e?e.wait():e)})})}();return v&&v.then?v.then(h):h(v)})})})}],[void 0,function(){throw new Error("Pricing schema not supported !")}]])}return s?u(s):Promise.resolve(t.getAddress()).then(u)}var v=u||i.providerFee,w=function(){if(v&&v.providerFeeAddress!==ue&&v.providerFeeAmount&&parseInt(v.providerFeeAmount)>0)return function(e,r){try{var i=Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(PT(t,n,e,v.providerFeeToken,g[0].datatokenAddress,v.providerFeeAmount)).then(function(){})})}catch(e){return r()}return i&&i.then?i.then(void 0,r):i}(0,function(){throw new Error("Failed to approve provider fee token "+v.providerFeeToken)})}();return w&&w.then?w.then(m):m()}var T=h.length>0?"fixed":m.length>0?"free":"NOT_ALLOWED",E=u||yT.initialize,x=u||g[l].id,P=u||e.id;return u?v(w(u)):Promise.resolve(t.getAddress()).then(v)})})})})})}catch(e){return Promise.reject(e)}},exports.sendTx=V,exports.setContractDefaults=te,exports.signHash=function(e,n){try{var r=t.getBytes(n);return Promise.resolve(e._legacySignMessage(r)).then(function(e){var t="0x"+(e=e.substr(2)).slice(0,64),n="0x"+e.slice(64,128),r="0x"+e.slice(128,130);return"0x00"===r&&(r="0x1b"),"0x01"===r&&(r="0x1c"),{v:r,r:t,s:n}})}catch(e){return Promise.reject(e)}},exports.signRequest=$e,exports.sleep=qe,exports.transfer=function(e,n,r,i,s,a,o){try{var u=new t.ethers.Contract(r,z,e);return Promise.resolve(G(e,r,s,a)).then(function(t){return Promise.resolve(u.transfer.estimateGas(i,t)).then(function(r){return o?r:Promise.resolve(V(r,e,null==n?void 0:n.gasFeeMultiplier,u.transfer,i,t))})})}catch(e){return Promise.reject(e)}},exports.unitsToAmount=K,exports.useOasisSDK=function(e){var t=(new $).getConfig(e);return t&&"oasis"===t.sdk};
|
|
5
5
|
//# sourceMappingURL=lib.cjs.map
|