@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.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("fs"),require("ethers"),require("@oasisprotocol/sapphire-paratime"),require("bignumber.js"),require("decimal.js"),require("cross-fetch"),require("@oceanprotocol/ddo-js"),require("jsonwebtoken"),require("eciesjs"),require("crypto-js/sha256.js")):"function"==typeof define&&define.amd?define(["exports","fs","ethers","@oasisprotocol/sapphire-paratime","bignumber.js","decimal.js","cross-fetch","@oceanprotocol/ddo-js","jsonwebtoken","eciesjs","crypto-js/sha256.js"],t):t((e||self).lib={},e.fs,e.ethers,e.sapphire,e.BigNumber,e.Decimal,e.crossFetch,e.ddoJs,e.jsonwebtoken,e.eciesjs,e.sha256$3)}(this,function(e,t,n,r,i,s,a,o,u,d,c){function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function p(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 h,f,m=/*#__PURE__*/l(t),y=/*#__PURE__*/p(r),b=/*#__PURE__*/l(i),g=/*#__PURE__*/l(s),v=/*#__PURE__*/l(a),w=/*#__PURE__*/l(u),T=/*#__PURE__*/l(c);e.FileObjectType=void 0,(h=e.FileObjectType||(e.FileObjectType={})).URL="url",h.IPFS="ipfs",h.ARWEAVE="arweave",h.S3="s3",h.FTP="ftp",e.EncryptMethod=void 0,(f=e.EncryptMethod||(e.EncryptMethod={})).AES="AES",f.ECIES="ECIES";var E={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 P(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 S(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 A(t.call(e));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function A(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 A=function(e){this.s=e,this.n=e.next},A.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 A(e)}function C(e){return new P(e,0)}function k(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 I(){return I=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},I.apply(null,arguments)}function D(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,F(e,t)}function M(){M=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 D(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 P=v.prototype=b.prototype=Object.create(w);function x(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 D(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(P,"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(P),e},t.awrap=function(e){return{__await:e}},x(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()})},x(P),d(P,u,"Generator"),d(P,a,function(){return this}),d(P,"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,D.prototype={constructor:D,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 F(e,t){return F=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},F(e,t)}function R(e){return function(){return new _(e.apply(this,arguments))}}function _(e){var t,n;function r(t,n){try{var s=e[t](n),a=s.value,o=a instanceof P;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)}_.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},_.prototype.next=function(e){return this._invoke("next",e)},_.prototype.throw=function(e){return this._invoke("throw",e)},_.prototype.return=function(e){return this._invoke("return",e)};var L,N={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"}};e.LogLevel=void 0,(L=e.LogLevel||(e.LogLevel={}))[L.None=-1]="None",L[L.Error=0]="Error",L[L.Warn=1]="Warn",L[L.Log=2]="Log",L[L.Verbose=3]="Verbose";var O=/*#__PURE__*/function(){function t(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||e.LogLevel.Error}var n=t.prototype;return n.setLevel=function(e){this.logLevel=e},n.bypass=function(){this.dispatch.apply(this,["log",-Infinity].concat([].slice.call(arguments)))},n.debug=function(){this.dispatch.apply(this,["debug",e.LogLevel.Verbose].concat([].slice.call(arguments)))},n.log=function(){this.dispatch.apply(this,["log",e.LogLevel.Log].concat([].slice.call(arguments)))},n.warn=function(){this.dispatch.apply(this,["warn",e.LogLevel.Warn].concat([].slice.call(arguments)))},n.error=function(){this.dispatch.apply(this,["error",e.LogLevel.Error].concat([].slice.call(arguments)))},n.dispatch=function(e,t){var n;this.logLevel>=t&&(n=console)[e].apply(n,[].slice.call(arguments,2))},t}(),B=new O,U={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},j=[I({},U),I({},U,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),I({},U,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),I({},U,{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"}),I({},U,{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"}),I({},U,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),I({},U,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),I({},U,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),I({},U,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),I({},U,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),I({},U,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),I({},U,{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"}),I({},U,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),I({},U,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),I({},U,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),I({},U,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),I({},U,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],q=[23294,23295],$=function(){return process.env.NODE_ENDPOINT||process.env.NODE_URL?{oceanNodeUri:process.env.NODE_ENDPOINT||process.env.NODE_URL}:{}},z=/*#__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=I({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},$())}else if(N[e]){var i=N[e];n=I({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},$())}return n},t.getConfig=function(e,t){var n="string"==typeof e?"network":"chainId",r=j.find(function(t){return t[n]===e});if(!r)return B.error("No config found for given network '"+e+"'"),null;var i=null;try{"undefined"==typeof window&&process.env.ADDRESS_FILE&&(i=JSON.parse(m.default.readFileSync(process.env.ADDRESS_FILE,"utf8")))}catch(e){console.log(e),i=null}var s=this.getAddressesFromEnv(r.network,i);return!s&&q.includes(r.chainId)&&(s=this.getAddressesFromEnv(r.network.replace("sapph","saph"),i)),"sdk"in r&&null!==r.sdk||(r.sdk=q.includes(r.chainId)?"oasis":"evm"),s&&"accessListFactory"in s&&(r.accessListFactory=s.accessListFactory),r=I({},r,s),I({},r,{nodeUri:t?r.nodeUri+"/"+t:r.nodeUri})},e}(),V=[{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"}],G=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)===ee||Number(a)===X)&&Number(o)<Y?Y:Number(a)===te&&Number(o)<J?J:q.includes(Number(a))&&Number(o)<Z?Z:Number(o),maxFeePerGas:(Number(a)===ee||Number(a)===X)&&Number(u)<Y?Y:Number(a)===te&&Number(u)<J?J:q.includes(Number(a))&&Number(u)<Z?Z:Number(u)}}else s={gasPrice:t.gasPrice};return s.gasLimit=BigInt(new b.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 B.error("Send tx error: ",e),null})})})}catch(e){return Promise.reject(e)}},K=function(e,t,r,i){try{var s=function(e){return"0"===e&&(e=18),n.parseUnits(r,e).toString()};return Promise.resolve(i?s(i):Promise.resolve(W(e,t)).then(s))}catch(e){return Promise.reject(e)}},H=function(e,t,r,i){try{var s=function(e){return"0"===e&&(e=18),n.formatUnits(r,e).toString()};return Promise.resolve(i?s(i):Promise.resolve(W(e,t)).then(s))}catch(e){return Promise.reject(e)}},W=function(e,t){try{var r=new n.ethers.Contract(t,V,e);return Promise.resolve(r.decimals())}catch(e){return Promise.reject(e)}},Q=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)}},Y=3e10,J=4e9,Z=1e10,X=137,ee=80001,te=11155111;function ne(e,t){return e}function re(e,t){if(e&&e.logs){var r=e.logs.filter(function(e){return e instanceof n.EventLog&&e.eventName===t})[0];return r}}var ie=/*#__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 z).getConfig(t),this.abi=r||this.getDefaultAbi()}var t=e.prototype;return t.getSignerAccordingSdk=function(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?y.wrap(this.signer):this.signer},t.amountToUnits=function(e,t,n){try{return Promise.resolve(K(this.signer,e,t,n))}catch(e){return Promise.reject(e)}},t.unitsToAmount=function(e,t,n){try{return Promise.resolve(H(this.signer,e,t,n))}catch(e){return Promise.reject(e)}},t.getFairGasPrice=function(){try{var e;return Promise.resolve(Q(this.signer,null==(e=this.config)?void 0:e.gasFeeMultiplier))}catch(e){return Promise.reject(e)}},t.getContract=function(e,t){if(!e)throw new Error("Contract address is required but not provided");return ne(new n.ethers.Contract(e,new n.ethers.Interface(JSON.stringify(t||this.abi)),this.signer))},e}(),se=/*#__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 D(t,e),t}(ie),ae=[{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"}],oe=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}D(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return ae},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(G(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(G(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(G(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(G(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(G(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(G(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 g.default(e).greaterThanOrEqualTo(i.maxBalance)||new g.default(String(r)).greaterThan(i.maxTokens)||!new g.default(i.balance).greaterThanOrEqualTo(r)&&!0!==i.isMinter)})})}catch(e){return Promise.reject(e)}},t}(se),ue=[{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"}],de="0x0000000000000000000000000000000000000000",ce=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}D(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return ue},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=de),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(G(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=de),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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier,r.contract.updateMarketFeeCollector,e,t))})}catch(e){return Promise.reject(e)}},t}(se),le=[{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"}],pe=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}D(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return le},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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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}(se),he=[{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"}],fe={_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:{}},me=[{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"}],ye={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 be(e){var t=e||ye,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 ge=[{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 ve(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var we=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}D(t,e);var r=t.prototype;return r.getDefaultAbi=function(){return ge},r.createNFT=function(e,t){try{var n=this;if(e.templateIndex||(e.templateIndex=1),!e.name||!e.symbol){var r=be(),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,de,de,e.tokenURI,e.transferable,e.owner)).then(function(r){return t?r:ve(function(){var t;return Promise.resolve(G(r,n.getSignerAccordingSdk(),null==(t=n.config)?void 0:t.gasFeeMultiplier,n.contract.deployERC721Contract,e.name,e.symbol,e.templateIndex,de,de,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 re(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===de)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(G(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(G(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(G(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===de)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(G(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(G(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(G(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(G(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(G(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(G(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(G(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 t,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||t,e.symbol||r],u=e.templateIndex;return Promise.resolve(s.amountToUnits(null,e.cap,18)).then(function(t){return Promise.resolve(s.amountToUnits(null,e.feeAmount,o)).then(function(r){return{templateIndex:u,strings:a,addresses:i,uints:[t,r],bytess:e.filesObject?[n.toUtf8Bytes(JSON.stringify(e.filesObject))]:[]}})})},s=this;if(!e.name||!e.symbol){var a=be();t=a.name,r=a.symbol}var o=18,u=function(){if(e.feeToken!==de){var t=ve(function(){return Promise.resolve(W(s.signer,e.feeToken)).then(function(e){o=e})},function(e){B.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=de);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)}},t}(se),Te=[{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 Ee(e,t,n){if(!e.s){if(n instanceof Pe){if(!n.s)return void(n.o=Ee.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(Ee.bind(null,e,t),Ee.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var Pe=/*#__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{Ee(r,1,s(this.v))}catch(e){Ee(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?Ee(r,1,t?t(i):i):n?Ee(r,1,n(i)):Ee(r,2,i)}catch(e){Ee(r,2,e)}},r},e}();function xe(e){return e instanceof Pe&&1&e.s}var Se=function(e,t,r,i){try{var s="number"==typeof r,a=new we(t,e,i);return Promise.resolve(a.getCurrentTokenTemplateCount()).then(function(t){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 Pe,u=Ee.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 Ee(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):Ee(o,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):Ee(o,1,s)}}(function(){return!i&&u<=t},function(){return u++},function(){return Promise.resolve(a.getTokenTemplate(u)).then(function(t){var a=new n.ethers.Contract(t.templateAddress,Te,e);return s?Promise.resolve(a.getId()).then(function(e){if(t.isActive&&e.toString()===r.toString())return i=1,u}):t.isActive&&t.templateAddress===r.toString()?(i=1,u):void 0})});return d&&d.then?d.then(o):o(d)})}catch(e){return Promise.reject(e)}};function Ae(){try{if("undefined"==typeof window&&process.env.ADDRESS_FILE){var e=m.default.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(e)}return N}catch(e){return N}}function Ce(e){try{var t=Ae();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 ke=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}D(t,e);var r=t.prototype;return r.getDefaultAbi=function(){return me},r.createDatatoken=function(e,t,r,i,s,a,o,u,d,c,l,p,h,f,m,y){try{var b=this;return Promise.resolve(b.getNftPermissions(e,t)).then(function(t){if(!0!==t.deployERC20)throw new Error("Caller is not DatatokenDeployer");if(l||(l=1),!d||!c){var g=be();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 t=e.chainId;function g(){var e=v.createERC20,t=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(t.call(e,w,g,[r,i,s,a],[T,E],[])).then(function(e){var t;if(y)return e;var g=[r,i,s,a];h&&(g.push(h.toLowerCase()),g.push(f?f.toLowerCase():de),g.push(m||de));var w=[d,c],T=l,E=v.createERC20,P=null==(t=b.config)?void 0:t.gasFeeMultiplier,x=b.getSignerAccordingSdk();return Promise.resolve(b.amountToUnits(null,u,18)).then(function(t){return Promise.resolve(b.amountToUnits(null,o,18)).then(function(r){return Promise.resolve(G(e,x,P,E,T,w,g,[t,r],p?[n.toUtf8Bytes(p)]:[])).then(function(e){return Promise.resolve(e.wait()).then(function(e){var t=re(e,"TokenCreated");return null==t?void 0:t.args[0]})})})})})})})}var w=Ce(Number(t)),T=function(){if(p)return Promise.resolve(Se(b.signer,w.ERC721Factory,4,Number(t))).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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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(G(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=I({},n,{metadataProofs:n.metadataProofs||[]});return Promise.resolve(s.setMetaDataAndTokenURI.estimateGas(t)).then(function(e){var n;return r?e:Promise.resolve(G(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(G(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(G(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,t,r,i,s){try{var a=this;return Promise.resolve(a.getNftPermissions(e,t)).then(function(t){if(!0!==t.store)throw new Error("User is not ERC20 store updater");var o=a.getContract(e),u=n.keccak256(r),d=n.hexlify(n.toUtf8Bytes(i));return Promise.resolve(o.setNewData.estimateGas(u,d)).then(function(e){var t;return s?e:Promise.resolve(G(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,t){try{var r=this.getContract(e),i=n.keccak256(t);return Promise.resolve(r.getData(i)).then(function(e){return e?n.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)}},t}(ie),Ie=/*#__PURE__*/function(e){function t(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||fe.abi,a.nft=new ke(a.signer,n),a}D(t,e);var r=t.prototype;return r.getDefaultAbi=function(){return he},r.approve=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(s.approve.estimateGas(t,K(null,null,n,18))).then(function(e){var a;return r?e:Promise.resolve(G(e,i.getSignerAccordingSdk(),null==(a=i.config)?void 0:a.gasFeeMultiplier,s.approve,t,K(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=de);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(G(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=de),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(G(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 g.default(e).gte(n))return Promise.resolve(a.mint.estimateGas(r||t,K(null,null,n,18))).then(function(e){var o;return i?e:Promise.resolve(G(e,s.getSignerAccordingSdk(),null==(o=s.config)?void 0:o.gasFeeMultiplier,a.mint,r||t,K(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(G(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(G(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(G(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(G(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(G(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(K(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(G(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:de,consumeMarketFeeToken:de,consumeMarketFeeAmount:"0"}),Promise.resolve(o.startOrder.estimateGas(t,n,r,i)).then(function(e){var u;return s?e:Promise.resolve(G(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(G(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(G(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(G(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,t,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),o=n.hexlify(n.toUtf8Bytes(r));return Promise.resolve(a.setData.estimateGas(o)).then(function(e){var t;return i?e:Promise.resolve(G(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(G(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(G(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(K(t.signer,e.baseTokenAddress,e.maxBaseTokenAmount,e.baseTokenDecimals)).then(function(i){return Promise.resolve(K(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)}},t}(ie),De=[{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"}],Me=/*#__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}D(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return De},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(G(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(G(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(G(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}(Ie),Fe=[{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"}],Re=/*#__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}D(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Fe},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(G(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(G(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(G(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(G(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(G(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier,t.contract.renounceOwnership))})}catch(e){return Promise.reject(e)}},t}(se),_e=[{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"}],Le=/*#__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}D(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return _e},n.deployAccessListContract=function(e,t,n,r,i,s,a){void 0===r&&(r=!1);try{var o=this;if(!e||!t){var u=be();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(G(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 re(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===de)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(G(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier,r.contract.changeTemplateAddress,t))})})}catch(e){return Promise.reject(e)}},t}(se),Ne=[{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 Oe(e,t,n){if(!e.s){if(n instanceof Be){if(!n.s)return void(n.o=Oe.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(Oe.bind(null,e,t),Oe.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var Be=/*#__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{Oe(r,1,s(this.v))}catch(e){Oe(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?Oe(r,1,t?t(i):i):n?Oe(r,1,n(i)):Oe(r,2,i)}catch(e){Oe(r,2,e)}},r},e}(),Ue=/*#__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}D(t,e);var r=t.prototype;return r.getDefaultAbi=function(){return Ne},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,t,r,i,s,a,o){try{var u,d=this;return Promise.resolve(null==(u=d.signer.provider)?void 0:u.getBalance(n.getAddress(t))).then(function(u){if(new b.default(u).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};var c=new Ie(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 b.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,t)).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(n.getAddress(e),n.getAddress(t),(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 b.default(l[0]).isZero()){var t=function(){if(r&&new b.default(n.parseEther(u)).isLessThanOrEqualTo(new b.default(n.parseEther(r)))&&new b.default(n.parseEther(r)).isGreaterThan(new b.default(i)))return Promise.resolve(d.deposit(e,r,o)).then(function(){});var t=function(){if(new b.default(n.parseEther(u)).isLessThanOrEqualTo(new b.default(n.parseEther(i)))){var t=d.deposit;return Promise.resolve(d.unitsToAmount(e,i,o)).then(function(n){return Promise.resolve(t.call(d,e,n,o)).then(function(){})})}return Promise.resolve(d.deposit(e,u,o)).then(function(){})}();return t&&t.then?t.then(function(){}):void 0}();if(t&&t.then)return t.then(function(){})}}();return h&&h.then?h.then(p):p()})})})})})})}var p=function(){if(new b.default(u).isLessThan(new b.default(i)))return Promise.resolve(c.approve(n.getAddress(e),n.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(G(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(G(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 Be&&1&o.s))return void a.then(s,r||(r=Oe.bind(null,n=new Be,2)));a=a.v}n?Oe(n,1,a):n=a}catch(e){Oe(n||(n=new Be),2,e)}var o}(),n}(e,function(n){var r=e[n],u=new b.default(t[n]);return Promise.resolve(i.getUserFunds(o,r)).then(function(e){var i=new b.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(G(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(G(a,s.getSignerAccordingSdk(),null==(o=s.config)?void 0:o.gasFeeMultiplier,s.contract.cancelExpiredLocks,e,t,n,r))})}catch(e){return Promise.reject(e)}},t}(se),je=[{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"}],qe=/*#__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}D(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return je},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}(se),$e=function(e){try{return Promise.resolve(new Promise(function(t){setTimeout(t,e)}))}catch(e){return Promise.reject(e)}},ze=function(e,t){try{var r=n.ethers.solidityPackedKeccak256(["bytes"],[n.ethers.hexlify(n.ethers.toUtf8Bytes(t))]),i=n.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 Ve=Symbol.for("@libp2p/connection"),Ge=Symbol.for("@libp2p/content-routing");class Ke extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class He extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}class We extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}}class Qe extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Ye extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}Error;class Je extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class Ze extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class Xe extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class et extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class tt extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class nt extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class rt extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}}class it extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}class st extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}}class at extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class ot extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class ut extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class dt extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}class ct extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}}class lt extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}}class pt extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}class ht extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}class ft extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}}class mt extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class yt extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class bt extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class gt extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}class vt extends Event{data;constructor(e,t){super("message",t),this.data=e}}class wt extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}}class Tt extends wt{constructor(e,t){super(!0,e,t)}}class Et extends wt{constructor(e,t){super(!1,e,t)}}const Pt=Symbol.for("@libp2p/peer-discovery"),xt=Symbol.for("@libp2p/peer-id");function St(e){return Boolean(e?.[xt])}const At=Symbol.for("@libp2p/peer-routing"),Ct="keep-alive";function kt(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}async function It(...e){const t=[];for(const n of e)kt(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 Dt(...e){const t=[];for(const n of e)kt(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 Mt=Symbol.for("@libp2p/transport");var Ft;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Ft||(Ft={}));class Rt 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 _t=Symbol.for("@libp2p/service-capabilities"),Lt=Symbol.for("@libp2p/service-dependencies");function Nt(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 Ot{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 Bt{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 jt(this,e)}}class Ut{decoders;constructor(e){this.decoders=e}or(e){return jt(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 jt(e,t){return new Ut({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class qt{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 Ot(e,t,n),this.decoder=new Bt(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function $t({name:e,prefix:t,encode:n,decode:r}){return new qt(e,t,n,r)}function zt({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 $t({prefix:t,name:e,encode:r,decode:e=>Nt(i(e))})}function Vt({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 $t({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 Gt=zt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Kt=zt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ht={__proto__:null,base58btc:Gt,base58flickr:Kt};const Wt=Vt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Qt=Vt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yt=Vt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Jt=Vt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zt=Vt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Xt=Vt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),en=Vt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),tn=Vt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nn=Vt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var rn={__proto__:null,base32:Wt,base32upper:Qt,base32pad:Yt,base32padupper:Jt,base32hex:Zt,base32hexupper:Xt,base32hexpad:en,base32hexpadupper:tn,base32z:nn};const sn=zt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),an=zt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var on={__proto__:null,base36:sn,base36upper:an},un=Math.pow(2,31),dn=Math.pow(2,7),cn=Math.pow(2,14),ln=Math.pow(2,21),pn=Math.pow(2,28),hn=Math.pow(2,35),fn=Math.pow(2,42),mn=Math.pow(2,49),yn=Math.pow(2,56),bn=Math.pow(2,63),gn={encode:function e(t,n,r){n=n||[];for(var i=r=r||0;t>=un;)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<dn?1:e<cn?2:e<ln?3:e<pn?4:e<hn?5:e<fn?6:e<mn?7:e<yn?8:e<bn?9:10}},vn=gn;function wn(e,t=0){return[vn.decode(e,t),vn.decode.bytes]}function Tn(e,t,n=0){return vn.encode(e,t,n),t}function En(e){return vn.encodingLength(e)}function Pn(e,t){const n=t.byteLength,r=En(e),i=r+En(n),s=new Uint8Array(i+n);return Tn(e,s,0),Tn(n,s,r),s.set(t,i),new Sn(e,n,t,s)}function xn(e){const t=Nt(e),[n,r]=wn(t),[i,s]=wn(t.subarray(r)),a=t.subarray(r+s);if(a.byteLength!==i)throw new Error("Incorrect length");return new Sn(n,i,a,t)}class Sn{code;size;digest;bytes;constructor(e,t,n,r){this.code=e,this.size=t,this.digest=n,this.bytes=r}}function An(e,t){const{bytes:n,version:r}=e;return 0===r?function(e,t,n){const{prefix:r}=n;if(r!==Gt.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,kn(e),t??Gt.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,kn(e),t??Wt.encoder)}const Cn=new WeakMap;function kn(e){const t=Cn.get(e);if(null==t){const t=new Map;return Cn.set(e,t),t}return t}class In{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!==Dn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Mn)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return In.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=Pn(e,t);return In.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 In.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 An(this,e)}toJSON(){return{"/":An(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 In)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:n,multihash:r,bytes:i}=t;return new In(e,n,r,i??Fn(e,n,r.bytes))}if(!0===t[Rn]){const{version:e,multihash:n,code:r}=t,i=xn(n);return In.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!==Dn)throw new Error(`Version 0 CID must use dag-pb (code: ${Dn}) block encoding`);return new In(e,t,n,n.bytes);case 1:{const r=Fn(e,t,n.bytes);return new In(e,t,n,r)}default:throw new Error("Invalid version")}}static createV0(e){return In.create(0,Dn,e)}static createV1(e,t){return In.create(1,e,t)}static decode(e){const[t,n]=In.decodeFirst(e);if(0!==n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=In.inspectBytes(e),n=t.size-t.multihashSize,r=Nt(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 Sn(t.multihashCode,t.digestSize,i,r);return[0===t.version?In.createV0(s):In.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0;const n=()=>{const[n,r]=wn(e.subarray(t));return t+=r,n};let r=n(),i=Dn;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[Gt.prefix,(t??Gt).decode(`${Gt.prefix}${e}`)];case Gt.prefix:return[Gt.prefix,(t??Gt).decode(e)];case Wt.prefix:return[Wt.prefix,(t??Wt).decode(e)];case sn.prefix:return[sn.prefix,(t??sn).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=In.decode(r);if(0===i.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return kn(i).set(n,e),i}}const Dn=112,Mn=18;function Fn(e,t,n){const r=En(e),i=r+En(t),s=new Uint8Array(i+n.byteLength);return Tn(e,s,0),Tn(t,s,r),s.set(n,i),s}const Rn=Symbol.for("@ipld/js-cid/CID"),_n=Nt,Ln=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 Pn(0,_n(e))};function Nn(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 On(e=0){return new Uint8Array(e)}function Bn(e=0){return new Uint8Array(e)}function Un(e,t){null==t&&(t=e.reduce((e,t)=>e+t.length,0));const n=Bn(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}const jn=Symbol.for("@achingbrain/uint8arraylist");function qn(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 $n(e){return Boolean(e?.[jn])}class zn{bufs;length;[jn]=!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(!$n(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(!$n(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=qn(this.bufs,e);return t.buf[t.index]}set(e,t){const n=qn(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(!$n(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 Un(n,r)}subarray(e,t){const{bufs:n,length:r}=this._subList(e,t);return 1===n.length?n[0]:Un(n,r)}sublist(e,t){const{bufs:n,length:r}=this._subList(e,t),i=new zn;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(!($n(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=Bn(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=On(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=On(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=On(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=Bn(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=On(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=On(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=On(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=On(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=On(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 zn))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Nn(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const n=new zn;return n.bufs=e,null==t&&(t=e.reduce((e,t)=>e+t.byteLength,0)),n.length=t,n}}var Vn={__proto__:null,base10:zt({prefix:"9",name:"base10",alphabet:"0123456789"})},Gn={__proto__:null,base16:Vt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper:Vt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})},Kn={__proto__:null,base2:Vt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})};const Hn=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Wn=Hn.reduce((e,t,n)=>(e[n]=t,e),[]),Qn=Hn.reduce((e,t,n)=>{const r=t.codePointAt(0);if(null==r)throw new Error(`Invalid character: ${t}`);return e[r]=n,e},[]),Yn=$t({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+Wn[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=Qn[e];if(null==r)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}});var Jn={__proto__:null,base256emoji:Yn};const Zn=Vt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Xn=Vt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),er=Vt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),tr=Vt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var nr={__proto__:null,base64:Zn,base64pad:Xn,base64url:er,base64urlpad:tr},rr={__proto__:null,base8:Vt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})},ir={__proto__:null,identity:$t({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 sr({name:e,code:t,encode:n,minDigestLength:r,maxDigestLength:i}){return new ar(e,t,n,r,i)}new TextEncoder,new TextDecoder;class ar{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?or(n,this.code,t?.truncate):n.then(e=>or(e,this.code,t?.truncate))}throw Error("Unknown type, must be binary type")}}function or(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 Pn(t,e)}function ur(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const dr=sr({name:"sha2-256",code:18,encode:ur("SHA-256")});sr({name:"sha2-512",code:19,encode:ur("SHA-512")});const cr={...ir,...Kn,...rr,...Vn,...Gn,...rn,...on,...Ht,...nr,...Jn};function lr(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const pr=lr("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),hr=lr("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{const t=Bn((e=e.substring(1)).length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),fr={utf8:pr,"utf-8":pr,hex:cr.base16,latin1:hr,ascii:hr,binary:hr,...cr};function mr(e,t="utf8"){const n=fr[t];if(null==n)throw new Error(`Unsupported encoding "${t}"`);return n.decoder.decode(`${n.prefix}${e}`)}function yr(e,t="utf8"){const n=fr[t];if(null==n)throw new Error(`Unsupported encoding "${t}"`);return n.encoder.encode(e).substring(1)}const br=parseInt("11111",2),gr=parseInt("10000000",2),vr=parseInt("01111111",2),wr={0:Pr,1:Pr,2:function(e,t){const n=Er(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=Er(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=Er(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=Er(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:Pr,22:Pr,48:Pr};function Tr(e,t={offset:0}){const n=e[t.offset]&br;if(t.offset++,null!=wr[n])return wr[n](e,t);throw new Error("No decoder for tag "+n)}function Er(e,t){let n=0;if((e[t.offset]&gr)===gr){const r=e[t.offset]&vr;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 Pr(e,t){Er(e,t);const n=[];for(;!(t.offset>=e.byteLength);){const r=Tr(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 zn;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 zn(Uint8Array.from([t.byteLength|gr]),t)}function Sr(e){const t=new zn;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new zn(Uint8Array.from([2]),xr(t),t)}function Ar(e){const t=Uint8Array.from([0]),n=new zn(t,e);return new zn(Uint8Array.from([3]),xr(n),n)}function Cr(e,t=48){const n=new zn;for(const t of e)n.append(t);return new zn(Uint8Array.from([t]),xr(n),n)}const kr=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ir=Uint8Array.from([6,5,43,129,4,0,34]),Dr=Uint8Array.from([6,5,43,129,4,0,35]),Mr={ext:!0,kty:"EC",crv:"P-256"},Fr={ext:!0,kty:"EC",crv:"P-384"},Rr={ext:!0,kty:"EC",crv:"P-521"};function _r(e){return function(e){const t=e[1][1][0];let n,r;if(65===t.byteLength)return n=yr(t.subarray(1,33),"base64url"),r=yr(t.subarray(33),"base64url"),new Nr({...Mr,key_ops:["verify"],x:n,y:r});if(97===t.byteLength)return n=yr(t.subarray(1,49),"base64url"),r=yr(t.subarray(49),"base64url"),new Nr({...Fr,key_ops:["verify"],x:n,y:r});if(133===t.byteLength)return n=yr(t.subarray(1,67),"base64url"),r=yr(t.subarray(67),"base64url"),new Nr({...Rr,key_ops:["verify"],x:n,y:r});throw new Qe(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(Tr(e))}function Lr(e){if("P-256"===e)return kr;if("P-384"===e)return Ir;if("P-521"===e)return Dr;throw new Qe(`Invalid curve ${e}`)}class Nr{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return null==this._raw&&(this._raw=(e=this.jwk,Cr([Sr(Uint8Array.from([1])),Cr([Lr(e.crv)],160),Cr([Ar(new zn(Uint8Array.from([4]),mr(e.x??"","base64url"),mr(e.y??"","base64url")))],161)]).subarray())),this._raw;var e}toMultihash(){return Ln(Ro(this))}toCID(){return In.createV1(114,this.toMultihash())}toString(){return Gt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(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 Or(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Br(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Ur(e,t,n=""){const r=Or(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 jr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");Br(e.outputLen),Br(e.blockLen)}function qr(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 $r(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function zr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Vr(e,t){return e<<32-t|e>>>t}const Gr=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Kr=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Hr(e){if(Ur(e),Gr)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Kr[e[n]];return t}function Wr(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Qr(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Gr)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=Wr(e.charCodeAt(i)),s=Wr(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 Yr(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Ur(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 Jr(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 Zr(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 Xr=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function ei(e,t,n){return e&t^~e&n}function ti(e,t,n){return e&t^e&n^t&n}class ni{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=zr(this.buffer)}update(e){qr(this),Ur(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=zr(e);for(;r<=i-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){qr(this),function(e,t){Ur(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,$r(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=zr(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 ri=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ii=/* @__PURE__ */Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),si=/* @__PURE__ */BigInt(2**32-1),ai=/* @__PURE__ */BigInt(32);function oi(e,t=!1){return t?{h:Number(e&si),l:Number(e>>ai&si)}:{h:0|Number(e>>ai&si),l:0|Number(e&si)}}const ui=(e,t,n)=>e>>>n,di=(e,t,n)=>e<<32-n|t>>>n,ci=(e,t,n)=>e>>>n|t<<32-n,li=(e,t,n)=>e<<32-n|t>>>n,pi=(e,t,n)=>e<<64-n|t>>>n-32,hi=(e,t,n)=>e>>>n-32|t<<64-n;function fi(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const mi=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),yi=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,bi=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),gi=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,vi=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),wi=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,Ti=/* @__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]),Ei=/* @__PURE__ */new Uint32Array(64);class Pi extends ni{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)Ei[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ei[e-15],n=Ei[e-2],r=Vr(t,7)^Vr(t,18)^t>>>3,i=Vr(n,17)^Vr(n,19)^n>>>10;Ei[e]=i+Ei[e-7]+r+Ei[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+(Vr(a,6)^Vr(a,11)^Vr(a,25))+ei(a,o,u)+Ti[e]+Ei[e]|0,c=(Vr(n,2)^Vr(n,13)^Vr(n,22))+ti(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(){$r(Ei)}destroy(){this.set(0,0,0,0,0,0,0,0),$r(this.buffer)}}class xi extends Pi{A=0|ri[0];B=0|ri[1];C=0|ri[2];D=0|ri[3];E=0|ri[4];F=0|ri[5];G=0|ri[6];H=0|ri[7];constructor(){super(32)}}const Si=/* @__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}=oi(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))))(),Ai=/* @__PURE__ */(()=>Si[0])(),Ci=/* @__PURE__ */(()=>Si[1])(),ki=/* @__PURE__ */new Uint32Array(80),Ii=/* @__PURE__ */new Uint32Array(80);class Di extends ni{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)ki[n]=e.getUint32(t),Ii[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ki[e-15],n=0|Ii[e-15],r=ci(t,n,1)^ci(t,n,8)^ui(t,0,7),i=li(t,n,1)^li(t,n,8)^di(t,n,7),s=0|ki[e-2],a=0|Ii[e-2],o=ci(s,a,19)^pi(s,a,61)^ui(s,0,6),u=li(s,a,19)^hi(s,a,61)^di(s,a,6),d=bi(i,u,Ii[e-7],Ii[e-16]),c=gi(d,r,o,ki[e-7],ki[e-16]);ki[e]=0|c,Ii[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=ci(c,l,14)^ci(c,l,18)^pi(c,l,41),g=li(c,l,14)^li(c,l,18)^hi(c,l,41),v=c&p^~c&f,w=vi(b,g,l&h^~l&m,Ci[e],Ii[e]),T=wi(w,y,t,v,Ai[e],ki[e]),E=0|w,P=ci(n,r,28)^pi(n,r,34)^pi(n,r,39),x=li(n,r,28)^hi(n,r,34)^hi(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}=fi(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=mi(E,x,A);n=yi(C,T,P,S),r=0|C}({h:n,l:r}=fi(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:s}=fi(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=fi(0|this.Ch,0|this.Cl,0|a,0|o)),({h:u,l:d}=fi(0|this.Dh,0|this.Dl,0|u,0|d)),({h:c,l:l}=fi(0|this.Eh,0|this.El,0|c,0|l)),({h:p,l:h}=fi(0|this.Fh,0|this.Fl,0|p,0|h)),({h:f,l:m}=fi(0|this.Gh,0|this.Gl,0|f,0|m)),({h:y,l:b}=fi(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(){$r(ki,Ii)}destroy(){$r(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Mi extends Di{Ah=0|ii[0];Al=0|ii[1];Bh=0|ii[2];Bl=0|ii[3];Ch=0|ii[4];Cl=0|ii[5];Dh=0|ii[6];Dl=0|ii[7];Eh=0|ii[8];El=0|ii[9];Fh=0|ii[10];Fl=0|ii[11];Gh=0|ii[12];Gl=0|ii[13];Hh=0|ii[14];Hl=0|ii[15];constructor(){super(64)}}const Fi=/* @__PURE__ */Jr(()=>new xi
|
|
2
2
|
/* @__PURE__ */,Xr(1)),Ri=/* @__PURE__ */Jr(()=>new Mi
|
|
3
|
-
/* @__PURE__ */,Xr(3)),_i=/* @__PURE__ */BigInt(0),Li=/* @__PURE__ */BigInt(1);function Ni(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e);return e}function Oi(e){if("bigint"==typeof e){if(!Gi(e))throw new Error("positive bigint expected, got "+e)}else Br(e);return e}function Bi(e){const t=Oi(e).toString(16);return 1&t.length?"0"+t:t}function Ui(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?_i:BigInt("0x"+e)}function ji(e){return Ui(Hr(e))}function qi(e){return Ui(Hr(Vi(Ur(e)).reverse()))}function $i(e,t){Br(t);const n=Qr((e=Oi(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}function zi(e,t){return $i(e,t).reverse()}function Vi(e){return Uint8Array.from(e)}const Gi=e=>"bigint"==typeof e&&_i<=e;function Ki(e,t,n,r){if(!function(e,t,n){return Gi(e)&&Gi(t)&&Gi(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const Hi=e=>(Li<<BigInt(e))-Li;function Wi(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 Qi(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 Yi=/* @__PURE__ */BigInt(0),Ji=/* @__PURE__ */BigInt(1),Zi=/* @__PURE__ */BigInt(2),Xi=/* @__PURE__ */BigInt(3),es=/* @__PURE__ */BigInt(4),ts=/* @__PURE__ */BigInt(5),ns=/* @__PURE__ */BigInt(7),rs=/* @__PURE__ */BigInt(8),is=/* @__PURE__ */BigInt(9),ss=/* @__PURE__ */BigInt(16);function as(e,t){const n=e%t;return n>=Yi?n:t+n}function os(e,t,n){let r=e;for(;t-- >Yi;)r*=r,r%=n;return r}function us(e,t){if(e===Yi)throw new Error("invert: expected non-zero number");if(t<=Yi)throw new Error("invert: expected positive modulus, got "+t);let n=as(e,t),r=t,i=Yi,s=Ji;for(;n!==Yi;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==Ji)throw new Error("invert: does not exist");return as(i,t)}function ds(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function cs(e,t){const n=e.pow(t,(e.ORDER+Ji)/es);return ds(e,n,t),n}function ls(e,t){const n=(e.ORDER-ts)/rs,r=e.mul(t,Zi),i=e.pow(r,n),s=e.mul(t,i),a=e.mul(e.mul(s,Zi),i),o=e.mul(s,e.sub(a,e.ONE));return ds(e,o,t),o}function ps(e){if(e<Xi)throw new Error("sqrt is not defined for small field");let t=e-Ji,n=0;for(;t%Zi===Yi;)t/=Zi,n++;let r=Zi;const i=bs(e);for(;1===ms(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return cs;let s=i.pow(r,t);const a=(t+Ji)/Zi;return function(e,r){if(e.is0(r))return r;if(1!==ms(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=Ji<<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 hs=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function fs(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 ms(e,t){const n=e.pow(t,(e.ORDER-Ji)/Zi),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 ys{ORDER;BITS;BYTES;isLE;ZERO=Yi;ONE=Ji;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Yi)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&&Br(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 as(e,this.ORDER)}isValid(e){if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return Yi<=e&&e<this.ORDER}is0(e){return e===Yi}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Ji)===Ji}neg(e){return as(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return as(e*e,this.ORDER)}add(e,t){return as(e+t,this.ORDER)}sub(e,t){return as(e-t,this.ORDER)}mul(e,t){return as(e*t,this.ORDER)}pow(e,t){return function(e,t,n){if(n<Yi)throw new Error("invalid exponent, negatives unsupported");if(n===Yi)return e.ONE;if(n===Ji)return t;let r=e.ONE,i=t;for(;n>Yi;)n&Ji&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Ji;return r}(this,e,t)}div(e,t){return as(e*us(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 us(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=(t=this.ORDER)%es===Xi?cs:t%rs===ts?ls:t%ss===is?function(e){const t=bs(e),n=ps(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),a=(e+ns)/ss;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 ds(e,h,t),h}}(t):ps(t)),this._sqrt(this,e);var t}toBytes(e){return this.isLE?zi(e,this.BYTES):$i(e,this.BYTES)}fromBytes(e,t=!1){Ur(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?qi(e):ji(e);if(a&&(o=as(o,s)),!t&&!this.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o}invertBatch(e){return fs(this,e)}cmov(e,t,n){return n?t:e}}function bs(e,t={}){return new ys(e,t)}function gs(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 vs(e){const t=gs(e);return t+Math.ceil(t/2)}const ws=/* @__PURE__ */BigInt(0),Ts=/* @__PURE__ */BigInt(1);function Es(e,t){const n=t.negate();return e?n:t}function Ps(e,t){const n=fs(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 Ss(e,t){xs(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Hi(e),maxNumber:n,shiftBy:BigInt(e)}}function As(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+=Ts);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 Cs=new WeakMap,ks=new WeakMap;function Is(e){return ks.get(e)||1}function Ds(e){if(e!==ws)throw new Error("invalid wNAF")}class Ms{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>ws;)t&Ts&&(n=n.add(r)),r=r.double(),t>>=Ts;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Ss(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=Ss(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:a,offset:o,isZero:u,isNeg:d,isNegF:c,offsetF:l}=As(n,e,s);n=a,u?i=i.add(Es(c,t[l])):r=r.add(Es(d,t[o]))}return Ds(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Ss(e,this.bits);for(let e=0;e<i.windows&&n!==ws;e++){const{nextN:s,offset:a,isZero:o,isNeg:u}=As(n,e,i);if(n=s,!o){const e=t[a];r=r.add(u?e.negate():e)}}return Ds(n),r}getPrecomputes(e,t,n){let r=Cs.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Cs.set(t,r))),r}cached(e,t,n){const r=Is(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=Is(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),ks.set(e,t),Cs.delete(e)}hasCache(e){return 1!==Is(e)}}function Fs(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=hs.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",BYTES:"number",BITS:"number"});Wi(e,t)}(t),t}return bs(e,{isLE:n})}function Rs(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>ws))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Fs(t.p,n.Fp,r),s=Fs(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 _s(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}const Ls=BigInt(0),Ns=BigInt(1),Os=BigInt(2),Bs=BigInt(8);function Us(e,t={}){const n=Rs("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a}=s;Wi(t,{},{uvRatio:"function"});const o=Os<<BigInt(8*i.BYTES)-Ns,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:Ls}}});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 Ki("coordinate "+e,t,n?Ns:Ls,o),t}function l(e){if(!(e instanceof f))throw new Error("EdwardsPoint expected")}const p=Qi((e,t)=>{const{X:n,Y:i,Z:s}=e,a=e.is0();null==t&&(t=a?Bs:r.inv(s));const o=u(n*t),d=u(i*t),c=r.mul(s,t);if(a)return{x:Ls,y:Ns};if(c!==Ns)throw new Error("invZ was invalid");return{x:o,y:d}}),h=Qi(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,Ns,u(s.Gx*s.Gy));static ZERO=new f(Ls,Ns,Ns,Ls);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,Ns,u(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:a}=s;e=Vi(Ur(e,n,"point")),Ni(t,"zip215");const c=Vi(e),l=e[n-1];c[n-1]=-129&l;const p=qi(c);Ki("point.y",p,Ls,t?o:r.ORDER);const h=u(p*p),m=u(h-Ns),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&Ns)===Ns,w=!!(128&l);if(!t&&g===Ls&&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(Qr(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(Os),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(Os*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),P=u(v*w),x=u(T*E),S=u(v*E),A=u(w*T);return new f(P,x,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=>Ps(f,e));return Ps(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===Ls?f.ZERO:this.is0()||e===Ns?this:m.unsafe(this,e,e=>Ps(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===Ns?this:this.multiplyUnsafe(a)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Ns?128:0,n}toHex(){return Hr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const m=new Ms(f,i.BITS);return f.BASE.precompute(8),f}const js=BigInt(1),qs=BigInt(2),$s=BigInt(5),zs=BigInt(8),Vs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Gs=/* @__PURE__ */(()=>({p:Vs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:zs,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ks(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Hs=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Ws=/* @__PURE__ */Us(Gs,{uvRatio:function(e,t){const n=Vs,r=as(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Vs,a=e*e%s*e%s,o=os(a,qs,s)*a%s,u=os(o,js,s)*e%s,d=os(u,$s,s)*u%s,c=os(d,t,s)*d%s,l=os(c,n,s)*c%s,p=os(l,r,s)*l%s,h=os(p,i,s)*p%s,f=os(h,i,s)*p%s,m=os(f,t,s)*d%s;return{pow_p_5_8:os(m,qs,s)*e%s,b2:a}}(e*as(r*r*t,n)).pow_p_5_8;let s=as(e*r*i,n);const a=as(t*s*s,n),o=s,u=as(s*Hs,n),d=a===e,c=a===as(-e,n),l=a===as(-e*Hs,n);return d&&(s=o),(c||l)&&(s=u),(as(s,n)&Ji)===Ji&&(s=as(-s,n)),{isValid:d||c,value:s}}});function Qs(e){return function(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Wi(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||Zr,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Ni(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function c(e){return a.create(qi(e))}function l(e){const{head:n,prefix:r,scalar:s}=function(e){const n=y.secretKey;Ur(e,y.secretKey,"secretKey");const r=Ur(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=Yr(...n);return c(t(d(i,Ur(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 Ur(e,y.seed,"seed")}const g={getExtendedPublicKey:l,randomSecretKey:b,isValidSecretKey:function(e){return Or(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(Ns+n,Ns-n):s.div(n-Ns,n+Ns);return s.toBytes(a)},toMontgomerySecret(e){const n=y.secretKey;Ur(e,n);const r=t(e.subarray(0,n));return u(r).subarray(0,n)}};return Object.freeze({keygen:_s(b,p),getPublicKey:p,sign:function(e,t,n={}){e=Ur(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 Ur(Yr(c,a.toBytes(f)),y.signature,"result")},verify:function(t,n,s,a=f){const{context:o,zip215:u}=a,d=y.signature;t=Ur(t,d,"signature"),n=Ur(n,void 0,"message"),s=Ur(s,y.publicKey,"publicKey"),void 0!==u&&Ni(u,"zip215"),r&&(n=r(n));const c=d/2,l=t.subarray(0,c),p=qi(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})}(Ws,Ri,Object.assign({adjustScalarBytes:Ks},e))}const Ys=/* @__PURE__ */Qs({});Error;class Js extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Zs extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var Xs={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Zs("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 ea;const ta=(async()=>{try{return await Xs.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function na(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class ra{type="Ed25519";raw;constructor(e){this.raw=aa(e,32)}toMultihash(){return Ln(Ro(this))}toCID(){return In.createV1(114,this.toMultihash())}toString(){return Gt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();const r=async function(e,t,n){return null==ea&&(ea=await ta),ea?async function(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await Xs.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Xs.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 Ys.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}(e,t,n)}(this.raw,t,e);return na(r)?r.then(e=>(n?.signal?.throwIfAborted(),e)):r}}class ia{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=aa(e,64),this.publicKey=new ra(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const n=async function(e,t){return null==ea&&(ea=await ta),ea?async function(e,t){let n;n=64===e.length?e.subarray(0,32):e;const r={crv:"Ed25519",kty:"OKP",x:yr(e.subarray(32),"base64url"),d:yr(n,"base64url"),ext:!0,key_ops:["sign"]},i=await Xs.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await Xs.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 Ys.sign(t instanceof Uint8Array?t:t.subarray(),n)}(e,t)}(this.raw,e);return na(n)?n.then(e=>(t?.signal?.throwIfAborted(),e)):(t?.signal?.throwIfAborted(),n)}}function sa(e){return e=aa(e,32),new ra(e)}function aa(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Qe(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const oa=Math.pow(2,7),ua=Math.pow(2,14),da=Math.pow(2,21),ca=Math.pow(2,28),la=Math.pow(2,35),pa=Math.pow(2,42),ha=Math.pow(2,49),fa=128,ma=127;function ya(e){if(e<oa)return 1;if(e<ua)return 2;if(e<da)return 3;if(e<ca)return 4;if(e<la)return 5;if(e<pa)return 6;if(e<ha)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ba(e,t,n=0){switch(ya(e)){case 8:t[n++]=255&e|fa,e/=128;case 7:t[n++]=255&e|fa,e/=128;case 6:t[n++]=255&e|fa,e/=128;case 5:t[n++]=255&e|fa,e/=128;case 4:t[n++]=255&e|fa,e>>>=7;case 3:t[n++]=255&e|fa,e>>>=7;case 2:t[n++]=255&e|fa,e>>>=7;case 1:t[n++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function ga(e,t){let n=e[t],r=0;if(r+=n&ma,n<fa)return r;if(n=e[t+1],r+=(n&ma)<<7,n<fa)return r;if(n=e[t+2],r+=(n&ma)<<14,n<fa)return r;if(n=e[t+3],r+=(n&ma)<<21,n<fa)return r;if(n=e[t+4],r+=(n&ma)*ca,n<fa)return r;if(n=e[t+5],r+=(n&ma)*la,n<fa)return r;if(n=e[t+6],r+=(n&ma)*pa,n<fa)return r;if(n=e[t+7],r+=(n&ma)*ha,n<fa)return r;throw new RangeError("Could not decode varint")}function va(e,t,n=0){return null==t&&(t=Bn(ya(e))),t instanceof Uint8Array?ba(e,t,n):function(e,t,n=0){switch(ya(e)){case 8:t.set(n++,255&e|fa),e/=128;case 7:t.set(n++,255&e|fa),e/=128;case 6:t.set(n++,255&e|fa),e/=128;case 5:t.set(n++,255&e|fa),e/=128;case 4:t.set(n++,255&e|fa),e>>>=7;case 3:t.set(n++,255&e|fa),e>>>=7;case 2:t.set(n++,255&e|fa),e>>>=7;case 1:t.set(n++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,n)}function wa(e,t=0){return e instanceof Uint8Array?ga(e,t):function(e,t){let n=e.get(t),r=0;if(r+=n&ma,n<fa)return r;if(n=e.get(t+1),r+=(n&ma)<<7,n<fa)return r;if(n=e.get(t+2),r+=(n&ma)<<14,n<fa)return r;if(n=e.get(t+3),r+=(n&ma)<<21,n<fa)return r;if(n=e.get(t+4),r+=(n&ma)*ca,n<fa)return r;if(n=e.get(t+5),r+=(n&ma)*la,n<fa)return r;if(n=e.get(t+6),r+=(n&ma)*pa,n<fa)return r;if(n=e.get(t+7),r+=(n&ma)*ha,n<fa)return r;throw new RangeError("Could not decode varint")}(e,t)}const Ta=new Float32Array([-0]),Ea=new Uint8Array(Ta.buffer);function Pa(e,t,n){Ta[0]=e,t[n]=Ea[0],t[n+1]=Ea[1],t[n+2]=Ea[2],t[n+3]=Ea[3]}const xa=new Float64Array([-0]),Sa=new Uint8Array(xa.buffer);function Aa(e,t,n){xa[0]=e,t[n]=Sa[0],t[n+1]=Sa[1],t[n+2]=Sa[2],t[n+3]=Sa[3],t[n+4]=Sa[4],t[n+5]=Sa[5],t[n+6]=Sa[6],t[n+7]=Sa[7]}const Ca=BigInt(Number.MAX_SAFE_INTEGER),ka=BigInt(Number.MIN_SAFE_INTEGER);class Ia{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 Da;if(e<Ca&&e>ka)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>Ma&&(r=0n,++n>Ma&&(n=0n))),new Ia(Number(r),Number(n))}static fromNumber(e){if(0===e)return Da;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 Ia(n,r)}static from(e){return"number"==typeof e?Ia.fromNumber(e):"bigint"==typeof e?Ia.fromBigInt(e):"string"==typeof e?Ia.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Ia(e.low>>>0,e.high>>>0):Da}}const Da=new Ia(0,0);Da.toBigInt=function(){return 0n},Da.zzEncode=Da.zzDecode=function(){return this},Da.length=function(){return 1};const Ma=4294967296n;function Fa(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 Ra(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function _a(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class La{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,Ra(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 Ra(this,4);return _a(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ra(this,4);return 0|_a(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Ra(this,4);const e=(Ea[0]=(t=this.buf)[n=this.pos],Ea[1]=t[n+1],Ea[2]=t[n+2],Ea[3]=t[n+3],Ta[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ra(this,4);const e=(Sa[0]=(t=this.buf)[n=this.pos],Sa[1]=t[n+1],Sa[2]=t[n+2],Sa[3]=t[n+3],Sa[4]=t[n+4],Sa[5]=t[n+5],Sa[6]=t[n+6],Sa[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 Ra(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 Ra(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Ra(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 Ia(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Ra(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 Ra(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 Ra(this,8);const e=_a(this.buf,this.pos+=4),t=_a(this.buf,this.pos+=4);return new Ia(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=ga(this.buf,this.pos);return this.pos+=ya(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 Na(e){return new La(e instanceof Uint8Array?e:e.subarray())}function Oa(e,t,n){const r=Na(e);return t.decode(r,void 0,n)}class Ba{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Ua(){}class ja{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const qa=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Bn(r);n+r>e&&(t=Bn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class $a{len;head;tail;states;constructor(){this.len=0,this.head=new Ba(Ua,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ba(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ga((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ka,10,Ia.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Ia.fromBigInt(e);return this._push(Ka,t.length(),t)}uint64Number(e){return this._push(ba,ya(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=Ia.fromBigInt(e).zzEncode();return this._push(Ka,t.length(),t)}sint64Number(e){const t=Ia.fromNumber(e).zzEncode();return this._push(Ka,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(za,1,e?1:0)}fixed32(e){return this._push(Ha,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Ia.fromBigInt(e);return this._push(Ha,4,t.lo)._push(Ha,4,t.hi)}fixed64Number(e){const t=Ia.fromNumber(e);return this._push(Ha,4,t.lo)._push(Ha,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(Pa,4,e)}double(e){return this._push(Aa,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(za,1,0):this.uint32(t)._push(Wa,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(Fa,t,e):this._push(za,1,0)}fork(){return this.states=new ja(this),this.head=this.tail=new Ba(Ua,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 Ba(Ua,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?Bn(n):qa(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function za(e,t,n){t[n]=255&e}function Va(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class Ga extends Ba{next;constructor(e,t){super(Va,e,t),this.next=void 0}}function Ka(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 Ha(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 Wa(e,t,n){t.set(e,n)}function Qa(e,t,n){t.set(e,n)}function Ya(e,t,n){e.length<40?Fa(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(mr(e),n)}function Ja(e,t){const n=new $a;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*Za(e,t,n){const r=Na(e);yield*t.stream(r,void 0,"$",n)}function Xa(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function eo(e,t,n){return Xa("message",2,e,t,n)}var to,no,ro,io;function so(e){if(isNaN(e)||e<=0)throw new Qe("random bytes length must be a Number bigger than 0");return Zr(e)}null!=globalThis.Buffer&&($a.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Qa,t,e),this},$a.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Ya,t,e),this}),function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(to||(to={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(no||(no={})),function(e){e.codec=()=>function(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Xa("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)})}(no)}(to||(to={})),function(e){let t;e.codec=()=>(null==t&&(t=eo((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),to.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=to.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:to.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 Ja(t,e.codec())},e.decode=function(t,n){return Oa(t,e.codec(),n)},e.stream=function(t,n){return Za(t,e.codec(),n)}}(ro||(ro={})),function(e){let t;e.codec=()=>(null==t&&(t=eo((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),to.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=to.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:to.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 Ja(t,e.codec())},e.decode=function(t,n){return Oa(t,e.codec(),n)},e.stream=function(t,n){return Za(t,e.codec(),n)}}(io||(io={}));class ao{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 Qe("JWK was missing components");return Cr([oo,Ar(Cr([Sr(mr(e.n,"base64url")),Sr(mr(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return In.createV1(114,this._multihash)}toString(){return Gt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(this.raw,e.raw)}verify(e,t,n){return async function(e,t,n,r){const i=await Xs.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Xs.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 oo=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class uo{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(jr(e),Ur(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),$r(r)}update(e){return qr(this),this.iHash.update(e),this}digestInto(e){qr(this),Ur(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 co=(e,t,n)=>new uo(e,t).update(n).digest();co.create=(e,t)=>new uo(e,t);const lo=(e,t)=>(e+(e>=0?t:-t)/go)/t;function po(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function ho(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Ni(n.lowS,"lowS"),Ni(n.prehash,"prehash"),void 0!==n.format&&po(n.format),n}class fo extends Error{constructor(e=""){super(e)}}const mo={Err:fo,_tlv:{encode:(e,t)=>{const{Err:n}=mo;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=Bi(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Bi(i.length/2|128):"";return Bi(e)+s+i+t},decode(e,t){const{Err:n}=mo;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}=mo;if(e<yo)throw new t("integer: negative integers are not allowed");let n=Bi(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}=mo;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 ji(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=mo,i=Ur(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}=mo,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s));return t.encode(48,r+i)}},yo=BigInt(0),bo=BigInt(1),go=BigInt(2),vo=BigInt(3),wo=BigInt(4);function To(e,t={}){const n=Rs("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a,n:o}=s;Wi(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=Po(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 Ni(n,"isCompressed"),n?(c(),Yr(Eo(!r.isOdd(s)),a)):Yr(Uint8Array.of(4),a,r.toBytes(s))},p=t.fromBytes||function(e){Ur(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,vo),wo),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 P))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=lo(a*e,n),u=lo(-i*e,n);let d=e-o*r-u*s,c=-o*i-u*a;const l=d<yo,p=c<yo;l&&(d=-d),p&&(c=-c);const h=Hi(Math.ceil(function(e){let t;for(t=0;e>_i;e>>=Li,t+=1);return t}(n)/2))+bo;if(d<yo||d>=h||c<yo||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=Qi((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=Qi(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 P(r.mul(n.X,e),n.Y,n.Z),t=Es(i,t),n=Es(s,n),t.add(n)}class P{static BASE=new P(s.Gx,s.Gy,r.ONE);static ZERO=new P(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 P)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?P.ZERO:new P(t,n,r.ONE)}static fromBytes(e){const t=P.fromAffine(p(Ur(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return P.fromBytes(Qr(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(vo),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 P(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,vo),{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 P(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,vo);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 P(d,c,l)}subtract(e){return this.add(e.negate())}is0(){return this.equals(P.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=>Ps(P,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 Ps(P,[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===yo||r.is0())return P.ZERO;if(e===bo)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>ws||r>ws;)n&Ts&&(s=s.add(i)),r&Ts&&(a=a.add(i)),i=i.double(),n>>=Ts,r>>=Ts;return{p1:s,p2:a}}(P,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===bo||(e?e(P,this):S.unsafe(this,o).is0())}clearCofactor(){const{clearCofactor:e}=t;return a===bo?this:e?e(P,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return Ni(e,"isCompressed"),this.assertValidity(),l(P,this,e)}toHex(e=!0){return Hr(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const x=i.BITS,S=new Ms(P,t.endo?Math.ceil(x/2):x);return P.BASE.precompute(8),P}function Eo(e){return Uint8Array.of(e?2:3)}function Po(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={}){jr(t),Wi(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=(n=Object.assign({},n)).randomBytes||Zr,i=n.hmac||((e,n)=>co(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||Zr,i=Object.assign(Po(e.Fp,n),{seed:vs(n.ORDER)});function s(e=r(i.seed)){return function(e,t,n=!1){Ur(e);const r=e.length,i=gs(t),s=vs(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const a=as(n?qi(e):ji(e),t-Ji)+Ji;return n?zi(a,i):$i(a,i)}(Ur(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(!Or(e))return;if("_lengths"in n&&n._lengths||t===r)return;const a=Ur(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=_s(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*go<s.ORDER;function y(e){return e>o>>bo}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){po(t);const n=h.signature;return Ur(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}=mo.toSig(Ur(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(Qr(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(Yr(Eo(!(1&i)),d)),l=a.inv(u),p=E(Ur(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(po(e),"der"===e)return Qr(mo.hexFromSig(this));const{r:t,s:n}=this,r=a.toBytes(t),i=a.toBytes(n);return"recovered"===e?(g(),Yr(Uint8Array.of(this.assertRecovery()),r,i)):Yr(r,i)}toHex(e){return Hr(this.toBytes(e))}}const T=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=ji(e),n=8*e.length-u;return n>0?t>>BigInt(n):t},E=n.bits2int_modN||function(e){return a.create(T(e))},P=Hi(u);function x(e){return Ki("num < 2^"+u,e,yo,P),a.toBytes(e)}function S(e,n){return Ur(e,void 0,"message"),n?Ur(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}=ho(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=[x(c),x(d)];if(null!=u&&!1!==u){const e=!0===u?r(h.secretKey):u;l.push(Ur(e,void 0,"extraEntropy"))}const p=Yr(...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===yo)return;const u=a.create(r*a.create(b+o*c));if(u===yo)return;let d=(i.x===o?0:2)|Number(i.y&bo),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(Br(e,"hashLen"),Br(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,Yr(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 Yr(...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}=ho(i,f);if(r=Ur(r,void 0,"publicKey"),n=S(n,o),!Or(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}=ho(n,f);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}const So={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ao={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Co=/* @__PURE__ */BigInt(2),ko=bs(So.p,{sqrt:function(e){const t=So.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=os(c,n,t)*c%t,p=os(l,n,t)*c%t,h=os(p,Co,t)*d%t,f=os(h,i,t)*h%t,m=os(f,s,t)*f%t,y=os(m,o,t)*m%t,b=os(y,u,t)*y%t,g=os(b,o,t)*m%t,v=os(g,n,t)*c%t,w=os(v,a,t)*f%t,T=os(w,r,t)*d%t,E=os(T,Co,t);if(!ko.eql(ko.sqr(E),e))throw new Error("Cannot find square root");return E}}),Io=/* @__PURE__ */xo(/* @__PURE__ */To(So,{Fp:ko,endo:Ao}),Fi);class Do{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return Io.Point.fromBytes(e),e}catch(e){throw new Ye(String(e))}}(e),this.raw=function(e){return Io.Point.fromBytes(e).toBytes()}(this._key)}toMultihash(){return Ln(Ro(this))}toCID(){return In.createV1(114,this.toMultihash())}toString(){return Gt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(this.raw,e.raw)}verify(e,t,n){return function(e,t,n,r){const i=dr.digest(n instanceof Uint8Array?n:n.subarray());if(na(i))return i.then(({digest:n})=>(r?.signal?.throwIfAborted(),Io.verify(t,n,e,{prehash:!1,format:"der"}))).catch(e=>{if("AbortError"===e.name)throw e;throw new Js(String(e))});try{return r?.signal?.throwIfAborted(),Io.verify(t,i.digest,e,{prehash:!1,format:"der"})}catch(e){throw new Js(String(e))}}(this._key,t,e,n)}}function Mo(e){return new Do(e)}function Fo(e,t){const{Type:n,Data:r}=ro.decode(e),i=r??new Uint8Array;switch(n){case to.RSA:return function(e,t){if(e.byteLength>=1062)throw new Ye("Key size is too large");return function(e,t,n){const r=function(e){const t=Tr(e[1],{offset:0});return{kty:"RSA",n:yr(t[0],"base64url"),e:yr(t[1],"base64url")}}(e);return null==n&&(n=Pn(18,Fi(ro.encode({Type:to.RSA,Data:t})))),new ao(r,n)}(Tr(e,{offset:0}),e,t)}(i,t);case to.Ed25519:return sa(i);case to.secp256k1:return Mo(i);case to.ECDSA:return _r(i);default:throw new gt}}function Ro(e){return ro.encode({Type:to[e.type],Data:e.raw})}const _o=Symbol.for("nodejs.util.inspect.custom");class Lo{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=Gt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return In.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Nn(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Nn(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[_o](){return`PeerId(${this.toString()})`}}class No extends Lo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Oo extends Lo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Bo extends Lo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class Uo{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ln(mr(this.url))}[_o](){return`PeerId(${this.url})`}[xt]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return In.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=yr(e)),e.toString()===this.toString())}}function jo(e,t){let n;if("1"===e.charAt(0)||"Q"===e.charAt(0))n=xn(Gt.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return zo(In.parse(e));if(null==t)throw new Qe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');n=xn(t.decode(e))}return $o(n)}function qo(e){if("Ed25519"===e.type)return new Oo({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Bo({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new No({multihash:e.toCID().multihash,publicKey:e});throw new gt}function $o(e){if(function(e){return e.code===dr.code}(e))return new No({multihash:e});if(function(e){return 0===e.code}(e))try{const t=function(e){const{Type:t,Data:n}=ro.decode(e.digest),r=n??new Uint8Array;switch(t){case to.Ed25519:return sa(r);case to.secp256k1:return Mo(r);case to.ECDSA:return _r(r);default:throw new gt}}(e);if("Ed25519"===t.type)return new Oo({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Bo({multihash:e,publicKey:t})}catch(t){const n=yr(e.digest);return new Uo(new URL(n))}throw new ot("Supplied PeerID Multihash is invalid")}function zo(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new at("Supplied PeerID CID is invalid");if(2336===e.code){const t=yr(e.multihash.digest);return new Uo(new URL(t))}return $o(e.multihash)}class Vo extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Go extends Error{static name="ValidationError";name="ValidationError"}class Ko extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Ho extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const Wo=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 Qo(e){if(!(e.length>15))return Wo.new(e).parseWith(()=>Wo.readIPv4Addr())}function Yo(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Wo.new(e).parseWith(()=>Wo.readIPv6Addr())}function Jo(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const n=Wo.new(e).parseWith(()=>Wo.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 Zo(e){return Boolean(Qo(e))}function Xo(e){return Boolean(Yo(e))}const eu=41,tu=421,nu=448,ru=449,iu=466,su=281,au=290;function ou(e){return t=>yr(t,e)}function uu(e){return t=>mr(t,e)}function du(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function cu(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function lu(e){const t=e.subarray(0,e.length-2),n=e.subarray(e.length-2);return`${yr(t,"base32")}:${du(n)}`}const pu=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 Vo("Invalid byte value in IP address");t[n]=r}),t},hu=Object.values(cr).map(e=>e.decoder),fu=function(){let e=hu[0].or(hu[1]);return hu.slice(2).forEach(t=>e=e.or(t)),e}(),mu=function(...e){return t=>{for(const n of e)n(t)}}(function(e){if(parseInt(e).toString()!==e)throw new Go("Value must be an integer")},function(e){if(e<0)throw new Go("Value must be a positive integer, or zero")},e=>{if(e>65535)throw new Go("Value must be smaller than or equal to 65535")}),yu=-1,bu=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 Ho(`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)}))}},gu=[{code:4,name:"ip4",size:32,valueToBytes:pu,bytesToValue:function(e){if(4!==e.byteLength)throw new Vo("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(!Zo(e))throw new Go(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:cu,bytesToValue:du,validate:mu},{code:273,name:"udp",size:16,valueToBytes:cu,bytesToValue:du,validate:mu},{code:33,name:"dccp",size:16,valueToBytes:cu,bytesToValue:du,validate:mu},{code:eu,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;Zo(n[r])&&(e=pu(n[r]),n[r]=yr(e.subarray(0,2),"base16")),null!=e&&++r<8&&n.splice(r,0,yr(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 Vo("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 Vo("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 Vo(`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 Vo(`Invalid IPv6 address "${e}"`)}},validate:e=>{if(!Xo(e))throw new Go(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:yu},{code:43,name:"ipcidr",size:8,bytesToValue:ou("base10"),valueToBytes:uu("base10")},{code:53,name:"dns",size:yu},{code:54,name:"dns4",size:yu},{code:55,name:"dns6",size:yu},{code:56,name:"dnsaddr",size:yu},{code:132,name:"sctp",size:16,valueToBytes:cu,bytesToValue:du,validate:mu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:yu,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:tu,name:"p2p",aliases:["ipfs"],size:yu,bytesToValue:ou("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?uu("base58btc")(e):In.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:lu,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=mr(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=cu(r);return Un([n,i],n.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:lu,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=Wt.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=cu(r);return Un([n,i],n.length+i.length)}},{code:446,name:"garlic64",size:yu},{code:447,name:"garlic32",size:yu},{code:nu,name:"tls"},{code:ru,name:"sni",size:yu},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:iu,name:"certhash",size:yu,bytesToValue:(vu=er,e=>vu.encoder.encode(e)),valueToBytes:function(e){return fu.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:yu,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:su,name:"webrtc"},{code:au,name:"p2p-circuit"},{code:777,name:"memory",size:yu}];var vu;function wu(e,t,n){return null==e.size||0===e.size?0:e.size>0?e.size/8:wa(t,n)}gu.forEach(e=>{bu.addProtocol(e)});const Tu=Symbol.for("nodejs.util.inspect.custom"),Eu=Symbol.for("@multiformats/multiaddr");class Pu{[Eu]=!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=wa(e,n),i=bu.getProtocol(r),s=ya(r),a=wu(i,e,n+s);let o=0;a>0&&i.size===yu&&(o=ya(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)??yr(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 Vo('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=bu.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 Vo(`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 Vo(`Component ${i} was missing value`);s.value=e.stringToValue?.(r)??r}t.push(s),r="",i="",n="protocol"}}}if(""!==i&&""!==r)throw new Vo("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new Vo("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach(e=>{const t=bu.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=bu.getProtocol(r.code),t=ya(r.code);let n,i=0,s=0;null!=r.value&&(n=e.valueToBytes?.(r.value)??mr(r.value),i=n.byteLength,e.size===yu&&(s=ya(i)));const a=new Uint8Array(t+s+i);let o=0;ba(r.code,a,o),o+=t,null!=n&&(e.size===yu&&(ba(i,a,o),o+=s),a.set(n,o)),r.bytes=a}n.push(r.bytes),t+=r.bytes.byteLength}return Un(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=bu.getProtocol(e.code);if(null==t)throw new Vo(`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 Pu(e);return new Pu([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),n=this.toString(),r=n.lastIndexOf(t);if(r<0)throw new Ko(`Address ${this.toString()} does not contain subaddress: ${t}`);return new Pu(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 Pu(this.#t.slice(0,t),{validate:!1})}equals(e){return Nn(this.bytes,e.bytes)}[Tu](){return`Multiaddr(${this.toString()})`}}function xu(e){return Boolean(e?.[Eu])}function Su(e){return new Pu(e)}function Au(e){return Array.from(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function Cu(e){for(var t,n=e.reduce(function(e,t){return e+t.length},0),r=new Uint8Array(n),i=0,s=k(e);!(t=s()).done;){var a=t.value;r.set(a,i),i+=a.length}return r}function ku(e,t){var n=d.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"+Au(t)}(e)),r=d.encrypt(n.toHex(),(new TextEncoder).encode(t));return Au(new Uint8Array(r))}function Iu(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Du=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getConsumerAddress=function(e){return hT(e)},t.getSignature=function(e,t,n){return pT(e,t,n)},t.getAuthorization=function(e){return fT(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=k(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(Iu(function(){return Promise.resolve(n.getData(e,t)).then(function(e){return Promise.resolve(e.json())})},function(e){throw B.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?Iu(function(){return Promise.resolve(v.default(r.urlPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:E.STATUS}),signal:t})).then(function(e){return null!=e&&e.ok?e.json():null})},function(e){return B.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),Iu(function(){return Promise.resolve(v.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 B.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?Iu(function(){return Promise.resolve(v.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 B.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,E.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,Iu(function(){return Promise.resolve(v.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 B.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 B.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=k(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=Iu(function(){return Promise.resolve(v.default(c,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json"},signal:i})).then(function(e){o=e})},function(e){throw B.error("File info call failed: "),B.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 B.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=k(e);!(n=r()).done;)u.push(n.value);return t=1,u})}();return r&&r.then?r.then(n):n(r)}var a,o=I({},e,{checksum:n}),u=[],d=i.getEndpointURL(t,"fileinfo")?i.getEndpointURL(t,"fileinfo").urlPath:null;if(!d)return null;var c=Iu(function(){return Promise.resolve(v.default(d,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){a=e})},function(e){throw B.error("File info call failed: "),B.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 B.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=Iu(function(){return Promise.resolve(v.default(a,{method:"GET",headers:{"Content-Type":"application/json"},signal:t})).then(function(e){s=e})},function(e){throw B.error("Fetch compute env failed: "),B.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 B.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=Iu(function(){return Promise.resolve(v.default(p,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})).then(function(e){l=e})},function(e){throw B.error("Provider initialized failed: "),B.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 B.error("Initialize compute failed: ",e.status,e.statusText,t),B.error("Payload was:",JSON.stringify(g)),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=Iu(function(){return Promise.resolve(v.default(b,{method:"POST",body:JSON.stringify(g),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 B.error("Initialize compute failed: "),B.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&&(g.output=ku(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 g={datasets:e,algorithm:t,environment:n,payment:{chainId:u,token:r,resources:o},maxJobDuration:i,consumerAddress:a};d&&(g.policyServer=d),l&&(g.queueMaxWaitTime=l);var w=function(){if(p)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(g.encryptedDockerRegistryAuth=ku(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,E.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(g){var w=y.getEndpointURL(g,"computeStart")?y.getEndpointURL(g,"computeStart").urlPath:null;return w?Promise.resolve(y.getConsumerAddress(t)).then(function(T){return Promise.resolve(y.getNonce(e,T,h,b,g)).then(function(b){var g=(b+1).toString();return Promise.resolve(y.getSignature(t,g,E.COMPUTE_START)).then(function(b){function E(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw B.error("Compute start failed: ",e.status,e.statusText,t),B.error("Payload was:",P),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&&(P.policyServer=p),f&&(P.queueMaxWaitTime=f);var r=Iu(function(){return Promise.resolve(v.default(w,{method:"POST",body:JSON.stringify(P),headers:{"Content-Type":"application/json",Authorization:y.getAuthorization(t)},signal:h})).then(function(t){e=t})},function(e){throw B.error("Compute start failed:"),B.error(e),B.error("Payload was:",P),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}o&&(P.resources=o),d&&(P.metadata=d),c&&(P.additionalViewers=c);var r=function(){if(l)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(P.output=ku(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var P=Object();P.consumerAddress=T,P.signature=b,P.nonce=g,P.environment=n,P.maxJobDuration=s,P.resources=o,P.dataset=r[0],P.datasets=r,P.algorithm=i,P.chainId=u,P.payment={chainId:u,token:a,maxJobDuration:s,resources:o};var x=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(P.encryptedDockerRegistryAuth=ku(e,JSON.stringify(m)))})}();return x&&x.then?x.then(E):E()})})}):(B.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,E.FREE_COMPUTE_START)).then(function(f){function g(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw B.error("Compute start failed: ",e.status,e.statusText,t),B.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=Iu(function(){return Promise.resolve(v.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 B.error("Compute start failed:"),B.error(e),B.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=ku(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=ku(e,JSON.stringify(p)))})}();return T&&T.then?T.then(g):g()})})}):(B.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=B.error,s=e.statusText,a=e.status;return Promise.resolve(e.json()).then(function(e){return i.call(B,"computeStreamableLogs failed: ",a,s,e),null})}var s=Iu(function(){return Promise.resolve(v.default(u+c,{method:"GET",headers:{"Content-Type":"application/json",Authorization:i.getAuthorization(t)},signal:r})).then(function(t){e=t})},function(e){throw B.error("computeStreamableLogs failed:"),B.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,E.COMPUTE_GET_STREAMABLE_LOGS)).then(function(e){c+="&signature="+e,c+="&nonce="+o})}();return l&&l.then?l.then(a):a()})}):(B.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,E.COMPUTE_STOP)).then(function(t){function u(e){var t;function n(e){return t?e:Promise.resolve(p.json()).then(function(e){throw B.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=Iu(function(){return Promise.resolve(v.default(d+"?"+h,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:s.getAuthorization(n)},signal:i})).then(function(e){p=e})},function(e){throw B.error("Compute stop failed:"),B.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(hT(t)).then(function(a){var o=fT(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 B.error("Get compute status failed:",u.status,u.statusText,e),new Error(JSON.stringify(e))})}B.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=Iu(function(){return Promise.resolve(v.default(d+c,{method:"GET",headers:{"Content-Type":"application/json",Authorization:o},signal:i})).then(function(e){u=e})},function(e){throw B.error("Get compute status failed"),B.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,E.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(v.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,E.CREATE_AUTH_TOKEN)).then(function(e){return Iu(function(){return Promise.resolve(v.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 B.error("Generate auth token failed:"),B.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(ze(e,s+i)).then(function(e){return Iu(function(){return Promise.resolve(v.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 B.error("Generate auth token failed:"),B.error(e),new Error("HTTP request failed calling Provider")})})})})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){try{return Promise.resolve(Iu(function(){return Promise.resolve(v.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 B.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 B.error("PolicyServerPassthrough failed: ",s.status,s.statusText,e),B.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=Iu(function(){return Promise.resolve(v.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 B.error("PolicyServerPassthrough failed: "),B.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 B.error("initializePSVerification failed: ",s.status,s.statusText,e),B.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=Iu(function(){return Promise.resolve(v.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 B.error("initializePSVerification failed: "),B.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,E.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 B.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=Iu(function(){return Promise.resolve(v.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 B.error("Download node logs failed:"),B.error(e),new Error("HTTP request failed calling Provider")});return f&&f.then?f.then(t):t()})})}):(B.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 B.debug("Not input string:"),B.debug(e),new Error("["+n+"] Expected string, input type: "+typeof e);var r=e.match(t);return r?{valid:!0,output:r[1]}:(B.warn("["+n+"] Input transformation failed."),{valid:!1,output:e})},t.resolveDdo=function(e,t,n){try{return Promise.resolve(v.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(ze(n,s+o+E.VALIDATE_DDO)).then(function(n){return Promise.resolve(v.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(v.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,E.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(e){var t;return Promise.resolve(v.default(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I({},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,E.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(v.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,E.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(e){var t=new URLSearchParams({consumerAddress:e.consumerAddress,signature:e.signature,nonce:e.nonce});return Promise.resolve(v.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,E.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(v.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,E.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(v.default(u+"?"+o.toString(),{method:"POST",body:r,headers:I({},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(import("stream")).then(function(e){var t=e.Readable,n=new TextEncoder,s=R(/*#__PURE__*/M().mark(function e(){var t,r,s,a,o,u,d;return M().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=!1,r=!1,e.prev=2,a=S(i);case 4:return e.next=6,C(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,C(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,E.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(v.default(u+"?"+n.toString(),{method:"DELETE",headers:I({"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 Mu(e){if(null===e.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Qe("Private network is enforced, but no protector was provided");return e}const Fu=1e3,Ru=60*Fu,_u=60*Ru,Lu=24*_u,Nu=7*Lu,Ou=365.25*Lu,Bu=Ou/12;var Uu=function(e,t){if("string"==typeof e)return ju(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?$u(e):qu(e)}(e,t);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(e)}`)};function ju(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*Ou;case"months":case"month":case"mo":return i*Bu;case"weeks":case"week":case"w":return i*Nu;case"days":case"day":case"d":return i*Lu;case"hours":case"hour":case"hrs":case"hr":case"h":return i*_u;case"minutes":case"minute":case"mins":case"min":case"m":return i*Ru;case"seconds":case"second":case"secs":case"sec":case"s":return i*Fu;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 qu(e){let t=Math.abs(e);return t>=Ou?`${Math.round(e/Ou)}y`:t>=Bu?`${Math.round(e/Bu)}mo`:t>=Nu?`${Math.round(e/Nu)}w`:t>=Lu?`${Math.round(e/Lu)}d`:t>=_u?`${Math.round(e/_u)}h`:t>=Ru?`${Math.round(e/Ru)}m`:t>=Fu?`${Math.round(e/Fu)}s`:`${e}ms`}function $u(e){let t=Math.abs(e);return t>=Ou?zu(e,t,Ou,"year"):t>=Bu?zu(e,t,Bu,"month"):t>=Nu?zu(e,t,Nu,"week"):t>=Lu?zu(e,t,Lu,"day"):t>=_u?zu(e,t,_u,"hour"):t>=Ru?zu(e,t,Ru,"minute"):t>=Fu?zu(e,t,Fu,"second"):`${e} ms`}function zu(e,t,n,r){let i=t>=1.5*n;return`${Math.round(e/n)} ${r}${i?"s":""}`}const Vu=function(){try{return localStorage}catch(e){}}(),Gu=console.debug??console.log??(()=>{});var Ku=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=Uu,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 ":" ")+"+"+Uu(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?Vu?.setItem("debug",e):Vu?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=Vu?.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:Vu,log:Gu});function Hu(e,t=""){const n=Ju(e.message),r=Ju(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 Wu(e,t=""){if(function(e){return e instanceof AggregateError||"AggregateError"===e?.name&&Array.isArray(e.errors)}(e)){let n=Hu(e,t);return n+=e.errors.length>0?`\n${t=`${t} `}${e.errors.map(e=>`${Wu(e,`${t}`)}`).join(`\n${t}`)}`:`\n${t}[Error list was empty]`,n.trim()}return Hu(e,t)}function Qu(e){return{forComponent:t=>Yu(t,e)}}function Yu(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 Ku.enabled(`${e}:trace`)&&null!=Ku.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(n=Ku(`${e}:trace`,t)),Object.assign(Ku(e,t),{error:Ku(`${e}:error`,t),trace:n,newScope:n=>Yu(`${e}:${n}`,t)})}function Ju(e){if(null!=e&&0!==(e=e.trim()).length)return e}function Zu(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 Xu(e){return $o(xn(Gt.decode(`z${e}`)))}Ku.formatters.b=e=>null==e?"undefined":Gt.baseEncode(e),Ku.formatters.t=e=>null==e?"undefined":Wt.baseEncode(e),Ku.formatters.m=e=>null==e?"undefined":Zn.baseEncode(e),Ku.formatters.p=e=>null==e?"undefined":e.toString(),Ku.formatters.c=e=>null==e?"undefined":e.toString(),Ku.formatters.k=e=>null==e?"undefined":e.toString(),Ku.formatters.a=e=>null==e?"undefined":e.toString(),Ku.formatters.e=e=>null==e?"undefined":Wu(e);class ed{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 Zu(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 Zu(this.map.values(),e=>e.key)}values(){return Zu(this.map.values(),e=>e.value)}get size(){return this.map.size}}class td{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 Zu(this.set.entries(),e=>{const t=Xu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{const n=Xu(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Zu(this.set.values(),e=>Xu(e))}intersection(e){const t=new td;for(const n of e)this.has(n)&&t.add(n);return t}difference(e){const t=new td;for(const n of this)e.has(n)||t.add(n);return t}union(e){const t=new td;for(const n of e)t.add(n);for(const e of this)t.add(e);return t}}const nd={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},rd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},id=new globalThis.TextEncoder,sd={hash:e=>Number(function(e,{size:t=32,utf8Buffer:n}={}){if(!nd[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=nd[t];let i=rd[t],s=e;for(;s.length>0;){const e=id.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=id.encode(e)}return function(e,t){const n=nd[t];let r=rd[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}`),mr(t,"base16")}(sd.hash(e,t))};class ad{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=On(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&&Nn(this.fp,e.fp)}}function od(e,t){return Math.floor(Math.random()*(t-e))+e}class ud{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ad))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ad))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 ad))throw new TypeError("Invalid Fingerprint");const t=od(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ad))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex(t=>e.equals(t));return t>-1&&(this.contents[t]=null,!0)}}class dd{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??sd,this.seed=e.seed??od(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=mr(e));const t=new ad(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 ud(this.bucketSize)),null==this.buckets[r]&&(this.buckets[r]=new ud(this.bucketSize)),this.buckets[n].add(t)||this.buckets[r].add(t))return this.count++,!0;const i=[n,r];let s=i[od(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new ud(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 ud(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=mr(e));const t=new ad(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=mr(e));const t=new ad(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 cd={1:.5,2:.84,4:.95,8:.98};function ld(e,t=.001){const n=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/cd[n]),bucketSize:n,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*n)),64)}}class pd{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??sd,this.seed=e.seed??od(0,Math.pow(2,10)),this.filterSeries=[new dd({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=mr(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 dd({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=mr(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=mr(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 hd(e,t=.001,n){return new pd({...ld(e,t),...n??{}})}function fd(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 Qe(`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 md=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function yd(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,md)&&(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 bd(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 gd{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=Qo(t);if(null==i&&(r=16,i=Yo(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=bd(s,8*r);return{network:yd(i,a),mask:a}}(e));else{const n=Jo(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=Jo(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=bd(r,8*n.length);this.network=yd(n,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Jo(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 vd(e){try{const n=fd(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 wd(e){try{return fd(e),!0}catch{return!1}}var Td="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ed(e){var t={exports:{}};return e(t,t.exports),t.exports}var Pd=Ed(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(Td)});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 Pd.Netmask(e));function Sd(e){for(const t of xd)if(t.contains(e))return!0;return!1}function Ad(e){return Zo(e)?Sd(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 Sd(`${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 Sd(t[t.length-1])}(e):Xo(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 Cd(e){try{const t=fd(e);switch(t.type){case"ip4":case"ip6":return Ad(t.host)??!1;default:return"localhost"===t.host}}catch{return!1}}function kd(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class Id{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 Dd{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Id(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 Id(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 Md extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Fd(e={}){return function(e,t){let n,r,i,s=(t=t??{}).onEnd,a=new Dd,o=kd();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 Dd,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=kd()})}},return:()=>(a=new Dd,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 Md)},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 Rd extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Rd)}}const _d=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Ld(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(_d(a));if(a&&(u=()=>{d(_d(a))},a.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Rd;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 Nd(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 Od 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 Bd extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Ud extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class jd extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"}class qd extends Error{static name="StreamClosedError";name="StreamClosedError"}function $d(e){return e.reason}async function zd(e,t,n){if(null==t)return e;const r=n?.translateError??$d;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 Vd{deferred;signal;constructor(e){this.signal=e,this.deferred=kd(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ke)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Gd{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 Ke),this.cleanup())}async join(e={}){const t=new Vd(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 zd(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 Kd extends Rt{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=Nd(this.emitEmpty.bind(this),1),this.emitIdle=Nd(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 Bd;const n=new Gd(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 Ke)}),this.clear()}async onEmpty(e){0!==this.size&&await Ld(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Ld(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Ld(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=Fd({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 Ke("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 Hd=4*Math.pow(2,20);class Wd extends Rt{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??Hd,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new zn,this.writeBuffer=new zn,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 qd)})}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()),zd(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if("readable"!==this.readStatus&&"paused"!==this.readStatus)return;const e=Fd(),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 tt(`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 Tt(e))}}pause(){if("closed"===this.readStatus||"closing"===this.readStatus)throw new tt("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 tt("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 tt(`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 tt(`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 et;this.dispatchEvent(new Et(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 wt))}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 zn(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 vt(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 nt(`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 nt(`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 Qd extends Wd{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 Ld(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 Ld(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}}class Yd extends Rt{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 zd(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 Xe;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 jd(`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 Jd extends Wd{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 Ld(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 Ld(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 Zd(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 Xd{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 ec{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new Xd(t),this.failure=new Xd(t),this.next=new Xd(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=Zd([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 tc{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=kd(),this.haveNext=kd()}[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=kd(),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=kd(),await zd(this.readNext.promise,t?.signal,t)}}function nc(...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 tc;(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 rc(e,...t){if(null==e)throw new Error("Empty pipeline");if(oc(e)){const t=e;e=()=>t.source}else if(ac(e)||sc(e)){const t=e;e=()=>t}const n=[e,...t];if(n.length>1&&oc(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++)oc(n[e])&&(n[e]=uc(n[e]));return ic(...n)}const ic=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},sc=e=>null!=e?.[Symbol.asyncIterator],ac=e=>null!=e?.[Symbol.iterator],oc=e=>null!=e&&null!=e.sink&&null!=e.source,uc=e=>t=>{const n=e.sink(t);if(null!=n?.then){const t=Fd({objectMode:!0});let r;n.then(()=>{t.end()},e=>{t.end(e)});const i=e.source;if(sc(i))r=async function*(){yield*i,t.end()};else{if(!ac(i))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");r=function*(){yield*i,t.end()}}return nc(t,r())}return e.source};class dc extends Error{static name="UnwrappedError";name="UnwrappedError"}class cc extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class lc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class pc extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function hc(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 fc(e,t){const n=t?.maxBufferSize??4194304,r=new zn;let i,s=!1;if(a=e,null==a?.addEventListener||null==a?.removeEventListener||null==a?.send||null==a?.push||null==a?.log)throw new Qe("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 dc("Stream was unwrapped");if(hc(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 Ud(`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 zd(i.promise,t?.signal),hc(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(hc(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,a),new Ud(`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 dc("Stream was unwrapped");e.send(t)||await Ld(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 mc(e,t={}){const n=fc(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=ya(t.maxDataLength));const r=t?.lengthDecoder??wa,i=t?.lengthEncoder??va;return{async read(i){let s=-1;const a=new zn;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 cc("Invalid message length");if(null!=t?.maxLengthLength&&a.byteLength>t.maxLengthLength)throw new pc(`Message length length too long - ${a.byteLength} > ${t.maxLengthLength}`);if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new lc(`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 Ud(`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 Ud(`Unexpected EOF - read ${o.byteLength}/${s} bytes before the stream closed`);return o},async write(e,t){await n.write(new zn(i(e.byteLength),e),t)},async writeV(e,t){const r=new zn(...e.flatMap(e=>[i(e.byteLength),e]));await n.write(r,t)},unwrap:()=>n.unwrap()}}function yc(e,t){const n=mc(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 bc{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new zn,this.maxBufferSize=e.maxBufferSize??4194304,this.maxDataLength=e.maxDataLength??4194304,this.lengthDecoder=e.lengthDecoder??wa,this.encodingLength=e.encodingLength??ya}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Qe(`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 cc("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 gc=4194304;class vc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}function wc(e,t){if(e.byteLength>t)throw new vc("Message length too long")}const Tc=e=>{const t=ya(e),n=Bn(t);return va(e,n),Tc.bytes=t,n};function Ec(e,t){const n=(t=t??{}).lengthEncoder??Tc,r=t?.maxDataLength??gc;function*i(e){wc(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 Pc;Tc.bytes=0,Ec.single=(e,t)=>{const n=(t=t??{}).lengthEncoder??Tc;return wc(e,t?.maxDataLength??gc),new zn(n(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Pc||(Pc={}));class xc extends Kd{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}class Sc extends Kd{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}class Ac{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 Cc}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 Od("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 Cc{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 kc(e,t,n){let r,i,s=!1;function a(){const o={signal:i.signal};let u;null!=n?.timeout&&(u=Zd([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=Nd(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 Ic 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 Dc(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Ic({name:t,metrics:n}):new Map,r}class Mc{filter;constructor(e,t){this.filter=hd(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 Fc(e,t=.001){return new Mc(e,t)}class Rc extends ed{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 _c(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Rc({name:t,metrics:n}):new ed,r}const Lc=new Float32Array([-0]),Nc=new Uint8Array(Lc.buffer);function Oc(e,t,n){Lc[0]=e,t[n]=Nc[0],t[n+1]=Nc[1],t[n+2]=Nc[2],t[n+3]=Nc[3]}const Bc=new Float64Array([-0]),Uc=new Uint8Array(Bc.buffer);function jc(e,t,n){Bc[0]=e,t[n]=Uc[0],t[n+1]=Uc[1],t[n+2]=Uc[2],t[n+3]=Uc[3],t[n+4]=Uc[4],t[n+5]=Uc[5],t[n+6]=Uc[6],t[n+7]=Uc[7]}const qc=BigInt(Number.MAX_SAFE_INTEGER),$c=BigInt(Number.MIN_SAFE_INTEGER);class zc{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 Vc;if(e<qc&&e>$c)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>Gc&&(r=0n,++n>Gc&&(n=0n))),new zc(Number(r),Number(n))}static fromNumber(e){if(0===e)return Vc;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 zc(n,r)}static from(e){return"number"==typeof e?zc.fromNumber(e):"bigint"==typeof e?zc.fromBigInt(e):"string"==typeof e?zc.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new zc(e.low>>>0,e.high>>>0):Vc}}const Vc=new zc(0,0);Vc.toBigInt=function(){return 0n},Vc.zzEncode=Vc.zzDecode=function(){return this},Vc.length=function(){return 1};const Gc=4294967296n;function Kc(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 Hc(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Wc(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Qc{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,Hc(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 Hc(this,4);return Wc(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Hc(this,4);return 0|Wc(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Hc(this,4);const e=(Nc[0]=(t=this.buf)[n=this.pos],Nc[1]=t[n+1],Nc[2]=t[n+2],Nc[3]=t[n+3],Lc[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Hc(this,4);const e=(Uc[0]=(t=this.buf)[n=this.pos],Uc[1]=t[n+1],Uc[2]=t[n+2],Uc[3]=t[n+3],Uc[4]=t[n+4],Uc[5]=t[n+5],Uc[6]=t[n+6],Uc[7]=t[n+7],Bc[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 Hc(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 Hc(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Hc(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 zc(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Hc(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 Hc(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 Hc(this,8);const e=Wc(this.buf,this.pos+=4),t=Wc(this.buf,this.pos+=4);return new zc(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=ga(this.buf,this.pos);return this.pos+=ya(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 Yc(e){return new Qc(e instanceof Uint8Array?e:e.subarray())}function Jc(e,t,n){const r=Yc(e);return t.decode(r,void 0,n)}class Zc{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Xc(){}class el{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const tl=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Bn(r);n+r>e&&(t=Bn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class nl{len;head;tail;states;constructor(){this.len=0,this.head=new Zc(Xc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Zc(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new sl((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(al,10,zc.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=zc.fromBigInt(e);return this._push(al,t.length(),t)}uint64Number(e){return this._push(ba,ya(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=zc.fromBigInt(e).zzEncode();return this._push(al,t.length(),t)}sint64Number(e){const t=zc.fromNumber(e).zzEncode();return this._push(al,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(rl,1,e?1:0)}fixed32(e){return this._push(ol,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=zc.fromBigInt(e);return this._push(ol,4,t.lo)._push(ol,4,t.hi)}fixed64Number(e){const t=zc.fromNumber(e);return this._push(ol,4,t.lo)._push(ol,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(Oc,4,e)}double(e){return this._push(jc,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(rl,1,0):this.uint32(t)._push(ul,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(Kc,t,e):this._push(rl,1,0)}fork(){return this.states=new el(this),this.head=this.tail=new Zc(Xc,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 Zc(Xc,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?Bn(n):tl(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function rl(e,t,n){t[n]=255&e}function il(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class sl extends Zc{next;constructor(e,t){super(il,e,t),this.next=void 0}}function al(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 ol(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 ul(e,t,n){t.set(e,n)}function dl(e,t,n){t.set(e,n)}function cl(e,t,n){e.length<40?Kc(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(mr(e),n)}function ll(e,t){const n=new nl;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*pl(e,t,n){const r=Yc(e);yield*t.stream(r,void 0,"$",n)}function hl(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&&(nl.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(dl,t,e),this},nl.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(cl,t,e),this});class fl extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var ml;!function(e){let t;e.codec=()=>(null==t&&(t=hl((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:On(0),payloadType:On(0),payload:On(0),signature:On(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 ll(t,e.codec())},e.decode=function(t,n){return Jc(t,e.codec(),n)},e.stream=function(t,n){return pl(t,e.codec(),n)}}(ml||(ml={}));class yl extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class bl{static createFromProtobuf=e=>{const t=ml.decode(e),n=Fo(t.publicKey);return new bl({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=gl(r,i,s),o=await t.sign(a.subarray(),n);return new bl({publicKey:t.publicKey,payloadType:i,payload:s,signature:o})};static openAndCertify=async(e,t,n)=>{const r=bl.createFromProtobuf(e);if(!await r.validate(t,n))throw new yl("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=ml.encode({publicKey:Ro(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Nn(this.marshal(),e.marshal())}async validate(e,t){const n=gl(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}}const gl=(e,t,n)=>{const r=mr(e),i=va(r.byteLength),s=va(t.length),a=va(n.length);return new zn(i,r,s,t,a,n)},vl=Uint8Array.from([3,1]);var wl;!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=hl((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:On(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 ll(t,e.codec())},e.decode=function(t,n){return Jc(t,e.codec(),n)},e.stream=function(t,n){return pl(t,e.codec(),n)}}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=hl((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:On(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 fl('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 fl('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 ll(t,e.codec())},e.decode=function(t,n){return Jc(t,e.codec(),n)},e.stream=function(t,n){return pl(t,e.codec(),n)}}(wl||(wl={}));class Tl{static createFromProtobuf=e=>{const t=wl.decode(e),n=$o(xn(t.peerId)),r=(t.addresses??[]).map(e=>Su(e.multiaddr));return new Tl({peerId:n,multiaddrs:r,seqNumber:t.seq})};static DOMAIN="libp2p-peer-record";static CODEC=vl;peerId;multiaddrs;seqNumber;domain=Tl.DOMAIN;codec=Tl.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=wl.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 Tl&&!!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 El(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 Pl 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 Pl(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(){Al(n,"abort",l),Al(e,t,d),Al(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)};Sl(n,"abort",l),Sl(e,t,d),Sl(e,s,c)})}function Sl(e,t,n){null!=e&&(Cl(e)?e.addEventListener(t,n):e.addListener(t,n))}function Al(e,t,n){null!=e&&(Cl(e)?e.removeEventListener(t,n):e.removeListener(t,n))}function Cl(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class kl extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Il{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 Pl)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Dl{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 Pl),this.cleanup())}async join(e={}){const t=new Il(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 zd(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 Ml(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 Fl extends Rt{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=Ml(this.emitEmpty.bind(this),1),this.emitIdle=Ml(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 kl;const n=new Dl(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 Pl)}),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=Fd({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 Pl("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 Rl="lock:worker:request-read",_l="lock:worker:abort-read-request",Ll="lock:worker:release-read",Nl="lock:master:grant-read",Ol="lock:master:error-read",Bl="lock:worker:request-write",Ul="lock:worker:abort-write-request",jl="lock:worker:release-write",ql="lock:master:grant-write",$l="lock:master:error-write",zl="lock:worker:finalize",Vl="mortice",Gl={singleProcess:!1},Kl=(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===zl&&e.safeDispatchEvent("finalizeRequest",{detail:{name:c.name}})};class Hl{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Vl)}readLock(e){return this.sendRequest(Rl,_l,Nl,Ol,Ll,e)}writeLock(e){return this.sendRequest(Bl,Ul,ql,$l,jl,e)}finalize(){this.channel.postMessage({type:zl,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 Wl=new Map;let Ql;function Yl(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}function Jl(e){if(null==Ql&&(Ql=(e=>{if(e=Object.assign({},Gl,e),Boolean(globalThis.document)||e.singleProcess){const e=new BroadcastChannel(Vl),t=new Rt;return e.addEventListener("message",Kl(t,e,"requestReadLock","abortReadLockRequest",Rl,_l,Ol,Ll,Nl)),e.addEventListener("message",Kl(t,e,"requestWriteLock","abortWriteLockRequest",Bl,Ul,$l,jl,ql)),t}return new Hl(e.name)})(e),!Yl(Ql))){const e=Ql;e.addEventListener("requestReadLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=Wl.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=Wl.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=Wl.get(e.detail.name);null!=t&&t.finalize()})}return Ql}async function Zl(e,t){let n,r;const i=new Promise((e,t)=>{n=e,r=t}),s=()=>{r(new Pl)};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 Xl={name:"lock",concurrency:Infinity,singleProcess:!1,autoFinalize:!1};function ep(e){const t=Object.assign({},Xl,e);return((e,t)=>{let n=Wl.get(e);if(null!=n)return n;const r=Jl(t);if(Yl(r))return n=r,Wl.set(e,n),n;const i=new Fl({concurrency:1});let s;return n={async readLock(e){if(null!=s)return Zl(s,e);s=new Fl({concurrency:t.concurrency,autoStart:!1});const n=s,r=Zl(s,e);return i.add(async()=>{n.start(),await n.onIdle().then(()=>{s===n&&(s=null)})}),r},writeLock:async e=>(s=null,Zl(i,e)),finalize:()=>{Wl.delete(e)},queue:i},Wl.set(e,n),!0===t.autoFinalize&&i.addEventListener("idle",()=>{n.finalize()},{once:!0}),n})(t.name,t)}const tp=new Float32Array([-0]),np=new Uint8Array(tp.buffer);function rp(e,t,n){tp[0]=e,t[n]=np[0],t[n+1]=np[1],t[n+2]=np[2],t[n+3]=np[3]}const ip=new Float64Array([-0]),sp=new Uint8Array(ip.buffer);function ap(e,t,n){ip[0]=e,t[n]=sp[0],t[n+1]=sp[1],t[n+2]=sp[2],t[n+3]=sp[3],t[n+4]=sp[4],t[n+5]=sp[5],t[n+6]=sp[6],t[n+7]=sp[7]}const op=BigInt(Number.MAX_SAFE_INTEGER),up=BigInt(Number.MIN_SAFE_INTEGER);class dp{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 cp;if(e<op&&e>up)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>lp&&(r=0n,++n>lp&&(n=0n))),new dp(Number(r),Number(n))}static fromNumber(e){if(0===e)return cp;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 dp(n,r)}static from(e){return"number"==typeof e?dp.fromNumber(e):"bigint"==typeof e?dp.fromBigInt(e):"string"==typeof e?dp.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new dp(e.low>>>0,e.high>>>0):cp}}const cp=new dp(0,0);cp.toBigInt=function(){return 0n},cp.zzEncode=cp.zzDecode=function(){return this},cp.length=function(){return 1};const lp=4294967296n;function pp(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 hp(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function fp(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class mp{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,hp(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 hp(this,4);return fp(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw hp(this,4);return 0|fp(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw hp(this,4);const e=(np[0]=(t=this.buf)[n=this.pos],np[1]=t[n+1],np[2]=t[n+2],np[3]=t[n+3],tp[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw hp(this,4);const e=(sp[0]=(t=this.buf)[n=this.pos],sp[1]=t[n+1],sp[2]=t[n+2],sp[3]=t[n+3],sp[4]=t[n+4],sp[5]=t[n+5],sp[6]=t[n+6],sp[7]=t[n+7],ip[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 hp(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 hp(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw hp(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 dp(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw hp(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 hp(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 hp(this,8);const e=fp(this.buf,this.pos+=4),t=fp(this.buf,this.pos+=4);return new dp(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=ga(this.buf,this.pos);return this.pos+=ya(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 yp(e,t,n){const r=function(e){return new mp(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(r,void 0,n)}class bp{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function gp(){}class vp{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const wp=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Bn(r);n+r>e&&(t=Bn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class Tp{len;head;tail;states;constructor(){this.len=0,this.head=new bp(gp,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new bp(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(Sp,10,dp.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=dp.fromBigInt(e);return this._push(Sp,t.length(),t)}uint64Number(e){return this._push(ba,ya(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=dp.fromBigInt(e).zzEncode();return this._push(Sp,t.length(),t)}sint64Number(e){const t=dp.fromNumber(e).zzEncode();return this._push(Sp,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ep,1,e?1:0)}fixed32(e){return this._push(Ap,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=dp.fromBigInt(e);return this._push(Ap,4,t.lo)._push(Ap,4,t.hi)}fixed64Number(e){const t=dp.fromNumber(e);return this._push(Ap,4,t.lo)._push(Ap,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(rp,4,e)}double(e){return this._push(ap,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Ep,1,0):this.uint32(t)._push(Cp,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(pp,t,e):this._push(Ep,1,0)}fork(){return this.states=new vp(this),this.head=this.tail=new bp(gp,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 bp(gp,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?Bn(n):wp(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function Ep(e,t,n){t[n]=255&e}function Pp(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class xp extends bp{next;constructor(e,t){super(Pp,e,t),this.next=void 0}}function Sp(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 Ap(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 Cp(e,t,n){t.set(e,n)}function kp(e,t,n){t.set(e,n)}function Ip(e,t,n){e.length<40?pp(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(mr(e),n)}function Dp(e,t){const n=new Tp;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var Mp,Fp,Rp,_p,Lp;function Np(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function Op(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Np("enum",Mp.VARINT,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())})}function Bp(e,t){return Np("message",Mp.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Tp.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(kp,t,e),this},Tp.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Ip,t,e),this}),(Lp=Mp||(Mp={}))[Lp.VARINT=0]="VARINT",Lp[Lp.BIT64=1]="BIT64",Lp[Lp.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",Lp[Lp.START_GROUP=3]="START_GROUP",Lp[Lp.END_GROUP=4]="END_GROUP",Lp[Lp.BIT32=5]="BIT32";class Up extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class jp extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function qp(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let n;return"RSA"===e.type&&(n=e.toMultihash()),qo(Fo(t.publicKey,n))}function $p(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:qp(e,t),addresses:t.addresses.filter(({observed:e})=>null!=e&&e>Date.now()-n).map(({multiaddr:e,isCertified:t})=>({multiaddr:Su(e),isCertified:t??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:r}}function zp(e,t){return null==e&&null==t||null!=e&&null!=t&&Nn(e,t)}function Vp(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 Gp(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=Bp((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:On(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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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),_p.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=_p.codec().decode(e,e.uint32(),{limits:n.limits?.value});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Bp((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.addresses)for(const e of t.addresses)n.uint32(10),Rp.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 Up('Decode error - map field "addresses" had too many elements');i.addresses.push(Rp.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 Up('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 jp('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 jp('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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Fp||(Fp={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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:On(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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Rp||(Rp={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(_p||(_p={}));const Kp="/",Hp=(new TextEncoder).encode(Kp),Wp=Hp[0];class Qp{_buf;constructor(e,t){if("string"==typeof e)this._buf=mr(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]!==Wp)throw new Error("Invalid key")}toString(e="utf8"){return yr(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Qp(e.join(Kp))}static random(){return new Qp(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Qp(e):"function"==typeof e.uint8Array?new Qp(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Hp),this._buf[0]!==Wp){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Wp,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Wp;)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 Qp.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Kp).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 Qp(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Kp)||(e+=Kp),e+=this.type(),new Qp(e)}parent(){const e=this.list();return new Qp(1===e.length?Kp:e.slice(0,-1).join(Kp))}child(e){return this.toString()===Kp?e:e.toString()===Kp?this:new Qp(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 Qp.withNamespaces([...this.namespaces(),...(t=e.map(e=>e.namespaces()),[].concat(...t))]);var t}}const Yp="/peers/";function Jp(e){if(!St(e)||null==e.type)throw new Qe("Invalid PeerId");const t=e.toCID().toString();return new Qp(`${Yp}${t}`)}async function Zp(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=Su(r.multiaddr)),!xu(r.multiaddr))throw new Qe("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===tu)?.value;return e.equals(r)&&(n=n.decapsulate(Su(`/p2p/${e}`))),{isCertified:t,multiaddr:n.bytes}})}async function Xp(e,t,n,r){if(null==t)throw new Qe("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Qe("publicKey bytes do not match peer id publicKey bytes");const i=r.existingPeer?.peer;if(null!=i&&!e.equals(i.id))throw new Qe("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=eh(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:th})),null!=t.tags&&(d=eh(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:nh,map:rh})),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=eh([...u.entries()],{validate:th})}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=eh([...n.entries()],{validate:nh,map:rh})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}null!=i?.id.publicKey?s=Ro(i.id.publicKey):null!=t.publicKey?s=Ro(t.publicKey):null!=e.publicKey&&(s=Ro(e.publicKey));const l={addresses:await Zp(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=>Nn(e.multiaddr,e.multiaddr))?.observed??Date.now()}),"RSA"!==e.type&&delete l.publicKey,l}function eh(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 th(e,t){if("string"!=typeof e)throw new Qe("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Qe("Metadata value must be a Uint8Array")}function nh(e,t){if("string"!=typeof e)throw new Qe("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Qe("Tag value must be an integer");if(t.value<0||t.value>100)throw new Qe("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Qe("Tag ttl must be an integer");if(t.ttl<0)throw new Qe("Tag ttl must be between greater than 0")}}function rh(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 ih(e){const t=e.toString().split("/")[2];return zo(In.parse(t,Wt))}function sh(e,t,n){return function(e,t,n){return $p(e,Fp.decode(t),n)}(ih(e),t,n)}class ah{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=_c({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:ep({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(Jp(e),t)}async load(e,t){const n=Jp(e),r=await this.datastore.get(n,t),i=Fp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new rt;return $p(e,i,this.peerId.equals(e)?Infinity:this.maxAddressAge)}async save(e,t,n){const r=await this.#s(e,n),i=await Xp(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 Xp(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 Xp(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:Yp,filters:(e.filters??[]).map(e=>({key:n,value:r})=>e(sh(n,r,t))),orders:(e.orders??[]).map(e=>(n,r)=>e(sh(n.key,n.value,t),sh(r.key,r.value,t)))}}(e??{},this.maxAddressAge),e)){const r=ih(t);if(r.equals(this.peerId))continue;const i=Fp.decode(n);this.#i(r,i)?await this.datastore.delete(t,e):yield $p(r,i,this.peerId.equals(r)?Infinity:this.maxAddressAge)}}async#s(e,t){try{const n=Jp(e),r=await this.datastore.get(n,t),i=Fp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new rt;return{peerPB:i,peer:$p(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=Fp.encode(t);return await this.datastore.put(Jp(e),i,r),{peer:$p(e,t,this.maxAddressAge),previous:n?.peer,updated:null==n||(s=t,a=n.peerPB,!(Vp(s.addresses,a.addresses,(e,t)=>e.isCertified===t.isCertified&&!!Nn(e.multiaddr,t.multiaddr))&&Vp(s.protocols,a.protocols,(e,t)=>e===t)&&zp(s.publicKey,a.publicKey)&&zp(s.peerRecordEnvelope,a.peerRecordEnvelope)&&Gp(s.metadata,a.metadata,(e,t)=>Nn(e,t))&&Gp(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 oh{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 ah(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 El(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=St(t)?t:St(t?.expectedPeer)?t.expectedPeer:void 0,i=St(t)||void 0===t?n:t,s=await bl.openAndCertify(e,Tl.DOMAIN,i),a=zo(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=Tl.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=bl.createFromProtobuf(u.peerRecordEnvelope),t=Tl.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 uh extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=uh.name;code=uh.code;constructor(e="Not Found"){super(e)}}function dh(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}function ch(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 lh(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=ch(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 ph(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const n=await El(e);yield*n.sort(t)}():function*(){const n=El(e);yield*n.sort(t)}()}function hh(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 fh{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 dh(this.putMany(e,n)),e=[],await dh(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=lh(n,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>lh(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>ph(e,t),n)),null!=e.offset){let t=0;const r=e.offset;n=lh(n,()=>t++>=r)}return null!=e.limit&&(n=hh(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;n=lh(n,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>lh(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>ph(e,t),n)),null!=e.offset){const t=e.offset;let r=0;n=lh(n,()=>r++>=t)}return null!=e.limit&&(n=hh(n,e.limit)),n}}class mh extends fh{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 uh;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 Qp(e),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(const e of this.data.keys())yield new Qp(e),t?.signal?.throwIfAborted()}}const yh=e=>({match:t=>{const n=t[0];return null!=n&&n.code===e&&null==n.value&&t.slice(1)}}),bh=(e,t)=>({match:n=>{const r=n[0];return r?.code===e&&null!=r.value&&(null==t||r.value===t)&&n.slice(1)}}),gh=e=>({match:t=>{const n=e.match(t);return!1===n?t:n}}),vh=(...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}}),wh=(...e)=>({match:t=>{for(const n of e){const e=n.match(t);if(!1===e)return!1;t=e}return t}});function Th(...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 Eh=Th(bh(tu)),Ph=bh(54),xh=bh(55),Sh=bh(56),Ah=bh(53),Ch=wh(bh(4),gh(bh(43))),kh=wh(gh(bh(42)),bh(eu),gh(bh(43))),Ih=vh(Ch,kh),Dh=vh(Ih,Ah,Ph,xh,Sh),Mh=Th(vh(Ih,wh(vh(Ah,Sh,Ph,xh),gh(bh(tu))))),Fh=Th(Ch),Rh=Th(kh),_h=wh(Dh,bh(6)),Lh=wh(Dh,bh(273)),Nh=Th(wh(_h,gh(bh(tu)))),Oh=wh(Lh,yh(460),gh(bh(tu))),Bh=wh(Lh,yh(461),gh(bh(tu))),Uh=vh(Oh,Bh),jh=Th(Bh),qh=vh(Dh,_h,Lh,Oh,Bh),$h=vh(wh(qh,yh(477),gh(bh(tu)))),zh=Th($h),Vh=vh(wh(qh,yh(478),gh(bh(tu))),wh(qh,yh(nu),gh(bh(ru)),yh(477),gh(bh(tu)))),Gh=Th(Vh),Kh=wh(Lh,yh(280),gh(bh(iu)),gh(bh(iu)),gh(bh(tu))),Hh=Th(Kh),Wh=wh(Bh,yh(465),gh(bh(iu)),gh(bh(iu)),gh(bh(tu))),Qh=Th(Wh),Yh=vh($h,Vh,wh(_h,gh(bh(tu))),wh(Uh,gh(bh(tu))),wh(Dh,gh(bh(tu))),Kh,Wh,bh(tu)),Jh=Th(Yh);var Zh;const Xh=Th(wh(gh(Yh),yh(au),(Zh=yh(su),{match:e=>!1===Zh.match(e)&&e}),gh(bh(tu)))),ef=Th(vh(wh(Yh,yh(au),yh(su),gh(bh(tu))),wh(Yh,yh(su),gh(bh(tu))),wh(yh(su),gh(bh(tu))))),tf=864e13;class nf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Dc({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=fd(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===Ad(t);this.mappings.set(t,{domain:e,verified:n,expires:n?tf-Date.now():0,lastVerified:n?tf-Date.now():void 0})})}remove(e){const t=fd(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(!wd(r))continue;const i=fd(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===nu&&n[e+1]?.code!==ru)return n.splice(e+1,0,{name:"sni",code:ru,value:t}),Su(n)}confirm(e,t){const n=fd(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=fd(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 rf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Dc({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=fd(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:Zo(n)?4:6,protocol:i,verified:!1,expires:0};a.push(o),this.mappings.set(s,a)}remove(e){const t=fd(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(!wd(n))continue;const e=fd(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===eu),o=s.findIndex(e=>e.name===r);return a>-1&&o>-1?(s[a].value=t,s[a].code=4===n?4:eu,s[o].value=`${i}`,Su(s)):e}confirm(e,t){if(!wd(e))return!1;const n=fd(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(!wd(e))return!1;const n=fd(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 sf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Dc({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&&(Cd(e)||function(e){try{const t=fd(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:Su(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 af{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Dc({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(Cd(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:!wd(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(!wd(e))return e.toString();const t=fd(e);return`${t.host}-${t.port}-${t.protocol}`}}const of=e=>e;function uf(e,t){const n=e.getComponents().findLast(e=>e.code===tu)?.value;return null!=n&&jo(n).equals(t)&&(e=e.decapsulate(Su(`/p2p/${t.toString()}`))),e}class df{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 sf(e,t),this.dnsMappings=new nf(e,t),this.ipMappings=new rf(e,t),this.transportAddresses=new af(e,t),this.announceFilter=t.announceFilter??of,this.observedAddressFilter=hd(1024),this.addressVerificationTTL=t.addressVerificationTTL??6e5,this.addressVerificationRetry=t.addressVerificationRetry??3e5,this._updatePeerStoreAddresses=Nd(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===tu)?.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=>Su(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Su(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Su(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){const t=fd(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=uf(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=uf(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=uf(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=Su(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(Su(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.add(e,t,n,r,i),this.observed.removePrefixed(`/ip${Zo(n)?4:6}/${n}/${i}/${r}`)}removePublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.remove(Su(`/ip${Zo(n)?4:6}/${n}/${i}/${r}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;if(!wd(e))return!1;const t=fd(e);if("ip4"!==t.type||!0===Ad(t.host))return!1;const n=this.components.transportManager.getListeners(),r=[e=>zh.exactMatch(e)||Gh.exactMatch(e),e=>Nh.exactMatch(e),e=>jh.exactMatch(e)];for(const i of r){if(!i(e))continue;const r=n.filter(e=>e.getAddrs().filter(e=>"ip4"===fd(e).type&&i(e)).length>0);if(1!==r.length)continue;const s=r[0].getAddrs().filter(e=>!vd(e)).pop();if(null==s)continue;const a=fd(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 cf;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(cf||(cf={}));class lf extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class pf extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class hf extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class ff extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class mf extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class yf extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class bf extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class gf extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class vf extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class wf extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class Tf extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Ef extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class Pf 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 Sf extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class Af extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class Cf extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}class kf{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=Qu())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>kt(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 If=["metrics","connectionProtector","dns"],Df=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Mf(e){return Array.isArray(e?.[_t])?e[_t]:[]}function Ff(e){return Array.isArray(e?.[Lt])?e[Lt]:[]}function Rf(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function _f(e={}){return null==e.denyDialMultiaddr&&(e.denyDialMultiaddr=e=>!!zh.matches(e)||Cd(e)),e}class Lf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Nf(e){if(St(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===tu)?.value;t=null==e?void 0:jo(e),n.forEach(e=>{if(!xu(e))throw new st("Invalid multiaddr");const n=e.getComponents().findLast(e=>e.code===tu)?.value;if(null==n){if(null!=t)throw new Qe("Multiaddrs must all have the same peer id or have no peer id")}else{const e=jo(n);if(!0!==t?.equals(e))throw new Qe("Multiaddrs must all have the same peer id or have no peer id")}})}return n=n.filter(e=>!Eh.exactMatch(e)),{peerId:t,multiaddrs:n}}const Of=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Bf(e){const t=fd(e);let n=t.cidr;if("ip4"!==t.type&&"ip6"!==t.type)throw new Qe(`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 Qe(`Multiaddr ${e} was not an IPv4 or IPv6 address`)}return new gd(t.host,n)}function Uf(e){return!Xh.exactMatch(e)}function jf(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=>Uf(e))?void 0:r}class qf{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(e=>Bf(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 ed;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(wd(e.remoteAddr)){const n=fd(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??Of;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 $f=1e4,zf="last-dial-failure",Vf="last-dial-success";function Gf(e,t){const n=Nh.exactMatch(e.multiaddr),r=Nh.exactMatch(t.multiaddr);if(n&&!r)return-1;if(!n&&r)return 1;const i=Gh.exactMatch(e.multiaddr),s=Gh.exactMatch(t.multiaddr);if(i&&!s)return-1;if(!i&&s)return 1;const a=zh.exactMatch(e.multiaddr),o=zh.exactMatch(t.multiaddr);if(a&&!o)return-1;if(!a&&o)return 1;const u=ef.exactMatch(e.multiaddr),d=ef.exactMatch(t.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;const c=Hh.exactMatch(e.multiaddr),l=Hh.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const p=Qh.exactMatch(e.multiaddr),h=Qh.exactMatch(t.multiaddr);return p&&!h?-1:!p&&h?1:0}function Kf(e,t){const n=vd(e.multiaddr),r=vd(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function Hf(e,t){const n=Cd(e.multiaddr),r=Cd(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function Wf(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function Qf(e,t){const n=Xh.exactMatch(e.multiaddr),r=Xh.exactMatch(t.multiaddr);return n&&!r?1:!n&&r?-1:0}class Yf extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"}var Jf=Ed(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}),Zf=Jf;class Xf extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Xf)}}const em=e=>e.reason??new DOMException("This operation was aborted.","AbortError");class tm{#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 nm extends Zf{#d;#c;#l=0;#p;#h=!1;#f=!1;#m;#y=0;#b=0;#g;#v;#w;#T=[];#E=0;#u;#P;#x=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:tm,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.#P=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.#x<this.#S}#N(){this.#x--,0===this.#x&&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.#x: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.#x){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.#x&&this.#g&&this.#z(),this.#l=this.#d?this.#x: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.#x++,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(em(a));if(a&&(u=()=>{d(em(a))},a.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Xf;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.#x} 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.#P,this.#z(),this.#W(),this.emit("empty"),0===this.#x&&(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.#x&&0===this.#u.size||await this.#Q("idle")}async onPendingZero(){0!==this.#x&&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.#x}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.#x===this.#S&&this.#u.size>0||this.isRateLimited&&this.#u.size>0}get runningTasks(){return[...this.#k.values()].map(e=>({...e}))}}function rm(e){const t=[um.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function im(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:um[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:um[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?yr(e.data):e.data}))}}function sm(e,t={}){const n=new nm({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),rm(r.types).forEach(e=>{s.append("type",um[e])}),r.onProgress?.(new Lf("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=im(await t.json());return r.onProgress?.(new Lf("dns:response",n)),n},{signal:r.signal});if(null==a)throw new Error("No DNS response received");return a}}class am{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 im({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:um[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 om{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=new am(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["."]=[sm("https://cloudflare-dns.com/dns-query"),sm("https://dns.google/resolve")])}async query(e,t={}){const n=rm(t.types),r=!1!==t.cached?this.cache.get(e,n):void 0;if(null!=r)return t.onProgress?.(new Lf("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 Lf("dns:error",e))}}throw new Yf(a,`DNS lookup of ${e} ${n} failed`)}}var um;!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(um||(um={}));const dm=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:[um.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(Su(t))}return a}getDNS(e){return null!=e.dns?e.dns:(null==this.dns&&(this.dns=function(e={}){return new om(e)}()),this.dns)}};async function cm(e,t,n){const r=n.depth??0;if(r>(n.maxRecursiveDepth??32))throw new Cf("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 cm(e,t,{...n,depth:r+1}))}return!1===i&&s.push(e),s}const lm={maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:dm}};class pm{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??lm.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??lm.maxDialQueueLength,this.dialTimeout=t.dialTimeout??lm.dialTimeout,this.connections=t.connections??new ed,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??lm.resolvers,this.shutDownController=new AbortController,this.queue=new Sc({concurrency:t.maxParallelDials??lm.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",e=>{e.detail?.error.name!==Ke.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}=Nf(e);if(null!=n&&!0!==t.force){const e=jf(n,this.connections.get(n),r);if(null!=e)return this.log("already connected to %a",e.remoteAddr),t.onProgress?.(new Lf("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 Lf("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new ht("Dial queue is full");return this.log("creating dial target for %p",n,r.map(e=>e.toString())),t.onProgress?.(new Lf("dial-queue:add-to-dial-queue")),this.queue.add(async e=>{e.onProgress?.(new Lf("dial-queue:start-dial"));const t=Zd([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}},{peerId:n,priority:t.priority??Tm,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 Lf("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 ht("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:{[Vf]:mr(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:{[zf]:mr(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 lt(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:Su(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new ht("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new gf("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 cm(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===tu)?.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 Tf("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(Gf).sort(Wf).sort(Qf).sort(Hf).sort(Kf):u.sort(this.addressSorter);if(0===d.length)throw new gf("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=>!Xh.matches(e.multiaddr))}catch{}return!1}}const hm=Object.prototype.toString,fm=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 mm(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 ym 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 bm(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function gm({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 ym)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),bm(r,o)<=0)throw s;const d=await i.shouldConsumeRetry(u),c=bm(r,o);if(c<=0||a<=0)throw s;if(s instanceof TypeError&&!function(e){const t=e&&(e=>"[object Error]"===hm.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(")"))||fm.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 vm{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);wm(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,mm("factor",t.factor,{min:0,allowInfinity:!1}),mm("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),mm("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),mm("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 gm({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(Ct)&&(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=>wm(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 wm(e){for(const t of e.tags.keys())if(t.startsWith(Ct))return!0;return!1}const Tm=50;class Em{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 Qe("Connection Manager maxConnections must be greater than 0");this.connections=new ed,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=>Bf(Su(e))),this.deny=(t.deny??[]).map(e=>Bf(Su(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Ac({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new qf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(e=>Su(e))}),this.dialQueue=new pm(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:dm},connections:this.connections}),this.reconnectQueue=new vm({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 It(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 Dt(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const n of t)e.push(Promise.all([Ld(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 Qe("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 pt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:n,multiaddrs:r}=Nf(e);if(this.peerId.equals(n))throw new it("Can not dial self");if(null!=n&&!0!==t.force){this.log("dial %p",n);const e=jf(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 Lf("dial-queue:already-connected")),e}const i=await this.dialQueue.dial(e,{...t,priority:t.priority??Tm});if("open"!==i.status)throw new Je("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 st("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([Ld(e,"close",t),e.close(t)])}catch(t){e.abort(t)}}))}acceptIncomingConnection(e){if(this.deny.some(t=>{if(wd(e.remoteAddr)){const n=fd(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(wd(e.remoteAddr)){const n=fd(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(wd(e.remoteAddr)){const t=fd(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=>Su(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Pm{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 ec({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[_t]=["@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=fc(r);t=Date.now(),await Promise.all([i.write(so(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:yr(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:yr(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 hf("No content routers available");const n=this,r=new td;for await(const i of nc(...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 hf("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 hf("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 pt;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 pt;return Promise.any(this.routers.filter(e=>e.get instanceof Function).map(async n=>n.get(e,t)))}}const Sm=globalThis.CustomEvent??Event;async function*Am(e,t={}){let n=t.concurrency??Infinity;n<1&&(n=Infinity);const r=t.ordered??!1,i=new EventTarget,s=[];let a,o=kd(),u=kd(),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=kd(),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 Sm("task-complete"))},t=>{e.done=!0,e.err=t,i.dispatchEvent(new Sm("task-complete"))})}d=!0,i.dispatchEvent(new Sm("task-complete"))}catch(e){a=e,i.dispatchEvent(new Sm("task-complete"))}});;){if(l()||(u=kd(),await u.promise),null!=a)throw a;if(r?yield*p():yield*h(),null!=a)throw a;if(d&&0===s.length)break}}class Cm{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:yr(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 ff("No peer routers available");if(e.toString()===this.peerId.toString())throw new mf("Should not try to find self");const n=this,r=nc(...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 rt}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new ff("No peer routers available");const n=this,r=hd(1024);for await(const i of Am(async function*(){const r=nc(...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 km extends Rt{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=Zd([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=kd();const e=await Ld(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=Zd([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=so(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 zd(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 Im{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=Dc({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 yf(`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 bf(`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 Qe("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 Dm{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Dc({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Dc({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ft.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Qe("Transport must have a valid tag");if(this.transports.has(t))throw new Qe(`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 Af(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Lf("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 pt("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 vf)});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})}),Fh.matches(e)?t.ipv4.attempts++:Rh.matches(e)&&t.ipv6.attempts++,n.push(s.listen(e).then(()=>{t.errors.delete(e.toString()),Fh.matches(e)&&t.ipv4.success++,Rh.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!==Ft.NO_FATAL)throw new wf(`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 Mm="/multistream/1.0.0",Fm=mr("\n");async function Rm(e,t){const n=(await e.read(t)).subarray();if(0===n.byteLength||n[n.length-1]!==Fm[0])throw new dt("Missing newline");return yr(n).trimEnd()}async function _m(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=mc(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"]',Mm,s);const e=mr(`${Mm}\n`),t=mr(`${s}\n`);if(await i.writeV([e,t],n),r.trace("reading multistream-select header"),a=await Rm(i,n),r.trace('read "%s"',a),a!==Mm){r.error("did not read multistream-select header from response");break}}else r.trace('write "%s"',s),await i.write(mr(`${s}\n`),n);if(r.trace("reading protocol response"),a=await Rm(i,n),r.trace('read "%s"',a),a===s)return r.trace('selected "%s" after negotiation',a),i.unwrap(),s}throw new ut(`Protocol selection failed - could not negotiate ${t}`)}async function Lm(e,t,n={}){t=Array.isArray(t)?t:[t];const r=e.log.newScope("mss:handle"),i=mc(e,{...n,maxDataLength:1024,maxLengthLength:2});for(;;){r.trace("reading incoming string");const e=await Rm(i,n);if(r.trace('read "%s"',e),e!==Mm){if(t.includes(e))return r.trace('respond with "%s" for "%s"',e,e),await i.write(mr(`${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(mr("na\n"),n),r('responded with "na" for "%s"',e);else{const s=new zn(...t.map(e=>Ec.single(mr(`${e}\n`))),mr("\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"',Mm,e),await i.write(mr(`${Mm}\n`),n),r.trace('responded with "%s" for "%s"',Mm,e)}}class Nm extends Rt{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??$f,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??$f,this.closeTimeout=t.closeTimeout??1e3,this.direct=Uf(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),null==this.remoteAddr.getComponents().find(e=>e.code===tu)&&(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 wt(e.local,e.error))})}[Symbol.toStringTag]="Connection";[Ve]=!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 Je(`The connection muxer is "${this.muxer.status}" and not "open"`);if("open"!==this.maConn.status)throw new Je(`The connection is "${this.status}" and not "open"`);if(null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new mt("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 _m(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=Om(n.protocol,"outbound",this);if(i>r){const e=new bt(`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 Lm(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(Om(t.protocol,"inbound",this)>e)throw new yt(`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 mt("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 Om(e,t,n){let r=0;return n.streams.forEach(n=>{n.direction===t&&n.protocol===e&&r++}),r}class Bm{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Dc({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(e=>{this.connectionEncrypters.set(e.protocol,e)}),this.streamMuxers=Dc({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??$f,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??$f,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 Ef(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){return Zd([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 Pf("Connection denied");await zd(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===tu)?.value;let r;null!=n&&(r=jo(n),await zd(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 st(`${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===tu)?.value;let u;null!=s&&(u=jo(s)),n?.onProgress?.(new Lf(`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 it("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 Lf(`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 Nm(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 Lm(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new Sf(`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 Sf(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 _m(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new Sf(`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 Sf(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 _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 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 Lm(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 Um="3.1.6",jm="js-libp2p";class qm extends Rt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Rt,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??Qu(),this.log=this.logger.forComponent("libp2p"),this.services={};const r=e.nodeInfo?.name??jm,i=e.nodeInfo?.version??Um,s=this.components=function(e={}){const t=new kf(e),n=new Proxy(t,{get(e,n,r){if("string"==typeof n&&!Df.includes(n)){const e=t.components[n];if(null==e&&!If.includes(n))throw new lf(`${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??jm}/${o??Um} browser/${globalThis.navigator.userAgent}`)},logger:this.logger,events:t,datastore:e.datastore??new mh,connectionGater:_f(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 oh(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 Bm(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 Dm(this.components,e.transportManager)),this.configureComponent("connectionManager",new Em(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Pm(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Im(this.components)),this.configureComponent("addressManager",new df(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 Cm(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 km(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[Ge]&&(this.log("registering service %s for content routing",t),d.push(n[Ge])),null!=n[At]&&(this.log("registering service %s for peer routing",t),u.push(n[At])),null!=n[Pt]&&(this.log("registering service %s for peer discovery",t),n[Pt].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 Mf(n))t[e]=!0;for(const n of Object.values(e.components))for(const e of Ff(n))if(!0!==t[e])throw new pf(`Service "${Rf(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 td;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 Qe("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Qe("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=jo(e.getComponents().findLast(e=>e.code===tu)?.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=Un([mr("/pk/"),e.toMultihash().bytes]),r=Fo(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 $m=65535,zm=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function Vm(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Gm(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Km(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 Hm(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 Wm(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Qm(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Ym=/* @__PURE__ */(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])(),Jm=(e,t)=>{function n(n,...r){if(Km(n,void 0,"key"),!Ym)throw new Error("Non little-endian hardware is not yet supported");void 0!==e.nonceLength&&Km(r[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");const i=e.tagLength;i&&void 0!==r[1]&&Km(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");Km(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,Km(e),a(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(Km(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 Zm(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 Xm(e){return Uint8Array.from(e)}const ey=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),ty=ey("expand 16-byte k"),ny=ey("expand 32-byte k"),ry=Wm(ty),iy=Wm(ny);function sy(e,t){return e<<t|e>>>32-t}function ay(e){return e.byteOffset%4==0}const oy=2**32-1,uy=Uint32Array.of();function dy(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 Gm(i),Gm(a),Vm(s),Vm(n),(t,o,u,d,c=0)=>{Km(t,void 0,"key"),Km(o,void 0,"nonce"),Km(u,void 0,"data");const l=u.length;if(void 0===d&&(d=new Uint8Array(l)),Km(d,void 0,"output"),Gm(c),c<0||c>=oy)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=Xm(t)),f=iy;else{if(16!==m||!n)throw Km(t,32,"arx key"),new Error("invalid key size");h=new Uint8Array(32),h.set(t),h.set(t,16),f=ry,p.push(h)}ay(o)||p.push(o=Xm(o));const y=Wm(h);if(r){if(24!==o.length)throw new Error("arx: extended nonce must be 24 bytes");r(f,y,Wm(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=Wm(o);return function(e,t,n,r,i,s,a,o){const u=i.length,d=new Uint8Array(64),c=Wm(d),l=ay(i)&&ay(s),p=l?Wm(i):uy,h=l?Wm(s):uy;for(let f=0;f<u;a++){if(e(t,n,r,c,a,o),a>=oy)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),Qm(...p),d}}function cy(e,t){return 255&e[t++]|(255&e[t++])<<8}class ly{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=cy(e=Xm(Km(e,32,"key")),0),n=cy(e,2),r=cy(e,4),i=cy(e,6),s=cy(e,8),a=cy(e,10),o=cy(e,12),u=cy(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]=cy(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=cy(e,t+0),b=cy(e,t+2),g=cy(e,t+4),v=cy(e,t+6),w=cy(e,t+8),T=cy(e,t+10),E=cy(e,t+12),P=cy(e,t+14);let x=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|P<<8)),R=i[9]+(P>>>5|r),_=0,L=_+x*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=_+x*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=_+x*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=_+x*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=_+x*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=_+x*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=_+x*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 $=_+x*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=_+x*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=_+x*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;Qm(n)}update(e){Hm(this),Km(e),e=Xm(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(){Qm(this.h,this.r,this.buffer,this.pad)}digestInto(e){Hm(this),function(e,t){Km(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 py=/** @__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 ly(e)))();function hy(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,P=o,x=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,_=sy(_^E,16),D=D+_|0,A=sy(A^D,12),E=E+A|0,_=sy(_^E,8),D=D+_|0,A=sy(A^D,7),P=P+C|0,L=sy(L^P,16),M=M+L|0,C=sy(C^M,12),P=P+C|0,L=sy(L^P,8),M=M+L|0,C=sy(C^M,7),x=x+k|0,N=sy(N^x,16),F=F+N|0,k=sy(k^F,12),x=x+k|0,N=sy(N^x,8),F=F+N|0,k=sy(k^F,7),S=S+I|0,O=sy(O^S,16),R=R+O|0,I=sy(I^R,12),S=S+I|0,O=sy(O^S,8),R=R+O|0,I=sy(I^R,7),E=E+C|0,O=sy(O^E,16),F=F+O|0,C=sy(C^F,12),E=E+C|0,O=sy(O^E,8),F=F+O|0,C=sy(C^F,7),P=P+k|0,_=sy(_^P,16),R=R+_|0,k=sy(k^R,12),P=P+k|0,_=sy(_^P,8),R=R+_|0,k=sy(k^R,7),x=x+I|0,L=sy(L^x,16),D=D+L|0,I=sy(I^D,12),x=x+I|0,L=sy(L^x,8),D=D+L|0,I=sy(I^D,7),S=S+A|0,N=sy(N^S,16),M=M+N|0,A=sy(A^M,12),S=S+A|0,N=sy(N^S,8),M=M+N|0,A=sy(A^M,7);let B=0;r[B++]=a+E|0,r[B++]=o+P|0,r[B++]=u+x|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 fy=/* @__PURE__ */dy(hy,{counterRight:!1,counterLength:4,allowShortKeys:!1}),my=/* @__PURE__ */new Uint8Array(16),yy=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(my.subarray(n))},by=/* @__PURE__ */new Uint8Array(32);function gy(e,t,n,r,i){void 0!==i&&Km(i,void 0,"AAD");const s=e(t,n,by),a=function(e,t,n){Vm(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=py.create(s);i&&yy(o,i),yy(o,r),o.update(a);const u=o.digest();return Qm(s,a),u}const vy=/* @__PURE__ */Jm({blockSize:64,nonceLength:12,tagLength:16},(wy=fy,(e,t,n)=>({encrypt(r,i){const s=r.length;(i=Zm(s+16,i,!1)).set(r);const a=i.subarray(0,-16);wy(e,t,a,a,1);const o=gy(wy,e,t,a,n);return i.set(o,s),Qm(o),i},decrypt(r,i){i=Zm(r.length-16,i,!1);const s=r.subarray(0,-16),a=r.subarray(-16),o=gy(wy,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)),wy(e,t,i,i,1),Qm(o),i}})));var wy;function Ty(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Ey(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 Py(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");Ty(e.outputLen),Ty(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 Sy(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ay(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Cy(e,t){return e<<32-t|e>>>t}const ky=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Iy=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Dy(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function My(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 Fy(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 Ry=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function _y(e,t,n){return e&t^~e&n}function Ly(e,t,n){return e&t^e&n^t&n}class Ny{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=Ay(this.buffer)}update(e){xy(this),Ey(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=Ay(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){Ey(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,Sy(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=Ay(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 Oy=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),By=/* @__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]),Uy=/* @__PURE__ */new Uint32Array(64);class jy extends Ny{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)Uy[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Uy[e-15],n=Uy[e-2],r=Cy(t,7)^Cy(t,18)^t>>>3,i=Cy(n,17)^Cy(n,19)^n>>>10;Uy[e]=i+Uy[e-7]+r+Uy[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+(Cy(a,6)^Cy(a,11)^Cy(a,25))+_y(a,o,u)+By[e]+Uy[e]|0,c=(Cy(n,2)^Cy(n,13)^Cy(n,22))+Ly(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(){Sy(Uy)}destroy(){this.set(0,0,0,0,0,0,0,0),Sy(this.buffer)}}class qy extends jy{A=0|Oy[0];B=0|Oy[1];C=0|Oy[2];D=0|Oy[3];E=0|Oy[4];F=0|Oy[5];G=0|Oy[6];H=0|Oy[7];constructor(){super(32)}}const $y=/* @__PURE__ */My(()=>new qy
|
|
4
|
-
/* @__PURE__ */,Ry(1)),zy=/* @__PURE__ */BigInt(0);function Vy(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?zy:BigInt("0x"+e)}(function(e){if(Ey(e),ky)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Iy[e[n]];return t}(Gy(Ey(e)).reverse()))}function Gy(e){return Uint8Array.from(e)}const Ky=e=>"bigint"==typeof e&&zy<=e;function Hy(e,t,n,r){if(!function(e,t,n){return Ky(e)&&Ky(t)&&Ky(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const Wy=/* @__PURE__ */BigInt(0);function Qy(e,t){const n=e%t;return n>=Wy?n:t+n}function Yy(e,t,n){let r=e;for(;t-- >Wy;)r*=r,r%=n;return r}function Jy(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 Zy=BigInt(0),Xy=BigInt(1),eb=BigInt(2),tb=BigInt(1),nb=BigInt(2),rb=/* @__PURE__ */BigInt(3),ib=BigInt(5),sb=(BigInt(8),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"));function ab(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const ob=/* @__PURE__ */(()=>{const e=sb;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||Fy,c=u?255:448,l=u?32:56,p=u?BigInt(9):BigInt(5),h=u?BigInt(121665):BigInt(39081),f=u?eb**BigInt(254):eb**BigInt(447),m=u?BigInt(8)*eb**BigInt(251)-Xy:BigInt(4)*eb**BigInt(445)-Xy,y=f+m+Xy,b=e=>Qy(e,r),g=v(p);function v(e){return function(e,t){return function(e,t){Ty(t);const n=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(ky)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=Dy(e.charCodeAt(i)),s=Dy(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(!Ky(e))throw new Error("positive bigint expected, got "+e)}else Ty(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){Hy("u",e,Zy,r),Hy("scalar",t,f,y);const n=t,i=e;let s=Xy,o=Zy,u=e,d=Xy,l=Zy;for(let e=BigInt(c-1);e>=Zy;e--){const t=n>>e&Xy;l^=t,({x_2:s,x_3:u}=x(l,s,u)),({x_2:o,x_3:d}=x(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}=x(l,s,u)),({x_2:o,x_3:d}=x(l,o,d));const p=a(o);return b(s*p)}(function(e){const t=Gy(Ey(e,l,"uCoordinate"));return u&&(t[31]&=127),b(Vy(t))}(t),function(e){return Vy(s(Gy(Ey(e,l,"scalar"))))}(e));if(n===Zy)throw new Error("invalid private or public key received");return v(n)}function T(e){return w(e,g)}const E=T,P=w;function x(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))=>(Ey(e,S.seed,"seed"),e),C={randomSecretKey:A};return Object.freeze({keygen:Jy(A,E),getSharedSecret:P,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=sb,a=e*e%s*e%s,o=Yy(a,nb,s)*a%s,u=Yy(o,tb,s)*e%s,d=Yy(u,ib,s)*u%s,c=Yy(d,t,s)*d%s,l=Yy(c,n,s)*c%s,p=Yy(l,r,s)*l%s,h=Yy(p,i,s)*p%s,f=Yy(h,i,s)*p%s,m=Yy(f,t,s)*d%s;return{pow_p_5_8:Yy(m,nb,s)*e%s,b2:a}}(t);return Qy(Yy(n,rb,e)*r,e)},adjustScalarBytes:ab})})();class ub{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Py(e),Ey(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),Sy(r)}update(e){return xy(this),this.iHash.update(e),this}digestInto(e){xy(this),Ey(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 db=(e,t,n)=>new ub(e,t).update(n).digest();db.create=(e,t)=>new ub(e,t);const cb=/* @__PURE__ */Uint8Array.of(0),lb=/* @__PURE__ */Uint8Array.of(),pb={hashSHA256:e=>$y(e.subarray()),getHKDF(e,t){const n=function(e,t,n){return Py(e),void 0===n&&(n=new Uint8Array(e.outputLen)),db(e,n,t)}($y,t,e),r=function(e,t,n,r=32){Py(e),Ty(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=lb:Ey(n,void 0,"info");const a=new Uint8Array(s*i),o=db.create(e,t),u=o._cloneInto(),d=new Uint8Array(o.outputLen);for(let e=0;e<s;e++)cb[0]=e+1,u.update(0===e?lb:d).update(n).update(cb).digestInto(d),a.set(d,i*e),o._cloneInto(u);return o.destroy(),u.destroy(),Sy(d,cb),a.slice(0,r)}($y,n,void 0,96),i=r;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){const e=ob.utils.randomSecretKey();return{publicKey:ob.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:ob.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>ob.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,n,r)=>vy(r,t,n).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,n,r,i)=>vy(r,t,n).decrypt(e.subarray(),i)},hb=pb,fb=e=>{const t=Bn(2);return t[0]=e>>8,t[1]=e,t};fb.bytes=2;const mb=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 yb(e,t){t.enabled&&zm&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${yr(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${yr(e.privateKey,"hex")}`)):t("Missing local static keys."))}function bb(e,t){t.enabled&&zm&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${yr(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${yr(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function gb(e,t){t.enabled&&zm&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${yr(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function vb(e,t,n){n.enabled&&zm&&(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&yr(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&yr(t.k,"hex")}`))}function wb(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");const n=Bn(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}mb.bytes=2;class Tb extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Tb.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Eb{n;bytes;view;constructor(e=0){this.n=e,this.bytes=On(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 Pb=On(0);class xb{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Eb(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 Sb{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const n=mr(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=On(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 zn(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,Pb);return[new xb(this.crypto,e),new xb(this.crypto,t)]}}class Ab{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 Sb(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 Cb extends Ab{writeMessageA(e){return new zn(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new zn(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new zn(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Tb(`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 Tb(`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 Tb(`handshake stage 2 validation fail: ${e.message}`)}}}var kb,Ib,Db,Mb,Fb;async function Rb(e,t,n){const r=await e.sign(Lb(t));return Ib.encode({identityKey:Ro(e.publicKey),identitySig:r,extensions:n})}async function _b(e,t,n){try{const r=Ib.decode(e),i=Fo(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=Lb(t);if(!await i.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(e){throw new He(e.message)}}function Lb(e){const t=mr("noise-libp2p-static-key:");return e instanceof Uint8Array?Un([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=Bp((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 Up('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 Up('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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(kb||(kb={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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),kb.codec().encode(e.extensions,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={identityKey:On(0),identitySig:On(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=kb.codec().decode(e,e.uint32(),{limits:n.limits?.extensions});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Ib||(Ib={}));class Nb extends Wd{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 bc({lengthDecoder:mb,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 zn;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(fb(r.byteLength)),t.append(r)}return t}decrypt(e){const t=new zn;for(let n=0;n<e.byteLength;n+=$m){let r,i=n+$m;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 Ob(e,t,n){return new Nb(e,t,n)}class Bb{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??hb;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??On(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[_t]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const n=e.log?.newScope("noise")??this.log,r=mc(e,{lengthEncoder:fb,lengthDecoder:mb,maxDataLength:$m}),i=await this.performHandshakeInitiator(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Fo(i.payload.identityKey);return{connection:Ob(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:qo(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 We("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=mc(e,{lengthEncoder:fb,lengthDecoder:mb,maxDataLength:$m}),i=await this.performHandshakeResponder(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Fo(i.payload.identityKey);return{connection:Ob(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:qo(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 Rb(s,o.publicKey,d),l=new Cb({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:a,s:o});yb(l.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(l.writeMessageA(Pb),t),n.trace("Stage 0 - Initiator finished sending first message."),bb(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."),gb(l.re,n),h=l.rs,(f=n).enabled&&zm&&f(h?`REMOTE_STATIC_PUBLIC_KEY ${yr(h.subarray(),"hex")}`:"Missing remote static public key."),n.trace("Initiator going to check remote's signature...");const m=await _b(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 vb(y,b,n),{payload:m,encrypt:e=>y.encryptWithAd(Pb,e),decrypt:(e,t)=>b.decryptWithAd(Pb,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 Rb(s,o.publicKey,d),l=new Cb({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:a,s:o});yb(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."),gb(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."),bb(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 _b(p,l.rs,u),[f,m]=l.ss.split();return vb(f,m,n),{payload:h,encrypt:e=>m.encryptWithAd(Pb,e),decrypt:(e,t)=>f.decryptWithAd(Pb,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 Ub(e={}){return t=>new Bb(t,e)}!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(Db||(Db={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(Mb||(Mb={})),Object.values(Mb).filter(e=>"string"!=typeof e),function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(Fb||(Fb={}));const jb=12;class qb extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}}class $b extends qb{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Fb.ProtocolError),this.name="InvalidFrameError"}}class zb extends qb{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Fb.ProtocolError),this.name="UnRequestedPingError"}}class Vb extends qb{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Fb.ProtocolError),this.name="NotMatchingPingError"}}class Gb extends qb{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Fb.ProtocolError),this.name="ReceiveWindowExceededError"}}const Kb=262144,Hb=2**24;class Wb{buffer;constructor(){this.buffer=new zn}*emitFrames(e){for(this.buffer.append(e);;){const e=this.readFrame();if(void 0===e)break;yield e}}readFrame(){let e=jb;if(this.buffer.byteLength<jb)return;const t=function(e){if(0!==e[0])throw new $b("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*Hb+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*Hb+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,jb));if(t.type===Db.Data){if(e+=t.length,this.buffer.byteLength<e)return;const n=this.buffer.sublist(jb,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}}function Qb(e){const t=new Uint8Array(jb);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 Yb;!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"}(Yb||(Yb={}));class Jb extends Jd{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){const t=e.initialStreamWindowSize??Kb;super({...e,maxMessageSize:t-jb}),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=Yb.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:Db.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:Db.WindowUpdate,flag:Mb.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){const e=this.getSendFlags()|Mb.FIN;this.sendFrame({type:Db.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Yb.Paused}sendResume(){this.state=Yb.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-jb,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===Db.Data&&null!==e.data}(e))throw new $b("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Gb("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&Mb.ACK)===Mb.ACK&&this.state===Yb.SYNSent&&(this.state=Yb.Established),(e&Mb.FIN)===Mb.FIN&&this.onRemoteCloseWrite(),(e&Mb.RST)===Mb.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Yb.Init:return this.state=Yb.SYNSent,Mb.SYN;case Yb.SYNReceived:return this.state=Yb.Established,Mb.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Yb.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:Db.WindowUpdate,flag:e,streamID:this.streamId,length:r})}}function Zb(e){return{type:Db[e.type],flags:[(e.flag&Mb.SYN)===Mb.SYN?"SYN":void 0,(e.flag&Mb.ACK)===Mb.ACK?"ACK":void 0,(e.flag&Mb.FIN)===Mb.FIN?"FIN":void 0,(e.flag&Mb.RST)===Mb.RST?"RST":void 0].filter(Boolean),streamID:e.streamID,length:e.length}}const Xb="/yamux/1.0.0";class eg{protocol=Xb;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[_t]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new tg(e,{...this._init})}}class tg extends Yd{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:Xb,name:"yamux"}),this.client="outbound"===e.direction,function(e){if(null!=e.keepAliveInterval&&e.keepAliveInterval<=0)throw new Qe("keep-alive interval must be positive");if(null!=e.maxInboundStreams&&e.maxInboundStreams<0)throw new Qe("max inbound streams must be larger or equal 0");if(null!=e.maxOutboundStreams&&e.maxOutboundStreams<0)throw new Qe("max outbound streams must be larger or equal 0");if(null!=e.maxMessageSize&&e.maxMessageSize<1024)throw new Qe("MaxMessageSize must be greater than a kilobyte");if(null!=e.streamOptions?.initialStreamWindowSize&&e.streamOptions?.initialStreamWindowSize<Kb)throw new Qe("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 Qe("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(null!=e.streamOptions?.maxStreamWindowSize&&e.streamOptions?.maxStreamWindowSize>2**32-1)throw new Qe("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 Wb,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=kc(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 Xe("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Xe("Muxer closed locally");const e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new bt("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);const t=this._newStream(e,Yb.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(void 0!==this.remoteGoAway)throw new Xe("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Xe("Muxer closed locally");if(null!=this.activePing)return zd(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 zd(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??Fb.NormalTermination;this.log.trace("muxer close reason=%s",Fb[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if("open"===this.status)try{super.abort(e);let t=Fb.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 Qe("Stream already exists with that id");const r=new Jb({...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",Zb(e.header)),0===t)switch(n){case Db.Ping:return void this.handlePing(e.header);case Db.GoAway:return void this.handleGoAway(r);default:throw new $b("Invalid frame type")}else switch(e.header.type){case Db.Data:case Db.WindowUpdate:return void this.handleStreamMessage(e);default:throw new $b("Invalid frame type")}}handlePing(e){if(e.flag===Mb.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Mb.ACK);else{if(e.flag!==Mb.ACK)throw new $b("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 zb("ping not requested");if(this.activePing.id!==e)throw new Vb("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Fb[e]??"unknown"),this.remoteGoAway=e,e===Fb.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){const{streamID:t,flag:n,type:r}=e.header;(n&Mb.SYN)===Mb.SYN&&this.incomingStream(t);const i=this.streams.find(e=>e.streamId===t);if(void 0!==i)switch(r){case Db.WindowUpdate:return void i.handleWindowUpdate(e);case Db.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 Qe("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:Db.WindowUpdate,flag:Mb.RST,streamID:e,length:0});if(this.numInboundStreams>=this.maxInboundStreams)return this.log("maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:Db.WindowUpdate,flag:Mb.RST,streamID:e,length:0});const t=this._newStream(e,Yb.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Db.Data){if(null==t)throw new $b("Invalid frame");n=new zn(Qb(e),t)}else n=Qb(e);return this.log.trace("sending frame %o",Zb(e)),this.send(n)}sendPing(e,t=Mb.SYN){this.log.trace(t===Mb.SYN?"sending ping request pingId=%s":"sending ping response pingId=%s",e),this.sendFrame({type:Db.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Fb.NormalTermination){this.log("sending GoAway reason=%s",Fb[e]),this.localGoAway=e,this.sendFrame({type:Db.GoAway,flag:0,streamID:0,length:e})}}function ng(e={}){return()=>new eg(e)}const rg=[6,53,56,54,55];function ig(e){return ag("sni",e)?.value}function sg(e){const t=ag("tcp",e)?.value;return null==t?"":`:${t}`}function ag(e,t){return t.find(t=>t.name===e)}function og(e){return e.some(({code:e})=>e===nu)}function ug(e,t){const n=dg[e.name];if(null==n)throw new Error(`Can't interpret protocol ${e.name}`);const r=n(e,t);return e.code===eu?`[${r}]`:r}const dg={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://${ug(n,t)}:${e.value}`},udp:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`udp://${ug(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`${ug(n,t)}`},p2p:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${ug(n,t)}`},http:(e,t)=>{const n=og(t),r=ig(t),i=sg(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=ug(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`${ug(n,t)}${decodeURIComponent(e.value??"")}`},tls:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return ug(n,t)},sni:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return ug(n,t)},https:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=ug(n,t);return r=r?.replace("tcp://",""),`https://${r}`},ws:(e,t)=>{const n=og(t),r=ig(t),i=sg(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=ug(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=ug(n,t);return r=r?.replace("tcp://",""),`wss://${r}`}};class cg extends Qd{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??4194304,this.checkBufferedAmountTask=kc(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=mr(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 lg{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"})})}[Mt]=!0;[Symbol.toStringTag]="@libp2p/websockets";[_t]=["@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 cg(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=Su(e).getComponents(),n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");const r=dg[n.name];if(null==r)throw new Error(`No interpreter found for ${n.name}`);let i=r(n,t)??"";return rg.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 Lf("websockets:open-connection")),await Ld(r,"open",t)}catch(e){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Ze(`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=>zh.exactMatch(e)||Gh.exactMatch(e))}dialFilter(e){return this.listenFilter(e)}}function pg(e={}){return t=>new lg(t,e)}class hg{constructor(){throw new Error("TCP connections are not possible in browsers")}[Mt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[_t]=["@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 fg(e={}){return t=>new hg(t,e)}const mg=`${Ct}-circuit-relay`;BigInt(1<<17);const yg="/libp2p/circuit/relay/0.2.0/hop",bg="/libp2p/circuit/relay/0.2.0/stop",gg=new Float32Array([-0]),vg=new Uint8Array(gg.buffer);function wg(e,t,n){gg[0]=e,t[n]=vg[0],t[n+1]=vg[1],t[n+2]=vg[2],t[n+3]=vg[3]}const Tg=new Float64Array([-0]),Eg=new Uint8Array(Tg.buffer);function Pg(e,t,n){Tg[0]=e,t[n]=Eg[0],t[n+1]=Eg[1],t[n+2]=Eg[2],t[n+3]=Eg[3],t[n+4]=Eg[4],t[n+5]=Eg[5],t[n+6]=Eg[6],t[n+7]=Eg[7]}const xg=BigInt(Number.MAX_SAFE_INTEGER),Sg=BigInt(Number.MIN_SAFE_INTEGER);class Ag{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 Cg;if(e<xg&&e>Sg)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>kg&&(r=0n,++n>kg&&(n=0n))),new Ag(Number(r),Number(n))}static fromNumber(e){if(0===e)return Cg;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 Ag(n,r)}static from(e){return"number"==typeof e?Ag.fromNumber(e):"bigint"==typeof e?Ag.fromBigInt(e):"string"==typeof e?Ag.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Ag(e.low>>>0,e.high>>>0):Cg}}const Cg=new Ag(0,0);Cg.toBigInt=function(){return 0n},Cg.zzEncode=Cg.zzDecode=function(){return this},Cg.length=function(){return 1};const kg=4294967296n;function Ig(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 Dg(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Mg(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Fg{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,Dg(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 Dg(this,4);return Mg(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Dg(this,4);return 0|Mg(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Dg(this,4);const e=(vg[0]=(t=this.buf)[n=this.pos],vg[1]=t[n+1],vg[2]=t[n+2],vg[3]=t[n+3],gg[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Dg(this,4);const e=(Eg[0]=(t=this.buf)[n=this.pos],Eg[1]=t[n+1],Eg[2]=t[n+2],Eg[3]=t[n+3],Eg[4]=t[n+4],Eg[5]=t[n+5],Eg[6]=t[n+6],Eg[7]=t[n+7],Tg[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 Dg(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 Dg(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Dg(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 Ag(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Dg(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 Dg(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 Dg(this,8);const e=Mg(this.buf,this.pos+=4),t=Mg(this.buf,this.pos+=4);return new Ag(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=ga(this.buf,this.pos);return this.pos+=ya(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 Rg(e){return new Fg(e instanceof Uint8Array?e:e.subarray())}function _g(e,t,n){const r=Rg(e);return t.decode(r,void 0,n)}class Lg{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Ng(){}class Og{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Bg=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Bn(r);n+r>e&&(t=Bn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class Ug{len;head;tail;states;constructor(){this.len=0,this.head=new Lg(Ng,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Lg(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $g((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(zg,10,Ag.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Ag.fromBigInt(e);return this._push(zg,t.length(),t)}uint64Number(e){return this._push(ba,ya(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=Ag.fromBigInt(e).zzEncode();return this._push(zg,t.length(),t)}sint64Number(e){const t=Ag.fromNumber(e).zzEncode();return this._push(zg,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(jg,1,e?1:0)}fixed32(e){return this._push(Vg,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Ag.fromBigInt(e);return this._push(Vg,4,t.lo)._push(Vg,4,t.hi)}fixed64Number(e){const t=Ag.fromNumber(e);return this._push(Vg,4,t.lo)._push(Vg,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(wg,4,e)}double(e){return this._push(Pg,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(jg,1,0):this.uint32(t)._push(Gg,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(Ig,t,e):this._push(jg,1,0)}fork(){return this.states=new Og(this),this.head=this.tail=new Lg(Ng,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 Lg(Ng,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?Bn(n):Bg(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function jg(e,t,n){t[n]=255&e}function qg(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class $g extends Lg{next;constructor(e,t){super(qg,e,t),this.next=void 0}}function zg(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 Vg(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 Gg(e,t,n){t.set(e,n)}function Kg(e,t,n){t.set(e,n)}function Hg(e,t,n){e.length<40?Ig(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(mr(e),n)}function Wg(e,t){const n=new Ug;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*Qg(e,t,n){const r=Rg(e);yield*t.stream(r,void 0,"$",n)}function Yg(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function Jg(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Yg("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 Zg(e,t,n){return Yg("message",2,e,t,n)}null!=globalThis.Buffer&&(Ug.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Kg,t,e),this},Ug.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Hg,t,e),this});class Xg extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var ev,tv,nv,rv,iv,sv,av,ov,uv;!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=()=>Jg(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Zg((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),nv.codec().encode(t.peer,n)),null!=t.reservation&&(n.uint32(26),rv.codec().encode(t.reservation,n)),null!=t.limit&&(n.uint32(34),iv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(40),sv.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=nv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.reservation=rv.codec().decode(t,t.uint32(),{limits:r.limits?.reservation});break;case 4:i.limit=iv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 5:i.status=sv.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*nv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*rv.codec().stream(t,t.uint32(),`${r}.reservation`,{limits:i.limits?.reservation});break;case 4:yield*iv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 5:yield{field:`${r}.status`,value:sv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(ev||(ev={})),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=()=>Jg(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Zg((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),nv.codec().encode(t.peer,n)),null!=t.limit&&(n.uint32(26),iv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(32),sv.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=nv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.limit=iv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 4:i.status=sv.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*nv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*iv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 4:yield{field:`${r}.status`,value:sv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(tv||(tv={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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:On(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 Xg('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 Xg('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 Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(nv||(nv={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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),uv.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 Xg('Decode error - repeated field "addrs" had too many elements');r.addrs.push(e.bytes());break;case 3:r.voucher=uv.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 Xg('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*uv.codec().stream(e,e.uint32(),`${n}.voucher`,{limits:r.limits?.voucher});break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(rv||(rv={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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 Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(iv||(iv={})),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"}(sv||(sv={})),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"}(av||(av={})),function(e){e.codec=()=>Jg(av)}(sv||(sv={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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:On(0),peer:On(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 Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(ov||(ov={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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),ov.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:On(0),payloadType:On(0),signature:On(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=ov.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*ov.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 Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(uv||(uv={}));class dv extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"}class cv extends Error{static name="DoubleRelayError";name="DoubleRelayError"}class lv extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"}function pv(e){const t=e*BigInt(1e3),n=(new Date).getTime();return Number(t-BigInt(n))}class hv{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 fv=Th(wh(Jh.matchers[0],yh(au))),mv=Th(yh(au));class yv extends Rt{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(yg,{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(yg)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{const n=bv(e),r=bv(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=Zd([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}}function bv(e){const t=e.metadata.get("last-dial-success");return null==t?0:new Date(yr(t)).getTime()}class gv extends Rt{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(mv.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else{if(!fv.exactMatch(e))throw new ft(`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=>Su(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}}class vv extends Rt{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 ed,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??5e3,this.started=!1,this.relayFilter=hd(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(mg)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async e=>{await this.peerStore.merge(e.id,{tags:{[mg]: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 ft("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new lv("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 ft("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&&pv(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 dv("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(Xh.matches(i.remoteAddr))throw new cv("not creating reservation over relayed connection");const s=await this.#X(i,{signal:r}),a=pv(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 dv("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:{[mg]:{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(yg,t),r=yc(n).pb(ev);let i;this.log.trace("send RESERVE to %p",e.remotePeer),await r.write({type:ev.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===sv.OK&&null!=i.reservation){const t=new Set;t.add(e.remoteAddr.toString());for(const n of i.reservation.addrs){let r=Su(n);null==r.getComponents().find(e=>e.code===tu)&&(r=r.encapsulate(`/p2p/${e.remotePeer}`)),r=Su(r.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),t.add(r.toString())}return i.reservation.addrs=[...t].map(e=>Su(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:{[mg]: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=hd(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}}class wv extends Qd{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 Tv(e){return new wv(e)}class Ev{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 yv(e,{filter:t.discoveryFilter??Fc(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 vv(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";[_t]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Lt](){return null!=this.discovery?["@libp2p/identify"]:[]}[Mt]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.components.registrar.handle(bg,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await It(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Dt(this.discovery,this.reservationStore),await this.components.registrar.unhandle(bg),this.started=!1}async dial(e,t){const n=e.toString().split("/p2p-circuit"),r=Su(n[0]),i=Su(n[n.length-1]),s=r.getComponents().find(e=>e.code===tu)?.value,a=i.getComponents().find(e=>e.code===tu)?.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 ht(`C${t}`)}const o=jo(s),u=jo(a);let d,c=this.components.connectionManager.getConnections(o)[0];null==c?(await this.components.peerStore.merge(o,{multiaddrs:[r]}),t.onProgress?.(new Lf("circuit-relay:open-connection")),c=await this.components.connectionManager.openConnection(o,t)):t.onProgress?.(new Lf("circuit-relay:reuse-connection"));try{t.onProgress?.(new Lf("circuit-relay:open-hop-stream")),d=await c.newStream(yg,t);const n=yc(d).pb(ev);t.onProgress?.(new Lf("circuit-relay:write-connect-message")),await n.write({type:ev.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Su(i).bytes]}},t),t.onProgress?.(new Lf("circuit-relay:read-connect-response"));const s=await n.read(t);if(s.status!==sv.OK)throw new dt(`failed to connect via relay with status ${s?.status?.toString()??"undefined"}`);const a=new hv(s.limit),o=Tv({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 gv(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=>fv.exactMatch(e)||mv.exactMatch(e))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter(e=>Xh.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=yc(e).pb(tv),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:tv.Type.STATUS,status:sv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});if(i.type!==tv.Type.CONNECT)return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:tv.Type.STATUS,status:sv.UNEXPECTED_MESSAGE},{signal:n}),void await e.close({signal:n});if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(Su)}catch{return!1}return!0})(i))return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:tv.Type.STATUS,status:sv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});const s=$o(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:tv.Type.STATUS,status:sv.PERMISSION_DENIED},{signal:n}),void await e.close({signal:n});this.log.trace("sending success response to %p",t.remotePeer),await r.write({type:tv.Type.STATUS,status:sv.OK},{signal:n});const a=new hv(i.limit),o=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),u=this.components.addressManager.getAddresses()[0],d=Tv({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 Pv(e={}){return t=>new Ev(t,e)}class xv extends Rt{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=>Su(e)).filter(e=>{if(!Jh.matches(e))return this.log.error("invalid multiaddr %a",e),!1;const t=e.getComponents().findLast(e=>e.code===tu)?.value;return null!=t||(this.log.error("invalid bootstrap multiaddr without peer id"),!1)}).map(e=>({id:jo(e.getComponents().findLast(e=>e.code===tu)?.value??""),multiaddrs:[e]})),this._init=t}[Pt]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[_t]=["@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 Sv;!function(e){let t;e.codec=()=>(null==t&&(t=Bp((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 Up('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 Up('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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Sv||(Sv={}));const Av="ipfs";class Cv{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??Av}/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:mr(this.host.agentVersion),ProtocolVersion:mr(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 kv extends Cv{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Av}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??1)&&e.events.addEventListener("connection:open",e=>{this.identify(e.detail).catch(()=>{})})}[_t]=["@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=yc(n,{maxDataLength:this.maxMessageSize}).pb(Sv),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 dt("Public key was missing from identify message");const a=zo(Fo(r).toCID());if(!e.remotePeer.equals(a))throw new dt("Identified peer does not match the expected peer");if(this.components.peerId.equals(a))throw new dt("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 dt("message was null or undefined");const s={};if(i.listenAddrs.length>0&&(s.addresses=i.listenAddrs.map(e=>({isCertified:!1,multiaddr:Su(e)}))),i.protocols.length>0&&(s.protocols=i.protocols),null!=i.publicKey){const e=Fo(i.publicKey);if(!qo(e).equals(r.remotePeer))throw new dt("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 bl.openAndCertify(t,Tl.DOMAIN);let u=Tl.createFromProtobuf(o.payload);const d=zo(o.publicKey.toCID());if(!u.peerId.equals(d))throw new dt("signing key does not match PeerId in the PeerRecord");if(!r.remotePeer.equals(u.peerId))throw new dt("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=bl.createFromProtobuf(c.peerRecordEnvelope),r=Tl.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=mr(i.agentVersion)),null!=i.protocolVersion&&(t.ProtocolVersion=mr(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=>Su(e)),observedAddr:null==i.observedAddr?void 0:Su(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 Su(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),Cd(t))return;const n=t.getComponents();n[0].code!==eu&&(42!==n[0].code||n[1].code!==eu)||function(e){try{const n=fd(e);return"ip6"===n.type&&(t=n.host,new gd("2000::/3").contains(t))}catch{return!1}var t}(t)?Nh.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(tu));let a=i.peerRecordEnvelope;if(s.length>0&&null==a){const e=new Tl({peerId:this.components.peerId,multiaddrs:s});a=(await bl.seal(e,this.components.privateKey,{signal:r})).marshal().subarray()}let o=t.remoteAddr.bytes;Mh.matches(t.remoteAddr)||(o=void 0);const u=yc(e).pb(Sv);n("send response"),await u.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Ro(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 Iv(e={}){return t=>new kv(t,e)}const Dv=36e5,Mv=48*Dv,Fv=Dv,Rv=Dv,_v=`${Ct}-kad-dht`;var Lv,Nv,Ov,Bv,Uv,jv,qv,$v;function zv(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=Bp((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:On(0),value:On(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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Lv||(Lv={}));class Vv{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 Lv.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:zv(this.timeReceived)}}static deserialize(e){const t=Lv.decode(e);return new Vv(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 Vv(e.key,e.value,t)}}function Gv(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=ch(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 Kv extends Error{constructor(e="Query error"){super(e),this.name="QueryError"}}class Hv extends Error{constructor(e="Invalid record"){super(e),this.name="InvalidRecordError"}}class Wv extends Error{constructor(e="No selector function configured for prefix"){super(e),this.name="MissingSelectorError"}}function Qv(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 Yv(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 Jv(e,t={}){const n={...e,name:"FINAL_PEER",type:2};return t.onProgress?.(new CustomEvent("kad-dht:query:final-peer",{detail:n})),n}function Zv(e,t={}){const n={...e,name:"QUERY_ERROR",type:3};return t.onProgress?.(new CustomEvent("kad-dht:query:query-error",{detail:n})),n}function Xv(e,t={}){const n={...e,name:"PROVIDER",type:4};return t.onProgress?.(new CustomEvent("kad-dht:query:provider",{detail:n})),n}function ew(e,t={}){const n={...e,name:"VALUE",type:5};return t.onProgress?.(new CustomEvent("kad-dht:query:value",{detail:n})),n}function tw(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=Bp((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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Nv||(Nv={})),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"}(Ov||(Ov={})),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"}(Bv||(Bv={})),function(e){e.codec=()=>Op(Bv)}(Ov||(Ov={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(Uv||(Uv={})),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"}(jv||(jv={})),function(e){e.codec=()=>Op(jv)}(Uv||(Uv={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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),Uv.codec().encode(e.connection,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={id:On(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 Up('Decode error - map field "multiaddrs" had too many elements');r.multiaddrs.push(e.bytes());break;case 3:r.connection=Uv.codec().decode(e);break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(qv||(qv={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.type&&0!==Bv[e.type]&&(t.uint32(8),Ov.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),qv.codec().encode(n,t);if(null!=e.providers)for(const n of e.providers)t.uint32(74),qv.codec().encode(n,t);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={type:Ov.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=Ov.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 Up('Decode error - map field "closer" had too many elements');r.closer.push(qv.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 Up('Decode error - map field "providers" had too many elements');r.providers.push(qv.codec().decode(e,e.uint32(),{limits:n.limits?.providers$}));break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}($v||($v={}));const nw={pk:function(e,t){return 0}};async function rw(e,t,n){const r=t.key,i=yr(r).split("/");if(i.length<3)return;const s=e[i[1].toString()];if(null==s)throw new Qe(`No validator available for key type "${i[1]}"`);await s(r,t.value,n)}const iw={pk:async(e,t,n)=>{if(!(e instanceof Uint8Array))throw new Qe('"key" must be a Uint8Array');if(e.byteLength<5)throw new Qe("Invalid public key record");if("/pk/"!==yr(e.subarray(0,4)))throw new Qe("key was not prefixed with /pk/");const r=Fo(t);if(!Nn(e.slice(4),r.toMultihash().bytes))throw new Qe("public key does not match passed in key")}},sw=mr("/pk/");function aw(e){return{...e,multiaddrs:e.multiaddrs.filter(e=>!Cd(e))}}async function ow(e,t){const n=await dr.digest(e);return t?.signal?.throwIfAborted(),n.digest}async function uw(e,t){return ow(e.toMultihash().bytes,t)}function dw(e,t){return new Qp(`${e}/${yr(t,"base32")}`,!1)}function cw(e,t){const n=new Date;return new Vv(e,t,n).serialize()}function lw(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:In.createV1(85,xn(mr(r,"base32"))),peerId:jo(n)}}function pw(e,t,n){const r=[e,"string"==typeof t?t:yr(t.multihash.bytes,"base32")];return null!=n&&r.push(n.toString()),new Qp(r.join("/"))}function hw(e){return new Date(wa(e))}function fw(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 mw(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 yw{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=dw(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=Vv.deserialize(r);return await rw(this.validators,i,t),i}async*sendCorrectionRecord(e,t,n,r){this.log("sendCorrection for %b",e);const i=cw(e,n);for(const{value:s,from:a}of t){if(Nn(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{const t=dw(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:Ov.PUT_VALUE,key:e,record:i};for await(const e of this.network.sendRequest(a,o,r))"PEER_RESPONSE"===e.name&&null!=e.record&&Nn(e.record.value,Vv.deserialize(i).value)&&(t=!0),yield e;if(!t)throw new Kv("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=cw(e,t),i=dw(this.datastorePrefix,e);this.log(`storing record for key ${i.toString()}`),await this.components.datastore.put(i,r.subarray(),n),yield*rc(this.peerRouting.getClosestPeers(e,{...n,signal:n.signal}),t=>Gv(t,t=>async()=>{if("FINAL_PEER"!==t.name)return[t];const i=[],s={type:Ov.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&&Nn(e.record.value,Vv.deserialize(r).value)||i.push(Zv({from:t.peer.id,error:new Kv("Value not put correctly"),path:e.path},n)));return i}),e=>Am(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 Qe("No records given");const r=yr(t).split("/");if(r.length<3)throw new Qe("Record key does not have a selector function");const i=e[r[1].toString()];if(null==i)throw new Wv(`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 rt("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 ew({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 ew({from:r.id,value:a.record.value,path:s},t))},t)}}function bw(e,t){const n={id:e.id.toMultihash().bytes,multiaddrs:(e.multiaddrs??[]).map(e=>e.bytes),connection:t};return n}function gw(e){if(null==e.id)throw new Error("Invalid peer in message");return{id:$o(xn(e.id)),multiaddrs:(e.multiaddrs??[]).map(e=>Su(e))}}class vw{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:Ov.ADD_PROVIDER,key:r,providers:[bw({id:this.components.peerId,multiaddrs:t})]};let s=0;const a=this,o=Fd({objectMode:!0}),u=new Kd({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 Zv({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 Yv({from:this.components.peerId,messageType:Ov.GET_PROVIDERS,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),yield Xv({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:Ov.GET_PROVIDERS,key:i};yield*s.network.sendRequest(e.id,a,{...t,signal:n,path:r})},u=new td(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 Xv({from:s.from,providers:i,path:s.path},t),r+=i.length,r>=n))return}}}class ww extends Rt{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 ec({...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 Qe("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 tw({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 Qv({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 Yv({from:e,messageType:s.type,closer:s.closer.map(gw),providers:s.providers.map(gw),record:null==s.record?void 0:Vv.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 Zv({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 Qe("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 tw({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 Qv({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 Yv({from:e,messageType:r,path:n.path},n)}catch(t){this.metrics.errors?.increment({[r]:!0}),i?.abort(t),yield Zv({from:e,error:t,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async _writeMessage(e,t,n){const r=yc(e);await r.write(t,$v,n)}async _writeReadMessage(e,t,n){const r=yc(e);await r.write(t,$v,n);const i=await r.read($v,n);return i.closer.forEach(e=>{this.safeDispatchEvent("peer",{detail:gw(e)})}),i.providers.forEach(e=>{this.safeDispatchEvent("peer",{detail:gw(e)})}),i}}function Tw(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 Ew{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 uw(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:wb(this.originDhtKey,t),path:n};if(this.peerDistances.length===this.capacity){const e=this.peerDistances[this.peerDistances.length-1];if(null!=e&&-1!==Tw(r.distance,e.distance))return}let i=!1;for(let e=0;e<this.peerDistances.length;e++){const t=Tw(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===Tw(wb(await uw(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 Pw{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:Ov.GET_VALUE,key:t};yield*this.network.sendRequest(e,r,n)}async*getPublicKeyFromNode(e,t={}){const n=Un([sw,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=qo(Fo(i.record.value));if(!n.equals(e))throw new Ye("public key does not match id");if(null==n.publicKey)throw new Ye("public key missing");yield ew({from:e,value:i.record.value,path:r},t)}throw new Kv(`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 Jv({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:Ov.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 Jv({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 rt("Not found")}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);const n=await ow(e,t),r=new Ew(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:Ov.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 Jv({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 Zv({from:r.from,error:new Kv(t),path:n.path},n);continue}yield r}}async _verifyRecordOnline(e,t){if(null==e.timeReceived)throw new Hv("invalid record received");await rw(this.validators,new Vv(e.key,e.value,e.timeReceived),t)}async getClosestPeersOffline(e,t){const n=[];try{const r=$o(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 ow(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=pw(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=pw(this.datastorePrefix,e,t),i=va(n?.time?.getTime()??Date.now());await this.datastore.put(r,i,n)}async loadProviders(e,t){const n=new ed,r=pw(this.datastorePrefix,e);for await(const e of this.datastore.query({prefix:r.toString()},t)){const{peerId:t}=lw(e.key);n.set(t,hw(e.value))}return n}}async function*Sw(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=Fd({objectMode:!0}),h=new Kd({concurrency:s,sort:(e,t)=>Tw(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 Ke)};l.addEventListener("abort",f);try{const y=await ow(t,{signal:l});function m(n,s){if(null==n)return;d.add(n.id.toMultihash().bytes);const f=wb(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 uw(e.id,{signal:l});-1===Tw(wb(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(Zv({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 uw(e,{signal:l}))})),yield*p}finally{l.removeEventListener("abort",f)}}class Aw{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=Zd([this.shutDownController.signal,r.signal,n.signal]),s=this.logger.forComponent(`${this.logPrefix}:query:`+yr(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 Ld(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 zd(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),s("query:start");const r=await ow(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=hd(1024),c=u.map((r,a)=>Sw({...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 nc(...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 Cw(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 kw{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=mw(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=kd(),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=Zd(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 rc(this.peerRouting.getClosestPeers(this.peerId.toMultihash().bytes,{signal:t,isSelfQuery:!0}),e=>hh(e,this.count),async e=>Cw(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 Iw extends Rt{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 Kd({concurrency:t.concurrency??10,metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_queue`}),this.reprovideTimeout=new ec({...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??Mv,this.interval=t.interval??Fv,this.contentRouting=t.contentRouting,this.running=!1,this.reprovide=mw(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(Rv)}).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}=lw(t.key),i=hw(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(Rv)}).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 dh(this.contentRouting.provide(e,this.addressManager.getAddresses(),t))}}class Dw{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 td,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}async start(){if(this.running)return;this.running=!0;const e=await uw(this.components.peerId);this.newPeers=new Ew(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 td(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},[_v]:{value:1}}})}),...[...n].map(async e=>{await this.components.peerStore.merge(e,{tags:{[this.closeTagName]:void 0,[_v]:void 0}})})])}}function Mw(e){return Array.isArray(e?.peers)}class Fw{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??_w,this.kBucketSize=t.kBucketSize??Rw,this.splitThreshold=t.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=t.numberOfOldContactsToPing??Lw,this.lastPingThreshold=t.lastPingThreshold??Ow,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=_c({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 uw(e,t),lastPing:Date.now()}}async add(e,t){const n={peerId:e,kadId:await uw(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 Ew(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*Gv(n.peers,({peer:e})=>e.id)}count(){return function e(t){if(Mw(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){Mw(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+yr(wb(e,t),"base16"))}_determineBucket(e){const t=yr(e,"base2");return function e(n,r=0){return Mw(n)?n:e("0"===t[r]?n.left:n.right,r+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex(e=>Nn(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"===yr(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 Rw=20,_w=6,Lw=3,Nw="kad-peer",Ow=6e5;class Bw extends Rt{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??Rw,this.running=!1,this.protocol=t.protocol,this.network=t.network,this.peerTagName=t.peerTagName??Nw,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 ec({...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 ec({...t.pingNewContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_new_contact_time_milliseconds`}),this.kb=new Fw(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 Dw(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 It(this.closestPeerTagger,this.kb))}async afterStart(){let e=0;Promise.resolve().then(async()=>{if(!this.populateFromDatastoreOnStart)return;const t=Zd([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(Nw)],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 Dt(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=Zd([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 Am(n))null!=e&&(yield e)}async verifyNewContact(e,t){const n=this.pingNewContactTimeout.getTimeoutSignal(),r=Zd([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 uw(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 uw(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(Mw(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 Uw,jw=[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 qw{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=Zd([r?.signal,AbortSignal.timeout(this.refreshQueryTimeout)]);try{const t=await Cw(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=so(2);return $o(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=jw[(r^32768>>n)&i|t&~i],a=new ArrayBuffer(34),o=new DataView(a,0,a.byteLength);return o.setUint8(0,dr.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=wb(this.routingTable.kb.localPeer.kadId,e);let n=0;for(const e of t){if(0!==e)break;n++}yield n}}}class $w{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 dt("Missing key");let n;try{n=In.decode(t.key)}catch(e){throw new dt("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=$o(xn(t.id)),i=t.multiaddrs.map(e=>Su(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 zw{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 dt("Invalid FIND_NODE message received - key was missing");const n=await this.peerRouting.getClosestPeersOffline(t.key,{exclude:[e,this.peerId]});Nn(this.peerId.toMultihash().bytes,t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map(e=>e.decapsulateCode(tu))});const r={type:Ov.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 Vw{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 dt("Invalid GET_PROVIDERS message received - key was missing");let n;try{n=In.decode(t.key)}catch(e){throw new dt("Invalid CID")}this.log("%p asking for providers for %s",e,n);const[r,i]=await Promise.all([El(Gv(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:Ov.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 Gw{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 dt("Invalid key");const r={type:Ov.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===yr(e.subarray(0,4))}(n)){this.log("is public key");const e=function(e){return $o(xn(e.subarray(4)))}(n);let t;try{const n=await this.peerStore.get(e);if(null==n.id.publicKey)throw new rt("No public key found in key book");t=Ro(n.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=t)return this.log("returning found public key"),r.record=new Vv(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=dw(this.datastorePrefix,e);let n;try{n=await this.datastore.get(t)}catch(e){if("NotFoundError"===e.name)return;throw e}const r=Vv.deserialize(n);if(!(null==r.timeReceived||Date.now()-r.timeReceived.getTime()>Mv))return r;await this.datastore.delete(t)}}class Kw{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 Hw{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 dt(`Empty record from: ${e}`);try{const e=Vv.deserialize(t.record);await rw(this.validators,e),e.timeReceived=new Date;const r=dw(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 Ww{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={[Ov.GET_VALUE.toString()]:new Gw(e,t),[Ov.PUT_VALUE.toString()]:new Hw(e,t),[Ov.FIND_NODE.toString()]:new zw(e,t),[Ov.ADD_PROVIDER.toString()]:new $w(e,t),[Ov.GET_PROVIDERS.toString()]:new Vw(e,t),[Ov.PING.toString()]:new Kw(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 lt)};let r=AbortSignal.timeout(this.incomingMessageTimeout);r.addEventListener("abort",n);const i=yc(e).pb($v);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 Qw extends Rt{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 Yw{dht;constructor(e){this.dht=e}async provide(e,t={}){await dh(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 dh(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 rt("Could not find value for key")}}class Jw{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 rt("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 Zw extends Rt{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??Rw,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??aw,this.onPeerConnectTimeout=t.onPeerConnectTimeout??1e4,this.providers=new xw(e,{...t.providers,logPrefix:n,datastorePrefix:r}),this.validators={...iw,...t.validators},this.selectors={...nw,...t.selectors},this.network=new ww(e,{protocol:this.protocol,logPrefix:n,metricsPrefix:i}),this.routingTable=new Bw(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=kd();!0===t.allowQueryWithZeroPeers&&a.resolve(),this.queryManager=new Aw(e,{disjointPaths:this.d,alpha:this.a,logPrefix:n,metricsPrefix:i,initialQuerySelfHasRun:a,routingTable:this.routingTable,allowQueryWithZeroPeers:t.allowQueryWithZeroPeers}),this.peerRouting=new Pw(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:n}),this.contentFetching=new yw(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:n,datastorePrefix:r}),this.contentRouting=new vw(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:n}),this.routingTableRefresh=new qw(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:n}),this.rpc=new Ww(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 Qw(e,{protocol:this.protocol,logPrefix:n}),this.querySelf=new kw(e,{peerRouting:this.peerRouting,interval:t.querySelfInterval,initialInterval:t.initialQuerySelfInterval,logPrefix:n,initialQuerySelfHasRun:a,operationMetrics:s}),this.reprovider=new Iw(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 Jw(this),this.dhtContentRouting=new Yw(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})=>!Cd(e)&&!Xh.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=fw(this.get.bind(this),s,"GET_VALUE"),this.findProviders=fw(this.findProviders.bind(this),s,"FIND_PROVIDERS"),this.findPeer=fw(this.findPeer.bind(this),s,"FIND_PEER"),this.getClosestPeers=fw(this.getClosestPeers.bind(this),s,"GET_CLOSEST_PEERS"),this.provide=fw(this.provide.bind(this),s,"PROVIDE"),this.put=fw(this.put.bind(this),s,"PUT_VALUE")}[Symbol.toStringTag]="@libp2p/kad-dht";[_t]=["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery","@libp2p/kad-dht"];[Lt]=["@libp2p/identify","@libp2p/ping"];get[Ge](){return this.dhtContentRouting}get[At](){return this.dhtPeerRouting}get[Pt](){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 It(this.routingTable,this.queryManager,this.network,this.topologyListener,this.routingTableRefresh,this.reprovider),await It(this.querySelf))}async stop(){this.running=!1,await Dt(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 Xw(e={}){return t=>new Zw(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"}(Uw||(Uw={}));class eT{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";[_t]=["@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 lt("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 Ld(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=so(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 zn,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(!Nn(n,s.subarray()))throw new ct(`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 zd(i.promise,t.signal)}catch(t){throw i.error("error while pinging %o - %e",e,t),r?.abort(t),t}finally{r?.close()}}}function tT(e={}){return t=>new eT(t,e)}function nT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function rT(e,t,n){if(!e.s){if(n instanceof iT){if(!n.s)return void(n.o=rT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(rT.bind(null,e,t),rT.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var iT=/*#__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{rT(r,1,s(this.v))}catch(e){rT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?rT(r,1,t?t(i):i):n?rT(r,1,n(i)):rT(r,2,i)}catch(e){rT(r,2,e)}},r},e}();function sT(e){return e instanceof iT&&1&e.s}function aT(e,t,n){for(var r;;){var i=e();if(sT(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!sT(s)){r=1;break}s=s.s}if(t){var a=t();if(a&&a.then&&!sT(a)){r=2;break}}}var o=new iT,u=rT.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&&!sT(a))return void a.then(l).then(void 0,u);if(!(i=e())||sT(i)&&!i.v)return void rT(o,1,s);if(i.then)return void i.then(c).then(void 0,u);sT(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):rT(o,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):rT(o,1,s)}}function oT(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 uT="/ocean/nodes/1.0.0",dT=1e4,cT=["/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"],lT=/*#__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=oT(function(){return nT(function(){return t=S(c.findPeer(jo(e),{signal:AbortSignal.timeout(2e4)})),aT(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===Uw.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=oT(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=nT(function(){return Promise.resolve(i.peerStore.get(jo(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:cT).map(Su);return Promise.resolve(async function(e={}){e.privateKey??=await async function(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=Ys.utils.randomSecretKey(),t=Ys.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 ia(e,t)}()}();const t=new qm({...await Mu(e),peerId:(n=e.privateKey,qo(n.publicKey))});var n;return!1!==e.start&&await t.start(),t}(I({addresses:{listen:[]},transports:[pg(),Pv()].concat(t.p2pConfig.enableTcp?[fg()]:[]),connectionEncrypters:[Ub()],streamMuxers:[ng()],peerDiscovery:[].concat(n.length>0?[(r={list:n.map(String),timeout:1e4},e=>new xv(e,r))]:[]),services:{identify:Iv(),ping:tT(),dht:Xw({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){B.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=k(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:(B.debug("[P2P] bare peerId -> dialByPeerId "+e),n.dialByPeerId(r,e,t))}var u=nT(function(){function i(i){if(a)return i;var o=n.peerIdFromMultiaddr(s);if(o){B.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=Su(e),o=function(){if(n.isDialable(s))return B.debug("[P2P] dial single addr: "+s),nT(function(){return Promise.resolve(r.dial(s,{signal:t})).then(function(e){return B.debug("[P2P] dial single SUCCESS via "+e.remoteAddr),a=1,e})},function(e){B.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=k(e);!(a=o()).done;){var u=n.peerIdFromMultiaddr(a.value);if(u){B.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 B.debug("[P2P] dial array: "+a.length+" dialable addrs"),nT(function(){return Promise.resolve(r.dial(a,{signal:t})).then(function(e){return B.debug("[P2P] dial array SUCCESS via "+e.remoteAddr),i=1,e})},function(e){B.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:(B.debug("[P2P] "+t+": last resort dial by peerId"),nT(function(){return Promise.resolve(e.dial(a,{signal:AbortSignal.timeout(1e4)})).then(function(e){return B.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:Su(n+"/p2p/"+t)});B.debug("[P2P] "+t+": "+o.length+"/"+d.length+" addrs are dialable");var u=function(){if(o.length>0)return B.debug("[P2P] "+t+": dialing "+o.map(String)),nT(function(){return Promise.resolve(e.dial(o,{signal:n})).then(function(e){return B.debug("[P2P] "+t+": SUCCESS via "+e.remoteAddr+" (limited="+(null!=e.limits)+")"),r=1,e})},function(e){B.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){B.debug("[P2P] "+t+": no dialable addrs in peerStore, querying DHT...");var n=nT(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=k(e.multiaddrs);!(n=r()).done;)c(n.value);B.debug("[P2P] "+t+": DHT returned "+e.multiaddrs.length+" addrs")})},function(e){B.debug("[P2P] "+t+": DHT findPeer failed: "+e.message)});if(n&&n.then)return n.then(function(){})}else B.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=nT(function(){return Promise.resolve(e.peerStore.get(a)).then(function(e){if(null!=e&&e.addresses){for(var n,r=k(e.addresses);!(n=r()).done;)c(n.value.multiaddr);B.debug("[P2P] "+t+": "+e.addresses.length+" peerStore addrs")}})},function(){B.debug("[P2P] "+t+": not in peerStore")});return l&&l.then?l.then(o):o()},s=this,a=jo(t),o=e.getConnections(a).filter(function(e){return"open"===e.status});if(o.length>0)return B.debug("[P2P] "+t+": reusing existing connection via "+o[0].remoteAddr),Promise.resolve(o[0]);var u=function(){if(0===e.getConnections().length)return B.debug("[P2P] "+t+": no connections yet, waiting for bootstrap..."),Promise.resolve($e(3e3)).then(function(){var n=e.getConnections(a);if(n.length>0)return B.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 hT(e)},t.getSignature=function(e,t,n){return pT(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 fT(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:dT);return Promise.resolve(s.getConnection(e,a)).then(function(e){return nT(function(){return Promise.resolve(e.newStream(uT,{signal:a,runOnLimitedConnection:!0})).then(function(n){var i=mc(n),o=t;return r&&(o=I({},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=oT(function(){return nT(function(){r=S(t);var s=aT(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=oT(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(nT(function(){var u=I({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===E.COMPUTE_GET_STREAMABLE_LOGS||t===E.COMPUTE_GET_RESULT)return R(/*#__PURE__*/M().mark(function e(){var t;return M().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,C(d.read({signal:AbortSignal.timeout(dT)}));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 Ud){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))();var m=[c],y=nT(function(){var e=aT(function(){return!0},void 0,function(){var e;return Promise.resolve(d.read({signal:AbortSignal.timeout(null!=(e=o.p2pConfig.dialTimeout)?e:dT)})).then(function(e){m.push(o.toUint8Array(e))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof Ud))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 B.debug("[P2P] Stream reset/closed on attempt "+(s+1)+", retrying..."),Promise.resolve($e(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(nT(function(){return Promise.resolve(t.sendP2pCommand(e,E.STATUS,{}))},function(e){throw B.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(nT(function(){var i={};return t&&(i.fromTimestamp=t.toString()),Promise.resolve(r.sendP2pCommand(e,E.JOBS,i,null,n)).then(function(e){return Array.isArray(e)?e:[]})},function(e){return B.error("P2P getNodeJobs failed:",e),[]}))}catch(e){return Promise.reject(e)}},t.getNonce=function(e,t,n){try{var r=this;return Promise.resolve(nT(function(){return Promise.resolve(r.sendP2pCommand(e,E.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 B.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,E.ENCRYPT)).then(function(o){return Promise.resolve(a.sendP2pCommand(n,E.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,E.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,E.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,E.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,E.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,E.COMPUTE_INITIALIZE,y,null,c)}var t=function(){if(h)return Promise.resolve(m.getNodePublicKey(s)).then(function(e){e&&(y.output=ku(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=ku(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,E.DOWNLOAD)).then(function(c){var p={command:E.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=Cu(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=nT(function(){var e=aT(function(){return!0},void 0,function(){var e;return Promise.resolve(t.read({signal:AbortSignal.timeout(null!=(e=u.p2pConfig.dialTimeout)?e:dT)})).then(function(e){d.push(new Uint8Array(u.toUint8Array(e)))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof Ud))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,E.COMPUTE_START)).then(function(g){function w(){function n(){return Promise.resolve(y.sendP2pCommand(e,E.COMPUTE_START,T,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&&(T.output=ku(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var T={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&&(T.metadata=d),c&&(T.additionalViewers=c),p&&(T.policyServer=p),f&&(T.queueMaxWaitTime=f);var P=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(T.encryptedDockerRegistryAuth=ku(e,JSON.stringify(m)))})}();return P&&P.then?P.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,E.FREE_COMPUTE_START)).then(function(m){function b(){function n(){return Promise.resolve(h.sendP2pCommand(e,E.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=ku(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=ku(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,E.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,E.COMPUTE_GET_STREAMABLE_LOGS)).then(function(a){return i.sendP2pCommand(e,E.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,E.COMPUTE_STOP)).then(function(o){var d={jobId:e,consumerAddress:a,nonce:u,signature:o};return r&&(d.agreementId=r),s.sendP2pCommand(t,E.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,E.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:dT;return R(/*#__PURE__*/M().mark(function e(){var t;return M().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,C(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 Ud){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))()})}var u={command:E.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,E.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,E.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,E.CREATE_AUTH_TOKEN)).then(function(e){return Promise.resolve(r.sendP2pCommand(t,E.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,E.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,E.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(ze(n,s+o+E.VALIDATE_DDO)).then(function(n){return Promise.resolve(i.sendP2pCommand(e,E.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(ze(e,s+o)).then(function(e){return i.sendP2pCommand(n,E.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(nT(function(){return Promise.resolve(n.sendP2pCommand(e,E.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,E.POLICY_SERVER_PASSTHROUGH,I({},t),null,n))}catch(e){return Promise.reject(e)}},t.initializePSVerification=function(e,t,n){try{return Promise.resolve(this.sendP2pCommand(e,E.POLICY_SERVER_PASSTHROUGH,I({},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,E.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,E.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,E.GET_LOGS,I({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,E.FETCH_CONFIG,t))}catch(e){return Promise.reject(e)}},t.pushConfig=function(e,t){try{return Promise.resolve(this.sendP2pCommand(e,E.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,E.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(s){var a;return i.sendP2pCommand(e,E.PERSISTENT_STORAGE_CREATE_BUCKET,I({},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,E.PERSISTENT_STORAGE_GET_BUCKETS,i)).then(function(a){return Promise.resolve(s.sendP2pCommand(e,E.PERSISTENT_STORAGE_GET_BUCKETS,I({},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,E.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.PERSISTENT_STORAGE_LIST_FILES,I({},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,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(a){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,I({},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,E.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(o){return a.sendP2pCommand(e,E.PERSISTENT_STORAGE_UPLOAD_FILE,I({},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,E.PERSISTENT_STORAGE_DELETE_FILE,s)).then(function(o){return a.sendP2pCommand(e,E.PERSISTENT_STORAGE_DELETE_FILE,I({},o,{bucketId:n,fileName:r,chainId:i}),t,s)})}catch(e){return Promise.reject(e)}},e}(),pT=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 ze(e,a)})}catch(e){return Promise.reject(e)}},hT=function(e){try{return Promise.resolve("string"==typeof e?function(e){try{return w.default.decode(e,{json:!0})}catch(e){throw new Error("Error decoding JWT")}}(e).address:e.getAddress())}catch(e){return Promise.reject(e)}};function fT(e){return"string"==typeof e?e:void 0}function mT(e){if(Array.isArray(e))return!0;if(!e)return!1;try{return Su(e),!0}catch(e){}try{return jo(e),!0}catch(e){return!1}}var yT=/*#__PURE__*/function(){function e(){this.httpProvider=new Du,this.p2pProvider=new lT}var t=e.prototype;return t.getImpl=function(e){return Array.isArray(e)||mT(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}(),bT=new yT;function gT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function vT(e,t,n){if(!e.s){if(n instanceof wT){if(!n.s)return void(n.o=vT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(vT.bind(null,e,t),vT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var wT=/*#__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{vT(r,1,s(this.v))}catch(e){vT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?vT(r,1,t?t(i):i):n?vT(r,1,n(i)):vT(r,2,i)}catch(e){vT(r,2,e)}},r},e}();function TT(e){return e instanceof wT&&1&e.s}var ET=/*#__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 gT(function(){return Promise.resolve(v.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 B.error(e),new Error("HTTP request failed")})},s=this,a=function(){if(mT(s.aquariusURL))return Promise.resolve(bT.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 a,u=this,d=0;i>500&&(B.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);var c=mT(u.aquariusURL),l=function(e,t){var n;do{var r=e();if(r&&r.then){if(!TT(r)){n=!0;break}r=r.v}var i=t();if(TT(i)&&(i=i.v),!i)return r}while(!i.then);var s=new wT,a=vT.bind(null,s,2);return(n?r.then(o):i.then(u)).then(void 0,a),s;function o(n){for(r=n;TT(i=t())&&(i=i.v),i;){if(i.then)return void i.then(u).then(void 0,a);if((r=e())&&r.then){if(!TT(r))return void r.then(o).then(void 0,a);r=r.v}}vT(s,1,r)}function u(n){if(n){do{if((r=e())&&r.then){if(!TT(r))return void r.then(o).then(void 0,a);r=r.v}if(TT(n=t())&&(n=n.v),!n)return void vT(s,1,r)}while(!n.then);n.then(u).then(void 0,a)}else vT(s,1,r)}}(function(){function i(e){return a?e:Promise.resolve($e(r)).then(function(){d++})}var l=gT(function(){function r(){if(i){var e=o.DDOManager.getDDOClass(i).getAssetFields().indexedMetadata;if(!t)return a=1,i;if(e.event&&e.event.txid===t)return a=1,i}}var i,d=c?Promise.resolve(bT.resolveDdo(u.aquariusURL,e,n)).then(function(e){i=e}):Promise.resolve(v.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!a&&d<i});return Promise.resolve(l&&l.then?l.then(function(e){return a?e:null}):a?l:null)}catch(e){return Promise.reject(e)}},t.validate=function(e,t,n,r,i){try{if(mT(n))return Promise.resolve(bT.validateDdo(n,e,t,r));var s=n+"/api/aquarius/assets/ddo/validate",a=n+"/api/services/nonce";return Promise.resolve(gT(function(){return Promise.resolve(t.getAddress()).then(function(n){return Promise.resolve(v.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(E.VALIDATE_DDO));return Promise.resolve(ze(t,a)).then(function(i){return Promise.resolve(v.default(s,{method:"POST",body:JSON.stringify({ddo:e,publisherAddress:n,nonce:o,signature:i}),headers:{"Content-Type":"application/json",Authorization:fT(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){B.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(gT(function(){return Promise.resolve(v.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 B.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(gT(function(){return Promise.resolve(v.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 B.error("Error querying metadata: ",e),new Error("Error querying metadata: "+e)}))}catch(e){return Promise.reject(e)}},e}(),PT=function(e,t,r,i){try{var s=new n.ethers.Contract(t,V,e);return Promise.resolve(s.allowance(r,i))}catch(e){return Promise.reject(e)}},xT=function(e,t,r,i,s){try{var a=new n.ethers.Contract(t,V,e);return Promise.resolve(a.allowance(r,i)).then(function(n){return Promise.resolve(H(e,t,n,s))})}catch(e){return Promise.reject(e)}},ST=function(e,t,r,i,s,a,o,u){void 0===o&&(o=!1);try{var d,c=function(n){if(d)return n;var r=null;return Promise.resolve(l.approve.estimateGas(s,a)).then(function(n){if(u)return n;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(G(n,e,null==t?void 0:t.gasFeeMultiplier,l.approve,s,a)).then(function(e){r=e})},function(e){B.error("ERROR: Failed to approve spender to spend tokens : "+e.message)});return i&&i.then?i.then(function(){return r}):r})},l=new n.ethers.Contract(i,V,e),p=function(){if(!o)return Promise.resolve(PT(e,i,r,s)).then(function(e){if(new b.default(e).isGreaterThan(new b.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)}},AT=function(e,t,r,i,s,a,o,u,d){void 0===o&&(o=!1);try{var c,l=function(n){return c?n:Promise.resolve(K(e,i,a,u)).then(function(n){return Promise.resolve(p.approve.estimateGas(s,n)).then(function(r){return d?new g.default(r.toString()):Promise.resolve(G(r,e,null==t?void 0:t.gasFeeMultiplier,p.approve,s,n))})})},p=new n.ethers.Contract(i,V,e),h=function(){if(!o)return Promise.resolve(xT(e,i,r,s)).then(function(e){if(new g.default(e).greaterThanOrEqualTo(new g.default(a))){var t=new g.default(e).toNumber();return c=1,t}})}();return Promise.resolve(h&&h.then?h.then(l):l(h))}catch(e){return Promise.reject(e)}},CT={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 kT(e,t,n){if(!e.s){if(n instanceof IT){if(!n.s)return void(n.o=kT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(kT.bind(null,e,t),kT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var IT=/*#__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{kT(r,1,s(this.v))}catch(e){kT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?kT(r,1,t?t(i):i):n?kT(r,1,n(i)):kT(r,2,i)}catch(e){kT(r,2,e)}},r},e}();function DT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}e.AccessListContract=Re,e.AccesslistFactory=Le,e.Aquarius=ET,e.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},e.ConfigHelper=z,e.DEVELOPMENT_CHAIN_ID=8996,e.Datatoken=Ie,e.Datatoken4=Me,e.Dispenser=oe,e.EnterpriseFeeCollectorContract=qe,e.EscrowContract=Ue,e.FEE_HISTORY_NOT_SUPPORTED="Returned error: Method eth_feeHistory not supported.",e.FixedRateExchange=ce,e.GASLIMIT_DEFAULT=1e6,e.KNOWN_CONFIDENTIAL_EVMS=q,e.Logger=O,e.LoggerInstance=B,e.MAX_UINT_256="115792089237316195423570985008687907853269984665640564039457584007913129639934",e.Nft=ke,e.NftFactory=we,e.OCEAN_P2P_PROTOCOL=uT,e.PROTOCOL_COMMANDS=E,e.Provider=yT,e.ProviderInstance=bT,e.Router=pe,e.SmartContract=ie,e.SmartContractWithAddress=se,e.ZERO_ADDRESS=de,e.allowance=xT,e.allowanceWei=PT,e.amountToUnits=K,e.approve=AT,e.approveWei=ST,e.balance=function(e,t,r,i){try{var s=new n.ethers.Contract(t,V,e);return Promise.resolve(s.balanceOf(r)).then(function(n){return Promise.resolve(H(e,t,n,i))})}catch(e){return Promise.reject(e)}},e.bytesToHex=Au,e.calculateActiveTemplateIndex=Se,e.concatUint8Arrays=Cu,e.configHelperNetworks=j,e.createAccessListFactory=function(e,t,r){try{var i=new n.ethers.Contract(e,_e,t);return Promise.resolve(t.getAddress()).then(function(e){var t,n=DT(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=re(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)}},e.createAsset=function(e,t,r,i,s,a,u,d,c,l,p,h,f,m,y){void 0===u&&(u=!0);try{var b,g,v=this,w=o.DDOManager.getDDOClass(a),E=w.getAssetFields().indexedMetadata,P=(null==(b=w.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),x=w.getDDOFields(),S=x.chainId,A=x.nftAddress,C=w.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(o){var b=o.chainId;if(S&&S!==Number(b))throw new Error("Chain ID from DDO is different than the configured network.");var g=(new z).getConfig(parseInt(String(b)));return Promise.resolve(Se(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 o=new ke(r,Number(b)),E=new we(g.nftFactoryAddress,r,Number(b));return Promise.resolve(r.getAddress()).then(function(x){var k;function I(e){return k?e:Promise.resolve(D.wait()).then(function(e){var t;function i(e){if(t)return e;function i(){function e(){var e=o.setMetadata,u=A;return Promise.resolve(r.getAddress()).then(function(r){return Promise.resolve(e.call(o,u,r,0,d,"",n.toBeHex(s),t,i)).then(function(){return a.id})})}C[0].datatokenAddress=h,C[0].serviceEndpoint=d;var t,i,s,c=w.makeDid(A=p,S.toString());a=w.updateFields({id:c,nftAddress:A});var f=function(){if(u)return Promise.resolve(bT.encrypt(a,Number(b),d,r,null)).then(function(e){return t=e,Promise.resolve(l.validate(a,r,d)).then(function(e){i=e.hash,s=2})});var e=JSON.stringify(a);t=n.hexlify(n.toUtf8Bytes(e)),i="0x"+T.default(t).toString(),s=0}();return f&&f.then?f.then(e):e()}var s=function(){if("oasis"!==g.sdk)return Promise.resolve(bT.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=re(e,"NFTCreated"),c=re(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 n.ethers.Contract(h,De,r);return DT(function(){return Promise.resolve(e.setFilesObject(n.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),t=1,null})}}();return f&&f.then?f.then(i):i(f)})}var D,M={name:e,symbol:t,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:x},F={templateIndex:s,cap:"100000",feeAmount:"0",paymentCollector:x,feeToken:c||g.oceanTokenAddress,minter:x,mpFeeAddress:de},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 _=DT(function(){var e=function(){if(!P)return Promise.resolve(E.createNftWithDatatoken(M,F)).then(function(e){D=e});var e=function(){if("0"===P.toString())return Promise.resolve(E.createNftWithDatatokenWithDispenser(M,F,{dispenserAddress:g.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:de})).then(function(e){D=e});var e=m||g.oceanTokenAddress;return Promise.resolve(W(v.signer,e)).then(function(t){y||(y=t);var n={fixedRateAddress:g.fixedRateExchangeAddress,baseTokenAddress:e,owner:x,marketFeeCollector:x,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:P.toString(),marketFee:"0",allowedConsumer:x,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)}},e.decimals=function(e,t){try{var r=new n.ethers.Contract(t,V,e);return Promise.resolve(r.decimals()).then(Number)}catch(e){return Promise.reject(e)}},e.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)}},e.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()},e.generateDid=function(e,t){return e=n.getAddress(e),"did:op:"+T.default(e+t.toString(10)).toString()},e.generateDtName=be,e.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=CT[n])?void 0:r[i])||"Provider request failed: "+i}var s=t[n];return t[Object.keys(t)[1]]+" : "+s}catch(t){return B.error("[getErrorMessage] error: ",t),e}},e.getEventFromTx=re,e.getFairGasPrice=Q,e.getHash=function(e){return T.default(e).toString()},e.getNodeEndpointConfig=$,e.getOceanArtifactsAddresses=Ae,e.getOceanArtifactsAddressesByChainId=Ce,e.getTokenDecimals=W,e.isDefined=function(e){return null!=e},e.isP2pUri=mT,e.minAbi=V,e.orderAsset=function(e,t,n,r,i,s,a,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=o.DDOManager.getDDOClass(e),f=h.getAssetFields().datatokens,m=h.getDDOFields(),y=m.chainId,b=m.services;return a||(a={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"}),Promise.resolve(t.provider.getNetwork()).then(function(o){if(y!==Number(o.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(!b[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(o){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(bT,x,P,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:a};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 IT,l=kT.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 kT(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());kT(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)}kT(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 a=function(){if(2===o||4===o)return Promise.resolve(r.buyFromDispenserAndOrder(b[l].datatokenAddress,u,n.dispenserAddress)).then(function(e){return t=1,e})}();return a&&a.then?a.then(i):i(a)},i=function(){if(1===o){var e=new oe(n.dispenserAddress,t),i=e.dispense,a=f[c].address;return Promise.resolve(t.getAddress()).then(function(t){return Promise.resolve(i.call(e,a,"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 ce(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",a.consumeMarketFeeAmount)).then(function(l){var p;function h(e){var i;if(p)return e;function a(e){if(i)return e}var d=function(){if(2===o||4===o)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(AT(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,b)).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(a):a(d)}var m=new g.default(+l.baseTokenAmount||0).add(new g.default(a.consumeMarketFeeAmount||0)).add(new g.default(+y.publishMarketFeeAmount||0)).toString(),b={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===o)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(AT(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!==de&&v.providerFeeAmount&&parseInt(v.providerFeeAmount)>0)return function(e,r){try{var i=Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(ST(t,n,e,v.providerFeeToken,b[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||bT.initialize,P=u||b[l].id,x=u||e.id;return u?v(w(u)):Promise.resolve(t.getAddress()).then(v)})})})})})}catch(e){return Promise.reject(e)}},e.sendTx=G,e.setContractDefaults=ne,e.signHash=function(e,t){try{var r=n.getBytes(t);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)}},e.signRequest=ze,e.sleep=$e,e.transfer=function(e,t,r,i,s,a,o){try{var u=new n.ethers.Contract(r,V,e);return Promise.resolve(K(e,r,s,a)).then(function(n){return Promise.resolve(u.transfer.estimateGas(i,n)).then(function(r){return o?r:Promise.resolve(G(r,e,null==t?void 0:t.gasFeeMultiplier,u.transfer,i,n))})})}catch(e){return Promise.reject(e)}},e.unitsToAmount=H,e.useOasisSDK=function(e){var t=(new z).getConfig(e);return t&&"oasis"===t.sdk}});
|
|
3
|
+
/* @__PURE__ */,Xr(3)),_i=/* @__PURE__ */BigInt(0),Li=/* @__PURE__ */BigInt(1);function Ni(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e);return e}function Oi(e){if("bigint"==typeof e){if(!Gi(e))throw new Error("positive bigint expected, got "+e)}else Br(e);return e}function Bi(e){const t=Oi(e).toString(16);return 1&t.length?"0"+t:t}function Ui(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?_i:BigInt("0x"+e)}function ji(e){return Ui(Hr(e))}function qi(e){return Ui(Hr(Vi(Ur(e)).reverse()))}function $i(e,t){Br(t);const n=Qr((e=Oi(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}function zi(e,t){return $i(e,t).reverse()}function Vi(e){return Uint8Array.from(e)}const Gi=e=>"bigint"==typeof e&&_i<=e;function Ki(e,t,n,r){if(!function(e,t,n){return Gi(e)&&Gi(t)&&Gi(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const Hi=e=>(Li<<BigInt(e))-Li;function Wi(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 Qi(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 Yi=/* @__PURE__ */BigInt(0),Ji=/* @__PURE__ */BigInt(1),Zi=/* @__PURE__ */BigInt(2),Xi=/* @__PURE__ */BigInt(3),es=/* @__PURE__ */BigInt(4),ts=/* @__PURE__ */BigInt(5),ns=/* @__PURE__ */BigInt(7),rs=/* @__PURE__ */BigInt(8),is=/* @__PURE__ */BigInt(9),ss=/* @__PURE__ */BigInt(16);function as(e,t){const n=e%t;return n>=Yi?n:t+n}function os(e,t,n){let r=e;for(;t-- >Yi;)r*=r,r%=n;return r}function us(e,t){if(e===Yi)throw new Error("invert: expected non-zero number");if(t<=Yi)throw new Error("invert: expected positive modulus, got "+t);let n=as(e,t),r=t,i=Yi,s=Ji;for(;n!==Yi;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==Ji)throw new Error("invert: does not exist");return as(i,t)}function ds(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function cs(e,t){const n=e.pow(t,(e.ORDER+Ji)/es);return ds(e,n,t),n}function ls(e,t){const n=(e.ORDER-ts)/rs,r=e.mul(t,Zi),i=e.pow(r,n),s=e.mul(t,i),a=e.mul(e.mul(s,Zi),i),o=e.mul(s,e.sub(a,e.ONE));return ds(e,o,t),o}function ps(e){if(e<Xi)throw new Error("sqrt is not defined for small field");let t=e-Ji,n=0;for(;t%Zi===Yi;)t/=Zi,n++;let r=Zi;const i=bs(e);for(;1===ms(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return cs;let s=i.pow(r,t);const a=(t+Ji)/Zi;return function(e,r){if(e.is0(r))return r;if(1!==ms(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=Ji<<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 hs=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function fs(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 ms(e,t){const n=e.pow(t,(e.ORDER-Ji)/Zi),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 ys{ORDER;BITS;BYTES;isLE;ZERO=Yi;ONE=Ji;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Yi)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&&Br(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 as(e,this.ORDER)}isValid(e){if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return Yi<=e&&e<this.ORDER}is0(e){return e===Yi}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Ji)===Ji}neg(e){return as(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return as(e*e,this.ORDER)}add(e,t){return as(e+t,this.ORDER)}sub(e,t){return as(e-t,this.ORDER)}mul(e,t){return as(e*t,this.ORDER)}pow(e,t){return function(e,t,n){if(n<Yi)throw new Error("invalid exponent, negatives unsupported");if(n===Yi)return e.ONE;if(n===Ji)return t;let r=e.ONE,i=t;for(;n>Yi;)n&Ji&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Ji;return r}(this,e,t)}div(e,t){return as(e*us(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 us(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=(t=this.ORDER)%es===Xi?cs:t%rs===ts?ls:t%ss===is?function(e){const t=bs(e),n=ps(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),a=(e+ns)/ss;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 ds(e,h,t),h}}(t):ps(t)),this._sqrt(this,e);var t}toBytes(e){return this.isLE?zi(e,this.BYTES):$i(e,this.BYTES)}fromBytes(e,t=!1){Ur(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?qi(e):ji(e);if(a&&(o=as(o,s)),!t&&!this.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o}invertBatch(e){return fs(this,e)}cmov(e,t,n){return n?t:e}}function bs(e,t={}){return new ys(e,t)}function gs(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 vs(e){const t=gs(e);return t+Math.ceil(t/2)}const ws=/* @__PURE__ */BigInt(0),Ts=/* @__PURE__ */BigInt(1);function Es(e,t){const n=t.negate();return e?n:t}function Ps(e,t){const n=fs(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 Ss(e,t){xs(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Hi(e),maxNumber:n,shiftBy:BigInt(e)}}function As(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+=Ts);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 Cs=new WeakMap,ks=new WeakMap;function Is(e){return ks.get(e)||1}function Ds(e){if(e!==ws)throw new Error("invalid wNAF")}class Ms{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>ws;)t&Ts&&(n=n.add(r)),r=r.double(),t>>=Ts;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Ss(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=Ss(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:a,offset:o,isZero:u,isNeg:d,isNegF:c,offsetF:l}=As(n,e,s);n=a,u?i=i.add(Es(c,t[l])):r=r.add(Es(d,t[o]))}return Ds(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Ss(e,this.bits);for(let e=0;e<i.windows&&n!==ws;e++){const{nextN:s,offset:a,isZero:o,isNeg:u}=As(n,e,i);if(n=s,!o){const e=t[a];r=r.add(u?e.negate():e)}}return Ds(n),r}getPrecomputes(e,t,n){let r=Cs.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Cs.set(t,r))),r}cached(e,t,n){const r=Is(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=Is(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),ks.set(e,t),Cs.delete(e)}hasCache(e){return 1!==Is(e)}}function Fs(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=hs.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",BYTES:"number",BITS:"number"});Wi(e,t)}(t),t}return bs(e,{isLE:n})}function Rs(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>ws))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Fs(t.p,n.Fp,r),s=Fs(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 _s(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}const Ls=BigInt(0),Ns=BigInt(1),Os=BigInt(2),Bs=BigInt(8);function Us(e,t={}){const n=Rs("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a}=s;Wi(t,{},{uvRatio:"function"});const o=Os<<BigInt(8*i.BYTES)-Ns,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:Ls}}});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 Ki("coordinate "+e,t,n?Ns:Ls,o),t}function l(e){if(!(e instanceof f))throw new Error("EdwardsPoint expected")}const p=Qi((e,t)=>{const{X:n,Y:i,Z:s}=e,a=e.is0();null==t&&(t=a?Bs:r.inv(s));const o=u(n*t),d=u(i*t),c=r.mul(s,t);if(a)return{x:Ls,y:Ns};if(c!==Ns)throw new Error("invZ was invalid");return{x:o,y:d}}),h=Qi(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,Ns,u(s.Gx*s.Gy));static ZERO=new f(Ls,Ns,Ns,Ls);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,Ns,u(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:a}=s;e=Vi(Ur(e,n,"point")),Ni(t,"zip215");const c=Vi(e),l=e[n-1];c[n-1]=-129&l;const p=qi(c);Ki("point.y",p,Ls,t?o:r.ORDER);const h=u(p*p),m=u(h-Ns),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&Ns)===Ns,w=!!(128&l);if(!t&&g===Ls&&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(Qr(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(Os),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(Os*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),P=u(v*w),x=u(T*E),S=u(v*E),A=u(w*T);return new f(P,x,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=>Ps(f,e));return Ps(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===Ls?f.ZERO:this.is0()||e===Ns?this:m.unsafe(this,e,e=>Ps(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===Ns?this:this.multiplyUnsafe(a)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Ns?128:0,n}toHex(){return Hr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const m=new Ms(f,i.BITS);return f.BASE.precompute(8),f}const js=BigInt(1),qs=BigInt(2),$s=BigInt(5),zs=BigInt(8),Vs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Gs=/* @__PURE__ */(()=>({p:Vs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:zs,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ks(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Hs=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Ws=/* @__PURE__ */Us(Gs,{uvRatio:function(e,t){const n=Vs,r=as(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Vs,a=e*e%s*e%s,o=os(a,qs,s)*a%s,u=os(o,js,s)*e%s,d=os(u,$s,s)*u%s,c=os(d,t,s)*d%s,l=os(c,n,s)*c%s,p=os(l,r,s)*l%s,h=os(p,i,s)*p%s,f=os(h,i,s)*p%s,m=os(f,t,s)*d%s;return{pow_p_5_8:os(m,qs,s)*e%s,b2:a}}(e*as(r*r*t,n)).pow_p_5_8;let s=as(e*r*i,n);const a=as(t*s*s,n),o=s,u=as(s*Hs,n),d=a===e,c=a===as(-e,n),l=a===as(-e*Hs,n);return d&&(s=o),(c||l)&&(s=u),(as(s,n)&Ji)===Ji&&(s=as(-s,n)),{isValid:d||c,value:s}}});function Qs(e){return function(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Wi(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||Zr,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Ni(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function c(e){return a.create(qi(e))}function l(e){const{head:n,prefix:r,scalar:s}=function(e){const n=y.secretKey;Ur(e,y.secretKey,"secretKey");const r=Ur(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=Yr(...n);return c(t(d(i,Ur(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 Ur(e,y.seed,"seed")}const g={getExtendedPublicKey:l,randomSecretKey:b,isValidSecretKey:function(e){return Or(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(Ns+n,Ns-n):s.div(n-Ns,n+Ns);return s.toBytes(a)},toMontgomerySecret(e){const n=y.secretKey;Ur(e,n);const r=t(e.subarray(0,n));return u(r).subarray(0,n)}};return Object.freeze({keygen:_s(b,p),getPublicKey:p,sign:function(e,t,n={}){e=Ur(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 Ur(Yr(c,a.toBytes(f)),y.signature,"result")},verify:function(t,n,s,a=f){const{context:o,zip215:u}=a,d=y.signature;t=Ur(t,d,"signature"),n=Ur(n,void 0,"message"),s=Ur(s,y.publicKey,"publicKey"),void 0!==u&&Ni(u,"zip215"),r&&(n=r(n));const c=d/2,l=t.subarray(0,c),p=qi(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})}(Ws,Ri,Object.assign({adjustScalarBytes:Ks},e))}const Ys=/* @__PURE__ */Qs({});Error;class Js extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Zs extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var Xs={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Zs("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 ea;const ta=(async()=>{try{return await Xs.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function na(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class ra{type="Ed25519";raw;constructor(e){this.raw=aa(e,32)}toMultihash(){return Ln(Ro(this))}toCID(){return In.createV1(114,this.toMultihash())}toString(){return Gt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();const r=async function(e,t,n){return null==ea&&(ea=await ta),ea?async function(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await Xs.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Xs.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 Ys.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}(e,t,n)}(this.raw,t,e);return na(r)?r.then(e=>(n?.signal?.throwIfAborted(),e)):r}}class ia{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=aa(e,64),this.publicKey=new ra(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const n=async function(e,t){return null==ea&&(ea=await ta),ea?async function(e,t){let n;n=64===e.length?e.subarray(0,32):e;const r={crv:"Ed25519",kty:"OKP",x:yr(e.subarray(32),"base64url"),d:yr(n,"base64url"),ext:!0,key_ops:["sign"]},i=await Xs.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await Xs.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 Ys.sign(t instanceof Uint8Array?t:t.subarray(),n)}(e,t)}(this.raw,e);return na(n)?n.then(e=>(t?.signal?.throwIfAborted(),e)):(t?.signal?.throwIfAborted(),n)}}function sa(e){return e=aa(e,32),new ra(e)}function aa(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Qe(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const oa=Math.pow(2,7),ua=Math.pow(2,14),da=Math.pow(2,21),ca=Math.pow(2,28),la=Math.pow(2,35),pa=Math.pow(2,42),ha=Math.pow(2,49),fa=128,ma=127;function ya(e){if(e<oa)return 1;if(e<ua)return 2;if(e<da)return 3;if(e<ca)return 4;if(e<la)return 5;if(e<pa)return 6;if(e<ha)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ba(e,t,n=0){switch(ya(e)){case 8:t[n++]=255&e|fa,e/=128;case 7:t[n++]=255&e|fa,e/=128;case 6:t[n++]=255&e|fa,e/=128;case 5:t[n++]=255&e|fa,e/=128;case 4:t[n++]=255&e|fa,e>>>=7;case 3:t[n++]=255&e|fa,e>>>=7;case 2:t[n++]=255&e|fa,e>>>=7;case 1:t[n++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function ga(e,t){let n=e[t],r=0;if(r+=n&ma,n<fa)return r;if(n=e[t+1],r+=(n&ma)<<7,n<fa)return r;if(n=e[t+2],r+=(n&ma)<<14,n<fa)return r;if(n=e[t+3],r+=(n&ma)<<21,n<fa)return r;if(n=e[t+4],r+=(n&ma)*ca,n<fa)return r;if(n=e[t+5],r+=(n&ma)*la,n<fa)return r;if(n=e[t+6],r+=(n&ma)*pa,n<fa)return r;if(n=e[t+7],r+=(n&ma)*ha,n<fa)return r;throw new RangeError("Could not decode varint")}function va(e,t,n=0){return null==t&&(t=Bn(ya(e))),t instanceof Uint8Array?ba(e,t,n):function(e,t,n=0){switch(ya(e)){case 8:t.set(n++,255&e|fa),e/=128;case 7:t.set(n++,255&e|fa),e/=128;case 6:t.set(n++,255&e|fa),e/=128;case 5:t.set(n++,255&e|fa),e/=128;case 4:t.set(n++,255&e|fa),e>>>=7;case 3:t.set(n++,255&e|fa),e>>>=7;case 2:t.set(n++,255&e|fa),e>>>=7;case 1:t.set(n++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,n)}function wa(e,t=0){return e instanceof Uint8Array?ga(e,t):function(e,t){let n=e.get(t),r=0;if(r+=n&ma,n<fa)return r;if(n=e.get(t+1),r+=(n&ma)<<7,n<fa)return r;if(n=e.get(t+2),r+=(n&ma)<<14,n<fa)return r;if(n=e.get(t+3),r+=(n&ma)<<21,n<fa)return r;if(n=e.get(t+4),r+=(n&ma)*ca,n<fa)return r;if(n=e.get(t+5),r+=(n&ma)*la,n<fa)return r;if(n=e.get(t+6),r+=(n&ma)*pa,n<fa)return r;if(n=e.get(t+7),r+=(n&ma)*ha,n<fa)return r;throw new RangeError("Could not decode varint")}(e,t)}const Ta=new Float32Array([-0]),Ea=new Uint8Array(Ta.buffer);function Pa(e,t,n){Ta[0]=e,t[n]=Ea[0],t[n+1]=Ea[1],t[n+2]=Ea[2],t[n+3]=Ea[3]}const xa=new Float64Array([-0]),Sa=new Uint8Array(xa.buffer);function Aa(e,t,n){xa[0]=e,t[n]=Sa[0],t[n+1]=Sa[1],t[n+2]=Sa[2],t[n+3]=Sa[3],t[n+4]=Sa[4],t[n+5]=Sa[5],t[n+6]=Sa[6],t[n+7]=Sa[7]}const Ca=BigInt(Number.MAX_SAFE_INTEGER),ka=BigInt(Number.MIN_SAFE_INTEGER);class Ia{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 Da;if(e<Ca&&e>ka)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>Ma&&(r=0n,++n>Ma&&(n=0n))),new Ia(Number(r),Number(n))}static fromNumber(e){if(0===e)return Da;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 Ia(n,r)}static from(e){return"number"==typeof e?Ia.fromNumber(e):"bigint"==typeof e?Ia.fromBigInt(e):"string"==typeof e?Ia.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Ia(e.low>>>0,e.high>>>0):Da}}const Da=new Ia(0,0);Da.toBigInt=function(){return 0n},Da.zzEncode=Da.zzDecode=function(){return this},Da.length=function(){return 1};const Ma=4294967296n;function Fa(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 Ra(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function _a(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class La{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,Ra(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 Ra(this,4);return _a(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ra(this,4);return 0|_a(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Ra(this,4);const e=(Ea[0]=(t=this.buf)[n=this.pos],Ea[1]=t[n+1],Ea[2]=t[n+2],Ea[3]=t[n+3],Ta[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ra(this,4);const e=(Sa[0]=(t=this.buf)[n=this.pos],Sa[1]=t[n+1],Sa[2]=t[n+2],Sa[3]=t[n+3],Sa[4]=t[n+4],Sa[5]=t[n+5],Sa[6]=t[n+6],Sa[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 Ra(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 Ra(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Ra(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 Ia(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Ra(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 Ra(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 Ra(this,8);const e=_a(this.buf,this.pos+=4),t=_a(this.buf,this.pos+=4);return new Ia(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=ga(this.buf,this.pos);return this.pos+=ya(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 Na(e){return new La(e instanceof Uint8Array?e:e.subarray())}function Oa(e,t,n){const r=Na(e);return t.decode(r,void 0,n)}class Ba{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Ua(){}class ja{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const qa=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Bn(r);n+r>e&&(t=Bn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class $a{len;head;tail;states;constructor(){this.len=0,this.head=new Ba(Ua,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Ba(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ga((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ka,10,Ia.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Ia.fromBigInt(e);return this._push(Ka,t.length(),t)}uint64Number(e){return this._push(ba,ya(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=Ia.fromBigInt(e).zzEncode();return this._push(Ka,t.length(),t)}sint64Number(e){const t=Ia.fromNumber(e).zzEncode();return this._push(Ka,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(za,1,e?1:0)}fixed32(e){return this._push(Ha,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Ia.fromBigInt(e);return this._push(Ha,4,t.lo)._push(Ha,4,t.hi)}fixed64Number(e){const t=Ia.fromNumber(e);return this._push(Ha,4,t.lo)._push(Ha,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(Pa,4,e)}double(e){return this._push(Aa,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(za,1,0):this.uint32(t)._push(Wa,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(Fa,t,e):this._push(za,1,0)}fork(){return this.states=new ja(this),this.head=this.tail=new Ba(Ua,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 Ba(Ua,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?Bn(n):qa(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function za(e,t,n){t[n]=255&e}function Va(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class Ga extends Ba{next;constructor(e,t){super(Va,e,t),this.next=void 0}}function Ka(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 Ha(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 Wa(e,t,n){t.set(e,n)}function Qa(e,t,n){t.set(e,n)}function Ya(e,t,n){e.length<40?Fa(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(mr(e),n)}function Ja(e,t){const n=new $a;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*Za(e,t,n){const r=Na(e);yield*t.stream(r,void 0,"$",n)}function Xa(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function eo(e,t,n){return Xa("message",2,e,t,n)}var to,no,ro,io;function so(e){if(isNaN(e)||e<=0)throw new Qe("random bytes length must be a Number bigger than 0");return Zr(e)}null!=globalThis.Buffer&&($a.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Qa,t,e),this},$a.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Ya,t,e),this}),function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(to||(to={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(no||(no={})),function(e){e.codec=()=>function(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Xa("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)})}(no)}(to||(to={})),function(e){let t;e.codec=()=>(null==t&&(t=eo((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),to.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=to.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:to.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 Ja(t,e.codec())},e.decode=function(t,n){return Oa(t,e.codec(),n)},e.stream=function(t,n){return Za(t,e.codec(),n)}}(ro||(ro={})),function(e){let t;e.codec=()=>(null==t&&(t=eo((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),to.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=to.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:to.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 Ja(t,e.codec())},e.decode=function(t,n){return Oa(t,e.codec(),n)},e.stream=function(t,n){return Za(t,e.codec(),n)}}(io||(io={}));class ao{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 Qe("JWK was missing components");return Cr([oo,Ar(Cr([Sr(mr(e.n,"base64url")),Sr(mr(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return In.createV1(114,this._multihash)}toString(){return Gt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(this.raw,e.raw)}verify(e,t,n){return async function(e,t,n,r){const i=await Xs.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Xs.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 oo=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class uo{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(jr(e),Ur(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),$r(r)}update(e){return qr(this),this.iHash.update(e),this}digestInto(e){qr(this),Ur(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 co=(e,t,n)=>new uo(e,t).update(n).digest();co.create=(e,t)=>new uo(e,t);const lo=(e,t)=>(e+(e>=0?t:-t)/go)/t;function po(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function ho(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Ni(n.lowS,"lowS"),Ni(n.prehash,"prehash"),void 0!==n.format&&po(n.format),n}class fo extends Error{constructor(e=""){super(e)}}const mo={Err:fo,_tlv:{encode:(e,t)=>{const{Err:n}=mo;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=Bi(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Bi(i.length/2|128):"";return Bi(e)+s+i+t},decode(e,t){const{Err:n}=mo;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}=mo;if(e<yo)throw new t("integer: negative integers are not allowed");let n=Bi(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}=mo;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 ji(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=mo,i=Ur(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}=mo,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s));return t.encode(48,r+i)}},yo=BigInt(0),bo=BigInt(1),go=BigInt(2),vo=BigInt(3),wo=BigInt(4);function To(e,t={}){const n=Rs("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:a,n:o}=s;Wi(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=Po(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 Ni(n,"isCompressed"),n?(c(),Yr(Eo(!r.isOdd(s)),a)):Yr(Uint8Array.of(4),a,r.toBytes(s))},p=t.fromBytes||function(e){Ur(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,vo),wo),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 P))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=lo(a*e,n),u=lo(-i*e,n);let d=e-o*r-u*s,c=-o*i-u*a;const l=d<yo,p=c<yo;l&&(d=-d),p&&(c=-c);const h=Hi(Math.ceil(function(e){let t;for(t=0;e>_i;e>>=Li,t+=1);return t}(n)/2))+bo;if(d<yo||d>=h||c<yo||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=Qi((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=Qi(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 P(r.mul(n.X,e),n.Y,n.Z),t=Es(i,t),n=Es(s,n),t.add(n)}class P{static BASE=new P(s.Gx,s.Gy,r.ONE);static ZERO=new P(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 P)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?P.ZERO:new P(t,n,r.ONE)}static fromBytes(e){const t=P.fromAffine(p(Ur(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return P.fromBytes(Qr(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(vo),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 P(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,vo),{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 P(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,vo);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 P(d,c,l)}subtract(e){return this.add(e.negate())}is0(){return this.equals(P.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=>Ps(P,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 Ps(P,[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===yo||r.is0())return P.ZERO;if(e===bo)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>ws||r>ws;)n&Ts&&(s=s.add(i)),r&Ts&&(a=a.add(i)),i=i.double(),n>>=Ts,r>>=Ts;return{p1:s,p2:a}}(P,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===bo||(e?e(P,this):S.unsafe(this,o).is0())}clearCofactor(){const{clearCofactor:e}=t;return a===bo?this:e?e(P,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return Ni(e,"isCompressed"),this.assertValidity(),l(P,this,e)}toHex(e=!0){return Hr(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const x=i.BITS,S=new Ms(P,t.endo?Math.ceil(x/2):x);return P.BASE.precompute(8),P}function Eo(e){return Uint8Array.of(e?2:3)}function Po(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={}){jr(t),Wi(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=(n=Object.assign({},n)).randomBytes||Zr,i=n.hmac||((e,n)=>co(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||Zr,i=Object.assign(Po(e.Fp,n),{seed:vs(n.ORDER)});function s(e=r(i.seed)){return function(e,t,n=!1){Ur(e);const r=e.length,i=gs(t),s=vs(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const a=as(n?qi(e):ji(e),t-Ji)+Ji;return n?zi(a,i):$i(a,i)}(Ur(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(!Or(e))return;if("_lengths"in n&&n._lengths||t===r)return;const a=Ur(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=_s(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*go<s.ORDER;function y(e){return e>o>>bo}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){po(t);const n=h.signature;return Ur(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}=mo.toSig(Ur(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(Qr(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(Yr(Eo(!(1&i)),d)),l=a.inv(u),p=E(Ur(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(po(e),"der"===e)return Qr(mo.hexFromSig(this));const{r:t,s:n}=this,r=a.toBytes(t),i=a.toBytes(n);return"recovered"===e?(g(),Yr(Uint8Array.of(this.assertRecovery()),r,i)):Yr(r,i)}toHex(e){return Hr(this.toBytes(e))}}const T=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=ji(e),n=8*e.length-u;return n>0?t>>BigInt(n):t},E=n.bits2int_modN||function(e){return a.create(T(e))},P=Hi(u);function x(e){return Ki("num < 2^"+u,e,yo,P),a.toBytes(e)}function S(e,n){return Ur(e,void 0,"message"),n?Ur(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}=ho(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=[x(c),x(d)];if(null!=u&&!1!==u){const e=!0===u?r(h.secretKey):u;l.push(Ur(e,void 0,"extraEntropy"))}const p=Yr(...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===yo)return;const u=a.create(r*a.create(b+o*c));if(u===yo)return;let d=(i.x===o?0:2)|Number(i.y&bo),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(Br(e,"hashLen"),Br(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,Yr(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 Yr(...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}=ho(i,f);if(r=Ur(r,void 0,"publicKey"),n=S(n,o),!Or(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}=ho(n,f);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}const So={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ao={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Co=/* @__PURE__ */BigInt(2),ko=bs(So.p,{sqrt:function(e){const t=So.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=os(c,n,t)*c%t,p=os(l,n,t)*c%t,h=os(p,Co,t)*d%t,f=os(h,i,t)*h%t,m=os(f,s,t)*f%t,y=os(m,o,t)*m%t,b=os(y,u,t)*y%t,g=os(b,o,t)*m%t,v=os(g,n,t)*c%t,w=os(v,a,t)*f%t,T=os(w,r,t)*d%t,E=os(T,Co,t);if(!ko.eql(ko.sqr(E),e))throw new Error("Cannot find square root");return E}}),Io=/* @__PURE__ */xo(/* @__PURE__ */To(So,{Fp:ko,endo:Ao}),Fi);class Do{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return Io.Point.fromBytes(e),e}catch(e){throw new Ye(String(e))}}(e),this.raw=function(e){return Io.Point.fromBytes(e).toBytes()}(this._key)}toMultihash(){return Ln(Ro(this))}toCID(){return In.createV1(114,this.toMultihash())}toString(){return Gt.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Nn(this.raw,e.raw)}verify(e,t,n){return function(e,t,n,r){const i=dr.digest(n instanceof Uint8Array?n:n.subarray());if(na(i))return i.then(({digest:n})=>(r?.signal?.throwIfAborted(),Io.verify(t,n,e,{prehash:!1,format:"der"}))).catch(e=>{if("AbortError"===e.name)throw e;throw new Js(String(e))});try{return r?.signal?.throwIfAborted(),Io.verify(t,i.digest,e,{prehash:!1,format:"der"})}catch(e){throw new Js(String(e))}}(this._key,t,e,n)}}function Mo(e){return new Do(e)}function Fo(e,t){const{Type:n,Data:r}=ro.decode(e),i=r??new Uint8Array;switch(n){case to.RSA:return function(e,t){if(e.byteLength>=1062)throw new Ye("Key size is too large");return function(e,t,n){const r=function(e){const t=Tr(e[1],{offset:0});return{kty:"RSA",n:yr(t[0],"base64url"),e:yr(t[1],"base64url")}}(e);return null==n&&(n=Pn(18,Fi(ro.encode({Type:to.RSA,Data:t})))),new ao(r,n)}(Tr(e,{offset:0}),e,t)}(i,t);case to.Ed25519:return sa(i);case to.secp256k1:return Mo(i);case to.ECDSA:return _r(i);default:throw new gt}}function Ro(e){return ro.encode({Type:to[e.type],Data:e.raw})}const _o=Symbol.for("nodejs.util.inspect.custom");class Lo{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=Gt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return In.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Nn(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Nn(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[_o](){return`PeerId(${this.toString()})`}}class No extends Lo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Oo extends Lo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Bo extends Lo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class Uo{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ln(mr(this.url))}[_o](){return`PeerId(${this.url})`}[xt]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return In.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=yr(e)),e.toString()===this.toString())}}function jo(e,t){let n;if("1"===e.charAt(0)||"Q"===e.charAt(0))n=xn(Gt.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return zo(In.parse(e));if(null==t)throw new Qe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');n=xn(t.decode(e))}return $o(n)}function qo(e){if("Ed25519"===e.type)return new Oo({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Bo({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new No({multihash:e.toCID().multihash,publicKey:e});throw new gt}function $o(e){if(function(e){return e.code===dr.code}(e))return new No({multihash:e});if(function(e){return 0===e.code}(e))try{const t=function(e){const{Type:t,Data:n}=ro.decode(e.digest),r=n??new Uint8Array;switch(t){case to.Ed25519:return sa(r);case to.secp256k1:return Mo(r);case to.ECDSA:return _r(r);default:throw new gt}}(e);if("Ed25519"===t.type)return new Oo({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Bo({multihash:e,publicKey:t})}catch(t){const n=yr(e.digest);return new Uo(new URL(n))}throw new ot("Supplied PeerID Multihash is invalid")}function zo(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new at("Supplied PeerID CID is invalid");if(2336===e.code){const t=yr(e.multihash.digest);return new Uo(new URL(t))}return $o(e.multihash)}class Vo extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class Go extends Error{static name="ValidationError";name="ValidationError"}class Ko extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class Ho extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const Wo=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 Qo(e){if(!(e.length>15))return Wo.new(e).parseWith(()=>Wo.readIPv4Addr())}function Yo(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Wo.new(e).parseWith(()=>Wo.readIPv6Addr())}function Jo(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const n=Wo.new(e).parseWith(()=>Wo.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 Zo(e){return Boolean(Qo(e))}function Xo(e){return Boolean(Yo(e))}const eu=41,tu=421,nu=448,ru=449,iu=466,su=281,au=290;function ou(e){return t=>yr(t,e)}function uu(e){return t=>mr(t,e)}function du(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function cu(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function lu(e){const t=e.subarray(0,e.length-2),n=e.subarray(e.length-2);return`${yr(t,"base32")}:${du(n)}`}const pu=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 Vo("Invalid byte value in IP address");t[n]=r}),t},hu=Object.values(cr).map(e=>e.decoder),fu=function(){let e=hu[0].or(hu[1]);return hu.slice(2).forEach(t=>e=e.or(t)),e}(),mu=function(...e){return t=>{for(const n of e)n(t)}}(function(e){if(parseInt(e).toString()!==e)throw new Go("Value must be an integer")},function(e){if(e<0)throw new Go("Value must be a positive integer, or zero")},e=>{if(e>65535)throw new Go("Value must be smaller than or equal to 65535")}),yu=-1,bu=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 Ho(`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)}))}},gu=[{code:4,name:"ip4",size:32,valueToBytes:pu,bytesToValue:function(e){if(4!==e.byteLength)throw new Vo("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(!Zo(e))throw new Go(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:cu,bytesToValue:du,validate:mu},{code:273,name:"udp",size:16,valueToBytes:cu,bytesToValue:du,validate:mu},{code:33,name:"dccp",size:16,valueToBytes:cu,bytesToValue:du,validate:mu},{code:eu,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;Zo(n[r])&&(e=pu(n[r]),n[r]=yr(e.subarray(0,2),"base16")),null!=e&&++r<8&&n.splice(r,0,yr(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 Vo("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 Vo("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 Vo(`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 Vo(`Invalid IPv6 address "${e}"`)}},validate:e=>{if(!Xo(e))throw new Go(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:yu},{code:43,name:"ipcidr",size:8,bytesToValue:ou("base10"),valueToBytes:uu("base10")},{code:53,name:"dns",size:yu},{code:54,name:"dns4",size:yu},{code:55,name:"dns6",size:yu},{code:56,name:"dnsaddr",size:yu},{code:132,name:"sctp",size:16,valueToBytes:cu,bytesToValue:du,validate:mu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:yu,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:tu,name:"p2p",aliases:["ipfs"],size:yu,bytesToValue:ou("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?uu("base58btc")(e):In.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:lu,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=mr(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=cu(r);return Un([n,i],n.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:lu,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=Wt.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=cu(r);return Un([n,i],n.length+i.length)}},{code:446,name:"garlic64",size:yu},{code:447,name:"garlic32",size:yu},{code:nu,name:"tls"},{code:ru,name:"sni",size:yu},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:iu,name:"certhash",size:yu,bytesToValue:(vu=er,e=>vu.encoder.encode(e)),valueToBytes:function(e){return fu.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:yu,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:su,name:"webrtc"},{code:au,name:"p2p-circuit"},{code:777,name:"memory",size:yu}];var vu;function wu(e,t,n){return null==e.size||0===e.size?0:e.size>0?e.size/8:wa(t,n)}gu.forEach(e=>{bu.addProtocol(e)});const Tu=Symbol.for("nodejs.util.inspect.custom"),Eu=Symbol.for("@multiformats/multiaddr");class Pu{[Eu]=!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=wa(e,n),i=bu.getProtocol(r),s=ya(r),a=wu(i,e,n+s);let o=0;a>0&&i.size===yu&&(o=ya(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)??yr(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 Vo('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=bu.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 Vo(`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 Vo(`Component ${i} was missing value`);s.value=e.stringToValue?.(r)??r}t.push(s),r="",i="",n="protocol"}}}if(""!==i&&""!==r)throw new Vo("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new Vo("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach(e=>{const t=bu.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=bu.getProtocol(r.code),t=ya(r.code);let n,i=0,s=0;null!=r.value&&(n=e.valueToBytes?.(r.value)??mr(r.value),i=n.byteLength,e.size===yu&&(s=ya(i)));const a=new Uint8Array(t+s+i);let o=0;ba(r.code,a,o),o+=t,null!=n&&(e.size===yu&&(ba(i,a,o),o+=s),a.set(n,o)),r.bytes=a}n.push(r.bytes),t+=r.bytes.byteLength}return Un(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=bu.getProtocol(e.code);if(null==t)throw new Vo(`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 Pu(e);return new Pu([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),n=this.toString(),r=n.lastIndexOf(t);if(r<0)throw new Ko(`Address ${this.toString()} does not contain subaddress: ${t}`);return new Pu(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 Pu(this.#t.slice(0,t),{validate:!1})}equals(e){return Nn(this.bytes,e.bytes)}[Tu](){return`Multiaddr(${this.toString()})`}}function xu(e){return Boolean(e?.[Eu])}function Su(e){return new Pu(e)}function Au(e){return Array.from(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function Cu(e){for(var t,n=e.reduce(function(e,t){return e+t.length},0),r=new Uint8Array(n),i=0,s=k(e);!(t=s()).done;){var a=t.value;r.set(a,i),i+=a.length}return r}function ku(e,t){var n=d.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"+Au(t)}(e)),r=d.encrypt(n.toHex(),(new TextEncoder).encode(t));return Au(new Uint8Array(r))}function Iu(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Du=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getConsumerAddress=function(e){return hT(e)},t.getSignature=function(e,t,n){return pT(e,t,n)},t.getAuthorization=function(e){return fT(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=k(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(Iu(function(){return Promise.resolve(n.getData(e,t)).then(function(e){return Promise.resolve(e.json())})},function(e){throw B.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?Iu(function(){return Promise.resolve(v.default(r.urlPath,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:E.STATUS}),signal:t})).then(function(e){return null!=e&&e.ok?e.json():null})},function(e){return B.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),Iu(function(){return Promise.resolve(v.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 B.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?Iu(function(){return Promise.resolve(v.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 B.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,E.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,Iu(function(){return Promise.resolve(v.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 B.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 B.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=k(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=Iu(function(){return Promise.resolve(v.default(c,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json"},signal:i})).then(function(e){o=e})},function(e){throw B.error("File info call failed: "),B.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 B.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=k(e);!(n=r()).done;)u.push(n.value);return t=1,u})}();return r&&r.then?r.then(n):n(r)}var a,o=I({},e,{checksum:n}),u=[],d=i.getEndpointURL(t,"fileinfo")?i.getEndpointURL(t,"fileinfo").urlPath:null;if(!d)return null;var c=Iu(function(){return Promise.resolve(v.default(d,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){a=e})},function(e){throw B.error("File info call failed: "),B.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 B.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=Iu(function(){return Promise.resolve(v.default(a,{method:"GET",headers:{"Content-Type":"application/json"},signal:t})).then(function(e){s=e})},function(e){throw B.error("Fetch compute env failed: "),B.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 B.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=Iu(function(){return Promise.resolve(v.default(p,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})).then(function(e){l=e})},function(e){throw B.error("Provider initialized failed: "),B.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 B.error("Initialize compute failed: ",e.status,e.statusText,t),B.error("Payload was:",JSON.stringify(g)),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=Iu(function(){return Promise.resolve(v.default(b,{method:"POST",body:JSON.stringify(g),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 B.error("Initialize compute failed: "),B.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&&(g.output=ku(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 g={datasets:e,algorithm:t,environment:n,payment:{chainId:u,token:r,resources:o},maxJobDuration:i,consumerAddress:a};d&&(g.policyServer=d),l&&(g.queueMaxWaitTime=l);var w=function(){if(p)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(g.encryptedDockerRegistryAuth=ku(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,E.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(g){var w=y.getEndpointURL(g,"computeStart")?y.getEndpointURL(g,"computeStart").urlPath:null;return w?Promise.resolve(y.getConsumerAddress(t)).then(function(T){return Promise.resolve(y.getNonce(e,T,h,b,g)).then(function(b){var g=(b+1).toString();return Promise.resolve(y.getSignature(t,g,E.COMPUTE_START)).then(function(b){function E(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw B.error("Compute start failed: ",e.status,e.statusText,t),B.error("Payload was:",P),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&&(P.policyServer=p),f&&(P.queueMaxWaitTime=f);var r=Iu(function(){return Promise.resolve(v.default(w,{method:"POST",body:JSON.stringify(P),headers:{"Content-Type":"application/json",Authorization:y.getAuthorization(t)},signal:h})).then(function(t){e=t})},function(e){throw B.error("Compute start failed:"),B.error(e),B.error("Payload was:",P),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}o&&(P.resources=o),d&&(P.metadata=d),c&&(P.additionalViewers=c);var r=function(){if(l)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(P.output=ku(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var P=Object();P.consumerAddress=T,P.signature=b,P.nonce=g,P.environment=n,P.maxJobDuration=s,P.resources=o,P.dataset=r[0],P.datasets=r,P.algorithm=i,P.chainId=u,P.payment={chainId:u,token:a,maxJobDuration:s,resources:o};var x=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(P.encryptedDockerRegistryAuth=ku(e,JSON.stringify(m)))})}();return x&&x.then?x.then(E):E()})})}):(B.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,E.FREE_COMPUTE_START)).then(function(f){function g(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw B.error("Compute start failed: ",e.status,e.statusText,t),B.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=Iu(function(){return Promise.resolve(v.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 B.error("Compute start failed:"),B.error(e),B.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=ku(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=ku(e,JSON.stringify(p)))})}();return T&&T.then?T.then(g):g()})})}):(B.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=B.error,s=e.statusText,a=e.status;return Promise.resolve(e.json()).then(function(e){return i.call(B,"computeStreamableLogs failed: ",a,s,e),null})}var s=Iu(function(){return Promise.resolve(v.default(u+c,{method:"GET",headers:{"Content-Type":"application/json",Authorization:i.getAuthorization(t)},signal:r})).then(function(t){e=t})},function(e){throw B.error("computeStreamableLogs failed:"),B.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,E.COMPUTE_GET_STREAMABLE_LOGS)).then(function(e){c+="&signature="+e,c+="&nonce="+o})}();return l&&l.then?l.then(a):a()})}):(B.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,E.COMPUTE_STOP)).then(function(t){function u(e){var t;function n(e){return t?e:Promise.resolve(p.json()).then(function(e){throw B.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=Iu(function(){return Promise.resolve(v.default(d+"?"+h,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:s.getAuthorization(n)},signal:i})).then(function(e){p=e})},function(e){throw B.error("Compute stop failed:"),B.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(hT(t)).then(function(a){var o=fT(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 B.error("Get compute status failed:",u.status,u.statusText,e),new Error(JSON.stringify(e))})}B.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=Iu(function(){return Promise.resolve(v.default(d+c,{method:"GET",headers:{"Content-Type":"application/json",Authorization:o},signal:i})).then(function(e){u=e})},function(e){throw B.error("Get compute status failed"),B.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,E.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(v.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,E.CREATE_AUTH_TOKEN)).then(function(e){return Iu(function(){return Promise.resolve(v.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 B.error("Generate auth token failed:"),B.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(ze(e,s+i)).then(function(e){return Iu(function(){return Promise.resolve(v.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 B.error("Generate auth token failed:"),B.error(e),new Error("HTTP request failed calling Provider")})})})})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){try{return Promise.resolve(Iu(function(){return Promise.resolve(v.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 B.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 B.error("PolicyServerPassthrough failed: ",s.status,s.statusText,e),B.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=Iu(function(){return Promise.resolve(v.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 B.error("PolicyServerPassthrough failed: "),B.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 B.error("initializePSVerification failed: ",s.status,s.statusText,e),B.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=Iu(function(){return Promise.resolve(v.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 B.error("initializePSVerification failed: "),B.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,E.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 B.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=Iu(function(){return Promise.resolve(v.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 B.error("Download node logs failed:"),B.error(e),new Error("HTTP request failed calling Provider")});return f&&f.then?f.then(t):t()})})}):(B.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 B.debug("Not input string:"),B.debug(e),new Error("["+n+"] Expected string, input type: "+typeof e);var r=e.match(t);return r?{valid:!0,output:r[1]}:(B.warn("["+n+"] Input transformation failed."),{valid:!1,output:e})},t.resolveDdo=function(e,t,n){try{return Promise.resolve(v.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(ze(n,s+o+E.VALIDATE_DDO)).then(function(n){return Promise.resolve(v.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(v.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,E.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(e){var i,s={"Content-Type":"application/json"};return"string"==typeof t&&(s.Authorization=t),Promise.resolve(v.default(a,{method:"POST",headers:s,body:JSON.stringify(I({},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,E.PERSISTENT_STORAGE_GET_BUCKETS,r)).then(function(e){var i={};"string"==typeof t&&(i.Authorization=t);var s=new URLSearchParams(I({},e,{owner:n}));return Promise.resolve(v.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,E.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(e){var n={};"string"==typeof t&&(n.Authorization=t);var i=new URLSearchParams(I({},e));return Promise.resolve(v.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,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(e){var n=new URLSearchParams(I({},e)),r={};return"string"==typeof t&&(r.Authorization=t),Promise.resolve(v.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,E.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(v.default(u+"?"+o.toString(),{method:"POST",body:r,headers:I({},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(I({},e)),d=function(){if("undefined"==typeof window)return Promise.resolve(import("stream")).then(function(e){var t=e.Readable,n=new TextEncoder,s=R(/*#__PURE__*/M().mark(function e(){var t,r,s,a,o,u,d;return M().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=!1,r=!1,e.prev=2,a=S(i);case 4:return e.next=6,C(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,C(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,E.PERSISTENT_STORAGE_DELETE_FILE,i)).then(function(e){var n={"Content-Type":"application/json"};"string"==typeof t&&(n.Authorization=t);var r=new URLSearchParams(I({},e));return Promise.resolve(v.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 Mu(e){if(null===e.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Qe("Private network is enforced, but no protector was provided");return e}const Fu=1e3,Ru=60*Fu,_u=60*Ru,Lu=24*_u,Nu=7*Lu,Ou=365.25*Lu,Bu=Ou/12;var Uu=function(e,t){if("string"==typeof e)return ju(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?$u(e):qu(e)}(e,t);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(e)}`)};function ju(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*Ou;case"months":case"month":case"mo":return i*Bu;case"weeks":case"week":case"w":return i*Nu;case"days":case"day":case"d":return i*Lu;case"hours":case"hour":case"hrs":case"hr":case"h":return i*_u;case"minutes":case"minute":case"mins":case"min":case"m":return i*Ru;case"seconds":case"second":case"secs":case"sec":case"s":return i*Fu;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 qu(e){let t=Math.abs(e);return t>=Ou?`${Math.round(e/Ou)}y`:t>=Bu?`${Math.round(e/Bu)}mo`:t>=Nu?`${Math.round(e/Nu)}w`:t>=Lu?`${Math.round(e/Lu)}d`:t>=_u?`${Math.round(e/_u)}h`:t>=Ru?`${Math.round(e/Ru)}m`:t>=Fu?`${Math.round(e/Fu)}s`:`${e}ms`}function $u(e){let t=Math.abs(e);return t>=Ou?zu(e,t,Ou,"year"):t>=Bu?zu(e,t,Bu,"month"):t>=Nu?zu(e,t,Nu,"week"):t>=Lu?zu(e,t,Lu,"day"):t>=_u?zu(e,t,_u,"hour"):t>=Ru?zu(e,t,Ru,"minute"):t>=Fu?zu(e,t,Fu,"second"):`${e} ms`}function zu(e,t,n,r){let i=t>=1.5*n;return`${Math.round(e/n)} ${r}${i?"s":""}`}const Vu=function(){try{return localStorage}catch(e){}}(),Gu=console.debug??console.log??(()=>{});var Ku=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=Uu,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 ":" ")+"+"+Uu(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?Vu?.setItem("debug",e):Vu?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=Vu?.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:Vu,log:Gu});function Hu(e,t=""){const n=Ju(e.message),r=Ju(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 Wu(e,t=""){if(function(e){return e instanceof AggregateError||"AggregateError"===e?.name&&Array.isArray(e.errors)}(e)){let n=Hu(e,t);return n+=e.errors.length>0?`\n${t=`${t} `}${e.errors.map(e=>`${Wu(e,`${t}`)}`).join(`\n${t}`)}`:`\n${t}[Error list was empty]`,n.trim()}return Hu(e,t)}function Qu(e){return{forComponent:t=>Yu(t,e)}}function Yu(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 Ku.enabled(`${e}:trace`)&&null!=Ku.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(n=Ku(`${e}:trace`,t)),Object.assign(Ku(e,t),{error:Ku(`${e}:error`,t),trace:n,newScope:n=>Yu(`${e}:${n}`,t)})}function Ju(e){if(null!=e&&0!==(e=e.trim()).length)return e}function Zu(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 Xu(e){return $o(xn(Gt.decode(`z${e}`)))}Ku.formatters.b=e=>null==e?"undefined":Gt.baseEncode(e),Ku.formatters.t=e=>null==e?"undefined":Wt.baseEncode(e),Ku.formatters.m=e=>null==e?"undefined":Zn.baseEncode(e),Ku.formatters.p=e=>null==e?"undefined":e.toString(),Ku.formatters.c=e=>null==e?"undefined":e.toString(),Ku.formatters.k=e=>null==e?"undefined":e.toString(),Ku.formatters.a=e=>null==e?"undefined":e.toString(),Ku.formatters.e=e=>null==e?"undefined":Wu(e);class ed{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 Zu(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 Zu(this.map.values(),e=>e.key)}values(){return Zu(this.map.values(),e=>e.value)}get size(){return this.map.size}}class td{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 Zu(this.set.entries(),e=>{const t=Xu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{const n=Xu(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Zu(this.set.values(),e=>Xu(e))}intersection(e){const t=new td;for(const n of e)this.has(n)&&t.add(n);return t}difference(e){const t=new td;for(const n of this)e.has(n)||t.add(n);return t}union(e){const t=new td;for(const n of e)t.add(n);for(const e of this)t.add(e);return t}}const nd={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},rd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},id=new globalThis.TextEncoder,sd={hash:e=>Number(function(e,{size:t=32,utf8Buffer:n}={}){if(!nd[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=nd[t];let i=rd[t],s=e;for(;s.length>0;){const e=id.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=id.encode(e)}return function(e,t){const n=nd[t];let r=rd[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}`),mr(t,"base16")}(sd.hash(e,t))};class ad{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=On(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&&Nn(this.fp,e.fp)}}function od(e,t){return Math.floor(Math.random()*(t-e))+e}class ud{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ad))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ad))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 ad))throw new TypeError("Invalid Fingerprint");const t=od(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ad))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex(t=>e.equals(t));return t>-1&&(this.contents[t]=null,!0)}}class dd{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??sd,this.seed=e.seed??od(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=mr(e));const t=new ad(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 ud(this.bucketSize)),null==this.buckets[r]&&(this.buckets[r]=new ud(this.bucketSize)),this.buckets[n].add(t)||this.buckets[r].add(t))return this.count++,!0;const i=[n,r];let s=i[od(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new ud(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 ud(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=mr(e));const t=new ad(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=mr(e));const t=new ad(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 cd={1:.5,2:.84,4:.95,8:.98};function ld(e,t=.001){const n=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/cd[n]),bucketSize:n,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*n)),64)}}class pd{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??sd,this.seed=e.seed??od(0,Math.pow(2,10)),this.filterSeries=[new dd({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=mr(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 dd({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=mr(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=mr(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 hd(e,t=.001,n){return new pd({...ld(e,t),...n??{}})}function fd(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 Qe(`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 md=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function yd(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,md)&&(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 bd(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 gd{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=Qo(t);if(null==i&&(r=16,i=Yo(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=bd(s,8*r);return{network:yd(i,a),mask:a}}(e));else{const n=Jo(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=Jo(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=bd(r,8*n.length);this.network=yd(n,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Jo(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 vd(e){try{const n=fd(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 wd(e){try{return fd(e),!0}catch{return!1}}var Td="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ed(e){var t={exports:{}};return e(t,t.exports),t.exports}var Pd=Ed(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(Td)});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 Pd.Netmask(e));function Sd(e){for(const t of xd)if(t.contains(e))return!0;return!1}function Ad(e){return Zo(e)?Sd(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 Sd(`${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 Sd(t[t.length-1])}(e):Xo(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 Cd(e){try{const t=fd(e);switch(t.type){case"ip4":case"ip6":return Ad(t.host)??!1;default:return"localhost"===t.host}}catch{return!1}}function kd(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class Id{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 Dd{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Id(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 Id(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 Md extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Fd(e={}){return function(e,t){let n,r,i,s=(t=t??{}).onEnd,a=new Dd,o=kd();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 Dd,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=kd()})}},return:()=>(a=new Dd,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 Md)},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 Rd extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Rd)}}const _d=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Ld(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(_d(a));if(a&&(u=()=>{d(_d(a))},a.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Rd;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 Nd(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 Od 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 Bd extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Ud extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class jd extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"}class qd extends Error{static name="StreamClosedError";name="StreamClosedError"}function $d(e){return e.reason}async function zd(e,t,n){if(null==t)return e;const r=n?.translateError??$d;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 Vd{deferred;signal;constructor(e){this.signal=e,this.deferred=kd(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ke)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Gd{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 Ke),this.cleanup())}async join(e={}){const t=new Vd(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 zd(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 Kd extends Rt{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=Nd(this.emitEmpty.bind(this),1),this.emitIdle=Nd(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 Bd;const n=new Gd(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 Ke)}),this.clear()}async onEmpty(e){0!==this.size&&await Ld(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Ld(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Ld(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=Fd({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 Ke("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 Hd=4*Math.pow(2,20);class Wd extends Rt{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??Hd,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new zn,this.writeBuffer=new zn,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 qd)})}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()),zd(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if("readable"!==this.readStatus&&"paused"!==this.readStatus)return;const e=Fd(),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 tt(`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 Tt(e))}}pause(){if("closed"===this.readStatus||"closing"===this.readStatus)throw new tt("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 tt("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 tt(`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 tt(`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 et;this.dispatchEvent(new Et(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 wt))}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 zn(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 vt(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 nt(`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 nt(`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 Qd extends Wd{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 Ld(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 Ld(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}}class Yd extends Rt{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 zd(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 Xe;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 jd(`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 Jd extends Wd{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 Ld(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 Ld(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 Zd(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 Xd{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 ec{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new Xd(t),this.failure=new Xd(t),this.next=new Xd(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=Zd([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 tc{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=kd(),this.haveNext=kd()}[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=kd(),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=kd(),await zd(this.readNext.promise,t?.signal,t)}}function nc(...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 tc;(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 rc(e,...t){if(null==e)throw new Error("Empty pipeline");if(oc(e)){const t=e;e=()=>t.source}else if(ac(e)||sc(e)){const t=e;e=()=>t}const n=[e,...t];if(n.length>1&&oc(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++)oc(n[e])&&(n[e]=uc(n[e]));return ic(...n)}const ic=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},sc=e=>null!=e?.[Symbol.asyncIterator],ac=e=>null!=e?.[Symbol.iterator],oc=e=>null!=e&&null!=e.sink&&null!=e.source,uc=e=>t=>{const n=e.sink(t);if(null!=n?.then){const t=Fd({objectMode:!0});let r;n.then(()=>{t.end()},e=>{t.end(e)});const i=e.source;if(sc(i))r=async function*(){yield*i,t.end()};else{if(!ac(i))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");r=function*(){yield*i,t.end()}}return nc(t,r())}return e.source};class dc extends Error{static name="UnwrappedError";name="UnwrappedError"}class cc extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class lc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class pc extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function hc(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 fc(e,t){const n=t?.maxBufferSize??4194304,r=new zn;let i,s=!1;if(a=e,null==a?.addEventListener||null==a?.removeEventListener||null==a?.send||null==a?.push||null==a?.log)throw new Qe("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 dc("Stream was unwrapped");if(hc(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 Ud(`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 zd(i.promise,t?.signal),hc(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(hc(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,a),new Ud(`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 dc("Stream was unwrapped");e.send(t)||await Ld(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 mc(e,t={}){const n=fc(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=ya(t.maxDataLength));const r=t?.lengthDecoder??wa,i=t?.lengthEncoder??va;return{async read(i){let s=-1;const a=new zn;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 cc("Invalid message length");if(null!=t?.maxLengthLength&&a.byteLength>t.maxLengthLength)throw new pc(`Message length length too long - ${a.byteLength} > ${t.maxLengthLength}`);if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new lc(`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 Ud(`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 Ud(`Unexpected EOF - read ${o.byteLength}/${s} bytes before the stream closed`);return o},async write(e,t){await n.write(new zn(i(e.byteLength),e),t)},async writeV(e,t){const r=new zn(...e.flatMap(e=>[i(e.byteLength),e]));await n.write(r,t)},unwrap:()=>n.unwrap()}}function yc(e,t){const n=mc(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 bc{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new zn,this.maxBufferSize=e.maxBufferSize??4194304,this.maxDataLength=e.maxDataLength??4194304,this.lengthDecoder=e.lengthDecoder??wa,this.encodingLength=e.encodingLength??ya}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Qe(`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 cc("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 gc=4194304;class vc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}function wc(e,t){if(e.byteLength>t)throw new vc("Message length too long")}const Tc=e=>{const t=ya(e),n=Bn(t);return va(e,n),Tc.bytes=t,n};function Ec(e,t){const n=(t=t??{}).lengthEncoder??Tc,r=t?.maxDataLength??gc;function*i(e){wc(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 Pc;Tc.bytes=0,Ec.single=(e,t)=>{const n=(t=t??{}).lengthEncoder??Tc;return wc(e,t?.maxDataLength??gc),new zn(n(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Pc||(Pc={}));class xc extends Kd{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}class Sc extends Kd{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}class Ac{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 Cc}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 Od("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 Cc{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 kc(e,t,n){let r,i,s=!1;function a(){const o={signal:i.signal};let u;null!=n?.timeout&&(u=Zd([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=Nd(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 Ic 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 Dc(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Ic({name:t,metrics:n}):new Map,r}class Mc{filter;constructor(e,t){this.filter=hd(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 Fc(e,t=.001){return new Mc(e,t)}class Rc extends ed{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 _c(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Rc({name:t,metrics:n}):new ed,r}const Lc=new Float32Array([-0]),Nc=new Uint8Array(Lc.buffer);function Oc(e,t,n){Lc[0]=e,t[n]=Nc[0],t[n+1]=Nc[1],t[n+2]=Nc[2],t[n+3]=Nc[3]}const Bc=new Float64Array([-0]),Uc=new Uint8Array(Bc.buffer);function jc(e,t,n){Bc[0]=e,t[n]=Uc[0],t[n+1]=Uc[1],t[n+2]=Uc[2],t[n+3]=Uc[3],t[n+4]=Uc[4],t[n+5]=Uc[5],t[n+6]=Uc[6],t[n+7]=Uc[7]}const qc=BigInt(Number.MAX_SAFE_INTEGER),$c=BigInt(Number.MIN_SAFE_INTEGER);class zc{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 Vc;if(e<qc&&e>$c)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>Gc&&(r=0n,++n>Gc&&(n=0n))),new zc(Number(r),Number(n))}static fromNumber(e){if(0===e)return Vc;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 zc(n,r)}static from(e){return"number"==typeof e?zc.fromNumber(e):"bigint"==typeof e?zc.fromBigInt(e):"string"==typeof e?zc.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new zc(e.low>>>0,e.high>>>0):Vc}}const Vc=new zc(0,0);Vc.toBigInt=function(){return 0n},Vc.zzEncode=Vc.zzDecode=function(){return this},Vc.length=function(){return 1};const Gc=4294967296n;function Kc(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 Hc(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Wc(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Qc{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,Hc(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 Hc(this,4);return Wc(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Hc(this,4);return 0|Wc(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Hc(this,4);const e=(Nc[0]=(t=this.buf)[n=this.pos],Nc[1]=t[n+1],Nc[2]=t[n+2],Nc[3]=t[n+3],Lc[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Hc(this,4);const e=(Uc[0]=(t=this.buf)[n=this.pos],Uc[1]=t[n+1],Uc[2]=t[n+2],Uc[3]=t[n+3],Uc[4]=t[n+4],Uc[5]=t[n+5],Uc[6]=t[n+6],Uc[7]=t[n+7],Bc[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 Hc(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 Hc(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Hc(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 zc(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Hc(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 Hc(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 Hc(this,8);const e=Wc(this.buf,this.pos+=4),t=Wc(this.buf,this.pos+=4);return new zc(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=ga(this.buf,this.pos);return this.pos+=ya(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 Yc(e){return new Qc(e instanceof Uint8Array?e:e.subarray())}function Jc(e,t,n){const r=Yc(e);return t.decode(r,void 0,n)}class Zc{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Xc(){}class el{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const tl=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Bn(r);n+r>e&&(t=Bn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class nl{len;head;tail;states;constructor(){this.len=0,this.head=new Zc(Xc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Zc(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new sl((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(al,10,zc.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=zc.fromBigInt(e);return this._push(al,t.length(),t)}uint64Number(e){return this._push(ba,ya(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=zc.fromBigInt(e).zzEncode();return this._push(al,t.length(),t)}sint64Number(e){const t=zc.fromNumber(e).zzEncode();return this._push(al,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(rl,1,e?1:0)}fixed32(e){return this._push(ol,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=zc.fromBigInt(e);return this._push(ol,4,t.lo)._push(ol,4,t.hi)}fixed64Number(e){const t=zc.fromNumber(e);return this._push(ol,4,t.lo)._push(ol,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(Oc,4,e)}double(e){return this._push(jc,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(rl,1,0):this.uint32(t)._push(ul,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(Kc,t,e):this._push(rl,1,0)}fork(){return this.states=new el(this),this.head=this.tail=new Zc(Xc,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 Zc(Xc,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?Bn(n):tl(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function rl(e,t,n){t[n]=255&e}function il(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class sl extends Zc{next;constructor(e,t){super(il,e,t),this.next=void 0}}function al(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 ol(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 ul(e,t,n){t.set(e,n)}function dl(e,t,n){t.set(e,n)}function cl(e,t,n){e.length<40?Kc(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(mr(e),n)}function ll(e,t){const n=new nl;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*pl(e,t,n){const r=Yc(e);yield*t.stream(r,void 0,"$",n)}function hl(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&&(nl.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(dl,t,e),this},nl.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(cl,t,e),this});class fl extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var ml;!function(e){let t;e.codec=()=>(null==t&&(t=hl((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:On(0),payloadType:On(0),payload:On(0),signature:On(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 ll(t,e.codec())},e.decode=function(t,n){return Jc(t,e.codec(),n)},e.stream=function(t,n){return pl(t,e.codec(),n)}}(ml||(ml={}));class yl extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class bl{static createFromProtobuf=e=>{const t=ml.decode(e),n=Fo(t.publicKey);return new bl({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=gl(r,i,s),o=await t.sign(a.subarray(),n);return new bl({publicKey:t.publicKey,payloadType:i,payload:s,signature:o})};static openAndCertify=async(e,t,n)=>{const r=bl.createFromProtobuf(e);if(!await r.validate(t,n))throw new yl("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=ml.encode({publicKey:Ro(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Nn(this.marshal(),e.marshal())}async validate(e,t){const n=gl(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}}const gl=(e,t,n)=>{const r=mr(e),i=va(r.byteLength),s=va(t.length),a=va(n.length);return new zn(i,r,s,t,a,n)},vl=Uint8Array.from([3,1]);var wl;!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=hl((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:On(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 ll(t,e.codec())},e.decode=function(t,n){return Jc(t,e.codec(),n)},e.stream=function(t,n){return pl(t,e.codec(),n)}}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=hl((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:On(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 fl('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 fl('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 ll(t,e.codec())},e.decode=function(t,n){return Jc(t,e.codec(),n)},e.stream=function(t,n){return pl(t,e.codec(),n)}}(wl||(wl={}));class Tl{static createFromProtobuf=e=>{const t=wl.decode(e),n=$o(xn(t.peerId)),r=(t.addresses??[]).map(e=>Su(e.multiaddr));return new Tl({peerId:n,multiaddrs:r,seqNumber:t.seq})};static DOMAIN="libp2p-peer-record";static CODEC=vl;peerId;multiaddrs;seqNumber;domain=Tl.DOMAIN;codec=Tl.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=wl.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 Tl&&!!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 El(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 Pl 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 Pl(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(){Al(n,"abort",l),Al(e,t,d),Al(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)};Sl(n,"abort",l),Sl(e,t,d),Sl(e,s,c)})}function Sl(e,t,n){null!=e&&(Cl(e)?e.addEventListener(t,n):e.addListener(t,n))}function Al(e,t,n){null!=e&&(Cl(e)?e.removeEventListener(t,n):e.removeListener(t,n))}function Cl(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class kl extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Il{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 Pl)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Dl{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 Pl),this.cleanup())}async join(e={}){const t=new Il(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 zd(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 Ml(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 Fl extends Rt{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=Ml(this.emitEmpty.bind(this),1),this.emitIdle=Ml(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 kl;const n=new Dl(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 Pl)}),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=Fd({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 Pl("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 Rl="lock:worker:request-read",_l="lock:worker:abort-read-request",Ll="lock:worker:release-read",Nl="lock:master:grant-read",Ol="lock:master:error-read",Bl="lock:worker:request-write",Ul="lock:worker:abort-write-request",jl="lock:worker:release-write",ql="lock:master:grant-write",$l="lock:master:error-write",zl="lock:worker:finalize",Vl="mortice",Gl={singleProcess:!1},Kl=(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===zl&&e.safeDispatchEvent("finalizeRequest",{detail:{name:c.name}})};class Hl{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Vl)}readLock(e){return this.sendRequest(Rl,_l,Nl,Ol,Ll,e)}writeLock(e){return this.sendRequest(Bl,Ul,ql,$l,jl,e)}finalize(){this.channel.postMessage({type:zl,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 Wl=new Map;let Ql;function Yl(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}function Jl(e){if(null==Ql&&(Ql=(e=>{if(e=Object.assign({},Gl,e),Boolean(globalThis.document)||e.singleProcess){const e=new BroadcastChannel(Vl),t=new Rt;return e.addEventListener("message",Kl(t,e,"requestReadLock","abortReadLockRequest",Rl,_l,Ol,Ll,Nl)),e.addEventListener("message",Kl(t,e,"requestWriteLock","abortWriteLockRequest",Bl,Ul,$l,jl,ql)),t}return new Hl(e.name)})(e),!Yl(Ql))){const e=Ql;e.addEventListener("requestReadLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=Wl.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=Wl.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=Wl.get(e.detail.name);null!=t&&t.finalize()})}return Ql}async function Zl(e,t){let n,r;const i=new Promise((e,t)=>{n=e,r=t}),s=()=>{r(new Pl)};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 Xl={name:"lock",concurrency:Infinity,singleProcess:!1,autoFinalize:!1};function ep(e){const t=Object.assign({},Xl,e);return((e,t)=>{let n=Wl.get(e);if(null!=n)return n;const r=Jl(t);if(Yl(r))return n=r,Wl.set(e,n),n;const i=new Fl({concurrency:1});let s;return n={async readLock(e){if(null!=s)return Zl(s,e);s=new Fl({concurrency:t.concurrency,autoStart:!1});const n=s,r=Zl(s,e);return i.add(async()=>{n.start(),await n.onIdle().then(()=>{s===n&&(s=null)})}),r},writeLock:async e=>(s=null,Zl(i,e)),finalize:()=>{Wl.delete(e)},queue:i},Wl.set(e,n),!0===t.autoFinalize&&i.addEventListener("idle",()=>{n.finalize()},{once:!0}),n})(t.name,t)}const tp=new Float32Array([-0]),np=new Uint8Array(tp.buffer);function rp(e,t,n){tp[0]=e,t[n]=np[0],t[n+1]=np[1],t[n+2]=np[2],t[n+3]=np[3]}const ip=new Float64Array([-0]),sp=new Uint8Array(ip.buffer);function ap(e,t,n){ip[0]=e,t[n]=sp[0],t[n+1]=sp[1],t[n+2]=sp[2],t[n+3]=sp[3],t[n+4]=sp[4],t[n+5]=sp[5],t[n+6]=sp[6],t[n+7]=sp[7]}const op=BigInt(Number.MAX_SAFE_INTEGER),up=BigInt(Number.MIN_SAFE_INTEGER);class dp{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 cp;if(e<op&&e>up)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>lp&&(r=0n,++n>lp&&(n=0n))),new dp(Number(r),Number(n))}static fromNumber(e){if(0===e)return cp;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 dp(n,r)}static from(e){return"number"==typeof e?dp.fromNumber(e):"bigint"==typeof e?dp.fromBigInt(e):"string"==typeof e?dp.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new dp(e.low>>>0,e.high>>>0):cp}}const cp=new dp(0,0);cp.toBigInt=function(){return 0n},cp.zzEncode=cp.zzDecode=function(){return this},cp.length=function(){return 1};const lp=4294967296n;function pp(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 hp(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function fp(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class mp{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,hp(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 hp(this,4);return fp(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw hp(this,4);return 0|fp(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw hp(this,4);const e=(np[0]=(t=this.buf)[n=this.pos],np[1]=t[n+1],np[2]=t[n+2],np[3]=t[n+3],tp[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw hp(this,4);const e=(sp[0]=(t=this.buf)[n=this.pos],sp[1]=t[n+1],sp[2]=t[n+2],sp[3]=t[n+3],sp[4]=t[n+4],sp[5]=t[n+5],sp[6]=t[n+6],sp[7]=t[n+7],ip[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 hp(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 hp(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw hp(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 dp(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw hp(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 hp(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 hp(this,8);const e=fp(this.buf,this.pos+=4),t=fp(this.buf,this.pos+=4);return new dp(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=ga(this.buf,this.pos);return this.pos+=ya(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 yp(e,t,n){const r=function(e){return new mp(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(r,void 0,n)}class bp{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function gp(){}class vp{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const wp=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Bn(r);n+r>e&&(t=Bn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class Tp{len;head;tail;states;constructor(){this.len=0,this.head=new bp(gp,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new bp(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(Sp,10,dp.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=dp.fromBigInt(e);return this._push(Sp,t.length(),t)}uint64Number(e){return this._push(ba,ya(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=dp.fromBigInt(e).zzEncode();return this._push(Sp,t.length(),t)}sint64Number(e){const t=dp.fromNumber(e).zzEncode();return this._push(Sp,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ep,1,e?1:0)}fixed32(e){return this._push(Ap,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=dp.fromBigInt(e);return this._push(Ap,4,t.lo)._push(Ap,4,t.hi)}fixed64Number(e){const t=dp.fromNumber(e);return this._push(Ap,4,t.lo)._push(Ap,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(rp,4,e)}double(e){return this._push(ap,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Ep,1,0):this.uint32(t)._push(Cp,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(pp,t,e):this._push(Ep,1,0)}fork(){return this.states=new vp(this),this.head=this.tail=new bp(gp,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 bp(gp,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?Bn(n):wp(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function Ep(e,t,n){t[n]=255&e}function Pp(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class xp extends bp{next;constructor(e,t){super(Pp,e,t),this.next=void 0}}function Sp(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 Ap(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 Cp(e,t,n){t.set(e,n)}function kp(e,t,n){t.set(e,n)}function Ip(e,t,n){e.length<40?pp(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(mr(e),n)}function Dp(e,t){const n=new Tp;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var Mp,Fp,Rp,_p,Lp;function Np(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function Op(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Np("enum",Mp.VARINT,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())})}function Bp(e,t){return Np("message",Mp.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Tp.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(kp,t,e),this},Tp.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Ip,t,e),this}),(Lp=Mp||(Mp={}))[Lp.VARINT=0]="VARINT",Lp[Lp.BIT64=1]="BIT64",Lp[Lp.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",Lp[Lp.START_GROUP=3]="START_GROUP",Lp[Lp.END_GROUP=4]="END_GROUP",Lp[Lp.BIT32=5]="BIT32";class Up extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class jp extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function qp(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let n;return"RSA"===e.type&&(n=e.toMultihash()),qo(Fo(t.publicKey,n))}function $p(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:qp(e,t),addresses:t.addresses.filter(({observed:e})=>null!=e&&e>Date.now()-n).map(({multiaddr:e,isCertified:t})=>({multiaddr:Su(e),isCertified:t??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:r}}function zp(e,t){return null==e&&null==t||null!=e&&null!=t&&Nn(e,t)}function Vp(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 Gp(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=Bp((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:On(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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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),_p.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=_p.codec().decode(e,e.uint32(),{limits:n.limits?.value});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Bp((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.addresses)for(const e of t.addresses)n.uint32(10),Rp.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 Up('Decode error - map field "addresses" had too many elements');i.addresses.push(Rp.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 Up('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 jp('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 jp('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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Fp||(Fp={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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:On(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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Rp||(Rp={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(_p||(_p={}));const Kp="/",Hp=(new TextEncoder).encode(Kp),Wp=Hp[0];class Qp{_buf;constructor(e,t){if("string"==typeof e)this._buf=mr(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]!==Wp)throw new Error("Invalid key")}toString(e="utf8"){return yr(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Qp(e.join(Kp))}static random(){return new Qp(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Qp(e):"function"==typeof e.uint8Array?new Qp(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Hp),this._buf[0]!==Wp){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Wp,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Wp;)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 Qp.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Kp).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 Qp(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Kp)||(e+=Kp),e+=this.type(),new Qp(e)}parent(){const e=this.list();return new Qp(1===e.length?Kp:e.slice(0,-1).join(Kp))}child(e){return this.toString()===Kp?e:e.toString()===Kp?this:new Qp(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 Qp.withNamespaces([...this.namespaces(),...(t=e.map(e=>e.namespaces()),[].concat(...t))]);var t}}const Yp="/peers/";function Jp(e){if(!St(e)||null==e.type)throw new Qe("Invalid PeerId");const t=e.toCID().toString();return new Qp(`${Yp}${t}`)}async function Zp(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=Su(r.multiaddr)),!xu(r.multiaddr))throw new Qe("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===tu)?.value;return e.equals(r)&&(n=n.decapsulate(Su(`/p2p/${e}`))),{isCertified:t,multiaddr:n.bytes}})}async function Xp(e,t,n,r){if(null==t)throw new Qe("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Qe("publicKey bytes do not match peer id publicKey bytes");const i=r.existingPeer?.peer;if(null!=i&&!e.equals(i.id))throw new Qe("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=eh(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:th})),null!=t.tags&&(d=eh(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:nh,map:rh})),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=eh([...u.entries()],{validate:th})}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=eh([...n.entries()],{validate:nh,map:rh})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}null!=i?.id.publicKey?s=Ro(i.id.publicKey):null!=t.publicKey?s=Ro(t.publicKey):null!=e.publicKey&&(s=Ro(e.publicKey));const l={addresses:await Zp(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=>Nn(e.multiaddr,e.multiaddr))?.observed??Date.now()}),"RSA"!==e.type&&delete l.publicKey,l}function eh(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 th(e,t){if("string"!=typeof e)throw new Qe("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Qe("Metadata value must be a Uint8Array")}function nh(e,t){if("string"!=typeof e)throw new Qe("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Qe("Tag value must be an integer");if(t.value<0||t.value>100)throw new Qe("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Qe("Tag ttl must be an integer");if(t.ttl<0)throw new Qe("Tag ttl must be between greater than 0")}}function rh(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 ih(e){const t=e.toString().split("/")[2];return zo(In.parse(t,Wt))}function sh(e,t,n){return function(e,t,n){return $p(e,Fp.decode(t),n)}(ih(e),t,n)}class ah{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=_c({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:ep({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(Jp(e),t)}async load(e,t){const n=Jp(e),r=await this.datastore.get(n,t),i=Fp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new rt;return $p(e,i,this.peerId.equals(e)?Infinity:this.maxAddressAge)}async save(e,t,n){const r=await this.#s(e,n),i=await Xp(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 Xp(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 Xp(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:Yp,filters:(e.filters??[]).map(e=>({key:n,value:r})=>e(sh(n,r,t))),orders:(e.orders??[]).map(e=>(n,r)=>e(sh(n.key,n.value,t),sh(r.key,r.value,t)))}}(e??{},this.maxAddressAge),e)){const r=ih(t);if(r.equals(this.peerId))continue;const i=Fp.decode(n);this.#i(r,i)?await this.datastore.delete(t,e):yield $p(r,i,this.peerId.equals(r)?Infinity:this.maxAddressAge)}}async#s(e,t){try{const n=Jp(e),r=await this.datastore.get(n,t),i=Fp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new rt;return{peerPB:i,peer:$p(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=Fp.encode(t);return await this.datastore.put(Jp(e),i,r),{peer:$p(e,t,this.maxAddressAge),previous:n?.peer,updated:null==n||(s=t,a=n.peerPB,!(Vp(s.addresses,a.addresses,(e,t)=>e.isCertified===t.isCertified&&!!Nn(e.multiaddr,t.multiaddr))&&Vp(s.protocols,a.protocols,(e,t)=>e===t)&&zp(s.publicKey,a.publicKey)&&zp(s.peerRecordEnvelope,a.peerRecordEnvelope)&&Gp(s.metadata,a.metadata,(e,t)=>Nn(e,t))&&Gp(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 oh{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 ah(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 El(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=St(t)?t:St(t?.expectedPeer)?t.expectedPeer:void 0,i=St(t)||void 0===t?n:t,s=await bl.openAndCertify(e,Tl.DOMAIN,i),a=zo(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=Tl.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=bl.createFromProtobuf(u.peerRecordEnvelope),t=Tl.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 uh extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=uh.name;code=uh.code;constructor(e="Not Found"){super(e)}}function dh(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}function ch(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 lh(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=ch(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 ph(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const n=await El(e);yield*n.sort(t)}():function*(){const n=El(e);yield*n.sort(t)}()}function hh(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 fh{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 dh(this.putMany(e,n)),e=[],await dh(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=lh(n,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>lh(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>ph(e,t),n)),null!=e.offset){let t=0;const r=e.offset;n=lh(n,()=>t++>=r)}return null!=e.limit&&(n=hh(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;n=lh(n,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>lh(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>ph(e,t),n)),null!=e.offset){const t=e.offset;let r=0;n=lh(n,()=>r++>=t)}return null!=e.limit&&(n=hh(n,e.limit)),n}}class mh extends fh{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 uh;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 Qp(e),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(const e of this.data.keys())yield new Qp(e),t?.signal?.throwIfAborted()}}const yh=e=>({match:t=>{const n=t[0];return null!=n&&n.code===e&&null==n.value&&t.slice(1)}}),bh=(e,t)=>({match:n=>{const r=n[0];return r?.code===e&&null!=r.value&&(null==t||r.value===t)&&n.slice(1)}}),gh=e=>({match:t=>{const n=e.match(t);return!1===n?t:n}}),vh=(...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}}),wh=(...e)=>({match:t=>{for(const n of e){const e=n.match(t);if(!1===e)return!1;t=e}return t}});function Th(...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 Eh=Th(bh(tu)),Ph=bh(54),xh=bh(55),Sh=bh(56),Ah=bh(53),Ch=wh(bh(4),gh(bh(43))),kh=wh(gh(bh(42)),bh(eu),gh(bh(43))),Ih=vh(Ch,kh),Dh=vh(Ih,Ah,Ph,xh,Sh),Mh=Th(vh(Ih,wh(vh(Ah,Sh,Ph,xh),gh(bh(tu))))),Fh=Th(Ch),Rh=Th(kh),_h=wh(Dh,bh(6)),Lh=wh(Dh,bh(273)),Nh=Th(wh(_h,gh(bh(tu)))),Oh=wh(Lh,yh(460),gh(bh(tu))),Bh=wh(Lh,yh(461),gh(bh(tu))),Uh=vh(Oh,Bh),jh=Th(Bh),qh=vh(Dh,_h,Lh,Oh,Bh),$h=vh(wh(qh,yh(477),gh(bh(tu)))),zh=Th($h),Vh=vh(wh(qh,yh(478),gh(bh(tu))),wh(qh,yh(nu),gh(bh(ru)),yh(477),gh(bh(tu)))),Gh=Th(Vh),Kh=wh(Lh,yh(280),gh(bh(iu)),gh(bh(iu)),gh(bh(tu))),Hh=Th(Kh),Wh=wh(Bh,yh(465),gh(bh(iu)),gh(bh(iu)),gh(bh(tu))),Qh=Th(Wh),Yh=vh($h,Vh,wh(_h,gh(bh(tu))),wh(Uh,gh(bh(tu))),wh(Dh,gh(bh(tu))),Kh,Wh,bh(tu)),Jh=Th(Yh);var Zh;const Xh=Th(wh(gh(Yh),yh(au),(Zh=yh(su),{match:e=>!1===Zh.match(e)&&e}),gh(bh(tu)))),ef=Th(vh(wh(Yh,yh(au),yh(su),gh(bh(tu))),wh(Yh,yh(su),gh(bh(tu))),wh(yh(su),gh(bh(tu))))),tf=864e13;class nf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Dc({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=fd(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===Ad(t);this.mappings.set(t,{domain:e,verified:n,expires:n?tf-Date.now():0,lastVerified:n?tf-Date.now():void 0})})}remove(e){const t=fd(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(!wd(r))continue;const i=fd(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===nu&&n[e+1]?.code!==ru)return n.splice(e+1,0,{name:"sni",code:ru,value:t}),Su(n)}confirm(e,t){const n=fd(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=fd(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 rf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Dc({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=fd(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:Zo(n)?4:6,protocol:i,verified:!1,expires:0};a.push(o),this.mappings.set(s,a)}remove(e){const t=fd(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(!wd(n))continue;const e=fd(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===eu),o=s.findIndex(e=>e.name===r);return a>-1&&o>-1?(s[a].value=t,s[a].code=4===n?4:eu,s[o].value=`${i}`,Su(s)):e}confirm(e,t){if(!wd(e))return!1;const n=fd(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(!wd(e))return!1;const n=fd(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 sf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Dc({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&&(Cd(e)||function(e){try{const t=fd(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:Su(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 af{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Dc({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(Cd(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:!wd(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(!wd(e))return e.toString();const t=fd(e);return`${t.host}-${t.port}-${t.protocol}`}}const of=e=>e;function uf(e,t){const n=e.getComponents().findLast(e=>e.code===tu)?.value;return null!=n&&jo(n).equals(t)&&(e=e.decapsulate(Su(`/p2p/${t.toString()}`))),e}class df{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 sf(e,t),this.dnsMappings=new nf(e,t),this.ipMappings=new rf(e,t),this.transportAddresses=new af(e,t),this.announceFilter=t.announceFilter??of,this.observedAddressFilter=hd(1024),this.addressVerificationTTL=t.addressVerificationTTL??6e5,this.addressVerificationRetry=t.addressVerificationRetry??3e5,this._updatePeerStoreAddresses=Nd(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===tu)?.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=>Su(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Su(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Su(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){const t=fd(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=uf(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=uf(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=uf(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=Su(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(Su(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.add(e,t,n,r,i),this.observed.removePrefixed(`/ip${Zo(n)?4:6}/${n}/${i}/${r}`)}removePublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.remove(Su(`/ip${Zo(n)?4:6}/${n}/${i}/${r}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;if(!wd(e))return!1;const t=fd(e);if("ip4"!==t.type||!0===Ad(t.host))return!1;const n=this.components.transportManager.getListeners(),r=[e=>zh.exactMatch(e)||Gh.exactMatch(e),e=>Nh.exactMatch(e),e=>jh.exactMatch(e)];for(const i of r){if(!i(e))continue;const r=n.filter(e=>e.getAddrs().filter(e=>"ip4"===fd(e).type&&i(e)).length>0);if(1!==r.length)continue;const s=r[0].getAddrs().filter(e=>!vd(e)).pop();if(null==s)continue;const a=fd(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 cf;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(cf||(cf={}));class lf extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class pf extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class hf extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class ff extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class mf extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class yf extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class bf extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class gf extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class vf extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class wf extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class Tf extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Ef extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class Pf 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 Sf extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class Af extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class Cf extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}class kf{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=Qu())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>kt(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 If=["metrics","connectionProtector","dns"],Df=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Mf(e){return Array.isArray(e?.[_t])?e[_t]:[]}function Ff(e){return Array.isArray(e?.[Lt])?e[Lt]:[]}function Rf(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function _f(e={}){return null==e.denyDialMultiaddr&&(e.denyDialMultiaddr=e=>!!zh.matches(e)||Cd(e)),e}class Lf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Nf(e){if(St(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===tu)?.value;t=null==e?void 0:jo(e),n.forEach(e=>{if(!xu(e))throw new st("Invalid multiaddr");const n=e.getComponents().findLast(e=>e.code===tu)?.value;if(null==n){if(null!=t)throw new Qe("Multiaddrs must all have the same peer id or have no peer id")}else{const e=jo(n);if(!0!==t?.equals(e))throw new Qe("Multiaddrs must all have the same peer id or have no peer id")}})}return n=n.filter(e=>!Eh.exactMatch(e)),{peerId:t,multiaddrs:n}}const Of=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Bf(e){const t=fd(e);let n=t.cidr;if("ip4"!==t.type&&"ip6"!==t.type)throw new Qe(`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 Qe(`Multiaddr ${e} was not an IPv4 or IPv6 address`)}return new gd(t.host,n)}function Uf(e){return!Xh.exactMatch(e)}function jf(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=>Uf(e))?void 0:r}class qf{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(e=>Bf(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 ed;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(wd(e.remoteAddr)){const n=fd(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??Of;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 $f=1e4,zf="last-dial-failure",Vf="last-dial-success";function Gf(e,t){const n=Nh.exactMatch(e.multiaddr),r=Nh.exactMatch(t.multiaddr);if(n&&!r)return-1;if(!n&&r)return 1;const i=Gh.exactMatch(e.multiaddr),s=Gh.exactMatch(t.multiaddr);if(i&&!s)return-1;if(!i&&s)return 1;const a=zh.exactMatch(e.multiaddr),o=zh.exactMatch(t.multiaddr);if(a&&!o)return-1;if(!a&&o)return 1;const u=ef.exactMatch(e.multiaddr),d=ef.exactMatch(t.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;const c=Hh.exactMatch(e.multiaddr),l=Hh.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const p=Qh.exactMatch(e.multiaddr),h=Qh.exactMatch(t.multiaddr);return p&&!h?-1:!p&&h?1:0}function Kf(e,t){const n=vd(e.multiaddr),r=vd(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function Hf(e,t){const n=Cd(e.multiaddr),r=Cd(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function Wf(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function Qf(e,t){const n=Xh.exactMatch(e.multiaddr),r=Xh.exactMatch(t.multiaddr);return n&&!r?1:!n&&r?-1:0}class Yf extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"}var Jf=Ed(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}),Zf=Jf;class Xf extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Xf)}}const em=e=>e.reason??new DOMException("This operation was aborted.","AbortError");class tm{#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 nm extends Zf{#d;#c;#l=0;#p;#h=!1;#f=!1;#m;#y=0;#b=0;#g;#v;#w;#T=[];#E=0;#u;#P;#x=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:tm,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.#P=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.#x<this.#S}#N(){this.#x--,0===this.#x&&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.#x: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.#x){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.#x&&this.#g&&this.#z(),this.#l=this.#d?this.#x: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.#x++,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(em(a));if(a&&(u=()=>{d(em(a))},a.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Xf;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.#x} 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.#P,this.#z(),this.#W(),this.emit("empty"),0===this.#x&&(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.#x&&0===this.#u.size||await this.#Q("idle")}async onPendingZero(){0!==this.#x&&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.#x}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.#x===this.#S&&this.#u.size>0||this.isRateLimited&&this.#u.size>0}get runningTasks(){return[...this.#k.values()].map(e=>({...e}))}}function rm(e){const t=[um.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function im(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:um[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:um[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?yr(e.data):e.data}))}}function sm(e,t={}){const n=new nm({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),rm(r.types).forEach(e=>{s.append("type",um[e])}),r.onProgress?.(new Lf("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=im(await t.json());return r.onProgress?.(new Lf("dns:response",n)),n},{signal:r.signal});if(null==a)throw new Error("No DNS response received");return a}}class am{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 im({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:um[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 om{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=new am(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["."]=[sm("https://cloudflare-dns.com/dns-query"),sm("https://dns.google/resolve")])}async query(e,t={}){const n=rm(t.types),r=!1!==t.cached?this.cache.get(e,n):void 0;if(null!=r)return t.onProgress?.(new Lf("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 Lf("dns:error",e))}}throw new Yf(a,`DNS lookup of ${e} ${n} failed`)}}var um;!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(um||(um={}));const dm=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:[um.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(Su(t))}return a}getDNS(e){return null!=e.dns?e.dns:(null==this.dns&&(this.dns=function(e={}){return new om(e)}()),this.dns)}};async function cm(e,t,n){const r=n.depth??0;if(r>(n.maxRecursiveDepth??32))throw new Cf("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 cm(e,t,{...n,depth:r+1}))}return!1===i&&s.push(e),s}const lm={maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:dm}};class pm{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??lm.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??lm.maxDialQueueLength,this.dialTimeout=t.dialTimeout??lm.dialTimeout,this.connections=t.connections??new ed,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??lm.resolvers,this.shutDownController=new AbortController,this.queue=new Sc({concurrency:t.maxParallelDials??lm.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",e=>{e.detail?.error.name!==Ke.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}=Nf(e);if(null!=n&&!0!==t.force){const e=jf(n,this.connections.get(n),r);if(null!=e)return this.log("already connected to %a",e.remoteAddr),t.onProgress?.(new Lf("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 Lf("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new ht("Dial queue is full");return this.log("creating dial target for %p",n,r.map(e=>e.toString())),t.onProgress?.(new Lf("dial-queue:add-to-dial-queue")),this.queue.add(async e=>{e.onProgress?.(new Lf("dial-queue:start-dial"));const t=Zd([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}},{peerId:n,priority:t.priority??Tm,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 Lf("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 ht("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:{[Vf]:mr(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:{[zf]:mr(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 lt(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:Su(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new ht("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new gf("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 cm(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===tu)?.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 Tf("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(Gf).sort(Wf).sort(Qf).sort(Hf).sort(Kf):u.sort(this.addressSorter);if(0===d.length)throw new gf("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=>!Xh.matches(e.multiaddr))}catch{}return!1}}const hm=Object.prototype.toString,fm=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 mm(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 ym 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 bm(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function gm({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 ym)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),bm(r,o)<=0)throw s;const d=await i.shouldConsumeRetry(u),c=bm(r,o);if(c<=0||a<=0)throw s;if(s instanceof TypeError&&!function(e){const t=e&&(e=>"[object Error]"===hm.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(")"))||fm.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 vm{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);wm(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,mm("factor",t.factor,{min:0,allowInfinity:!1}),mm("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),mm("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),mm("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 gm({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(Ct)&&(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=>wm(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 wm(e){for(const t of e.tags.keys())if(t.startsWith(Ct))return!0;return!1}const Tm=50;class Em{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 Qe("Connection Manager maxConnections must be greater than 0");this.connections=new ed,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=>Bf(Su(e))),this.deny=(t.deny??[]).map(e=>Bf(Su(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Ac({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new qf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(e=>Su(e))}),this.dialQueue=new pm(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:dm},connections:this.connections}),this.reconnectQueue=new vm({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 It(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 Dt(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const n of t)e.push(Promise.all([Ld(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 Qe("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 pt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:n,multiaddrs:r}=Nf(e);if(this.peerId.equals(n))throw new it("Can not dial self");if(null!=n&&!0!==t.force){this.log("dial %p",n);const e=jf(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 Lf("dial-queue:already-connected")),e}const i=await this.dialQueue.dial(e,{...t,priority:t.priority??Tm});if("open"!==i.status)throw new Je("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 st("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([Ld(e,"close",t),e.close(t)])}catch(t){e.abort(t)}}))}acceptIncomingConnection(e){if(this.deny.some(t=>{if(wd(e.remoteAddr)){const n=fd(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(wd(e.remoteAddr)){const n=fd(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(wd(e.remoteAddr)){const t=fd(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=>Su(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Pm{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 ec({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[_t]=["@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=fc(r);t=Date.now(),await Promise.all([i.write(so(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:yr(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:yr(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 hf("No content routers available");const n=this,r=new td;for await(const i of nc(...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 hf("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 hf("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 pt;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 pt;return Promise.any(this.routers.filter(e=>e.get instanceof Function).map(async n=>n.get(e,t)))}}const Sm=globalThis.CustomEvent??Event;async function*Am(e,t={}){let n=t.concurrency??Infinity;n<1&&(n=Infinity);const r=t.ordered??!1,i=new EventTarget,s=[];let a,o=kd(),u=kd(),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=kd(),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 Sm("task-complete"))},t=>{e.done=!0,e.err=t,i.dispatchEvent(new Sm("task-complete"))})}d=!0,i.dispatchEvent(new Sm("task-complete"))}catch(e){a=e,i.dispatchEvent(new Sm("task-complete"))}});;){if(l()||(u=kd(),await u.promise),null!=a)throw a;if(r?yield*p():yield*h(),null!=a)throw a;if(d&&0===s.length)break}}class Cm{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:yr(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 ff("No peer routers available");if(e.toString()===this.peerId.toString())throw new mf("Should not try to find self");const n=this,r=nc(...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 rt}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new ff("No peer routers available");const n=this,r=hd(1024);for await(const i of Am(async function*(){const r=nc(...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 km extends Rt{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=Zd([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=kd();const e=await Ld(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=Zd([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=so(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 zd(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 Im{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=Dc({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 yf(`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 bf(`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 Qe("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 Dm{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Dc({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Dc({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ft.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Qe("Transport must have a valid tag");if(this.transports.has(t))throw new Qe(`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 Af(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Lf("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 pt("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 vf)});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})}),Fh.matches(e)?t.ipv4.attempts++:Rh.matches(e)&&t.ipv6.attempts++,n.push(s.listen(e).then(()=>{t.errors.delete(e.toString()),Fh.matches(e)&&t.ipv4.success++,Rh.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!==Ft.NO_FATAL)throw new wf(`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 Mm="/multistream/1.0.0",Fm=mr("\n");async function Rm(e,t){const n=(await e.read(t)).subarray();if(0===n.byteLength||n[n.length-1]!==Fm[0])throw new dt("Missing newline");return yr(n).trimEnd()}async function _m(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=mc(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"]',Mm,s);const e=mr(`${Mm}\n`),t=mr(`${s}\n`);if(await i.writeV([e,t],n),r.trace("reading multistream-select header"),a=await Rm(i,n),r.trace('read "%s"',a),a!==Mm){r.error("did not read multistream-select header from response");break}}else r.trace('write "%s"',s),await i.write(mr(`${s}\n`),n);if(r.trace("reading protocol response"),a=await Rm(i,n),r.trace('read "%s"',a),a===s)return r.trace('selected "%s" after negotiation',a),i.unwrap(),s}throw new ut(`Protocol selection failed - could not negotiate ${t}`)}async function Lm(e,t,n={}){t=Array.isArray(t)?t:[t];const r=e.log.newScope("mss:handle"),i=mc(e,{...n,maxDataLength:1024,maxLengthLength:2});for(;;){r.trace("reading incoming string");const e=await Rm(i,n);if(r.trace('read "%s"',e),e!==Mm){if(t.includes(e))return r.trace('respond with "%s" for "%s"',e,e),await i.write(mr(`${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(mr("na\n"),n),r('responded with "na" for "%s"',e);else{const s=new zn(...t.map(e=>Ec.single(mr(`${e}\n`))),mr("\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"',Mm,e),await i.write(mr(`${Mm}\n`),n),r.trace('responded with "%s" for "%s"',Mm,e)}}class Nm extends Rt{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??$f,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??$f,this.closeTimeout=t.closeTimeout??1e3,this.direct=Uf(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),null==this.remoteAddr.getComponents().find(e=>e.code===tu)&&(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 wt(e.local,e.error))})}[Symbol.toStringTag]="Connection";[Ve]=!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 Je(`The connection muxer is "${this.muxer.status}" and not "open"`);if("open"!==this.maConn.status)throw new Je(`The connection is "${this.status}" and not "open"`);if(null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new mt("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 _m(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=Om(n.protocol,"outbound",this);if(i>r){const e=new bt(`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 Lm(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(Om(t.protocol,"inbound",this)>e)throw new yt(`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 mt("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 Om(e,t,n){let r=0;return n.streams.forEach(n=>{n.direction===t&&n.protocol===e&&r++}),r}class Bm{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Dc({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(e=>{this.connectionEncrypters.set(e.protocol,e)}),this.streamMuxers=Dc({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??$f,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??$f,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 Ef(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){return Zd([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 Pf("Connection denied");await zd(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===tu)?.value;let r;null!=n&&(r=jo(n),await zd(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 st(`${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===tu)?.value;let u;null!=s&&(u=jo(s)),n?.onProgress?.(new Lf(`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 it("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 Lf(`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 Nm(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 Lm(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new Sf(`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 Sf(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 _m(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new Sf(`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 Sf(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 _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 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 Lm(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 Um="3.1.6",jm="js-libp2p";class qm extends Rt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Rt,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??Qu(),this.log=this.logger.forComponent("libp2p"),this.services={};const r=e.nodeInfo?.name??jm,i=e.nodeInfo?.version??Um,s=this.components=function(e={}){const t=new kf(e),n=new Proxy(t,{get(e,n,r){if("string"==typeof n&&!Df.includes(n)){const e=t.components[n];if(null==e&&!If.includes(n))throw new lf(`${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??jm}/${o??Um} browser/${globalThis.navigator.userAgent}`)},logger:this.logger,events:t,datastore:e.datastore??new mh,connectionGater:_f(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 oh(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 Bm(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 Dm(this.components,e.transportManager)),this.configureComponent("connectionManager",new Em(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Pm(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Im(this.components)),this.configureComponent("addressManager",new df(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 Cm(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 km(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[Ge]&&(this.log("registering service %s for content routing",t),d.push(n[Ge])),null!=n[At]&&(this.log("registering service %s for peer routing",t),u.push(n[At])),null!=n[Pt]&&(this.log("registering service %s for peer discovery",t),n[Pt].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 Mf(n))t[e]=!0;for(const n of Object.values(e.components))for(const e of Ff(n))if(!0!==t[e])throw new pf(`Service "${Rf(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 td;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 Qe("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Qe("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=jo(e.getComponents().findLast(e=>e.code===tu)?.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=Un([mr("/pk/"),e.toMultihash().bytes]),r=Fo(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 $m=65535,zm=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function Vm(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Gm(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Km(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 Hm(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 Wm(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Qm(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Ym=/* @__PURE__ */(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])(),Jm=(e,t)=>{function n(n,...r){if(Km(n,void 0,"key"),!Ym)throw new Error("Non little-endian hardware is not yet supported");void 0!==e.nonceLength&&Km(r[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");const i=e.tagLength;i&&void 0!==r[1]&&Km(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");Km(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,Km(e),a(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(Km(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 Zm(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 Xm(e){return Uint8Array.from(e)}const ey=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),ty=ey("expand 16-byte k"),ny=ey("expand 32-byte k"),ry=Wm(ty),iy=Wm(ny);function sy(e,t){return e<<t|e>>>32-t}function ay(e){return e.byteOffset%4==0}const oy=2**32-1,uy=Uint32Array.of();function dy(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 Gm(i),Gm(a),Vm(s),Vm(n),(t,o,u,d,c=0)=>{Km(t,void 0,"key"),Km(o,void 0,"nonce"),Km(u,void 0,"data");const l=u.length;if(void 0===d&&(d=new Uint8Array(l)),Km(d,void 0,"output"),Gm(c),c<0||c>=oy)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=Xm(t)),f=iy;else{if(16!==m||!n)throw Km(t,32,"arx key"),new Error("invalid key size");h=new Uint8Array(32),h.set(t),h.set(t,16),f=ry,p.push(h)}ay(o)||p.push(o=Xm(o));const y=Wm(h);if(r){if(24!==o.length)throw new Error("arx: extended nonce must be 24 bytes");r(f,y,Wm(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=Wm(o);return function(e,t,n,r,i,s,a,o){const u=i.length,d=new Uint8Array(64),c=Wm(d),l=ay(i)&&ay(s),p=l?Wm(i):uy,h=l?Wm(s):uy;for(let f=0;f<u;a++){if(e(t,n,r,c,a,o),a>=oy)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),Qm(...p),d}}function cy(e,t){return 255&e[t++]|(255&e[t++])<<8}class ly{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=cy(e=Xm(Km(e,32,"key")),0),n=cy(e,2),r=cy(e,4),i=cy(e,6),s=cy(e,8),a=cy(e,10),o=cy(e,12),u=cy(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]=cy(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=cy(e,t+0),b=cy(e,t+2),g=cy(e,t+4),v=cy(e,t+6),w=cy(e,t+8),T=cy(e,t+10),E=cy(e,t+12),P=cy(e,t+14);let x=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|P<<8)),R=i[9]+(P>>>5|r),_=0,L=_+x*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=_+x*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=_+x*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=_+x*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=_+x*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=_+x*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=_+x*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 $=_+x*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=_+x*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=_+x*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;Qm(n)}update(e){Hm(this),Km(e),e=Xm(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(){Qm(this.h,this.r,this.buffer,this.pad)}digestInto(e){Hm(this),function(e,t){Km(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 py=/** @__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 ly(e)))();function hy(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,P=o,x=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,_=sy(_^E,16),D=D+_|0,A=sy(A^D,12),E=E+A|0,_=sy(_^E,8),D=D+_|0,A=sy(A^D,7),P=P+C|0,L=sy(L^P,16),M=M+L|0,C=sy(C^M,12),P=P+C|0,L=sy(L^P,8),M=M+L|0,C=sy(C^M,7),x=x+k|0,N=sy(N^x,16),F=F+N|0,k=sy(k^F,12),x=x+k|0,N=sy(N^x,8),F=F+N|0,k=sy(k^F,7),S=S+I|0,O=sy(O^S,16),R=R+O|0,I=sy(I^R,12),S=S+I|0,O=sy(O^S,8),R=R+O|0,I=sy(I^R,7),E=E+C|0,O=sy(O^E,16),F=F+O|0,C=sy(C^F,12),E=E+C|0,O=sy(O^E,8),F=F+O|0,C=sy(C^F,7),P=P+k|0,_=sy(_^P,16),R=R+_|0,k=sy(k^R,12),P=P+k|0,_=sy(_^P,8),R=R+_|0,k=sy(k^R,7),x=x+I|0,L=sy(L^x,16),D=D+L|0,I=sy(I^D,12),x=x+I|0,L=sy(L^x,8),D=D+L|0,I=sy(I^D,7),S=S+A|0,N=sy(N^S,16),M=M+N|0,A=sy(A^M,12),S=S+A|0,N=sy(N^S,8),M=M+N|0,A=sy(A^M,7);let B=0;r[B++]=a+E|0,r[B++]=o+P|0,r[B++]=u+x|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 fy=/* @__PURE__ */dy(hy,{counterRight:!1,counterLength:4,allowShortKeys:!1}),my=/* @__PURE__ */new Uint8Array(16),yy=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(my.subarray(n))},by=/* @__PURE__ */new Uint8Array(32);function gy(e,t,n,r,i){void 0!==i&&Km(i,void 0,"AAD");const s=e(t,n,by),a=function(e,t,n){Vm(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=py.create(s);i&&yy(o,i),yy(o,r),o.update(a);const u=o.digest();return Qm(s,a),u}const vy=/* @__PURE__ */Jm({blockSize:64,nonceLength:12,tagLength:16},(wy=fy,(e,t,n)=>({encrypt(r,i){const s=r.length;(i=Zm(s+16,i,!1)).set(r);const a=i.subarray(0,-16);wy(e,t,a,a,1);const o=gy(wy,e,t,a,n);return i.set(o,s),Qm(o),i},decrypt(r,i){i=Zm(r.length-16,i,!1);const s=r.subarray(0,-16),a=r.subarray(-16),o=gy(wy,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)),wy(e,t,i,i,1),Qm(o),i}})));var wy;function Ty(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Ey(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 Py(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");Ty(e.outputLen),Ty(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 Sy(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ay(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Cy(e,t){return e<<32-t|e>>>t}const ky=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Iy=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Dy(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function My(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 Fy(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 Ry=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function _y(e,t,n){return e&t^~e&n}function Ly(e,t,n){return e&t^e&n^t&n}class Ny{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=Ay(this.buffer)}update(e){xy(this),Ey(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=Ay(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){Ey(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,Sy(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=Ay(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 Oy=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),By=/* @__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]),Uy=/* @__PURE__ */new Uint32Array(64);class jy extends Ny{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)Uy[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Uy[e-15],n=Uy[e-2],r=Cy(t,7)^Cy(t,18)^t>>>3,i=Cy(n,17)^Cy(n,19)^n>>>10;Uy[e]=i+Uy[e-7]+r+Uy[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+(Cy(a,6)^Cy(a,11)^Cy(a,25))+_y(a,o,u)+By[e]+Uy[e]|0,c=(Cy(n,2)^Cy(n,13)^Cy(n,22))+Ly(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(){Sy(Uy)}destroy(){this.set(0,0,0,0,0,0,0,0),Sy(this.buffer)}}class qy extends jy{A=0|Oy[0];B=0|Oy[1];C=0|Oy[2];D=0|Oy[3];E=0|Oy[4];F=0|Oy[5];G=0|Oy[6];H=0|Oy[7];constructor(){super(32)}}const $y=/* @__PURE__ */My(()=>new qy
|
|
4
|
+
/* @__PURE__ */,Ry(1)),zy=/* @__PURE__ */BigInt(0);function Vy(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?zy:BigInt("0x"+e)}(function(e){if(Ey(e),ky)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Iy[e[n]];return t}(Gy(Ey(e)).reverse()))}function Gy(e){return Uint8Array.from(e)}const Ky=e=>"bigint"==typeof e&&zy<=e;function Hy(e,t,n,r){if(!function(e,t,n){return Ky(e)&&Ky(t)&&Ky(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const Wy=/* @__PURE__ */BigInt(0);function Qy(e,t){const n=e%t;return n>=Wy?n:t+n}function Yy(e,t,n){let r=e;for(;t-- >Wy;)r*=r,r%=n;return r}function Jy(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 Zy=BigInt(0),Xy=BigInt(1),eb=BigInt(2),tb=BigInt(1),nb=BigInt(2),rb=/* @__PURE__ */BigInt(3),ib=BigInt(5),sb=(BigInt(8),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"));function ab(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const ob=/* @__PURE__ */(()=>{const e=sb;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||Fy,c=u?255:448,l=u?32:56,p=u?BigInt(9):BigInt(5),h=u?BigInt(121665):BigInt(39081),f=u?eb**BigInt(254):eb**BigInt(447),m=u?BigInt(8)*eb**BigInt(251)-Xy:BigInt(4)*eb**BigInt(445)-Xy,y=f+m+Xy,b=e=>Qy(e,r),g=v(p);function v(e){return function(e,t){return function(e,t){Ty(t);const n=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(ky)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=Dy(e.charCodeAt(i)),s=Dy(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(!Ky(e))throw new Error("positive bigint expected, got "+e)}else Ty(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){Hy("u",e,Zy,r),Hy("scalar",t,f,y);const n=t,i=e;let s=Xy,o=Zy,u=e,d=Xy,l=Zy;for(let e=BigInt(c-1);e>=Zy;e--){const t=n>>e&Xy;l^=t,({x_2:s,x_3:u}=x(l,s,u)),({x_2:o,x_3:d}=x(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}=x(l,s,u)),({x_2:o,x_3:d}=x(l,o,d));const p=a(o);return b(s*p)}(function(e){const t=Gy(Ey(e,l,"uCoordinate"));return u&&(t[31]&=127),b(Vy(t))}(t),function(e){return Vy(s(Gy(Ey(e,l,"scalar"))))}(e));if(n===Zy)throw new Error("invalid private or public key received");return v(n)}function T(e){return w(e,g)}const E=T,P=w;function x(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))=>(Ey(e,S.seed,"seed"),e),C={randomSecretKey:A};return Object.freeze({keygen:Jy(A,E),getSharedSecret:P,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=sb,a=e*e%s*e%s,o=Yy(a,nb,s)*a%s,u=Yy(o,tb,s)*e%s,d=Yy(u,ib,s)*u%s,c=Yy(d,t,s)*d%s,l=Yy(c,n,s)*c%s,p=Yy(l,r,s)*l%s,h=Yy(p,i,s)*p%s,f=Yy(h,i,s)*p%s,m=Yy(f,t,s)*d%s;return{pow_p_5_8:Yy(m,nb,s)*e%s,b2:a}}(t);return Qy(Yy(n,rb,e)*r,e)},adjustScalarBytes:ab})})();class ub{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Py(e),Ey(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),Sy(r)}update(e){return xy(this),this.iHash.update(e),this}digestInto(e){xy(this),Ey(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 db=(e,t,n)=>new ub(e,t).update(n).digest();db.create=(e,t)=>new ub(e,t);const cb=/* @__PURE__ */Uint8Array.of(0),lb=/* @__PURE__ */Uint8Array.of(),pb={hashSHA256:e=>$y(e.subarray()),getHKDF(e,t){const n=function(e,t,n){return Py(e),void 0===n&&(n=new Uint8Array(e.outputLen)),db(e,n,t)}($y,t,e),r=function(e,t,n,r=32){Py(e),Ty(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=lb:Ey(n,void 0,"info");const a=new Uint8Array(s*i),o=db.create(e,t),u=o._cloneInto(),d=new Uint8Array(o.outputLen);for(let e=0;e<s;e++)cb[0]=e+1,u.update(0===e?lb:d).update(n).update(cb).digestInto(d),a.set(d,i*e),o._cloneInto(u);return o.destroy(),u.destroy(),Sy(d,cb),a.slice(0,r)}($y,n,void 0,96),i=r;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){const e=ob.utils.randomSecretKey();return{publicKey:ob.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:ob.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>ob.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,n,r)=>vy(r,t,n).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,n,r,i)=>vy(r,t,n).decrypt(e.subarray(),i)},hb=pb,fb=e=>{const t=Bn(2);return t[0]=e>>8,t[1]=e,t};fb.bytes=2;const mb=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 yb(e,t){t.enabled&&zm&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${yr(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${yr(e.privateKey,"hex")}`)):t("Missing local static keys."))}function bb(e,t){t.enabled&&zm&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${yr(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${yr(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function gb(e,t){t.enabled&&zm&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${yr(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function vb(e,t,n){n.enabled&&zm&&(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&yr(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&yr(t.k,"hex")}`))}function wb(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");const n=Bn(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}mb.bytes=2;class Tb extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Tb.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Eb{n;bytes;view;constructor(e=0){this.n=e,this.bytes=On(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 Pb=On(0);class xb{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Eb(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 Sb{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const n=mr(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=On(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 zn(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,Pb);return[new xb(this.crypto,e),new xb(this.crypto,t)]}}class Ab{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 Sb(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 Cb extends Ab{writeMessageA(e){return new zn(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new zn(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new zn(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Tb(`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 Tb(`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 Tb(`handshake stage 2 validation fail: ${e.message}`)}}}var kb,Ib,Db,Mb,Fb;async function Rb(e,t,n){const r=await e.sign(Lb(t));return Ib.encode({identityKey:Ro(e.publicKey),identitySig:r,extensions:n})}async function _b(e,t,n){try{const r=Ib.decode(e),i=Fo(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=Lb(t);if(!await i.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(e){throw new He(e.message)}}function Lb(e){const t=mr("noise-libp2p-static-key:");return e instanceof Uint8Array?Un([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=Bp((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 Up('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 Up('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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(kb||(kb={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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),kb.codec().encode(e.extensions,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={identityKey:On(0),identitySig:On(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=kb.codec().decode(e,e.uint32(),{limits:n.limits?.extensions});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Ib||(Ib={}));class Nb extends Wd{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 bc({lengthDecoder:mb,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 zn;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(fb(r.byteLength)),t.append(r)}return t}decrypt(e){const t=new zn;for(let n=0;n<e.byteLength;n+=$m){let r,i=n+$m;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 Ob(e,t,n){return new Nb(e,t,n)}class Bb{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??hb;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??On(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[_t]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const n=e.log?.newScope("noise")??this.log,r=mc(e,{lengthEncoder:fb,lengthDecoder:mb,maxDataLength:$m}),i=await this.performHandshakeInitiator(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Fo(i.payload.identityKey);return{connection:Ob(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:qo(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 We("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=mc(e,{lengthEncoder:fb,lengthDecoder:mb,maxDataLength:$m}),i=await this.performHandshakeResponder(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Fo(i.payload.identityKey);return{connection:Ob(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:qo(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 Rb(s,o.publicKey,d),l=new Cb({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:a,s:o});yb(l.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(l.writeMessageA(Pb),t),n.trace("Stage 0 - Initiator finished sending first message."),bb(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."),gb(l.re,n),h=l.rs,(f=n).enabled&&zm&&f(h?`REMOTE_STATIC_PUBLIC_KEY ${yr(h.subarray(),"hex")}`:"Missing remote static public key."),n.trace("Initiator going to check remote's signature...");const m=await _b(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 vb(y,b,n),{payload:m,encrypt:e=>y.encryptWithAd(Pb,e),decrypt:(e,t)=>b.decryptWithAd(Pb,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 Rb(s,o.publicKey,d),l=new Cb({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:a,s:o});yb(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."),gb(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."),bb(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 _b(p,l.rs,u),[f,m]=l.ss.split();return vb(f,m,n),{payload:h,encrypt:e=>m.encryptWithAd(Pb,e),decrypt:(e,t)=>f.decryptWithAd(Pb,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 Ub(e={}){return t=>new Bb(t,e)}!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(Db||(Db={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(Mb||(Mb={})),Object.values(Mb).filter(e=>"string"!=typeof e),function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(Fb||(Fb={}));const jb=12;class qb extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}}class $b extends qb{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Fb.ProtocolError),this.name="InvalidFrameError"}}class zb extends qb{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Fb.ProtocolError),this.name="UnRequestedPingError"}}class Vb extends qb{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Fb.ProtocolError),this.name="NotMatchingPingError"}}class Gb extends qb{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Fb.ProtocolError),this.name="ReceiveWindowExceededError"}}const Kb=262144,Hb=2**24;class Wb{buffer;constructor(){this.buffer=new zn}*emitFrames(e){for(this.buffer.append(e);;){const e=this.readFrame();if(void 0===e)break;yield e}}readFrame(){let e=jb;if(this.buffer.byteLength<jb)return;const t=function(e){if(0!==e[0])throw new $b("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*Hb+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*Hb+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,jb));if(t.type===Db.Data){if(e+=t.length,this.buffer.byteLength<e)return;const n=this.buffer.sublist(jb,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}}function Qb(e){const t=new Uint8Array(jb);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 Yb;!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"}(Yb||(Yb={}));class Jb extends Jd{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){const t=e.initialStreamWindowSize??Kb;super({...e,maxMessageSize:t-jb}),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=Yb.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:Db.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:Db.WindowUpdate,flag:Mb.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){const e=this.getSendFlags()|Mb.FIN;this.sendFrame({type:Db.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Yb.Paused}sendResume(){this.state=Yb.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-jb,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===Db.Data&&null!==e.data}(e))throw new $b("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Gb("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&Mb.ACK)===Mb.ACK&&this.state===Yb.SYNSent&&(this.state=Yb.Established),(e&Mb.FIN)===Mb.FIN&&this.onRemoteCloseWrite(),(e&Mb.RST)===Mb.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Yb.Init:return this.state=Yb.SYNSent,Mb.SYN;case Yb.SYNReceived:return this.state=Yb.Established,Mb.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Yb.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:Db.WindowUpdate,flag:e,streamID:this.streamId,length:r})}}function Zb(e){return{type:Db[e.type],flags:[(e.flag&Mb.SYN)===Mb.SYN?"SYN":void 0,(e.flag&Mb.ACK)===Mb.ACK?"ACK":void 0,(e.flag&Mb.FIN)===Mb.FIN?"FIN":void 0,(e.flag&Mb.RST)===Mb.RST?"RST":void 0].filter(Boolean),streamID:e.streamID,length:e.length}}const Xb="/yamux/1.0.0";class eg{protocol=Xb;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[_t]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new tg(e,{...this._init})}}class tg extends Yd{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:Xb,name:"yamux"}),this.client="outbound"===e.direction,function(e){if(null!=e.keepAliveInterval&&e.keepAliveInterval<=0)throw new Qe("keep-alive interval must be positive");if(null!=e.maxInboundStreams&&e.maxInboundStreams<0)throw new Qe("max inbound streams must be larger or equal 0");if(null!=e.maxOutboundStreams&&e.maxOutboundStreams<0)throw new Qe("max outbound streams must be larger or equal 0");if(null!=e.maxMessageSize&&e.maxMessageSize<1024)throw new Qe("MaxMessageSize must be greater than a kilobyte");if(null!=e.streamOptions?.initialStreamWindowSize&&e.streamOptions?.initialStreamWindowSize<Kb)throw new Qe("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 Qe("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(null!=e.streamOptions?.maxStreamWindowSize&&e.streamOptions?.maxStreamWindowSize>2**32-1)throw new Qe("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 Wb,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=kc(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 Xe("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Xe("Muxer closed locally");const e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new bt("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);const t=this._newStream(e,Yb.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(void 0!==this.remoteGoAway)throw new Xe("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Xe("Muxer closed locally");if(null!=this.activePing)return zd(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 zd(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??Fb.NormalTermination;this.log.trace("muxer close reason=%s",Fb[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if("open"===this.status)try{super.abort(e);let t=Fb.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 Qe("Stream already exists with that id");const r=new Jb({...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",Zb(e.header)),0===t)switch(n){case Db.Ping:return void this.handlePing(e.header);case Db.GoAway:return void this.handleGoAway(r);default:throw new $b("Invalid frame type")}else switch(e.header.type){case Db.Data:case Db.WindowUpdate:return void this.handleStreamMessage(e);default:throw new $b("Invalid frame type")}}handlePing(e){if(e.flag===Mb.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Mb.ACK);else{if(e.flag!==Mb.ACK)throw new $b("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 zb("ping not requested");if(this.activePing.id!==e)throw new Vb("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Fb[e]??"unknown"),this.remoteGoAway=e,e===Fb.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){const{streamID:t,flag:n,type:r}=e.header;(n&Mb.SYN)===Mb.SYN&&this.incomingStream(t);const i=this.streams.find(e=>e.streamId===t);if(void 0!==i)switch(r){case Db.WindowUpdate:return void i.handleWindowUpdate(e);case Db.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 Qe("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:Db.WindowUpdate,flag:Mb.RST,streamID:e,length:0});if(this.numInboundStreams>=this.maxInboundStreams)return this.log("maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:Db.WindowUpdate,flag:Mb.RST,streamID:e,length:0});const t=this._newStream(e,Yb.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Db.Data){if(null==t)throw new $b("Invalid frame");n=new zn(Qb(e),t)}else n=Qb(e);return this.log.trace("sending frame %o",Zb(e)),this.send(n)}sendPing(e,t=Mb.SYN){this.log.trace(t===Mb.SYN?"sending ping request pingId=%s":"sending ping response pingId=%s",e),this.sendFrame({type:Db.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Fb.NormalTermination){this.log("sending GoAway reason=%s",Fb[e]),this.localGoAway=e,this.sendFrame({type:Db.GoAway,flag:0,streamID:0,length:e})}}function ng(e={}){return()=>new eg(e)}const rg=[6,53,56,54,55];function ig(e){return ag("sni",e)?.value}function sg(e){const t=ag("tcp",e)?.value;return null==t?"":`:${t}`}function ag(e,t){return t.find(t=>t.name===e)}function og(e){return e.some(({code:e})=>e===nu)}function ug(e,t){const n=dg[e.name];if(null==n)throw new Error(`Can't interpret protocol ${e.name}`);const r=n(e,t);return e.code===eu?`[${r}]`:r}const dg={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://${ug(n,t)}:${e.value}`},udp:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`udp://${ug(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`${ug(n,t)}`},p2p:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${ug(n,t)}`},http:(e,t)=>{const n=og(t),r=ig(t),i=sg(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=ug(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`${ug(n,t)}${decodeURIComponent(e.value??"")}`},tls:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return ug(n,t)},sni:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return ug(n,t)},https:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=ug(n,t);return r=r?.replace("tcp://",""),`https://${r}`},ws:(e,t)=>{const n=og(t),r=ig(t),i=sg(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=ug(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=ug(n,t);return r=r?.replace("tcp://",""),`wss://${r}`}};class cg extends Qd{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??4194304,this.checkBufferedAmountTask=kc(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=mr(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 lg{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"})})}[Mt]=!0;[Symbol.toStringTag]="@libp2p/websockets";[_t]=["@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 cg(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=Su(e).getComponents(),n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");const r=dg[n.name];if(null==r)throw new Error(`No interpreter found for ${n.name}`);let i=r(n,t)??"";return rg.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 Lf("websockets:open-connection")),await Ld(r,"open",t)}catch(e){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Ze(`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=>zh.exactMatch(e)||Gh.exactMatch(e))}dialFilter(e){return this.listenFilter(e)}}function pg(e={}){return t=>new lg(t,e)}class hg{constructor(){throw new Error("TCP connections are not possible in browsers")}[Mt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[_t]=["@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 fg(e={}){return t=>new hg(t,e)}const mg=`${Ct}-circuit-relay`;BigInt(1<<17);const yg="/libp2p/circuit/relay/0.2.0/hop",bg="/libp2p/circuit/relay/0.2.0/stop",gg=new Float32Array([-0]),vg=new Uint8Array(gg.buffer);function wg(e,t,n){gg[0]=e,t[n]=vg[0],t[n+1]=vg[1],t[n+2]=vg[2],t[n+3]=vg[3]}const Tg=new Float64Array([-0]),Eg=new Uint8Array(Tg.buffer);function Pg(e,t,n){Tg[0]=e,t[n]=Eg[0],t[n+1]=Eg[1],t[n+2]=Eg[2],t[n+3]=Eg[3],t[n+4]=Eg[4],t[n+5]=Eg[5],t[n+6]=Eg[6],t[n+7]=Eg[7]}const xg=BigInt(Number.MAX_SAFE_INTEGER),Sg=BigInt(Number.MIN_SAFE_INTEGER);class Ag{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 Cg;if(e<xg&&e>Sg)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>kg&&(r=0n,++n>kg&&(n=0n))),new Ag(Number(r),Number(n))}static fromNumber(e){if(0===e)return Cg;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 Ag(n,r)}static from(e){return"number"==typeof e?Ag.fromNumber(e):"bigint"==typeof e?Ag.fromBigInt(e):"string"==typeof e?Ag.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Ag(e.low>>>0,e.high>>>0):Cg}}const Cg=new Ag(0,0);Cg.toBigInt=function(){return 0n},Cg.zzEncode=Cg.zzDecode=function(){return this},Cg.length=function(){return 1};const kg=4294967296n;function Ig(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 Dg(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Mg(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Fg{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,Dg(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 Dg(this,4);return Mg(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Dg(this,4);return 0|Mg(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Dg(this,4);const e=(vg[0]=(t=this.buf)[n=this.pos],vg[1]=t[n+1],vg[2]=t[n+2],vg[3]=t[n+3],gg[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Dg(this,4);const e=(Eg[0]=(t=this.buf)[n=this.pos],Eg[1]=t[n+1],Eg[2]=t[n+2],Eg[3]=t[n+3],Eg[4]=t[n+4],Eg[5]=t[n+5],Eg[6]=t[n+6],Eg[7]=t[n+7],Tg[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 Dg(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 Dg(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Dg(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 Ag(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Dg(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 Dg(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 Dg(this,8);const e=Mg(this.buf,this.pos+=4),t=Mg(this.buf,this.pos+=4);return new Ag(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=ga(this.buf,this.pos);return this.pos+=ya(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 Rg(e){return new Fg(e instanceof Uint8Array?e:e.subarray())}function _g(e,t,n){const r=Rg(e);return t.decode(r,void 0,n)}class Lg{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Ng(){}class Og{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Bg=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Bn(r);n+r>e&&(t=Bn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class Ug{len;head;tail;states;constructor(){this.len=0,this.head=new Lg(Ng,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Lg(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $g((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(zg,10,Ag.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Ag.fromBigInt(e);return this._push(zg,t.length(),t)}uint64Number(e){return this._push(ba,ya(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=Ag.fromBigInt(e).zzEncode();return this._push(zg,t.length(),t)}sint64Number(e){const t=Ag.fromNumber(e).zzEncode();return this._push(zg,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(jg,1,e?1:0)}fixed32(e){return this._push(Vg,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Ag.fromBigInt(e);return this._push(Vg,4,t.lo)._push(Vg,4,t.hi)}fixed64Number(e){const t=Ag.fromNumber(e);return this._push(Vg,4,t.lo)._push(Vg,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(wg,4,e)}double(e){return this._push(Pg,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(jg,1,0):this.uint32(t)._push(Gg,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(Ig,t,e):this._push(jg,1,0)}fork(){return this.states=new Og(this),this.head=this.tail=new Lg(Ng,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 Lg(Ng,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?Bn(n):Bg(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function jg(e,t,n){t[n]=255&e}function qg(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class $g extends Lg{next;constructor(e,t){super(qg,e,t),this.next=void 0}}function zg(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 Vg(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 Gg(e,t,n){t.set(e,n)}function Kg(e,t,n){t.set(e,n)}function Hg(e,t,n){e.length<40?Ig(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(mr(e),n)}function Wg(e,t){const n=new Ug;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*Qg(e,t,n){const r=Rg(e);yield*t.stream(r,void 0,"$",n)}function Yg(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function Jg(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Yg("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 Zg(e,t,n){return Yg("message",2,e,t,n)}null!=globalThis.Buffer&&(Ug.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Kg,t,e),this},Ug.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Hg,t,e),this});class Xg extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var ev,tv,nv,rv,iv,sv,av,ov,uv;!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=()=>Jg(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Zg((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),nv.codec().encode(t.peer,n)),null!=t.reservation&&(n.uint32(26),rv.codec().encode(t.reservation,n)),null!=t.limit&&(n.uint32(34),iv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(40),sv.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=nv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.reservation=rv.codec().decode(t,t.uint32(),{limits:r.limits?.reservation});break;case 4:i.limit=iv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 5:i.status=sv.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*nv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*rv.codec().stream(t,t.uint32(),`${r}.reservation`,{limits:i.limits?.reservation});break;case 4:yield*iv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 5:yield{field:`${r}.status`,value:sv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(ev||(ev={})),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=()=>Jg(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Zg((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),nv.codec().encode(t.peer,n)),null!=t.limit&&(n.uint32(26),iv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(32),sv.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=nv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.limit=iv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 4:i.status=sv.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*nv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*iv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 4:yield{field:`${r}.status`,value:sv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(tv||(tv={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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:On(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 Xg('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 Xg('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 Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(nv||(nv={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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),uv.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 Xg('Decode error - repeated field "addrs" had too many elements');r.addrs.push(e.bytes());break;case 3:r.voucher=uv.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 Xg('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*uv.codec().stream(e,e.uint32(),`${n}.voucher`,{limits:r.limits?.voucher});break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(rv||(rv={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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 Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(iv||(iv={})),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"}(sv||(sv={})),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"}(av||(av={})),function(e){e.codec=()=>Jg(av)}(sv||(sv={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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:On(0),peer:On(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 Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(ov||(ov={})),function(e){let t;e.codec=()=>(null==t&&(t=Zg((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),ov.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:On(0),payloadType:On(0),signature:On(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=ov.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*ov.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 Wg(t,e.codec())},e.decode=function(t,n){return _g(t,e.codec(),n)},e.stream=function(t,n){return Qg(t,e.codec(),n)}}(uv||(uv={}));class dv extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"}class cv extends Error{static name="DoubleRelayError";name="DoubleRelayError"}class lv extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"}function pv(e){const t=e*BigInt(1e3),n=(new Date).getTime();return Number(t-BigInt(n))}class hv{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 fv=Th(wh(Jh.matchers[0],yh(au))),mv=Th(yh(au));class yv extends Rt{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(yg,{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(yg)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{const n=bv(e),r=bv(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=Zd([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}}function bv(e){const t=e.metadata.get("last-dial-success");return null==t?0:new Date(yr(t)).getTime()}class gv extends Rt{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(mv.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else{if(!fv.exactMatch(e))throw new ft(`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=>Su(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}}class vv extends Rt{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 ed,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??5e3,this.started=!1,this.relayFilter=hd(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(mg)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async e=>{await this.peerStore.merge(e.id,{tags:{[mg]: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 ft("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new lv("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 ft("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&&pv(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 dv("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(Xh.matches(i.remoteAddr))throw new cv("not creating reservation over relayed connection");const s=await this.#X(i,{signal:r}),a=pv(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 dv("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:{[mg]:{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(yg,t),r=yc(n).pb(ev);let i;this.log.trace("send RESERVE to %p",e.remotePeer),await r.write({type:ev.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===sv.OK&&null!=i.reservation){const t=new Set;t.add(e.remoteAddr.toString());for(const n of i.reservation.addrs){let r=Su(n);null==r.getComponents().find(e=>e.code===tu)&&(r=r.encapsulate(`/p2p/${e.remotePeer}`)),r=Su(r.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),t.add(r.toString())}return i.reservation.addrs=[...t].map(e=>Su(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:{[mg]: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=hd(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}}class wv extends Qd{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 Tv(e){return new wv(e)}class Ev{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 yv(e,{filter:t.discoveryFilter??Fc(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 vv(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";[_t]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Lt](){return null!=this.discovery?["@libp2p/identify"]:[]}[Mt]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.components.registrar.handle(bg,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await It(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Dt(this.discovery,this.reservationStore),await this.components.registrar.unhandle(bg),this.started=!1}async dial(e,t){const n=e.toString().split("/p2p-circuit"),r=Su(n[0]),i=Su(n[n.length-1]),s=r.getComponents().find(e=>e.code===tu)?.value,a=i.getComponents().find(e=>e.code===tu)?.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 ht(`C${t}`)}const o=jo(s),u=jo(a);let d,c=this.components.connectionManager.getConnections(o)[0];null==c?(await this.components.peerStore.merge(o,{multiaddrs:[r]}),t.onProgress?.(new Lf("circuit-relay:open-connection")),c=await this.components.connectionManager.openConnection(o,t)):t.onProgress?.(new Lf("circuit-relay:reuse-connection"));try{t.onProgress?.(new Lf("circuit-relay:open-hop-stream")),d=await c.newStream(yg,t);const n=yc(d).pb(ev);t.onProgress?.(new Lf("circuit-relay:write-connect-message")),await n.write({type:ev.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Su(i).bytes]}},t),t.onProgress?.(new Lf("circuit-relay:read-connect-response"));const s=await n.read(t);if(s.status!==sv.OK)throw new dt(`failed to connect via relay with status ${s?.status?.toString()??"undefined"}`);const a=new hv(s.limit),o=Tv({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 gv(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=>fv.exactMatch(e)||mv.exactMatch(e))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter(e=>Xh.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=yc(e).pb(tv),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:tv.Type.STATUS,status:sv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});if(i.type!==tv.Type.CONNECT)return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:tv.Type.STATUS,status:sv.UNEXPECTED_MESSAGE},{signal:n}),void await e.close({signal:n});if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(Su)}catch{return!1}return!0})(i))return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:tv.Type.STATUS,status:sv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});const s=$o(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:tv.Type.STATUS,status:sv.PERMISSION_DENIED},{signal:n}),void await e.close({signal:n});this.log.trace("sending success response to %p",t.remotePeer),await r.write({type:tv.Type.STATUS,status:sv.OK},{signal:n});const a=new hv(i.limit),o=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),u=this.components.addressManager.getAddresses()[0],d=Tv({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 Pv(e={}){return t=>new Ev(t,e)}class xv extends Rt{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=>Su(e)).filter(e=>{if(!Jh.matches(e))return this.log.error("invalid multiaddr %a",e),!1;const t=e.getComponents().findLast(e=>e.code===tu)?.value;return null!=t||(this.log.error("invalid bootstrap multiaddr without peer id"),!1)}).map(e=>({id:jo(e.getComponents().findLast(e=>e.code===tu)?.value??""),multiaddrs:[e]})),this._init=t}[Pt]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[_t]=["@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 Sv;!function(e){let t;e.codec=()=>(null==t&&(t=Bp((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 Up('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 Up('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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Sv||(Sv={}));const Av="ipfs";class Cv{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??Av}/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:mr(this.host.agentVersion),ProtocolVersion:mr(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 kv extends Cv{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Av}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??1)&&e.events.addEventListener("connection:open",e=>{this.identify(e.detail).catch(()=>{})})}[_t]=["@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=yc(n,{maxDataLength:this.maxMessageSize}).pb(Sv),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 dt("Public key was missing from identify message");const a=zo(Fo(r).toCID());if(!e.remotePeer.equals(a))throw new dt("Identified peer does not match the expected peer");if(this.components.peerId.equals(a))throw new dt("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 dt("message was null or undefined");const s={};if(i.listenAddrs.length>0&&(s.addresses=i.listenAddrs.map(e=>({isCertified:!1,multiaddr:Su(e)}))),i.protocols.length>0&&(s.protocols=i.protocols),null!=i.publicKey){const e=Fo(i.publicKey);if(!qo(e).equals(r.remotePeer))throw new dt("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 bl.openAndCertify(t,Tl.DOMAIN);let u=Tl.createFromProtobuf(o.payload);const d=zo(o.publicKey.toCID());if(!u.peerId.equals(d))throw new dt("signing key does not match PeerId in the PeerRecord");if(!r.remotePeer.equals(u.peerId))throw new dt("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=bl.createFromProtobuf(c.peerRecordEnvelope),r=Tl.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=mr(i.agentVersion)),null!=i.protocolVersion&&(t.ProtocolVersion=mr(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=>Su(e)),observedAddr:null==i.observedAddr?void 0:Su(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 Su(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),Cd(t))return;const n=t.getComponents();n[0].code!==eu&&(42!==n[0].code||n[1].code!==eu)||function(e){try{const n=fd(e);return"ip6"===n.type&&(t=n.host,new gd("2000::/3").contains(t))}catch{return!1}var t}(t)?Nh.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(tu));let a=i.peerRecordEnvelope;if(s.length>0&&null==a){const e=new Tl({peerId:this.components.peerId,multiaddrs:s});a=(await bl.seal(e,this.components.privateKey,{signal:r})).marshal().subarray()}let o=t.remoteAddr.bytes;Mh.matches(t.remoteAddr)||(o=void 0);const u=yc(e).pb(Sv);n("send response"),await u.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Ro(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 Iv(e={}){return t=>new kv(t,e)}const Dv=36e5,Mv=48*Dv,Fv=Dv,Rv=Dv,_v=`${Ct}-kad-dht`;var Lv,Nv,Ov,Bv,Uv,jv,qv,$v;function zv(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=Bp((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:On(0),value:On(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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Lv||(Lv={}));class Vv{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 Lv.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:zv(this.timeReceived)}}static deserialize(e){const t=Lv.decode(e);return new Vv(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 Vv(e.key,e.value,t)}}function Gv(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=ch(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 Kv extends Error{constructor(e="Query error"){super(e),this.name="QueryError"}}class Hv extends Error{constructor(e="Invalid record"){super(e),this.name="InvalidRecordError"}}class Wv extends Error{constructor(e="No selector function configured for prefix"){super(e),this.name="MissingSelectorError"}}function Qv(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 Yv(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 Jv(e,t={}){const n={...e,name:"FINAL_PEER",type:2};return t.onProgress?.(new CustomEvent("kad-dht:query:final-peer",{detail:n})),n}function Zv(e,t={}){const n={...e,name:"QUERY_ERROR",type:3};return t.onProgress?.(new CustomEvent("kad-dht:query:query-error",{detail:n})),n}function Xv(e,t={}){const n={...e,name:"PROVIDER",type:4};return t.onProgress?.(new CustomEvent("kad-dht:query:provider",{detail:n})),n}function ew(e,t={}){const n={...e,name:"VALUE",type:5};return t.onProgress?.(new CustomEvent("kad-dht:query:value",{detail:n})),n}function tw(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=Bp((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=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(Nv||(Nv={})),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"}(Ov||(Ov={})),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"}(Bv||(Bv={})),function(e){e.codec=()=>Op(Bv)}(Ov||(Ov={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(Uv||(Uv={})),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"}(jv||(jv={})),function(e){e.codec=()=>Op(jv)}(Uv||(Uv={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((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),Uv.codec().encode(e.connection,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={id:On(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 Up('Decode error - map field "multiaddrs" had too many elements');r.multiaddrs.push(e.bytes());break;case 3:r.connection=Uv.codec().decode(e);break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}(qv||(qv={})),function(e){let t;e.codec=()=>(null==t&&(t=Bp((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.type&&0!==Bv[e.type]&&(t.uint32(8),Ov.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),qv.codec().encode(n,t);if(null!=e.providers)for(const n of e.providers)t.uint32(74),qv.codec().encode(n,t);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={type:Ov.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=Ov.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 Up('Decode error - map field "closer" had too many elements');r.closer.push(qv.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 Up('Decode error - map field "providers" had too many elements');r.providers.push(qv.codec().decode(e,e.uint32(),{limits:n.limits?.providers$}));break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Dp(t,e.codec()),e.decode=(t,n)=>yp(t,e.codec(),n)}($v||($v={}));const nw={pk:function(e,t){return 0}};async function rw(e,t,n){const r=t.key,i=yr(r).split("/");if(i.length<3)return;const s=e[i[1].toString()];if(null==s)throw new Qe(`No validator available for key type "${i[1]}"`);await s(r,t.value,n)}const iw={pk:async(e,t,n)=>{if(!(e instanceof Uint8Array))throw new Qe('"key" must be a Uint8Array');if(e.byteLength<5)throw new Qe("Invalid public key record");if("/pk/"!==yr(e.subarray(0,4)))throw new Qe("key was not prefixed with /pk/");const r=Fo(t);if(!Nn(e.slice(4),r.toMultihash().bytes))throw new Qe("public key does not match passed in key")}},sw=mr("/pk/");function aw(e){return{...e,multiaddrs:e.multiaddrs.filter(e=>!Cd(e))}}async function ow(e,t){const n=await dr.digest(e);return t?.signal?.throwIfAborted(),n.digest}async function uw(e,t){return ow(e.toMultihash().bytes,t)}function dw(e,t){return new Qp(`${e}/${yr(t,"base32")}`,!1)}function cw(e,t){const n=new Date;return new Vv(e,t,n).serialize()}function lw(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:In.createV1(85,xn(mr(r,"base32"))),peerId:jo(n)}}function pw(e,t,n){const r=[e,"string"==typeof t?t:yr(t.multihash.bytes,"base32")];return null!=n&&r.push(n.toString()),new Qp(r.join("/"))}function hw(e){return new Date(wa(e))}function fw(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 mw(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 yw{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=dw(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=Vv.deserialize(r);return await rw(this.validators,i,t),i}async*sendCorrectionRecord(e,t,n,r){this.log("sendCorrection for %b",e);const i=cw(e,n);for(const{value:s,from:a}of t){if(Nn(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{const t=dw(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:Ov.PUT_VALUE,key:e,record:i};for await(const e of this.network.sendRequest(a,o,r))"PEER_RESPONSE"===e.name&&null!=e.record&&Nn(e.record.value,Vv.deserialize(i).value)&&(t=!0),yield e;if(!t)throw new Kv("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=cw(e,t),i=dw(this.datastorePrefix,e);this.log(`storing record for key ${i.toString()}`),await this.components.datastore.put(i,r.subarray(),n),yield*rc(this.peerRouting.getClosestPeers(e,{...n,signal:n.signal}),t=>Gv(t,t=>async()=>{if("FINAL_PEER"!==t.name)return[t];const i=[],s={type:Ov.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&&Nn(e.record.value,Vv.deserialize(r).value)||i.push(Zv({from:t.peer.id,error:new Kv("Value not put correctly"),path:e.path},n)));return i}),e=>Am(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 Qe("No records given");const r=yr(t).split("/");if(r.length<3)throw new Qe("Record key does not have a selector function");const i=e[r[1].toString()];if(null==i)throw new Wv(`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 rt("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 ew({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 ew({from:r.id,value:a.record.value,path:s},t))},t)}}function bw(e,t){const n={id:e.id.toMultihash().bytes,multiaddrs:(e.multiaddrs??[]).map(e=>e.bytes),connection:t};return n}function gw(e){if(null==e.id)throw new Error("Invalid peer in message");return{id:$o(xn(e.id)),multiaddrs:(e.multiaddrs??[]).map(e=>Su(e))}}class vw{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:Ov.ADD_PROVIDER,key:r,providers:[bw({id:this.components.peerId,multiaddrs:t})]};let s=0;const a=this,o=Fd({objectMode:!0}),u=new Kd({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 Zv({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 Yv({from:this.components.peerId,messageType:Ov.GET_PROVIDERS,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),yield Xv({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:Ov.GET_PROVIDERS,key:i};yield*s.network.sendRequest(e.id,a,{...t,signal:n,path:r})},u=new td(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 Xv({from:s.from,providers:i,path:s.path},t),r+=i.length,r>=n))return}}}class ww extends Rt{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 ec({...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 Qe("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 tw({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 Qv({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 Yv({from:e,messageType:s.type,closer:s.closer.map(gw),providers:s.providers.map(gw),record:null==s.record?void 0:Vv.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 Zv({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 Qe("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 tw({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 Qv({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 Yv({from:e,messageType:r,path:n.path},n)}catch(t){this.metrics.errors?.increment({[r]:!0}),i?.abort(t),yield Zv({from:e,error:t,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async _writeMessage(e,t,n){const r=yc(e);await r.write(t,$v,n)}async _writeReadMessage(e,t,n){const r=yc(e);await r.write(t,$v,n);const i=await r.read($v,n);return i.closer.forEach(e=>{this.safeDispatchEvent("peer",{detail:gw(e)})}),i.providers.forEach(e=>{this.safeDispatchEvent("peer",{detail:gw(e)})}),i}}function Tw(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 Ew{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 uw(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:wb(this.originDhtKey,t),path:n};if(this.peerDistances.length===this.capacity){const e=this.peerDistances[this.peerDistances.length-1];if(null!=e&&-1!==Tw(r.distance,e.distance))return}let i=!1;for(let e=0;e<this.peerDistances.length;e++){const t=Tw(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===Tw(wb(await uw(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 Pw{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:Ov.GET_VALUE,key:t};yield*this.network.sendRequest(e,r,n)}async*getPublicKeyFromNode(e,t={}){const n=Un([sw,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=qo(Fo(i.record.value));if(!n.equals(e))throw new Ye("public key does not match id");if(null==n.publicKey)throw new Ye("public key missing");yield ew({from:e,value:i.record.value,path:r},t)}throw new Kv(`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 Jv({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:Ov.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 Jv({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 rt("Not found")}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);const n=await ow(e,t),r=new Ew(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:Ov.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 Jv({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 Zv({from:r.from,error:new Kv(t),path:n.path},n);continue}yield r}}async _verifyRecordOnline(e,t){if(null==e.timeReceived)throw new Hv("invalid record received");await rw(this.validators,new Vv(e.key,e.value,e.timeReceived),t)}async getClosestPeersOffline(e,t){const n=[];try{const r=$o(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 ow(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=pw(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=pw(this.datastorePrefix,e,t),i=va(n?.time?.getTime()??Date.now());await this.datastore.put(r,i,n)}async loadProviders(e,t){const n=new ed,r=pw(this.datastorePrefix,e);for await(const e of this.datastore.query({prefix:r.toString()},t)){const{peerId:t}=lw(e.key);n.set(t,hw(e.value))}return n}}async function*Sw(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=Fd({objectMode:!0}),h=new Kd({concurrency:s,sort:(e,t)=>Tw(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 Ke)};l.addEventListener("abort",f);try{const y=await ow(t,{signal:l});function m(n,s){if(null==n)return;d.add(n.id.toMultihash().bytes);const f=wb(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 uw(e.id,{signal:l});-1===Tw(wb(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(Zv({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 uw(e,{signal:l}))})),yield*p}finally{l.removeEventListener("abort",f)}}class Aw{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=Zd([this.shutDownController.signal,r.signal,n.signal]),s=this.logger.forComponent(`${this.logPrefix}:query:`+yr(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 Ld(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 zd(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),s("query:start");const r=await ow(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=hd(1024),c=u.map((r,a)=>Sw({...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 nc(...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 Cw(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 kw{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=mw(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=kd(),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=Zd(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 rc(this.peerRouting.getClosestPeers(this.peerId.toMultihash().bytes,{signal:t,isSelfQuery:!0}),e=>hh(e,this.count),async e=>Cw(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 Iw extends Rt{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 Kd({concurrency:t.concurrency??10,metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_queue`}),this.reprovideTimeout=new ec({...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??Mv,this.interval=t.interval??Fv,this.contentRouting=t.contentRouting,this.running=!1,this.reprovide=mw(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(Rv)}).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}=lw(t.key),i=hw(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(Rv)}).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 dh(this.contentRouting.provide(e,this.addressManager.getAddresses(),t))}}class Dw{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 td,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}async start(){if(this.running)return;this.running=!0;const e=await uw(this.components.peerId);this.newPeers=new Ew(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 td(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},[_v]:{value:1}}})}),...[...n].map(async e=>{await this.components.peerStore.merge(e,{tags:{[this.closeTagName]:void 0,[_v]:void 0}})})])}}function Mw(e){return Array.isArray(e?.peers)}class Fw{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??_w,this.kBucketSize=t.kBucketSize??Rw,this.splitThreshold=t.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=t.numberOfOldContactsToPing??Lw,this.lastPingThreshold=t.lastPingThreshold??Ow,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=_c({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 uw(e,t),lastPing:Date.now()}}async add(e,t){const n={peerId:e,kadId:await uw(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 Ew(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*Gv(n.peers,({peer:e})=>e.id)}count(){return function e(t){if(Mw(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){Mw(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+yr(wb(e,t),"base16"))}_determineBucket(e){const t=yr(e,"base2");return function e(n,r=0){return Mw(n)?n:e("0"===t[r]?n.left:n.right,r+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex(e=>Nn(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"===yr(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 Rw=20,_w=6,Lw=3,Nw="kad-peer",Ow=6e5;class Bw extends Rt{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??Rw,this.running=!1,this.protocol=t.protocol,this.network=t.network,this.peerTagName=t.peerTagName??Nw,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 ec({...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 ec({...t.pingNewContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_new_contact_time_milliseconds`}),this.kb=new Fw(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 Dw(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 It(this.closestPeerTagger,this.kb))}async afterStart(){let e=0;Promise.resolve().then(async()=>{if(!this.populateFromDatastoreOnStart)return;const t=Zd([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(Nw)],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 Dt(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=Zd([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 Am(n))null!=e&&(yield e)}async verifyNewContact(e,t){const n=this.pingNewContactTimeout.getTimeoutSignal(),r=Zd([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 uw(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 uw(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(Mw(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 Uw,jw=[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 qw{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=Zd([r?.signal,AbortSignal.timeout(this.refreshQueryTimeout)]);try{const t=await Cw(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=so(2);return $o(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=jw[(r^32768>>n)&i|t&~i],a=new ArrayBuffer(34),o=new DataView(a,0,a.byteLength);return o.setUint8(0,dr.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=wb(this.routingTable.kb.localPeer.kadId,e);let n=0;for(const e of t){if(0!==e)break;n++}yield n}}}class $w{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 dt("Missing key");let n;try{n=In.decode(t.key)}catch(e){throw new dt("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=$o(xn(t.id)),i=t.multiaddrs.map(e=>Su(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 zw{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 dt("Invalid FIND_NODE message received - key was missing");const n=await this.peerRouting.getClosestPeersOffline(t.key,{exclude:[e,this.peerId]});Nn(this.peerId.toMultihash().bytes,t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map(e=>e.decapsulateCode(tu))});const r={type:Ov.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 Vw{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 dt("Invalid GET_PROVIDERS message received - key was missing");let n;try{n=In.decode(t.key)}catch(e){throw new dt("Invalid CID")}this.log("%p asking for providers for %s",e,n);const[r,i]=await Promise.all([El(Gv(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:Ov.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 Gw{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 dt("Invalid key");const r={type:Ov.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===yr(e.subarray(0,4))}(n)){this.log("is public key");const e=function(e){return $o(xn(e.subarray(4)))}(n);let t;try{const n=await this.peerStore.get(e);if(null==n.id.publicKey)throw new rt("No public key found in key book");t=Ro(n.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=t)return this.log("returning found public key"),r.record=new Vv(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=dw(this.datastorePrefix,e);let n;try{n=await this.datastore.get(t)}catch(e){if("NotFoundError"===e.name)return;throw e}const r=Vv.deserialize(n);if(!(null==r.timeReceived||Date.now()-r.timeReceived.getTime()>Mv))return r;await this.datastore.delete(t)}}class Kw{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 Hw{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 dt(`Empty record from: ${e}`);try{const e=Vv.deserialize(t.record);await rw(this.validators,e),e.timeReceived=new Date;const r=dw(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 Ww{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={[Ov.GET_VALUE.toString()]:new Gw(e,t),[Ov.PUT_VALUE.toString()]:new Hw(e,t),[Ov.FIND_NODE.toString()]:new zw(e,t),[Ov.ADD_PROVIDER.toString()]:new $w(e,t),[Ov.GET_PROVIDERS.toString()]:new Vw(e,t),[Ov.PING.toString()]:new Kw(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 lt)};let r=AbortSignal.timeout(this.incomingMessageTimeout);r.addEventListener("abort",n);const i=yc(e).pb($v);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 Qw extends Rt{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 Yw{dht;constructor(e){this.dht=e}async provide(e,t={}){await dh(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 dh(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 rt("Could not find value for key")}}class Jw{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 rt("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 Zw extends Rt{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??Rw,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??aw,this.onPeerConnectTimeout=t.onPeerConnectTimeout??1e4,this.providers=new xw(e,{...t.providers,logPrefix:n,datastorePrefix:r}),this.validators={...iw,...t.validators},this.selectors={...nw,...t.selectors},this.network=new ww(e,{protocol:this.protocol,logPrefix:n,metricsPrefix:i}),this.routingTable=new Bw(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=kd();!0===t.allowQueryWithZeroPeers&&a.resolve(),this.queryManager=new Aw(e,{disjointPaths:this.d,alpha:this.a,logPrefix:n,metricsPrefix:i,initialQuerySelfHasRun:a,routingTable:this.routingTable,allowQueryWithZeroPeers:t.allowQueryWithZeroPeers}),this.peerRouting=new Pw(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:n}),this.contentFetching=new yw(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:n,datastorePrefix:r}),this.contentRouting=new vw(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:n}),this.routingTableRefresh=new qw(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:n}),this.rpc=new Ww(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 Qw(e,{protocol:this.protocol,logPrefix:n}),this.querySelf=new kw(e,{peerRouting:this.peerRouting,interval:t.querySelfInterval,initialInterval:t.initialQuerySelfInterval,logPrefix:n,initialQuerySelfHasRun:a,operationMetrics:s}),this.reprovider=new Iw(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 Jw(this),this.dhtContentRouting=new Yw(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})=>!Cd(e)&&!Xh.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=fw(this.get.bind(this),s,"GET_VALUE"),this.findProviders=fw(this.findProviders.bind(this),s,"FIND_PROVIDERS"),this.findPeer=fw(this.findPeer.bind(this),s,"FIND_PEER"),this.getClosestPeers=fw(this.getClosestPeers.bind(this),s,"GET_CLOSEST_PEERS"),this.provide=fw(this.provide.bind(this),s,"PROVIDE"),this.put=fw(this.put.bind(this),s,"PUT_VALUE")}[Symbol.toStringTag]="@libp2p/kad-dht";[_t]=["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery","@libp2p/kad-dht"];[Lt]=["@libp2p/identify","@libp2p/ping"];get[Ge](){return this.dhtContentRouting}get[At](){return this.dhtPeerRouting}get[Pt](){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 It(this.routingTable,this.queryManager,this.network,this.topologyListener,this.routingTableRefresh,this.reprovider),await It(this.querySelf))}async stop(){this.running=!1,await Dt(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 Xw(e={}){return t=>new Zw(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"}(Uw||(Uw={}));class eT{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";[_t]=["@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 lt("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 Ld(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=so(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 zn,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(!Nn(n,s.subarray()))throw new ct(`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 zd(i.promise,t.signal)}catch(t){throw i.error("error while pinging %o - %e",e,t),r?.abort(t),t}finally{r?.close()}}}function tT(e={}){return t=>new eT(t,e)}function nT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function rT(e,t,n){if(!e.s){if(n instanceof iT){if(!n.s)return void(n.o=rT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(rT.bind(null,e,t),rT.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var iT=/*#__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{rT(r,1,s(this.v))}catch(e){rT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?rT(r,1,t?t(i):i):n?rT(r,1,n(i)):rT(r,2,i)}catch(e){rT(r,2,e)}},r},e}();function sT(e){return e instanceof iT&&1&e.s}function aT(e,t,n){for(var r;;){var i=e();if(sT(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!sT(s)){r=1;break}s=s.s}if(t){var a=t();if(a&&a.then&&!sT(a)){r=2;break}}}var o=new iT,u=rT.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&&!sT(a))return void a.then(l).then(void 0,u);if(!(i=e())||sT(i)&&!i.v)return void rT(o,1,s);if(i.then)return void i.then(c).then(void 0,u);sT(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):rT(o,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):rT(o,1,s)}}function oT(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 uT="/ocean/nodes/1.0.0",dT=1e4,cT=["/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"],lT=/*#__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=oT(function(){return nT(function(){return t=S(c.findPeer(jo(e),{signal:AbortSignal.timeout(2e4)})),aT(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===Uw.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=oT(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=nT(function(){return Promise.resolve(i.peerStore.get(jo(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:cT).map(Su);return Promise.resolve(async function(e={}){e.privateKey??=await async function(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=Ys.utils.randomSecretKey(),t=Ys.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 ia(e,t)}()}();const t=new qm({...await Mu(e),peerId:(n=e.privateKey,qo(n.publicKey))});var n;return!1!==e.start&&await t.start(),t}(I({addresses:{listen:[]},transports:[pg(),Pv()].concat(t.p2pConfig.enableTcp?[fg()]:[]),connectionEncrypters:[Ub()],streamMuxers:[ng()],peerDiscovery:[].concat(n.length>0?[(r={list:n.map(String),timeout:1e4},e=>new xv(e,r))]:[]),services:{identify:Iv(),ping:tT(),dht:Xw({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){B.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=k(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:(B.debug("[P2P] bare peerId -> dialByPeerId "+e),n.dialByPeerId(r,e,t))}var u=nT(function(){function i(i){if(a)return i;var o=n.peerIdFromMultiaddr(s);if(o){B.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=Su(e),o=function(){if(n.isDialable(s))return B.debug("[P2P] dial single addr: "+s),nT(function(){return Promise.resolve(r.dial(s,{signal:t})).then(function(e){return B.debug("[P2P] dial single SUCCESS via "+e.remoteAddr),a=1,e})},function(e){B.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=k(e);!(a=o()).done;){var u=n.peerIdFromMultiaddr(a.value);if(u){B.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 B.debug("[P2P] dial array: "+a.length+" dialable addrs"),nT(function(){return Promise.resolve(r.dial(a,{signal:t})).then(function(e){return B.debug("[P2P] dial array SUCCESS via "+e.remoteAddr),i=1,e})},function(e){B.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:(B.debug("[P2P] "+t+": last resort dial by peerId"),nT(function(){return Promise.resolve(e.dial(a,{signal:AbortSignal.timeout(1e4)})).then(function(e){return B.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:Su(n+"/p2p/"+t)});B.debug("[P2P] "+t+": "+o.length+"/"+d.length+" addrs are dialable");var u=function(){if(o.length>0)return B.debug("[P2P] "+t+": dialing "+o.map(String)),nT(function(){return Promise.resolve(e.dial(o,{signal:n})).then(function(e){return B.debug("[P2P] "+t+": SUCCESS via "+e.remoteAddr+" (limited="+(null!=e.limits)+")"),r=1,e})},function(e){B.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){B.debug("[P2P] "+t+": no dialable addrs in peerStore, querying DHT...");var n=nT(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=k(e.multiaddrs);!(n=r()).done;)c(n.value);B.debug("[P2P] "+t+": DHT returned "+e.multiaddrs.length+" addrs")})},function(e){B.debug("[P2P] "+t+": DHT findPeer failed: "+e.message)});if(n&&n.then)return n.then(function(){})}else B.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=nT(function(){return Promise.resolve(e.peerStore.get(a)).then(function(e){if(null!=e&&e.addresses){for(var n,r=k(e.addresses);!(n=r()).done;)c(n.value.multiaddr);B.debug("[P2P] "+t+": "+e.addresses.length+" peerStore addrs")}})},function(){B.debug("[P2P] "+t+": not in peerStore")});return l&&l.then?l.then(o):o()},s=this,a=jo(t),o=e.getConnections(a).filter(function(e){return"open"===e.status});if(o.length>0)return B.debug("[P2P] "+t+": reusing existing connection via "+o[0].remoteAddr),Promise.resolve(o[0]);var u=function(){if(0===e.getConnections().length)return B.debug("[P2P] "+t+": no connections yet, waiting for bootstrap..."),Promise.resolve($e(3e3)).then(function(){var n=e.getConnections(a);if(n.length>0)return B.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 hT(e)},t.getSignature=function(e,t,n){return pT(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 fT(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:dT);return Promise.resolve(s.getConnection(e,a)).then(function(e){return nT(function(){return Promise.resolve(e.newStream(uT,{signal:a,runOnLimitedConnection:!0})).then(function(n){var i=mc(n),o=t;return r&&(o=I({},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=oT(function(){return nT(function(){r=S(t);var s=aT(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=oT(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(nT(function(){var u=I({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===E.COMPUTE_GET_STREAMABLE_LOGS||t===E.COMPUTE_GET_RESULT)return R(/*#__PURE__*/M().mark(function e(){var t;return M().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,C(d.read({signal:AbortSignal.timeout(dT)}));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 Ud){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))();var m=[c],y=nT(function(){var e=aT(function(){return!0},void 0,function(){var e;return Promise.resolve(d.read({signal:AbortSignal.timeout(null!=(e=o.p2pConfig.dialTimeout)?e:dT)})).then(function(e){m.push(o.toUint8Array(e))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof Ud))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 B.debug("[P2P] Stream reset/closed on attempt "+(s+1)+", retrying..."),Promise.resolve($e(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(nT(function(){return Promise.resolve(t.sendP2pCommand(e,E.STATUS,{}))},function(e){throw B.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(nT(function(){var i={};return t&&(i.fromTimestamp=t.toString()),Promise.resolve(r.sendP2pCommand(e,E.JOBS,i,null,n)).then(function(e){return Array.isArray(e)?e:[]})},function(e){return B.error("P2P getNodeJobs failed:",e),[]}))}catch(e){return Promise.reject(e)}},t.getNonce=function(e,t,n){try{var r=this;return Promise.resolve(nT(function(){return Promise.resolve(r.sendP2pCommand(e,E.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 B.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,E.ENCRYPT)).then(function(o){return Promise.resolve(a.sendP2pCommand(n,E.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,E.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,E.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,E.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,E.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,E.COMPUTE_INITIALIZE,y,null,c)}var t=function(){if(h)return Promise.resolve(m.getNodePublicKey(s)).then(function(e){e&&(y.output=ku(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=ku(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,E.DOWNLOAD)).then(function(c){var p={command:E.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=Cu(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=nT(function(){var e=aT(function(){return!0},void 0,function(){var e;return Promise.resolve(t.read({signal:AbortSignal.timeout(null!=(e=u.p2pConfig.dialTimeout)?e:dT)})).then(function(e){d.push(new Uint8Array(u.toUint8Array(e)))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof Ud))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,E.COMPUTE_START)).then(function(g){function w(){function n(){return Promise.resolve(y.sendP2pCommand(e,E.COMPUTE_START,T,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&&(T.output=ku(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var T={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&&(T.metadata=d),c&&(T.additionalViewers=c),p&&(T.policyServer=p),f&&(T.queueMaxWaitTime=f);var P=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(T.encryptedDockerRegistryAuth=ku(e,JSON.stringify(m)))})}();return P&&P.then?P.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,E.FREE_COMPUTE_START)).then(function(m){function b(){function n(){return Promise.resolve(h.sendP2pCommand(e,E.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=ku(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=ku(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,E.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,E.COMPUTE_GET_STREAMABLE_LOGS)).then(function(a){return i.sendP2pCommand(e,E.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,E.COMPUTE_STOP)).then(function(o){var d={jobId:e,consumerAddress:a,nonce:u,signature:o};return r&&(d.agreementId=r),s.sendP2pCommand(t,E.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,E.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:dT;return R(/*#__PURE__*/M().mark(function e(){var t;return M().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,C(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 Ud){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))()})}var u={command:E.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,E.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,E.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,E.CREATE_AUTH_TOKEN)).then(function(e){return Promise.resolve(r.sendP2pCommand(t,E.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,E.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,E.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(ze(n,s+o+E.VALIDATE_DDO)).then(function(n){return Promise.resolve(i.sendP2pCommand(e,E.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(ze(e,s+o)).then(function(e){return i.sendP2pCommand(n,E.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(nT(function(){return Promise.resolve(n.sendP2pCommand(e,E.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,E.POLICY_SERVER_PASSTHROUGH,I({},t),null,n))}catch(e){return Promise.reject(e)}},t.initializePSVerification=function(e,t,n){try{return Promise.resolve(this.sendP2pCommand(e,E.POLICY_SERVER_PASSTHROUGH,I({},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,E.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,E.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,E.GET_LOGS,I({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,E.FETCH_CONFIG,t))}catch(e){return Promise.reject(e)}},t.pushConfig=function(e,t){try{return Promise.resolve(this.sendP2pCommand(e,E.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,E.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(s){var a;return i.sendP2pCommand(e,E.PERSISTENT_STORAGE_CREATE_BUCKET,I({},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,E.PERSISTENT_STORAGE_GET_BUCKETS,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.PERSISTENT_STORAGE_GET_BUCKETS,I({},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,E.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.PERSISTENT_STORAGE_LIST_FILES,I({},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,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(a){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,I({},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,E.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(o){return a.sendP2pCommand(e,E.PERSISTENT_STORAGE_UPLOAD_FILE,I({},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,E.PERSISTENT_STORAGE_DELETE_FILE,i)).then(function(a){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_DELETE_FILE,I({},a,{bucketId:n,fileName:r}),t,i)})}catch(e){return Promise.reject(e)}},e}(),pT=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 ze(e,a)})}catch(e){return Promise.reject(e)}},hT=function(e){try{return Promise.resolve("string"==typeof e?function(e){try{return w.default.decode(e,{json:!0})}catch(e){throw new Error("Error decoding JWT")}}(e).address:e.getAddress())}catch(e){return Promise.reject(e)}};function fT(e){return"string"==typeof e?e:void 0}function mT(e){if(Array.isArray(e))return!0;if(!e)return!1;try{return Su(e),!0}catch(e){}try{return jo(e),!0}catch(e){return!1}}var yT=/*#__PURE__*/function(){function e(){this.httpProvider=new Du,this.p2pProvider=new lT}var t=e.prototype;return t.getImpl=function(e){return Array.isArray(e)||mT(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}(),bT=new yT;function gT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function vT(e,t,n){if(!e.s){if(n instanceof wT){if(!n.s)return void(n.o=vT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(vT.bind(null,e,t),vT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var wT=/*#__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{vT(r,1,s(this.v))}catch(e){vT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?vT(r,1,t?t(i):i):n?vT(r,1,n(i)):vT(r,2,i)}catch(e){vT(r,2,e)}},r},e}();function TT(e){return e instanceof wT&&1&e.s}var ET=/*#__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 gT(function(){return Promise.resolve(v.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 B.error(e),new Error("HTTP request failed")})},s=this,a=function(){if(mT(s.aquariusURL))return Promise.resolve(bT.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 a,u=this,d=0;i>500&&(B.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);var c=mT(u.aquariusURL),l=function(e,t){var n;do{var r=e();if(r&&r.then){if(!TT(r)){n=!0;break}r=r.v}var i=t();if(TT(i)&&(i=i.v),!i)return r}while(!i.then);var s=new wT,a=vT.bind(null,s,2);return(n?r.then(o):i.then(u)).then(void 0,a),s;function o(n){for(r=n;TT(i=t())&&(i=i.v),i;){if(i.then)return void i.then(u).then(void 0,a);if((r=e())&&r.then){if(!TT(r))return void r.then(o).then(void 0,a);r=r.v}}vT(s,1,r)}function u(n){if(n){do{if((r=e())&&r.then){if(!TT(r))return void r.then(o).then(void 0,a);r=r.v}if(TT(n=t())&&(n=n.v),!n)return void vT(s,1,r)}while(!n.then);n.then(u).then(void 0,a)}else vT(s,1,r)}}(function(){function i(e){return a?e:Promise.resolve($e(r)).then(function(){d++})}var l=gT(function(){function r(){if(i){var e=o.DDOManager.getDDOClass(i).getAssetFields().indexedMetadata;if(!t)return a=1,i;if(e.event&&e.event.txid===t)return a=1,i}}var i,d=c?Promise.resolve(bT.resolveDdo(u.aquariusURL,e,n)).then(function(e){i=e}):Promise.resolve(v.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!a&&d<i});return Promise.resolve(l&&l.then?l.then(function(e){return a?e:null}):a?l:null)}catch(e){return Promise.reject(e)}},t.validate=function(e,t,n,r,i){try{if(mT(n))return Promise.resolve(bT.validateDdo(n,e,t,r));var s=n+"/api/aquarius/assets/ddo/validate",a=n+"/api/services/nonce";return Promise.resolve(gT(function(){return Promise.resolve(t.getAddress()).then(function(n){return Promise.resolve(v.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(E.VALIDATE_DDO));return Promise.resolve(ze(t,a)).then(function(i){return Promise.resolve(v.default(s,{method:"POST",body:JSON.stringify({ddo:e,publisherAddress:n,nonce:o,signature:i}),headers:{"Content-Type":"application/json",Authorization:fT(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){B.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(gT(function(){return Promise.resolve(v.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 B.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(gT(function(){return Promise.resolve(v.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 B.error("Error querying metadata: ",e),new Error("Error querying metadata: "+e)}))}catch(e){return Promise.reject(e)}},e}(),PT=function(e,t,r,i){try{var s=new n.ethers.Contract(t,V,e);return Promise.resolve(s.allowance(r,i))}catch(e){return Promise.reject(e)}},xT=function(e,t,r,i,s){try{var a=new n.ethers.Contract(t,V,e);return Promise.resolve(a.allowance(r,i)).then(function(n){return Promise.resolve(H(e,t,n,s))})}catch(e){return Promise.reject(e)}},ST=function(e,t,r,i,s,a,o,u){void 0===o&&(o=!1);try{var d,c=function(n){if(d)return n;var r=null;return Promise.resolve(l.approve.estimateGas(s,a)).then(function(n){if(u)return n;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(G(n,e,null==t?void 0:t.gasFeeMultiplier,l.approve,s,a)).then(function(e){r=e})},function(e){B.error("ERROR: Failed to approve spender to spend tokens : "+e.message)});return i&&i.then?i.then(function(){return r}):r})},l=new n.ethers.Contract(i,V,e),p=function(){if(!o)return Promise.resolve(PT(e,i,r,s)).then(function(e){if(new b.default(e).isGreaterThan(new b.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)}},AT=function(e,t,r,i,s,a,o,u,d){void 0===o&&(o=!1);try{var c,l=function(n){return c?n:Promise.resolve(K(e,i,a,u)).then(function(n){return Promise.resolve(p.approve.estimateGas(s,n)).then(function(r){return d?new g.default(r.toString()):Promise.resolve(G(r,e,null==t?void 0:t.gasFeeMultiplier,p.approve,s,n))})})},p=new n.ethers.Contract(i,V,e),h=function(){if(!o)return Promise.resolve(xT(e,i,r,s)).then(function(e){if(new g.default(e).greaterThanOrEqualTo(new g.default(a))){var t=new g.default(e).toNumber();return c=1,t}})}();return Promise.resolve(h&&h.then?h.then(l):l(h))}catch(e){return Promise.reject(e)}},CT={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 kT(e,t,n){if(!e.s){if(n instanceof IT){if(!n.s)return void(n.o=kT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(kT.bind(null,e,t),kT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var IT=/*#__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{kT(r,1,s(this.v))}catch(e){kT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?kT(r,1,t?t(i):i):n?kT(r,1,n(i)):kT(r,2,i)}catch(e){kT(r,2,e)}},r},e}();function DT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}e.AccessListContract=Re,e.AccesslistFactory=Le,e.Aquarius=ET,e.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},e.ConfigHelper=z,e.DEVELOPMENT_CHAIN_ID=8996,e.Datatoken=Ie,e.Datatoken4=Me,e.Dispenser=oe,e.EnterpriseFeeCollectorContract=qe,e.EscrowContract=Ue,e.FEE_HISTORY_NOT_SUPPORTED="Returned error: Method eth_feeHistory not supported.",e.FixedRateExchange=ce,e.GASLIMIT_DEFAULT=1e6,e.KNOWN_CONFIDENTIAL_EVMS=q,e.Logger=O,e.LoggerInstance=B,e.MAX_UINT_256="115792089237316195423570985008687907853269984665640564039457584007913129639934",e.Nft=ke,e.NftFactory=we,e.OCEAN_P2P_PROTOCOL=uT,e.PROTOCOL_COMMANDS=E,e.Provider=yT,e.ProviderInstance=bT,e.Router=pe,e.SmartContract=ie,e.SmartContractWithAddress=se,e.ZERO_ADDRESS=de,e.allowance=xT,e.allowanceWei=PT,e.amountToUnits=K,e.approve=AT,e.approveWei=ST,e.balance=function(e,t,r,i){try{var s=new n.ethers.Contract(t,V,e);return Promise.resolve(s.balanceOf(r)).then(function(n){return Promise.resolve(H(e,t,n,i))})}catch(e){return Promise.reject(e)}},e.bytesToHex=Au,e.calculateActiveTemplateIndex=Se,e.concatUint8Arrays=Cu,e.configHelperNetworks=j,e.createAccessListFactory=function(e,t,r){try{var i=new n.ethers.Contract(e,_e,t);return Promise.resolve(t.getAddress()).then(function(e){var t,n=DT(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=re(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)}},e.createAsset=function(e,t,r,i,s,a,u,d,c,l,p,h,f,m,y){void 0===u&&(u=!0);try{var b,g,v=this,w=o.DDOManager.getDDOClass(a),E=w.getAssetFields().indexedMetadata,P=(null==(b=w.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),x=w.getDDOFields(),S=x.chainId,A=x.nftAddress,C=w.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(o){var b=o.chainId;if(S&&S!==Number(b))throw new Error("Chain ID from DDO is different than the configured network.");var g=(new z).getConfig(parseInt(String(b)));return Promise.resolve(Se(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 o=new ke(r,Number(b)),E=new we(g.nftFactoryAddress,r,Number(b));return Promise.resolve(r.getAddress()).then(function(x){var k;function I(e){return k?e:Promise.resolve(D.wait()).then(function(e){var t;function i(e){if(t)return e;function i(){function e(){var e=o.setMetadata,u=A;return Promise.resolve(r.getAddress()).then(function(r){return Promise.resolve(e.call(o,u,r,0,d,"",n.toBeHex(s),t,i)).then(function(){return a.id})})}C[0].datatokenAddress=h,C[0].serviceEndpoint=d;var t,i,s,c=w.makeDid(A=p,S.toString());a=w.updateFields({id:c,nftAddress:A});var f=function(){if(u)return Promise.resolve(bT.encrypt(a,Number(b),d,r,null)).then(function(e){return t=e,Promise.resolve(l.validate(a,r,d)).then(function(e){i=e.hash,s=2})});var e=JSON.stringify(a);t=n.hexlify(n.toUtf8Bytes(e)),i="0x"+T.default(t).toString(),s=0}();return f&&f.then?f.then(e):e()}var s=function(){if("oasis"!==g.sdk)return Promise.resolve(bT.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=re(e,"NFTCreated"),c=re(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 n.ethers.Contract(h,De,r);return DT(function(){return Promise.resolve(e.setFilesObject(n.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),t=1,null})}}();return f&&f.then?f.then(i):i(f)})}var D,M={name:e,symbol:t,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:x},F={templateIndex:s,cap:"100000",feeAmount:"0",paymentCollector:x,feeToken:c||g.oceanTokenAddress,minter:x,mpFeeAddress:de},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 _=DT(function(){var e=function(){if(!P)return Promise.resolve(E.createNftWithDatatoken(M,F)).then(function(e){D=e});var e=function(){if("0"===P.toString())return Promise.resolve(E.createNftWithDatatokenWithDispenser(M,F,{dispenserAddress:g.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:de})).then(function(e){D=e});var e=m||g.oceanTokenAddress;return Promise.resolve(W(v.signer,e)).then(function(t){y||(y=t);var n={fixedRateAddress:g.fixedRateExchangeAddress,baseTokenAddress:e,owner:x,marketFeeCollector:x,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:P.toString(),marketFee:"0",allowedConsumer:x,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)}},e.decimals=function(e,t){try{var r=new n.ethers.Contract(t,V,e);return Promise.resolve(r.decimals()).then(Number)}catch(e){return Promise.reject(e)}},e.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)}},e.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()},e.generateDid=function(e,t){return e=n.getAddress(e),"did:op:"+T.default(e+t.toString(10)).toString()},e.generateDtName=be,e.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=CT[n])?void 0:r[i])||"Provider request failed: "+i}var s=t[n];return t[Object.keys(t)[1]]+" : "+s}catch(t){return B.error("[getErrorMessage] error: ",t),e}},e.getEventFromTx=re,e.getFairGasPrice=Q,e.getHash=function(e){return T.default(e).toString()},e.getNodeEndpointConfig=$,e.getOceanArtifactsAddresses=Ae,e.getOceanArtifactsAddressesByChainId=Ce,e.getTokenDecimals=W,e.isDefined=function(e){return null!=e},e.isP2pUri=mT,e.minAbi=V,e.orderAsset=function(e,t,n,r,i,s,a,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=o.DDOManager.getDDOClass(e),f=h.getAssetFields().datatokens,m=h.getDDOFields(),y=m.chainId,b=m.services;return a||(a={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"}),Promise.resolve(t.provider.getNetwork()).then(function(o){if(y!==Number(o.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(!b[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(o){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(bT,x,P,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:a};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 IT,l=kT.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 kT(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());kT(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)}kT(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 a=function(){if(2===o||4===o)return Promise.resolve(r.buyFromDispenserAndOrder(b[l].datatokenAddress,u,n.dispenserAddress)).then(function(e){return t=1,e})}();return a&&a.then?a.then(i):i(a)},i=function(){if(1===o){var e=new oe(n.dispenserAddress,t),i=e.dispense,a=f[c].address;return Promise.resolve(t.getAddress()).then(function(t){return Promise.resolve(i.call(e,a,"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 ce(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",a.consumeMarketFeeAmount)).then(function(l){var p;function h(e){var i;if(p)return e;function a(e){if(i)return e}var d=function(){if(2===o||4===o)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(AT(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,b)).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(a):a(d)}var m=new g.default(+l.baseTokenAmount||0).add(new g.default(a.consumeMarketFeeAmount||0)).add(new g.default(+y.publishMarketFeeAmount||0)).toString(),b={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===o)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(AT(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!==de&&v.providerFeeAmount&&parseInt(v.providerFeeAmount)>0)return function(e,r){try{var i=Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(ST(t,n,e,v.providerFeeToken,b[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||bT.initialize,P=u||b[l].id,x=u||e.id;return u?v(w(u)):Promise.resolve(t.getAddress()).then(v)})})})})})}catch(e){return Promise.reject(e)}},e.sendTx=G,e.setContractDefaults=ne,e.signHash=function(e,t){try{var r=n.getBytes(t);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)}},e.signRequest=ze,e.sleep=$e,e.transfer=function(e,t,r,i,s,a,o){try{var u=new n.ethers.Contract(r,V,e);return Promise.resolve(K(e,r,s,a)).then(function(n){return Promise.resolve(u.transfer.estimateGas(i,n)).then(function(r){return o?r:Promise.resolve(G(r,e,null==t?void 0:t.gasFeeMultiplier,u.transfer,i,n))})})}catch(e){return Promise.reject(e)}},e.unitsToAmount=H,e.useOasisSDK=function(e){var t=(new z).getConfig(e);return t&&"oasis"===t.sdk}});
|
|
5
5
|
//# sourceMappingURL=lib.umd.js.map
|