@oceanprotocol/lib 8.5.0 → 8.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import e from"fs";import{ethers as t,parseUnits as n,formatUnits as r,EventLog as i,toUtf8Bytes as s,keccak256 as o,hexlify as a,toUtf8String as u,getAddress as d,parseEther as c,getBytes as l,toBeHex as p}from"ethers";import*as h from"@oasisprotocol/sapphire-paratime";import f from"bignumber.js";import m from"decimal.js";import y from"cross-fetch";import{DDOManager as b}from"@oceanprotocol/ddo-js";import g from"jsonwebtoken";import{PublicKey as v,encrypt as w}from"eciesjs";import T from"crypto-js/sha256.js";var P,x;!function(e){e.URL="url",e.IPFS="ipfs",e.ARWEAVE="arweave",e.S3="s3",e.FTP="ftp"}(P||(P={})),function(e){e.AES="AES",e.ECIES="ECIES"}(x||(x={}));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_UPDATE_BUCKET:"persistentStorageUpdateBucket",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"},S=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};function A(e,t){this.v=e,this.k=t}function k(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 C(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 I(t.call(e));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function I(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 I=function(e){this.s=e,this.n=e.next},I.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 I(e)}function D(e){return new A(e,0)}function M(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 k(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)?k(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 F(){return F=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},F.apply(null,arguments)}function R(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,_(e,t)}function L(){L=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:{},o=s.iterator||"@@iterator",a=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),o=new D(r||[]);return i(s,"_invoke",{value:A(e,n,o)}),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,o,function(){return this});var T=Object.getPrototypeOf,P=T&&T(T(M([])));P&&P!==n&&r.call(P,o)&&(w=P);var x=v.prototype=b.prototype=Object.create(w);function E(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,o,a){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,o,a)},function(e){n("throw",e,o,a)}):t.resolve(c).then(function(e){d.value=e,o(d)},function(e){return n("throw",e,o,a)})}a(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,o){if(i===f)throw Error("Generator is already running");if(i===m){if("throw"===s)throw o;return{value:e,done:!0}}for(r.method=s,r.arg=o;;){var a=r.delegate;if(a){var u=k(a,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 k(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,k(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 o=s.arg;return o?o.done?(n[t.resultName]=o.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,y):o:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,y)}function C(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(C,this),this.reset(!0)}function M(t){if(t||""===t){var n=t[o];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function n(){for(;++i<t.length;)if(r.call(t,i))return n.value=t[i],n.done=!1,n;return n.value=e,n.done=!0,n};return s.next=s}}throw new TypeError(typeof t+" is not iterable")}return g.prototype=v,i(x,"constructor",{value:v,configurable:!0}),i(v,"constructor",{value:g,configurable:!0}),g.displayName=d(v,u,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===g||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,v):(e.__proto__=v,d(e,u,"GeneratorFunction")),e.prototype=Object.create(x),e},t.awrap=function(e){return{__await:e}},E(S.prototype),d(S.prototype,a,function(){return this}),t.AsyncIterator=S,t.async=function(e,n,r,i,s){void 0===s&&(s=Promise);var o=new S(c(e,n,r,i),s);return t.isGeneratorFunction(n)?o:o.next().then(function(e){return e.done?e.value:o.next()})},E(x),d(x,u,"Generator"),d(x,o,function(){return this}),d(x,"toString",function(){return"[object Generator]"}),t.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=M,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 a.type="throw",a.arg=t,n.next=r,i&&(n.method="next",n.arg=e),!!i}for(var s=this.tryEntries.length-1;s>=0;--s){var o=this.tryEntries[s],a=o.completion;if("root"===o.tryLoc)return i("end");if(o.tryLoc<=this.prev){var u=r.call(o,"catchLoc"),d=r.call(o,"finallyLoc");if(u&&d){if(this.prev<o.catchLoc)return i(o.catchLoc,!0);if(this.prev<o.finallyLoc)return i(o.finallyLoc)}else if(u){if(this.prev<o.catchLoc)return i(o.catchLoc,!0)}else{if(!d)throw Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return i(o.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 o=s?s.completion:{};return o.type=e,o.arg=t,s?(this.method="next",this.next=s.finallyLoc,y):this.complete(o)},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:M(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),y}},t}function _(e,t){return _=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_(e,t)}function N(e){return function(){return new O(e.apply(this,arguments))}}function O(e){var t,n;function r(t,n){try{var s=e[t](n),o=s.value,a=o instanceof A;Promise.resolve(a?o.v:o).then(function(n){if(a){var u="return"===t?"return":"next";if(!o.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,o){var a={key:e,arg:i,resolve:s,reject:o,next:null};n?n=n.next=a:(t=n=a,r(e,i))})},"function"!=typeof e.return&&(this.return=void 0)}O.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},O.prototype.next=function(e){return this._invoke("next",e)},O.prototype.throw=function(e){return this._invoke("throw",e)},O.prototype.return=function(e){return this._invoke("return",e)};var B,U={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:"0x92b368055425f34c18e6f7A80DEaB7Ff106C9d05",COMPYFaucet:"0xC56663D0c3f535211E5bb238Eb8E80e184A4bA11",COMPYSwap:"0x7DBDcF3579831ed30666817D53DA7f6D5bC9861F"},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",EnterpriseFeeCollector:"0x43eC0a34E1b70C7f8E579ab866F37642777727E7",FixedPriceEnterprise:"0x6976320eC365202118B4B0B0906E13DDf21633A5",EnterpriseEscrow:"0x5494711392a67DA50D3bC7b1fcC2d1877cFaA4d2"},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:"0x5494711392a67DA50D3bC7b1fcC2d1877cFaA4d2",COMPYFaucet:"0x8c98ea273bA22327F896Aa1a1a46E1BFf56e9b1D",COMPYSwap:"0x8daC419D5D81Af8c8E795D0D73f64d5220e28cd8"}};!function(e){e[e.None=-1]="None",e[e.Error=0]="Error",e[e.Warn=1]="Warn",e[e.Log=2]="Log",e[e.Verbose=3]="Verbose"}(B||(B={}));var j=/*#__PURE__*/function(){function e(e){this.logLevel=void 0,this.logLevel=e,this.logLevel=e||B.Error}var t=e.prototype;return t.setLevel=function(e){this.logLevel=e},t.bypass=function(){this.dispatch.apply(this,["log",-Infinity].concat([].slice.call(arguments)))},t.debug=function(){this.dispatch.apply(this,["debug",B.Verbose].concat([].slice.call(arguments)))},t.log=function(){this.dispatch.apply(this,["log",B.Log].concat([].slice.call(arguments)))},t.warn=function(){this.dispatch.apply(this,["warn",B.Warn].concat([].slice.call(arguments)))},t.error=function(){this.dispatch.apply(this,["error",B.Error].concat([].slice.call(arguments)))},t.dispatch=function(e,t){var n;this.logLevel>=t&&(n=console)[e].apply(n,[].slice.call(arguments,2))},e}(),q=new j,$={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},z=[F({},$),F({},$,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),F({},$,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),F({},$,{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"}),F({},$,{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"}),F({},$,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),F({},$,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),F({},$,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),F({},$,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),F({},$,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),F({},$,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),F({},$,{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"}),F({},$,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),F({},$,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),F({},$,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),F({},$,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),F({},$,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],V=[23294,23295],G=function(){return process.env.NODE_ENDPOINT||process.env.NODE_URL?{oceanNodeUri:process.env.NODE_ENDPOINT||process.env.NODE_URL}:{}},K=/*#__PURE__*/function(){function t(){}var n=t.prototype;return n.getAddressesFromEnv=function(e,t){var n;if(t&&t[e]){var r=t[e];n=F({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},G())}else if(U[e]){var i=U[e];n=F({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},G())}return n},n.getConfig=function(t,n){var r="string"==typeof t?"network":"chainId",i=z.find(function(e){return e[r]===t});if(!i)return q.error("No config found for given network '"+t+"'"),null;var s=null;try{"undefined"==typeof window&&process.env.ADDRESS_FILE&&(s=JSON.parse(e.readFileSync(process.env.ADDRESS_FILE,"utf8")))}catch(e){console.log(e),s=null}var o=this.getAddressesFromEnv(i.network,s);return!o&&V.includes(i.chainId)&&(o=this.getAddressesFromEnv(i.network.replace("sapph","saph"),s)),"sdk"in i&&null!==i.sdk||(i.sdk=V.includes(i.chainId)?"oasis":"evm"),o&&"accessListFactory"in o&&(i.accessListFactory=o.accessListFactory),i=F({},i,o),F({},i,{nodeUri:n?i.nodeUri+"/"+n:i.nodeUri})},t}(),W=[{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"}],H={_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:{}},Q=[{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"}],Y=[{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"}],J=[{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"}],Z=[{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"}],X=[{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"}];function ee(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var te=function(e,t){try{return Promise.resolve(ee(function(){return Promise.resolve(e.sendTransaction(t)).then(function(e){return Promise.resolve(e.wait()).then(function(){return e})})},function(e){return q.error("Send prepared tx error: ",e),null}))}catch(e){return Promise.reject(e)}},ne=function(e,t,n){try{return Promise.resolve(ee(function(){return Promise.resolve(e.apply(void 0,t.concat([n]))).then(function(e){return Promise.resolve(e.wait()).then(function(){return e})})},function(e){return q.error("Send tx error: ",e),null}))}catch(e){return Promise.reject(e)}},re=function(e,t,n){try{return Promise.resolve(e.populateTransaction.apply(e,t.concat([n])))}catch(e){return Promise.reject(e)}},ie=function(e,t,n){try{return Promise.resolve(t.provider.getNetwork()).then(function(r){var i=r.chainId;return Promise.resolve(t.provider.getFeeData()).then(function(t){var r={};if(t.maxPriorityFeePerGas){var s=t.maxPriorityFeePerGas.toString(),o=t.maxFeePerGas.toString();n>1&&(s=Math.round(Number(t.maxPriorityFeePerGas)*n).toString(),o=Math.round(Number(t.maxFeePerGas)*n).toString()),r={maxPriorityFeePerGas:(Number(i)===fe||Number(i)===he)&&Number(s)<ce?ce:Number(i)===me&&Number(s)<le?le:V.includes(Number(i))&&Number(s)<pe?pe:Number(s),maxFeePerGas:(Number(i)===fe||Number(i)===he)&&Number(o)<ce?ce:Number(i)===me&&Number(o)<le?le:V.includes(Number(i))&&Number(o)<pe?pe:Number(o)}}else r={gasPrice:t.gasPrice};return r.gasLimit=BigInt(new f(e).plus(20000n).toString()),r})})}catch(e){return Promise.reject(e)}},se=function(e,t,n,r){try{var i=arguments;return Promise.resolve(ie(e,t,n)).then(function(e){return ne(r,[].slice.call(i,4),e)})}catch(e){return Promise.reject(e)}},oe=function(e,t,r,i){try{var s=function(e){return"0"===e&&(e=18),n(r,e).toString()};return Promise.resolve(i?s(i):Promise.resolve(ue(e,t)).then(s))}catch(e){return Promise.reject(e)}},ae=function(e,t,n,i){try{var s=function(e){return"0"===e&&(e=18),r(n,e).toString()};return Promise.resolve(i?s(i):Promise.resolve(ue(e,t)).then(s))}catch(e){return Promise.reject(e)}},ue=function(e,n){try{var r=new t.Contract(n,X,e);return Promise.resolve(r.decimals())}catch(e){return Promise.reject(e)}},de=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)}},ce=3e10,le=4e9,pe=1e10,he=137,fe=80001,me=11155111,ye=[new t.Interface(W),new t.Interface(H.abi),new t.Interface(Q),new t.Interface(Y),new t.Interface(J),new t.Interface(Z)];function be(e,t){return e}function ge(e,n){if(e&&e.logs){var r=e.logs.filter(function(e){var r;if(!(e instanceof i)||e.eventName!==n)return!1;var s=null==(r=e.topics)||null==(r=r[0])?void 0:r.toLowerCase();return!s||!e.eventSignature||s===t.id(e.eventSignature).toLowerCase()})[0];if(r)return r;for(var s,o=M(e.logs);!(s=o()).done;)for(var a,u=s.value,d=M(ye);!(a=d()).done;){var c=a.value;try{var l=c.parseLog(u);if(!l||l.name!==n)continue;return{event:l.name,eventName:l.name,args:l.args,transactionHash:u.transactionHash,blockHash:u.blockHash,blockNumber:u.blockNumber,address:u.address,logIndex:u.index,topics:u.topics,data:u.data}}catch(e){}}}}var ve=/*#__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 K).getConfig(t),this.abi=r||this.getDefaultAbi()}var n=e.prototype;return n.getSignerAccordingSdk=function(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?h.wrap(this.signer):this.signer},n.amountToUnits=function(e,t,n){try{return Promise.resolve(oe(this.signer,e,t,n))}catch(e){return Promise.reject(e)}},n.unitsToAmount=function(e,t,n){try{return Promise.resolve(ae(this.signer,e,t,n))}catch(e){return Promise.reject(e)}},n.getFairGasPrice=function(){try{var e;return Promise.resolve(de(this.signer,null==(e=this.config)?void 0:e.gasFeeMultiplier))}catch(e){return Promise.reject(e)}},n.getContract=function(e,n){if(!e)throw new Error("Contract address is required but not provided");return be(new t.Contract(e,new t.Interface(JSON.stringify(n||this.abi)),this.signer))},e}(),we=/*#__PURE__*/function(e){function t(t,n,r,i,s){var o;return(o=e.call(this,n,r,i,s)||this).address=void 0,o.contract=void 0,o.address=t,o.contract=o.getContract(o.address),o}return R(t,e),t}(ve),Te=[{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"}],Pe=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Te},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(o){return Promise.resolve(t.unitsToAmount(null,e.balance,18)).then(function(t){return{active:i,owner:r,isMinter:n,maxTokens:s,maxBalance:o,balance:t,allowedSwapper:e.allowedSwapper}})})})})}catch(e){return Promise.reject(e)}},n.create=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.createTx(e,t,n,r,i)).then(function(e){return s?e.gasLimit:Promise.resolve(te(o.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.createTx=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.amountToUnits(null,n,18)).then(function(n){return Promise.resolve(s.amountToUnits(null,r,18)).then(function(r){return Promise.resolve(s.contract.create.estimateGas(e,n,r,t,i)).then(function(o){var a;return Promise.resolve(ie(o,s.getSignerAccordingSdk(),null==(a=s.config)?void 0:a.gasFeeMultiplier)).then(function(o){return re(s.contract.create,[e,n,r,t,i],o)})})})})}catch(e){return Promise.reject(e)}},n.activate=function(e,t,n,r){try{var i=this;return Promise.resolve(i.activateTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.activateTx=function(e,t,n){try{var r=this;return Promise.resolve(r.amountToUnits(null,t,18)).then(function(t){return Promise.resolve(r.amountToUnits(null,n,18)).then(function(n){return Promise.resolve(r.contract.activate.estimateGas(e,t,n)).then(function(i){var s;return Promise.resolve(ie(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier)).then(function(i){return re(r.contract.activate,[e,t,n],i)})})})})}catch(e){return Promise.reject(e)}},n.deactivate=function(e,t){try{var n=this;return Promise.resolve(n.deactivateTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.deactivateTx=function(e){try{var t=this;return Promise.resolve(t.contract.deactivate.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.deactivate,[e],n)})})}catch(e){return Promise.reject(e)}},n.setAllowedSwapper=function(e,t,n){try{var r=this;return Promise.resolve(r.setAllowedSwapperTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setAllowedSwapperTx=function(e,t){try{var n=this;return Promise.resolve(n.contract.setAllowedSwapper.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.setAllowedSwapper,[e,t],r)})})}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.dispenseTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.dispenseTx=function(e,t,n){void 0===t&&(t="1");try{var r=this;return Promise.resolve(r.amountToUnits(null,t,18)).then(function(t){return Promise.resolve(r.contract.dispense.estimateGas(e,t,n)).then(function(i){var s;return Promise.resolve(ie(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier)).then(function(i){return re(r.contract.dispense,[e,t,n],i)})})})}catch(e){return Promise.reject(e)}},n.ownerWithdraw=function(e,t){try{var n=this;return Promise.resolve(n.ownerWithdrawTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.ownerWithdrawTx=function(e){try{var t=this;return Promise.resolve(t.contract.ownerWithdraw.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.ownerWithdraw,[e],n)})})}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 m(e).greaterThanOrEqualTo(i.maxBalance)||new m(String(r)).greaterThan(i.maxTokens)||!new m(i.balance).greaterThanOrEqualTo(r)&&!0!==i.isMinter)})})}catch(e){return Promise.reject(e)}},t}(we),xe="0x0000000000000000000000000000000000000000",Ee=1e6,Se="115792089237316195423570985008687907853269984665640564039457584007913129639934",Ae="Returned error: Method eth_feeHistory not supported.",ke=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return J},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=xe),void 0===i&&(i="0");try{var o=this;return Promise.resolve(o.buyDatatokensTx(e,t,n,r,i)).then(function(e){return s?e.gasLimit:Promise.resolve(te(o.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.buyDatatokensTx=function(e,t,n,r,i){void 0===r&&(r=xe),void 0===i&&(i="0");try{var s=this;return Promise.resolve(s.getExchange(e)).then(function(o){return Promise.resolve(s.amountToUnits(null,i,18)).then(function(i){return Promise.resolve(s.amountToUnits(o.datatoken,t,Number(o.dtDecimals))).then(function(t){return Promise.resolve(s.amountToUnits(o.baseToken,n,Number(o.btDecimals))).then(function(n){return Promise.resolve(s.contract.buyDT.estimateGas(e,t,n,r,i)).then(function(o){var a;return Promise.resolve(ie(o,s.getSignerAccordingSdk(),null==(a=s.config)?void 0:a.gasFeeMultiplier)).then(function(o){return re(s.contract.buyDT,[e,t,n,r,i],o)})})})})})})}catch(e){return Promise.reject(e)}},n.sellDatatokens=function(e,t,n,r,i,s){void 0===r&&(r=xe),void 0===i&&(i="0");try{var o=this;return Promise.resolve(o.sellDatatokensTx(e,t,n,r,i)).then(function(e){return s?e.gasLimit:Promise.resolve(te(o.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.sellDatatokensTx=function(e,t,n,r,i){void 0===r&&(r=xe),void 0===i&&(i="0");try{var s=this;return Promise.resolve(s.getExchange(e)).then(function(o){return Promise.resolve(s.amountToUnits(null,i,18)).then(function(i){return Promise.resolve(s.amountToUnits(o.datatoken,t,Number(o.dtDecimals))).then(function(t){return Promise.resolve(s.amountToUnits(o.baseToken,n,Number(o.btDecimals))).then(function(n){return Promise.resolve(s.contract.sellDT.estimateGas(e,t,n,r,i)).then(function(o){var a;return Promise.resolve(ie(o,s.getSignerAccordingSdk(),null==(a=s.config)?void 0:a.gasFeeMultiplier)).then(function(o){return re(s.contract.sellDT,[e,t,n,r,i],o)})})})})})})}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;return Promise.resolve(r.setRateTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setRateTx=function(e,t){try{var n=this;return Promise.resolve(n.amountToUnits(null,t,18)).then(function(t){return Promise.resolve(n.contract.setRate.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.setRate,[e,t],r)})})})}catch(e){return Promise.reject(e)}},n.setAllowedSwapper=function(e,t,n){try{var r=this;return Promise.resolve(r.setAllowedSwapperTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setAllowedSwapperTx=function(e,t){try{var n=this;return Promise.resolve(n.contract.setAllowedSwapper.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.setAllowedSwapper,[e,t],r)})})}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.activateTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))}):null})}catch(e){return Promise.reject(e)}},n.activateTx=function(e){try{var t=this;return Promise.resolve(t.getExchange(e)).then(function(n){if(!n)throw new Error("Exchange not found");if(!0===n.active)throw new Error("Exchange already active");return Promise.resolve(t.contract.toggleExchangeState.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.toggleExchangeState,[e],n)})})})}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.deactivateTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))}):null})}catch(e){return Promise.reject(e)}},n.deactivateTx=function(e){try{var t=this;return Promise.resolve(t.getExchange(e)).then(function(n){if(!n)throw new Error("Exchange not found");if(!1===n.active)throw new Error("Exchange already inactive");return Promise.resolve(t.contract.toggleExchangeState.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.toggleExchangeState,[e],n)})})})}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,o=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(o.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,o=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(o.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,o=n.exchangeOwner,a=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:a,exchangeOwner:o,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 o=n.marketFeeCollector;return Promise.resolve(t.unitsToAmount(r.baseToken,n.marketFeeAvailable,Number(r.btDecimals))).then(function(a){return Promise.resolve(t.unitsToAmount(r.baseToken,n.oceanFeeAvailable,Number(r.btDecimals))).then(function(t){return{opcFee:i,marketFee:s,marketFeeCollector:o,marketFeeAvailable:a,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.activateMintTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))}):null})}catch(e){return Promise.reject(e)}},n.activateMintTx=function(e){try{var t=this;return Promise.resolve(t.getExchange(e)).then(function(n){if(!n)throw new Error("Exchange not found");if(!0===n.withMint)throw new Error("Mint already active");return Promise.resolve(t.contract.toggleMintState.estimateGas(e,!0)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.toggleMintState,[e,!0],n)})})})}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.deactivateMintTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))}):null})}catch(e){return Promise.reject(e)}},n.deactivateMintTx=function(e){try{var t=this;return Promise.resolve(t.getExchange(e)).then(function(n){if(!n)throw new Error("Exchange not found");if(!1===n.withMint)throw new Error("Mint already inactive");return Promise.resolve(t.contract.toggleMintState.estimateGas(e,!1)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.toggleMintState,[e,!1],n)})})})}catch(e){return Promise.reject(e)}},n.collectBasetokens=function(e,t,n){try{var r=this;return Promise.resolve(r.collectBasetokensTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.collectBasetokensTx=function(e,t){try{var n=this;return Promise.resolve(n.getExchange(e)).then(function(r){if(!r)throw new Error("Exchange not found");return Promise.resolve(n.contract.getExchange(e)).then(function(r){return Promise.resolve(n.amountToUnits(r.baseToken,t,Number(r.btDecimals))).then(function(t){return Promise.resolve(n.contract.collectBT.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.collectBT,[e,t],r)})})})})})}catch(e){return Promise.reject(e)}},n.collectDatatokens=function(e,t,n){try{var r=this;return Promise.resolve(r.collectDatatokensTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.collectDatatokensTx=function(e,t){try{var n=this;return Promise.resolve(n.getExchange(e)).then(function(r){if(!r)throw new Error("Exchange not found");return Promise.resolve(n.contract.getExchange(e)).then(function(r){return Promise.resolve(n.amountToUnits(r.datatoken,t,Number(r.dtDecimals))).then(function(t){return Promise.resolve(n.contract.collectDT.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.collectDT,[e,t],r)})})})})})}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.collectMarketFeeTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))}):null})}catch(e){return Promise.reject(e)}},n.collectMarketFeeTx=function(e){try{var t=this;return Promise.resolve(t.contract.collectMarketFee.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.collectMarketFee,[e],n)})})}catch(e){return Promise.reject(e)}},n.collectOceanFee=function(e,t){try{var n=this;return Promise.resolve(n.collectOceanFeeTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.collectOceanFeeTx=function(e){try{var t=this;return Promise.resolve(t.getExchange(e)).then(function(n){if(!n)throw new Error("Exchange not found");return Promise.resolve(t.contract.collectOceanFee.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.collectOceanFee,[e],n)})})})}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;return Promise.resolve(r.updateMarketFeeTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.updateMarketFeeTx=function(e,t){try{var n=this;return Promise.resolve(n.amountToUnits(null,t,18)).then(function(t){return Promise.resolve(n.contract.updateMarketFee.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.updateMarketFee,[e,t],r)})})})}catch(e){return Promise.reject(e)}},n.updateMarketFeeCollector=function(e,t,n){try{var r=this;return Promise.resolve(r.updateMarketFeeCollectorTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.updateMarketFeeCollectorTx=function(e,t){try{var n=this;return Promise.resolve(n.contract.updateMarketFeeCollector.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.updateMarketFeeCollector,[e,t],r)})})}catch(e){return Promise.reject(e)}},t}(we),Ce=[{inputs:[{internalType:"address",name:"_routerOwner",type:"address"},{internalType:"address",name:"_oceanToken",type:"address"},{internalType:"address",name:"_bpoolTemplate",type:"address"},{internalType:"address",name:"_opcCollector",type:"address"},{internalType:"address[]",name:"_preCreatedPools",type:"address[]"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newBPoolAddress",type:"address"},{indexed:!0,internalType:"address",name:"registeredBy",type:"address"},{indexed:!0,internalType:"address",name:"datatokenAddress",type:"address"},{indexed:!1,internalType:"address",name:"baseTokenAddress",type:"address"},{indexed:!1,internalType:"address",name:"bpoolTemplateAddress",type:"address"},{indexed:!1,internalType:"address",name:"ssAddress",type:"address"}],name:"BPoolCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"DispenserContractAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"DispenserContractRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"FactoryContractChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"FixedRateContractAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"FixedRateContractRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"instance",type:"address"}],name:"InstanceDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"poolAddress",type:"address"},{indexed:!1,internalType:"bool",name:"isOcean",type:"bool"}],name:"NewPool",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"_newOpcCollector",type:"address"}],name:"OPCCollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint256",name:"newSwapOceanFee",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newSwapNonOceanFee",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newConsumeFee",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newProviderFee",type:"uint256"}],name:"OPCFeeChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"PoolTemplateAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"PoolTemplateRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"newRouter",type:"address"}],name:"RouterChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"SSContractAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"contractAddress",type:"address"}],name:"SSContractRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"}],name:"TokenAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"}],name:"TokenRemoved",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"caller",type:"address"},{indexed:!1,internalType:"uint256",name:"minVestingPeriodInBlocks",type:"uint256"}],name:"VestingPeriodChanges",type:"event"},{inputs:[],name:"BONE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"BPOW_PRECISION",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"EXIT_FEE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"INIT_POOL_SUPPLY",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_BOUND_TOKENS",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_BPOW_BASE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_FEE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_IN_RATIO",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_OUT_RATIO",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_TOTAL_WEIGHT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MAX_WEIGHT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_BALANCE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_BOUND_TOKENS",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_BPOW_BASE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_FEE",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MIN_WEIGHT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"addApprovedToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"}],name:"addDispenserContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_factory",type:"address"}],name:"addFactory",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_fixedRate",type:"address"}],name:"addFixedRateContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"poolTemplate",type:"address"}],name:"addPoolTemplate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_ssContract",type:"address"}],name:"addSSContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"approvedTokens",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"bytes32",name:"exchangeIds",type:"bytes32"},{internalType:"address",name:"source",type:"address"},{internalType:"enum IFactoryRouter.operationType",name:"operation",type:"uint8"},{internalType:"address",name:"tokenIn",type:"address"},{internalType:"uint256",name:"amountsIn",type:"uint256"},{internalType:"address",name:"tokenOut",type:"address"},{internalType:"uint256",name:"amountsOut",type:"uint256"},{internalType:"uint256",name:"maxPrice",type:"uint256"},{internalType:"uint256",name:"swapMarketFee",type:"uint256"},{internalType:"address",name:"marketFeeAddress",type:"address"}],internalType:"struct IFactoryRouter.Operations[]",name:"_operations",type:"tuple[]"}],name:"buyDTBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_routerOwner",type:"address"}],name:"changeRouterOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"consumeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"},{internalType:"address",name:"datatoken",type:"address"},{internalType:"uint256",name:"maxTokens",type:"uint256"},{internalType:"uint256",name:"maxBalance",type:"uint256"},{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"allowedSwapper",type:"address"}],name:"deployDispenser",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"fixedPriceAddress",type:"address"},{internalType:"address[]",name:"addresses",type:"address[]"},{internalType:"uint256[]",name:"uints",type:"uint256[]"}],name:"deployFixedRate",outputs:[{internalType:"bytes32",name:"exchangeId",type:"bytes32"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address[2]",name:"tokens",type:"address[2]"},{internalType:"uint256[]",name:"ssParams",type:"uint256[]"},{internalType:"uint256[]",name:"swapFees",type:"uint256[]"},{internalType:"address[]",name:"addresses",type:"address[]"}],name:"deployPool",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"dispensers",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"fixedRate",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"fixedrates",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getApprovedTokens",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getDispensersContracts",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFixedRatesContracts",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getMinVestingPeriod",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getOPCCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getOPCConsumeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"baseToken",type:"address"}],name:"getOPCFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getOPCFees",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getOPCProviderFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getPoolTemplates",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getSSContracts",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"isApprovedToken",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"}],name:"isDispenserContract",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_fixedRate",type:"address"}],name:"isFixedRateContract",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"poolTemplate",type:"address"}],name:"isPoolTemplate",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_ssContract",type:"address"}],name:"isSSContract",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"minVestingPeriodInBlocks",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"opcCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"poolTemplates",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"providerFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"tokenAddress",type:"address"}],name:"removeApprovedToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_dispenser",type:"address"}],name:"removeDispenserContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_fixedRate",type:"address"}],name:"removeFixedRateContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"poolTemplate",type:"address"}],name:"removePoolTemplate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_ssContract",type:"address"}],name:"removeSSContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"routerOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"ssContracts",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"address",name:"poolAddress",type:"address"},{internalType:"uint256",name:"tokenAmountIn",type:"uint256"},{internalType:"uint256",name:"minPoolAmountOut",type:"uint256"}],internalType:"struct IFactoryRouter.Stakes[]",name:"_stakes",type:"tuple[]"}],name:"stakeBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"swapNonOceanFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"swapOceanFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_newPeriod",type:"uint256"}],name:"updateMinVestingPeriod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_opcCollector",type:"address"}],name:"updateOPCCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_newSwapOceanFee",type:"uint256"},{internalType:"uint256",name:"_newSwapNonOceanFee",type:"uint256"},{internalType:"uint256",name:"_newConsumeFee",type:"uint256"},{internalType:"uint256",name:"_newProviderFee",type:"uint256"}],name:"updateOPCFee",outputs:[],stateMutability:"nonpayable",type:"function"}],Ie=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Ce},n.buyDatatokenBatch=function(e,t){try{var n=this;return Promise.resolve(n.buyDatatokenBatchTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.buyDatatokenBatchTx=function(e){try{var t=this;return Promise.resolve(t.contract.buyDTBatch.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.buyDTBatch,[e],n)})})}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.addApprovedTokenTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addApprovedTokenTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(n.contract.addApprovedToken.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.addApprovedToken,[t],e)})})})}catch(e){return Promise.reject(e)}},n.removeApprovedToken=function(e,t,n){try{var r=this;return Promise.resolve(r.removeApprovedTokenTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removeApprovedTokenTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(n.contract.removeApprovedToken.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.removeApprovedToken,[t],e)})})})}catch(e){return Promise.reject(e)}},n.addFixedRateContract=function(e,t,n){try{var r=this;return Promise.resolve(r.addFixedRateContractTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addFixedRateContractTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(n.contract.addFixedRateContract.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.addFixedRateContract,[t],e)})})})}catch(e){return Promise.reject(e)}},n.removeFixedRateContract=function(e,t,n){try{var r=this;return Promise.resolve(r.removeFixedRateContractTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removeFixedRateContractTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(n.contract.removeFixedRateContract.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.removeFixedRateContract,[t],e)})})})}catch(e){return Promise.reject(e)}},n.addDispenserContract=function(e,t,n){try{var r=this;return Promise.resolve(r.addDispenserContractTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addDispenserContractTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(n.contract.addDispenserContract.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.addDispenserContract,[t],e)})})})}catch(e){return Promise.reject(e)}},n.removeDispenserContract=function(e,t,n){try{var r=this;return Promise.resolve(r.removeDispenserContractTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removeDispenserContractTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(n.contract.removeDispenserContract.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.removeDispenserContract,[t],e)})})})}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 o=this;return Promise.resolve(o.updateOPCFeeTx(e,t,n,r,i)).then(function(e){return s?e.gasLimit:Promise.resolve(te(o.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.updateOPCFeeTx=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getOwner()).then(function(o){if(o!==e)throw new Error("Caller is not Router Owner");return Promise.resolve(s.contract.updateOPCFee.estimateGas(t,n,r,i)).then(function(e){var o;return Promise.resolve(ie(e,s.getSignerAccordingSdk(),null==(o=s.config)?void 0:o.gasFeeMultiplier)).then(function(e){return re(s.contract.updateOPCFee,[t,n,r,i],e)})})})}catch(e){return Promise.reject(e)}},t}(we),De={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 Me(e){var t=e||De,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()}),o=t.nouns[r].replace(/^\w/,function(e){return e.toUpperCase()});return{name:s+" "+o+" Token",symbol:(s.substring(0,3)+o.substring(0,3)).toUpperCase()+"-"+i}}function Fe(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Re=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Y},n.createNFT=function(e,t){try{var n=this;return Promise.resolve(n.createNFTTx(e)).then(function(e){return t?e.gasLimit:Fe(function(){return Promise.resolve(te(n.getSignerAccordingSdk(),e)).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 ge(e,"NFTCreated").args[0]})})},function(e){console.error("Creation of NFT failed: "+e)})})}catch(e){return Promise.reject(e)}},n.createNFTTx=function(e){try{var t=this,n=F({},e);if(n.templateIndex||(n.templateIndex=1),!n.name||!n.symbol){var r=Me();n.name=n.name||r.name,n.symbol=n.symbol||r.symbol}var i=n.templateIndex;return Promise.resolve(t.getCurrentNFTTemplateCount()).then(function(e){if(i>e)throw new Error("Template index doesnt exist");if(0===n.templateIndex)throw new Error("Template index cannot be ZERO");return Promise.resolve(t.getNFTTemplate(n.templateIndex)).then(function(e){if(!1===e.isActive)throw new Error("Template is not active");return Promise.resolve(t.contract.deployERC721Contract.estimateGas(n.name,n.symbol,n.templateIndex,xe,xe,n.tokenURI,n.transferable,n.owner)).then(function(e){var r;return Promise.resolve(ie(e,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(t.contract.deployERC721Contract,[n.name,n.symbol,n.templateIndex,xe,xe,n.tokenURI,n.transferable,n.owner],e)})})})})}catch(e){return Promise.reject(e)}},n.getCurrentNFTCount=function(){try{return Promise.resolve(this.contract.getCurrentNFTCount()).then(Number)}catch(e){return Promise.reject(e)}},n.getCurrentTokenCount=function(){try{return Promise.resolve(this.contract.getCurrentTokenCount()).then(Number)}catch(e){return Promise.reject(e)}},n.getOwner=function(){try{return Promise.resolve(this.contract.owner())}catch(e){return Promise.reject(e)}},n.getCurrentNFTTemplateCount=function(){try{return Promise.resolve(this.contract.getCurrentNFTTemplateCount()).then(Number)}catch(e){return Promise.reject(e)}},n.getCurrentTokenTemplateCount=function(){try{return Promise.resolve(this.contract.getCurrentTemplateCount()).then(Number)}catch(e){return Promise.reject(e)}},n.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)}},n.getTokenTemplate=function(e){try{return Promise.resolve(this.contract.getTokenTemplate(e))}catch(e){return Promise.reject(e)}},n.checkDatatoken=function(e){try{return Promise.resolve(this.contract.erc20List(e))}catch(e){return Promise.reject(e)}},n.checkNFT=function(e){try{return Promise.resolve(this.contract.erc721List(e))}catch(e){return Promise.reject(e)}},n.addNFTTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.addNFTTemplateTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addNFTTemplateTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Factory Owner");if(t===xe)throw new Error("Template cannot be ZERO address");return Promise.resolve(n.contract.add721TokenTemplate.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.add721TokenTemplate,[t],e)})})})}catch(e){return Promise.reject(e)}},n.disableNFTTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.disableNFTTemplateTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.disableNFTTemplateTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Factory Owner");return Promise.resolve(n.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(n.contract.disable721TokenTemplate.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.disable721TokenTemplate,[t],e)})})})})}catch(e){return Promise.reject(e)}},n.reactivateNFTTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.reactivateNFTTemplateTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.reactivateNFTTemplateTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Factory Owner");return Promise.resolve(n.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(n.contract.reactivate721TokenTemplate.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.reactivate721TokenTemplate,[t],e)})})})})}catch(e){return Promise.reject(e)}},n.addTokenTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.addTokenTemplateTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addTokenTemplateTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Factory Owner");if(t===xe)throw new Error("Template cannot be address ZERO");return Promise.resolve(n.contract.addTokenTemplate.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.addTokenTemplate,[t],e)})})})}catch(e){return Promise.reject(e)}},n.disableTokenTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.disableTokenTemplateTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.disableTokenTemplateTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Factory Owner");return Promise.resolve(n.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(n.getTokenTemplate(t)).then(function(e){if(!1===e.isActive)throw new Error("Template is already disabled");return Promise.resolve(n.contract.disableTokenTemplate.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.disableTokenTemplate,[t],e)})})})})})}catch(e){return Promise.reject(e)}},n.reactivateTokenTemplate=function(e,t,n){try{var r=this;return Promise.resolve(r.reactivateTokenTemplateTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.reactivateTokenTemplateTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Factory Owner");return Promise.resolve(n.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(n.getTokenTemplate(t)).then(function(e){if(!0===e.isActive)throw new Error("Template is already active");return Promise.resolve(n.contract.reactivateTokenTemplate.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.reactivateTokenTemplate,[t],e)})})})})})}catch(e){return Promise.reject(e)}},n.startMultipleTokenOrder=function(e,t){try{var n=this;if(e.length>50)throw new Error("Too many orders");return Promise.resolve(n.startMultipleTokenOrderTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.startMultipleTokenOrderTx=function(e){try{var t=this;if(e.length>50)throw new Error("Too many orders");return Promise.resolve(t.contract.startMultipleTokenOrder.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.startMultipleTokenOrder,[e],n)})})}catch(e){return Promise.reject(e)}},n.createNftWithDatatoken=function(e,t,n){try{var r=this;return Promise.resolve(r.createNftWithDatatokenTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.createNftWithDatatokenTx=function(e,t){try{var n=this;return Promise.resolve(n.getErcCreationParams(t)).then(function(t){return Promise.resolve(n.contract.createNftWithErc20.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.createNftWithErc20,[e,t],r)})})})}catch(e){return Promise.reject(e)}},n.createNftWithDatatokenWithFixedRate=function(e,t,n,r){try{var i=this;return Promise.resolve(i.createNftWithDatatokenWithFixedRateTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.createNftWithDatatokenWithFixedRateTx=function(e,t,n){try{var r=this;return Promise.resolve(r.getErcCreationParams(t)).then(function(t){return Promise.resolve(r.getFreCreationParams(n)).then(function(n){return Promise.resolve(r.contract.createNftWithErc20WithFixedRate.estimateGas(e,t,n)).then(function(i){var s;return Promise.resolve(ie(i,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier)).then(function(i){return re(r.contract.createNftWithErc20WithFixedRate,[e,t,n],i)})})})})}catch(e){return Promise.reject(e)}},n.createNftWithDatatokenWithDispenser=function(e,t,n,r){try{var i=this;return Promise.resolve(i.createNftWithDatatokenWithDispenserTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.createNftWithDatatokenWithDispenserTx=function(e,t,n){try{var r=this;return Promise.resolve(r.getErcCreationParams(t)).then(function(t){return Promise.resolve(r.amountToUnits(null,n.maxBalance,18)).then(function(i){return Promise.resolve(r.amountToUnits(null,n.maxTokens,18)).then(function(s){var o=F({},n,{maxBalance:i,maxTokens:s});return Promise.resolve(r.contract.createNftWithErc20WithDispenser.estimateGas(e,t,o)).then(function(n){var i;return Promise.resolve(ie(n,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier)).then(function(n){return re(r.contract.createNftWithErc20WithDispenser,[e,t,o],n)})})})})})}catch(e){return Promise.reject(e)}},n.getErcCreationParams=function(e){try{var t,n,r=function(){var r=[e.minter,e.paymentCollector,e.mpFeeAddress,e.feeToken];e.filesObject&&(e.accessListFactory&&r.push(e.accessListFactory),e.allowAccessList&&r.push(e.allowAccessList),e.denyAccessList&&r.push(e.denyAccessList));var o=[e.name||t,e.symbol||n],u=e.templateIndex;return Promise.resolve(i.amountToUnits(null,e.cap,18)).then(function(t){return Promise.resolve(i.amountToUnits(null,e.feeAmount,a)).then(function(n){return{templateIndex:u,strings:o,addresses:r,uints:[t,n],bytess:e.filesObject?[s(JSON.stringify(e.filesObject))]:[]}})})},i=this;if(!e.name||!e.symbol){var o=Me();t=o.name,n=o.symbol}var a=18,u=function(){if(e.feeToken!==xe){var t=Fe(function(){return Promise.resolve(ue(i.signer,e.feeToken)).then(function(e){a=e})},function(e){q.error("getTokenDecimals error",e)});if(t&&t.then)return t.then(function(){})}}();return Promise.resolve(u&&u.then?u.then(r):r())}catch(e){return Promise.reject(e)}},n.getFreCreationParams=function(e){try{var t=this;e.allowedConsumer||(e.allowedConsumer=xe);var n=!1===e.withMint?0:1,r=[e.baseTokenAddress,e.owner,e.marketFeeCollector,e.allowedConsumer],i=e.fixedRateAddress,s=e.datatokenDecimals,o=e.baseTokenDecimals;return Promise.resolve(t.amountToUnits(null,e.fixedRate,e.datatokenDecimals)).then(function(a){return Promise.resolve(t.amountToUnits(null,e.marketFee,e.datatokenDecimals)).then(function(e){return{fixedPriceAddress:i,addresses:r,uints:[o,s,a,e,n]}})})}catch(e){return Promise.reject(e)}},t}(we),Le=[{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 _e(e,t,n){if(!e.s){if(n instanceof Ne){if(!n.s)return void(n.o=_e.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(_e.bind(null,e,t),_e.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var Ne=/*#__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{_e(r,1,s(this.v))}catch(e){_e(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?_e(r,1,t?t(i):i):n?_e(r,1,n(i)):_e(r,2,i)}catch(e){_e(r,2,e)}},r},e}();function Oe(e){return e instanceof Ne&&1&e.s}var Be=function(e,n,r,i){try{var s="number"==typeof r,o=new Re(n,e,i);return Promise.resolve(o.getCurrentTokenTemplateCount()).then(function(n){var i;function a(e){return i?e:-1}var u=1,d=function(e,t,n){for(var r;;){var i=e();if(Oe(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!Oe(s)){r=1;break}s=s.s}if(t){var o=t();if(o&&o.then&&!Oe(o)){r=2;break}}}var a=new Ne,u=_e.bind(null,a,2);return(0===r?i.then(c):1===r?s.then(d):o.then(l)).then(void 0,u),a;function d(r){s=r;do{if(t&&(o=t())&&o.then&&!Oe(o))return void o.then(l).then(void 0,u);if(!(i=e())||Oe(i)&&!i.v)return void _e(a,1,s);if(i.then)return void i.then(c).then(void 0,u);Oe(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):_e(a,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):_e(a,1,s)}}(function(){return!i&&u<=n},function(){return u++},function(){return Promise.resolve(o.getTokenTemplate(u)).then(function(n){var o=new t.Contract(n.templateAddress,Le,e);return s?Promise.resolve(o.getId()).then(function(e){if(n.isActive&&e.toString()===r.toString())return i=1,u}):n.isActive&&n.templateAddress===r.toString()?(i=1,u):void 0})});return d&&d.then?d.then(a):a(d)})}catch(e){return Promise.reject(e)}};function Ue(){try{if("undefined"==typeof window&&process.env.ADDRESS_FILE){var t=e.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(t)}return U}catch(e){return U}}function je(e){try{var t=Ue();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 qe=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Q},n.createDatatoken=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h,f,m){try{var y=this;return Promise.resolve(y.createDatatokenTx(e,t,n,r,i,s,o,a,u,d,c,l,p,h,f)).then(function(e){return m?e.gasLimit:Promise.resolve(te(y.getSignerAccordingSdk(),e)).then(function(e){if(!e)throw new Error("Failed to send createDatatoken transaction");return Promise.resolve(e.wait()).then(function(e){var t=ge(e,"TokenCreated");return null==t?void 0:t.args[0]})})})}catch(e){return Promise.reject(e)}},n.createDatatokenTx=function(e,t,n,r,i,o,a,u,d,c,l,p,h,f,m){try{var y=this;return Promise.resolve(y.getNftPermissions(e,t)).then(function(t){if(!0!==t.deployERC20)throw new Error("Caller is not DatatokenDeployer");if(l||(l=1),!d||!c){var b=Me();d=b.name,c=b.symbol}var g=y.getContract(e);if(!y.signer.provider)throw new Error("Provider is required but not available");return Promise.resolve(y.signer.provider.getNetwork()).then(function(e){var t=e.chainId;function b(){var e=[n,r,i,o];return h&&(e.push(h.toLowerCase()),e.push(f?f.toLowerCase():xe),e.push(m||xe)),Promise.resolve(y.amountToUnits(null,u,18)).then(function(t){return Promise.resolve(y.amountToUnits(null,a,18)).then(function(n){var r=[t,n],i=p?[s(p)]:[];return Promise.resolve(g.createERC20.estimateGas(l,[d,c],e,r,i)).then(function(t){var n;return Promise.resolve(ie(t,y.getSignerAccordingSdk(),null==(n=y.config)?void 0:n.gasFeeMultiplier)).then(function(t){return re(g.createERC20,[l,[d,c],e,r,i],t)})})})})}var v=je(Number(t)),w=function(){if(p)return Promise.resolve(Be(y.signer,v.ERC721Factory,4,Number(t))).then(function(e){l=e})}();return w&&w.then?w.then(b):b()})})}catch(e){return Promise.reject(e)}},n.addManager=function(e,t,n,r){try{var i=this;return Promise.resolve(i.addManagerTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addManagerTx=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.addManager.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.addManager,[n],e)})})})}catch(e){return Promise.reject(e)}},n.removeManager=function(e,t,n,r){try{var i=this;return Promise.resolve(i.removeManagerTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removeManagerTx=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.removeManager.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.removeManager,[n],e)})})})}catch(e){return Promise.reject(e)}},n.addDatatokenDeployer=function(e,t,n,r){try{var i=this;return Promise.resolve(i.addDatatokenDeployerTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addDatatokenDeployerTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftPermissions(e,t)).then(function(e){if(!0!==e.manager)throw new Error("Caller is not Manager");return Promise.resolve(i.addToCreateERC20List.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.addToCreateERC20List,[n],e)})})})}catch(e){return Promise.reject(e)}},n.removeDatatokenDeployer=function(e,t,n,r){try{var i=this;return Promise.resolve(i.removeDatatokenDeployerTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removeDatatokenDeployerTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftPermissions(e,t)).then(function(s){function o(e){if(a||t===n&&!0!==e.deployERC20)throw new Error("Caller is not Manager nor DatatokenDeployer");return Promise.resolve(i.removeFromCreateERC20List.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.removeFromCreateERC20List,[n],e)})})}var a=!0!==s.manager;return a||t!==n?o(a||t===n&&r.getNftPermissions(e,t)):Promise.resolve(a||t===n&&r.getNftPermissions(e,t)).then(o)})}catch(e){return Promise.reject(e)}},n.addMetadataUpdater=function(e,t,n,r){try{var i=this;return Promise.resolve(i.addMetadataUpdaterTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addMetadataUpdaterTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftPermissions(e,t)).then(function(e){if(!0!==e.manager)throw new Error("Caller is not Manager");return Promise.resolve(i.addToMetadataList.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.addToMetadataList,[n],e)})})})}catch(e){return Promise.reject(e)}},n.removeMetadataUpdater=function(e,t,n,r){try{var i=this;return Promise.resolve(i.removeMetadataUpdaterTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removeMetadataUpdaterTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftPermissions(e,t)).then(function(s){function o(e){if(a||t!==n&&!0!==e.updateMetadata)throw new Error("Caller is not Manager nor Metadata Updater");return Promise.resolve(i.removeFromMetadataList.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.removeFromMetadataList,[n],e)})})}var a=!0!==s.manager;return a||t===n?o(a||t!==n&&r.getNftPermissions(e,t)):Promise.resolve(a||t!==n&&r.getNftPermissions(e,t)).then(o)})}catch(e){return Promise.reject(e)}},n.addStoreUpdater=function(e,t,n,r){try{var i=this;return Promise.resolve(i.addStoreUpdaterTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addStoreUpdaterTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftPermissions(e,t)).then(function(e){if(!0!==e.manager)throw new Error("Caller is not Manager");return Promise.resolve(i.addTo725StoreList.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.addTo725StoreList,[n],e)})})})}catch(e){return Promise.reject(e)}},n.removeStoreUpdater=function(e,t,n,r){try{var i=this;return Promise.resolve(i.removeStoreUpdaterTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removeStoreUpdaterTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftPermissions(e,t)).then(function(s){function o(e){if(a||t!==n&&!0!==e.store)throw new Error("Caller is not Manager nor storeUpdater");return Promise.resolve(i.removeFrom725StoreList.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.removeFrom725StoreList,[n],e)})})}var a=!0!==s.manager;return a||t===n?o(a||t!==n&&r.getNftPermissions(e,t)):Promise.resolve(a||t!==n&&r.getNftPermissions(e,t)).then(o)})}catch(e){return Promise.reject(e)}},n.cleanPermissions=function(e,t,n){try{var r=this;return Promise.resolve(r.cleanPermissionsTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.cleanPermissionsTx=function(e,t){try{var n=this,r=n.getContract(e);return Promise.resolve(n.getNftOwner(e)).then(function(e){if(e!==t)throw new Error("Caller is not NFT Owner");return Promise.resolve(r.cleanPermissions.estimateGas()).then(function(e){var t;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(t=n.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(r.cleanPermissions,[],e)})})})}catch(e){return Promise.reject(e)}},n.transferNft=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.transferNftTx(e,t,n,r)).then(function(e){return i?e.gasLimit:Promise.resolve(te(s.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.transferNftTx=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");var o=r||1;return Promise.resolve(s.transferFrom.estimateGas(t,n,o)).then(function(e){var r;return Promise.resolve(ie(e,i.getSignerAccordingSdk(),null==(r=i.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(s.transferFrom,[t,n,o],e)})})})}catch(e){return Promise.reject(e)}},n.safeTransferNft=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.safeTransferNftTx(e,t,n,r)).then(function(e){return i?e.gasLimit:Promise.resolve(te(s.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.safeTransferNftTx=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");var o=r||1;return Promise.resolve(s.safeTransferFrom.estimateGas(t,n,o)).then(function(e){var r;return Promise.resolve(ie(e,i.getSignerAccordingSdk(),null==(r=i.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(s.safeTransferFrom,[t,n,o],e)})})})}catch(e){return Promise.reject(e)}},n.setMetadata=function(e,t,n,r,i,s,o,a,u,d){try{var c=this;return Promise.resolve(c.setMetadataTx(e,t,n,r,i,s,o,a,u)).then(function(e){return d?e.gasLimit:Promise.resolve(te(c.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setMetadataTx=function(e,t,n,r,i,s,o,a,u){try{var d=this,c=d.getContract(e);return u||(u=[]),Promise.resolve(d.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 l,p=r.match(/\/p2p\/([^/]+)/);t=null!=(l=null==p?void 0:p[1])?l:r}return Promise.resolve(c.setMetaData.estimateGas(n,t,i,s,o,a,u)).then(function(e){var r;return Promise.resolve(ie(e,d.getSignerAccordingSdk(),null==(r=d.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(c.setMetaData,[n,t,i,s,o,a,u],e)})})})}catch(e){return Promise.reject(e)}},n.setMetadataAndTokenURI=function(e,t,n,r){try{var i=this;return Promise.resolve(i.setMetadataAndTokenURITx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setMetadataAndTokenURITx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftPermissions(e,t)).then(function(e){if(!e.updateMetadata)throw new Error("Caller is not Metadata updater");var t=F({},n,{metadataProofs:n.metadataProofs||[]});return Promise.resolve(i.setMetaDataAndTokenURI.estimateGas(t)).then(function(e){var n;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(n=r.config)?void 0:n.gasFeeMultiplier)).then(function(e){return re(i.setMetaDataAndTokenURI,[t],e)})})})}catch(e){return Promise.reject(e)}},n.setMetadataState=function(e,t,n,r){try{var i=this;return Promise.resolve(i.setMetadataStateTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setMetadataStateTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getNftPermissions(e,t)).then(function(e){if(!e.updateMetadata)throw new Error("Caller is not Metadata updater");return Promise.resolve(i.setMetaDataState.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.setMetaDataState,[n],e)})})})}catch(e){return Promise.reject(e)}},n.setTokenURI=function(e,t,n){try{var r=this;return Promise.resolve(r.setTokenURITx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setTokenURITx=function(e,t){try{var n=this,r=n.getContract(e);return Promise.resolve(r.setTokenURI.estimateGas("1",t)).then(function(e){var i;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(e){return re(r.setTokenURI,["1",t],e)})})}catch(e){return Promise.reject(e)}},n.getNftOwner=function(e){try{var t=this.getContract(e);return Promise.resolve(t.ownerOf(1))}catch(e){return Promise.reject(e)}},n.getNftPermissions=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.getPermissions(t))}catch(e){return Promise.reject(e)}},n.getMetadata=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getMetaData())}catch(e){return Promise.reject(e)}},n.isDatatokenDeployer=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.isERC20Deployer(t))}catch(e){return Promise.reject(e)}},n.setData=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.setDataTx(e,t,n,r)).then(function(e){return i?e.gasLimit:Promise.resolve(te(s.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setDataTx=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getNftPermissions(e,t)).then(function(t){if(!0!==t.store)throw new Error("User is not ERC20 store updater");var u=i.getContract(e),d=o(n),c=a(s(r));return Promise.resolve(u.setNewData.estimateGas(d,c)).then(function(e){var t;return Promise.resolve(ie(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(u.setNewData,[d,c],e)})})})}catch(e){return Promise.reject(e)}},n.getData=function(e,t){try{var n=this.getContract(e),r=o(t);return Promise.resolve(n.getData(r)).then(function(e){return e?u(e):null})}catch(e){return Promise.reject(e)}},n.getTokenURI=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.tokenURI(t))}catch(e){return Promise.reject(e)}},n.isDatatokenDeployed=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.isDeployed(t))}catch(e){return Promise.reject(e)}},t}(ve),$e=/*#__PURE__*/function(e){function t(t,n,r,i,s){var o;return(o=e.call(this,t,n,r,i)||this).abiEnterprise=void 0,o.nft=void 0,o.abiEnterprise=s||H.abi,o.nft=new qe(o.signer,n),o}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return W},n.approve=function(e,t,n,r){try{var i=this;return Promise.resolve(i.approveTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.approveTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(oe(null,null,n,18)).then(function(e){return Promise.resolve(i.approve.estimateGas(t,e)).then(function(n){var s;return Promise.resolve(ie(n,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier)).then(function(n){return re(i.approve,[t,e],n)})})})}catch(e){return Promise.reject(e)}},n.createFixedRate=function(e,t,n,r){try{var i=this;return Promise.resolve(i.createFixedRateTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.createFixedRateTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.isDatatokenDeployer(e,t)).then(function(e){if(!e)throw new Error("User is not Datatoken Deployer");var t=[n.baseTokenAddress,n.owner,n.marketFeeCollector,n.allowedConsumer||xe],s=[n.baseTokenDecimals,n.datatokenDecimals,n.fixedRate,n.marketFee,!1===n.withMint?0:1];return Promise.resolve(i.createFixedRate.estimateGas(n.fixedRateAddress,t,s)).then(function(e){var o;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(o=r.config)?void 0:o.gasFeeMultiplier)).then(function(e){return re(i.createFixedRate,[n.fixedRateAddress,t,s],e)})})})}catch(e){return Promise.reject(e)}},n.createDispenser=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.createDispenserTx(e,t,n,r)).then(function(e){return i?e.gasLimit:Promise.resolve(te(s.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.createDispenserTx=function(e,t,n,r){try{var i=this;return Promise.resolve(i.isDatatokenDeployer(e,t)).then(function(t){if(!t)throw new Error("User is not Datatoken Deployer");var s=i.getContract(e),o=r.allowedSwapper||xe,a=!1!==r.withMint;return Promise.resolve(s.createDispenser.estimateGas(n,r.maxTokens,r.maxBalance,a,o)).then(function(e){var t;return Promise.resolve(ie(e,i.getSignerAccordingSdk(),null==(t=i.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(s.createDispenser,[n,r.maxTokens,r.maxBalance,a,o],e)})})})}catch(e){return Promise.reject(e)}},n.mint=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.mintTx(e,t,n,r)).then(function(e){return i?e.gasLimit:Promise.resolve(te(s.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.mintTx=function(e,t,n,r){try{var i=this,s=i.getContract(e);return Promise.resolve(i.getPermissions(e,t)).then(function(o){if(!0!==o.minter)throw new Error("Caller is not Minter");return Promise.resolve(i.getCap(e)).then(function(e){if(!new m(e).gte(n))throw new Error("Mint amount exceeds cap available");return Promise.resolve(oe(null,null,n,18)).then(function(e){var n=r||t;return Promise.resolve(s.mint.estimateGas(n,e)).then(function(t){var r;return Promise.resolve(ie(t,i.getSignerAccordingSdk(),null==(r=i.config)?void 0:r.gasFeeMultiplier)).then(function(t){return re(s.mint,[n,e],t)})})})})})}catch(e){return Promise.reject(e)}},n.addMinter=function(e,t,n,r){try{var i=this;return Promise.resolve(i.addMinterTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addMinterTx=function(e,t,n){try{var r=this;return Promise.resolve(r.isDatatokenDeployer(e,t)).then(function(t){if(!0!==t)throw new Error("Caller is not DatatokenDeployer");var i=r.getContract(e);return Promise.resolve(i.addMinter.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.addMinter,[n],e)})})})}catch(e){return Promise.reject(e)}},n.removeMinter=function(e,t,n,r){try{var i=this;return Promise.resolve(i.removeMinterTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removeMinterTx=function(e,t,n){try{var r=this;return Promise.resolve(r.isDatatokenDeployer(e,t)).then(function(t){if(!0!==t)throw new Error("Caller is not DatatokenDeployer");var i=r.getContract(e);return Promise.resolve(i.removeMinter.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.removeMinter,[n],e)})})})}catch(e){return Promise.reject(e)}},n.addPaymentManager=function(e,t,n,r){try{var i=this;return Promise.resolve(i.addPaymentManagerTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.addPaymentManagerTx=function(e,t,n){try{var r=this;return Promise.resolve(r.isDatatokenDeployer(e,t)).then(function(t){if(!0!==t)throw new Error("Caller is not DatatokenDeployer");var i=r.getContract(e);return Promise.resolve(i.addPaymentManager.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.addPaymentManager,[n],e)})})})}catch(e){return Promise.reject(e)}},n.removePaymentManager=function(e,t,n,r){try{var i=this;return Promise.resolve(i.removePaymentManagerTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.removePaymentManagerTx=function(e,t,n){try{var r=this;return Promise.resolve(r.isDatatokenDeployer(e,t)).then(function(t){if(!0!==t)throw new Error("Caller is not DatatokenDeployer");var i=r.getContract(e);return Promise.resolve(i.removePaymentManager.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.removePaymentManager,[n],e)})})})}catch(e){return Promise.reject(e)}},n.setPaymentCollector=function(e,t,n,r){try{var i=this;return Promise.resolve(i.setPaymentCollectorTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setPaymentCollectorTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(r.getPermissions(e,t)).then(function(s){function o(e){function s(s){function o(e){if(!a&&!u&&!(null==e?void 0:e.deployERC20))throw new Error("Caller is not Fee Manager, owner or Datatoken Deployer");return Promise.resolve(i.setPaymentCollector.estimateGas(n)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.setPaymentCollector,[n],e)})})}var u=e&&s===t;return e&&!u?Promise.resolve(e&&!u&&r.nft.getNftPermissions(e,t)).then(o):o(e&&!u&&r.nft.getNftPermissions(e,t))}return e?Promise.resolve(r.nft.getNftOwner(e)).then(s):s(e)}var a=s.paymentManager;return a?o(!a&&r.getNFTAddress(e)):Promise.resolve(!a&&r.getNFTAddress(e)).then(o)})}catch(e){return Promise.reject(e)}},n.getPaymentCollector=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getPaymentCollector())}catch(e){return Promise.reject(e)}},n.transfer=function(e,t,n,r){try{var i=this,s=i.transferWei;return Promise.resolve(oe(null,null,n,18)).then(function(n){return s.call(i,e,t,n,r)})}catch(e){return Promise.reject(e)}},n.transferWei=function(e,t,n,r){try{var i=this;return Promise.resolve(i.transferWeiTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.transferWeiTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(i.transfer.estimateGas(t,n)).then(function(e){var s;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier)).then(function(e){return re(i.transfer,[t,n],e)})})}catch(e){return Promise.reject(e)}},n.startOrder=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.startOrderTx(e,t,n,r,i)).then(function(e){return s?e.gasLimit:Promise.resolve(te(o.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.startOrderTx=function(e,t,n,r,i){try{var s=this,o=s.getContract(e,s.abi),a=i||{consumeMarketFeeAddress:xe,consumeMarketFeeToken:xe,consumeMarketFeeAmount:"0"};return Promise.resolve(o.startOrder.estimateGas(t,n,r,a)).then(function(e){var i;return Promise.resolve(ie(e,s.getSignerAccordingSdk(),null==(i=s.config)?void 0:i.gasFeeMultiplier)).then(function(e){return re(o.startOrder,[t,n,r,a],e)})})}catch(e){return Promise.reject(e)}},n.reuseOrder=function(e,t,n,r){try{var i=this;return Promise.resolve(i.reuseOrderTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.reuseOrderTx=function(e,t,n){try{var r=this,i=r.getContract(e);return Promise.resolve(i.reuseOrder.estimateGas(t,n)).then(function(e){var s;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier)).then(function(e){return re(i.reuseOrder,[t,n],e)})})}catch(e){return Promise.reject(e)}},n.buyFromFreAndOrder=function(e,t,n,r){try{var i=this;return Promise.resolve(i.buyFromFreAndOrderTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.buyFromFreAndOrderTx=function(e,t,n){try{var r=this,i=r.getContract(e,r.abiEnterprise);return Promise.resolve(r.getFreOrderParams(n)).then(function(e){return Promise.resolve(i.buyFromFreAndOrder.estimateGas(t,e)).then(function(n){var s;return Promise.resolve(ie(n,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier)).then(function(n){return re(i.buyFromFreAndOrder,[t,e],n)})})})}catch(e){return Promise.reject(e)}},n.buyFromDispenserAndOrder=function(e,t,n,r){try{var i=this;return Promise.resolve(i.buyFromDispenserAndOrderTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.buyFromDispenserAndOrderTx=function(e,t,n){try{var r=this,i=r.getContract(e,r.abiEnterprise);return Promise.resolve(i.buyFromDispenserAndOrder.estimateGas(t,n)).then(function(e){var s;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(s=r.config)?void 0:s.gasFeeMultiplier)).then(function(e){return re(i.buyFromDispenserAndOrder,[t,n],e)})})}catch(e){return Promise.reject(e)}},n.setData=function(e,t,n,r){try{var i=this;return Promise.resolve(i.setDataTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setDataTx=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),o=a(s(n));return Promise.resolve(i.setData.estimateGas(o)).then(function(e){var t;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(t=r.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.setData,[o],e)})})})}catch(e){return Promise.reject(e)}},n.cleanPermissions=function(e,t,n){try{var r=this;return Promise.resolve(r.cleanPermissionsTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.cleanPermissionsTx=function(e,t){try{var n=this,r=n.nft,i=r.getNftOwner;return Promise.resolve(n.getNFTAddress(e)).then(function(s){return Promise.resolve(i.call(r,s)).then(function(r){if(r!==t)throw new Error("Caller is NOT Nft Owner");var i=n.getContract(e);return Promise.resolve(i.cleanPermissions.estimateGas()).then(function(e){var t;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(t=n.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(i.cleanPermissions,[],e)})})})})}catch(e){return Promise.reject(e)}},n.getPermissions=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.permissions(t))}catch(e){return Promise.reject(e)}},n.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)}},n.getDecimals=function(e){try{var t=this.getContract(e);return Promise.resolve(t.decimals()).then(Number)}catch(e){return Promise.reject(e)}},n.getId=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getId()).then(Number)}catch(e){return Promise.reject(e)}},n.getSymbol=function(e){try{var t=this.getContract(e);return Promise.resolve(t.symbol())}catch(e){return Promise.reject(e)}},n.getName=function(e){try{var t=this.getContract(e);return Promise.resolve(t.name())}catch(e){return Promise.reject(e)}},n.getNFTAddress=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getERC721Address())}catch(e){return Promise.reject(e)}},n.getFixedRates=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getFixedRates())}catch(e){return Promise.reject(e)}},n.getDispensers=function(e){try{var t=this.getContract(e);return Promise.resolve(t.getDispensers())}catch(e){return Promise.reject(e)}},n.isDatatokenDeployer=function(e,t){try{var n=this.getContract(e);return Promise.resolve(n.isERC20Deployer(t))}catch(e){return Promise.reject(e)}},n.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)}},n.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)}},n.setPublishingMarketFee=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.setPublishingMarketFeeTx(e,t,n,r,i)).then(function(e){return s?e.gasLimit:Promise.resolve(te(o.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setPublishingMarketFeeTx=function(e,t,n,r,i){try{var s=this,o=s.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 Promise.resolve(ie(e,s.getSignerAccordingSdk(),null==(i=s.config)?void 0:i.gasFeeMultiplier)).then(function(e){return re(o.setPublishingMarketFee,[t,n,r],e)})})})}catch(e){return Promise.reject(e)}},n.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)}},n.getFreOrderParams=function(e){try{var t=this,n=e.exchangeId,r=e.exchangeContract;return Promise.resolve(oe(t.signer,e.baseTokenAddress,e.maxBaseTokenAmount,e.baseTokenDecimals)).then(function(i){return Promise.resolve(oe(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}(ve),ze=[{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"}],Ve=/*#__PURE__*/function(e){function t(t,n,r,i,s){var o;return(o=e.call(this,t,r,i,s)||this).accessList=void 0,o.fileObject=void 0,o.abi=o.getDefaultAbi(),o.fileObject=n,o}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return ze},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.setAllowListContractTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setAllowListContractTx=function(e,t,n){try{var r=this;return Promise.resolve(r.isDatatokenDeployer(e,n)).then(function(n){if(!n)throw new Error("User is not Datatoken Deployer");var i=r.getContract(e);return Promise.resolve(i.setAllowListContract.estimateGas(t)).then(function(e){var n;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(n=r.config)?void 0:n.gasFeeMultiplier)).then(function(e){return re(i.setAllowListContract,[t],e)})})})}catch(e){return Promise.reject(e)}},n.setDenyListContract=function(e,t,n,r){try{var i=this;return Promise.resolve(i.setDenyListContractTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setDenyListContractTx=function(e,t,n){try{var r=this;return Promise.resolve(r.isDatatokenDeployer(e,n)).then(function(n){if(!n)throw new Error("User is not Datatoken Deployer");var i=r.getContract(e);return Promise.resolve(i.setDenyListContract.estimateGas(t)).then(function(e){var n;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(n=r.config)?void 0:n.gasFeeMultiplier)).then(function(e){return re(i.setDenyListContract,[t],e)})})})}catch(e){return Promise.reject(e)}},n.setFileObject=function(e,t,n){try{var r=this;return Promise.resolve(r.setFileObjectTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.setFileObjectTx=function(e,t){try{var n=this;return Promise.resolve(n.isDatatokenDeployer(e,t)).then(function(t){if(!t)throw new Error("User is not Datatoken Deployer");var r=n.getContract(e);return Promise.resolve(r.setFilesObject.estimateGas(n.fileObject)).then(function(e){var t;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(t=n.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(r.setFilesObject,[n.fileObject],e)})})})}catch(e){return Promise.reject(e)}},n.getFileObject=function(e,t,n,r,i,s,o){try{var a=this.getContract(e,this.getDefaultAbi());return Promise.resolve(a.getFileObject(t,n,r,i,s,o))}catch(e){return Promise.reject(e)}},t}($e),Ge=[{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"}],Ke=/*#__PURE__*/function(e){function t(t,n,r,i,s){var o;return(o=e.call(this,t,n,r,i,s)||this).abiEnterprise=void 0,o.abi=s||o.getDefaultAbi(),o}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Ge},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.mintTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.mintTx=function(e,t){try{var n=this;return Promise.resolve(n.contract.mint.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.mint,[e,t],r)})})}catch(e){return Promise.reject(e)}},n.batchMint=function(e,t,n){try{var r=this;return Promise.resolve(r.batchMintTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.batchMintTx=function(e,t){try{var n=this;return Promise.resolve(n.contract.batchMint.estimateGas(e,t)).then(function(r){var i;return Promise.resolve(ie(r,n.getSignerAccordingSdk(),null==(i=n.config)?void 0:i.gasFeeMultiplier)).then(function(r){return re(n.contract.batchMint,[e,t],r)})})}catch(e){return Promise.reject(e)}},n.burn=function(e,t){try{var n=this;return Promise.resolve(n.burnTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.burnTx=function(e){try{var t=this;return Promise.resolve(t.contract.burn.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.burn,[e],n)})})}catch(e){return Promise.reject(e)}},n.transferOwnership=function(e,t){try{var n=this;return Promise.resolve(n.transferOwnershipTx(e)).then(function(e){return t?e.gasLimit:Promise.resolve(te(n.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.transferOwnershipTx=function(e){try{var t=this;return Promise.resolve(t.contract.transferOwnership.estimateGas(e)).then(function(n){var r;return Promise.resolve(ie(n,t.getSignerAccordingSdk(),null==(r=t.config)?void 0:r.gasFeeMultiplier)).then(function(n){return re(t.contract.transferOwnership,[e],n)})})}catch(e){return Promise.reject(e)}},n.renounceOwnership=function(e){try{var t=this;return Promise.resolve(t.renounceOwnershipTx()).then(function(n){return e?n.gasLimit:Promise.resolve(te(t.getSignerAccordingSdk(),n))})}catch(e){return Promise.reject(e)}},n.renounceOwnershipTx=function(){try{var e=this;return Promise.resolve(e.contract.renounceOwnership.estimateGas()).then(function(t){var n;return Promise.resolve(ie(t,e.getSignerAccordingSdk(),null==(n=e.config)?void 0:n.gasFeeMultiplier)).then(function(t){return re(e.contract.renounceOwnership,[],t)})})}catch(e){return Promise.reject(e)}},t}(we),We=/*#__PURE__*/function(e){function t(t,n,r,i,s){var o;return(o=e.call(this,t,n,r,i,s)||this).abi=s||o.getDefaultAbi(),o}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Z},n.deployAccessListContract=function(e,t,n,r,i,s,o){void 0===r&&(r=!1);try{var a=this;return Promise.resolve(a.deployAccessListContractTx(e,t,n,r,i,s)).then(function(e){return o?e.gasLimit:function(t,n){try{var r=Promise.resolve(te(a.getSignerAccordingSdk(),e)).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){var t,n=e.logs.map(function(e){try{return a.contract.interface.parseLog(e)}catch(e){return null}}).find(function(e){return"NewAccessList"===(null==e?void 0:e.name)});return null==n||null==(t=n.args)?void 0:t[0]})})}catch(e){return n(e)}return r&&r.then?r.then(void 0,n):r}(0,function(e){console.error("Creation of AccessList failed: "+e)})})}catch(e){return Promise.reject(e)}},n.deployAccessListContractTx=function(e,t,n,r,i,s){void 0===r&&(r=!1);try{var o=this,a=o.normalizeDeployAccessListInput(e,t,n,r,i,s);return Promise.resolve(o.contract.deployAccessListContract.estimateGas(a.nameAccessList,a.symbolAccessList,a.transferable,a.owner,a.user,a.tokenURI)).then(function(e){var t;return Promise.resolve(ie(e,o.getSignerAccordingSdk(),null==(t=o.config)?void 0:t.gasFeeMultiplier)).then(function(e){return re(o.contract.deployAccessListContract,[a.nameAccessList,a.symbolAccessList,a.transferable,a.owner,a.user,a.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.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.changeTemplateAddressTx(e,t)).then(function(e){return n?e.gasLimit:Promise.resolve(te(r.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.changeTemplateAddressTx=function(e,t){try{var n=this;return Promise.resolve(n.getOwner()).then(function(r){if(r!==e)throw new Error("Caller is not Factory Owner");if(t===xe)throw new Error("Template address cannot be ZERO address");return Promise.resolve(n.contract.changeTemplateAddress.estimateGas(t)).then(function(e){var r;return Promise.resolve(ie(e,n.getSignerAccordingSdk(),null==(r=n.config)?void 0:r.gasFeeMultiplier)).then(function(e){return re(n.contract.changeTemplateAddress,[t],e)})})})}catch(e){return Promise.reject(e)}},n.normalizeDeployAccessListInput=function(e,t,n,r,i,s){var o=e,a=t;if(!o||!a){var u=Me();o=u.name,a=u.symbol}return{nameAccessList:o,symbolAccessList:a,tokenURI:n,transferable:r,owner:i,user:s}},t}(we),He=[{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 Qe(e,t,n){if(!e.s){if(n instanceof Ye){if(!n.s)return void(n.o=Qe.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(Qe.bind(null,e,t),Qe.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var Ye=/*#__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{Qe(r,1,s(this.v))}catch(e){Qe(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?Qe(r,1,t?t(i):i):n?Qe(r,1,n(i)):Qe(r,2,i)}catch(e){Qe(r,2,e)}},r},e}(),Je=/*#__PURE__*/function(e){function t(t,n,r,i,s){var o;return(o=e.call(this,t,n,r,i,s)||this).abiEnterprise=void 0,o.abi=s||o.getDefaultAbi(),o}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return He},n.getFunds=function(e){try{return Promise.resolve(this.contract.getFunds(e))}catch(e){return Promise.reject(e)}},n.getUserFunds=function(e,t){try{return Promise.resolve(this.contract.getUserFunds(e,t))}catch(e){return Promise.reject(e)}},n.getUserTokens=function(e){try{return Promise.resolve(this.contract.getUserTokens(e))}catch(e){return Promise.reject(e)}},n.getLocks=function(e,t,n){try{return Promise.resolve(this.contract.getLocks(e,t,n))}catch(e){return Promise.reject(e)}},n.getAuthorizations=function(e,t,n){try{return Promise.resolve(this.contract.getAuthorizations(e,t,n))}catch(e){return Promise.reject(e)}},n.verifyFundsForEscrowPayment=function(e,t,n,r,i,s,o){try{var a,u=this;return Promise.resolve(null==(a=u.signer.provider)?void 0:a.getBalance(d(t))).then(function(a){if(new f(a).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};var l=new $e(u.signer),p=l.allowance;return Promise.resolve(u.signer.getAddress()).then(function(a){return Promise.resolve(p.call(l,e,a,u.contract.target.toString(),o)).then(function(a){return Promise.resolve(u.amountToUnits(e,a,18)).then(function(a){function p(){var a=l.balance;return Promise.resolve(u.signer.getAddress()).then(function(p){return Promise.resolve(a.call(l,e,p)).then(function(a){if(new f(a).isZero())return{isValid:!1,message:"Payment token balance is 0. Please add funds"};var l=u.getAuthorizations;return Promise.resolve(u.signer.getAddress()).then(function(p){return Promise.resolve(l.call(u,e,p,t)).then(function(l){var p=u.getUserFunds;return Promise.resolve(u.signer.getAddress()).then(function(h){return Promise.resolve(p.call(u,h,e)).then(function(p){function h(){var n=function(){if(0===l.length)return Promise.resolve(u.authorize(d(e),d(t),(Number(r)/2).toString(),i,s)).then(function(){})}();return n&&n.then?n.then(function(){return{isValid:!0,message:""}}):{isValid:!0,message:""}}var m=function(){if(new f(p[0]).isZero()){var t=function(){if(n&&new f(c(a)).isLessThanOrEqualTo(new f(c(n)))&&new f(c(n)).isGreaterThan(new f(r)))return Promise.resolve(u.deposit(e,n,o)).then(function(){});var t=function(){if(new f(c(a)).isLessThanOrEqualTo(new f(c(r)))){var t=u.deposit;return Promise.resolve(u.unitsToAmount(e,r,o)).then(function(n){return Promise.resolve(t.call(u,e,n,o)).then(function(){})})}return Promise.resolve(u.deposit(e,a,o)).then(function(){})}();return t&&t.then?t.then(function(){}):void 0}();if(t&&t.then)return t.then(function(){})}}();return m&&m.then?m.then(h):h()})})})})})})}var h=function(){if(new f(a).isLessThan(new f(r)))return Promise.resolve(l.approve(d(e),d(u.contract.target.toString()),r)).then(function(){})}();return h&&h.then?h.then(p):p()})})})})}catch(e){return Promise.reject(e)}},n.deposit=function(e,t,n,r){try{var i=this;return Promise.resolve(i.depositTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.depositTx=function(e,t,n){try{var r=this;return Promise.resolve(r.amountToUnits(e,t,n)).then(function(t){return Promise.resolve(r.contract.deposit.estimateGas(e,t)).then(function(n){var i;return Promise.resolve(ie(n,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier)).then(function(n){return re(r.contract.deposit,[e,t],n)})})})}catch(e){return Promise.reject(e)}},n.withdraw=function(e,t,n,r){try{var i=this;return Promise.resolve(i.withdrawTx(e,t,n)).then(function(e){return r?e.gasLimit:Promise.resolve(te(i.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.withdrawTx=function(e,t,n){try{var r=this;return Promise.resolve(r.prepareWithdrawInputs(e,t,n)).then(function(e){var t=e.tokensWithSufficientFunds,n=e.amountsParsed;return Promise.resolve(r.contract.withdraw.estimateGas(t,n)).then(function(e){var i;return Promise.resolve(ie(e,r.getSignerAccordingSdk(),null==(i=r.config)?void 0:i.gasFeeMultiplier)).then(function(e){return re(r.contract.withdraw,[t,n],e)})})})}catch(e){return Promise.reject(e)}},n.prepareWithdrawInputs=function(e,t,n){try{var r=this;if(e.length!==t.length)throw new Error("Tokens and amounts arrays must have the same length");return Promise.resolve(r.signer.getAddress()).then(function(i){function s(i){var s=[].concat(e);return Promise.resolve(Promise.all(t.map(function(e,t){return r.amountToUnits(s[t],e,n)}))).then(function(e){return{tokensWithSufficientFunds:s,amountsParsed:e}})}var o=function(e,t){var n,r,i=-1;return function s(o){try{for(;++i<e.length;)if((o=t(i))&&o.then){if(!((a=o)instanceof Ye&&1&a.s))return void o.then(s,r||(r=Qe.bind(null,n=new Ye,2)));o=o.v}n?Qe(n,1,o):n=o}catch(e){Qe(n||(n=new Ye),2,e)}var a}(),n}(e,function(n){var s=e[n],o=new f(t[n]);return Promise.resolve(r.getUserFunds(i,s)).then(function(e){var r=new f(e[0]);if(!o.isGreaterThan(0))throw new Error("Invalid withdraw amount for token "+s+": requested "+t[n]+", expected > 0");if(o.isGreaterThan(r))throw new Error("Insufficient funds for token "+s+": requested "+t[n]+", available "+r.toString())})});return o&&o.then?o.then(s):s()})}catch(e){return Promise.reject(e)}},n.authorize=function(e,t,n,r,i,s,o){try{var a=this;return Promise.resolve(a.authorizeTx(e,t,n,r,i,s)).then(function(e){return o?e.gasLimit:Promise.resolve(te(a.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.authorizeTx=function(e,t,n,r,i,s){try{var o=this,a=o.getAuthorizations;return Promise.resolve(o.signer.getAddress()).then(function(u){return Promise.resolve(a.call(o,e,u,t)).then(function(a){return 0!==a.length?(console.log("Payee "+t+" already authorized"),null):Promise.resolve(o.prepareAuthorizeInputs(e,t,n,r,i,s)).then(function(e){var t=e.tokenArg,n=e.payeeArg,r=e.maxLockedAmountParsed,i=e.maxLockSecondsParsed,s=e.maxLockCountsParsed;return Promise.resolve(o.contract.authorize.estimateGas(t,n,r,i,s)).then(function(e){var a;return Promise.resolve(ie(e,o.getSignerAccordingSdk(),null==(a=o.config)?void 0:a.gasFeeMultiplier)).then(function(e){return re(o.contract.authorize,[t,n,r,i,s],e)})})})})})}catch(e){return Promise.reject(e)}},n.prepareAuthorizeInputs=function(e,t,n,r,i,s){try{var o=this;return 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{tokenArg:e,payeeArg:t,maxLockedAmountParsed:n,maxLockSecondsParsed:r,maxLockCountsParsed:i}})})})}catch(e){return Promise.reject(e)}},n.cancelExpiredLocks=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.cancelExpiredLocksTx(e,t,n,r)).then(function(e){return i?e.gasLimit:Promise.resolve(te(s.getSignerAccordingSdk(),e))})}catch(e){return Promise.reject(e)}},n.cancelExpiredLocksTx=function(e,t,n,r){try{var i=this;return Promise.resolve(i.contract.cancelExpiredLocks.estimateGas(e,t,n,r)).then(function(s){var o;return Promise.resolve(ie(s,i.getSignerAccordingSdk(),null==(o=i.config)?void 0:o.gasFeeMultiplier)).then(function(s){return re(i.contract.cancelExpiredLocks,[e,t,n,r],s)})})}catch(e){return Promise.reject(e)}},t}(we),Ze=[{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"}],Xe=/*#__PURE__*/function(e){function t(t,n,r,i,s){var o;return(o=e.call(this,t,n,r,i,s)||this).abi=s||o.getDefaultAbi(),o}R(t,e);var n=t.prototype;return n.getDefaultAbi=function(){return Ze},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;return Promise.resolve(r.amountToUnits(e,t.toString(),n)).then(function(t){return Promise.resolve(r.contract.calculateFee(e,t)).then(function(t){return r.unitsToAmount(e,t,n)})})}catch(e){return Promise.reject(e)}},t}(we),et=function(e){try{return Promise.resolve(new Promise(function(t){setTimeout(t,e)}))}catch(e){return Promise.reject(e)}};function tt(e){return null!=e}var nt=function(e,n){try{var r=t.solidityPackedKeccak256(["bytes"],[t.hexlify(t.toUtf8Bytes(n))]),i=t.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)}},rt=function(e,t){try{var n=l(t);return Promise.resolve(e._legacySignMessage(n)).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)}};const it=Symbol.for("@libp2p/connection"),st=Symbol.for("@libp2p/content-routing");class ot extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class at extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}class ut extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}}class dt extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class ct extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}Error;class lt extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class pt extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class ht extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class ft extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class mt extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class yt extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class bt extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}}class gt extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}class vt extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}}class wt extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Tt extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Pt extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class xt extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}class Et extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}}class St extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}}class At extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}class kt extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}class Ct extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}}class It extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class Dt extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class Mt extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class Ft extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}class Rt extends Event{data;constructor(e,t){super("message",t),this.data=e}}class Lt extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}}class _t extends Lt{constructor(e,t){super(!0,e,t)}}class Nt extends Lt{constructor(e,t){super(!1,e,t)}}const Ot=Symbol.for("@libp2p/peer-discovery"),Bt=Symbol.for("@libp2p/peer-id");function Ut(e){return Boolean(e?.[Bt])}const jt=Symbol.for("@libp2p/peer-routing"),qt="keep-alive";function $t(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}async function zt(...e){const t=[];for(const n of e)$t(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 Vt(...e){const t=[];for(const n of e)$t(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 Gt=Symbol.for("@libp2p/transport");var Kt;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Kt||(Kt={}));class Wt 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 Ht=Symbol.for("@libp2p/service-capabilities"),Qt=Symbol.for("@libp2p/service-dependencies");function Yt(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 Jt{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 Zt{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 en(this,e)}}class Xt{decoders;constructor(e){this.decoders=e}or(e){return en(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 en(e,t){return new Xt({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class tn{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 Jt(e,t,n),this.decoder=new Zt(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function nn({name:e,prefix:t,encode:n,decode:r}){return new tn(e,t,n,r)}function rn({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),o=s.charCodeAt(0);if(255!==n[o])throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,u=e.charAt(0),d=Math.log(a)/Math.log(256),c=Math.log(256)/Math.log(a);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,o=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++)o[p]=(c+=a*o[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===o[h];)h++;for(var f=new Uint8Array(r+(s-h)),m=r;h!==s;)f[m++]=o[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 o=(s-i)*c+1>>>0,d=new Uint8Array(o);i!==s;){for(var l=t[i],p=0,h=o-1;(0!==l||p<r)&&-1!==h;h--,p++)d[h]=(l+=256*d[h]>>>0)%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");r=p,i++}for(var f=o-r;f!==o&&0===d[f];)f++;for(var m=u.repeat(n);f<o;++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 nn({prefix:t,name:e,encode:r,decode:e=>Yt(i(e))})}function sn({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 nn({prefix:t,name:e,encode:e=>function(e,t,n){const r="="===t[t.length-1],i=(1<<n)-1;let s="",o=0,a=0;for(let r=0;r<e.length;++r)for(a=a<<8|e[r],o+=8;o>n;)o-=n,s+=t[i&a>>o];if(0!==o&&(s+=t[i&a<<n-o]),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 o=0,a=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`);a=a<<n|i,o+=n,o>=8&&(o-=8,s[u++]=255&a>>o)}if(o>=n||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return s}(t,i,n,e)})}const on=rn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),an=rn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var un={__proto__:null,base58btc:on,base58flickr:an};const dn=sn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cn=sn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ln=sn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pn=sn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hn=sn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fn=sn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),mn=sn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),yn=sn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bn=sn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var gn={__proto__:null,base32:dn,base32upper:cn,base32pad:ln,base32padupper:pn,base32hex:hn,base32hexupper:fn,base32hexpad:mn,base32hexpadupper:yn,base32z:bn};const vn=rn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wn=rn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Tn={__proto__:null,base36:vn,base36upper:wn},Pn=Math.pow(2,31),xn=Math.pow(2,7),En=Math.pow(2,14),Sn=Math.pow(2,21),An=Math.pow(2,28),kn=Math.pow(2,35),Cn=Math.pow(2,42),In=Math.pow(2,49),Dn=Math.pow(2,56),Mn=Math.pow(2,63),Fn={encode:function e(t,n,r){n=n||[];for(var i=r=r||0;t>=Pn;)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,o=n=n||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");r=t[o++],i+=s<28?(127&r)<<s:(127&r)*Math.pow(2,s),s+=7}while(r>=128);return e.bytes=o-n,i},encodingLength:function(e){return e<xn?1:e<En?2:e<Sn?3:e<An?4:e<kn?5:e<Cn?6:e<In?7:e<Dn?8:e<Mn?9:10}},Rn=Fn;function Ln(e,t=0){return[Rn.decode(e,t),Rn.decode.bytes]}function _n(e,t,n=0){return Rn.encode(e,t,n),t}function Nn(e){return Rn.encodingLength(e)}function On(e,t){const n=t.byteLength,r=Nn(e),i=r+Nn(n),s=new Uint8Array(i+n);return _n(e,s,0),_n(n,s,r),s.set(t,i),new Un(e,n,t,s)}function Bn(e){const t=Yt(e),[n,r]=Ln(t),[i,s]=Ln(t.subarray(r)),o=t.subarray(r+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Un(n,i,o,t)}class Un{code;size;digest;bytes;constructor(e,t,n,r){this.code=e,this.size=t,this.digest=n,this.bytes=r}}function jn(e,t){const{bytes:n,version:r}=e;return 0===r?function(e,t,n){const{prefix:r}=n;if(r!==on.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,$n(e),t??on.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,$n(e),t??dn.encoder)}const qn=new WeakMap;function $n(e){const t=qn.get(e);if(null==t){const t=new Map;return qn.set(e,t),t}return t}class zn{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!==Vn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Gn)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return zn.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=On(e,t);return zn.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 zn.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 jn(this,e)}toJSON(){return{"/":jn(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 zn)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:n,multihash:r,bytes:i}=t;return new zn(e,n,r,i??Kn(e,n,r.bytes))}if(!0===t[Wn]){const{version:e,multihash:n,code:r}=t,i=Bn(n);return zn.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!==Vn)throw new Error(`Version 0 CID must use dag-pb (code: ${Vn}) block encoding`);return new zn(e,t,n,n.bytes);case 1:{const r=Kn(e,t,n.bytes);return new zn(e,t,n,r)}default:throw new Error("Invalid version")}}static createV0(e){return zn.create(0,Vn,e)}static createV1(e,t){return zn.create(1,e,t)}static decode(e){const[t,n]=zn.decodeFirst(e);if(0!==n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=zn.inspectBytes(e),n=t.size-t.multihashSize,r=Yt(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 Un(t.multihashCode,t.digestSize,i,r);return[0===t.version?zn.createV0(s):zn.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0;const n=()=>{const[n,r]=Ln(e.subarray(t));return t+=r,n};let r=n(),i=Vn;if(18===r?(r=0,t=0):i=n(),0!==r&&1!==r)throw new RangeError(`Invalid CID version ${r}`);const s=t,o=n(),a=n(),u=t+a;return{version:r,codec:i,multihashCode:o,digestSize:a,multihashSize:u-s,size:u}}static parse(e,t){const[n,r]=function(e,t){switch(e[0]){case"Q":return[on.prefix,(t??on).decode(`${on.prefix}${e}`)];case on.prefix:return[on.prefix,(t??on).decode(e)];case dn.prefix:return[dn.prefix,(t??dn).decode(e)];case vn.prefix:return[vn.prefix,(t??vn).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=zn.decode(r);if(0===i.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return $n(i).set(n,e),i}}const Vn=112,Gn=18;function Kn(e,t,n){const r=Nn(e),i=r+Nn(t),s=new Uint8Array(i+n.byteLength);return _n(e,s,0),_n(t,s,r),s.set(n,i),s}const Wn=Symbol.for("@ipld/js-cid/CID"),Hn=Yt,Qn=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 On(0,Hn(e))};function Yn(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 Jn(e=0){return new Uint8Array(e)}function Zn(e=0){return new Uint8Array(e)}function Xn(e,t){null==t&&(t=e.reduce((e,t)=>e+t.length,0));const n=Zn(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}const er=Symbol.for("@achingbrain/uint8arraylist");function tr(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 nr(e){return Boolean(e?.[er])}class rr{bufs;length;[er]=!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(!nr(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(!nr(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=tr(this.bufs,e);return t.buf[t.index]}set(e,t){const n=tr(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(!nr(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 Xn(n,r)}subarray(e,t){const{bufs:n,length:r}=this._subList(e,t);return 1===n.length?n[0]:Xn(n,r)}sublist(e,t){const{bufs:n,length:r}=this._subList(e,t),i=new rr;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],o=r,a=o+s.byteLength;if(r=a,e>=a)continue;const u=e>=o&&e<a,d=t>o&&t<=a;if(u&&d){if(e===o&&t===a){n.push(s);break}const r=e-o;n.push(s.subarray(r,r+(t-e)));break}if(u){if(0===e){n.push(s);continue}n.push(s.subarray(e-o))}else{if(d){if(t===a){n.push(s);break}n.push(s.subarray(0,t-o));break}n.push(s)}}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!(nr(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,o=this.byteLength-n.byteLength,a=n.byteLength-1;let u;for(let e=t;e<=o;e+=u){u=0;for(let t=a;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=Zn(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=Jn(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=Jn(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=Jn(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=Zn(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=Jn(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=Jn(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=Jn(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=Jn(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=Jn(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 rr))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Yn(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const n=new rr;return n.bufs=e,null==t&&(t=e.reduce((e,t)=>e+t.byteLength,0)),n.length=t,n}}var ir={__proto__:null,base10:rn({prefix:"9",name:"base10",alphabet:"0123456789"})},sr={__proto__:null,base16:sn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper:sn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})},or={__proto__:null,base2:sn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})};const ar=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ur=ar.reduce((e,t,n)=>(e[n]=t,e),[]),dr=ar.reduce((e,t,n)=>{const r=t.codePointAt(0);if(null==r)throw new Error(`Invalid character: ${t}`);return e[r]=n,e},[]),cr=nn({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+ur[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=dr[e];if(null==r)throw new Error(`Non-base256emoji character: ${n}`);t.push(r)}return new Uint8Array(t)}});var lr={__proto__:null,base256emoji:cr};const pr=sn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),hr=sn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fr=sn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),mr=sn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var yr={__proto__:null,base64:pr,base64pad:hr,base64url:fr,base64urlpad:mr},br={__proto__:null,base8:sn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})},gr={__proto__:null,identity:nn({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 vr({name:e,code:t,encode:n,minDigestLength:r,maxDigestLength:i}){return new wr(e,t,n,r,i)}new TextEncoder,new TextDecoder;class wr{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?Tr(n,this.code,t?.truncate):n.then(e=>Tr(e,this.code,t?.truncate))}throw Error("Unknown type, must be binary type")}}function Tr(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 On(t,e)}function Pr(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const xr=vr({name:"sha2-256",code:18,encode:Pr("SHA-256")});vr({name:"sha2-512",code:19,encode:Pr("SHA-512")});const Er={...gr,...or,...br,...ir,...sr,...gn,...Tn,...un,...yr,...lr};function Sr(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const Ar=Sr("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),kr=Sr("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{const t=Zn((e=e.substring(1)).length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),Cr={utf8:Ar,"utf-8":Ar,hex:Er.base16,latin1:kr,ascii:kr,binary:kr,...Er};function Ir(e,t="utf8"){const n=Cr[t];if(null==n)throw new Error(`Unsupported encoding "${t}"`);return n.decoder.decode(`${n.prefix}${e}`)}function Dr(e,t="utf8"){const n=Cr[t];if(null==n)throw new Error(`Unsupported encoding "${t}"`);return n.encoder.encode(e).substring(1)}const Mr=parseInt("11111",2),Fr=parseInt("10000000",2),Rr=parseInt("01111111",2),Lr={0:Or,1:Or,2:function(e,t){const n=Nr(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=Nr(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=Nr(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=Nr(e,t),r=t.offset+n,i=e[t.offset];t.offset++;let s=0,o=0;i<40?(s=0,o=i):i<80?(s=1,o=i-40):(s=2,o=i-80);let a=`${s}.${o}`,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;a+=`.${e}`,u=[]}}return a},16:Or,22:Or,48:Or};function _r(e,t={offset:0}){const n=e[t.offset]&Mr;if(t.offset++,null!=Lr[n])return Lr[n](e,t);throw new Error("No decoder for tag "+n)}function Nr(e,t){let n=0;if((e[t.offset]&Fr)===Fr){const r=e[t.offset]&Rr;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 Or(e,t){Nr(e,t);const n=[];for(;!(t.offset>=e.byteLength);){const r=_r(e,t);if(null===r)break;n.push(r)}return n}function Br(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 rr;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 rr(Uint8Array.from([t.byteLength|Fr]),t)}function Ur(e){const t=new rr;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new rr(Uint8Array.from([2]),Br(t),t)}function jr(e){const t=Uint8Array.from([0]),n=new rr(t,e);return new rr(Uint8Array.from([3]),Br(n),n)}function qr(e,t=48){const n=new rr;for(const t of e)n.append(t);return new rr(Uint8Array.from([t]),Br(n),n)}const $r=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),zr=Uint8Array.from([6,5,43,129,4,0,34]),Vr=Uint8Array.from([6,5,43,129,4,0,35]),Gr={ext:!0,kty:"EC",crv:"P-256"},Kr={ext:!0,kty:"EC",crv:"P-384"},Wr={ext:!0,kty:"EC",crv:"P-521"};function Hr(e){return function(e){const t=e[1][1][0];let n,r;if(65===t.byteLength)return n=Dr(t.subarray(1,33),"base64url"),r=Dr(t.subarray(33),"base64url"),new Yr({...Gr,key_ops:["verify"],x:n,y:r});if(97===t.byteLength)return n=Dr(t.subarray(1,49),"base64url"),r=Dr(t.subarray(49),"base64url"),new Yr({...Kr,key_ops:["verify"],x:n,y:r});if(133===t.byteLength)return n=Dr(t.subarray(1,67),"base64url"),r=Dr(t.subarray(67),"base64url"),new Yr({...Wr,key_ops:["verify"],x:n,y:r});throw new dt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(_r(e))}function Qr(e){if("P-256"===e)return $r;if("P-384"===e)return zr;if("P-521"===e)return Vr;throw new dt(`Invalid curve ${e}`)}class Yr{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return null==this._raw&&(this._raw=(e=this.jwk,qr([Ur(Uint8Array.from([1])),qr([Qr(e.crv)],160),qr([jr(new rr(Uint8Array.from([4]),Ir(e.x??"","base64url"),Ir(e.y??"","base64url")))],161)]).subarray())),this._raw;var e}toMultihash(){return Qn(Wa(this))}toCID(){return zn.createV1(114,this.toMultihash())}toString(){return on.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(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 Jr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Zr(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Xr(e,t,n=""){const r=Jr(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 ei(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");Zr(e.outputLen),Zr(e.blockLen)}function ti(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 ni(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ri(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ii(e,t){return e<<32-t|e>>>t}const si=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),oi=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ai(e){if(Xr(e),si)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=oi[e[n]];return t}function ui(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function di(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(si)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=ui(e.charCodeAt(i)),s=ui(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 ci(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];Xr(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 li(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 pi(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 hi=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function fi(e,t,n){return e&t^~e&n}function mi(e,t,n){return e&t^e&n^t&n}class yi{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=ri(this.buffer)}update(e){ti(this),Xr(e);const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o!==r)n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=ri(e);for(;r<=i-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){ti(this),function(e,t){Xr(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,ni(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 o=ri(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<u;e++)o.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:o}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const bi=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),gi=/* @__PURE__ */Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),vi=/* @__PURE__ */BigInt(2**32-1),wi=/* @__PURE__ */BigInt(32);function Ti(e,t=!1){return t?{h:Number(e&vi),l:Number(e>>wi&vi)}:{h:0|Number(e>>wi&vi),l:0|Number(e&vi)}}const Pi=(e,t,n)=>e>>>n,xi=(e,t,n)=>e<<32-n|t>>>n,Ei=(e,t,n)=>e>>>n|t<<32-n,Si=(e,t,n)=>e<<32-n|t>>>n,Ai=(e,t,n)=>e<<64-n|t>>>n-32,ki=(e,t,n)=>e>>>n-32|t<<64-n;function Ci(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const Ii=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Di=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Mi=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Fi=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Ri=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Li=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,_i=/* @__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]),Ni=/* @__PURE__ */new Uint32Array(64);class Oi extends yi{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[e,t,n,r,i,s,o,a]}set(e,t,n,r,i,s,o,a){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|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Ni[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ni[e-15],n=Ni[e-2],r=ii(t,7)^ii(t,18)^t>>>3,i=ii(n,17)^ii(n,19)^n>>>10;Ni[e]=i+Ni[e-7]+r+Ni[e-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:u,H:d}=this;for(let e=0;e<64;e++){const t=d+(ii(o,6)^ii(o,11)^ii(o,25))+fi(o,a,u)+_i[e]+Ni[e]|0,c=(ii(n,2)^ii(n,13)^ii(n,22))+mi(n,r,i)|0;d=u,u=a,a=o,o=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,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,r,i,s,o,a,u,d)}roundClean(){ni(Ni)}destroy(){this.set(0,0,0,0,0,0,0,0),ni(this.buffer)}}class Bi extends Oi{A=0|bi[0];B=0|bi[1];C=0|bi[2];D=0|bi[3];E=0|bi[4];F=0|bi[5];G=0|bi[6];H=0|bi[7];constructor(){super(32)}}const Ui=/* @__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:o}=Ti(e[s],t);[r[s],i[s]]=[n,o]}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))))(),ji=/* @__PURE__ */(()=>Ui[0])(),qi=/* @__PURE__ */(()=>Ui[1])(),$i=/* @__PURE__ */new Uint32Array(80),zi=/* @__PURE__ */new Uint32Array(80);class Vi extends yi{constructor(e){super(128,e,16,!1)}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:s,Dh:o,Dl:a,Eh:u,El:d,Fh:c,Fl:l,Gh:p,Gl:h,Hh:f,Hl:m}=this;return[e,t,n,r,i,s,o,a,u,d,c,l,p,h,f,m]}set(e,t,n,r,i,s,o,a,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|o,this.Dl=0|a,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)$i[n]=e.getUint32(t),zi[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|$i[e-15],n=0|zi[e-15],r=Ei(t,n,1)^Ei(t,n,8)^Pi(t,0,7),i=Si(t,n,1)^Si(t,n,8)^xi(t,n,7),s=0|$i[e-2],o=0|zi[e-2],a=Ei(s,o,19)^Ai(s,o,61)^Pi(s,0,6),u=Si(s,o,19)^ki(s,o,61)^xi(s,o,6),d=Mi(i,u,zi[e-7],zi[e-16]),c=Fi(d,r,a,$i[e-7],$i[e-16]);$i[e]=0|c,zi[e]=0|d}let{Ah:n,Al:r,Bh:i,Bl:s,Ch:o,Cl:a,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=Ei(c,l,14)^Ei(c,l,18)^Ai(c,l,41),g=Si(c,l,14)^Si(c,l,18)^ki(c,l,41),v=c&p^~c&f,w=Ri(b,g,l&h^~l&m,qi[e],zi[e]),T=Li(w,y,t,v,ji[e],$i[e]),P=0|w,x=Ei(n,r,28)^Ai(n,r,34)^Ai(n,r,39),E=Si(n,r,28)^ki(n,r,34)^ki(n,r,39),S=n&i^n&o^i&o,A=r&s^r&a^s&a;y=0|f,b=0|m,f=0|p,m=0|h,p=0|c,h=0|l,({h:c,l:l}=Ci(0|u,0|d,0|T,0|P)),u=0|o,d=0|a,o=0|i,a=0|s,i=0|n,s=0|r;const k=Ii(P,E,A);n=Di(k,T,x,S),r=0|k}({h:n,l:r}=Ci(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:s}=Ci(0|this.Bh,0|this.Bl,0|i,0|s)),({h:o,l:a}=Ci(0|this.Ch,0|this.Cl,0|o,0|a)),({h:u,l:d}=Ci(0|this.Dh,0|this.Dl,0|u,0|d)),({h:c,l:l}=Ci(0|this.Eh,0|this.El,0|c,0|l)),({h:p,l:h}=Ci(0|this.Fh,0|this.Fl,0|p,0|h)),({h:f,l:m}=Ci(0|this.Gh,0|this.Gl,0|f,0|m)),({h:y,l:b}=Ci(0|this.Hh,0|this.Hl,0|y,0|b)),this.set(n,r,i,s,o,a,u,d,c,l,p,h,f,m,y,b)}roundClean(){ni($i,zi)}destroy(){ni(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Gi extends Vi{Ah=0|gi[0];Al=0|gi[1];Bh=0|gi[2];Bl=0|gi[3];Ch=0|gi[4];Cl=0|gi[5];Dh=0|gi[6];Dl=0|gi[7];Eh=0|gi[8];El=0|gi[9];Fh=0|gi[10];Fl=0|gi[11];Gh=0|gi[12];Gl=0|gi[13];Hh=0|gi[14];Hl=0|gi[15];constructor(){super(64)}}const Ki=/* @__PURE__ */li(()=>new Bi
2
2
  /* @__PURE__ */,hi(1)),Wi=/* @__PURE__ */li(()=>new Gi
3
- /* @__PURE__ */,hi(3)),Hi=/* @__PURE__ */BigInt(0),Qi=/* @__PURE__ */BigInt(1);function Yi(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e);return e}function Ji(e){if("bigint"==typeof e){if(!ss(e))throw new Error("positive bigint expected, got "+e)}else Zr(e);return e}function Zi(e){const t=Ji(e).toString(16);return 1&t.length?"0"+t:t}function Xi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Hi:BigInt("0x"+e)}function es(e){return Xi(ai(e))}function ts(e){return Xi(ai(is(Xr(e)).reverse()))}function ns(e,t){Zr(t);const n=di((e=Ji(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}function rs(e,t){return ns(e,t).reverse()}function is(e){return Uint8Array.from(e)}const ss=e=>"bigint"==typeof e&&Hi<=e;function os(e,t,n,r){if(!function(e,t,n){return ss(e)&&ss(t)&&ss(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const as=e=>(Qi<<BigInt(e))-Qi;function us(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 ds(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 cs=/* @__PURE__ */BigInt(0),ls=/* @__PURE__ */BigInt(1),ps=/* @__PURE__ */BigInt(2),hs=/* @__PURE__ */BigInt(3),fs=/* @__PURE__ */BigInt(4),ms=/* @__PURE__ */BigInt(5),ys=/* @__PURE__ */BigInt(7),bs=/* @__PURE__ */BigInt(8),gs=/* @__PURE__ */BigInt(9),vs=/* @__PURE__ */BigInt(16);function ws(e,t){const n=e%t;return n>=cs?n:t+n}function Ts(e,t,n){let r=e;for(;t-- >cs;)r*=r,r%=n;return r}function Ps(e,t){if(e===cs)throw new Error("invert: expected non-zero number");if(t<=cs)throw new Error("invert: expected positive modulus, got "+t);let n=ws(e,t),r=t,i=cs,s=ls;for(;n!==cs;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==ls)throw new Error("invert: does not exist");return ws(i,t)}function xs(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Es(e,t){const n=e.pow(t,(e.ORDER+ls)/fs);return xs(e,n,t),n}function Ss(e,t){const n=(e.ORDER-ms)/bs,r=e.mul(t,ps),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,ps),i),a=e.mul(s,e.sub(o,e.ONE));return xs(e,a,t),a}function As(e){if(e<hs)throw new Error("sqrt is not defined for small field");let t=e-ls,n=0;for(;t%ps===cs;)t/=ps,n++;let r=ps;const i=Ms(e);for(;1===Is(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Es;let s=i.pow(r,t);const o=(t+ls)/ps;return function(e,r){if(e.is0(r))return r;if(1!==Is(e,r))throw new Error("Cannot find square root");let i=n,a=e.mul(e.ONE,s),u=e.pow(r,t),d=e.pow(r,o);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=ls<<BigInt(i-t-1),s=e.pow(a,r);i=t,a=e.sqr(s),u=e.mul(u,a),d=e.mul(d,s)}return d}}const ks=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Cs(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 Is(e,t){const n=e.pow(t,(e.ORDER-ls)/ps),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 Ds{ORDER;BITS;BYTES;isLE;ZERO=cs;ONE=ls;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=cs)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&&Zr(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 ws(e,this.ORDER)}isValid(e){if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return cs<=e&&e<this.ORDER}is0(e){return e===cs}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ls)===ls}neg(e){return ws(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ws(e*e,this.ORDER)}add(e,t){return ws(e+t,this.ORDER)}sub(e,t){return ws(e-t,this.ORDER)}mul(e,t){return ws(e*t,this.ORDER)}pow(e,t){return function(e,t,n){if(n<cs)throw new Error("invalid exponent, negatives unsupported");if(n===cs)return e.ONE;if(n===ls)return t;let r=e.ONE,i=t;for(;n>cs;)n&ls&&(r=e.mul(r,i)),i=e.sqr(i),n>>=ls;return r}(this,e,t)}div(e,t){return ws(e*Ps(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 Ps(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=(t=this.ORDER)%fs===hs?Es:t%bs===ms?Ss:t%vs===gs?function(e){const t=Ms(e),n=As(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+ys)/vs;return(e,t)=>{let n=e.pow(t,o),a=e.mul(n,r);const u=e.mul(n,i),d=e.mul(n,s),c=e.eql(e.sqr(a),t),l=e.eql(e.sqr(u),t);n=e.cmov(n,a,c),a=e.cmov(d,u,l);const p=e.eql(e.sqr(a),t),h=e.cmov(n,a,p);return xs(e,h,t),h}}(t):As(t)),this._sqrt(this,e);var t}toBytes(e){return this.isLE?rs(e,this.BYTES):ns(e,this.BYTES)}fromBytes(e,t=!1){Xr(e);const{_lengths:n,BYTES:r,isLE:i,ORDER:s,_mod:o}=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 a=i?ts(e):es(e);if(o&&(a=ws(a,s)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Cs(this,e)}cmov(e,t,n){return n?t:e}}function Ms(e,t={}){return new Ds(e,t)}function Fs(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 Rs(e){const t=Fs(e);return t+Math.ceil(t/2)}const Ls=/* @__PURE__ */BigInt(0),_s=/* @__PURE__ */BigInt(1);function Ns(e,t){const n=t.negate();return e?n:t}function Os(e,t){const n=Cs(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Bs(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Us(e,t){Bs(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:as(e),maxNumber:n,shiftBy:BigInt(e)}}function js(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(e&i),u=e>>o;a>r&&(a-=s,u+=_s);const d=t*r;return{nextN:u,offset:d+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:d}}const qs=new WeakMap,$s=new WeakMap;function zs(e){return $s.get(e)||1}function Vs(e){if(e!==Ls)throw new Error("invalid wNAF")}class Gs{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>Ls;)t&_s&&(n=n.add(r)),r=r.double(),t>>=_s;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Us(t,this.bits),i=[];let s=e,o=s;for(let e=0;e<n;e++){o=s,i.push(o);for(let e=1;e<r;e++)o=o.add(s),i.push(o);s=o.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=Us(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:o,offset:a,isZero:u,isNeg:d,isNegF:c,offsetF:l}=js(n,e,s);n=o,u?i=i.add(Ns(c,t[l])):r=r.add(Ns(d,t[a]))}return Vs(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Us(e,this.bits);for(let e=0;e<i.windows&&n!==Ls;e++){const{nextN:s,offset:o,isZero:a,isNeg:u}=js(n,e,i);if(n=s,!a){const e=t[o];r=r.add(u?e.negate():e)}}return Vs(n),r}getPrecomputes(e,t,n){let r=qs.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),qs.set(t,r))),r}cached(e,t,n){const r=zs(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=zs(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Bs(t,this.bits),$s.set(e,t),qs.delete(e)}hasCache(e){return 1!==zs(e)}}function Ks(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=ks.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",BYTES:"number",BITS:"number"});us(e,t)}(t),t}return Ms(e,{isLE:n})}function Ws(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>Ls))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Ks(t.p,n.Fp,r),s=Ks(t.n,n.Fn,r),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)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 Hs(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}const Qs=BigInt(0),Ys=BigInt(1),Js=BigInt(2),Zs=BigInt(8);function Xs(e,t={}){const n=Ws("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;us(t,{},{uvRatio:"function"});const a=Js<<BigInt(8*i.BYTES)-Ys,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:Qs}}});if(!function(e,t,n,r){const i=e.sqr(n),s=e.sqr(r),o=e.add(e.mul(t.a,i),s),a=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(o,a)}(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function c(e,t,n=!1){return os("coordinate "+e,t,n?Ys:Qs,a),t}function l(e){if(!(e instanceof f))throw new Error("EdwardsPoint expected")}const p=ds((e,t)=>{const{X:n,Y:i,Z:s}=e,o=e.is0();null==t&&(t=o?Zs:r.inv(s));const a=u(n*t),d=u(i*t),c=r.mul(s,t);if(o)return{x:Qs,y:Ys};if(c!==Ys)throw new Error("invZ was invalid");return{x:a,y:d}}),h=ds(e=>{const{a:t,d:n}=s;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:o,T:a}=e,d=u(r*r),c=u(i*i),l=u(o*o),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(o*a))throw new Error("bad point: equation left != right (2)");return!0});class f{static BASE=new f(s.Gx,s.Gy,Ys,u(s.Gx*s.Gy));static ZERO=new f(Qs,Ys,Ys,Qs);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,Ys,u(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:o}=s;e=is(Xr(e,n,"point")),Yi(t,"zip215");const c=is(e),l=e[n-1];c[n-1]=-129&l;const p=ts(c);os("point.y",p,Qs,t?a:r.ORDER);const h=u(p*p),m=u(h-Ys),y=u(o*h-i);let{isValid:b,value:g}=d(m,y);if(!b)throw new Error("bad point: invalid y coordinate");const v=(g&Ys)===Ys,w=!!(128&l);if(!t&&g===Qs&&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(di(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(Js),this}assertValidity(){h(this)}equals(e){l(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:s,Z:o}=e,a=u(t*o),d=u(i*r),c=u(n*o),p=u(s*r);return a===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),o=u(n*n),a=u(Js*u(r*r)),d=u(e*i),c=t+n,l=u(u(c*c)-i-o),p=d+o,h=p-a,m=d-o,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:o,T:a}=this,{X:d,Y:c,Z:p,T:h}=e,m=u(r*d),y=u(i*c),b=u(a*n*h),g=u(o*p),v=u((r+i)*(d+c)-m-y),w=g-b,T=g+b,P=u(y-t*m),x=u(v*w),E=u(T*P),S=u(v*P),A=u(w*T);return new f(x,E,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=>Os(f,e));return Os(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===Qs?f.ZERO:this.is0()||e===Ys?this:m.unsafe(this,e,e=>Os(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(e){return p(this,e)}clearCofactor(){return o===Ys?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Ys?128:0,n}toHex(){return ai(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const m=new Gs(f,i.BITS);return f.BASE.precompute(8),f}const eo=BigInt(1),to=BigInt(2),no=BigInt(5),ro=BigInt(8),io=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),so=/* @__PURE__ */(()=>({p:io,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ro,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function oo(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const ao=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),uo=/* @__PURE__ */Xs(so,{uvRatio:function(e,t){const n=io,r=ws(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=io,o=e*e%s*e%s,a=Ts(o,to,s)*o%s,u=Ts(a,eo,s)*e%s,d=Ts(u,no,s)*u%s,c=Ts(d,t,s)*d%s,l=Ts(c,n,s)*c%s,p=Ts(l,r,s)*l%s,h=Ts(p,i,s)*p%s,f=Ts(h,i,s)*p%s,m=Ts(f,t,s)*d%s;return{pow_p_5_8:Ts(m,to,s)*e%s,b2:o}}(e*ws(r*r*t,n)).pow_p_5_8;let s=ws(e*r*i,n);const o=ws(t*s*s,n),a=s,u=ws(s*ao,n),d=o===e,c=o===ws(-e,n),l=o===ws(-e*ao,n);return d&&(s=a),(c||l)&&(s=u),(ws(s,n)&ls)===ls&&(s=ws(-s,n)),{isValid:d||c,value:s}}});function co(e){return function(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');us(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:o}=e,a=n.randomBytes||pi,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Yi(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function c(e){return o.create(ts(e))}function l(e){const{head:n,prefix:r,scalar:s}=function(e){const n=y.secretKey;Xr(e,y.secretKey,"secretKey");const r=Xr(t(e),2*n,"hashedSecretKey"),i=u(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:c(i)}}(e),o=i.multiply(s),a=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:a}}function p(e){return l(e).pointBytes}function h(e=Uint8Array.of(),...n){const i=ci(...n);return c(t(d(i,Xr(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=a(y.seed)){return Xr(e,y.seed,"seed")}const g={getExtendedPublicKey:l,randomSecretKey:b,isValidSecretKey:function(e){return Jr(e)&&e.length===o.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 o=i?s.div(Ys+n,Ys-n):s.div(n-Ys,n+Ys);return s.toBytes(o)},toMontgomerySecret(e){const n=y.secretKey;Xr(e,n);const r=t(e.subarray(0,n));return u(r).subarray(0,n)}};return Object.freeze({keygen:Hs(b,p),getPublicKey:p,sign:function(e,t,n={}){e=Xr(e,void 0,"message"),r&&(e=r(e));const{prefix:s,scalar:a,pointBytes:u}=l(t),d=h(n.context,s,e),c=i.multiply(d).toBytes(),p=h(n.context,c,u,e),f=o.create(d+p*a);if(!o.isValid(f))throw new Error("sign failed: invalid s");return Xr(ci(c,o.toBytes(f)),y.signature,"result")},verify:function(t,n,s,o=f){const{context:a,zip215:u}=o,d=y.signature;t=Xr(t,d,"signature"),n=Xr(n,void 0,"message"),s=Xr(s,y.publicKey,"publicKey"),void 0!==u&&Yi(u,"zip215"),r&&(n=r(n));const c=d/2,l=t.subarray(0,c),p=ts(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(a,b.toBytes(),m.toBytes(),n);return b.add(m.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()},utils:g,Point:e,lengths:y})}(uo,Wi,Object.assign({adjustScalarBytes:oo},e))}const lo=/* @__PURE__ */co({});Error;class po extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class ho extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var fo={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new ho("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 mo;const yo=(async()=>{try{return await fo.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function bo(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class go{type="Ed25519";raw;constructor(e){this.raw=To(e,32)}toMultihash(){return Qn(Wa(this))}toCID(){return zn.createV1(114,this.toMultihash())}toString(){return on.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();const r=async function(e,t,n){return null==mo&&(mo=await yo),mo?async function(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await fo.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await fo.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 lo.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}(e,t,n)}(this.raw,t,e);return bo(r)?r.then(e=>(n?.signal?.throwIfAborted(),e)):r}}class vo{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=To(e,64),this.publicKey=new go(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const n=async function(e,t){return null==mo&&(mo=await yo),mo?async function(e,t){let n;n=64===e.length?e.subarray(0,32):e;const r={crv:"Ed25519",kty:"OKP",x:Dr(e.subarray(32),"base64url"),d:Dr(n,"base64url"),ext:!0,key_ops:["sign"]},i=await fo.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await fo.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 lo.sign(t instanceof Uint8Array?t:t.subarray(),n)}(e,t)}(this.raw,e);return bo(n)?n.then(e=>(t?.signal?.throwIfAborted(),e)):(t?.signal?.throwIfAborted(),n)}}function wo(e){return e=To(e,32),new go(e)}function To(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new dt(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const Po=Math.pow(2,7),xo=Math.pow(2,14),Eo=Math.pow(2,21),So=Math.pow(2,28),Ao=Math.pow(2,35),ko=Math.pow(2,42),Co=Math.pow(2,49),Io=128,Do=127;function Mo(e){if(e<Po)return 1;if(e<xo)return 2;if(e<Eo)return 3;if(e<So)return 4;if(e<Ao)return 5;if(e<ko)return 6;if(e<Co)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fo(e,t,n=0){switch(Mo(e)){case 8:t[n++]=255&e|Io,e/=128;case 7:t[n++]=255&e|Io,e/=128;case 6:t[n++]=255&e|Io,e/=128;case 5:t[n++]=255&e|Io,e/=128;case 4:t[n++]=255&e|Io,e>>>=7;case 3:t[n++]=255&e|Io,e>>>=7;case 2:t[n++]=255&e|Io,e>>>=7;case 1:t[n++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function Ro(e,t){let n=e[t],r=0;if(r+=n&Do,n<Io)return r;if(n=e[t+1],r+=(n&Do)<<7,n<Io)return r;if(n=e[t+2],r+=(n&Do)<<14,n<Io)return r;if(n=e[t+3],r+=(n&Do)<<21,n<Io)return r;if(n=e[t+4],r+=(n&Do)*So,n<Io)return r;if(n=e[t+5],r+=(n&Do)*Ao,n<Io)return r;if(n=e[t+6],r+=(n&Do)*ko,n<Io)return r;if(n=e[t+7],r+=(n&Do)*Co,n<Io)return r;throw new RangeError("Could not decode varint")}function Lo(e,t,n=0){return null==t&&(t=Zn(Mo(e))),t instanceof Uint8Array?Fo(e,t,n):function(e,t,n=0){switch(Mo(e)){case 8:t.set(n++,255&e|Io),e/=128;case 7:t.set(n++,255&e|Io),e/=128;case 6:t.set(n++,255&e|Io),e/=128;case 5:t.set(n++,255&e|Io),e/=128;case 4:t.set(n++,255&e|Io),e>>>=7;case 3:t.set(n++,255&e|Io),e>>>=7;case 2:t.set(n++,255&e|Io),e>>>=7;case 1:t.set(n++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,n)}function _o(e,t=0){return e instanceof Uint8Array?Ro(e,t):function(e,t){let n=e.get(t),r=0;if(r+=n&Do,n<Io)return r;if(n=e.get(t+1),r+=(n&Do)<<7,n<Io)return r;if(n=e.get(t+2),r+=(n&Do)<<14,n<Io)return r;if(n=e.get(t+3),r+=(n&Do)<<21,n<Io)return r;if(n=e.get(t+4),r+=(n&Do)*So,n<Io)return r;if(n=e.get(t+5),r+=(n&Do)*Ao,n<Io)return r;if(n=e.get(t+6),r+=(n&Do)*ko,n<Io)return r;if(n=e.get(t+7),r+=(n&Do)*Co,n<Io)return r;throw new RangeError("Could not decode varint")}(e,t)}const No=new Float32Array([-0]),Oo=new Uint8Array(No.buffer);function Bo(e,t,n){No[0]=e,t[n]=Oo[0],t[n+1]=Oo[1],t[n+2]=Oo[2],t[n+3]=Oo[3]}const Uo=new Float64Array([-0]),jo=new Uint8Array(Uo.buffer);function qo(e,t,n){Uo[0]=e,t[n]=jo[0],t[n+1]=jo[1],t[n+2]=jo[2],t[n+3]=jo[3],t[n+4]=jo[4],t[n+5]=jo[5],t[n+6]=jo[6],t[n+7]=jo[7]}const $o=BigInt(Number.MAX_SAFE_INTEGER),zo=BigInt(Number.MIN_SAFE_INTEGER);class Vo{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 Go;if(e<$o&&e>zo)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>Ko&&(r=0n,++n>Ko&&(n=0n))),new Vo(Number(r),Number(n))}static fromNumber(e){if(0===e)return Go;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 Vo(n,r)}static from(e){return"number"==typeof e?Vo.fromNumber(e):"bigint"==typeof e?Vo.fromBigInt(e):"string"==typeof e?Vo.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Vo(e.low>>>0,e.high>>>0):Go}}const Go=new Vo(0,0);Go.toBigInt=function(){return 0n},Go.zzEncode=Go.zzDecode=function(){return this},Go.length=function(){return 1};const Ko=4294967296n;function Wo(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 Ho(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Qo(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Yo{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,Ho(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 Ho(this,4);return Qo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ho(this,4);return 0|Qo(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Ho(this,4);const e=(Oo[0]=(t=this.buf)[n=this.pos],Oo[1]=t[n+1],Oo[2]=t[n+2],Oo[3]=t[n+3],No[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ho(this,4);const e=(jo[0]=(t=this.buf)[n=this.pos],jo[1]=t[n+1],jo[2]=t[n+2],jo[3]=t[n+3],jo[4]=t[n+4],jo[5]=t[n+5],jo[6]=t[n+6],jo[7]=t[n+7],Uo[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 Ho(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,o=0;for(;t<n;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(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[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Ho(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Ho(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 Vo(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Ho(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 Ho(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 Ho(this,8);const e=Qo(this.buf,this.pos+=4),t=Qo(this.buf,this.pos+=4);return new Vo(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=Ro(this.buf,this.pos);return this.pos+=Mo(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 Jo(e){return new Yo(e instanceof Uint8Array?e:e.subarray())}function Zo(e,t,n){const r=Jo(e);return t.decode(r,void 0,n)}class Xo{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function ea(){}class ta{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const na=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Zn(r);n+r>e&&(t=Zn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class ra{len;head;tail;states;constructor(){this.len=0,this.head=new Xo(ea,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Xo(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new oa((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(aa,10,Vo.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Vo.fromBigInt(e);return this._push(aa,t.length(),t)}uint64Number(e){return this._push(Fo,Mo(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=Vo.fromBigInt(e).zzEncode();return this._push(aa,t.length(),t)}sint64Number(e){const t=Vo.fromNumber(e).zzEncode();return this._push(aa,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ia,1,e?1:0)}fixed32(e){return this._push(ua,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Vo.fromBigInt(e);return this._push(ua,4,t.lo)._push(ua,4,t.hi)}fixed64Number(e){const t=Vo.fromNumber(e);return this._push(ua,4,t.lo)._push(ua,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(Bo,4,e)}double(e){return this._push(qo,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(ia,1,0):this.uint32(t)._push(da,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(Wo,t,e):this._push(ia,1,0)}fork(){return this.states=new ta(this),this.head=this.tail=new Xo(ea,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 Xo(ea,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?Zn(n):na(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function ia(e,t,n){t[n]=255&e}function sa(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class oa extends Xo{next;constructor(e,t){super(sa,e,t),this.next=void 0}}function aa(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 ua(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 da(e,t,n){t.set(e,n)}function ca(e,t,n){t.set(e,n)}function la(e,t,n){e.length<40?Wo(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(Ir(e),n)}function pa(e,t){const n=new ra;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*ha(e,t,n){const r=Jo(e);yield*t.stream(r,void 0,"$",n)}function fa(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function ma(e,t,n){return fa("message",2,e,t,n)}var ya,ba,ga,va;function wa(e){if(isNaN(e)||e<=0)throw new dt("random bytes length must be a Number bigger than 0");return pi(e)}null!=globalThis.Buffer&&(ra.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(ca,t,e),this},ra.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(la,t,e),this}),function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(ya||(ya={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(ba||(ba={})),function(e){e.codec=()=>function(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return fa("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)})}(ba)}(ya||(ya={})),function(e){let t;e.codec=()=>(null==t&&(t=ma((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ya.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=ya.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:ya.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 pa(t,e.codec())},e.decode=function(t,n){return Zo(t,e.codec(),n)},e.stream=function(t,n){return ha(t,e.codec(),n)}}(ga||(ga={})),function(e){let t;e.codec=()=>(null==t&&(t=ma((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ya.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=ya.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:ya.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 pa(t,e.codec())},e.decode=function(t,n){return Zo(t,e.codec(),n)},e.stream=function(t,n){return ha(t,e.codec(),n)}}(va||(va={}));class Ta{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 dt("JWK was missing components");return qr([Pa,jr(qr([Ur(Ir(e.n,"base64url")),Ur(Ir(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return zn.createV1(114,this._multihash)}toString(){return on.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(this.raw,e.raw)}verify(e,t,n){return async function(e,t,n,r){const i=await fo.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await fo.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 Pa=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class xa{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(ei(e),Xr(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),ni(r)}update(e){return ti(this),this.iHash.update(e),this}digestInto(e){ti(this),Xr(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:o}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=o,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 Ea=(e,t,n)=>new xa(e,t).update(n).digest();Ea.create=(e,t)=>new xa(e,t);const Sa=(e,t)=>(e+(e>=0?t:-t)/Fa)/t;function Aa(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function ka(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Yi(n.lowS,"lowS"),Yi(n.prehash,"prehash"),void 0!==n.format&&Aa(n.format),n}class Ca extends Error{constructor(e=""){super(e)}}const Ia={Err:Ca,_tlv:{encode:(e,t)=>{const{Err:n}=Ia;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=Zi(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Zi(i.length/2|128):"";return Zi(e)+s+i+t},decode(e,t){const{Err:n}=Ia;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 o=t.subarray(r,r+e);if(o.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===o[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of o)s=s<<8|e;if(r+=e,s<128)throw new n("tlv.decode(long): not minimal encoding")}else s=i;const o=t.subarray(r,r+s);if(o.length!==s)throw new n("tlv.decode: wrong value length");return{v:o,l:t.subarray(r+s)}}},_int:{encode(e){const{Err:t}=Ia;if(e<Da)throw new t("integer: negative integers are not allowed");let n=Zi(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}=Ia;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 es(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ia,i=Xr(e,void 0,"signature"),{v:s,l:o}=r.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,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(a),s:n.decode(d)}},hexFromSig(e){const{_tlv:t,_int:n}=Ia,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s));return t.encode(48,r+i)}},Da=BigInt(0),Ma=BigInt(1),Fa=BigInt(2),Ra=BigInt(3),La=BigInt(4);function _a(e,t={}){const n=Ws("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;us(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=Oa(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(),o=r.toBytes(i);return Yi(n,"isCompressed"),n?(c(),ci(Na(!r.isOdd(s)),o)):ci(Uint8Array.of(4),o,r.toBytes(s))},p=t.fromBytes||function(e){Xr(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=d,i=e.length,s=e[0],o=e.subarray(1);if(i!==t||2!==s&&3!==s){if(i===n&&4===s){const e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.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(o);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,Ra),La),y=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(m,y)))throw new Error("bad curve params: a or b");function b(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function g(e){if(!(e instanceof x))throw new Error("Weierstrass Point expected")}function v(e){if(!u||!u.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[s,o]]=t,a=Sa(o*e,n),u=Sa(-i*e,n);let d=e-a*r-u*s,c=-a*i-u*o;const l=d<Da,p=c<Da;l&&(d=-d),p&&(c=-c);const h=as(Math.ceil(function(e){let t;for(t=0;e>Hi;e>>=Qi,t+=1);return t}(n)/2))+Ma;if(d<Da||d>=h||c<Da||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=ds((e,t)=>{const{X:n,Y:i,Z:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const o=e.is0();null==t&&(t=o?r.ONE:r.inv(s));const a=r.mul(n,t),u=r.mul(i,t),d=r.mul(s,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(d,r.ONE))throw new Error("invZ was invalid");return{x:a,y:u}}),T=ds(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 P(e,t,n,i,s){return n=new x(r.mul(n.X,e),n.Y,n.Z),t=Ns(i,t),n=Ns(s,n),t.add(n)}class x{static BASE=new x(s.Gx,s.Gy,r.ONE);static ZERO=new x(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=i;X;Y;Z;constructor(e,t,n){this.X=b("x",e),this.Y=b("y",t,!0),this.Z=b("z",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof x)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?x.ZERO:new x(t,n,r.ONE)}static fromBytes(e){const t=x.fromAffine(p(Xr(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return x.fromBytes(di(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(Ra),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:o,Z:a}=e,u=r.eql(r.mul(t,a),r.mul(s,i)),d=r.eql(r.mul(n,a),r.mul(o,i));return u&&d}negate(){return new x(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,Ra),{X:i,Y:o,Z:a}=this;let u=r.ZERO,d=r.ZERO,c=r.ZERO,l=r.mul(i,i),p=r.mul(o,o),h=r.mul(a,a),f=r.mul(i,o);return f=r.add(f,f),c=r.mul(i,a),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(o,a),h=r.add(h,h),l=r.mul(h,f),u=r.sub(u,l),c=r.mul(h,p),c=r.add(c,c),c=r.add(c,c),new x(u,d,c)}add(e){g(e);const{X:t,Y:n,Z:i}=this,{X:o,Y:a,Z:u}=e;let d=r.ZERO,c=r.ZERO,l=r.ZERO;const p=s.a,h=r.mul(s.b,Ra);let f=r.mul(t,o),m=r.mul(n,a),y=r.mul(i,u),b=r.add(t,n),v=r.add(o,a);b=r.mul(b,v),v=r.add(f,m),b=r.sub(b,v),v=r.add(t,i);let w=r.add(o,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(a,u),w=r.mul(w,d),d=r.add(m,y),w=r.sub(w,d),l=r.mul(p,v),d=r.mul(h,y),l=r.add(d,l),d=r.sub(m,l),l=r.add(m,l),c=r.mul(d,l),m=r.add(f,f),m=r.add(m,f),y=r.mul(p,y),v=r.mul(h,v),m=r.add(m,y),y=r.sub(f,y),y=r.mul(p,y),v=r.add(v,y),f=r.mul(m,v),c=r.add(c,f),f=r.mul(w,v),d=r.mul(b,d),d=r.sub(d,f),f=r.mul(b,m),l=r.mul(w,l),l=r.add(l,f),new x(d,c,l)}subtract(e){return this.add(e.negate())}is0(){return this.equals(x.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,s;const o=e=>S.cached(this,e,e=>Os(x,e));if(n){const{k1neg:t,k1:i,k2neg:a,k2:u}=v(e),{p:d,f:c}=o(i),{p:l,f:p}=o(u);s=c.add(p),r=P(n.beta,d,l,t,a)}else{const{p:t,f:n}=o(e);r=t,s=n}return Os(x,[r,s])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===Da||r.is0())return x.ZERO;if(e===Ma)return r;if(S.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:s,k2:o}=v(e),{p1:a,p2:u}=function(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>Ls||r>Ls;)n&_s&&(s=s.add(i)),r&_s&&(o=o.add(i)),i=i.double(),n>>=_s,r>>=_s;return{p1:s,p2:o}}(x,r,i,o);return P(n.beta,a,u,t,s)}return S.unsafe(r,e)}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===Ma||(e?e(x,this):S.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===Ma?this:e?e(x,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Yi(e,"isCompressed"),this.assertValidity(),l(x,this,e)}toHex(e=!0){return ai(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const E=i.BITS,S=new Gs(x,t.endo?Math.ceil(E/2):E);return x.BASE.precompute(8),x}function Na(e){return Uint8Array.of(e?2:3)}function Oa(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ba(e,t,n={}){ei(t),us(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=(n=Object.assign({},n)).randomBytes||pi,i=n.hmac||((e,n)=>Ea(t,e,n)),{Fp:s,Fn:o}=e,{ORDER:a,BITS:u}=o,{keygen:d,getPublicKey:c,getSharedSecret:l,utils:p,lengths:h}=function(e,t={}){const{Fn:n}=e,r=t.randomBytes||pi,i=Object.assign(Oa(e.Fp,n),{seed:Rs(n.ORDER)});function s(e=r(i.seed)){return function(e,t,n=!1){Xr(e);const r=e.length,i=Fs(t),s=Rs(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=ws(n?ts(e):es(e),t-ls)+ls;return n?rs(o,i):ns(o,i)}(Xr(e,i.seed,"seed"),n.ORDER)}function o(t,r=!0){return e.BASE.multiply(n.fromBytes(t)).toBytes(r)}function a(e){const{secretKey:t,publicKey:r,publicKeyUncompressed:s}=i;if(!Jr(e))return;if("_lengths"in n&&n._lengths||t===r)return;const o=Xr(e,void 0,"key").length;return o===r||o===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=Hs(s,o);return Object.freeze({getPublicKey:o,getSharedSecret:function(t,r,i=!0){if(!0===a(t))throw new Error("first arg must be private key");if(!1===a(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=a*Fa<s.ORDER;function y(e){return e>a>>Ma}function b(e,t){if(!o.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){Aa(t);const n=h.signature;return Xr(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}=Ia.toSig(Xr(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(o.fromBytes(i),o.fromBytes(s),n)}static fromHex(e,t){return this.fromBytes(di(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+a: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(ci(Na(!(1&i)),d)),l=o.inv(u),p=P(Xr(t,void 0,"msgHash")),h=o.create(-p*l),f=o.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(Aa(e),"der"===e)return di(Ia.hexFromSig(this));const{r:t,s:n}=this,r=o.toBytes(t),i=o.toBytes(n);return"recovered"===e?(g(),ci(Uint8Array.of(this.assertRecovery()),r,i)):ci(r,i)}toHex(e){return ai(this.toBytes(e))}}const T=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=es(e),n=8*e.length-u;return n>0?t>>BigInt(n):t},P=n.bits2int_modN||function(e){return o.create(T(e))},x=as(u);function E(e){return os("num < 2^"+u,e,Da,x),o.toBytes(e)}function S(e,n){return Xr(e,void 0,"message"),n?Xr(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,a={}){const{seed:u,k2sig:d}=function(t,n,i){const{lowS:s,prehash:a,extraEntropy:u}=ka(i,f);t=S(t,a);const d=P(t),c=o.fromBytes(n);if(!o.isValidNot0(c))throw new Error("invalid private key");const l=[E(c),E(d)];if(null!=u&&!1!==u){const e=!0===u?r(h.secretKey):u;l.push(Xr(e,void 0,"extraEntropy"))}const p=ci(...l),b=d;return{seed:p,k2sig:function(t){const n=T(t);if(!o.isValidNot0(n))return;const r=o.inv(n),i=e.BASE.multiply(n).toAffine(),a=o.create(i.x);if(a===Da)return;const u=o.create(r*o.create(b+a*c));if(u===Da)return;let d=(i.x===a?0:2)|Number(i.y&Ma),l=u;return s&&y(u)&&(l=o.neg(u),d^=1),new w(a,l,m?void 0:d)}}}(n,s,a),c=function(e,t,n){if(Zr(e,"hashLen"),Zr(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),o=Uint8Array.of(1);let a=r(e),u=r(e),d=0;const c=()=>{a.fill(1),u.fill(0),d=0},l=(...e)=>n(u,ci(a,...e)),p=(e=i)=>{u=l(s,e),a=l(),0!==e.length&&(u=l(o,e),a=l())},h=()=>{if(d++>=1e3)throw new Error("drbg: tried max amount of iterations");let e=0;const n=[];for(;e<t;){a=l();const t=a.slice();n.push(t),e+=a.length}return ci(...n)};return(e,t)=>{let n;for(c(),p(e);!(n=t(h()));)p();return c(),n}}(t.outputLen,o.BYTES,i);return c(u,d).toBytes(a.format)},verify:function(t,n,r,i={}){const{lowS:s,prehash:a,format:u}=ka(i,f);if(r=Xr(r,void 0,"publicKey"),n=S(n,a),!Jr(t))throw new Error("verify expects Uint8Array signature"+(t instanceof w?", use sig.toBytes()":""));v(t,u);try{const i=w.fromBytes(t,u),a=e.fromBytes(r);if(s&&i.hasHighS())return!1;const{r:d,s:c}=i,l=P(n),p=o.inv(c),h=o.create(l*p),f=o.create(d*p),m=e.BASE.multiplyUnsafe(h).add(a.multiplyUnsafe(f));return!m.is0()&&o.create(m.x)===d}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=ka(n,f);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}const Ua={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ja={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},qa=/* @__PURE__ */BigInt(2),$a=Ms(Ua.p,{sqrt:function(e){const t=Ua.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),u=BigInt(88),d=e*e*e%t,c=d*d*e%t,l=Ts(c,n,t)*c%t,p=Ts(l,n,t)*c%t,h=Ts(p,qa,t)*d%t,f=Ts(h,i,t)*h%t,m=Ts(f,s,t)*f%t,y=Ts(m,a,t)*m%t,b=Ts(y,u,t)*y%t,g=Ts(b,a,t)*m%t,v=Ts(g,n,t)*c%t,w=Ts(v,o,t)*f%t,T=Ts(w,r,t)*d%t,P=Ts(T,qa,t);if(!$a.eql($a.sqr(P),e))throw new Error("Cannot find square root");return P}}),za=/* @__PURE__ */Ba(/* @__PURE__ */_a(Ua,{Fp:$a,endo:ja}),Ki);class Va{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return za.Point.fromBytes(e),e}catch(e){throw new ct(String(e))}}(e),this.raw=function(e){return za.Point.fromBytes(e).toBytes()}(this._key)}toMultihash(){return Qn(Wa(this))}toCID(){return zn.createV1(114,this.toMultihash())}toString(){return on.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(this.raw,e.raw)}verify(e,t,n){return function(e,t,n,r){const i=xr.digest(n instanceof Uint8Array?n:n.subarray());if(bo(i))return i.then(({digest:n})=>(r?.signal?.throwIfAborted(),za.verify(t,n,e,{prehash:!1,format:"der"}))).catch(e=>{if("AbortError"===e.name)throw e;throw new po(String(e))});try{return r?.signal?.throwIfAborted(),za.verify(t,i.digest,e,{prehash:!1,format:"der"})}catch(e){throw new po(String(e))}}(this._key,t,e,n)}}function Ga(e){return new Va(e)}function Ka(e,t){const{Type:n,Data:r}=ga.decode(e),i=r??new Uint8Array;switch(n){case ya.RSA:return function(e,t){if(e.byteLength>=1062)throw new ct("Key size is too large");return function(e,t,n){const r=function(e){const t=_r(e[1],{offset:0});return{kty:"RSA",n:Dr(t[0],"base64url"),e:Dr(t[1],"base64url")}}(e);return null==n&&(n=On(18,Ki(ga.encode({Type:ya.RSA,Data:t})))),new Ta(r,n)}(_r(e,{offset:0}),e,t)}(i,t);case ya.Ed25519:return wo(i);case ya.secp256k1:return Ga(i);case ya.ECDSA:return Hr(i);default:throw new Ft}}function Wa(e){return ga.encode({Type:ya[e.type],Data:e.raw})}const Ha=Symbol.for("nodejs.util.inspect.custom");class Qa{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()})`}[Bt]=!0;toString(){return null==this.string&&(this.string=on.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return zn.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Yn(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Yn(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ha](){return`PeerId(${this.toString()})`}}class Ya extends Qa{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Ja extends Qa{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Za extends Qa{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class Xa{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Qn(Ir(this.url))}[Ha](){return`PeerId(${this.url})`}[Bt]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return zn.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=Dr(e)),e.toString()===this.toString())}}function eu(e,t){let n;if("1"===e.charAt(0)||"Q"===e.charAt(0))n=Bn(on.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return ru(zn.parse(e));if(null==t)throw new dt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');n=Bn(t.decode(e))}return nu(n)}function tu(e){if("Ed25519"===e.type)return new Ja({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Za({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Ya({multihash:e.toCID().multihash,publicKey:e});throw new Ft}function nu(e){if(function(e){return e.code===xr.code}(e))return new Ya({multihash:e});if(function(e){return 0===e.code}(e))try{const t=function(e){const{Type:t,Data:n}=ga.decode(e.digest),r=n??new Uint8Array;switch(t){case ya.Ed25519:return wo(r);case ya.secp256k1:return Ga(r);case ya.ECDSA:return Hr(r);default:throw new Ft}}(e);if("Ed25519"===t.type)return new Ja({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Za({multihash:e,publicKey:t})}catch(t){const n=Dr(e.digest);return new Xa(new URL(n))}throw new Tt("Supplied PeerID Multihash is invalid")}function ru(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new wt("Supplied PeerID CID is invalid");if(2336===e.code){const t=Dr(e.multihash.digest);return new Xa(new URL(t))}return nu(e.multihash)}class iu extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class su extends Error{static name="ValidationError";name="ValidationError"}class ou extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class au extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const uu=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 o=this.peekChar();if(void 0===o)return;const a="0"===o,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&&a&&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),[o]=e(i.subarray(0,s));return t.set(i.subarray(0,o),16-o),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function du(e){if(!(e.length>15))return uu.new(e).parseWith(()=>uu.readIPv4Addr())}function cu(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return uu.new(e).parseWith(()=>uu.readIPv6Addr())}function lu(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const n=uu.new(e).parseWith(()=>uu.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 pu(e){return Boolean(du(e))}function hu(e){return Boolean(cu(e))}const fu=41,mu=421,yu=448,bu=449,gu=466,vu=281,wu=290;function Tu(e){return t=>Dr(t,e)}function Pu(e){return t=>Ir(t,e)}function xu(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Eu(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function Su(e){const t=e.subarray(0,e.length-2),n=e.subarray(e.length-2);return`${Dr(t,"base32")}:${xu(n)}`}const Au=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 iu("Invalid byte value in IP address");t[n]=r}),t},ku=Object.values(Er).map(e=>e.decoder),Cu=function(){let e=ku[0].or(ku[1]);return ku.slice(2).forEach(t=>e=e.or(t)),e}(),Iu=function(...e){return t=>{for(const n of e)n(t)}}(function(e){if(parseInt(e).toString()!==e)throw new su("Value must be an integer")},function(e){if(e<0)throw new su("Value must be a positive integer, or zero")},e=>{if(e>65535)throw new su("Value must be smaller than or equal to 65535")}),Du=-1,Mu=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 au(`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)}))}},Fu=[{code:4,name:"ip4",size:32,valueToBytes:Au,bytesToValue:function(e){if(4!==e.byteLength)throw new iu("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(!pu(e))throw new su(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Eu,bytesToValue:xu,validate:Iu},{code:273,name:"udp",size:16,valueToBytes:Eu,bytesToValue:xu,validate:Iu},{code:33,name:"dccp",size:16,valueToBytes:Eu,bytesToValue:xu,validate:Iu},{code:fu,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;pu(n[r])&&(e=Au(n[r]),n[r]=Dr(e.subarray(0,2),"base16")),null!=e&&++r<8&&n.splice(r,0,Dr(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 iu("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 iu("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 iu(`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 iu(`Invalid IPv6 address "${e}"`)}},validate:e=>{if(!hu(e))throw new su(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:Du},{code:43,name:"ipcidr",size:8,bytesToValue:Tu("base10"),valueToBytes:Pu("base10")},{code:53,name:"dns",size:Du},{code:54,name:"dns4",size:Du},{code:55,name:"dns6",size:Du},{code:56,name:"dnsaddr",size:Du},{code:132,name:"sctp",size:16,valueToBytes:Eu,bytesToValue:xu,validate:Iu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Du,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:mu,name:"p2p",aliases:["ipfs"],size:Du,bytesToValue:Tu("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Pu("base58btc")(e):zn.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Su,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=Ir(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=Eu(r);return Xn([n,i],n.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:Su,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=dn.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=Eu(r);return Xn([n,i],n.length+i.length)}},{code:446,name:"garlic64",size:Du},{code:447,name:"garlic32",size:Du},{code:yu,name:"tls"},{code:bu,name:"sni",size:Du},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:gu,name:"certhash",size:Du,bytesToValue:(Ru=fr,e=>Ru.encoder.encode(e)),valueToBytes:function(e){return Cu.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:Du,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:vu,name:"webrtc"},{code:wu,name:"p2p-circuit"},{code:777,name:"memory",size:Du}];var Ru;function Lu(e,t,n){return null==e.size||0===e.size?0:e.size>0?e.size/8:_o(t,n)}Fu.forEach(e=>{Mu.addProtocol(e)});const _u=Symbol.for("nodejs.util.inspect.custom"),Nu=Symbol.for("@multiformats/multiaddr");class Ou{[Nu]=!0;#t;#n;#r;constructor(e="/",t={}){this.#t=function(e){if(null==e&&(e="/"),Bu(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let n=0;for(;n<e.length;){const r=_o(e,n),i=Mu.getProtocol(r),s=Mo(r),o=Lu(i,e,n+s);let a=0;o>0&&i.size===Du&&(a=Mo(o));const u=s+a+o,d={code:r,name:i.name,bytes:e.subarray(n,n+u)};if(o>0){const t=n+s+a,r=e.subarray(t,t+o);d.value=i.bytesToValue?.(r)??Dr(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 iu('String multiaddr must start with "/"');const t=[];let n="protocol",r="",i="";for(let s=1;s<e.length;s++){const o=e.charAt(s);"/"!==o&&("protocol"===n?i+=e.charAt(s):r+=e.charAt(s));const a=s===e.length-1;if("/"===o||a){const e=Mu.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(a)throw new iu(`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 iu(`Component ${i} was missing value`);s.value=e.stringToValue?.(r)??r}t.push(s),r="",i="",n="protocol"}}}if(""!==i&&""!==r)throw new iu("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new iu("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach(e=>{const t=Mu.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=Mu.getProtocol(r.code),t=Mo(r.code);let n,i=0,s=0;null!=r.value&&(n=e.valueToBytes?.(r.value)??Ir(r.value),i=n.byteLength,e.size===Du&&(s=Mo(i)));const o=new Uint8Array(t+s+i);let a=0;Fo(r.code,o,a),a+=t,null!=n&&(e.size===Du&&(Fo(i,o,a),a+=s),o.set(n,a)),r.bytes=o}n.push(r.bytes),t+=r.bytes.byteLength}return Xn(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=Mu.getProtocol(e.code);if(null==t)throw new iu(`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 Ou(e);return new Ou([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),n=this.toString(),r=n.lastIndexOf(t);if(r<0)throw new ou(`Address ${this.toString()} does not contain subaddress: ${t}`);return new Ou(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 Ou(this.#t.slice(0,t),{validate:!1})}equals(e){return Yn(this.bytes,e.bytes)}[_u](){return`Multiaddr(${this.toString()})`}}function Bu(e){return Boolean(e?.[Nu])}function Uu(e){return new Ou(e)}function ju(e){return Array.from(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function qu(e){for(var t,n=e.reduce(function(e,t){return e+t.length},0),r=new Uint8Array(n),i=0,s=M(e);!(t=s()).done;){var o=t.value;r.set(o,i),i+=o.length}return r}function $u(e,t){var n=v.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"+ju(t)}(e)),r=w(n.toHex(),(new TextEncoder).encode(t));return ju(new Uint8Array(r))}function zu(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Vu=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getAuthorization=function(e){return RT(e)},t.getSignedCommandParams=function(e,t,n,r,i,s){try{var o,a=function(a){if(o)return a;function d(){function o(){return Promise.resolve(FT(t)).then(function(o){return Promise.resolve(u.getNonce(e,o,r,i,s)).then(function(e){var r=(e+1).toString();return Promise.resolve(MT(t,r,n)).then(function(e){if(!e)throw new Error("Could not sign persistent storage request.");return{consumerAddress:o,nonce:r,signature:e}})})})}var a=function(){if(!s)return Promise.resolve(u.getServiceEndpoints(e,i)).then(function(e){s=e})}();return a&&a.then?a.then(o):o()}var c=function(){if(!i)return Promise.resolve(u.getEndpoints(e)).then(function(e){i=e})}();return c&&c.then?c.then(d):d()},u=this;if(LT(t))return Promise.resolve({consumerAddress:t.consumerAddress,nonce:t.nonce,signature:t.signature});var d=function(){if("string"==typeof t)return Promise.resolve(FT(t)).then(function(e){return o=1,{consumerAddress:e,nonce:void 0,signature:void 0}})}();return Promise.resolve(d&&d.then?d.then(a):a(d))}catch(e){return Promise.reject(e)}},t.resolvePersistentStorageRoute=function(e,t,n,r){for(var i,s=M(n);!(i=s()).done;){var o=this.getEndpointURL(t,i.value);if(null!=o&&o.urlPath)return o.urlPath}return e.replace(/\/+$/,"")+r},t.getEndpoints=function(e,t){try{var n=this;return Promise.resolve(zu(function(){return Promise.resolve(n.getData(e,t)).then(function(e){return Promise.resolve(e.json())})},function(e){throw q.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?zu(function(){return Promise.resolve(y(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 q.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),zu(function(){return Promise.resolve(y(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 q.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=o.getEndpointURL(i,"nonce")?o.getEndpointURL(i,"nonce").urlPath:null;return e?zu(function(){return Promise.resolve(y(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 q.error(e),new Error(e.message)}):null}var a=function(){if(!i)return Promise.resolve(o.getServiceEndpoints(e,r)).then(function(e){i=e})}();return a&&a.then?a.then(s):s()},o=this,a=function(){if(!r)return Promise.resolve(o.getEndpoints(e)).then(function(e){r=e})}();return Promise.resolve(a&&a.then?a.then(s):s())}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.getEndpoints(n)).then(function(i){return Promise.resolve(o.getServiceEndpoints(n,i)).then(function(a){return Promise.resolve(o.getSignedCommandParams(n,r,E.ENCRYPT,s,i,a)).then(function(n){var r=n.consumerAddress,i=n.nonce,u=n.signature,d=(o.getEndpointURL(a,"encrypt")?o.getEndpointURL(a,"encrypt").urlPath:null)+"?chainId="+t;return d?(i&&(d+="&nonce="+i),r&&(d+="&consumerAddress="+r),u&&(d+="&signature="+u),zu(function(){return Promise.resolve(y(d,{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 q.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(o){return Promise.resolve(s.getServiceEndpoints(n,o)).then(function(n){function o(e){var t;function n(e){return t?e:Promise.resolve(a.json()).then(function(e){throw q.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=M(e);!(n=r()).done;)d.push(n.value);return t=1,d})}();return r&&r.then?r.then(n):n(r)}var a,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=zu(function(){return Promise.resolve(y(c,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json"},signal:i})).then(function(e){a=e})},function(e){throw q.error("File info call failed: "),q.error(e),new Error(e)});return l&&l.then?l.then(o):o()})})}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(o.json()).then(function(e){throw q.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=M(e);!(n=r()).done;)u.push(n.value);return t=1,u})}();return r&&r.then?r.then(n):n(r)}var o,a=F({},e,{checksum:n}),u=[],d=i.getEndpointURL(t,"fileinfo")?i.getEndpointURL(t,"fileinfo").urlPath:null;if(!d)return null;var c=zu(function(){return Promise.resolve(y(d,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){o=e})},function(e){throw q.error("File info call failed: "),q.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 q.error("Fetch compute env failed: ",s.status,s.statusText,e),new Error(JSON.stringify(e))})}var s,o=null==(r=n.getEndpointURL(e,"computeEnvironments"))?void 0:r.urlPath;if(!o)return null;var a=zu(function(){return Promise.resolve(y(o,{method:"GET",headers:{"Content-Type":"application/json"},signal:t})).then(function(e){s=e})},function(e){throw q.error("Fetch compute env failed: "),q.error(e),new Error(e)});return a&&a.then?a.then(i):i()})})}catch(e){return Promise.reject(e)}},t.initialize=function(e,t,n,r,i,s,o,a,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 q.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,o&&(p+="&userdata="+encodeURI(JSON.stringify(o))),a&&(p+="&environment="+encodeURI(a)),u&&(p+="&validUntil="+u);var h=zu(function(){return Promise.resolve(y(p,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})).then(function(e){l=e})},function(e){throw q.error("Provider initialized failed: "),q.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,o,a,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 b(){function e(){var e;function t(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw q.error("Initialize compute failed: ",e.status,e.statusText,t),q.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(t))})}var i=function(t){if(null!=(t=e)&&t.ok)return Promise.resolve(e.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var n=zu(function(){return Promise.resolve(y(g,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json"},signal:c})).then(function(t){return e=t,function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(""+e)})}()})},function(e){throw q.error("Initialize compute failed: "),q.error(e),new Error("ComputeJob cannot be initialized: "+e.message+".")});return n&&n.then?n.then(t):t()}var t=function(){if(h)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(v.output=$u(e,JSON.stringify(h)))})}();return t&&t.then?t.then(e):e()}var g=f.getEndpointURL(m,"initializeCompute")?f.getEndpointURL(m,"initializeCompute").urlPath:null;if(!g)return null;var v={datasets:e,algorithm:t,environment:n,payment:{chainId:u,token:r,resources:a},maxJobDuration:i,consumerAddress:o};d&&(v.policyServer=d),l&&(v.queueMaxWaitTime=l);var w=function(){if(p)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(v.encryptedDockerRegistryAuth=$u(e,JSON.stringify(p)))})}();return w&&w.then?w.then(b):b()})})}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,o,a){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.getSignedCommandParams(i,s,E.DOWNLOAD,void 0,d,c)).then(function(i){var s=i.consumerAddress,u=i.nonce,d=i.signature,c=l;return c+="?fileIndex="+n,c+="&documentId="+e,c+="&transferTxId="+r,c+="&serviceId="+t,s&&(c+="&consumerAddress="+s),u&&(c+="&nonce="+u),d&&(c+="&signature="+d),o&&(c+="&policyServer="+encodeURI(JSON.stringify(o))),a&&(c+="&userdata="+encodeURI(JSON.stringify(a))),c}):null})})}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h,f,m){try{var b=this;return Promise.resolve(b.getEndpoints(e)).then(function(g){return Promise.resolve(b.getServiceEndpoints(e,g)).then(function(v){var w=b.getEndpointURL(v,"computeStart")?b.getEndpointURL(v,"computeStart").urlPath:null;return w?Promise.resolve(b.getSignedCommandParams(e,t,E.COMPUTE_START,h,g,v)).then(function(g){var v=g.consumerAddress,T=g.nonce,P=g.signature;function x(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw q.error("Compute start failed: ",e.status,e.statusText,t),q.error("Payload was:",E),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&&(E.policyServer=p),f&&(E.queueMaxWaitTime=f);var r=zu(function(){var n=b.getAuthorization(t);return Promise.resolve(y(w,{method:"POST",body:JSON.stringify(E),headers:F({"Content-Type":"application/json"},n?{Authorization:n}:{}),signal:h})).then(function(t){e=t})},function(e){throw q.error("Compute start failed:"),q.error(e),q.error("Payload was:",E),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}a&&(E.resources=a),d&&(E.metadata=d),c&&(E.additionalViewers=c);var r=function(){if(l)return Promise.resolve(b.getNodePublicKey(e)).then(function(e){e&&(E.output=$u(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var E=Object();E.consumerAddress=v,E.signature=P,E.nonce=T,E.environment=n,E.maxJobDuration=s,E.resources=a,E.dataset=r[0],E.datasets=r,E.algorithm=i,E.chainId=u,E.payment={chainId:u,token:o,maxJobDuration:s,resources:a};var S=function(){if(m)return Promise.resolve(b.getNodePublicKey(e)).then(function(e){e&&(E.encryptedDockerRegistryAuth=$u(e,JSON.stringify(m)))})}();return S&&S.then?S.then(x):x()}):(q.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,o,a,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 b=h.getEndpointURL(m,"freeCompute")?h.getEndpointURL(m,"freeCompute").urlPath:null;return b?Promise.resolve(h.getSignedCommandParams(e,t,E.FREE_COMPUTE_START,c,f,m)).then(function(f){var m=f.consumerAddress,g=f.nonce,v=f.signature;function w(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw q.error("Compute start failed: ",e.status,e.statusText,t),q.error("Payload was:",T),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&&(T.policyServer=d),l&&(T.queueMaxWaitTime=l);var r=zu(function(){var n=h.getAuthorization(t);return Promise.resolve(y(b,{method:"POST",body:JSON.stringify(T),headers:F({"Content-Type":"application/json"},n?{Authorization:n}:{}),signal:c})).then(function(t){e=t})},function(e){throw q.error("Compute start failed:"),q.error(e),q.error("Payload was:",T),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&&(T.output=$u(e,JSON.stringify(u)))})}();return r&&r.then?r.then(n):n()}var T=Object();T.consumerAddress=m,T.signature=v,T.nonce=g,T.environment=n,T.resources=s,T.dataset=r[0],T.datasets=r,T.algorithm=i,o&&(T.metadata=o),a&&(T.additionalViewers=a);var P=function(){if(p)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(T.encryptedDockerRegistryAuth=$u(e,JSON.stringify(p)))})}();return P&&P.then?P.then(w):w()}):(q.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;return Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(o){var a=i.getEndpointURL(o,"computeStreamableLogs")?i.getEndpointURL(o,"computeStreamableLogs").urlPath:null;return a?Promise.resolve(i.getSignedCommandParams(e,t,E.COMPUTE_GET_STREAMABLE_LOGS,r,s,o)).then(function(e){var s=e.consumerAddress,o=e.nonce,u=e.signature;function d(e){var t,n;if(null!=(t=c)&&t.ok||200===(null==(n=c)?void 0:n.status))return c.body;var r=q.error,i=c.statusText,s=c.status;return Promise.resolve(c.json()).then(function(e){return r.call(q,"computeStreamableLogs failed: ",s,i,e),null})}var c,l="?jobId="+n;s&&(l+="&consumerAddress="+s),u&&(l+="&signature="+u),o&&(l+="&nonce="+o);var p=zu(function(){var e=i.getAuthorization(t);return Promise.resolve(y(a+l,{method:"GET",headers:F({"Content-Type":"application/json"},e?{Authorization:e}:{}),signal:r})).then(function(e){c=e})},function(e){throw q.error("computeStreamableLogs failed:"),q.error(e),new Error("HTTP request failed calling Provider")});return p&&p.then?p.then(d):d()}):(q.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;return Promise.resolve(s.getEndpoints(t)).then(function(o){return Promise.resolve(s.getServiceEndpoints(t,o)).then(function(a){var u=s.getEndpointURL(a,"computeStop")?s.getEndpointURL(a,"computeStop").urlPath:null;return Promise.resolve(s.getSignedCommandParams(t,n,E.COMPUTE_STOP,i,o,a)).then(function(t){var o=t.consumerAddress,a=t.nonce,d=t.signature;function c(e){var t;function n(e){return t?e:Promise.resolve(p.json()).then(function(e){throw q.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;o&&l.set("consumerAddress",o),a&&l.set("nonce",a),d&&l.set("signature",d),l.set("jobId",e),r&&l.set("agreementId",r);var p,h=l.toString();if(!h)return null;var f=zu(function(){var e=s.getAuthorization(n);return Promise.resolve(y(u+"?"+h,{method:"PUT",headers:F({"Content-Type":"application/json"},e?{Authorization:e}:{}),signal:i})).then(function(e){p=e})},function(e){throw q.error("Compute stop failed:"),q.error(e),new Error("HTTP request failed calling Provider")});return f&&f.then?f.then(c):c()})})})}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{var s=this;return Promise.resolve(FT(t)).then(function(o){return Promise.resolve(s.getEndpoints(e)).then(function(a){return Promise.resolve(s.getServiceEndpoints(e,a)).then(function(e){function a(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 q.error("Get compute status failed:",u.status,u.statusText,e),new Error(JSON.stringify(e))})}q.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="+o;if(c+=r&&"&agreementId="+r||"",c+=n&&"&jobId="+n||"",!d)return null;var l=zu(function(){var e=s.getAuthorization(t);return Promise.resolve(y(d+c,{method:"GET",headers:F({"Content-Type":"application/json"},e?{Authorization:e}:{}),signal:i})).then(function(e){u=e})},function(e){throw q.error("Get compute status failed"),q.error(e),new Error(e)});return l&&l.then?l.then(a):a()})})})}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(o){return Promise.resolve(i.getServiceEndpoints(e,o)).then(function(a){var u=i.getEndpointURL(a,"computeResult")?i.getEndpointURL(a,"computeResult").urlPath:null;return Promise.resolve(i.getSignedCommandParams(e,t,E.COMPUTE_GET_RESULT,void 0,o,a)).then(function(e){var t=e.nonce,i=e.signature;if(!u)return null;var o=u;return o+="?consumerAddress="+e.consumerAddress,o+="&jobId="+n,o+="&index="+r.toString(),s||(o+="&nonce="+t,o+="&signature="+i),o})})})}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(y(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(o){var a=r.getEndpointURL(o,"generateAuthToken").urlPath||null;return Promise.resolve(r.getNonce(t,i,n,s,o)).then(function(t){var r=(t+1).toString();return Promise.resolve(MT(e,r,E.CREATE_AUTH_TOKEN)).then(function(e){return zu(function(){return Promise.resolve(y(a,{method:"POST",body:JSON.stringify({address:i,signature:e,nonce:r}),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 q.error("Generate auth token failed:"),q.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(o){return Promise.resolve(i.getServiceEndpoints(n,o)).then(function(a){var u=i.getEndpointURL(a,"invalidateAuthToken").urlPath||null;return Promise.resolve(i.getNonce(n,s,r,o,a)).then(function(n){var i=(n+1).toString();return Promise.resolve(nt(e,s+i)).then(function(e){return zu(function(){return Promise.resolve(y(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 q.error("Generate auth token failed:"),q.error(e),new Error("HTTP request failed calling Provider")})})})})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){try{return Promise.resolve(zu(function(){return Promise.resolve(y(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 q.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 q.error("PolicyServerPassthrough failed: ",s.status,s.statusText,e),q.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,o=r.getEndpointURL(e,"PolicyServerPassthrough")?r.getEndpointURL(e,"PolicyServerPassthrough").urlPath:null;if(!o)return null;var a=zu(function(){return Promise.resolve(y(o,{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 q.error("PolicyServerPassthrough failed: "),q.error(e),new Error("PolicyServerPassthrough failed: "+e.message+".")});return a&&a.then?a.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 q.error("initializePSVerification failed: ",s.status,s.statusText,e),q.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,o=r.getEndpointURL(e,"initializePSVerification")?r.getEndpointURL(e,"initializePSVerification").urlPath:null;if(!o)return null;var a=zu(function(){return Promise.resolve(y(o,{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 q.error("initializePSVerification failed: "),q.error(e),new Error("initializePSVerification failed: "+e.message+".")});return a&&a.then?a.then(i):i()})})}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,o,a,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(d.getSignedCommandParams(e,t,E.GET_LOGS,u,c,l)).then(function(e){var c=e.consumerAddress,l=e.nonce,h=e.signature;function f(e){var t;return null!=(t=m)&&t.ok?m.body:Promise.resolve(m.json()).then(function(e){throw q.error("Download node logs failed: ",m.status,m.statusText,e),new Error(JSON.stringify(e))})}var m,b=p+"?startTime="+n+"&endTime="+r;i&&(b+="&maxLogs="+i),s&&(b+="&moduleName="+s),o&&(b+="&level="+o),a&&(b+="&page="+a);var g=zu(function(){var e=d.getAuthorization(t);return Promise.resolve(y(b,{method:"POST",body:JSON.stringify({signature:h,nonce:l,address:c}),headers:F({"Content-Type":"application/json"},e?{Authorization:e}:{}),signal:u})).then(function(e){m=e})},function(e){throw q.error("Download node logs failed:"),q.error(e),new Error("HTTP request failed calling Provider")});return g&&g.then?g.then(f):f()}):(q.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 q.debug("Not input string:"),q.debug(e),new Error("["+n+"] Expected string, input type: "+typeof e);var r=e.match(t);return r?{valid:!0,output:r[1]}:(q.warn("["+n+"] Input transformation failed."),{valid:!1,output:e})},t.resolveDdo=function(e,t,n){try{return Promise.resolve(y(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(i.getSignedCommandParams(e,n,E.VALIDATE_DDO,r)).then(function(s){var o=s.consumerAddress,a=s.nonce,u=s.signature,d=i.getAuthorization(n);return Promise.resolve(y(e+"/api/aquarius/assets/ddo/validate",{method:"POST",body:JSON.stringify({ddo:t,publisherAddress:o,nonce:a,signature:u}),headers:F({"Content-Type":"application/json"},d?{Authorization:d}:{}),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(y(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 o=i.resolvePersistentStorageRoute(e,s,["persistentStorageCreateBucket"],"/api/services/persistentStorage/buckets");return Promise.resolve(i.getSignedCommandParams(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(y(o,{method:"POST",headers:s,body:JSON.stringify(F({},e,{accessLists:null!=(i=n.accessLists)?i:[],label:n.label})),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 o=i.resolvePersistentStorageRoute(e,s,["persistentStorageGetBuckets"],"/api/services/persistentStorage/buckets");return Promise.resolve(i.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_GET_BUCKETS,r)).then(function(e){var i={};"string"==typeof t&&(i.Authorization=t);var s=new URLSearchParams(F({},e,{owner:n}));return Promise.resolve(y(o+"?"+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 o=i.resolvePersistentStorageRoute(e,s,["persistentStorageListFiles"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files");return Promise.resolve(i.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(e){var n={};"string"==typeof t&&(n.Authorization=t);var i=new URLSearchParams(F({},e));return Promise.resolve(y(o+"?"+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(o){return Promise.resolve(s.getServiceEndpoints(e,o)).then(function(o){var a=s.resolvePersistentStorageRoute(e,o,["persistentStorageGetFileObject"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r)+"/object");return Promise.resolve(s.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(e){var n=new URLSearchParams(F({},e)),r={};return"string"==typeof t&&(r.Authorization=t),Promise.resolve(y(a+"?"+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 o=this;return Promise.resolve(o.getEndpoints(e)).then(function(a){return Promise.resolve(o.getServiceEndpoints(e,a)).then(function(a){var u=o.resolvePersistentStorageRoute(e,a,["persistentStorageUploadFile"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r));return Promise.resolve(o.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(e){function n(e){var n=o.getAuthorization(t);return Promise.resolve(y(u+"?"+a.toString(),{method:"POST",body:r,headers:F({"Content-Type":"application/octet-stream"},n?{Authorization: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,a=new URLSearchParams(F({},e)),d=function(){if("undefined"==typeof window)return Promise.resolve(import("stream")).then(function(e){var t=e.Readable,n=new TextEncoder,s=N(/*#__PURE__*/L().mark(function e(){var t,r,s,o,a,u,d;return L().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=!1,r=!1,e.prev=2,o=C(i);case 4:return e.next=6,D(o.next());case 6:if(!(t=!(a=e.sent).done)){e.next=25;break}if(!((u=a.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==o.return){e.next=36;break}return e.next=36,D(o.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(o){return Promise.resolve(s.getServiceEndpoints(e,o)).then(function(o){var a=s.resolvePersistentStorageRoute(e,o,["persistentStorageDeleteFile"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r));return Promise.resolve(s.getSignedCommandParams(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(F({},e));return Promise.resolve(y(a+"?"+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)}},t.updatePersistentStorageBucket=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getEndpoints(e)).then(function(o){return Promise.resolve(s.getServiceEndpoints(e,o)).then(function(o){var a=s.resolvePersistentStorageRoute(e,o,["persistentStorageUpdateBucket"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n));return Promise.resolve(s.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_UPDATE_BUCKET,i)).then(function(e){var n={"Content-Type":"application/json"};"string"==typeof t&&(n.Authorization=t);var s=new URLSearchParams(F({},e));return Promise.resolve(y(a+"?"+s.toString(),{method:"PATCH",headers:n,body:JSON.stringify({label: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)}},e}();async function Gu(e){if(null===e.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new dt("Private network is enforced, but no protector was provided");return e}const Ku=1e3,Wu=60*Ku,Hu=60*Wu,Qu=24*Hu,Yu=7*Qu,Ju=365.25*Qu,Zu=Ju/12;var Xu=function(e,t){if("string"==typeof e)return ed(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?nd(e):td(e)}(e,t);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(e)}`)};function ed(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*Ju;case"months":case"month":case"mo":return i*Zu;case"weeks":case"week":case"w":return i*Yu;case"days":case"day":case"d":return i*Qu;case"hours":case"hour":case"hrs":case"hr":case"h":return i*Hu;case"minutes":case"minute":case"mins":case"min":case"m":return i*Wu;case"seconds":case"second":case"secs":case"sec":case"s":return i*Ku;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 td(e){let t=Math.abs(e);return t>=Ju?`${Math.round(e/Ju)}y`:t>=Zu?`${Math.round(e/Zu)}mo`:t>=Yu?`${Math.round(e/Yu)}w`:t>=Qu?`${Math.round(e/Qu)}d`:t>=Hu?`${Math.round(e/Hu)}h`:t>=Wu?`${Math.round(e/Wu)}m`:t>=Ku?`${Math.round(e/Ku)}s`:`${e}ms`}function nd(e){let t=Math.abs(e);return t>=Ju?rd(e,t,Ju,"year"):t>=Zu?rd(e,t,Zu,"month"):t>=Yu?rd(e,t,Yu,"week"):t>=Qu?rd(e,t,Qu,"day"):t>=Hu?rd(e,t,Hu,"hour"):t>=Wu?rd(e,t,Wu,"minute"):t>=Ku?rd(e,t,Ku,"second"):`${e} ms`}function rd(e,t,n,r){let i=t>=1.5*n;return`${Math.round(e/n)} ${r}${i?"s":""}`}const id=function(){try{return localStorage}catch(e){}}(),sd=console.debug??console.log??(()=>{});var od=function(e){function t(e,r){let i,s,o,a=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 o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";o++;const s=t.formatters[i];return"function"==typeof s&&(r=s.call(n,e[o]),e.splice(o,1),o--),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!==a?a:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{a=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=Xu,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 ":" ")+"+"+Xu(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?id?.setItem("debug",e):id?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=id?.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:id,log:sd});function ad(e,t=""){const n=ld(e.message),r=ld(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 ud(e,t=""){if(function(e){return e instanceof AggregateError||"AggregateError"===e?.name&&Array.isArray(e.errors)}(e)){let n=ad(e,t);return n+=e.errors.length>0?`\n${t=`${t} `}${e.errors.map(e=>`${ud(e,`${t}`)}`).join(`\n${t}`)}`:`\n${t}[Error list was empty]`,n.trim()}return ad(e,t)}function dd(e){return{forComponent:t=>cd(t,e)}}function cd(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 od.enabled(`${e}:trace`)&&null!=od.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(n=od(`${e}:trace`,t)),Object.assign(od(e,t),{error:od(`${e}:error`,t),trace:n,newScope:n=>cd(`${e}:${n}`,t)})}function ld(e){if(null!=e&&0!==(e=e.trim()).length)return e}function pd(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 hd(e){return nu(Bn(on.decode(`z${e}`)))}od.formatters.b=e=>null==e?"undefined":on.baseEncode(e),od.formatters.t=e=>null==e?"undefined":dn.baseEncode(e),od.formatters.m=e=>null==e?"undefined":pr.baseEncode(e),od.formatters.p=e=>null==e?"undefined":e.toString(),od.formatters.c=e=>null==e?"undefined":e.toString(),od.formatters.k=e=>null==e?"undefined":e.toString(),od.formatters.a=e=>null==e?"undefined":e.toString(),od.formatters.e=e=>null==e?"undefined":ud(e);class fd{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 pd(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 pd(this.map.values(),e=>e.key)}values(){return pd(this.map.values(),e=>e.value)}get size(){return this.map.size}}class md{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 pd(this.set.entries(),e=>{const t=hd(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{const n=hd(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return pd(this.set.values(),e=>hd(e))}intersection(e){const t=new md;for(const n of e)this.has(n)&&t.add(n);return t}difference(e){const t=new md;for(const n of this)e.has(n)||t.add(n);return t}union(e){const t=new md;for(const n of e)t.add(n);for(const e of this)t.add(e);return t}}const yd={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},bd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},gd=new globalThis.TextEncoder,vd={hash:e=>Number(function(e,{size:t=32,utf8Buffer:n}={}){if(!yd[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=yd[t];let i=bd[t],s=e;for(;s.length>0;){const e=gd.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=gd.encode(e)}return function(e,t){const n=yd[t];let r=bd[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}`),Ir(t,"base16")}(vd.hash(e,t))};class wd{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=Jn(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&&Yn(this.fp,e.fp)}}function Td(e,t){return Math.floor(Math.random()*(t-e))+e}class Pd{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof wd))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof wd))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 wd))throw new TypeError("Invalid Fingerprint");const t=Td(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof wd))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex(t=>e.equals(t));return t>-1&&(this.contents[t]=null,!0)}}class xd{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??vd,this.seed=e.seed??Td(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=Ir(e));const t=new wd(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 Pd(this.bucketSize)),null==this.buckets[r]&&(this.buckets[r]=new Pd(this.bucketSize)),this.buckets[n].add(t)||this.buckets[r].add(t))return this.count++,!0;const i=[n,r];let s=i[Td(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new Pd(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 Pd(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=Ir(e));const t=new wd(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=Ir(e));const t=new wd(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 Ed={1:.5,2:.84,4:.95,8:.98};function Sd(e,t=.001){const n=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/Ed[n]),bucketSize:n,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*n)),64)}}class Ad{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??vd,this.seed=e.seed??Td(0,Math.pow(2,10)),this.filterSeries=[new xd({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=Ir(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 xd({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=Ir(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=Ir(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 kd(e,t=.001,n){return new Ad({...Sd(e,t),...n??{}})}function Cd(e){const t=e.getComponents(),n={};let r=0;return"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?null:("tls"===t[r]?.name&&"sni"===t[r+1]?.name&&(n.sni=t[r+1].value,r+=2),n)}function Id(e){const t=Cd(e);if(null==t)throw new dt(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}const Dd=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Md(e,t){16===t.length&&4===e.length&&function(e){let t=0;for(const n of e)if(!(t<0)){if(t>11)break;if(255!==n)return!1;t++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t){let n=0;for(const r of e)if(!(n<0)){if(n>11)break;if(r!==t[n])return!1;n++}return!0}(e,Dd)&&(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 Fd(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 Rd{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=du(t);if(null==i&&(r=16,i=cu(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 o=Fd(s,8*r);return{network:Md(i,o),mask:o}}(e));else{const n=lu(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=lu(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=Fd(r,8*n.length);this.network=Md(n,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=lu(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 Ld(e){try{const n=Id(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 _d(e){return null!==Cd(e)}var Nd="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Od(e){var t={exports:{}};return e(t,t.exports),t.exports}var Bd=Od(function(e,t){(function(){var e,n,r,i,s,o,a,u;u=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,r,i,s,o;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=(o=n(e))[0],e=e.substring(o[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"),o=r("a"),s=r("A"),n=function(e){var t,n,a,u,d;for(u=0,t=10,n="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,n="7")),d=a;a<e.length;){if("0"<=e[a]&&e[a]<=n)u=u*t+(r(e[a])-i)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")u=u*t+(10+r(e[a])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;u=u*t+(10+r(e[a])-s)>>>0}}if(u>4294967295)throw new Error("too large");a++}if(a===d)throw new Error("empty octet");return[u,a]},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=a(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=(a(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):(a(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=a(this.first),n=a(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=a,t.long2ip=u,t.Netmask=e}).call(Nd)});const Ud=["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 Bd.Netmask(e));function jd(e){for(const t of Ud)if(t.contains(e))return!0;return!1}function qd(e){return pu(e)?jd(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 jd(`${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 jd(t[t.length-1])}(e):hu(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 $d(e){try{const t=Id(e);switch(t.type){case"ip4":case"ip6":return qd(t.host)??!1;default:return"localhost"===t.host}}catch{return!1}}function zd(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class Vd{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 Gd{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Vd(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 Vd(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 Kd extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Wd(e={}){return function(e,t){let n,r,i,s=(t=t??{}).onEnd,o=new Gd,a=zd();const u=e=>null!=r?r(e):(o.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=>(o=new Gd,null!=r?r({error:e}):(o.push({error:e}),n)))(e):u({done:!0}));if(n={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?i?{done:!0}:await new Promise((t,i)=>{r=s=>{r=null,o.push(s);try{t(e(o))}catch(e){i(e)}return n}}):e(o)}finally{o.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=zd()})}},return:()=>(o=new Gd,c(),{done:!0}),throw:e=>(c(e),{done:!0}),push:d,end:c,get readableLength(){return o.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let n,r;null!=t&&(n=new Promise((e,n)=>{r=()=>{n(new Kd)},t.addEventListener("abort",r)}));try{await Promise.race([a.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 Hd extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Hd)}}const Qd=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Yd(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 o=[t].flat(),a=[],{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)}a.push(t),n.count===a.length&&(r(),i(a))},l=(...e)=>{r(),s(n.rejectionMultiArgs?e:e[0])};r=()=>{for(const e of o)d(e,c);for(const e of n.rejectionEvents)o.includes(e)||d(e,l)};for(const e of o)u(e,c);for(const e of n.rejectionEvents)o.includes(e)||u(e,l);n.signal&&n.signal.addEventListener("abort",()=>{l(n.signal.reason)},{once:!0}),n.resolveImmediately&&i(a)});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:o}=t;let a,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(o?.aborted)return void d(Qd(o));if(o&&(u=()=>{d(Qd(o))},o.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Hd;a=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&&o&&o.removeEventListener("abort",u)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=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 Jd(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 Zd 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 Xd extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class ec extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class tc extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"}class nc extends Error{static name="StreamClosedError";name="StreamClosedError"}function rc(e){return e.reason}async function ic(e,t,n){if(null==t)return e;const r=n?.translateError??rc;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 sc{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=zd(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ot)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class oc{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 ot),this.cleanup())}async join(e){const t=new sc(e);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 ic(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{this.recipients.forEach(t=>{t.onProgress?.(e)})}}),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 ac extends Wt{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=Jd(this.emitEmpty.bind(this),1),this.emitIdle=Jd(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 Xd;const n=new oc(e,t);this.enqueue(n),this.safeDispatchEvent("add");const r=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});return this.tryToStartAnother(),r}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ot)}),this.clear()}async onEmpty(e){0!==this.size&&await Yd(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Yd(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Yd(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=Wd({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()},o=()=>{n(new ot("Queue aborted"))};this.addEventListener("completed",r),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",o),n()}}}const uc=4*Math.pow(2,20);class dc extends Wt{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??uc,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new rr,this.writeBuffer=new rr,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,queueMicrotask(()=>{this.processSendQueue()})),this.onDrainPromise?.resolve()}),this.addEventListener("close",e=>{this.onDrainPromise?.reject(e.error??new nc)})}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()),ic(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if("readable"!==this.readStatus&&"paused"!==this.readStatus)return;const e=Wd(),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 mt(`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 _t(e))}}pause(){if("closed"===this.readStatus||"closing"===this.readStatus)throw new mt("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 mt("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 mt(`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 mt(`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 ft;this.dispatchEvent(new Nt(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 Lt))}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 rr(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 Rt(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 yt(`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 yt(`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 cc extends dc{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 Yd(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 Yd(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}}class lc extends Wt{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 ic(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 ht;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 tc(`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 pc extends dc{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 Yd(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 Yd(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 hc(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 fc{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 mc{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new fc(t),this.failure=new fc(t),this.next=new fc(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=hc([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 yc{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=zd(),this.haveNext=zd()}[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=zd(),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=zd(),await ic(this.readNext.promise,t?.signal,t)}}function bc(...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 yc;(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 gc(e,...t){if(null==e)throw new Error("Empty pipeline");if(Pc(e)){const t=e;e=()=>t.source}else if(Tc(e)||wc(e)){const t=e;e=()=>t}const n=[e,...t];if(n.length>1&&Pc(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++)Pc(n[e])&&(n[e]=xc(n[e]));return vc(...n)}const vc=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},wc=e=>null!=e?.[Symbol.asyncIterator],Tc=e=>null!=e?.[Symbol.iterator],Pc=e=>null!=e&&null!=e.sink&&null!=e.source,xc=e=>t=>{const n=e.sink(t);if(null!=n?.then){const t=Wd({objectMode:!0});let r;n.then(()=>{t.end()},e=>{t.end(e)});const i=e.source;if(wc(i))r=async function*(){yield*i,t.end()};else{if(!Tc(i))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");r=function*(){yield*i,t.end()}}return bc(t,r())}return e.source};class Ec extends Error{static name="UnwrappedError";name="UnwrappedError"}class Sc extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Ac extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class kc extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Cc(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 Ic(e,t){const n=t?.maxBufferSize??4194304,r=new rr;let i,s=!1;if(o=e,null==o?.addEventListener||null==o?.removeEventListener||null==o?.send||null==o?.push||null==o?.log)throw new dt("Argument should be a Stream or a Multiaddr");var o;const a=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",a);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 Ec("Stream was unwrapped");if(Cc(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 ec(`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 ic(i.promise,t?.signal),Cc(e)){if(0===r.byteLength&&null==t?.bytes)return null;break}i=Promise.withResolvers()}const o=t?.bytes??r.byteLength;if(r.byteLength<o){if(Cc(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,o),new ec(`Unexpected EOF - stream closed while reading ${r.byteLength}/${o} bytes`);return c.read(t)}const a=r.sublist(0,o);return r.consume(o),a},async write(t,n){if(!0===s)throw new Ec("Stream was unwrapped");e.send(t)||await Yd(e,"drain",{signal:n?.signal,rejectionEvents:["close"]})},unwrap:()=>(s||(s=!0,e.removeEventListener("message",a),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 Dc(e,t={}){const n=Ic(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=Mo(t.maxDataLength));const r=t?.lengthDecoder??_o,i=t?.lengthEncoder??Lo;return{async read(i){let s=-1;const o=new rr;for(;;){const e=await n.read({...i,bytes:1});if(null==e)break;o.append(e);try{s=r(o)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new Sc("Invalid message length");if(null!=t?.maxLengthLength&&o.byteLength>t.maxLengthLength)throw new kc(`Message length length too long - ${o.byteLength} > ${t.maxLengthLength}`);if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new Ac(`Message length too long - ${s} > ${t.maxDataLength}`);const a=await n.read({...i,bytes:s});if(null==a)throw e.log.error("tried to read %d bytes but the stream closed",s),new ec(`Unexpected EOF - tried to read ${s} bytes but the stream closed`);if(a.byteLength!==s)throw e.log.error("read %d/%d bytes before the stream closed",a.byteLength,s),new ec(`Unexpected EOF - read ${a.byteLength}/${s} bytes before the stream closed`);return a},async write(e,t){await n.write(new rr(i(e.byteLength),e),t)},async writeV(e,t){const r=new rr(...e.flatMap(e=>[i(e.byteLength),e]));await n.write(r,t)},unwrap:()=>n.unwrap()}}function Mc(e,t){const n=Dc(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 Fc{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new rr,this.maxBufferSize=e.maxBufferSize??4194304,this.maxDataLength=e.maxDataLength??4194304,this.lengthDecoder=e.lengthDecoder??_o,this.encodingLength=e.encodingLength??Mo}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new dt(`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 Sc("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 Rc=4194304;class Lc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}function _c(e,t){if(e.byteLength>t)throw new Lc("Message length too long")}const Nc=e=>{const t=Mo(e),n=Zn(t);return Lo(e,n),Nc.bytes=t,n};function Oc(e,t){const n=(t=t??{}).lengthEncoder??Nc,r=t?.maxDataLength??Rc;function*i(e){_c(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 Bc;Nc.bytes=0,Oc.single=(e,t)=>{const n=(t=t??{}).lengthEncoder??Nc;return _c(e,t?.maxDataLength??Rc),new rr(n(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Bc||(Bc={}));class Uc extends ac{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}class jc extends ac{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}class qc{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 $c}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 Zd("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 $c{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 zc(e,t,n){let r,i,s=!1;function o(){const a={signal:i.signal};let u;null!=n?.timeout&&(u=hc([i.signal,AbortSignal.timeout(n.timeout)]),a.signal=u),s=!0,Promise.resolve().then(async()=>{await e(a)}).catch(()=>{}).finally(()=>{null!=u&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),s=!1,i.signal.aborted||(r=setTimeout(o,t))})}const a=Jd(o,n?.debounce??100);let u=!1;return{setInterval:e=>{t!==e&&(t=e,null!=r&&(clearTimeout(r),r=setTimeout(o,t)))},setTimeout:e=>{n??={},n.timeout=e},run:()=>{s||(clearTimeout(r),a())},start:()=>{u||(u=!0,i=new AbortController,!0===n?.runImmediately?queueMicrotask(()=>{o()}):r=setTimeout(o,t))},stop:()=>{clearTimeout(r),i?.abort(),u=!1}}}class Vc 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 Gc(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Vc({name:t,metrics:n}):new Map,r}class Kc{filter;constructor(e,t){this.filter=kd(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 Wc(e,t=.001){return new Kc(e,t)}class Hc extends fd{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 Qc(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Hc({name:t,metrics:n}):new fd,r}const Yc=new Float32Array([-0]),Jc=new Uint8Array(Yc.buffer);function Zc(e,t,n){Yc[0]=e,t[n]=Jc[0],t[n+1]=Jc[1],t[n+2]=Jc[2],t[n+3]=Jc[3]}const Xc=new Float64Array([-0]),el=new Uint8Array(Xc.buffer);function tl(e,t,n){Xc[0]=e,t[n]=el[0],t[n+1]=el[1],t[n+2]=el[2],t[n+3]=el[3],t[n+4]=el[4],t[n+5]=el[5],t[n+6]=el[6],t[n+7]=el[7]}const nl=BigInt(Number.MAX_SAFE_INTEGER),rl=BigInt(Number.MIN_SAFE_INTEGER);class il{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 sl;if(e<nl&&e>rl)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>ol&&(r=0n,++n>ol&&(n=0n))),new il(Number(r),Number(n))}static fromNumber(e){if(0===e)return sl;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 il(n,r)}static from(e){return"number"==typeof e?il.fromNumber(e):"bigint"==typeof e?il.fromBigInt(e):"string"==typeof e?il.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new il(e.low>>>0,e.high>>>0):sl}}const sl=new il(0,0);sl.toBigInt=function(){return 0n},sl.zzEncode=sl.zzDecode=function(){return this},sl.length=function(){return 1};const ol=4294967296n;function al(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 ul(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function dl(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class cl{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,ul(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 ul(this,4);return dl(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ul(this,4);return 0|dl(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw ul(this,4);const e=(Jc[0]=(t=this.buf)[n=this.pos],Jc[1]=t[n+1],Jc[2]=t[n+2],Jc[3]=t[n+3],Yc[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ul(this,4);const e=(el[0]=(t=this.buf)[n=this.pos],el[1]=t[n+1],el[2]=t[n+2],el[3]=t[n+3],el[4]=t[n+4],el[5]=t[n+5],el[6]=t[n+6],el[7]=t[n+7],Xc[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 ul(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,o=0;for(;t<n;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(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[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw ul(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw ul(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 il(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw ul(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 ul(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 ul(this,8);const e=dl(this.buf,this.pos+=4),t=dl(this.buf,this.pos+=4);return new il(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=Ro(this.buf,this.pos);return this.pos+=Mo(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 ll(e){return new cl(e instanceof Uint8Array?e:e.subarray())}function pl(e,t,n){const r=ll(e);return t.decode(r,void 0,n)}class hl{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function fl(){}class ml{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const yl=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Zn(r);n+r>e&&(t=Zn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class bl{len;head;tail;states;constructor(){this.len=0,this.head=new hl(fl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new hl(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new wl((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Tl,10,il.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=il.fromBigInt(e);return this._push(Tl,t.length(),t)}uint64Number(e){return this._push(Fo,Mo(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=il.fromBigInt(e).zzEncode();return this._push(Tl,t.length(),t)}sint64Number(e){const t=il.fromNumber(e).zzEncode();return this._push(Tl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(gl,1,e?1:0)}fixed32(e){return this._push(Pl,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=il.fromBigInt(e);return this._push(Pl,4,t.lo)._push(Pl,4,t.hi)}fixed64Number(e){const t=il.fromNumber(e);return this._push(Pl,4,t.lo)._push(Pl,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(Zc,4,e)}double(e){return this._push(tl,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(gl,1,0):this.uint32(t)._push(xl,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(al,t,e):this._push(gl,1,0)}fork(){return this.states=new ml(this),this.head=this.tail=new hl(fl,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 hl(fl,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?Zn(n):yl(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function gl(e,t,n){t[n]=255&e}function vl(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class wl extends hl{next;constructor(e,t){super(vl,e,t),this.next=void 0}}function Tl(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 Pl(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 xl(e,t,n){t.set(e,n)}function El(e,t,n){t.set(e,n)}function Sl(e,t,n){e.length<40?al(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(Ir(e),n)}function Al(e,t){const n=new bl;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*kl(e,t,n){const r=ll(e);yield*t.stream(r,void 0,"$",n)}function Cl(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&&(bl.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(El,t,e),this},bl.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Sl,t,e),this});class Il extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var Dl;!function(e){let t;e.codec=()=>(null==t&&(t=Cl((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:Jn(0),payloadType:Jn(0),payload:Jn(0),signature:Jn(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 Al(t,e.codec())},e.decode=function(t,n){return pl(t,e.codec(),n)},e.stream=function(t,n){return kl(t,e.codec(),n)}}(Dl||(Dl={}));class Ml extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class Fl{static createFromProtobuf=e=>{const t=Dl.decode(e),n=Ka(t.publicKey);return new Fl({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(),o=Rl(r,i,s),a=await t.sign(o.subarray(),n);return new Fl({publicKey:t.publicKey,payloadType:i,payload:s,signature:a})};static openAndCertify=async(e,t,n)=>{const r=Fl.createFromProtobuf(e);if(!await r.validate(t,n))throw new Ml("Envelope signature is not valid for the given domain");return r};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:n,payload:r,signature:i}=e;this.publicKey=t,this.payloadType=n,this.payload=r,this.signature=i}marshal(){return null==this.marshaled&&(this.marshaled=Dl.encode({publicKey:Wa(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Yn(this.marshal(),e.marshal())}async validate(e,t){const n=Rl(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}}const Rl=(e,t,n)=>{const r=Ir(e),i=Lo(r.byteLength),s=Lo(t.length),o=Lo(n.length);return new rr(i,r,s,t,o,n)},Ll=Uint8Array.from([3,1]);var _l;!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=Cl((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:Jn(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 Al(t,e.codec())},e.decode=function(t,n){return pl(t,e.codec(),n)},e.stream=function(t,n){return kl(t,e.codec(),n)}}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=Cl((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:Jn(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 Il('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},o=null==n?t.len:t.pos+n;for(;t.pos<o;){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 Il('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 Al(t,e.codec())},e.decode=function(t,n){return pl(t,e.codec(),n)},e.stream=function(t,n){return kl(t,e.codec(),n)}}(_l||(_l={}));class Nl{static createFromProtobuf=e=>{const t=_l.decode(e),n=nu(Bn(t.peerId)),r=(t.addresses??[]).map(e=>Uu(e.multiaddr));return new Nl({peerId:n,multiaddrs:r,seqNumber:t.seq})};static DOMAIN="libp2p-peer-record";static CODEC=Ll;peerId;multiaddrs;seqNumber;domain=Nl.DOMAIN;codec=Nl.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=_l.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 Nl&&!!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 Ol(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 Bl extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}}async function Ul(e,t,n,r){const i=new Bl(r?.errorMessage);null!=r?.errorCode&&(i.code=r.errorCode);const s=r?.errorEvent??"error";return!0===n?.aborted?Promise.reject(i):new Promise((o,a)=>{function u(){ql(n,"abort",l),ql(e,t,d),ql(e,s,c)}const d=e=>{try{if(!1===r?.filter?.(e))return}catch(e){return u(),void a(e)}u(),o(e)},c=e=>{u(),e instanceof Error?a(e):a(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(),a(i)};jl(n,"abort",l),jl(e,t,d),jl(e,s,c)})}function jl(e,t,n){null!=e&&($l(e)?e.addEventListener(t,n):e.addListener(t,n))}function ql(e,t,n){null!=e&&($l(e)?e.removeEventListener(t,n):e.removeListener(t,n))}function $l(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class zl extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Vl{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 Bl)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Gl{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 Bl),this.cleanup())}async join(e={}){const t=new Vl(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 ic(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 Kl(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 Wl extends Wt{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=Kl(this.emitEmpty.bind(this),1),this.emitIdle=Kl(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 zl;const n=new Gl(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 Bl)}),this.clear()}async onEmpty(e){0!==this.size&&await Ul(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ul(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Ul(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=Wd({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()},o=()=>{n(new Bl("Queue aborted"))};this.addEventListener("success",r),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("success",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",o),n()}}}const Hl="lock:worker:request-read",Ql="lock:worker:abort-read-request",Yl="lock:worker:release-read",Jl="lock:master:grant-read",Zl="lock:master:error-read",Xl="lock:worker:request-write",ep="lock:worker:abort-write-request",tp="lock:worker:release-write",np="lock:master:grant-write",rp="lock:master:error-write",ip="lock:worker:finalize",sp="mortice",op={singleProcess:!1},ap=(e,t,n,r,i,s,o,a,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===a&&r.data.identifier===c.identifier&&(t.removeEventListener("message",n),e())};t.addEventListener("message",n)})},onError:e=>{t.postMessage({type:o,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===ip&&e.safeDispatchEvent("finalizeRequest",{detail:{name:c.name}})};class up{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(sp)}readLock(e){return this.sendRequest(Hl,Ql,Jl,Zl,Yl,e)}writeLock(e){return this.sendRequest(Xl,ep,np,rp,tp,e)}finalize(){this.channel.postMessage({type:ip,name:this.name}),this.channel.close()}async sendRequest(e,t,n,r,i,s){s?.signal?.throwIfAborted();const o=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:o,name:this.name}),new Promise((e,a)=>{const u=()=>{this.channel.postMessage({type:t,identifier:o,name:this.name})};s?.signal?.addEventListener("abort",u,{once:!0});const d=t=>{if(t.data?.identifier===o&&(t.data?.type===n&&(this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u),e(()=>{this.channel.postMessage({type:i,identifier:o,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),a(e)}};this.channel.addEventListener("message",d)})}}const dp=new Map;let cp;function lp(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}function pp(e){if(null==cp&&(cp=(e=>{if(e=Object.assign({},op,e),Boolean(globalThis.document)||e.singleProcess){const e=new BroadcastChannel(sp),t=new Wt;return e.addEventListener("message",ap(t,e,"requestReadLock","abortReadLockRequest",Hl,Ql,Zl,Yl,Jl)),e.addEventListener("message",ap(t,e,"requestWriteLock","abortWriteLockRequest",Xl,ep,rp,tp,np)),t}return new up(e.name)})(e),!lp(cp))){const e=cp;e.addEventListener("requestReadLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=dp.get(n);if(null==i)return;const s=new AbortController,o=e=>{e.detail.name===n&&e.detail.identifier===r&&s.abort()};e.addEventListener("abortReadLockRequest",o),i.readLock({signal:s.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortReadLockRequest",o)})}),e.addEventListener("requestWriteLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=dp.get(n);if(null==i)return;const s=new AbortController,o=e=>{e.detail.name===n&&e.detail.identifier===r&&s.abort()};e.addEventListener("abortWriteLockRequest",o),i.writeLock({signal:s.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",o)})}),e.addEventListener("finalizeRequest",e=>{const t=dp.get(e.detail.name);null!=t&&t.finalize()})}return cp}async function hp(e,t){let n,r;const i=new Promise((e,t)=>{n=e,r=t}),s=()=>{r(new Bl)};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 fp={name:"lock",concurrency:Infinity,singleProcess:!1,autoFinalize:!1};function mp(e){const t=Object.assign({},fp,e);return((e,t)=>{let n=dp.get(e);if(null!=n)return n;const r=pp(t);if(lp(r))return n=r,dp.set(e,n),n;const i=new Wl({concurrency:1});let s;return n={async readLock(e){if(null!=s)return hp(s,e);s=new Wl({concurrency:t.concurrency,autoStart:!1});const n=s,r=hp(s,e);return i.add(async()=>{n.start(),await n.onIdle().then(()=>{s===n&&(s=null)})}),r},writeLock:async e=>(s=null,hp(i,e)),finalize:()=>{dp.delete(e)},queue:i},dp.set(e,n),!0===t.autoFinalize&&i.addEventListener("idle",()=>{n.finalize()},{once:!0}),n})(t.name,t)}const yp=new Float32Array([-0]),bp=new Uint8Array(yp.buffer);function gp(e,t,n){yp[0]=e,t[n]=bp[0],t[n+1]=bp[1],t[n+2]=bp[2],t[n+3]=bp[3]}const vp=new Float64Array([-0]),wp=new Uint8Array(vp.buffer);function Tp(e,t,n){vp[0]=e,t[n]=wp[0],t[n+1]=wp[1],t[n+2]=wp[2],t[n+3]=wp[3],t[n+4]=wp[4],t[n+5]=wp[5],t[n+6]=wp[6],t[n+7]=wp[7]}const Pp=BigInt(Number.MAX_SAFE_INTEGER),xp=BigInt(Number.MIN_SAFE_INTEGER);class Ep{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 Sp;if(e<Pp&&e>xp)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>Ap&&(r=0n,++n>Ap&&(n=0n))),new Ep(Number(r),Number(n))}static fromNumber(e){if(0===e)return Sp;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 Ep(n,r)}static from(e){return"number"==typeof e?Ep.fromNumber(e):"bigint"==typeof e?Ep.fromBigInt(e):"string"==typeof e?Ep.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Ep(e.low>>>0,e.high>>>0):Sp}}const Sp=new Ep(0,0);Sp.toBigInt=function(){return 0n},Sp.zzEncode=Sp.zzDecode=function(){return this},Sp.length=function(){return 1};const Ap=4294967296n;function kp(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 Cp(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Ip(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Dp{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,Cp(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 Cp(this,4);return Ip(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Cp(this,4);return 0|Ip(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Cp(this,4);const e=(bp[0]=(t=this.buf)[n=this.pos],bp[1]=t[n+1],bp[2]=t[n+2],bp[3]=t[n+3],yp[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Cp(this,4);const e=(wp[0]=(t=this.buf)[n=this.pos],wp[1]=t[n+1],wp[2]=t[n+2],wp[3]=t[n+3],wp[4]=t[n+4],wp[5]=t[n+5],wp[6]=t[n+6],wp[7]=t[n+7],vp[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 Cp(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,o=0;for(;t<n;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(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[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Cp(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Cp(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 Ep(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Cp(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 Cp(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 Cp(this,8);const e=Ip(this.buf,this.pos+=4),t=Ip(this.buf,this.pos+=4);return new Ep(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=Ro(this.buf,this.pos);return this.pos+=Mo(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Mp(e,t,n){const r=function(e){return new Dp(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(r,void 0,n)}class Fp{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Rp(){}class Lp{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const _p=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Zn(r);n+r>e&&(t=Zn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class Np{len;head;tail;states;constructor(){this.len=0,this.head=new Fp(Rp,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Fp(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Up((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(jp,10,Ep.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Ep.fromBigInt(e);return this._push(jp,t.length(),t)}uint64Number(e){return this._push(Fo,Mo(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=Ep.fromBigInt(e).zzEncode();return this._push(jp,t.length(),t)}sint64Number(e){const t=Ep.fromNumber(e).zzEncode();return this._push(jp,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Op,1,e?1:0)}fixed32(e){return this._push(qp,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Ep.fromBigInt(e);return this._push(qp,4,t.lo)._push(qp,4,t.hi)}fixed64Number(e){const t=Ep.fromNumber(e);return this._push(qp,4,t.lo)._push(qp,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(gp,4,e)}double(e){return this._push(Tp,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Op,1,0):this.uint32(t)._push($p,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(kp,t,e):this._push(Op,1,0)}fork(){return this.states=new Lp(this),this.head=this.tail=new Fp(Rp,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 Fp(Rp,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?Zn(n):_p(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function Op(e,t,n){t[n]=255&e}function Bp(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class Up extends Fp{next;constructor(e,t){super(Bp,e,t),this.next=void 0}}function jp(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 qp(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 $p(e,t,n){t.set(e,n)}function zp(e,t,n){t.set(e,n)}function Vp(e,t,n){e.length<40?kp(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(Ir(e),n)}function Gp(e,t){const n=new Np;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var Kp,Wp,Hp,Qp,Yp;function Jp(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function Zp(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Jp("enum",Kp.VARINT,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())})}function Xp(e,t){return Jp("message",Kp.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Np.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(zp,t,e),this},Np.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Vp,t,e),this}),(Yp=Kp||(Kp={}))[Yp.VARINT=0]="VARINT",Yp[Yp.BIT64=1]="BIT64",Yp[Yp.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",Yp[Yp.START_GROUP=3]="START_GROUP",Yp[Yp.END_GROUP=4]="END_GROUP",Yp[Yp.BIT32=5]="BIT32";class eh extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class th extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function nh(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let n;return"RSA"===e.type&&(n=e.toMultihash()),tu(Ka(t.publicKey,n))}function rh(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:nh(e,t),addresses:t.addresses.filter(({observed:e})=>null!=e&&e>Date.now()-n).map(({multiaddr:e,isCertified:t})=>({multiaddr:Uu(e),isCertified:t??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:r}}function ih(e,t){return null==e&&null==t||null!=e&&null!=t&&Yn(e,t)}function sh(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 oh(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=Xp((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:Jn(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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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),Qp.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=Qp.codec().decode(e,e.uint32(),{limits:n.limits?.value});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Xp((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.addresses)for(const e of t.addresses)n.uint32(10),Hp.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 eh('Decode error - map field "addresses" had too many elements');i.addresses.push(Hp.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 eh('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 th('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 th('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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Wp||(Wp={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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:Jn(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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Hp||(Hp={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Qp||(Qp={}));const ah="/",uh=(new TextEncoder).encode(ah),dh=uh[0];class ch{_buf;constructor(e,t){if("string"==typeof e)this._buf=Ir(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]!==dh)throw new Error("Invalid key")}toString(e="utf8"){return Dr(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new ch(e.join(ah))}static random(){return new ch(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new ch(e):"function"==typeof e.uint8Array?new ch(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=uh),this._buf[0]!==dh){const e=new Uint8Array(this._buf.byteLength+1);e.fill(dh,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===dh;)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 ch.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(ah).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 ch(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ah)||(e+=ah),e+=this.type(),new ch(e)}parent(){const e=this.list();return new ch(1===e.length?ah:e.slice(0,-1).join(ah))}child(e){return this.toString()===ah?e:e.toString()===ah?this:new ch(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 ch.withNamespaces([...this.namespaces(),...(t=e.map(e=>e.namespaces()),[].concat(...t))]);var t}}const lh="/peers/";function ph(e){if(!Ut(e)||null==e.type)throw new dt("Invalid PeerId");const t=e.toCID().toString();return new ch(`${lh}${t}`)}async function hh(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=Uu(r.multiaddr)),!Bu(r.multiaddr))throw new dt("Multiaddr was invalid");if(!await t(e,r.multiaddr,i))continue;const n=r.isCertified??!1,o=r.multiaddr.toString(),a=s.get(o);null!=a?r.isCertified=a.isCertified||n:s.set(o,{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===mu)?.value;return e.equals(r)&&(n=n.decapsulate(Uu(`/p2p/${e}`))),{isCertified:t,multiaddr:n.bytes}})}async function fh(e,t,n,r){if(null==t)throw new dt("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new dt("publicKey bytes do not match peer id publicKey bytes");const i=r.existingPeer?.peer;if(null!=i&&!e.equals(i.id))throw new dt("peer id did not match existing peer id");let s,o=i?.addresses??[],a=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||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(a=new Set(t.protocols)),null!=t.metadata&&(u=mh(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:yh})),null!=t.tags&&(d=mh(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:bh,map:gh})),null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)),"merge"===n){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(a=new Set([...a,...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=mh([...u.entries()],{validate:yh})}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=mh([...n.entries()],{validate:bh,map:gh})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}null!=i?.id.publicKey?s=Wa(i.id.publicKey):null!=t.publicKey?s=Wa(t.publicKey):null!=e.publicKey&&(s=Wa(e.publicKey));const l={addresses:await hh(e,r.addressFilter??(async()=>!0),o,0,r),protocols:[...a.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=>Yn(e.multiaddr,e.multiaddr))?.observed??Date.now()}),"RSA"!==e.type&&delete l.publicKey,l}function mh(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 yh(e,t){if("string"!=typeof e)throw new dt("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new dt("Metadata value must be a Uint8Array")}function bh(e,t){if("string"!=typeof e)throw new dt("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new dt("Tag value must be an integer");if(t.value<0||t.value>100)throw new dt("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new dt("Tag ttl must be an integer");if(t.ttl<0)throw new dt("Tag ttl must be between greater than 0")}}function gh(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 vh(e){const t=e.toString().split("/")[2];return ru(zn.parse(t,dn))}function wh(e,t,n){return function(e,t,n){return rh(e,Wp.decode(t),n)}(vh(e),t,n)}class Th{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=Qc({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:mp({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(ph(e),t)}async load(e,t){const n=ph(e),r=await this.datastore.get(n,t),i=Wp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new bt;return rh(e,i,this.peerId.equals(e)?Infinity:this.maxAddressAge)}async save(e,t,n){const r=await this.#s(e,n),i=await fh(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#o(e,i,r)}async patch(e,t,n){const r=await this.#s(e,n),i=await fh(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:r});return this.#o(e,i,r)}async merge(e,t,n){const r=await this.#s(e,n),i=await fh(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:r});return this.#o(e,i,r)}async*all(e){for await(const{key:t,value:n}of this.datastore.query(function(e,t){return{prefix:lh,filters:(e.filters??[]).map(e=>({key:n,value:r})=>e(wh(n,r,t))),orders:(e.orders??[]).map(e=>(n,r)=>e(wh(n.key,n.value,t),wh(r.key,r.value,t)))}}(e??{},this.maxAddressAge),e)){const r=vh(t);if(r.equals(this.peerId))continue;const i=Wp.decode(n);this.#i(r,i)?await this.datastore.delete(t,e):yield rh(r,i,this.peerId.equals(r)?Infinity:this.maxAddressAge)}}async#s(e,t){try{const n=ph(e),r=await this.datastore.get(n,t),i=Wp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new bt;return{peerPB:i,peer:rh(e,i,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#o(e,t,n,r){t.updated=Date.now();const i=Wp.encode(t);return await this.datastore.put(ph(e),i,r),{peer:rh(e,t,this.maxAddressAge),previous:n?.peer,updated:null==n||(s=t,o=n.peerPB,!(sh(s.addresses,o.addresses,(e,t)=>e.isCertified===t.isCertified&&!!Yn(e.multiaddr,t.multiaddr))&&sh(s.protocols,o.protocols,(e,t)=>e===t)&&ih(s.publicKey,o.publicKey)&&ih(s.peerRecordEnvelope,o.peerRecordEnvelope)&&oh(s.metadata,o.metadata,(e,t)=>Yn(e,t))&&oh(s.tags,o.tags,(e,t)=>e.value===t.value&&e.expiry===t.expiry)))};var s,o}#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 Ph{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 Th(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 Ol(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.#a(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.#a(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.#a(e,r),r.peer}finally{r?.()}}async consumePeerRecord(e,t,n){const r=Ut(t)?t:Ut(t?.expectedPeer)?t.expectedPeer:void 0,i=Ut(t)||void 0===t?n:t,s=await Fl.openAndCertify(e,Nl.DOMAIN,i),o=ru(s.publicKey.toCID());if(!1===r?.equals(o))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",r,o),!1;const a=Nl.createFromProtobuf(s.payload);let u;try{u=await this.get(o,i)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u?.peerRecordEnvelope){const e=Fl.createFromProtobuf(u.peerRecordEnvelope),t=Nl.createFromProtobuf(e.payload);if(t.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:e,addresses:a.multiaddrs.map(e=>({isCertified:!0,multiaddr:e}))},i),!0}#a(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}class xh extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=xh.name;code=xh.code;constructor(e="Not Found"){super(e)}}function Eh(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}function Sh(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 Ah(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=Sh(e),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const o=t(i,n++);if("function"==typeof o.then)return async function*(){await o&&(yield i);for(const e of r)await t(e,n++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield i);for(const e of r)a(e,n++)&&(yield e)}()}function kh(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const n=await Ol(e);yield*n.sort(t)}():function*(){const n=Ol(e);yield*n.sort(t)}()}function Ch(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 Ih{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 Eh(this.putMany(e,n)),e=[],await Eh(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=Ah(n,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>Ah(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>kh(e,t),n)),null!=e.offset){let t=0;const r=e.offset;n=Ah(n,()=>t++>=r)}return null!=e.limit&&(n=Ch(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;n=Ah(n,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>Ah(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>kh(e,t),n)),null!=e.offset){const t=e.offset;let r=0;n=Ah(n,()=>r++>=t)}return null!=e.limit&&(n=Ch(n,e.limit)),n}}class Dh extends Ih{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 xh;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 ch(e),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(const e of this.data.keys())yield new ch(e),t?.signal?.throwIfAborted()}}const Mh=e=>({match:t=>{const n=t[0];return null!=n&&n.code===e&&null==n.value&&t.slice(1)}}),Fh=(e,t)=>({match:n=>{const r=n[0];return r?.code===e&&null!=r.value&&(null==t||r.value===t)&&n.slice(1)}}),Rh=e=>({match:t=>{const n=e.match(t);return!1===n?t:n}}),Lh=(...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}}),_h=(...e)=>({match:t=>{for(const n of e){const e=n.match(t);if(!1===e)return!1;t=e}return t}});function Nh(...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 Oh=Nh(Fh(mu)),Bh=Fh(54),Uh=Fh(55),jh=Fh(56),qh=Fh(53),$h=_h(Fh(4),Rh(Fh(43))),zh=_h(Rh(Fh(42)),Fh(fu),Rh(Fh(43))),Vh=Lh($h,zh),Gh=Lh(Vh,qh,Bh,Uh,jh),Kh=Nh(Lh(Vh,_h(Lh(qh,jh,Bh,Uh),Rh(Fh(mu))))),Wh=Nh($h),Hh=Nh(zh),Qh=_h(Gh,Fh(6)),Yh=_h(Gh,Fh(273)),Jh=Nh(_h(Qh,Rh(Fh(mu)))),Zh=_h(Yh,Mh(460),Rh(Fh(mu))),Xh=_h(Yh,Mh(461),Rh(Fh(mu))),ef=Lh(Zh,Xh),tf=Nh(Xh),nf=Lh(Gh,Qh,Yh,Zh,Xh),rf=Lh(_h(nf,Mh(477),Rh(Fh(mu)))),sf=Nh(rf),of=Lh(_h(nf,Mh(478),Rh(Fh(mu))),_h(nf,Mh(yu),Rh(Fh(bu)),Mh(477),Rh(Fh(mu)))),af=Nh(of),uf=_h(Yh,Mh(280),Rh(Fh(gu)),Rh(Fh(gu)),Rh(Fh(mu))),df=Nh(uf),cf=_h(Xh,Mh(465),Rh(Fh(gu)),Rh(Fh(gu)),Rh(Fh(mu))),lf=Nh(cf),pf=Lh(rf,of,_h(Qh,Rh(Fh(mu))),_h(ef,Rh(Fh(mu))),_h(Gh,Rh(Fh(mu))),uf,cf,Fh(mu)),hf=Nh(pf);var ff;const mf=Nh(_h(Rh(pf),Mh(wu),(ff=Mh(vu),{match:e=>!1===ff.match(e)&&e}),Rh(Fh(mu)))),yf=Nh(Lh(_h(pf,Mh(wu),Mh(vu),Rh(Fh(mu))),_h(pf,Mh(vu),Rh(Fh(mu))),_h(Mh(vu),Rh(Fh(mu))))),bf=864e13;class gf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Gc({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=Id(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===qd(t);this.mappings.set(t,{domain:e,verified:n,expires:n?bf-Date.now():0,lastVerified:n?bf-Date.now():void 0})})}remove(e){const t=Id(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(!_d(r))continue;const i=Id(r);for(const[s,o]of this.mappings.entries()){if(i.host!==s)continue;const a=this.maybeAddSNIComponent(r,o.domain);null!=a&&(e.splice(n,1),n--,t.push({multiaddr:a,verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}}return t}maybeAddSNIComponent(e,t){const n=e.getComponents();for(let e=0;e<n.length;e++)if(n[e].code===yu&&n[e+1]?.code!==bu)return n.splice(e+1,0,{name:"sni",code:bu,value:t}),Uu(n)}confirm(e,t){const n=Id(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=Id(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 vf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Gc({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=Id(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}`,o=this.mappings.get(s)??[],a={internalIp:e,internalPort:t,externalIp:n,externalPort:r,externalFamily:pu(n)?4:6,protocol:i,verified:!1,expires:0};o.push(a),this.mappings.set(s,o)}remove(e){const t=Id(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(!_d(n))continue;const e=Id(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(),o=s.findIndex(e=>4===e.code||e.code===fu),a=s.findIndex(e=>e.name===r);return o>-1&&a>-1?(s[o].value=t,s[o].code=4===n?4:fu,s[a].value=`${i}`,Uu(s)):e}confirm(e,t){if(!_d(e))return!1;const n=Id(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(!_d(e))return!1;const n=Id(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 wf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Gc({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&&($d(e)||function(e){try{const t=Id(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:Uu(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 Tf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Gc({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if($d(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:!_d(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(!_d(e))return e.toString();const t=Id(e);return`${t.host}-${t.port}-${t.protocol}`}}const Pf=e=>e;function xf(e,t){const n=e.getComponents().findLast(e=>e.code===mu)?.value;return null!=n&&eu(n).equals(t)&&(e=e.decapsulate(Uu(`/p2p/${t.toString()}`))),e}class Ef{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 wf(e,t),this.dnsMappings=new gf(e,t),this.ipMappings=new vf(e,t),this.transportAddresses=new Tf(e,t),this.announceFilter=t.announceFilter??Pf,this.observedAddressFilter=kd(1024),this.addressVerificationTTL=t.addressVerificationTTL??6e5,this.addressVerificationRetry=t.addressVerificationRetry??3e5,this._updatePeerStoreAddresses=Jd(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===mu)?.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=>Uu(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Uu(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Uu(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){const t=Id(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=xf(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=xf(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=xf(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=Uu(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(Uu(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.add(e,t,n,r,i),this.observed.removePrefixed(`/ip${pu(n)?4:6}/${n}/${i}/${r}`)}removePublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.remove(Uu(`/ip${pu(n)?4:6}/${n}/${i}/${r}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;if(!_d(e))return!1;const t=Id(e);if("ip4"!==t.type||!0===qd(t.host))return!1;const n=this.components.transportManager.getListeners(),r=[e=>sf.exactMatch(e)||af.exactMatch(e),e=>Jh.exactMatch(e),e=>tf.exactMatch(e)];for(const i of r){if(!i(e))continue;const r=n.filter(e=>e.getAddrs().filter(e=>"ip4"===Id(e).type&&i(e)).length>0);if(1!==r.length)continue;const s=r[0].getAddrs().filter(e=>!Ld(e)).pop();if(null==s)continue;const o=Id(s);return null!=o.port&&(this.observed.remove(e),this.ipMappings.add(o.host,o.port,t.host,t.port,t.protocol),!0)}return!1}}var Sf;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(Sf||(Sf={}));class Af extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class kf extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class Cf extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class If extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class Df extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class Mf extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class Ff extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class Rf extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class Lf extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class _f extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class Nf extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Of extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class Bf extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class Uf extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class jf extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class qf extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class $f extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}class zf{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=dd())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>$t(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 Vf=["metrics","connectionProtector","dns"],Gf=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Kf(e){return Array.isArray(e?.[Ht])?e[Ht]:[]}function Wf(e){return Array.isArray(e?.[Qt])?e[Qt]:[]}function Hf(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function Qf(e={}){return null==e.denyDialMultiaddr&&(e.denyDialMultiaddr=e=>!!sf.matches(e)||$d(e)),e}class Yf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Jf(e){if(Ut(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===mu)?.value;t=null==e?void 0:eu(e),n.forEach(e=>{if(!Bu(e))throw new vt("Invalid multiaddr");const n=e.getComponents().findLast(e=>e.code===mu)?.value;if(null==n){if(null!=t)throw new dt("Multiaddrs must all have the same peer id or have no peer id")}else{const e=eu(n);if(!0!==t?.equals(e))throw new dt("Multiaddrs must all have the same peer id or have no peer id")}})}return n=n.filter(e=>!Oh.exactMatch(e)),{peerId:t,multiaddrs:n}}const Zf=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Xf(e){const t=Id(e);let n=t.cidr;if("ip4"!==t.type&&"ip6"!==t.type)throw new dt(`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 dt(`Multiaddr ${e} was not an IPv4 or IPv6 address`)}return new Rd(t.host,n)}function em(e){return!mf.exactMatch(e)}function tm(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=>em(e))?void 0:r}class nm{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(e=>Xf(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 fd;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),o=[];for(const e of i)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some(t=>{if(_d(e.remoteAddr)){const n=Id(e.remoteAddr);return t.contains(n.host)}return!0})||o.push(e),o.length===s)break;await Promise.all(o.map(async e=>{await async function(e,t){const n=e?.streams?.map(e=>e.protocol)??[],r=t?.closableProtocols??Zf;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:o})}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 rm=1e4,im="last-dial-failure",sm="last-dial-success";function om(e,t){const n=Jh.exactMatch(e.multiaddr),r=Jh.exactMatch(t.multiaddr);if(n&&!r)return-1;if(!n&&r)return 1;const i=af.exactMatch(e.multiaddr),s=af.exactMatch(t.multiaddr);if(i&&!s)return-1;if(!i&&s)return 1;const o=sf.exactMatch(e.multiaddr),a=sf.exactMatch(t.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const u=yf.exactMatch(e.multiaddr),d=yf.exactMatch(t.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;const c=df.exactMatch(e.multiaddr),l=df.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const p=lf.exactMatch(e.multiaddr),h=lf.exactMatch(t.multiaddr);return p&&!h?-1:!p&&h?1:0}function am(e,t){const n=Ld(e.multiaddr),r=Ld(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function um(e,t){const n=$d(e.multiaddr),r=$d(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function dm(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function cm(e,t){const n=mf.exactMatch(e.multiaddr),r=mf.exactMatch(t.multiaddr);return n&&!r?1:!n&&r?-1:0}class lm extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"}var pm=Od(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,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new i(r,s||e,o),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],a]:e._events[u].push(a):(e._events[u]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.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},a.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},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,i,s,o){var a=n?n+e:e;if(!this._events[a])return!1;var u,d,c=this._events[a],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,o),!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},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||o(this,s);else{for(var u=0,d=[],c=a.length;u<c;u++)(a[u].fn!==t||i&&!a[u].once||r&&a[u].context!==r)&&d.push(a[u]);d.length?this._events[s]=1===d.length?d[0]:d:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&o(this,t):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}),hm=pm;class fm extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,fm)}}const mm=e=>e.reason??new DOMException("This operation was aborted.","AbortError");class ym{#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 o=r+s;n(e[o],t)<=0?(r=++o,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 bm extends hm{#d;#c;#l=0;#p;#h=!1;#f=!1;#m;#y=0;#b=0;#g;#v;#w;#T=[];#P=0;#u;#x;#E=0;#S;#A;#k=1n;#C=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:ym,strict:!1,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&0===e.interval)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#d=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#c=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#p=e.intervalCap,this.#m=e.interval,this.#w=e.strict,this.#u=new e.queueClass,this.#x=e.queueClass,this.concurrency=e.concurrency,void 0!==e.timeout&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#A=!1===e.autoStart,this.#I()}#D(e){for(;this.#P<this.#T.length;){const t=this.#T[this.#P];if(!(void 0!==t&&e-t>=this.#m))break;this.#P++}(this.#P>100&&this.#P>this.#T.length/2||this.#P===this.#T.length)&&(this.#T=this.#T.slice(this.#P),this.#P=0)}#M(e){this.#w?this.#T.push(e):this.#l++}#F(){this.#w?this.#T.length>this.#P&&this.#T.pop():this.#l>0&&this.#l--}#R(){return this.#T.length-this.#P}get#L(){return!!this.#c||(this.#w?this.#R()<this.#p:this.#l<this.#p)}get#_(){return this.#E<this.#S}#N(){this.#E--,0===this.#E&&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.#P],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.#E: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.#E){if(this.#V(),this.#w&&this.#P>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.#L&&this.#_){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.#E&&this.#g&&this.#z(),this.#l=this.#d?this.#E: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.#k++).toString()},new Promise((n,r)=>{const i=Symbol(`task-${t.id}`);this.#u.enqueue(async()=>{let s;this.#E++,this.#C.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});try{try{t.signal?.throwIfAborted()}catch(e){throw this.#W(),this.#C.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:o}=t;let a,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(o?.aborted)return void d(mm(o));if(o&&(u=()=>{d(mm(o))},o.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new fm;a=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&&o&&o.removeEventListener("abort",u)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}(Promise.resolve(r),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#E} 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 o=await r;n(o),this.emit("completed",o)}catch(e){r(e),this.emit("error",e)}finally{s&&t.signal?.removeEventListener("abort",s),this.#C.delete(i),queueMicrotask(()=>{this.#N()})}},t),this.emit("add"),this.#O()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#A?(this.#A=!1,this.#K(),this):this}pause(){this.#A=!0}clear(){this.#u=new this.#x,this.#z(),this.#H(),this.emit("empty"),0===this.#E&&(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.#E&&0===this.#u.size||await this.#Q("idle")}async onPendingZero(){0!==this.#E&&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.#E}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.#H()}))}#W(){this.#c||(this.#F(),this.#G())}#H(){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.#E===this.#S&&this.#u.size>0||this.isRateLimited&&this.#u.size>0}get runningTasks(){return[...this.#C.values()].map(e=>({...e}))}}function gm(e){const t=[xm.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function vm(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:xm[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:xm[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?Dr(e.data):e.data}))}}function wm(e,t={}){const n=new bm({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),gm(r.types).forEach(e=>{s.append("type",xm[e])}),r.onProgress?.(new Yf("dns:query",t)),i?.("GET %s",`${e}?${s}`);const o=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=vm(await t.json());return r.onProgress?.(new Yf("dns:response",n)),n},{signal:r.signal});if(null==o)throw new Error("No DNS response received");return o}}class Tm{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 vm({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:xm[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 Pm{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=new Tm(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["."]=[wm("https://cloudflare-dns.com/dns-query"),wm("https://dns.google/resolve")])}async query(e,t={}){const n=gm(t.types),r=!1!==t.cached?this.cache.get(e,n):void 0;if(null!=r)return t.onProgress?.(new Yf("dns:cache",r)),r;const i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),o=[];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){o.push(e),t.onProgress?.(new Yf("dns:error",e))}}throw new lm(o,`DNS lookup of ${e} ${n} failed`)}}var xm;!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(xm||(xm={}));const Em=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:[xm.TXT]}),s=e.getComponents().find(e=>"p2p"===e.name)?.value,o=[];for(const e of i.Answer){const t=e.data.replace(/["']/g,"").trim().split("=")[1];null!=t&&(null==s||t.includes(s))&&o.push(Uu(t))}return o}getDNS(e){return null!=e.dns?e.dns:(null==this.dns&&(this.dns=function(e={}){return new Pm(e)}()),this.dns)}};async function Sm(e,t,n){const r=n.depth??0;if(r>(n.maxRecursiveDepth??32))throw new $f("Max recursive depth reached");let i=!1;const s=[];for(const o of Object.values(t))if(o.canResolve(e)){i=!0;const a=await o.resolve(e,n);for(const e of a)s.push(...await Sm(e,t,{...n,depth:r+1}))}return!1===i&&s.push(e),s}const Am={maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Em}};class km{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Am.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Am.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Am.dialTimeout,this.connections=t.connections??new fd,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Am.resolvers,this.shutDownController=new AbortController,this.queue=new jc({concurrency:t.maxParallelDials??Am.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",e=>{e.detail?.error.name!==ot.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}=Jf(e);if(null!=n&&!0!==t.force){const e=tm(n,this.connections.get(n),r);if(null!=e)return this.log("already connected to %a",e.remoteAddr),t.onProgress?.(new Yf("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 Yf("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new kt("Dial queue is full");return this.log("creating dial target for %p",n,r.map(e=>e.toString())),t.onProgress?.(new Yf("dial-queue:add-to-dial-queue")),this.queue.add(async e=>{e.onProgress?.(new Yf("dial-queue:start-dial"));const t=hc([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}},{peerId:n,priority:t.priority??Nm,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,o=0,a=0;const u=[];for(this.log("starting dial to %p",n);s||r.size>0;){a++,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===a?"starting":"continuing",n,d.map(e=>e.multiaddr.toString())),e?.onProgress?.(new Yf("dial-queue:calculated-addresses",d));for(const r of d){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,e.peerId),new kt("Peer had more than maxPeerAddrsToDial");o++;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:{[sm]:Ir(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:{[im]:Ir(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 St(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:Uu(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new kt("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new Rf("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 Sm(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===mu)?.value;return null==e||null==n||e.equals(n)}),o=new Map;for(const e of s){const t=e.multiaddr.toString(),n=o.get(t);null==n?o.set(t,e):n.isCertified=n.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new Nf("The dial request has no valid addresses");const u=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||u.push(e);const d=null==this.addressSorter?u.sort(om).sort(dm).sort(cm).sort(um).sort(am):u.sort(this.addressSorter);if(0===d.length)throw new Rf("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=>!mf.matches(e.multiaddr))}catch{}return!1}}const Cm=Object.prototype.toString,Im=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 Dm(e,t,{min:n=0,allowInfinity:r=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be ≥ ${n}.`)}}class Mm extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}function Fm(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Rm({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){const s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof Mm)throw s.originalError;const o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,a=i.maxRetryTime??Number.POSITIVE_INFINITY,u=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(u),Fm(r,a)<=0)throw s;const d=await i.shouldConsumeRetry(u),c=Fm(r,a);if(c<=0||o<=0)throw s;if(s instanceof TypeError&&!function(e){const t=e&&(e=>"[object Error]"===Cm.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(")"))||Im.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 Lm{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 Uc({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);_m(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,Dm("factor",t.factor,{min:0,allowInfinity:!1}),Dm("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),Dm("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),Dm("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 Rm({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(qt)&&(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=>_m(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 _m(e){for(const t of e.tags.keys())if(t.startsWith(qt))return!0;return!1}const Nm=50;class Om{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 dt("Connection Manager maxConnections must be greater than 0");this.connections=new fd,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=>Xf(Uu(e))),this.deny=(t.deny??[]).map(e=>Xf(Uu(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new qc({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new nm({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(e=>Uu(e))}),this.dialQueue=new km(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Em},connections:this.connections}),this.reconnectQueue=new Lm({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 zt(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 Vt(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const n of t)e.push(Promise.all([Yd(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 dt("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 At("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:n,multiaddrs:r}=Jf(e);if(this.peerId.equals(n))throw new gt("Can not dial self");if(null!=n&&!0!==t.force){this.log("dial %p",n);const e=tm(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 Yf("dial-queue:already-connected")),e}const i=await this.dialQueue.dial(e,{...t,priority:t.priority??Nm});if("open"!==i.status)throw new lt("Remote closed connection during opening");let s=this.connections.get(i.remotePeer);null==s&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(const e of s)if(e.id===i.id&&(o=!0),!0!==t.force&&e.id!==i.id&&e.remoteAddr.equals(i.remoteAddr))return i.abort(new vt("Duplicate multiaddr connection")),e;return o||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([Yd(e,"close",t),e.close(t)])}catch(t){e.abort(t)}}))}acceptIncomingConnection(e){if(this.deny.some(t=>{if(_d(e.remoteAddr)){const n=Id(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(_d(e.remoteAddr)){const n=Id(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(_d(e.remoteAddr)){const t=Id(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=>Uu(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Bm{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 mc({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ht]=["@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=Ic(r);t=Date.now(),await Promise.all([i.write(wa(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 Um{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:Dr(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:Dr(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 Cf("No content routers available");const n=this,r=new md;for await(const i of bc(...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 Cf("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 Cf("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 At;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 At;return Promise.any(this.routers.filter(e=>e.get instanceof Function).map(async n=>n.get(e,t)))}}const jm=globalThis.CustomEvent??Event;async function*qm(e,t={}){let n=t.concurrency??Infinity;n<1&&(n=Infinity);const r=t.ordered??!1,i=new EventTarget,s=[];let o,a=zd(),u=zd(),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,a.resolve(),e.err;yield e.value,a.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,a.resolve(),t.err;yield t.value,a.resolve()}}for(i.addEventListener("task-complete",()=>{u.resolve()}),Promise.resolve().then(async()=>{try{for await(const t of e){if(s.length===n&&(a=zd(),await a.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 jm("task-complete"))},t=>{e.done=!0,e.err=t,i.dispatchEvent(new jm("task-complete"))})}d=!0,i.dispatchEvent(new jm("task-complete"))}catch(e){o=e,i.dispatchEvent(new jm("task-complete"))}});;){if(l()||(u=zd(),await u.promise),null!=o)throw o;if(r?yield*p():yield*h(),null!=o)throw o;if(d&&0===s.length)break}}class $m{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:Dr(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 If("No peer routers available");if(e.toString()===this.peerId.toString())throw new Df("Should not try to find self");const n=this,r=bc(...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 bt}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new If("No peer routers available");const n=this,r=kd(1024);for await(const i of qm(async function*(){const r=bc(...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 zm extends Wt{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=hc([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=zd();const e=await Yd(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=hc([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=wa(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 ic(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 Vm{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=Gc({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Mf(`No handler registered for protocol ${e}`);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&!0!==n?.force)throw new Ff(`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 dt("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 Gm{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Gc({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Gc({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Kt.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new dt("Transport must have a valid tag");if(this.transports.has(t))throw new dt(`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 qf(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Yf("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 At("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 Lf)});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 o=this.listeners.get(r)??[];null==o&&(o=[],this.listeners.set(r,o)),o.push(s),s.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:s})}),s.addEventListener("close",()=>{const e=o.findIndex(e=>e===s);o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:s})}),Wh.matches(e)?t.ipv4.attempts++:Hh.matches(e)&&t.ipv6.attempts++,n.push(s.listen(e).then(()=>{t.errors.delete(e.toString()),Wh.matches(e)&&t.ipv4.success++,Hh.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!==Kt.NO_FATAL)throw new _f(`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 Km="/multistream/1.0.0",Wm=Ir("\n");async function Hm(e,t){const n=(await e.read(t)).subarray();if(0===n.byteLength||n[n.length-1]!==Wm[0])throw new xt("Missing newline");return Dr(n).trimEnd()}async function Qm(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=Dc(e,{...n,maxDataLength:1024});for(let e=0;e<t.length;e++){const s=t[e];let o;if(0===e){r.trace('write ["%s", "%s"]',Km,s);const e=Ir(`${Km}\n`),t=Ir(`${s}\n`);if(await i.writeV([e,t],n),r.trace("reading multistream-select header"),o=await Hm(i,n),r.trace('read "%s"',o),o!==Km){r.error("did not read multistream-select header from response");break}}else r.trace('write "%s"',s),await i.write(Ir(`${s}\n`),n);if(r.trace("reading protocol response"),o=await Hm(i,n),r.trace('read "%s"',o),o===s)return r.trace('selected "%s" after negotiation',o),i.unwrap(),s}throw new Pt(`Protocol selection failed - could not negotiate ${t}`)}async function Ym(e,t,n={}){t=Array.isArray(t)?t:[t];const r=e.log.newScope("mss:handle"),i=Dc(e,{...n,maxDataLength:1024,maxLengthLength:2});for(;;){r.trace("reading incoming string");const e=await Hm(i,n);if(r.trace('read "%s"',e),e!==Km){if(t.includes(e))return r.trace('respond with "%s" for "%s"',e,e),await i.write(Ir(`${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(Ir("na\n"),n),r('responded with "na" for "%s"',e);else{const s=new rr(...t.map(e=>Oc.single(Ir(`${e}\n`))),Ir("\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"',Km,e),await i.write(Ir(`${Km}\n`),n),r.trace('responded with "%s" for "%s"',Km,e)}}class Jm extends Wt{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??rm,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??rm,this.closeTimeout=t.closeTimeout??1e3,this.direct=em(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),null==this.remoteAddr.getComponents().find(e=>e.code===mu)&&(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 Lt(e.local,e.error))})}[Symbol.toStringTag]="Connection";[it]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(null==this.muxer)throw new Uf("Connection is not multiplexed");if("open"!==this.muxer.status)throw new lt(`The connection muxer is "${this.muxer.status}" and not "open"`);if("open"!==this.maConn.status)throw new lt(`The connection is "${this.status}" and not "open"`);if(null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new It("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 Qm(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=Zm(n.protocol,"outbound",this);if(i>r){const e=new Mt(`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 Ym(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(Zm(t.protocol,"inbound",this)>e)throw new Dt(`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 It("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 Zm(e,t,n){let r=0;return n.streams.forEach(n=>{n.direction===t&&n.protocol===e&&r++}),r}class Xm{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Gc({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(e=>{this.connectionEncrypters.set(e.protocol,e)}),this.streamMuxers=Gc({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??rm,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??rm,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 Of(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){return hc([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 Bf("Connection denied");await ic(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===mu)?.value;let r;null!=n&&(r=eu(n),await ic(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,o,a=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),a=await r.protect(a,n))}try{if(function(e){return!0===e.skipEncryption}(n)){if(null==n.remotePeer)throw new vt(`${t} connection that skipped encryption must have a peer id`);o="native",r=n.remotePeer}else{const s=e.remoteAddr.getComponents().findLast(e=>e.code===mu)?.value;let u;null!=s&&(u=eu(s)),n?.onProgress?.(new Yf(`upgrader:encrypt-${t}-connection`)),({connection:a,remotePeer:r,protocol:o,streamMuxer:i}=await("inbound"===t?this._encryptInbound(a,{...n,remotePeer:u}):this._encryptOutbound(a,{...n,remotePeer:u})))}if(r.equals(this.components.peerId)){const t=new gt("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 Yf(`upgrader:multiplex-${t}-connection`)),i=await("inbound"===t?this._multiplexInbound(a,this.streamMuxers,n):this._multiplexOutbound(a,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(a)),await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",r,e);const d=this._createConnection({id:u,cryptoProtocol:o,direction:t,maConn:e,stream:a,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 Jm(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 Ym(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new jf(`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 jf(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 Qm(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new jf(`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 jf(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 Qm(e,r,n),s=t.get(i);if(null==s)throw new Uf(`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 Uf(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 Ym(e,r,n),s=t.get(i);if(null==s)throw new Uf(`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 ey="3.1.6",ty="js-libp2p";class ny extends Wt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Wt,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??dd(),this.log=this.logger.forComponent("libp2p"),this.services={};const r=e.nodeInfo?.name??ty,i=e.nodeInfo?.version??ey,s=this.components=function(e={}){const t=new zf(e),n=new Proxy(t,{get(e,n,r){if("string"==typeof n&&!Gf.includes(n)){const e=t.components[n];if(null==e&&!Vf.includes(n))throw new Af(`${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??(o=r,a=i,`${o??ty}/${a??ey} browser/${globalThis.navigator.userAgent}`)},logger:this.logger,events:t,datastore:e.datastore??new Dh,connectionGater:Qf(e.connectionGater),dns:e.dns});var o,a;null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new Ph(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 Xm(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 Gm(this.components,e.transportManager)),this.configureComponent("connectionManager",new Om(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Bm(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Vm(this.components)),this.configureComponent("addressManager",new Ef(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 $m(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 Um(this.components,{routers:d})),this.configureComponent("randomWalk",new zm(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[st]&&(this.log("registering service %s for content routing",t),d.push(n[st])),null!=n[jt]&&(this.log("registering service %s for peer routing",t),u.push(n[jt])),null!=n[Ot]&&(this.log("registering service %s for peer discovery",t),n[Ot].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 Kf(n))t[e]=!0;for(const n of Object.values(e.components))for(const e of Wf(n))if(!0!==t[e])throw new kf(`Service "${Hf(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 md;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 dt("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new dt("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={}){Bu(e)&&(e=eu(e.getComponents().findLast(e=>e.code===mu)?.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=Xn([Ir("/pk/"),e.toMultihash().bytes]),r=Ka(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 ry=65535,iy=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function sy(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function oy(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ay(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 uy(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 dy(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function cy(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const ly=/* @__PURE__ */(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])(),py=(e,t)=>{function n(n,...r){if(ay(n,void 0,"key"),!ly)throw new Error("Non little-endian hardware is not yet supported");void 0!==e.nonceLength&&ay(r[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");const i=e.tagLength;i&&void 0!==r[1]&&ay(r[1],void 0,"AAD");const s=t(n,...r),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");ay(t,void 0,"output")}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,ay(e),o(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(ay(e),i&&e.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return o(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(n,e),n};function hy(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 fy(e){return Uint8Array.from(e)}const my=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),yy=my("expand 16-byte k"),by=my("expand 32-byte k"),gy=dy(yy),vy=dy(by);function wy(e,t){return e<<t|e>>>32-t}function Ty(e){return e.byteOffset%4==0}const Py=2**32-1,xy=Uint32Array.of();function Ey(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=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 oy(i),oy(o),sy(s),sy(n),(t,a,u,d,c=0)=>{ay(t,void 0,"key"),ay(a,void 0,"nonce"),ay(u,void 0,"data");const l=u.length;if(void 0===d&&(d=new Uint8Array(l)),ay(d,void 0,"output"),oy(c),c<0||c>=Py)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=fy(t)),f=vy;else{if(16!==m||!n)throw ay(t,32,"arx key"),new Error("invalid key size");h=new Uint8Array(32),h.set(t),h.set(t,16),f=gy,p.push(h)}Ty(a)||p.push(a=fy(a));const y=dy(h);if(r){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");r(f,y,dy(a.subarray(0,16)),y),a=a.subarray(16)}const b=16-i;if(b!==a.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(12!==b){const e=new Uint8Array(12);e.set(a,s?0:12-a.length),p.push(a=e)}const g=dy(a);return function(e,t,n,r,i,s,o,a){const u=i.length,d=new Uint8Array(64),c=dy(d),l=Ty(i)&&Ty(s),p=l?dy(i):xy,h=l?dy(s):xy;for(let f=0;f<u;o++){if(e(t,n,r,c,o,a),o>=Py)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,o),cy(...p),d}}function Sy(e,t){return 255&e[t++]|(255&e[t++])<<8}class Ay{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=Sy(e=fy(ay(e,32,"key")),0),n=Sy(e,2),r=Sy(e,4),i=Sy(e,6),s=Sy(e,8),o=Sy(e,10),a=Sy(e,12),u=Sy(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|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|u<<8),this.r[9]=u>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Sy(e,16+2*t)}process(e,t,n=!1){const r=n?0:2048,{h:i,r:s}=this,o=s[0],a=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=Sy(e,t+0),b=Sy(e,t+2),g=Sy(e,t+4),v=Sy(e,t+6),w=Sy(e,t+8),T=Sy(e,t+10),P=Sy(e,t+12),x=Sy(e,t+14);let E=i[0]+(8191&y),S=i[1]+(8191&(y>>>13|b<<3)),A=i[2]+(8191&(b>>>10|g<<6)),k=i[3]+(8191&(g>>>7|v<<9)),C=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|P<<5)),F=i[8]+(8191&(P>>>8|x<<8)),R=i[9]+(x>>>5|r),L=0,_=L+E*o+S*(5*m)+A*(5*f)+k*(5*h)+C*(5*p);L=_>>>13,_&=8191,_+=I*(5*l)+D*(5*c)+M*(5*d)+F*(5*u)+R*(5*a),L+=_>>>13,_&=8191;let N=L+E*a+S*o+A*(5*m)+k*(5*f)+C*(5*h);L=N>>>13,N&=8191,N+=I*(5*p)+D*(5*l)+M*(5*c)+F*(5*d)+R*(5*u),L+=N>>>13,N&=8191;let O=L+E*u+S*a+A*o+k*(5*m)+C*(5*f);L=O>>>13,O&=8191,O+=I*(5*h)+D*(5*p)+M*(5*l)+F*(5*c)+R*(5*d),L+=O>>>13,O&=8191;let B=L+E*d+S*u+A*a+k*o+C*(5*m);L=B>>>13,B&=8191,B+=I*(5*f)+D*(5*h)+M*(5*p)+F*(5*l)+R*(5*c),L+=B>>>13,B&=8191;let U=L+E*c+S*d+A*u+k*a+C*o;L=U>>>13,U&=8191,U+=I*(5*m)+D*(5*f)+M*(5*h)+F*(5*p)+R*(5*l),L+=U>>>13,U&=8191;let j=L+E*l+S*c+A*d+k*u+C*a;L=j>>>13,j&=8191,j+=I*o+D*(5*m)+M*(5*f)+F*(5*h)+R*(5*p),L+=j>>>13,j&=8191;let q=L+E*p+S*l+A*c+k*d+C*u;L=q>>>13,q&=8191,q+=I*a+D*o+M*(5*m)+F*(5*f)+R*(5*h),L+=q>>>13,q&=8191;let $=L+E*h+S*p+A*l+k*c+C*d;L=$>>>13,$&=8191,$+=I*u+D*a+M*o+F*(5*m)+R*(5*f),L+=$>>>13,$&=8191;let z=L+E*f+S*h+A*p+k*l+C*c;L=z>>>13,z&=8191,z+=I*d+D*u+M*a+F*o+R*(5*m),L+=z>>>13,z&=8191;let V=L+E*m+S*f+A*h+k*p+C*l;L=V>>>13,V&=8191,V+=I*c+D*d+M*u+F*a+R*o,L+=V>>>13,V&=8191,L=(L<<2)+L|0,L=L+_|0,_=8191&L,L>>>=13,N+=L,i[0]=_,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;cy(n)}update(e){uy(this),ay(e),e=fy(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(){cy(this.h,this.r,this.buffer,this.pad)}digestInto(e){uy(this),function(e,t){ay(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 ky=/** @__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 Ay(e)))();function Cy(e,t,n,r,i,s=20){let o=e[0],a=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],P=o,x=a,E=u,S=d,A=c,k=l,C=p,I=h,D=f,M=m,F=y,R=b,L=g,_=v,N=w,O=T;for(let e=0;e<s;e+=2)P=P+A|0,L=wy(L^P,16),D=D+L|0,A=wy(A^D,12),P=P+A|0,L=wy(L^P,8),D=D+L|0,A=wy(A^D,7),x=x+k|0,_=wy(_^x,16),M=M+_|0,k=wy(k^M,12),x=x+k|0,_=wy(_^x,8),M=M+_|0,k=wy(k^M,7),E=E+C|0,N=wy(N^E,16),F=F+N|0,C=wy(C^F,12),E=E+C|0,N=wy(N^E,8),F=F+N|0,C=wy(C^F,7),S=S+I|0,O=wy(O^S,16),R=R+O|0,I=wy(I^R,12),S=S+I|0,O=wy(O^S,8),R=R+O|0,I=wy(I^R,7),P=P+k|0,O=wy(O^P,16),F=F+O|0,k=wy(k^F,12),P=P+k|0,O=wy(O^P,8),F=F+O|0,k=wy(k^F,7),x=x+C|0,L=wy(L^x,16),R=R+L|0,C=wy(C^R,12),x=x+C|0,L=wy(L^x,8),R=R+L|0,C=wy(C^R,7),E=E+I|0,_=wy(_^E,16),D=D+_|0,I=wy(I^D,12),E=E+I|0,_=wy(_^E,8),D=D+_|0,I=wy(I^D,7),S=S+A|0,N=wy(N^S,16),M=M+N|0,A=wy(A^M,12),S=S+A|0,N=wy(N^S,8),M=M+N|0,A=wy(A^M,7);let B=0;r[B++]=o+P|0,r[B++]=a+x|0,r[B++]=u+E|0,r[B++]=d+S|0,r[B++]=c+A|0,r[B++]=l+k|0,r[B++]=p+C|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+L|0,r[B++]=v+_|0,r[B++]=w+N|0,r[B++]=T+O|0}const Iy=/* @__PURE__ */Ey(Cy,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Dy=/* @__PURE__ */new Uint8Array(16),My=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(Dy.subarray(n))},Fy=/* @__PURE__ */new Uint8Array(32);function Ry(e,t,n,r,i){void 0!==i&&ay(i,void 0,"AAD");const s=e(t,n,Fy),o=function(e,t,n){sy(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),a=ky.create(s);i&&My(a,i),My(a,r),a.update(o);const u=a.digest();return cy(s,o),u}const Ly=/* @__PURE__ */py({blockSize:64,nonceLength:12,tagLength:16},(_y=Iy,(e,t,n)=>({encrypt(r,i){const s=r.length;(i=hy(s+16,i,!1)).set(r);const o=i.subarray(0,-16);_y(e,t,o,o,1);const a=Ry(_y,e,t,o,n);return i.set(a,s),cy(a),i},decrypt(r,i){i=hy(r.length-16,i,!1);const s=r.subarray(0,-16),o=r.subarray(-16),a=Ry(_y,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}(o,a))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),_y(e,t,i,i,1),cy(a),i}})));var _y;function Ny(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Oy(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 By(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");Ny(e.outputLen),Ny(e.blockLen)}function Uy(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 jy(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function qy(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function $y(e,t){return e<<32-t|e>>>t}const zy=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Vy=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Gy(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Ky(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 Wy(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 Hy=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Qy(e,t,n){return e&t^~e&n}function Yy(e,t,n){return e&t^e&n^t&n}class Jy{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=qy(this.buffer)}update(e){Uy(this),Oy(e);const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o!==r)n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=qy(e);for(;r<=i-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Uy(this),function(e,t){Oy(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,jy(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 o=qy(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<u;e++)o.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:o}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Zy=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xy=/* @__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]),eb=/* @__PURE__ */new Uint32Array(64);class tb extends Jy{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[e,t,n,r,i,s,o,a]}set(e,t,n,r,i,s,o,a){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|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)eb[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=eb[e-15],n=eb[e-2],r=$y(t,7)^$y(t,18)^t>>>3,i=$y(n,17)^$y(n,19)^n>>>10;eb[e]=i+eb[e-7]+r+eb[e-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:u,H:d}=this;for(let e=0;e<64;e++){const t=d+($y(o,6)^$y(o,11)^$y(o,25))+Qy(o,a,u)+Xy[e]+eb[e]|0,c=($y(n,2)^$y(n,13)^$y(n,22))+Yy(n,r,i)|0;d=u,u=a,a=o,o=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,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,r,i,s,o,a,u,d)}roundClean(){jy(eb)}destroy(){this.set(0,0,0,0,0,0,0,0),jy(this.buffer)}}class nb extends tb{A=0|Zy[0];B=0|Zy[1];C=0|Zy[2];D=0|Zy[3];E=0|Zy[4];F=0|Zy[5];G=0|Zy[6];H=0|Zy[7];constructor(){super(32)}}const rb=/* @__PURE__ */Ky(()=>new nb
4
- /* @__PURE__ */,Hy(1)),ib=/* @__PURE__ */BigInt(0);function sb(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?ib:BigInt("0x"+e)}(function(e){if(Oy(e),zy)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Vy[e[n]];return t}(ob(Oy(e)).reverse()))}function ob(e){return Uint8Array.from(e)}const ab=e=>"bigint"==typeof e&&ib<=e;function ub(e,t,n,r){if(!function(e,t,n){return ab(e)&&ab(t)&&ab(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const db=/* @__PURE__ */BigInt(0);function cb(e,t){const n=e%t;return n>=db?n:t+n}function lb(e,t,n){let r=e;for(;t-- >db;)r*=r,r%=n;return r}function pb(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 hb=BigInt(0),fb=BigInt(1),mb=BigInt(2),yb=BigInt(1),bb=BigInt(2),gb=/* @__PURE__ */BigInt(3),vb=BigInt(5),wb=(BigInt(8),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"));function Tb(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Pb=/* @__PURE__ */(()=>{const e=wb;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:o,randomBytes:a}=t,u="x25519"===i;if(!u&&"x448"!==i)throw new Error("invalid type");const d=a||Wy,c=u?255:448,l=u?32:56,p=u?BigInt(9):BigInt(5),h=u?BigInt(121665):BigInt(39081),f=u?mb**BigInt(254):mb**BigInt(447),m=u?BigInt(8)*mb**BigInt(251)-fb:BigInt(4)*mb**BigInt(445)-fb,y=f+m+fb,b=e=>cb(e,r),g=v(p);function v(e){return function(e,t){return function(e,t){Ny(t);const n=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(zy)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=Gy(e.charCodeAt(i)),s=Gy(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(!ab(e))throw new Error("positive bigint expected, got "+e)}else Ny(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){ub("u",e,hb,r),ub("scalar",t,f,y);const n=t,i=e;let s=fb,a=hb,u=e,d=fb,l=hb;for(let e=BigInt(c-1);e>=hb;e--){const t=n>>e&fb;l^=t,({x_2:s,x_3:u}=E(l,s,u)),({x_2:a,x_3:d}=E(l,a,d)),l=t;const r=s+a,o=b(r*r),c=s-a,p=b(c*c),f=o-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(o*p),a=b(f*(o+b(h*f)))}({x_2:s,x_3:u}=E(l,s,u)),({x_2:a,x_3:d}=E(l,a,d));const p=o(a);return b(s*p)}(function(e){const t=ob(Oy(e,l,"uCoordinate"));return u&&(t[31]&=127),b(sb(t))}(t),function(e){return sb(s(ob(Oy(e,l,"scalar"))))}(e));if(n===hb)throw new Error("invalid private or public key received");return v(n)}function T(e){return w(e,g)}const P=T,x=w;function E(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))=>(Oy(e,S.seed,"seed"),e),k={randomSecretKey:A};return Object.freeze({keygen:pb(A,P),getSharedSecret:x,getPublicKey:P,scalarMult:w,scalarMultBase:T,utils:k,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=wb,o=e*e%s*e%s,a=lb(o,bb,s)*o%s,u=lb(a,yb,s)*e%s,d=lb(u,vb,s)*u%s,c=lb(d,t,s)*d%s,l=lb(c,n,s)*c%s,p=lb(l,r,s)*l%s,h=lb(p,i,s)*p%s,f=lb(h,i,s)*p%s,m=lb(f,t,s)*d%s;return{pow_p_5_8:lb(m,bb,s)*e%s,b2:o}}(t);return cb(lb(n,gb,e)*r,e)},adjustScalarBytes:Tb})})();class xb{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(By(e),Oy(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),jy(r)}update(e){return Uy(this),this.iHash.update(e),this}digestInto(e){Uy(this),Oy(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:o}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=o,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 Eb=(e,t,n)=>new xb(e,t).update(n).digest();Eb.create=(e,t)=>new xb(e,t);const Sb=/* @__PURE__ */Uint8Array.of(0),Ab=/* @__PURE__ */Uint8Array.of(),kb={hashSHA256:e=>rb(e.subarray()),getHKDF(e,t){const n=function(e,t,n){return By(e),void 0===n&&(n=new Uint8Array(e.outputLen)),Eb(e,n,t)}(rb,t,e),r=function(e,t,n,r=32){By(e),Ny(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=Ab:Oy(n,void 0,"info");const o=new Uint8Array(s*i),a=Eb.create(e,t),u=a._cloneInto(),d=new Uint8Array(a.outputLen);for(let e=0;e<s;e++)Sb[0]=e+1,u.update(0===e?Ab:d).update(n).update(Sb).digestInto(d),o.set(d,i*e),a._cloneInto(u);return a.destroy(),u.destroy(),jy(d,Sb),o.slice(0,r)}(rb,n,void 0,96),i=r;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){const e=Pb.utils.randomSecretKey();return{publicKey:Pb.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Pb.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Pb.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,n,r)=>Ly(r,t,n).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,n,r,i)=>Ly(r,t,n).decrypt(e.subarray(),i)},Cb=kb,Ib=e=>{const t=Zn(2);return t[0]=e>>8,t[1]=e,t};Ib.bytes=2;const Db=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function Mb(e,t){t.enabled&&iy&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${Dr(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${Dr(e.privateKey,"hex")}`)):t("Missing local static keys."))}function Fb(e,t){t.enabled&&iy&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Dr(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Dr(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Rb(e,t){t.enabled&&iy&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Dr(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Lb(e,t,n){n.enabled&&iy&&(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&Dr(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&Dr(t.k,"hex")}`))}function _b(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");const n=Zn(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}Db.bytes=2;class Nb extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Nb.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Ob{n;bytes;view;constructor(e=0){this.n=e,this.bytes=Jn(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 Bb=Jn(0);class Ub{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Ob(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 jb{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const n=Ir(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=Jn(32);return e.set(t),e}return e.hash(t)}(e,n),this.ck=this.h,this.cs=new Ub(e)}mixKey(e){const[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Ub(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new rr(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,Bb);return[new Ub(this.crypto,e),new Ub(this.crypto,t)]}}class qb{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:n,prologue:r,initiator:i,s:s,e:o,rs:a,re:u}=e;this.crypto=t,this.ss=new jb(t,n),this.ss.mixHash(r),this.initiator=i,this.s=s,this.e=o,this.rs=a,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 $b extends qb{writeMessageA(e){return new rr(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new rr(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new rr(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Nb(`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 Nb(`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 Nb(`handshake stage 2 validation fail: ${e.message}`)}}}var zb,Vb,Gb,Kb,Wb;async function Hb(e,t,n){const r=await e.sign(Yb(t));return Vb.encode({identityKey:Wa(e.publicKey),identitySig:r,extensions:n})}async function Qb(e,t,n){try{const r=Vb.decode(e),i=Ka(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=Yb(t);if(!await i.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(e){throw new at(e.message)}}function Yb(e){const t=Ir("noise-libp2p-static-key:");return e instanceof Uint8Array?Xn([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=Xp((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 eh('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 eh('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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(zb||(zb={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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),zb.codec().encode(e.extensions,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={identityKey:Jn(0),identitySig:Jn(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=zb.codec().decode(e,e.uint32(),{limits:n.limits?.extensions});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Vb||(Vb={}));class Jb extends dc{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 Fc({lengthDecoder:Db,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 rr;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(Ib(r.byteLength)),t.append(r)}return t}decrypt(e){const t=new rr;for(let n=0;n<e.byteLength;n+=ry){let r,i=n+ry;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 Zb(e,t,n){return new Jb(e,t,n)}class Xb{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){const{staticNoiseKey:n,extensions:r,crypto:i,prologueBytes:s}=t,{metrics:o}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const a=i??Cb;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}}(a),this.extensions={webtransportCerthashes:[],...r},this.metrics=o?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"})}}(o):void 0,this.staticKey=n?a.generateX25519KeyPairFromSeed(n):a.generateX25519KeyPair(),this.prologue=s??Jn(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ht]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const n=e.log?.newScope("noise")??this.log,r=Dc(e,{lengthEncoder:Ib,lengthDecoder:Db,maxDataLength:ry}),i=await this.performHandshakeInitiator(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Ka(i.payload.identityKey);return{connection:Zb(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:tu(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 ut("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=Dc(e,{lengthEncoder:Ib,lengthDecoder:Db,maxDataLength:ry}),i=await this.performHandshakeResponder(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Ka(i.payload.identityKey);return{connection:Zb(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:tu(s),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,r,i){let s;const o=!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:o,s:a,remoteIdentityKey:u,extensions:d}=e,c=await Hb(s,a.publicKey,d),l=new $b({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});Mb(l.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(l.writeMessageA(Bb),t),n.trace("Stage 0 - Initiator finished sending first message."),Fb(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."),Rb(l.re,n),h=l.rs,(f=n).enabled&&iy&&f(h?`REMOTE_STATIC_PUBLIC_KEY ${Dr(h.subarray(),"hex")}`:"Missing remote static public key."),n.trace("Initiator going to check remote's signature...");const m=await Qb(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 Lb(y,b,n),{payload:m,encrypt:e=>y.encryptWithAd(Bb,e),decrypt:(e,t)=>b.decryptWithAd(Bb,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:o,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 o=!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:o,s:a,remoteIdentityKey:u,extensions:d}=e,c=await Hb(s,a.publicKey,d),l=new $b({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});Mb(l.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await r.read(t)),n.trace("Stage 0 - Responder received first message."),Rb(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."),Fb(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 Qb(p,l.rs,u),[f,m]=l.ss.split();return Lb(f,m,n),{payload:h,encrypt:e=>m.encryptWithAd(Bb,e),decrypt:(e,t)=>f.decryptWithAd(Bb,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:o,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}}function eg(e={}){return t=>new Xb(t,e)}!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(Gb||(Gb={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(Kb||(Kb={})),Object.values(Kb).filter(e=>"string"!=typeof e),function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(Wb||(Wb={}));const tg=12;class ng extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}}class rg extends ng{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Wb.ProtocolError),this.name="InvalidFrameError"}}class ig extends ng{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Wb.ProtocolError),this.name="UnRequestedPingError"}}class sg extends ng{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Wb.ProtocolError),this.name="NotMatchingPingError"}}class og extends ng{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Wb.ProtocolError),this.name="ReceiveWindowExceededError"}}const ag=262144,ug=2**24;class dg{buffer;constructor(){this.buffer=new rr}*emitFrames(e){for(this.buffer.append(e);;){const e=this.readFrame();if(void 0===e)break;yield e}}readFrame(){let e=tg;if(this.buffer.byteLength<tg)return;const t=function(e){if(0!==e[0])throw new rg("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*ug+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*ug+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,tg));if(t.type===Gb.Data){if(e+=t.length,this.buffer.byteLength<e)return;const n=this.buffer.sublist(tg,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}}function cg(e){const t=new Uint8Array(tg);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 lg;!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"}(lg||(lg={}));class pg extends pc{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){const t=e.initialStreamWindowSize??ag;super({...e,maxMessageSize:t-tg}),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=lg.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(),o=e.sublist(0,i);e.consume(i);const a=this.sendFrame({type:Gb.Data,flag:s,streamID:this.streamId,length:i},o);if(this.sendWindowCapacity-=i,n+=i,!a){r=a,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:Gb.WindowUpdate,flag:Kb.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){const e=this.getSendFlags()|Kb.FIN;this.sendFrame({type:Gb.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=lg.Paused}sendResume(){this.state=lg.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-tg,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===Gb.Data&&null!==e.data}(e))throw new rg("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new og("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&Kb.ACK)===Kb.ACK&&this.state===lg.SYNSent&&(this.state=lg.Established),(e&Kb.FIN)===Kb.FIN&&this.onRemoteCloseWrite(),(e&Kb.RST)===Kb.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case lg.Init:return this.state=lg.SYNSent,Kb.SYN;case lg.SYNReceived:return this.state=lg.Established,Kb.ACK;default:return 0}}sendWindowUpdate(){if(this.state===lg.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:Gb.WindowUpdate,flag:e,streamID:this.streamId,length:r})}}function hg(e){return{type:Gb[e.type],flags:[(e.flag&Kb.SYN)===Kb.SYN?"SYN":void 0,(e.flag&Kb.ACK)===Kb.ACK?"ACK":void 0,(e.flag&Kb.FIN)===Kb.FIN?"FIN":void 0,(e.flag&Kb.RST)===Kb.RST?"RST":void 0].filter(Boolean),streamID:e.streamID,length:e.length}}const fg="/yamux/1.0.0";class mg{protocol=fg;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[Ht]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new yg(e,{...this._init})}}class yg extends lc{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:fg,name:"yamux"}),this.client="outbound"===e.direction,function(e){if(null!=e.keepAliveInterval&&e.keepAliveInterval<=0)throw new dt("keep-alive interval must be positive");if(null!=e.maxInboundStreams&&e.maxInboundStreams<0)throw new dt("max inbound streams must be larger or equal 0");if(null!=e.maxOutboundStreams&&e.maxOutboundStreams<0)throw new dt("max outbound streams must be larger or equal 0");if(null!=e.maxMessageSize&&e.maxMessageSize<1024)throw new dt("MaxMessageSize must be greater than a kilobyte");if(null!=e.streamOptions?.initialStreamWindowSize&&e.streamOptions?.initialStreamWindowSize<ag)throw new dt("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 dt("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(null!=e.streamOptions?.maxStreamWindowSize&&e.streamOptions?.maxStreamWindowSize>2**32-1)throw new dt("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 dg,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=zc(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 ht("Muxer closed remotely");if(void 0!==this.localGoAway)throw new ht("Muxer closed locally");const e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Mt("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);const t=this._newStream(e,lg.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(void 0!==this.remoteGoAway)throw new ht("Muxer closed remotely");if(void 0!==this.localGoAway)throw new ht("Muxer closed locally");if(null!=this.activePing)return ic(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 ic(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??Wb.NormalTermination;this.log.trace("muxer close reason=%s",Wb[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if("open"===this.status)try{super.abort(e);let t=Wb.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 dt("Stream already exists with that id");const r=new pg({...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",hg(e.header)),0===t)switch(n){case Gb.Ping:return void this.handlePing(e.header);case Gb.GoAway:return void this.handleGoAway(r);default:throw new rg("Invalid frame type")}else switch(e.header.type){case Gb.Data:case Gb.WindowUpdate:return void this.handleStreamMessage(e);default:throw new rg("Invalid frame type")}}handlePing(e){if(e.flag===Kb.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Kb.ACK);else{if(e.flag!==Kb.ACK)throw new rg("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 ig("ping not requested");if(this.activePing.id!==e)throw new sg("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Wb[e]??"unknown"),this.remoteGoAway=e,e===Wb.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){const{streamID:t,flag:n,type:r}=e.header;(n&Kb.SYN)===Kb.SYN&&this.incomingStream(t);const i=this.streams.find(e=>e.streamId===t);if(void 0!==i)switch(r){case Gb.WindowUpdate:return void i.handleWindowUpdate(e);case Gb.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 dt("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:Gb.WindowUpdate,flag:Kb.RST,streamID:e,length:0});if(this.numInboundStreams>=this.maxInboundStreams)return this.log("maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:Gb.WindowUpdate,flag:Kb.RST,streamID:e,length:0});const t=this._newStream(e,lg.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Gb.Data){if(null==t)throw new rg("Invalid frame");n=new rr(cg(e),t)}else n=cg(e);return this.log.trace("sending frame %o",hg(e)),this.send(n)}sendPing(e,t=Kb.SYN){this.log.trace(t===Kb.SYN?"sending ping request pingId=%s":"sending ping response pingId=%s",e),this.sendFrame({type:Gb.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Wb.NormalTermination){this.log("sending GoAway reason=%s",Wb[e]),this.localGoAway=e,this.sendFrame({type:Gb.GoAway,flag:0,streamID:0,length:e})}}function bg(e={}){return()=>new mg(e)}const gg=[6,53,56,54,55];function vg(e){return Tg("sni",e)?.value}function wg(e){const t=Tg("tcp",e)?.value;return null==t?"":`:${t}`}function Tg(e,t){return t.find(t=>t.name===e)}function Pg(e){return e.some(({code:e})=>e===yu)}function xg(e,t){const n=Eg[e.name];if(null==n)throw new Error(`Can't interpret protocol ${e.name}`);const r=n(e,t);return e.code===fu?`[${r}]`:r}const Eg={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://${xg(n,t)}:${e.value}`},udp:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`udp://${xg(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`${xg(n,t)}`},p2p:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${xg(n,t)}`},http:(e,t)=>{const n=Pg(t),r=vg(t),i=wg(t);if(n&&null!=r)return`https://${r}${i}`;const s=n?"https://":"http://",o=t.pop();if(null==o)throw new Error("Unexpected end of multiaddr");let a=xg(o,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${xg(n,t)}${decodeURIComponent(e.value??"")}`},tls:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return xg(n,t)},sni:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return xg(n,t)},https:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=xg(n,t);return r=r?.replace("tcp://",""),`https://${r}`},ws:(e,t)=>{const n=Pg(t),r=vg(t),i=wg(t);if(n&&null!=r)return`wss://${r}${i}`;const s=n?"wss://":"ws://",o=t.pop();if(null==o)throw new Error("Unexpected end of multiaddr");let a=xg(o,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=xg(n,t);return r=r?.replace("tcp://",""),`wss://${r}`}};class Sg extends cc{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??4194304,this.checkBufferedAmountTask=zc(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=Ir(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 Ag{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"})})}[Gt]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ht]=["@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 Sg(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=Uu(e).getComponents(),n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");const r=Eg[n.name];if(null==r)throw new Error(`No interpreter found for ${n.name}`);let i=r(n,t)??"";return gg.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 Yf("websockets:open-connection")),await Yd(r,"open",t)}catch(e){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new pt(`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=>sf.exactMatch(e)||af.exactMatch(e))}dialFilter(e){return this.listenFilter(e)}}function kg(e={}){return t=>new Ag(t,e)}class Cg{constructor(){throw new Error("TCP connections are not possible in browsers")}[Gt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Ht]=["@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 Ig(e={}){return t=>new Cg(t,e)}const Dg=`${qt}-circuit-relay`;BigInt(1<<17);const Mg="/libp2p/circuit/relay/0.2.0/hop",Fg="/libp2p/circuit/relay/0.2.0/stop",Rg=new Float32Array([-0]),Lg=new Uint8Array(Rg.buffer);function _g(e,t,n){Rg[0]=e,t[n]=Lg[0],t[n+1]=Lg[1],t[n+2]=Lg[2],t[n+3]=Lg[3]}const Ng=new Float64Array([-0]),Og=new Uint8Array(Ng.buffer);function Bg(e,t,n){Ng[0]=e,t[n]=Og[0],t[n+1]=Og[1],t[n+2]=Og[2],t[n+3]=Og[3],t[n+4]=Og[4],t[n+5]=Og[5],t[n+6]=Og[6],t[n+7]=Og[7]}const Ug=BigInt(Number.MAX_SAFE_INTEGER),jg=BigInt(Number.MIN_SAFE_INTEGER);class qg{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 $g;if(e<Ug&&e>jg)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>zg&&(r=0n,++n>zg&&(n=0n))),new qg(Number(r),Number(n))}static fromNumber(e){if(0===e)return $g;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 qg(n,r)}static from(e){return"number"==typeof e?qg.fromNumber(e):"bigint"==typeof e?qg.fromBigInt(e):"string"==typeof e?qg.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new qg(e.low>>>0,e.high>>>0):$g}}const $g=new qg(0,0);$g.toBigInt=function(){return 0n},$g.zzEncode=$g.zzDecode=function(){return this},$g.length=function(){return 1};const zg=4294967296n;function Vg(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 Gg(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Kg(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Wg{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,Gg(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 Gg(this,4);return Kg(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Gg(this,4);return 0|Kg(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Gg(this,4);const e=(Lg[0]=(t=this.buf)[n=this.pos],Lg[1]=t[n+1],Lg[2]=t[n+2],Lg[3]=t[n+3],Rg[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Gg(this,4);const e=(Og[0]=(t=this.buf)[n=this.pos],Og[1]=t[n+1],Og[2]=t[n+2],Og[3]=t[n+3],Og[4]=t[n+4],Og[5]=t[n+5],Og[6]=t[n+6],Og[7]=t[n+7],Ng[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 Gg(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,o=0;for(;t<n;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(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[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Gg(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Gg(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 qg(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Gg(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 Gg(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 Gg(this,8);const e=Kg(this.buf,this.pos+=4),t=Kg(this.buf,this.pos+=4);return new qg(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=Ro(this.buf,this.pos);return this.pos+=Mo(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 Hg(e){return new Wg(e instanceof Uint8Array?e:e.subarray())}function Qg(e,t,n){const r=Hg(e);return t.decode(r,void 0,n)}class Yg{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Jg(){}class Zg{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Xg=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Zn(r);n+r>e&&(t=Zn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class ev{len;head;tail;states;constructor(){this.len=0,this.head=new Yg(Jg,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Yg(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new rv((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(iv,10,qg.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=qg.fromBigInt(e);return this._push(iv,t.length(),t)}uint64Number(e){return this._push(Fo,Mo(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=qg.fromBigInt(e).zzEncode();return this._push(iv,t.length(),t)}sint64Number(e){const t=qg.fromNumber(e).zzEncode();return this._push(iv,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(tv,1,e?1:0)}fixed32(e){return this._push(sv,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=qg.fromBigInt(e);return this._push(sv,4,t.lo)._push(sv,4,t.hi)}fixed64Number(e){const t=qg.fromNumber(e);return this._push(sv,4,t.lo)._push(sv,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(_g,4,e)}double(e){return this._push(Bg,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(tv,1,0):this.uint32(t)._push(ov,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(Vg,t,e):this._push(tv,1,0)}fork(){return this.states=new Zg(this),this.head=this.tail=new Yg(Jg,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 Yg(Jg,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?Zn(n):Xg(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function tv(e,t,n){t[n]=255&e}function nv(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class rv extends Yg{next;constructor(e,t){super(nv,e,t),this.next=void 0}}function iv(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 sv(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 ov(e,t,n){t.set(e,n)}function av(e,t,n){t.set(e,n)}function uv(e,t,n){e.length<40?Vg(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(Ir(e),n)}function dv(e,t){const n=new ev;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*cv(e,t,n){const r=Hg(e);yield*t.stream(r,void 0,"$",n)}function lv(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function pv(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return lv("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 hv(e,t,n){return lv("message",2,e,t,n)}null!=globalThis.Buffer&&(ev.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(av,t,e),this},ev.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(uv,t,e),this});class fv extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var mv,yv,bv,gv,vv,wv,Tv,Pv,xv;!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=()=>pv(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=hv((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),bv.codec().encode(t.peer,n)),null!=t.reservation&&(n.uint32(26),gv.codec().encode(t.reservation,n)),null!=t.limit&&(n.uint32(34),vv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(40),wv.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=bv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.reservation=gv.codec().decode(t,t.uint32(),{limits:r.limits?.reservation});break;case 4:i.limit=vv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 5:i.status=wv.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*bv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*gv.codec().stream(t,t.uint32(),`${r}.reservation`,{limits:i.limits?.reservation});break;case 4:yield*vv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 5:yield{field:`${r}.status`,value:wv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(mv||(mv={})),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=()=>pv(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=hv((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),bv.codec().encode(t.peer,n)),null!=t.limit&&(n.uint32(26),vv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(32),wv.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=bv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.limit=vv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 4:i.status=wv.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*bv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*vv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 4:yield{field:`${r}.status`,value:wv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(yv||(yv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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:Jn(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 fv('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 fv('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 dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(bv||(bv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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),xv.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 fv('Decode error - repeated field "addrs" had too many elements');r.addrs.push(e.bytes());break;case 3:r.voucher=xv.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 fv('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*xv.codec().stream(e,e.uint32(),`${n}.voucher`,{limits:r.limits?.voucher});break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(gv||(gv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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 dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(vv||(vv={})),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"}(wv||(wv={})),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"}(Tv||(Tv={})),function(e){e.codec=()=>pv(Tv)}(wv||(wv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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:Jn(0),peer:Jn(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 dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(Pv||(Pv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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),Pv.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:Jn(0),payloadType:Jn(0),signature:Jn(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=Pv.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*Pv.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 dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(xv||(xv={}));class Ev extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"}class Sv extends Error{static name="DoubleRelayError";name="DoubleRelayError"}class Av extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"}function kv(e){const t=e*BigInt(1e3),n=(new Date).getTime();return Number(t-BigInt(n))}class Cv{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 Iv=Nh(_h(hf.matchers[0],Mh(wu))),Dv=Nh(Mh(wu));class Mv extends Wt{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(Mg,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){null!=this.topologyId&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");const e=await this.components.peerStore.all({filters:[e=>e.protocols.includes(Mg)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{const n=Fv(e),r=Fv(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 Uc({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=hc([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}}function Fv(e){const t=e.metadata.get("last-dial-success");return null==t?0:new Date(Dr(t)).getTime()}class Rv extends Wt{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(Dv.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else{if(!Iv.exactMatch(e))throw new Ct(`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=>Uu(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}}class Lv extends Wt{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 fd,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??5e3,this.started=!1,this.relayFilter=kd(100),this.reserveQueue=new Uc({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(Dg)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async e=>{await this.peerStore.merge(e.id,{tags:{[Dg]: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 Ct("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Av("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 Ct("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&&kv(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 Ev("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(mf.matches(i.remoteAddr))throw new Sv("not creating reservation over relayed connection");const s=await this.#X(i,{signal:r}),o=kv(s.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+o).toString());const a=Math.min(Math.max(o-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)})},a);let d;if("discovered"===t){const e=this.pendingReservations.pop();if(null==e)throw new Ev("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:{[Dg]:{value:1,ttl:o}}}),this.#Z();const c={relay:e,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:c}),c}catch(r){throw"discovered"===t&&"HadEnoughRelaysError"===r.name||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-n,r),"DialError"!==r.name&&"UnsupportedProtocolError"!==r.name||this.relayFilter.add(e.toMultihash().bytes),this.#J(e).catch(t=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,t)}),r}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return null==e?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#X(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);const n=await e.newStream(Mg,t),r=Mc(n).pb(mv);let i;this.log.trace("send RESERVE to %p",e.remotePeer),await r.write({type:mv.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===wv.OK&&null!=i.reservation){const t=new Set;t.add(e.remoteAddr.toString());for(const n of i.reservation.addrs){let r=Uu(n);null==r.getComponents().find(e=>e.code===mu)&&(r=r.encapsulate(`/p2p/${e.remotePeer}`)),r=Uu(r.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),t.add(r.toString())}return i.reservation.addrs=[...t].map(e=>Uu(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:{[Dg]: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=kd(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}}class _v extends cc{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 Nv(e){return new _v(e)}class Ov{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??300,this.maxOutboundStopStreams=t.maxOutboundStopStreams??300,this.shutdownController=new AbortController,this.discovery=new Mv(e,{filter:t.discoveryFilter??Wc(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 Lv(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";[Ht]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Qt](){return null!=this.discovery?["@libp2p/identify"]:[]}[Gt]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.components.registrar.handle(Fg,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await zt(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Vt(this.discovery,this.reservationStore),await this.components.registrar.unhandle(Fg),this.started=!1}async dial(e,t){const n=e.toString().split("/p2p-circuit"),r=Uu(n[0]),i=Uu(n[n.length-1]),s=r.getComponents().find(e=>e.code===mu)?.value,o=i.getComponents().find(e=>e.code===mu)?.value;if(null==s||null==o){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 kt(`C${t}`)}const a=eu(s),u=eu(o);let d,c=this.components.connectionManager.getConnections(a)[0];null==c?(await this.components.peerStore.merge(a,{multiaddrs:[r]}),t.onProgress?.(new Yf("circuit-relay:open-connection")),c=await this.components.connectionManager.openConnection(a,t)):t.onProgress?.(new Yf("circuit-relay:reuse-connection"));try{t.onProgress?.(new Yf("circuit-relay:open-hop-stream")),d=await c.newStream(Mg,t);const n=Mc(d).pb(mv);t.onProgress?.(new Yf("circuit-relay:write-connect-message")),await n.write({type:mv.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Uu(i).bytes]}},t),t.onProgress?.(new Yf("circuit-relay:read-connect-response"));const s=await n.read(t);if(s.status!==wv.OK)throw new xt(`failed to connect via relay with status ${s?.status?.toString()??"undefined"}`);const o=new Cv(s.limit),a=Nv({stream:n.unwrap().unwrap(),remoteAddr:e,localAddr:r.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:o.onData,onDataWrite:o.onData,log:d.log.newScope("circuit-relay:connection")}),l=await this.components.upgrader.upgradeOutbound(a,{...t,limits:o.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,a,e),d?.abort(e),e}}createListener(e){return function(e){return new Rv(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=>Iv.exactMatch(e)||Dv.exactMatch(e))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter(e=>mf.exactMatch(e))}async onStop(e,t){const n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(e){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",e)}const r=Mc(e).pb(yv),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:yv.Type.STATUS,status:wv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});if(i.type!==yv.Type.CONNECT)return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:yv.Type.STATUS,status:wv.UNEXPECTED_MESSAGE},{signal:n}),void await e.close({signal:n});if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(Uu)}catch{return!1}return!0})(i))return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:yv.Type.STATUS,status:wv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});const s=nu(Bn(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:yv.Type.STATUS,status:wv.PERMISSION_DENIED},{signal:n}),void await e.close({signal:n});this.log.trace("sending success response to %p",t.remotePeer),await r.write({type:yv.Type.STATUS,status:wv.OK},{signal:n});const o=new Cv(i.limit),a=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),u=this.components.addressManager.getAddresses()[0],d=Nv({stream:r.unwrap().unwrap(),remoteAddr:a,localAddr:u,onDataRead:o.onData,onDataWrite:o.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(d,{limits:o.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 Bv(e={}){return t=>new Ov(t,e)}class Uv extends Wt{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=>Uu(e)).filter(e=>{if(!hf.matches(e))return this.log.error("invalid multiaddr %a",e),!1;const t=e.getComponents().findLast(e=>e.code===mu)?.value;return null!=t||(this.log.error("invalid bootstrap multiaddr without peer id"),!1)}).map(e=>({id:eu(e.getComponents().findLast(e=>e.code===mu)?.value??""),multiaddrs:[e]})),this._init=t}[Ot]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Ht]=["@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 jv;!function(e){let t;e.codec=()=>(null==t&&(t=Xp((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 eh('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 eh('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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(jv||(jv={}));const qv="ipfs";async function $v(e,t,n,r,i){if(n("received identify from %p",r.remotePeer),null==i)throw new xt("message was null or undefined");const s={};if(i.listenAddrs.length>0&&(s.addresses=i.listenAddrs.map(e=>({isCertified:!1,multiaddr:Uu(e)}))),i.protocols.length>0&&(s.protocols=i.protocols),null!=i.publicKey){const e=Ka(i.publicKey);if(!tu(e).equals(r.remotePeer))throw new xt("public key did not match remote PeerId");s.publicKey=e}let o;if(null!=i.signedPeerRecord){n.trace("received signedPeerRecord from %p",r.remotePeer);let t=i.signedPeerRecord;const a=await Fl.openAndCertify(t,Nl.DOMAIN);let u=Nl.createFromProtobuf(a.payload);const d=ru(a.publicKey.toCID());if(!u.peerId.equals(d))throw new xt("signing key does not match PeerId in the PeerRecord");if(!r.remotePeer.equals(u.peerId))throw new xt("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=Fl.createFromProtobuf(c.peerRecordEnvelope),r=Nl.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})),o={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=Ir(i.agentVersion)),null!=i.protocolVersion&&(t.ProtocolVersion=Ir(i.protocolVersion)),n.trace("merging %p metadata",r.remotePeer,t),await e.merge(r.remotePeer,{metadata:t})}const a={peerId:r.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map(e=>Uu(e)),observedAddr:null==i.observedAddr?void 0:Uu(i.observedAddr),protocols:i.protocols,signedPeerRecord:o,connection:r};return t.safeDispatchEvent("peer:identify",{detail:a}),a}class zv{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??qv}/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:Ir(this.host.agentVersion),ProtocolVersion:Ir(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 Vv extends zv{connectionManager;concurrency;_push;constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??qv}/id/push/1.0.0`,log:e.logger.forComponent("libp2p:identify-push")}),this.connectionManager=e.connectionManager,this.concurrency=t.concurrency??32,this._push=Jd(this.sendPushMessage.bind(this),t.debounce??1e3),(t.runOnSelfUpdate??1)&&e.events.addEventListener("self:peer:update",e=>{this.push().catch(e=>{this.log.error("error pushing updates to peers - %e",e)})})}[Ht]=["@libp2p/identify-push"];async push(){this._push()}async sendPushMessage(){if(this.isStarted())try{const e=this.components.addressManager.getAddresses().map(e=>e.decapsulateCode(mu)),t=new Nl({peerId:this.components.peerId,multiaddrs:e}),n=await Fl.seal(t,this.components.privateKey),r=this.components.registrar.getProtocols(),i=await this.components.peerStore.get(this.components.peerId),s=Dr(i.metadata.get("AgentVersion")??Ir(this.host.agentVersion)),o=Dr(i.metadata.get("ProtocolVersion")??Ir(this.host.protocolVersion)),a=this;async function*u(){for(const t of a.connectionManager.getConnections())(await a.components.peerStore.get(t.remotePeer)).protocols.includes(a.protocol)&&(yield async()=>{let i;const u=AbortSignal.timeout(a.timeout);try{i=await t.newStream(a.protocol,{signal:u,runOnLimitedConnection:a.runOnLimitedConnection});const d=Mc(i,{maxDataLength:a.maxMessageSize}).pb(jv);await d.write({listenAddrs:e.map(e=>e.bytes),signedPeerRecord:n.marshal(),protocols:r,agentVersion:s,protocolVersion:o},{signal:u}),await i.close({signal:u})}catch(e){const t=i?.log.newScope("identify-push");t?.error("could not push identify update to peer",e),i?.abort(e)}})}await Eh(qm(u(),{concurrency:this.concurrency}))}catch(d){this.log.error("error pushing updates to peers - %e",d)}}async handleProtocol(e,t){const n=e.log.newScope("identify-push");if(this.components.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");const r={signal:AbortSignal.timeout(this.timeout)},i=Mc(e,{maxDataLength:this.maxMessageSize}).pb(jv),s=await i.read(r);await e.close(r),await $v(this.components.peerStore,this.components.events,n,t,s),n.trace("handled push from %p",t.remotePeer)}}class Gv extends zv{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??qv}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??1)&&e.events.addEventListener("connection:open",e=>{this.identify(e.detail).catch(()=>{})})}[Ht]=["@libp2p/identify"];async _identify(e,t={}){let n,r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),r=n.log.newScope("identify");const i=Mc(n,{maxDataLength:this.maxMessageSize}).pb(jv),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 xt("Public key was missing from identify message");const o=ru(Ka(r).toCID());if(!e.remotePeer.equals(o))throw new xt("Identified peer does not match the expected peer");if(this.components.peerId.equals(o))throw new xt("Identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("completed for peer %p and protocols %o",o,i),$v(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Uu(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),$d(t))return;const n=t.getComponents();n[0].code!==fu&&(42!==n[0].code||n[1].code!==fu)||function(e){try{const n=Id(e);return"ip6"===n.type&&(t=n.host,new Rd("2000::/3").contains(t))}catch{return!1}var t}(t)?Jh.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(mu));let o=i.peerRecordEnvelope;if(s.length>0&&null==o){const e=new Nl({peerId:this.components.peerId,multiaddrs:s});o=(await Fl.seal(e,this.components.privateKey,{signal:r})).marshal().subarray()}let a=t.remoteAddr.bytes;Kh.matches(t.remoteAddr)||(a=void 0);const u=Mc(e).pb(jv);n("send response"),await u.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Wa(this.components.privateKey.publicKey),listenAddrs:s.map(e=>e.bytes),signedPeerRecord:o,observedAddr:a,protocols:i.protocols},{signal:r}),n("close write"),await u.unwrap().unwrap().close({signal:r})}}function Kv(e={}){return t=>new Gv(t,e)}function Wv(e={}){return t=>new Vv(t,e)}const Hv=36e5,Qv=48*Hv,Yv=Hv,Jv=Hv,Zv=`${qt}-kad-dht`;var Xv,ew,tw,nw,rw,iw,sw,ow;function aw(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"),o=String(e.getUTCSeconds()).padStart(2,"0"),a=e.getUTCMilliseconds();return`${t}-${n}-${r}T${i}:${s}:${o}.${String(1e3*a*1e3).padStart(9,"0")}Z`}!function(e){let t;e.codec=()=>(null==t&&(t=Xp((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:Jn(0),value:Jn(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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Xv||(Xv={}));class uw{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 Xv.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:aw(this.timeReceived)}}static deserialize(e){const t=Xv.decode(e);return new uw(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),o=parseInt(n[4],10),a=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,o,a,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 uw(e.key,e.value,t)}}function dw(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=Sh(e),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const o=t(i,n++);if("function"==typeof o.then)return async function*(){yield await o;for(const e of r)yield t(e,n++)}();const a=t;return function*(){yield o;for(const e of r)yield a(e,n++)}()}class cw extends Error{constructor(e="Query error"){super(e),this.name="QueryError"}}class lw extends Error{constructor(e="Invalid record"){super(e),this.name="InvalidRecordError"}}class pw extends Error{constructor(e="No selector function configured for prefix"){super(e),this.name="MissingSelectorError"}}function hw(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 fw(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 mw(e,t={}){const n={...e,name:"FINAL_PEER",type:2};return t.onProgress?.(new CustomEvent("kad-dht:query:final-peer",{detail:n})),n}function yw(e,t={}){const n={...e,name:"QUERY_ERROR",type:3};return t.onProgress?.(new CustomEvent("kad-dht:query:query-error",{detail:n})),n}function bw(e,t={}){const n={...e,name:"PROVIDER",type:4};return t.onProgress?.(new CustomEvent("kad-dht:query:provider",{detail:n})),n}function gw(e,t={}){const n={...e,name:"VALUE",type:5};return t.onProgress?.(new CustomEvent("kad-dht:query:value",{detail:n})),n}function vw(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=Xp((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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(ew||(ew={})),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"}(tw||(tw={})),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"}(nw||(nw={})),function(e){e.codec=()=>Zp(nw)}(tw||(tw={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(rw||(rw={})),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"}(iw||(iw={})),function(e){e.codec=()=>Zp(iw)}(rw||(rw={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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),rw.codec().encode(e.connection,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={id:Jn(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 eh('Decode error - map field "multiaddrs" had too many elements');r.multiaddrs.push(e.bytes());break;case 3:r.connection=rw.codec().decode(e);break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(sw||(sw={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.type&&0!==nw[e.type]&&(t.uint32(8),tw.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),sw.codec().encode(n,t);if(null!=e.providers)for(const n of e.providers)t.uint32(74),sw.codec().encode(n,t);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={type:tw.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=tw.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 eh('Decode error - map field "closer" had too many elements');r.closer.push(sw.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 eh('Decode error - map field "providers" had too many elements');r.providers.push(sw.codec().decode(e,e.uint32(),{limits:n.limits?.providers$}));break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(ow||(ow={}));const ww={pk:function(e,t){return 0}};async function Tw(e,t,n){const r=t.key,i=Dr(r).split("/");if(i.length<3)return;const s=e[i[1].toString()];if(null==s)throw new dt(`No validator available for key type "${i[1]}"`);await s(r,t.value,n)}const Pw={pk:async(e,t,n)=>{if(!(e instanceof Uint8Array))throw new dt('"key" must be a Uint8Array');if(e.byteLength<5)throw new dt("Invalid public key record");if("/pk/"!==Dr(e.subarray(0,4)))throw new dt("key was not prefixed with /pk/");const r=Ka(t);if(!Yn(e.slice(4),r.toMultihash().bytes))throw new dt("public key does not match passed in key")}},xw=Ir("/pk/");function Ew(e){return{...e,multiaddrs:e.multiaddrs.filter(e=>!$d(e))}}function Sw(e){return e}async function Aw(e,t){const n=await xr.digest(e);return t?.signal?.throwIfAborted(),n.digest}async function kw(e,t){return Aw(e.toMultihash().bytes,t)}function Cw(e,t){return new ch(`${e}/${Dr(t,"base32")}`,!1)}function Iw(e,t){const n=new Date;return new uw(e,t,n).serialize()}function Dw(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:zn.createV1(85,Bn(Ir(r,"base32"))),peerId:eu(n)}}function Mw(e,t,n){const r=[e,"string"==typeof t?t:Dr(t.multihash.bytes,"base32")];return null!=n&&r.push(n.toString()),new ch(r.join("/"))}function Fw(e){return new Date(_o(e))}function Rw(e,t,n){return async function*(...r){const i=t.queryTime?.timer(n),s=t.errorTime?.timer(n);let o=!1;try{t.queries?.increment({[n]:!0}),yield*e(...r)}catch(e){throw o=!0,s?.(),t.errors?.increment({[n]:!0}),e}finally{t.queries?.decrement({[n]:!0}),o||i?.()}}}function Lw(e,t,n){return async function(...r){const i=t?.queryTime?.timer(n),s=t?.errorTime?.timer(n);let o=!1;try{return t.queries?.increment({[n]:!0}),await e(...r)}catch(e){throw o=!0,s?.(),t.errors?.increment({[n]:!0}),e}finally{t.queries?.decrement({[n]:!0}),o||i?.()}}}class _w{log;components;validators;selectors;peerRouting;queryManager;network;datastorePrefix;constructor(e,t){const{validators:n,selectors:r,peerRouting:i,queryManager:s,network:o,logPrefix:a}=t;this.components=e,this.log=e.logger.forComponent(`${a}:content-fetching`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n,this.selectors=r,this.peerRouting=i,this.queryManager=s,this.network=o,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=Cw(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=uw.deserialize(r);return await Tw(this.validators,i,t),i}async*sendCorrectionRecord(e,t,n,r){this.log("sendCorrection for %b",e);const i=Iw(e,n);for(const{value:s,from:o}of t){if(Yn(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(o)){try{const t=Cw(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 a={type:tw.PUT_VALUE,key:e,record:i};for await(const e of this.network.sendRequest(o,a,r))"PEER_RESPONSE"===e.name&&null!=e.record&&Yn(e.record.value,uw.deserialize(i).value)&&(t=!0),yield e;if(!t)throw new cw("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=Iw(e,t),i=Cw(this.datastorePrefix,e);this.log(`storing record for key ${i.toString()}`),await this.components.datastore.put(i,r.subarray(),n),yield*gc(this.peerRouting.getClosestPeers(e,{...n,signal:n.signal}),t=>dw(t,t=>async()=>{if("FINAL_PEER"!==t.name)return[t];const i=[],s={type:tw.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&&Yn(e.record.value,uw.deserialize(r).value)||i.push(yw({from:t.peer.id,error:new cw("Value not put correctly"),path:e.path},n)));return i}),e=>qm(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 dt("No records given");const r=Dr(t).split("/");if(r.length<3)throw new dt("Record key does not have a selector function");const i=e[r[1].toString()];if(null==i)throw new pw(`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 bt("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 gw({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 o of n.peerRouting.getValueOrPeers(r.id,e,{...t,signal:i,path:s}))yield o,"PEER_RESPONSE"===o.name&&null!=o.record&&(yield gw({from:r.id,value:o.record.value,path:s},t))},t)}}function Nw(e,t){const n={id:e.id.toMultihash().bytes,multiaddrs:(e.multiaddrs??[]).map(e=>e.bytes),connection:t};return n}function Ow(e){if(null==e.id)throw new Error("Invalid peer in message");return{id:nu(Bn(e.id)),multiaddrs:(e.multiaddrs??[]).map(e=>Uu(e))}}class Bw{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){const{network:n,peerRouting:r,queryManager:i,routingTable:s,providers:o,logPrefix:a}=t;this.components=e,this.log=e.logger.forComponent(`${a}:content-routing`),this.network=n,this.peerRouting=r,this.queryManager=i,this.routingTable=s,this.providers=o,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:tw.ADD_PROVIDER,key:r,providers:[Nw({id:this.components.peerId,multiaddrs:t})]};let s=0;const o=this,a=Wd({objectMode:!0}),u=new ac({concurrency:10});u.addEventListener("idle",()=>{a.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))a.push(e),"FINAL_PEER"===e.name&&t.push(e);t.forEach(t=>{u.add(async()=>{for await(const r of async function*(t){try{o.log("sending provider record for %s to %p",e,t.peer.id);for await(const r of o.network.sendMessage(t.peer.id,i,{...n,path:t.path}))"PEER_RESPONSE"===r.name&&(o.log("sent provider record for %s to %p",e,t.peer.id),s++),yield r}catch(e){o.log.error("error sending provide record to peer %p - %e",t.peer.id,e),yield yw({from:t.peer.id,error:e,path:t.path},n)}}(t))a.push(r)}).catch(e=>{this.log.error("error publishing provider record to peer - %e",e)})})}).catch(e=>{a.end(e)}),yield*a,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 o=await this.providers.getProviders(e,t);if(o.length>0){const e=[];for(const r of o.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 fw({from:this.components.peerId,messageType:tw.GET_PROVIDERS,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),yield bw({from:this.components.peerId,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),r+=e.length,r>=n)return}const a=async function*({peer:e,signal:n,path:r}){const o={type:tw.GET_PROVIDERS,key:i};yield*s.network.sendRequest(e.id,o,{...t,signal:n,path:r})},u=new md(o);for await(const s of this.queryManager.run(i,a,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 bw({from:s.from,providers:i,path:s.path},t),r+=i.length,r>=n))return}}}class Uw extends Wt{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 mc({...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 dt("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 vw({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 hw({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 fw({from:e,messageType:s.type,closer:s.closer.map(Ow),providers:s.providers.map(Ow),record:null==s.record?void 0:uw.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 yw({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 dt("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 vw({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 hw({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 fw({from:e,messageType:r,path:n.path},n)}catch(t){this.metrics.errors?.increment({[r]:!0}),i?.abort(t),yield yw({from:e,error:t,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async _writeMessage(e,t,n){const r=Mc(e);await r.write(t,ow,n)}async _writeReadMessage(e,t,n){const r=Mc(e);await r.write(t,ow,n);const i=await r.read(ow,n);return i.closer.forEach(e=>{this.safeDispatchEvent("peer",{detail:Ow(e)})}),i.providers.forEach(e=>{this.safeDispatchEvent("peer",{detail:Ow(e)})}),i}}function jw(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 qw{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 kw(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:_b(this.originDhtKey,t),path:n};if(this.peerDistances.length===this.capacity){const e=this.peerDistances[this.peerDistances.length-1];if(null!=e&&-1!==jw(r.distance,e.distance))return}let i=!1;for(let e=0;e<this.peerDistances.length;e++){const t=jw(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===jw(_b(await kw(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 $w{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:tw.GET_VALUE,key:t};yield*this.network.sendRequest(e,r,n)}async*getPublicKeyFromNode(e,t={}){const n=Xn([xw,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=tu(Ka(i.record.value));if(!n.equals(e))throw new ct("public key does not match id");if(null==n.publicKey)throw new ct("public key missing");yield gw({from:e,value:i.record.value,path:r},t)}throw new cw(`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 mw({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 o={type:tw.FIND_NODE,key:e.toMultihash().bytes};for await(const a of r.network.sendRequest(n.id,o,{...t,signal:i,path:s}))if(yield a,"PEER_RESPONSE"===a.name){const n=a.closer.find(t=>t.id.equals(e));null!=n&&(yield mw({from:a.from,peer:n,path:a.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 bt("Not found")}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);const n=await Aw(e,t),r=new qw(n,this.routingTable.kBucketSize),i=this;yield*this.queryManager.run(e,async function*({peer:n,path:s,peerKadId:o,signal:a}){i.log("getClosestPeers asking %p",n.id);const u={type:tw.FIND_NODE,key:e};yield*i.network.sendRequest(n.id,u,{...t,signal:a,path:s}),r.addWithKadId(n,o,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 mw({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 yw({from:r.from,error:new cw(t),path:n.path},n);continue}yield r}}async _verifyRecordOnline(e,t){if(null==e.timeReceived)throw new lw("invalid record received");await Tw(this.validators,new uw(e.key,e.value,e.timeReceived),t)}async getClosestPeersOffline(e,t){const n=[];try{const r=nu(Bn(e)),i=await this.components.peerStore.get(r,t);n.push({id:i.id,multiaddrs:i.addresses.map(({multiaddr:e})=>e)})}catch{}const r=await Aw(e,t),i=this.routingTable.closestPeers(r,t);for(const e of i)try{n.push(await this.components.peerStore.getInfo(e,t))}catch(e){if("NotFoundError"!==e.name)throw e}return n.length>0?this.log("getClosestPeersOffline returning the %d closest peer(s) we know to %b",n.length,e):this.log("getClosestPeersOffline could not any peers close to %b with %d peers in the routing table",e,this.routingTable.size),n}}class zw{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=Mw(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=Mw(this.datastorePrefix,e,t),i=Lo(n?.time?.getTime()??Date.now());await this.datastore.put(r,i,n)}async loadProviders(e,t){const n=new fd,r=Mw(this.datastorePrefix,e);for await(const e of this.datastore.query({prefix:r.toString()},t)){const{peerId:t}=Dw(e.key);n.set(t,Fw(e.value))}return n}}async function*Vw(e){const{key:t,startingPeers:n,ourPeerId:r,query:i,alpha:s,path:o,numPaths:a,log:u,peersSeen:d,connectionManager:c,signal:l}=e,p=Wd({objectMode:!0}),h=new ac({concurrency:s,sort:(e,t)=>jw(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:o,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 ot)};l.addEventListener("abort",f);try{const y=await Aw(t,{signal:l});function m(n,s){if(null==n)return;d.add(n.id.toMultihash().bytes);const f=_b(s,y);h.add(async()=>{try{for await(const b of i({...e,key:t,peer:n,path:{index:o,queued:h.queued,running:h.running,total:h.size},numPaths:a,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 kw(e.id,{signal:l});-1===jw(_b(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:o,queued:h.queued,running:h.running,total:h.size}})}}catch(t){p.push(yw({from:n.id,error:t,path:{index:o,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 kw(e,{signal:l}))})),yield*p}finally{l.removeEventListener("abort",f)}}class Gw{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=hc([this.shutDownController.signal,r.signal,n.signal]),s=this.logger.forComponent(`${this.logPrefix}:query:`+Dr(e,"base58btc"));let o=!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 Yd(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 ic(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),s("query:start");const r=await Aw(e,{signal:i}),a=this.routingTable.closestPeers(r,{count:this.routingTable.kBucketSize}),u=a.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===a.length)return void s.error("running query with no peers");const d=kd(1024),c=u.map((r,o)=>Vw({...n,key:e,startingPeers:r,ourPeerId:this.peerId,signal:i,query:t,path:o,numPaths:u.length,alpha:this.alpha,log:s,peersSeen:d,onProgress:n.onProgress,connectionManager:this.connectionManager}));for await(const e of bc(...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}o=!0}catch(e){if(this.running)throw e}finally{o||(s("query exited early"),r.abort()),i.clear(),s("query finished")}}}function Kw(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 Ww{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=Lw(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=zd(),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=hc(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 gc(this.peerRouting.getClosestPeers(this.peerId.toMultihash().bytes,{signal:t,isSelfQuery:!0}),e=>Ch(e,this.count),async e=>Kw(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 Hw extends Wt{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 ac({concurrency:t.concurrency??10,metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_queue`}),this.reprovideTimeout=new mc({...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??Qv,this.interval=t.interval??Yv,this.contentRouting=t.contentRouting,this.running=!1,this.reprovide=Lw(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(Jv)}).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}=Dw(t.key),i=Fw(t.value).getTime()+this.validity,s=Date.now(),o=s>i,a=this.peerId.equals(r);this.log.trace("comparing: %d (now) < %d (expires) = %s %s",s,i,o,o?"(expired)":"(valid)"),o&&!a&&await this.datastore.delete(t.key,e),this.shouldReprovide(a,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(Jv)}).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 Eh(this.contentRouting.provide(e,this.addressManager.getAddresses(),t))}}class Qw{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 md,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}async start(){if(this.running)return;this.running=!0;const e=await kw(this.components.peerId);this.newPeers=new qw(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 md(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},[Zv]:{value:1}}})}),...[...n].map(async e=>{await this.components.peerStore.merge(e,{tags:{[this.closeTagName]:void 0,[Zv]:void 0}})})])}}function Yw(e){return Array.isArray(e?.peers)}class Jw{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??Xw,this.kBucketSize=t.kBucketSize??Zw,this.splitThreshold=t.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=t.numberOfOldContactsToPing??eT,this.lastPingThreshold=t.lastPingThreshold??nT,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=Qc({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 kw(e,t),lastPing:Date.now()}}async add(e,t){const n={peerId:e,kadId:await kw(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 qw(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*dw(n.peers,({peer:e})=>e.id)}count(){return function e(t){if(Yw(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){Yw(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+Dr(_b(e,t),"base16"))}_determineBucket(e){const t=Dr(e,"base2");return function e(n,r=0){return Yw(n)?n:e("0"===t[r]?n.left:n.right,r+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex(e=>Yn(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"===Dr(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 Zw=20,Xw=6,eT=3,tT="kad-peer",nT=6e5;class rT extends Wt{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??Zw,this.running=!1,this.protocol=t.protocol,this.network=t.network,this.peerTagName=t.peerTagName??tT,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 Uc({concurrency:t.pingOldContactConcurrency??20,metricName:`${t.metricsPrefix}_ping_old_contact_queue`,metrics:this.components.metrics,maxSize:t.pingOldContactMaxQueueSize??100}),this.pingOldContactTimeout=new mc({...t.pingOldContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_old_contact_time_milliseconds`}),this.pingNewContactQueue=new Uc({concurrency:t.pingNewContactConcurrency??20,metricName:`${t.metricsPrefix}_ping_new_contact_queue`,metrics:this.components.metrics,maxSize:t.pingNewContactMaxQueueSize??100}),this.pingNewContactTimeout=new mc({...t.pingNewContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_new_contact_time_milliseconds`}),this.kb=new Jw(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 Qw(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 zt(this.closestPeerTagger,this.kb))}async afterStart(){let e=0;Promise.resolve().then(async()=>{if(!this.populateFromDatastoreOnStart)return;const t=hc([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(tT)],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 Vt(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=hc([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 qm(n))null!=e&&(yield e)}async verifyNewContact(e,t){const n=this.pingNewContactTimeout.getTimeoutSignal(),r=hc([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 kw(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 kw(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(o){if(Yw(o))return o.depth>n&&(n=o.depth),t++,e+=o.peers.length,o.peers.length<r&&(r=o.peers.length),void(o.peers.length>i&&(i=o.peers.length));s(o.left),s(o.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 iT,sT=[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 oT{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e,t){const{peerRouting:n,routingTable:r,refreshInterval:i,refreshQueryTimeout:s,logPrefix:o}=t;this.log=e.logger.forComponent(`${o}: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=hc([r?.signal,AbortSignal.timeout(this.refreshQueryTimeout)]);try{const t=await Kw(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=wa(2);return nu(Bn(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=sT[(r^32768>>n)&i|t&~i],o=new ArrayBuffer(34),a=new DataView(o,0,o.byteLength);return a.setUint8(0,xr.code),a.setUint8(1,32),a.setUint32(2,s,!1),new Uint8Array(a.buffer,a.byteOffset,a.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=_b(this.routingTable.kb.localPeer.kadId,e);let n=0;for(const e of t){if(0!==e)break;n++}yield n}}}class aT{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 xt("Missing key");let n;try{n=zn.decode(t.key)}catch(e){throw new xt("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=nu(Bn(t.id)),i=t.multiaddrs.map(e=>Uu(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 uT{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 xt("Invalid FIND_NODE message received - key was missing");const n=await this.peerRouting.getClosestPeersOffline(t.key,{exclude:[e,this.peerId]});Yn(this.peerId.toMultihash().bytes,t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map(e=>e.decapsulateCode(mu))});const r={type:tw.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 dT{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 xt("Invalid GET_PROVIDERS message received - key was missing");let n;try{n=zn.decode(t.key)}catch(e){throw new xt("Invalid CID")}this.log("%p asking for providers for %s",e,n);const[r,i]=await Promise.all([Ol(dw(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:tw.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 cT{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 xt("Invalid key");const r={type:tw.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===Dr(e.subarray(0,4))}(n)){this.log("is public key");const e=function(e){return nu(Bn(e.subarray(4)))}(n);let t;try{const n=await this.peerStore.get(e);if(null==n.id.publicKey)throw new bt("No public key found in key book");t=Wa(n.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=t)return this.log("returning found public key"),r.record=new uw(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=Cw(this.datastorePrefix,e);let n;try{n=await this.datastore.get(t)}catch(e){if("NotFoundError"===e.name)return;throw e}const r=uw.deserialize(n);if(!(null==r.timeReceived||Date.now()-r.timeReceived.getTime()>Qv))return r;await this.datastore.delete(t)}}class lT{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 pT{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 xt(`Empty record from: ${e}`);try{const e=uw.deserialize(t.record);await Tw(this.validators,e),e.timeReceived=new Date;const r=Cw(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 hT{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={[tw.GET_VALUE.toString()]:new cT(e,t),[tw.PUT_VALUE.toString()]:new pT(e,t),[tw.FIND_NODE.toString()]:new uT(e,t),[tw.ADD_PROVIDER.toString()]:new aT(e,t),[tw.GET_PROVIDERS.toString()]:new dT(e,t),[tw.PING.toString()]:new lT(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 St)};let r=AbortSignal.timeout(this.incomingMessageTimeout);r.addEventListener("abort",n);const i=Mc(e).pb(ow);for(;;){if("readable"!==e.readStatus){await e.close({signal:r});break}const s=await i.read({signal:r}),o=this.metrics?.rpcTime?.timer(s.type.toString()),a=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,a?.(),e}finally{u||o?.()}r.removeEventListener("abort",n),r=AbortSignal.timeout(this.incomingMessageTimeout),r.addEventListener("abort",n)}}}class fT extends Wt{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 mT{dht;constructor(e){this.dht=e}async provide(e,t={}){await Eh(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 Eh(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 bt("Could not find value for key")}}class yT{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 bt("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 bT extends Wt{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??Zw,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??Ew,this.onPeerConnectTimeout=t.onPeerConnectTimeout??1e4,this.providers=new zw(e,{...t.providers,logPrefix:n,datastorePrefix:r}),this.validators={...Pw,...t.validators},this.selectors={...ww,...t.selectors},this.network=new Uw(e,{protocol:this.protocol,logPrefix:n,metricsPrefix:i}),this.routingTable=new rT(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 o=zd();!0===t.allowQueryWithZeroPeers&&o.resolve(),this.queryManager=new Gw(e,{disjointPaths:this.d,alpha:this.a,logPrefix:n,metricsPrefix:i,initialQuerySelfHasRun:o,routingTable:this.routingTable,allowQueryWithZeroPeers:t.allowQueryWithZeroPeers}),this.peerRouting=new $w(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:n}),this.contentFetching=new _w(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:n,datastorePrefix:r}),this.contentRouting=new Bw(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:n}),this.routingTableRefresh=new oT(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:n}),this.rpc=new hT(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 fT(e,{protocol:this.protocol,logPrefix:n}),this.querySelf=new Ww(e,{peerRouting:this.peerRouting,interval:t.querySelfInterval,initialInterval:t.initialQuerySelfInterval,logPrefix:n,initialQuerySelfHasRun:o,operationMetrics:s}),this.reprovider=new Hw(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 yT(this),this.dhtContentRouting=new mT(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})=>!$d(e)&&!mf.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=Rw(this.get.bind(this),s,"GET_VALUE"),this.findProviders=Rw(this.findProviders.bind(this),s,"FIND_PROVIDERS"),this.findPeer=Rw(this.findPeer.bind(this),s,"FIND_PEER"),this.getClosestPeers=Rw(this.getClosestPeers.bind(this),s,"GET_CLOSEST_PEERS"),this.provide=Rw(this.provide.bind(this),s,"PROVIDE"),this.put=Rw(this.put.bind(this),s,"PUT_VALUE")}[Symbol.toStringTag]="@libp2p/kad-dht";[Ht]=["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery","@libp2p/kad-dht"];[Qt]=["@libp2p/identify","@libp2p/ping"];get[st](){return this.dhtContentRouting}get[jt](){return this.dhtPeerRouting}get[Ot](){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 zt(this.routingTable,this.queryManager,this.network,this.topologyListener,this.routingTableRefresh,this.reprovider),await zt(this.querySelf))}async stop(){this.running=!1,await Vt(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 gT(e={}){return t=>new bT(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"}(iT||(iT={}));class vT{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";[Ht]=["@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 St("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 Yd(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=wa(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 rr,o=a=>{if(s.append(a.data),32===s.byteLength){r.removeEventListener("message",o);const a=Date.now()-e;Promise.all([r.closeRead(t)]).then(()=>{if(!Yn(n,s.subarray()))throw new Et(`Received wrong ping ack after ${a}ms`);i.resolve(a)}).catch(e=>{r.abort(e),i.reject(e)})}};return r.addEventListener("message",o),r.send(n),await r.close(t),await ic(i.promise,t.signal)}catch(t){throw i.error("error while pinging %o - %e",e,t),r?.abort(t),t}finally{r?.close()}}}function wT(e={}){return t=>new vT(t,e)}function TT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function PT(e,t,n){if(!e.s){if(n instanceof xT){if(!n.s)return void(n.o=PT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(PT.bind(null,e,t),PT.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var xT=/*#__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{PT(r,1,s(this.v))}catch(e){PT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?PT(r,1,t?t(i):i):n?PT(r,1,n(i)):PT(r,2,i)}catch(e){PT(r,2,e)}},r},e}();function ET(e){return e instanceof xT&&1&e.s}function ST(e,t,n){for(var r;;){var i=e();if(ET(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!ET(s)){r=1;break}s=s.s}if(t){var o=t();if(o&&o.then&&!ET(o)){r=2;break}}}var a=new xT,u=PT.bind(null,a,2);return(0===r?i.then(c):1===r?s.then(d):o.then(l)).then(void 0,u),a;function d(r){s=r;do{if(t&&(o=t())&&o.then&&!ET(o))return void o.then(l).then(void 0,u);if(!(i=e())||ET(i)&&!i.v)return void PT(a,1,s);if(i.then)return void i.then(c).then(void 0,u);ET(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):PT(a,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):PT(a,1,s)}}function AT(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var kT="/ocean/nodes/1.0.0",CT=1e4,IT=["/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"],DT=/*#__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 o(o){var a;if(s)return o;function u(t){if(a)return t;throw new Error("No multiaddrs found for peer id "+e)}var d,c=i.services.dht,l=!1,p=!1,h=AT(function(){return TT(function(){return t=C(c.findPeer(eu(e),{signal:AbortSignal.timeout(2e4)})),ST(function(){function e(e){return!a&&(l=!(n=e).done)}return a?!!e(!a&&t.next()):Promise.resolve(!a&&t.next()).then(e)},function(){return!!(l=!1)},function(){var e=n.value;if(e.type===iT.FINAL_PEER&&e.peer.multiaddrs.length>0){var t=e.peer.multiaddrs[0].toString(),i=r(t);return a=1,i}})},function(e){p=!0,d=e})},function(e,n){function r(t){if(a)return t;if(e)throw n;return n}var i=AT(function(){var e=function(){if(l&&null!=t.return)return Promise.resolve(t.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,t){if(p)throw d;if(e)throw t;return t});return i&&i.then?i.then(r):r(i)});return h&&h.then?h.then(u):u(h)}var a=i.getConnections().find(function(t){return t.remotePeer.toString()===e});if(null!=a&&a.remoteAddr){var u=a.remoteAddr.toString();return r(u)}var d=TT(function(){return Promise.resolve(i.peerStore.get(eu(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(o):o(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:IT).map(Uu);return Promise.resolve(async function(e={}){e.privateKey??=await async function(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=lo.utils.randomSecretKey(),t=lo.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 vo(e,t)}()}();const t=new ny({...await Gu(e),peerId:(n=e.privateKey,tu(n.publicKey))});var n;return!1!==e.start&&await t.start(),t}(F({addresses:{listen:[]},transports:[kg(),Bv()].concat(t.p2pConfig.enableTcp?[Ig()]:[]),connectionEncrypters:[eg()],streamMuxers:[bg()],peerDiscovery:[].concat(n.length>0?[(r={list:n.map(String),timeout:1e4},e=>new Uv(e,r))]:[]),services:{identify:Kv(),identifyPush:Wv(),ping:wT(),dht:gT({peerInfoMapper:Sw,allowQueryWithZeroPeers:!1,kBucketSize:20,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){q.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=M(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.cidFromRawString=function(e){try{return Promise.resolve(xr.digest(Ir(e))).then(function(e){return zn.create(1,85,e)})}catch(e){return Promise.reject(e)}},t.getProvidersForString=function(e,t){try{var n,r,i=this;return Promise.resolve(i.getOrCreateLibp2pNode()).then(function(s){return Promise.resolve(i.cidFromRawString(e)).then(function(e){function i(e){return o.map(function(e){return{id:e.id.toString(),multiaddrs:e.multiaddrs}})}var o=[],a=TT(function(){var i,a=!1,u=!1;return AT(function(){return TT(function(){n=C(s.contentRouting.findProviders(e,{useCache:!1,useNetwork:!0,signal:t}));var i=ST(function(){return Promise.resolve(n.next()).then(function(e){return a=!(r=e).done})},function(){return!!(a=!1)},function(){o.push(r.value)});if(i&&i.then)return i.then(function(){})},function(e){u=!0,i=e})},function(e,t){function r(n){if(e)throw t;return t}var s=AT(function(){var e=function(){if(a&&null!=n.return)return Promise.resolve(n.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,t){if(u)throw i;if(e)throw t;return t});return s&&s.then?s.then(r):r()})},function(){});return a&&a.then?a.then(i):i()})})}catch(e){return Promise.reject(e)}},t.isDialable=function(e){return"undefined"==typeof window||e.toString().includes("/tls/sni")},t.isNotP2PCircuit=function(e){return!/\/p2p-circuit(\/|$)/.test(e.toString())},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,n){void 0===n&&(n=!1);try{var r=this;return Promise.resolve(r.getOrCreateLibp2pNode()).then(function(i){function s(){function e(){var e=u.filter(function(e){return r.isDialable(e)}),s=e.length;n||(e=e.filter(function(e){return r.isNotP2PCircuit(e)}));var o=e.length;if(e.length<1){if(!n&&o<s)return r.getConnection({nodeId:a?a.toString():"",multiaddress:u},t,!0);throw new Error("No valid multiaddresses, cannot connect")}return a&&(e=e.map(function(e){var t=e.toString();return t.includes("/p2p/")?e:Uu(t+"/p2p/"+a.toString())})),TT(function(){return Promise.resolve(i.dial(e,{signal:t})).then(function(e){return q.debug("[P2P] Dial SUCCESS via "+e.remoteAddr+" (limited="+(null!=e.limits)+")"),e})},function(e){var d;if(!n&&o<s)return q.debug("[P2P] Direct dial failed, falling back to relayed addresses..."),r.getConnection({nodeId:a?a.toString():"",multiaddress:u},t,!0);throw new Error("Cannot dial peer "+(null==(d=a)?void 0:d.toString())+". "+(u.length>0?"Found addrs: "+u.map(String).join(", ")+". ":"No addresses found. ")+"Active connections: "+i.getConnections().length+". "+e.message)})}var s=function(){if(!o()&&a){var e=TT(function(){return Promise.resolve(i.peerRouting.findPeer(a,{signal:t})).then(function(e){for(var t,n=M(e.multiaddrs);!(t=n()).done;)u.push(t.value);q.debug("[P2P] "+a.toString()+": DHT returned "+e.multiaddrs.length+" addrs")})},function(e){q.debug("[P2P] "+a.toString()+": DHT findPeer failed: "+e.message)});if(e&&e.then)return e.then(function(){})}}();return s&&s.then?s.then(e):e()}var o=function(){return u.some(function(e){return r.isDialable(e)})},a=null,u=[];if(e&&"string"==typeof e){try{var d=Uu(e);if(u.push(d),!a){var c=r.peerIdFromMultiaddr(d);c&&(a=eu(c))}}catch(e){}try{a||(a=eu(e))}catch(e){}}if("object"==typeof e&&null!==e&&!Array.isArray(e))if("nodeId"in e||"multiaddress"in e){var l=e;if(Array.isArray(l.multiaddress)&&l.multiaddress.length>0)for(var p,h=M(l.multiaddress);!(p=h()).done;)u.push(p.value);if(l.nodeId)try{a=eu(l.nodeId)}catch(e){}}else a=e;if(a){var f=i.getConnections(a).filter(function(e){return"open"===e.status});if(f.length>0)return q.debug("[P2P] "+a.toString()+": reusing existing connection via "+f[0].remoteAddr),f[0]}var m=function(){if(!o()&&a){var e=TT(function(){return Promise.resolve(i.peerStore.get(a)).then(function(e){if(null!=e&&e.addresses){for(var t,n=M(e.addresses);!(t=n()).done;)u.push(t.value.multiaddr);q.debug("[P2P] "+a.toString()+": "+e.addresses.length+" peerStore addrs")}})},function(){q.debug("[P2P] "+a.toString()+": not in peerStore")});if(e&&e.then)return e.then(function(){})}}();return m&&m.then?m.then(s):s()})}catch(e){return Promise.reject(e)}},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 RT(e)},t.getSignedCommandParams=function(e,t,n,r){try{var i,s=function(s){return i?s:Promise.resolve(FT(t)).then(function(i){return Promise.resolve(o.getNonce(e,i,r)).then(function(e){var r=(e+1).toString();return Promise.resolve(MT(t,r,n)).then(function(e){return{consumerAddress:i,nonce:r,signature:e}})})})},o=this;if(LT(t))return Promise.resolve({consumerAddress:t.consumerAddress,nonce:t.nonce,signature:t.signature});var a=function(){if("string"==typeof t)return Promise.resolve(FT(t)).then(function(e){return i=1,{consumerAddress:e,nonce:void 0,signature:void 0}})}();return Promise.resolve(a&&a.then?a.then(s):s(a))}catch(e){return Promise.reject(e)}},t.dialAndStream=function(e,t,n,r){try{var i,s=this,o=null!=n?n:AbortSignal.timeout(null!=(i=s.p2pConfig.dialTimeout)?i:CT);return Promise.resolve(s.getConnection(e,o)).then(function(e){return TT(function(){return Promise.resolve(e.newStream(kT,{signal:o,runOnLimitedConnection:!0})).then(function(n){var i=Dc(n),a=t;return r&&(a=F({},t,{p2pStreamBody:!0})),Promise.resolve(i.write((new TextEncoder).encode(JSON.stringify(a)),{signal:o})).then(function(){function t(){return Promise.resolve(n.close()).then(function(){return Promise.resolve(i.read({signal:o})).then(function(t){var n=s.toUint8Array(t);return{lp:i,firstBytes:n,connection:e}})})}var a=function(){if(r)return Promise.resolve(function(e,t,n){try{var r,i,s,o=function(t){return Promise.resolve(e.write(new Uint8Array(0),{signal:n})).then(function(){})},a=!1,u=!1,d=AT(function(){return TT(function(){r=C(t);var s=ST(function(){return Promise.resolve(r.next()).then(function(e){return a=!(i=e).done})},function(){return!!(a=!1)},function(){return Promise.resolve(e.write(function(e){if(e instanceof Uint8Array)return e;if("string"==typeof e)return(new TextEncoder).encode(e);if(e&&"object"==typeof e&&ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type for P2P request body")}(i.value),{signal:n})).then(function(){})});if(s&&s.then)return s.then(function(){})},function(e){u=!0,s=e})},function(e,t){function n(n){if(e)throw t;return t}var i=AT(function(){var e=function(){if(a&&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(o):o())}catch(e){return Promise.reject(e)}}(i,r,o)).then(function(){})}();return a&&a.then?a.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,o){void 0===s&&(s=0);try{var a=this;return Promise.resolve(TT(function(){var u=F({command:t,authorization:r?a.getAuthorization(r):void 0},n);return Promise.resolve(a.dialAndStream(e,u,i,o)).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=a.p2pConfig.maxRetries)?u:5))return Promise.resolve(new Promise(function(e){var t;return setTimeout(e,null!=(t=a.p2pConfig.retryDelay)?t:1e3)})).then(function(){var u=a.sendP2pCommand(e,t,n,r,i,s+1,o);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 N(/*#__PURE__*/L().mark(function e(){var t;return L().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,D(d.read({signal:AbortSignal.timeout(CT)}));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 ec){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))();var m=[c],y=TT(function(){var e=ST(function(){return!0},void 0,function(){var e;return Promise.resolve(d.read({signal:AbortSignal.timeout(null!=(e=a.p2pConfig.dialTimeout)?e:CT)})).then(function(e){m.push(a.toUint8Array(e))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof ec))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=a.p2pConfig.maxRetries)?u:5))return q.debug("[P2P] Stream reset/closed on attempt "+(s+1)+", retrying..."),Promise.resolve(et(1e3)).then(function(){var u=a.sendP2pCommand(e,t,n,r,i,s+1,o);return c=1,u})}();return h&&h.then?h.then(l):l(h)}))}catch(e){return Promise.reject(e)}},t.getEndpoints=function(e){try{var t=this;return Promise.resolve(TT(function(){return Promise.resolve(t.sendP2pCommand(e,E.STATUS,{}))},function(e){throw q.error("P2P getEndpoints (STATUS) failed:",e),e}))}catch(e){return Promise.reject(e)}},t.getNodeStatus=function(e,t){try{return Promise.resolve(this.getEndpoints(e))}catch(e){return Promise.reject(e)}},t.getNodeJobs=function(e,t,n){try{var r=this;return Promise.resolve(TT(function(){var i={};return t&&(i.fromTimestamp=t.toString()),Promise.resolve(r.sendP2pCommand(e,E.JOBS,i,null,n)).then(function(e){return Array.isArray(e)?e:[]})},function(e){return q.error("P2P getNodeJobs failed:",e),[]}))}catch(e){return Promise.reject(e)}},t.getNonce=function(e,t,n){try{var r=this;return Promise.resolve(TT(function(){return Promise.resolve(r.sendP2pCommand(e,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 q.error("P2P getNonce failed:",e),e}))}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.getSignedCommandParams(n,r,E.ENCRYPT,s)).then(function(i){return Promise.resolve(o.sendP2pCommand(n,E.ENCRYPT,{chainId:t,nonce:i.nonce,consumerAddress:i.consumerAddress,signature:i.signature,blob:"string"==typeof e?e:JSON.stringify(e)},r,s)).then(function(e){return o.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,o,a,u){try{var d={ddoId:e,serviceId:t,consumerAddress:r};return o&&(d.userdata=o),a&&(d.environment=a),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,o,a,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=$u(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:a},maxJobDuration:i,consumerAddress:o};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=$u(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,o,a){try{var u=this;return Promise.resolve(u.getSignedCommandParams(i,s,E.DOWNLOAD)).then(function(d){var c=d.consumerAddress,l=d.nonce,p=d.signature,h={command:E.DOWNLOAD,authorization:u.getAuthorization(s),fileIndex:n,documentId:e,transferTxId:r,serviceId:t,consumerAddress:c,nonce:l,signature:p};return o&&(h.policyServer=o),a&&(h.userData=a),Promise.resolve(u.dialAndStream(i,h)).then(function(e){var t=e.lp,r=e.firstBytes;function i(e){var t=qu(d);return{data:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),filename:"file"+n}}var s,o=(new TextDecoder).decode(r),a=null;try{a=JSON.parse(o)}catch(e){}if(a&&"number"==typeof a.httpStatus&&a.httpStatus>=400)throw new Error(null!=(s=a.error)?s:"P2P download error: "+a.httpStatus);var d=null===a?[new Uint8Array(r)]:[],c=TT(function(){var e=ST(function(){return!0},void 0,function(){var e;return Promise.resolve(t.read({signal:AbortSignal.timeout(null!=(e=u.p2pConfig.dialTimeout)?e:CT)})).then(function(e){d.push(new Uint8Array(u.toUint8Array(e)))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof ec))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,o,a,u,d,c,l,p,h,f,m){try{var y=this;return Promise.resolve(y.getSignedCommandParams(e,t,E.COMPUTE_START,h)).then(function(b){function g(){function n(){return Promise.resolve(y.sendP2pCommand(e,E.COMPUTE_START,v,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&&(v.output=$u(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var v={environment:n,dataset:r[0],datasets:r,algorithm:i,maxJobDuration:s,feeToken:o,resources:a,chainId:u,payment:{chainId:u,token:o,maxJobDuration:s,resources:a},consumerAddress:b.consumerAddress,nonce:b.nonce,signature:b.signature};d&&(v.metadata=d),c&&(v.additionalViewers=c),p&&(v.policyServer=p),f&&(v.queueMaxWaitTime=f);var w=function(){if(m)return Promise.resolve(y.getNodePublicKey(e)).then(function(e){e&&(v.encryptedDockerRegistryAuth=$u(e,JSON.stringify(m)))})}();return w&&w.then?w.then(g):g()})}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,o,a,u,d,c,l,p){try{var h=this;return Promise.resolve(h.getSignedCommandParams(e,t,E.FREE_COMPUTE_START,c)).then(function(f){function m(){function n(){return Promise.resolve(h.sendP2pCommand(e,E.FREE_COMPUTE_START,y,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&&(y.output=$u(e,JSON.stringify(u)))})}();return r&&r.then?r.then(n):n()}var y={environment:n,dataset:r[0],datasets:r,algorithm:i,resources:s,consumerAddress:f.consumerAddress,nonce:f.nonce,signature:f.signature};o&&(y.metadata=o),a&&(y.additionalViewers=a),d&&(y.policyServer=d),l&&(y.queueMaxWaitTime=l);var b=function(){if(p)return Promise.resolve(h.getNodePublicKey(e)).then(function(e){e&&(y.encryptedDockerRegistryAuth=$u(e,JSON.stringify(p)))})}();return b&&b.then?b.then(m):m()})}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.getSignedCommandParams(e,t,E.COMPUTE_GET_STREAMABLE_LOGS,r)).then(function(s){return i.sendP2pCommand(e,E.COMPUTE_GET_STREAMABLE_LOGS,{jobId:n,consumerAddress:s.consumerAddress,nonce:s.nonce,signature:s.signature},t,r)})}catch(e){return Promise.reject(e)}},t.computeStop=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getSignedCommandParams(t,n,E.COMPUTE_STOP,i)).then(function(o){var a={jobId:e,consumerAddress:o.consumerAddress,nonce:o.nonce,signature:o.signature};return r&&(a.agreementId=r),s.sendP2pCommand(t,E.COMPUTE_STOP,a,n,i)})}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{var s=this;return Promise.resolve(FT(t)).then(function(o){var a={consumerAddress:o};return n&&(a.jobId=n),r&&(a.agreementId=r),s.sendP2pCommand(e,E.COMPUTE_GET_STATUS,a,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.getSignedCommandParams(e,t,E.COMPUTE_GET_RESULT)).then(function(o){var a=o.nonce,u=o.signature,d={command:E.COMPUTE_GET_RESULT,jobId:n,index:r,offset:i,consumerAddress:o.consumerAddress};return"string"==typeof t?d.authorization=t:(d.nonce=a,d.signature=u),Promise.resolve(s.dialAndStream(e,d)).then(function(e){var t,n,r=e.lp,i=e.firstBytes,o=JSON.parse((new TextDecoder).decode(i));if("number"==typeof(null==o?void 0:o.httpStatus)&&o.httpStatus>=400)throw new Error(null!=(n=o.error)?n:"P2P compute result error: "+o.httpStatus);var a=null!=(t=s.p2pConfig.dialTimeout)?t:CT;return N(/*#__PURE__*/L().mark(function e(){var t;return L().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,D(r.read({signal:AbortSignal.timeout(a)}));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 ec){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))()})})}catch(e){return Promise.reject(e)}},t.getComputeResultUrl=function(e,t,n,r){try{var i=this;return Promise.resolve(FT(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 o=(s+1).toString();return Promise.resolve(MT(e,o,E.CREATE_AUTH_TOKEN)).then(function(e){return Promise.resolve(r.sendP2pCommand(t,E.CREATE_AUTH_TOKEN,{address:i,signature:e,nonce:o},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,s){try{return Promise.resolve(this.sendP2pCommand(r,E.CREATE_AUTH_TOKEN,{address:e,signature:t,nonce:n,validUntil:i},null,s)).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(i.getSignedCommandParams(e,n,E.VALIDATE_DDO,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.VALIDATE_DDO,{ddo:t,publisherAddress:s.consumerAddress,nonce:s.nonce,signature:s.signature},n,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(o){var a=(o+1).toString();return Promise.resolve(nt(e,s+a)).then(function(e){return i.sendP2pCommand(n,E.INVALIDATE_AUTH_TOKEN,{address:s,signature:e,token:t,nonce:a},null,r)})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){var n=this;return Promise.resolve(TT(function(){return Promise.resolve(n.sendP2pCommand(e,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,F({},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,F({},t),null,n))}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,o,a,u){try{var d=this;return Promise.resolve(d.getSignedCommandParams(e,t,E.GET_LOGS,u)).then(function(c){var l={startTime:n,endTime:r,signature:c.signature,nonce:c.nonce,address:c.consumerAddress};return i&&(l.maxLogs=i),s&&(l.moduleName=s),o&&(l.level=o),a&&(l.page=a),d.sendP2pCommand(e,E.GET_LOGS,l,t,u)})}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.createPersistentStorageBucket=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(s){var o;return i.sendP2pCommand(e,E.PERSISTENT_STORAGE_CREATE_BUCKET,F({},s,{accessLists:null!=(o=n.accessLists)?o:[],label:n.label}),t,r)})}catch(e){return Promise.reject(e)}},t.updatePersistentStorageBucket=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_UPDATE_BUCKET,i)).then(function(o){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_UPDATE_BUCKET,F({},o,{bucketId:n,label:r}),t,i)})}catch(e){return Promise.reject(e)}},t.getPersistentStorageBuckets=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_GET_BUCKETS,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.PERSISTENT_STORAGE_GET_BUCKETS,F({},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.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.PERSISTENT_STORAGE_LIST_FILES,F({},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.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(o){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,F({},o,{bucketId:n,fileName:r}),t,i)})}catch(e){return Promise.reject(e)}},t.uploadPersistentStorageFile=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(a){return o.sendP2pCommand(e,E.PERSISTENT_STORAGE_UPLOAD_FILE,F({},a,{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.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_DELETE_FILE,i)).then(function(o){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_DELETE_FILE,F({},o,{bucketId:n,fileName:r}),t,i)})}catch(e){return Promise.reject(e)}},e}(),MT=function(e,t,n){try{if("string"==typeof e)return Promise.resolve(null);if(LT(e))return Promise.resolve(e.signature);var r=String,i=String;return Promise.resolve(e.getAddress()).then(function(s){var o=r(i(s)+String(t)+String(n));return nt(e,o)})}catch(e){return Promise.reject(e)}},FT=function(e){try{return LT(e)?Promise.resolve(e.consumerAddress):Promise.resolve("string"==typeof e?function(e){try{return g.decode(e,{json:!0})}catch(e){throw new Error("Error decoding JWT")}}(e).address:e.getAddress())}catch(e){return Promise.reject(e)}};function RT(e){return"string"==typeof e?e:void 0}function LT(e){return!!e&&"object"==typeof e&&"string"==typeof e.consumerAddress&&"string"==typeof e.nonce&&"string"==typeof e.signature}function _T(e){try{return Uu(e),!0}catch(e){}try{return eu(e),!0}catch(e){return!1}}function NT(e){if(!e)return!1;if("string"==typeof e)return _T(e);if("object"==typeof e&&("nodeId"in e||"multiaddress"in e)){var t=e;if(Array.isArray(t.multiaddress)&&t.multiaddress.length>0)return!0;if(t.nodeId)return _T(t.nodeId)}if("object"==typeof e&&"function"==typeof e.toString){var n=String(e.toString());try{return eu(n),!0}catch(e){return!1}}return!1}var OT=/*#__PURE__*/function(){function e(){this.httpProvider=new Vu,this.p2pProvider=new DT}var t=e.prototype;return t.getImpl=function(e){return NT(e)?this.p2pProvider:this.httpProvider},t.getP2PProvider=function(){return this.p2pProvider},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,o,a,u){try{return Promise.resolve(this.getImpl(i).initialize(e,t,n,r,i,s,o,a,u))}catch(e){return Promise.reject(e)}},t.initializeCompute=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h){try{return Promise.resolve(this.getImpl(s).initializeCompute(e,t,n,r,i,s,o,a,u,d,c,l,p,h))}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,o,a){try{return Promise.resolve(this.getImpl(i).getDownloadUrl(e,t,n,r,i,s,o,a))}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h,f,m){try{return Promise.resolve(this.getImpl(e).computeStart(e,t,n,r,i,s,o,a,u,d,c,l,p,h,f,m))}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,o,a,u,d,c,l,p){try{return Promise.resolve(this.getImpl(e).freeComputeStart(e,t,n,r,i,s,o,a,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,s){try{return Promise.resolve(this.p2pProvider.generateSignedAuthToken(e,t,n,r,i,s))}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,o,a,u){try{return Promise.resolve(this.getImpl(e).downloadNodeLogs(e,t,n,r,i,s,o,a,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.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.updatePersistentStorageBucket=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).updatePersistentStorageBucket(e,t,n,r,i))}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 OT;function UT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function jT(e,t,n){if(!e.s){if(n instanceof qT){if(!n.s)return void(n.o=jT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(jT.bind(null,e,t),jT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var qT=/*#__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{jT(r,1,s(this.v))}catch(e){jT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?jT(r,1,t?t(i):i):n?jT(r,1,n(i)):jT(r,2,i)}catch(e){jT(r,2,e)}},r},e}();function $T(e){return e instanceof qT&&1&e.s}var zT=/*#__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 o=s.aquariusURL+"/api/aquarius/assets/ddo/"+e;return UT(function(){return Promise.resolve(y(o,{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 q.error(e),new Error("HTTP request failed")})},s=this,o=function(){if(NT(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(o&&o.then?o.then(i):i(o))}catch(e){return Promise.reject(e)}},t.waitForIndexer=function(e,t,n,r,i,s){void 0===r&&(r=3e4),void 0===i&&(i=100);try{var o,a=this,u=0;i>500&&(q.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);var d=NT(a.aquariusURL),c=function(e,t){var n;do{var r=e();if(r&&r.then){if(!$T(r)){n=!0;break}r=r.v}var i=t();if($T(i)&&(i=i.v),!i)return r}while(!i.then);var s=new qT,o=jT.bind(null,s,2);return(n?r.then(a):i.then(u)).then(void 0,o),s;function a(n){for(r=n;$T(i=t())&&(i=i.v),i;){if(i.then)return void i.then(u).then(void 0,o);if((r=e())&&r.then){if(!$T(r))return void r.then(a).then(void 0,o);r=r.v}}jT(s,1,r)}function u(n){if(n){do{if((r=e())&&r.then){if(!$T(r))return void r.then(a).then(void 0,o);r=r.v}if($T(n=t())&&(n=n.v),!n)return void jT(s,1,r)}while(!n.then);n.then(u).then(void 0,o)}else jT(s,1,r)}}(function(){function i(e){return o?e:Promise.resolve(et(r)).then(function(){u++})}var c=UT(function(){function r(){if(i){var e=b.getDDOClass(i).getAssetFields().indexedMetadata;if(!t)return o=1,i;if(e.event&&e.event.txid===t)return o=1,i}}var i,u=d?Promise.resolve(BT.resolveDdo(a.aquariusURL,e,n)).then(function(e){i=e}):Promise.resolve(y(a.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 u&&u.then?u.then(r):r()},function(){});return c&&c.then?c.then(i):i(c)},function(){return!o&&u<i});return Promise.resolve(c&&c.then?c.then(function(e){return o?e:null}):o?c:null)}catch(e){return Promise.reject(e)}},t.validate=function(e,t,n,r,i){try{if(NT(n))return Promise.resolve(BT.validateDdo(n,e,t,r));var s=n+"/api/aquarius/assets/ddo/validate",o=n+"/api/services/nonce";return Promise.resolve(UT(function(){return Promise.resolve(t.getAddress()).then(function(n){return Promise.resolve(y(o+"?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 o=i.nonce;o&&null!==o||(o="0");var a=(Number(o)+1).toString(),u=String,d=String;return Promise.resolve(t.getAddress()).then(function(i){var o=u(d(i)+String(a)+String(E.VALIDATE_DDO));return Promise.resolve(nt(t,o)).then(function(i){return Promise.resolve(y(s,{method:"POST",body:JSON.stringify({ddo:e,publisherAddress:n,nonce:a,signature:i}),headers:{"Content-Type":"application/json",Authorization:RT(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){q.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(UT(function(){return Promise.resolve(y(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 q.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(UT(function(){return Promise.resolve(y(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 q.error("Error querying metadata: ",e),new Error("Error querying metadata: "+e)}))}catch(e){return Promise.reject(e)}},e}();function VT(e,t){return e=d(e),"did:op:"+T(e+t.toString(10)).toString()}function GT(e){return T(e).toString()}var KT=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)}};function WT(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()}var HT=function(e,n){try{var r=new t.Contract(n,X,e);return Promise.resolve(r.decimals()).then(Number)}catch(e){return Promise.reject(e)}},QT=function(e,n,r,i){try{var s=new t.Contract(n,X,e);return Promise.resolve(s.allowance(r,i))}catch(e){return Promise.reject(e)}},YT=function(e,n,r,i){try{var s=new t.Contract(n,X,e);return Promise.resolve(s.balanceOf(r)).then(function(t){return Promise.resolve(ae(e,n,t,i))})}catch(e){return Promise.reject(e)}},JT=function(e,n,r,i,s){try{var o=new t.Contract(n,X,e);return Promise.resolve(o.allowance(r,i)).then(function(t){return Promise.resolve(ae(e,n,t,s))})}catch(e){return Promise.reject(e)}},ZT=function(e,n,r,i,s,o,a){try{var u=new t.Contract(r,X,e);return Promise.resolve(oe(e,r,s,o)).then(function(t){return Promise.resolve(u.transfer.estimateGas(i,t)).then(function(r){return a?r:Promise.resolve(se(r,e,null==n?void 0:n.gasFeeMultiplier,u.transfer,i,t))})})}catch(e){return Promise.reject(e)}},XT=function(e,n,r,i,s,o,a,u){void 0===a&&(a=!1);try{var d,c=function(t){if(d)return t;var r=null;return Promise.resolve(l.approve.estimateGas(s,o)).then(function(t){if(u)return t;var i=function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(function(){return Promise.resolve(se(t,e,null==n?void 0:n.gasFeeMultiplier,l.approve,s,o)).then(function(e){r=e})},function(e){q.error("ERROR: Failed to approve spender to spend tokens : "+e.message)});return i&&i.then?i.then(function(){return r}):r})},l=new t.Contract(i,X,e),p=function(){if(!a)return Promise.resolve(QT(e,i,r,s)).then(function(e){if(new f(e).isGreaterThan(new f(o))){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)}},eP=function(e,n,r,i,s,o,a,u,d){void 0===a&&(a=!1);try{var c,l=function(t){return c?t:Promise.resolve(oe(e,i,o,u)).then(function(t){return Promise.resolve(p.approve.estimateGas(s,t)).then(function(r){return d?new m(r.toString()):Promise.resolve(se(r,e,null==n?void 0:n.gasFeeMultiplier,p.approve,s,t))})})},p=new t.Contract(i,X,e),h=function(){if(!a)return Promise.resolve(JT(e,i,r,s)).then(function(e){if(new m(e).greaterThanOrEqualTo(new m(o))){var t=new m(e).toNumber();return c=1,t}})}();return Promise.resolve(h&&h.then?h.then(l):l(h))}catch(e){return Promise.reject(e)}},tP={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 nP(e){try{var t=JSON.parse(e),n=Object.keys(t)[0];if("error"===n){var r,i=t[n];return(null==(r=tP[n])?void 0:r[i])||"Provider request failed: "+i}var s=t[n];return t[Object.keys(t)[1]]+" : "+s}catch(t){return q.error("[getErrorMessage] error: ",t),e}}function rP(e,t,n){if(!e.s){if(n instanceof iP){if(!n.s)return void(n.o=rP.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(rP.bind(null,e,t),rP.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var iP=/*#__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{rP(r,1,s(this.v))}catch(e){rP(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?rP(r,1,t?t(i):i):n?rP(r,1,n(i)):rP(r,2,i)}catch(e){rP(r,2,e)}},r},e}(),sP=function(e,t,n,r,i,s,o,a,u,d,c,l){void 0===u&&(u="0"),void 0===d&&(d=0),void 0===c&&(c=0),void 0===l&&(l=0);try{var p=b.getDDOClass(e),h=p.getAssetFields().datatokens,f=p.getDDOFields(),y=f.chainId,g=f.services;return o||(o={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"}),Promise.resolve(t.provider.getNetwork()).then(function(p){if(y!==Number(p.chainId))throw new Error("Chain ID from DDO is different than the configured network.");if(!h[d].address)throw new Error("The datatoken with index: "+d+" does not exist for the asset with did: "+e.id);if(!g[c].id)throw new Error("There is no service with index: "+c+" defined for the asset with did: "+e.id);return Promise.resolve(r.getId(h[d].address)).then(function(p){return Promise.resolve(r.getFixedRates(h[d].address)).then(function(f){return Promise.resolve(r.getDispensers(h[d].address)).then(function(y){return Promise.resolve(r.getPublishingMarketFee(h[d].address)).then(function(b){function v(e){return a?e:Promise.resolve(P.call(BT,E,x,0,e,i||n.oceanNodeUri)).then(w)}function w(i){function y(i){function a(i){var s,a={consumer:i,serviceIndex:c,_providerFee:v,_consumeMarketFee:o};return function(e,t){var n,r=-1;e:{for(var i=0;i<t.length;i++){var s=t[i][0];if(s){var o=s();if(o&&o.then)break e;if(o===e){r=i;break}}else r=i}if(-1!==r){do{for(var a=t[r][1];!a;)r++,a=t[r][1];var u=a();if(u&&u.then){n=!0;break e}var d=t[r][2];r++}while(d&&!d());return u}}var c=new iP,l=rP.bind(null,c,2);return(n?u.then(p):o.then(function n(o){for(;;){if(o===e){r=i;break}if(++i===t.length){if(-1!==r)break;return void rP(c,1,u)}if(s=t[i][0]){if((o=s())&&o.then)return void o.then(n).then(void 0,l)}else r=i}do{for(var a=t[r][1];!a;)r++,a=t[r][1];var u=a();if(u&&u.then)return void u.then(p).then(void 0,l);var d=t[r][2];r++}while(d&&!d());rP(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)}rP(c,1,e)}}(T,[[function(){return"free"},function(){var e=function(e){var t;if(s)return e;function i(e){if(t)return e}var o=function(){if(2===p||4===p)return Promise.resolve(r.buyFromDispenserAndOrder(g[c].datatokenAddress,a,n.dispenserAddress)).then(function(e){return t=1,e})}();return o&&o.then?o.then(i):i(o)},i=function(){if(1===p){var e=new Pe(n.dispenserAddress,t),i=e.dispense,o=h[d].address;return Promise.resolve(t.getAddress()).then(function(t){return Promise.resolve(i.call(e,o,"1",t)).then(function(e){if(!e)throw new Error("Failed to dispense !");return Promise.resolve(e.wait()).then(function(){return Promise.resolve(r.startOrder(h[d].address,a.consumer,a.serviceIndex,a._providerFee,a._consumeMarketFee)).then(function(e){return s=1,e})})})})}}();return i&&i.then?i.then(e):e(i)}],[function(){return"fixed"},function(){var i=new ke(n.fixedRateExchangeAddress,t);if(!f[l].id)throw new Error("There is no fixed rate exchange with index: "+c+" for the asset with did: "+e.id);return Promise.resolve(i.getFeesInfo(f[l].id)).then(function(e){return Promise.resolve(i.getExchange(f[l].id)).then(function(s){return Promise.resolve(i.calcBaseInGivenDatatokensOut(e.exchangeId,"1",o.consumeMarketFeeAmount)).then(function(c){var l;function f(e){var i;if(l)return e;function o(e){if(i)return e}var u=function(){if(2===p||4===p)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(eP(t,n,e,s.baseToken,h[d].address,y,!1)).then(function(e){function t(e){if(!e)throw new Error("Failed to confirm/mine approval transaction!");return Promise.resolve(r.buyFromFreAndOrder(h[d].address,a,g)).then(function(e){return i=1,e})}if(!e)throw new Error("Failed to approve "+s.baseToken+" !");return"number"!=typeof e?Promise.resolve("number"!=typeof e?e.wait():e).then(t):t("number"!=typeof e?e.wait():e)})})}();return u&&u.then?u.then(o):o(u)}var y=new m(+c.baseTokenAmount||0).add(new m(o.consumeMarketFeeAmount||0)).add(new m(+b.publishMarketFeeAmount||0)).toString(),g={exchangeContract:n.fixedRateExchangeAddress,exchangeId:e.exchangeId,maxBaseTokenAmount:y,baseTokenAddress:s.baseToken,baseTokenDecimals:parseInt(s.btDecimals)||18,swapMarketFee:u,marketFeeAddress:b.publishMarketFeeAddress},v=function(){if(1===p)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(eP(t,n,e,s.baseToken,n.fixedRateExchangeAddress,y,!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",y,b.publishMarketFeeAddress,u)).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(h[d].address,a.consumer,a.serviceIndex,a._providerFee,a._consumeMarketFee)).then(function(e){return l=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(f):f(v)})})})}],[void 0,function(){throw new Error("Pricing schema not supported !")}]])}return s?a(s):Promise.resolve(t.getAddress()).then(a)}var v=a||i.providerFee,w=function(){if(v&&v.providerFeeAddress!==xe&&v.providerFeeAmount&&parseInt(v.providerFeeAmount)>0)return function(e,r){try{var i=Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(XT(t,n,e,v.providerFeeToken,g[0].datatokenAddress,v.providerFeeAmount)).then(function(){})})}catch(e){return r()}return i&&i.then?i.then(void 0,r):i}(0,function(){throw new Error("Failed to approve provider fee token "+v.providerFeeToken)})}();return w&&w.then?w.then(y):y()}var T=f.length>0?"fixed":y.length>0?"free":"NOT_ALLOWED",P=a||BT.initialize,x=a||g[c].id,E=a||e.id;return a?v(w(a)):Promise.resolve(t.getAddress()).then(v)})})})})})}catch(e){return Promise.reject(e)}};function oP(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var aP=function(e,n,r){try{var i=new t.Contract(e,Z,n);return Promise.resolve(n.getAddress()).then(function(e){var t,n=oP(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=ge(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)}},uP=function(e,n,r,i,o,u,d,c,l,h,f,m,y,g,v){void 0===d&&(d=!0);try{var w,P,x=this,E=b.getDDOClass(u),S=E.getAssetFields().indexedMetadata,A=(null==(w=E.getDDOData())||null==(w=w.stats)||null==(w=w.price)?void 0:w.value)||(null==S||null==(P=S.stats[0])||null==(P=P.prices[0])?void 0:P.price),k=E.getDDOFields(),C=k.chainId,I=k.nftAddress,D=E.getDDOFields().services;if("string"!=typeof o&&"number"!=typeof o)throw new Error('Invalid template! Must be a "number" or a "string"');return Promise.resolve(r.provider.getNetwork()).then(function(b){var w=b.chainId;if(C&&C!==Number(w))throw new Error("Chain ID from DDO is different than the configured network.");var P=(new K).getConfig(parseInt(String(w)));return Promise.resolve(Be(r,P.nftFactoryAddress,o,Number(w))).then(function(o){if(o<1){if(Number(w)!==dP)throw new Error("Invalid template index: "+o);o=1}var b=new qe(r,Number(w)),S=new Re(P.nftFactoryAddress,r,Number(w));return Promise.resolve(r.getAddress()).then(function(k){var M;function F(e){return M?e:Promise.resolve(R.wait()).then(function(e){var n;function i(e){if(n)return e;function t(){function e(){var e=b.setMetadata,s=I;return Promise.resolve(r.getAddress()).then(function(r){return Promise.resolve(e.call(b,s,r,0,c,"",p(i),t,n)).then(function(){return u.id})})}D[0].datatokenAddress=m,D[0].serviceEndpoint=c;var t,n,i,o=E.makeDid(I=f,C.toString());u=E.updateFields({id:o,nftAddress:I});var l=function(){if(d)return Promise.resolve(BT.encrypt(u,Number(w),c,r,null)).then(function(e){return t=e,Promise.resolve(h.validate(u,r,c)).then(function(e){n=e.hash,i=2})});var e=JSON.stringify(u);t=a(s(e)),n="0x"+T(t).toString(),i=0}();return l&&l.then?l.then(e):e()}var i=function(){if("oasis"!==P.sdk)return Promise.resolve(BT.encrypt(N,Number(w),c,r,null)).then(function(e){D[0].files=e});D[0].files=""}();return i&&i.then?i.then(t):t()}var o=ge(e,"NFTCreated"),l=ge(e,"TokenCreated"),f=o.args.newTokenAddress,m=l.args.newTokenAddress;N.datatokenAddress=m,N.nftAddress=f;var y=function(){if("oasis"===P.sdk){var e=new t.Contract(m,ze,r);return oP(function(){return Promise.resolve(e.setFilesObject(s(JSON.stringify(N)))).then(function(e){var t=function(){if(e.wait)return Promise.resolve(e.wait()).then(function(){})}();if(t&&t.then)return t.then(function(){})})},function(e){return console.log("Error updating files object with data token and nft addresses: ",e),n=1,null})}}();return y&&y.then?y.then(i):i(y)})}var R,L={name:e,symbol:n,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:k},_={templateIndex:o,cap:"100000",feeAmount:"0",paymentCollector:k,feeToken:l||P.oceanTokenAddress,minter:k,mpFeeAddress:xe},N={nftAddress:"0x0",datatokenAddress:"0x0",files:i};"oasis"===P.sdk&&(_.filesObject=N,_.accessListFactory=f||P.accessListFactory,_.allowAccessList=m,_.denyAccessList=y);var O=oP(function(){var e=function(){if(!A)return Promise.resolve(S.createNftWithDatatoken(L,_)).then(function(e){R=e});var e=function(){if("0"===A.toString())return Promise.resolve(S.createNftWithDatatokenWithDispenser(L,_,{dispenserAddress:P.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:xe})).then(function(e){R=e});var e=g||P.oceanTokenAddress;return Promise.resolve(ue(x.signer,e)).then(function(t){v||(v=t);var n={fixedRateAddress:P.fixedRateExchangeAddress,baseTokenAddress:e,owner:k,marketFeeCollector:k,baseTokenDecimals:v,datatokenDecimals:18,fixedRate:A.toString(),marketFee:"0",allowedConsumer:k,withMint:!0};return Promise.resolve(S.createNftWithDatatokenWithFixedRate(L,_,n)).then(function(e){R=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),M=1,null});return O&&O.then?O.then(F):F(O)})})})}catch(e){return Promise.reject(e)}},dP=8996;function cP(e){var t=(new K).getConfig(e);return t&&"oasis"===t.sdk}export{Ke as AccessListContract,We as AccesslistFactory,zT as Aquarius,S as Config,K as ConfigHelper,dP as DEVELOPMENT_CHAIN_ID,$e as Datatoken,Ve as Datatoken4,Pe as Dispenser,x as EncryptMethod,Xe as EnterpriseFeeCollectorContract,Je as EscrowContract,Ae as FEE_HISTORY_NOT_SUPPORTED,P as FileObjectType,ke as FixedRateExchange,Ee as GASLIMIT_DEFAULT,V as KNOWN_CONFIDENTIAL_EVMS,B as LogLevel,j as Logger,q as LoggerInstance,Se as MAX_UINT_256,qe as Nft,Re as NftFactory,kT as OCEAN_P2P_PROTOCOL,E as PROTOCOL_COMMANDS,OT as Provider,BT as ProviderInstance,Ie as Router,ve as SmartContract,we as SmartContractWithAddress,xe as ZERO_ADDRESS,JT as allowance,QT as allowanceWei,oe as amountToUnits,eP as approve,XT as approveWei,YT as balance,ie as buildTxOverrides,re as buildUnsignedTx,ju as bytesToHex,Be as calculateActiveTemplateIndex,qu as concatUint8Arrays,z as configHelperNetworks,aP as createAccessListFactory,uP as createAsset,HT as decimals,KT as downloadFile,WT as downloadFileBrowser,VT as generateDid,Me as generateDtName,nP as getErrorMessage,ge as getEventFromTx,de as getFairGasPrice,GT as getHash,G as getNodeEndpointConfig,Ue as getOceanArtifactsAddresses,je as getOceanArtifactsAddressesByChainId,ue as getTokenDecimals,tt as isDefined,NT as isP2pUri,X as minAbi,sP as orderAsset,te as sendPreparedTransaction,ne as sendPreparedTx,se as sendTx,be as setContractDefaults,rt as signHash,nt as signRequest,et as sleep,ZT as transfer,ae as unitsToAmount,cP as useOasisSDK};
3
+ /* @__PURE__ */,hi(3)),Hi=/* @__PURE__ */BigInt(0),Qi=/* @__PURE__ */BigInt(1);function Yi(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e);return e}function Ji(e){if("bigint"==typeof e){if(!ss(e))throw new Error("positive bigint expected, got "+e)}else Zr(e);return e}function Zi(e){const t=Ji(e).toString(16);return 1&t.length?"0"+t:t}function Xi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Hi:BigInt("0x"+e)}function es(e){return Xi(ai(e))}function ts(e){return Xi(ai(is(Xr(e)).reverse()))}function ns(e,t){Zr(t);const n=di((e=Ji(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}function rs(e,t){return ns(e,t).reverse()}function is(e){return Uint8Array.from(e)}const ss=e=>"bigint"==typeof e&&Hi<=e;function os(e,t,n,r){if(!function(e,t,n){return ss(e)&&ss(t)&&ss(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const as=e=>(Qi<<BigInt(e))-Qi;function us(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 ds(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 cs=/* @__PURE__ */BigInt(0),ls=/* @__PURE__ */BigInt(1),ps=/* @__PURE__ */BigInt(2),hs=/* @__PURE__ */BigInt(3),fs=/* @__PURE__ */BigInt(4),ms=/* @__PURE__ */BigInt(5),ys=/* @__PURE__ */BigInt(7),bs=/* @__PURE__ */BigInt(8),gs=/* @__PURE__ */BigInt(9),vs=/* @__PURE__ */BigInt(16);function ws(e,t){const n=e%t;return n>=cs?n:t+n}function Ts(e,t,n){let r=e;for(;t-- >cs;)r*=r,r%=n;return r}function Ps(e,t){if(e===cs)throw new Error("invert: expected non-zero number");if(t<=cs)throw new Error("invert: expected positive modulus, got "+t);let n=ws(e,t),r=t,i=cs,s=ls;for(;n!==cs;){const e=r%n,t=i-s*(r/n);r=n,n=e,i=s,s=t}if(r!==ls)throw new Error("invert: does not exist");return ws(i,t)}function xs(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Es(e,t){const n=e.pow(t,(e.ORDER+ls)/fs);return xs(e,n,t),n}function Ss(e,t){const n=(e.ORDER-ms)/bs,r=e.mul(t,ps),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,ps),i),a=e.mul(s,e.sub(o,e.ONE));return xs(e,a,t),a}function As(e){if(e<hs)throw new Error("sqrt is not defined for small field");let t=e-ls,n=0;for(;t%ps===cs;)t/=ps,n++;let r=ps;const i=Ms(e);for(;1===Is(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Es;let s=i.pow(r,t);const o=(t+ls)/ps;return function(e,r){if(e.is0(r))return r;if(1!==Is(e,r))throw new Error("Cannot find square root");let i=n,a=e.mul(e.ONE,s),u=e.pow(r,t),d=e.pow(r,o);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=ls<<BigInt(i-t-1),s=e.pow(a,r);i=t,a=e.sqr(s),u=e.mul(u,a),d=e.mul(d,s)}return d}}const ks=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Cs(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 Is(e,t){const n=e.pow(t,(e.ORDER-ls)/ps),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 Ds{ORDER;BITS;BYTES;isLE;ZERO=cs;ONE=ls;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=cs)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&&Zr(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 ws(e,this.ORDER)}isValid(e){if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return cs<=e&&e<this.ORDER}is0(e){return e===cs}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ls)===ls}neg(e){return ws(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ws(e*e,this.ORDER)}add(e,t){return ws(e+t,this.ORDER)}sub(e,t){return ws(e-t,this.ORDER)}mul(e,t){return ws(e*t,this.ORDER)}pow(e,t){return function(e,t,n){if(n<cs)throw new Error("invalid exponent, negatives unsupported");if(n===cs)return e.ONE;if(n===ls)return t;let r=e.ONE,i=t;for(;n>cs;)n&ls&&(r=e.mul(r,i)),i=e.sqr(i),n>>=ls;return r}(this,e,t)}div(e,t){return ws(e*Ps(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 Ps(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=(t=this.ORDER)%fs===hs?Es:t%bs===ms?Ss:t%vs===gs?function(e){const t=Ms(e),n=As(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+ys)/vs;return(e,t)=>{let n=e.pow(t,o),a=e.mul(n,r);const u=e.mul(n,i),d=e.mul(n,s),c=e.eql(e.sqr(a),t),l=e.eql(e.sqr(u),t);n=e.cmov(n,a,c),a=e.cmov(d,u,l);const p=e.eql(e.sqr(a),t),h=e.cmov(n,a,p);return xs(e,h,t),h}}(t):As(t)),this._sqrt(this,e);var t}toBytes(e){return this.isLE?rs(e,this.BYTES):ns(e,this.BYTES)}fromBytes(e,t=!1){Xr(e);const{_lengths:n,BYTES:r,isLE:i,ORDER:s,_mod:o}=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 a=i?ts(e):es(e);if(o&&(a=ws(a,s)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Cs(this,e)}cmov(e,t,n){return n?t:e}}function Ms(e,t={}){return new Ds(e,t)}function Fs(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 Rs(e){const t=Fs(e);return t+Math.ceil(t/2)}const Ls=/* @__PURE__ */BigInt(0),_s=/* @__PURE__ */BigInt(1);function Ns(e,t){const n=t.negate();return e?n:t}function Os(e,t){const n=Cs(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Bs(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Us(e,t){Bs(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:as(e),maxNumber:n,shiftBy:BigInt(e)}}function js(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(e&i),u=e>>o;a>r&&(a-=s,u+=_s);const d=t*r;return{nextN:u,offset:d+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:d}}const qs=new WeakMap,$s=new WeakMap;function zs(e){return $s.get(e)||1}function Vs(e){if(e!==Ls)throw new Error("invalid wNAF")}class Gs{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>Ls;)t&_s&&(n=n.add(r)),r=r.double(),t>>=_s;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Us(t,this.bits),i=[];let s=e,o=s;for(let e=0;e<n;e++){o=s,i.push(o);for(let e=1;e<r;e++)o=o.add(s),i.push(o);s=o.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=Us(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:o,offset:a,isZero:u,isNeg:d,isNegF:c,offsetF:l}=js(n,e,s);n=o,u?i=i.add(Ns(c,t[l])):r=r.add(Ns(d,t[a]))}return Vs(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Us(e,this.bits);for(let e=0;e<i.windows&&n!==Ls;e++){const{nextN:s,offset:o,isZero:a,isNeg:u}=js(n,e,i);if(n=s,!a){const e=t[o];r=r.add(u?e.negate():e)}}return Vs(n),r}getPrecomputes(e,t,n){let r=qs.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),qs.set(t,r))),r}cached(e,t,n){const r=zs(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=zs(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Bs(t,this.bits),$s.set(e,t),qs.delete(e)}hasCache(e){return 1!==zs(e)}}function Ks(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=ks.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",BYTES:"number",BITS:"number"});us(e,t)}(t),t}return Ms(e,{isLE:n})}function Ws(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>Ls))throw new Error(`CURVE.${e} must be positive bigint`)}const i=Ks(t.p,n.Fp,r),s=Ks(t.n,n.Fn,r),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)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 Hs(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}const Qs=BigInt(0),Ys=BigInt(1),Js=BigInt(2),Zs=BigInt(8);function Xs(e,t={}){const n=Ws("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;us(t,{},{uvRatio:"function"});const a=Js<<BigInt(8*i.BYTES)-Ys,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:Qs}}});if(!function(e,t,n,r){const i=e.sqr(n),s=e.sqr(r),o=e.add(e.mul(t.a,i),s),a=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(o,a)}(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function c(e,t,n=!1){return os("coordinate "+e,t,n?Ys:Qs,a),t}function l(e){if(!(e instanceof f))throw new Error("EdwardsPoint expected")}const p=ds((e,t)=>{const{X:n,Y:i,Z:s}=e,o=e.is0();null==t&&(t=o?Zs:r.inv(s));const a=u(n*t),d=u(i*t),c=r.mul(s,t);if(o)return{x:Qs,y:Ys};if(c!==Ys)throw new Error("invZ was invalid");return{x:a,y:d}}),h=ds(e=>{const{a:t,d:n}=s;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:o,T:a}=e,d=u(r*r),c=u(i*i),l=u(o*o),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(o*a))throw new Error("bad point: equation left != right (2)");return!0});class f{static BASE=new f(s.Gx,s.Gy,Ys,u(s.Gx*s.Gy));static ZERO=new f(Qs,Ys,Ys,Qs);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,Ys,u(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:o}=s;e=is(Xr(e,n,"point")),Yi(t,"zip215");const c=is(e),l=e[n-1];c[n-1]=-129&l;const p=ts(c);os("point.y",p,Qs,t?a:r.ORDER);const h=u(p*p),m=u(h-Ys),y=u(o*h-i);let{isValid:b,value:g}=d(m,y);if(!b)throw new Error("bad point: invalid y coordinate");const v=(g&Ys)===Ys,w=!!(128&l);if(!t&&g===Qs&&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(di(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(Js),this}assertValidity(){h(this)}equals(e){l(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:s,Z:o}=e,a=u(t*o),d=u(i*r),c=u(n*o),p=u(s*r);return a===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),o=u(n*n),a=u(Js*u(r*r)),d=u(e*i),c=t+n,l=u(u(c*c)-i-o),p=d+o,h=p-a,m=d-o,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:o,T:a}=this,{X:d,Y:c,Z:p,T:h}=e,m=u(r*d),y=u(i*c),b=u(a*n*h),g=u(o*p),v=u((r+i)*(d+c)-m-y),w=g-b,T=g+b,P=u(y-t*m),x=u(v*w),E=u(T*P),S=u(v*P),A=u(w*T);return new f(x,E,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=>Os(f,e));return Os(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===Qs?f.ZERO:this.is0()||e===Ys?this:m.unsafe(this,e,e=>Os(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(e){return p(this,e)}clearCofactor(){return o===Ys?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Ys?128:0,n}toHex(){return ai(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const m=new Gs(f,i.BITS);return f.BASE.precompute(8),f}const eo=BigInt(1),to=BigInt(2),no=BigInt(5),ro=BigInt(8),io=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),so=/* @__PURE__ */(()=>({p:io,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ro,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function oo(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const ao=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),uo=/* @__PURE__ */Xs(so,{uvRatio:function(e,t){const n=io,r=ws(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=io,o=e*e%s*e%s,a=Ts(o,to,s)*o%s,u=Ts(a,eo,s)*e%s,d=Ts(u,no,s)*u%s,c=Ts(d,t,s)*d%s,l=Ts(c,n,s)*c%s,p=Ts(l,r,s)*l%s,h=Ts(p,i,s)*p%s,f=Ts(h,i,s)*p%s,m=Ts(f,t,s)*d%s;return{pow_p_5_8:Ts(m,to,s)*e%s,b2:o}}(e*ws(r*r*t,n)).pow_p_5_8;let s=ws(e*r*i,n);const o=ws(t*s*s,n),a=s,u=ws(s*ao,n),d=o===e,c=o===ws(-e,n),l=o===ws(-e*ao,n);return d&&(s=a),(c||l)&&(s=u),(ws(s,n)&ls)===ls&&(s=ws(-s,n)),{isValid:d||c,value:s}}});function co(e){return function(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');us(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:o}=e,a=n.randomBytes||pi,u=n.adjustScalarBytes||(e=>e),d=n.domain||((e,t,n)=>{if(Yi(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function c(e){return o.create(ts(e))}function l(e){const{head:n,prefix:r,scalar:s}=function(e){const n=y.secretKey;Xr(e,y.secretKey,"secretKey");const r=Xr(t(e),2*n,"hashedSecretKey"),i=u(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:c(i)}}(e),o=i.multiply(s),a=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:a}}function p(e){return l(e).pointBytes}function h(e=Uint8Array.of(),...n){const i=ci(...n);return c(t(d(i,Xr(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=a(y.seed)){return Xr(e,y.seed,"seed")}const g={getExtendedPublicKey:l,randomSecretKey:b,isValidSecretKey:function(e){return Jr(e)&&e.length===o.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 o=i?s.div(Ys+n,Ys-n):s.div(n-Ys,n+Ys);return s.toBytes(o)},toMontgomerySecret(e){const n=y.secretKey;Xr(e,n);const r=t(e.subarray(0,n));return u(r).subarray(0,n)}};return Object.freeze({keygen:Hs(b,p),getPublicKey:p,sign:function(e,t,n={}){e=Xr(e,void 0,"message"),r&&(e=r(e));const{prefix:s,scalar:a,pointBytes:u}=l(t),d=h(n.context,s,e),c=i.multiply(d).toBytes(),p=h(n.context,c,u,e),f=o.create(d+p*a);if(!o.isValid(f))throw new Error("sign failed: invalid s");return Xr(ci(c,o.toBytes(f)),y.signature,"result")},verify:function(t,n,s,o=f){const{context:a,zip215:u}=o,d=y.signature;t=Xr(t,d,"signature"),n=Xr(n,void 0,"message"),s=Xr(s,y.publicKey,"publicKey"),void 0!==u&&Yi(u,"zip215"),r&&(n=r(n));const c=d/2,l=t.subarray(0,c),p=ts(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(a,b.toBytes(),m.toBytes(),n);return b.add(m.multiplyUnsafe(v)).subtract(g).clearCofactor().is0()},utils:g,Point:e,lengths:y})}(uo,Wi,Object.assign({adjustScalarBytes:oo},e))}const lo=/* @__PURE__ */co({});Error;class po extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class ho extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}var fo={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new ho("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 mo;const yo=(async()=>{try{return await fo.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function bo(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class go{type="Ed25519";raw;constructor(e){this.raw=To(e,32)}toMultihash(){return Qn(Wa(this))}toCID(){return zn.createV1(114,this.toMultihash())}toString(){return on.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();const r=async function(e,t,n){return null==mo&&(mo=await yo),mo?async function(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await fo.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await fo.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 lo.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}(e,t,n)}(this.raw,t,e);return bo(r)?r.then(e=>(n?.signal?.throwIfAborted(),e)):r}}class vo{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=To(e,64),this.publicKey=new go(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const n=async function(e,t){return null==mo&&(mo=await yo),mo?async function(e,t){let n;n=64===e.length?e.subarray(0,32):e;const r={crv:"Ed25519",kty:"OKP",x:Dr(e.subarray(32),"base64url"),d:Dr(n,"base64url"),ext:!0,key_ops:["sign"]},i=await fo.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await fo.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 lo.sign(t instanceof Uint8Array?t:t.subarray(),n)}(e,t)}(this.raw,e);return bo(n)?n.then(e=>(t?.signal?.throwIfAborted(),e)):(t?.signal?.throwIfAborted(),n)}}function wo(e){return e=To(e,32),new go(e)}function To(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new dt(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const Po=Math.pow(2,7),xo=Math.pow(2,14),Eo=Math.pow(2,21),So=Math.pow(2,28),Ao=Math.pow(2,35),ko=Math.pow(2,42),Co=Math.pow(2,49),Io=128,Do=127;function Mo(e){if(e<Po)return 1;if(e<xo)return 2;if(e<Eo)return 3;if(e<So)return 4;if(e<Ao)return 5;if(e<ko)return 6;if(e<Co)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fo(e,t,n=0){switch(Mo(e)){case 8:t[n++]=255&e|Io,e/=128;case 7:t[n++]=255&e|Io,e/=128;case 6:t[n++]=255&e|Io,e/=128;case 5:t[n++]=255&e|Io,e/=128;case 4:t[n++]=255&e|Io,e>>>=7;case 3:t[n++]=255&e|Io,e>>>=7;case 2:t[n++]=255&e|Io,e>>>=7;case 1:t[n++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function Ro(e,t){let n=e[t],r=0;if(r+=n&Do,n<Io)return r;if(n=e[t+1],r+=(n&Do)<<7,n<Io)return r;if(n=e[t+2],r+=(n&Do)<<14,n<Io)return r;if(n=e[t+3],r+=(n&Do)<<21,n<Io)return r;if(n=e[t+4],r+=(n&Do)*So,n<Io)return r;if(n=e[t+5],r+=(n&Do)*Ao,n<Io)return r;if(n=e[t+6],r+=(n&Do)*ko,n<Io)return r;if(n=e[t+7],r+=(n&Do)*Co,n<Io)return r;throw new RangeError("Could not decode varint")}function Lo(e,t,n=0){return null==t&&(t=Zn(Mo(e))),t instanceof Uint8Array?Fo(e,t,n):function(e,t,n=0){switch(Mo(e)){case 8:t.set(n++,255&e|Io),e/=128;case 7:t.set(n++,255&e|Io),e/=128;case 6:t.set(n++,255&e|Io),e/=128;case 5:t.set(n++,255&e|Io),e/=128;case 4:t.set(n++,255&e|Io),e>>>=7;case 3:t.set(n++,255&e|Io),e>>>=7;case 2:t.set(n++,255&e|Io),e>>>=7;case 1:t.set(n++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,n)}function _o(e,t=0){return e instanceof Uint8Array?Ro(e,t):function(e,t){let n=e.get(t),r=0;if(r+=n&Do,n<Io)return r;if(n=e.get(t+1),r+=(n&Do)<<7,n<Io)return r;if(n=e.get(t+2),r+=(n&Do)<<14,n<Io)return r;if(n=e.get(t+3),r+=(n&Do)<<21,n<Io)return r;if(n=e.get(t+4),r+=(n&Do)*So,n<Io)return r;if(n=e.get(t+5),r+=(n&Do)*Ao,n<Io)return r;if(n=e.get(t+6),r+=(n&Do)*ko,n<Io)return r;if(n=e.get(t+7),r+=(n&Do)*Co,n<Io)return r;throw new RangeError("Could not decode varint")}(e,t)}const No=new Float32Array([-0]),Oo=new Uint8Array(No.buffer);function Bo(e,t,n){No[0]=e,t[n]=Oo[0],t[n+1]=Oo[1],t[n+2]=Oo[2],t[n+3]=Oo[3]}const Uo=new Float64Array([-0]),jo=new Uint8Array(Uo.buffer);function qo(e,t,n){Uo[0]=e,t[n]=jo[0],t[n+1]=jo[1],t[n+2]=jo[2],t[n+3]=jo[3],t[n+4]=jo[4],t[n+5]=jo[5],t[n+6]=jo[6],t[n+7]=jo[7]}const $o=BigInt(Number.MAX_SAFE_INTEGER),zo=BigInt(Number.MIN_SAFE_INTEGER);class Vo{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 Go;if(e<$o&&e>zo)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>Ko&&(r=0n,++n>Ko&&(n=0n))),new Vo(Number(r),Number(n))}static fromNumber(e){if(0===e)return Go;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 Vo(n,r)}static from(e){return"number"==typeof e?Vo.fromNumber(e):"bigint"==typeof e?Vo.fromBigInt(e):"string"==typeof e?Vo.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Vo(e.low>>>0,e.high>>>0):Go}}const Go=new Vo(0,0);Go.toBigInt=function(){return 0n},Go.zzEncode=Go.zzDecode=function(){return this},Go.length=function(){return 1};const Ko=4294967296n;function Wo(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 Ho(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Qo(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Yo{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,Ho(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 Ho(this,4);return Qo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ho(this,4);return 0|Qo(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Ho(this,4);const e=(Oo[0]=(t=this.buf)[n=this.pos],Oo[1]=t[n+1],Oo[2]=t[n+2],Oo[3]=t[n+3],No[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ho(this,4);const e=(jo[0]=(t=this.buf)[n=this.pos],jo[1]=t[n+1],jo[2]=t[n+2],jo[3]=t[n+3],jo[4]=t[n+4],jo[5]=t[n+5],jo[6]=t[n+6],jo[7]=t[n+7],Uo[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 Ho(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,o=0;for(;t<n;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(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[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Ho(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Ho(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 Vo(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Ho(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 Ho(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 Ho(this,8);const e=Qo(this.buf,this.pos+=4),t=Qo(this.buf,this.pos+=4);return new Vo(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=Ro(this.buf,this.pos);return this.pos+=Mo(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 Jo(e){return new Yo(e instanceof Uint8Array?e:e.subarray())}function Zo(e,t,n){const r=Jo(e);return t.decode(r,void 0,n)}class Xo{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function ea(){}class ta{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const na=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Zn(r);n+r>e&&(t=Zn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class ra{len;head;tail;states;constructor(){this.len=0,this.head=new Xo(ea,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Xo(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new oa((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(aa,10,Vo.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Vo.fromBigInt(e);return this._push(aa,t.length(),t)}uint64Number(e){return this._push(Fo,Mo(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=Vo.fromBigInt(e).zzEncode();return this._push(aa,t.length(),t)}sint64Number(e){const t=Vo.fromNumber(e).zzEncode();return this._push(aa,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ia,1,e?1:0)}fixed32(e){return this._push(ua,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Vo.fromBigInt(e);return this._push(ua,4,t.lo)._push(ua,4,t.hi)}fixed64Number(e){const t=Vo.fromNumber(e);return this._push(ua,4,t.lo)._push(ua,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(Bo,4,e)}double(e){return this._push(qo,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(ia,1,0):this.uint32(t)._push(da,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(Wo,t,e):this._push(ia,1,0)}fork(){return this.states=new ta(this),this.head=this.tail=new Xo(ea,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 Xo(ea,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?Zn(n):na(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function ia(e,t,n){t[n]=255&e}function sa(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class oa extends Xo{next;constructor(e,t){super(sa,e,t),this.next=void 0}}function aa(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 ua(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 da(e,t,n){t.set(e,n)}function ca(e,t,n){t.set(e,n)}function la(e,t,n){e.length<40?Wo(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(Ir(e),n)}function pa(e,t){const n=new ra;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*ha(e,t,n){const r=Jo(e);yield*t.stream(r,void 0,"$",n)}function fa(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function ma(e,t,n){return fa("message",2,e,t,n)}var ya,ba,ga,va;function wa(e){if(isNaN(e)||e<=0)throw new dt("random bytes length must be a Number bigger than 0");return pi(e)}null!=globalThis.Buffer&&(ra.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(ca,t,e),this},ra.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(la,t,e),this}),function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(ya||(ya={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(ba||(ba={})),function(e){e.codec=()=>function(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return fa("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)})}(ba)}(ya||(ya={})),function(e){let t;e.codec=()=>(null==t&&(t=ma((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ya.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=ya.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:ya.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 pa(t,e.codec())},e.decode=function(t,n){return Zo(t,e.codec(),n)},e.stream=function(t,n){return ha(t,e.codec(),n)}}(ga||(ga={})),function(e){let t;e.codec=()=>(null==t&&(t=ma((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),ya.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=ya.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:ya.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 pa(t,e.codec())},e.decode=function(t,n){return Zo(t,e.codec(),n)},e.stream=function(t,n){return ha(t,e.codec(),n)}}(va||(va={}));class Ta{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 dt("JWK was missing components");return qr([Pa,jr(qr([Ur(Ir(e.n,"base64url")),Ur(Ir(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return zn.createV1(114,this._multihash)}toString(){return on.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(this.raw,e.raw)}verify(e,t,n){return async function(e,t,n,r){const i=await fo.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await fo.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 Pa=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);class xa{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(ei(e),Xr(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),ni(r)}update(e){return ti(this),this.iHash.update(e),this}digestInto(e){ti(this),Xr(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:o}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=o,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 Ea=(e,t,n)=>new xa(e,t).update(n).digest();Ea.create=(e,t)=>new xa(e,t);const Sa=(e,t)=>(e+(e>=0?t:-t)/Fa)/t;function Aa(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function ka(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Yi(n.lowS,"lowS"),Yi(n.prehash,"prehash"),void 0!==n.format&&Aa(n.format),n}class Ca extends Error{constructor(e=""){super(e)}}const Ia={Err:Ca,_tlv:{encode:(e,t)=>{const{Err:n}=Ia;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=Zi(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Zi(i.length/2|128):"";return Zi(e)+s+i+t},decode(e,t){const{Err:n}=Ia;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 o=t.subarray(r,r+e);if(o.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===o[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of o)s=s<<8|e;if(r+=e,s<128)throw new n("tlv.decode(long): not minimal encoding")}else s=i;const o=t.subarray(r,r+s);if(o.length!==s)throw new n("tlv.decode: wrong value length");return{v:o,l:t.subarray(r+s)}}},_int:{encode(e){const{Err:t}=Ia;if(e<Da)throw new t("integer: negative integers are not allowed");let n=Zi(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}=Ia;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 es(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ia,i=Xr(e,void 0,"signature"),{v:s,l:o}=r.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,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(a),s:n.decode(d)}},hexFromSig(e){const{_tlv:t,_int:n}=Ia,r=t.encode(2,n.encode(e.r)),i=t.encode(2,n.encode(e.s));return t.encode(48,r+i)}},Da=BigInt(0),Ma=BigInt(1),Fa=BigInt(2),Ra=BigInt(3),La=BigInt(4);function _a(e,t={}){const n=Ws("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;us(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=Oa(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(),o=r.toBytes(i);return Yi(n,"isCompressed"),n?(c(),ci(Na(!r.isOdd(s)),o)):ci(Uint8Array.of(4),o,r.toBytes(s))},p=t.fromBytes||function(e){Xr(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=d,i=e.length,s=e[0],o=e.subarray(1);if(i!==t||2!==s&&3!==s){if(i===n&&4===s){const e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.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(o);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,Ra),La),y=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(m,y)))throw new Error("bad curve params: a or b");function b(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function g(e){if(!(e instanceof x))throw new Error("Weierstrass Point expected")}function v(e){if(!u||!u.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[s,o]]=t,a=Sa(o*e,n),u=Sa(-i*e,n);let d=e-a*r-u*s,c=-a*i-u*o;const l=d<Da,p=c<Da;l&&(d=-d),p&&(c=-c);const h=as(Math.ceil(function(e){let t;for(t=0;e>Hi;e>>=Qi,t+=1);return t}(n)/2))+Ma;if(d<Da||d>=h||c<Da||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=ds((e,t)=>{const{X:n,Y:i,Z:s}=e;if(r.eql(s,r.ONE))return{x:n,y:i};const o=e.is0();null==t&&(t=o?r.ONE:r.inv(s));const a=r.mul(n,t),u=r.mul(i,t),d=r.mul(s,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(d,r.ONE))throw new Error("invZ was invalid");return{x:a,y:u}}),T=ds(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 P(e,t,n,i,s){return n=new x(r.mul(n.X,e),n.Y,n.Z),t=Ns(i,t),n=Ns(s,n),t.add(n)}class x{static BASE=new x(s.Gx,s.Gy,r.ONE);static ZERO=new x(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=i;X;Y;Z;constructor(e,t,n){this.X=b("x",e),this.Y=b("y",t,!0),this.Z=b("z",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof x)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?x.ZERO:new x(t,n,r.ONE)}static fromBytes(e){const t=x.fromAffine(p(Xr(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return x.fromBytes(di(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(Ra),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:o,Z:a}=e,u=r.eql(r.mul(t,a),r.mul(s,i)),d=r.eql(r.mul(n,a),r.mul(o,i));return u&&d}negate(){return new x(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,Ra),{X:i,Y:o,Z:a}=this;let u=r.ZERO,d=r.ZERO,c=r.ZERO,l=r.mul(i,i),p=r.mul(o,o),h=r.mul(a,a),f=r.mul(i,o);return f=r.add(f,f),c=r.mul(i,a),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(o,a),h=r.add(h,h),l=r.mul(h,f),u=r.sub(u,l),c=r.mul(h,p),c=r.add(c,c),c=r.add(c,c),new x(u,d,c)}add(e){g(e);const{X:t,Y:n,Z:i}=this,{X:o,Y:a,Z:u}=e;let d=r.ZERO,c=r.ZERO,l=r.ZERO;const p=s.a,h=r.mul(s.b,Ra);let f=r.mul(t,o),m=r.mul(n,a),y=r.mul(i,u),b=r.add(t,n),v=r.add(o,a);b=r.mul(b,v),v=r.add(f,m),b=r.sub(b,v),v=r.add(t,i);let w=r.add(o,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(a,u),w=r.mul(w,d),d=r.add(m,y),w=r.sub(w,d),l=r.mul(p,v),d=r.mul(h,y),l=r.add(d,l),d=r.sub(m,l),l=r.add(m,l),c=r.mul(d,l),m=r.add(f,f),m=r.add(m,f),y=r.mul(p,y),v=r.mul(h,v),m=r.add(m,y),y=r.sub(f,y),y=r.mul(p,y),v=r.add(v,y),f=r.mul(m,v),c=r.add(c,f),f=r.mul(w,v),d=r.mul(b,d),d=r.sub(d,f),f=r.mul(b,m),l=r.mul(w,l),l=r.add(l,f),new x(d,c,l)}subtract(e){return this.add(e.negate())}is0(){return this.equals(x.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,s;const o=e=>S.cached(this,e,e=>Os(x,e));if(n){const{k1neg:t,k1:i,k2neg:a,k2:u}=v(e),{p:d,f:c}=o(i),{p:l,f:p}=o(u);s=c.add(p),r=P(n.beta,d,l,t,a)}else{const{p:t,f:n}=o(e);r=t,s=n}return Os(x,[r,s])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===Da||r.is0())return x.ZERO;if(e===Ma)return r;if(S.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:s,k2:o}=v(e),{p1:a,p2:u}=function(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>Ls||r>Ls;)n&_s&&(s=s.add(i)),r&_s&&(o=o.add(i)),i=i.double(),n>>=_s,r>>=_s;return{p1:s,p2:o}}(x,r,i,o);return P(n.beta,a,u,t,s)}return S.unsafe(r,e)}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===Ma||(e?e(x,this):S.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===Ma?this:e?e(x,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Yi(e,"isCompressed"),this.assertValidity(),l(x,this,e)}toHex(e=!0){return ai(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const E=i.BITS,S=new Gs(x,t.endo?Math.ceil(E/2):E);return x.BASE.precompute(8),x}function Na(e){return Uint8Array.of(e?2:3)}function Oa(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ba(e,t,n={}){ei(t),us(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=(n=Object.assign({},n)).randomBytes||pi,i=n.hmac||((e,n)=>Ea(t,e,n)),{Fp:s,Fn:o}=e,{ORDER:a,BITS:u}=o,{keygen:d,getPublicKey:c,getSharedSecret:l,utils:p,lengths:h}=function(e,t={}){const{Fn:n}=e,r=t.randomBytes||pi,i=Object.assign(Oa(e.Fp,n),{seed:Rs(n.ORDER)});function s(e=r(i.seed)){return function(e,t,n=!1){Xr(e);const r=e.length,i=Fs(t),s=Rs(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=ws(n?ts(e):es(e),t-ls)+ls;return n?rs(o,i):ns(o,i)}(Xr(e,i.seed,"seed"),n.ORDER)}function o(t,r=!0){return e.BASE.multiply(n.fromBytes(t)).toBytes(r)}function a(e){const{secretKey:t,publicKey:r,publicKeyUncompressed:s}=i;if(!Jr(e))return;if("_lengths"in n&&n._lengths||t===r)return;const o=Xr(e,void 0,"key").length;return o===r||o===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=Hs(s,o);return Object.freeze({getPublicKey:o,getSharedSecret:function(t,r,i=!0){if(!0===a(t))throw new Error("first arg must be private key");if(!1===a(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=a*Fa<s.ORDER;function y(e){return e>a>>Ma}function b(e,t){if(!o.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){Aa(t);const n=h.signature;return Xr(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}=Ia.toSig(Xr(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(o.fromBytes(i),o.fromBytes(s),n)}static fromHex(e,t){return this.fromBytes(di(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+a: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(ci(Na(!(1&i)),d)),l=o.inv(u),p=P(Xr(t,void 0,"msgHash")),h=o.create(-p*l),f=o.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(Aa(e),"der"===e)return di(Ia.hexFromSig(this));const{r:t,s:n}=this,r=o.toBytes(t),i=o.toBytes(n);return"recovered"===e?(g(),ci(Uint8Array.of(this.assertRecovery()),r,i)):ci(r,i)}toHex(e){return ai(this.toBytes(e))}}const T=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=es(e),n=8*e.length-u;return n>0?t>>BigInt(n):t},P=n.bits2int_modN||function(e){return o.create(T(e))},x=as(u);function E(e){return os("num < 2^"+u,e,Da,x),o.toBytes(e)}function S(e,n){return Xr(e,void 0,"message"),n?Xr(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,a={}){const{seed:u,k2sig:d}=function(t,n,i){const{lowS:s,prehash:a,extraEntropy:u}=ka(i,f);t=S(t,a);const d=P(t),c=o.fromBytes(n);if(!o.isValidNot0(c))throw new Error("invalid private key");const l=[E(c),E(d)];if(null!=u&&!1!==u){const e=!0===u?r(h.secretKey):u;l.push(Xr(e,void 0,"extraEntropy"))}const p=ci(...l),b=d;return{seed:p,k2sig:function(t){const n=T(t);if(!o.isValidNot0(n))return;const r=o.inv(n),i=e.BASE.multiply(n).toAffine(),a=o.create(i.x);if(a===Da)return;const u=o.create(r*o.create(b+a*c));if(u===Da)return;let d=(i.x===a?0:2)|Number(i.y&Ma),l=u;return s&&y(u)&&(l=o.neg(u),d^=1),new w(a,l,m?void 0:d)}}}(n,s,a),c=function(e,t,n){if(Zr(e,"hashLen"),Zr(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),o=Uint8Array.of(1);let a=r(e),u=r(e),d=0;const c=()=>{a.fill(1),u.fill(0),d=0},l=(...e)=>n(u,ci(a,...e)),p=(e=i)=>{u=l(s,e),a=l(),0!==e.length&&(u=l(o,e),a=l())},h=()=>{if(d++>=1e3)throw new Error("drbg: tried max amount of iterations");let e=0;const n=[];for(;e<t;){a=l();const t=a.slice();n.push(t),e+=a.length}return ci(...n)};return(e,t)=>{let n;for(c(),p(e);!(n=t(h()));)p();return c(),n}}(t.outputLen,o.BYTES,i);return c(u,d).toBytes(a.format)},verify:function(t,n,r,i={}){const{lowS:s,prehash:a,format:u}=ka(i,f);if(r=Xr(r,void 0,"publicKey"),n=S(n,a),!Jr(t))throw new Error("verify expects Uint8Array signature"+(t instanceof w?", use sig.toBytes()":""));v(t,u);try{const i=w.fromBytes(t,u),a=e.fromBytes(r);if(s&&i.hasHighS())return!1;const{r:d,s:c}=i,l=P(n),p=o.inv(c),h=o.create(l*p),f=o.create(d*p),m=e.BASE.multiplyUnsafe(h).add(a.multiplyUnsafe(f));return!m.is0()&&o.create(m.x)===d}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=ka(n,f);return t=S(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}const Ua={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ja={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},qa=/* @__PURE__ */BigInt(2),$a=Ms(Ua.p,{sqrt:function(e){const t=Ua.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),u=BigInt(88),d=e*e*e%t,c=d*d*e%t,l=Ts(c,n,t)*c%t,p=Ts(l,n,t)*c%t,h=Ts(p,qa,t)*d%t,f=Ts(h,i,t)*h%t,m=Ts(f,s,t)*f%t,y=Ts(m,a,t)*m%t,b=Ts(y,u,t)*y%t,g=Ts(b,a,t)*m%t,v=Ts(g,n,t)*c%t,w=Ts(v,o,t)*f%t,T=Ts(w,r,t)*d%t,P=Ts(T,qa,t);if(!$a.eql($a.sqr(P),e))throw new Error("Cannot find square root");return P}}),za=/* @__PURE__ */Ba(/* @__PURE__ */_a(Ua,{Fp:$a,endo:ja}),Ki);class Va{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return za.Point.fromBytes(e),e}catch(e){throw new ct(String(e))}}(e),this.raw=function(e){return za.Point.fromBytes(e).toBytes()}(this._key)}toMultihash(){return Qn(Wa(this))}toCID(){return zn.createV1(114,this.toMultihash())}toString(){return on.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Yn(this.raw,e.raw)}verify(e,t,n){return function(e,t,n,r){const i=xr.digest(n instanceof Uint8Array?n:n.subarray());if(bo(i))return i.then(({digest:n})=>(r?.signal?.throwIfAborted(),za.verify(t,n,e,{prehash:!1,format:"der"}))).catch(e=>{if("AbortError"===e.name)throw e;throw new po(String(e))});try{return r?.signal?.throwIfAborted(),za.verify(t,i.digest,e,{prehash:!1,format:"der"})}catch(e){throw new po(String(e))}}(this._key,t,e,n)}}function Ga(e){return new Va(e)}function Ka(e,t){const{Type:n,Data:r}=ga.decode(e),i=r??new Uint8Array;switch(n){case ya.RSA:return function(e,t){if(e.byteLength>=1062)throw new ct("Key size is too large");return function(e,t,n){const r=function(e){const t=_r(e[1],{offset:0});return{kty:"RSA",n:Dr(t[0],"base64url"),e:Dr(t[1],"base64url")}}(e);return null==n&&(n=On(18,Ki(ga.encode({Type:ya.RSA,Data:t})))),new Ta(r,n)}(_r(e,{offset:0}),e,t)}(i,t);case ya.Ed25519:return wo(i);case ya.secp256k1:return Ga(i);case ya.ECDSA:return Hr(i);default:throw new Ft}}function Wa(e){return ga.encode({Type:ya[e.type],Data:e.raw})}const Ha=Symbol.for("nodejs.util.inspect.custom");class Qa{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()})`}[Bt]=!0;toString(){return null==this.string&&(this.string=on.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return zn.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Yn(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Yn(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ha](){return`PeerId(${this.toString()})`}}class Ya extends Qa{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Ja extends Qa{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Za extends Qa{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class Xa{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Qn(Ir(this.url))}[Ha](){return`PeerId(${this.url})`}[Bt]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return zn.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=Dr(e)),e.toString()===this.toString())}}function eu(e,t){let n;if("1"===e.charAt(0)||"Q"===e.charAt(0))n=Bn(on.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return ru(zn.parse(e));if(null==t)throw new dt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');n=Bn(t.decode(e))}return nu(n)}function tu(e){if("Ed25519"===e.type)return new Ja({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Za({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Ya({multihash:e.toCID().multihash,publicKey:e});throw new Ft}function nu(e){if(function(e){return e.code===xr.code}(e))return new Ya({multihash:e});if(function(e){return 0===e.code}(e))try{const t=function(e){const{Type:t,Data:n}=ga.decode(e.digest),r=n??new Uint8Array;switch(t){case ya.Ed25519:return wo(r);case ya.secp256k1:return Ga(r);case ya.ECDSA:return Hr(r);default:throw new Ft}}(e);if("Ed25519"===t.type)return new Ja({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Za({multihash:e,publicKey:t})}catch(t){const n=Dr(e.digest);return new Xa(new URL(n))}throw new Tt("Supplied PeerID Multihash is invalid")}function ru(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new wt("Supplied PeerID CID is invalid");if(2336===e.code){const t=Dr(e.multihash.digest);return new Xa(new URL(t))}return nu(e.multihash)}class iu extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class su extends Error{static name="ValidationError";name="ValidationError"}class ou extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class au extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const uu=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 o=this.peekChar();if(void 0===o)return;const a="0"===o,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&&a&&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),[o]=e(i.subarray(0,s));return t.set(i.subarray(0,o),16-o),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function du(e){if(!(e.length>15))return uu.new(e).parseWith(()=>uu.readIPv4Addr())}function cu(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return uu.new(e).parseWith(()=>uu.readIPv6Addr())}function lu(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const n=uu.new(e).parseWith(()=>uu.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 pu(e){return Boolean(du(e))}function hu(e){return Boolean(cu(e))}const fu=41,mu=421,yu=448,bu=449,gu=466,vu=281,wu=290;function Tu(e){return t=>Dr(t,e)}function Pu(e){return t=>Ir(t,e)}function xu(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Eu(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function Su(e){const t=e.subarray(0,e.length-2),n=e.subarray(e.length-2);return`${Dr(t,"base32")}:${xu(n)}`}const Au=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 iu("Invalid byte value in IP address");t[n]=r}),t},ku=Object.values(Er).map(e=>e.decoder),Cu=function(){let e=ku[0].or(ku[1]);return ku.slice(2).forEach(t=>e=e.or(t)),e}(),Iu=function(...e){return t=>{for(const n of e)n(t)}}(function(e){if(parseInt(e).toString()!==e)throw new su("Value must be an integer")},function(e){if(e<0)throw new su("Value must be a positive integer, or zero")},e=>{if(e>65535)throw new su("Value must be smaller than or equal to 65535")}),Du=-1,Mu=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 au(`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)}))}},Fu=[{code:4,name:"ip4",size:32,valueToBytes:Au,bytesToValue:function(e){if(4!==e.byteLength)throw new iu("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(!pu(e))throw new su(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Eu,bytesToValue:xu,validate:Iu},{code:273,name:"udp",size:16,valueToBytes:Eu,bytesToValue:xu,validate:Iu},{code:33,name:"dccp",size:16,valueToBytes:Eu,bytesToValue:xu,validate:Iu},{code:fu,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;pu(n[r])&&(e=Au(n[r]),n[r]=Dr(e.subarray(0,2),"base16")),null!=e&&++r<8&&n.splice(r,0,Dr(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 iu("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 iu("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 iu(`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 iu(`Invalid IPv6 address "${e}"`)}},validate:e=>{if(!hu(e))throw new su(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:Du},{code:43,name:"ipcidr",size:8,bytesToValue:Tu("base10"),valueToBytes:Pu("base10")},{code:53,name:"dns",size:Du},{code:54,name:"dns4",size:Du},{code:55,name:"dns6",size:Du},{code:56,name:"dnsaddr",size:Du},{code:132,name:"sctp",size:16,valueToBytes:Eu,bytesToValue:xu,validate:Iu},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Du,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:mu,name:"p2p",aliases:["ipfs"],size:Du,bytesToValue:Tu("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Pu("base58btc")(e):zn.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Su,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=Ir(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=Eu(r);return Xn([n,i],n.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:Su,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=dn.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=Eu(r);return Xn([n,i],n.length+i.length)}},{code:446,name:"garlic64",size:Du},{code:447,name:"garlic32",size:Du},{code:yu,name:"tls"},{code:bu,name:"sni",size:Du},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:gu,name:"certhash",size:Du,bytesToValue:(Ru=fr,e=>Ru.encoder.encode(e)),valueToBytes:function(e){return Cu.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:Du,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:vu,name:"webrtc"},{code:wu,name:"p2p-circuit"},{code:777,name:"memory",size:Du}];var Ru;function Lu(e,t,n){return null==e.size||0===e.size?0:e.size>0?e.size/8:_o(t,n)}Fu.forEach(e=>{Mu.addProtocol(e)});const _u=Symbol.for("nodejs.util.inspect.custom"),Nu=Symbol.for("@multiformats/multiaddr");class Ou{[Nu]=!0;#t;#n;#r;constructor(e="/",t={}){this.#t=function(e){if(null==e&&(e="/"),Bu(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let n=0;for(;n<e.length;){const r=_o(e,n),i=Mu.getProtocol(r),s=Mo(r),o=Lu(i,e,n+s);let a=0;o>0&&i.size===Du&&(a=Mo(o));const u=s+a+o,d={code:r,name:i.name,bytes:e.subarray(n,n+u)};if(o>0){const t=n+s+a,r=e.subarray(t,t+o);d.value=i.bytesToValue?.(r)??Dr(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 iu('String multiaddr must start with "/"');const t=[];let n="protocol",r="",i="";for(let s=1;s<e.length;s++){const o=e.charAt(s);"/"!==o&&("protocol"===n?i+=e.charAt(s):r+=e.charAt(s));const a=s===e.length-1;if("/"===o||a){const e=Mu.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(a)throw new iu(`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 iu(`Component ${i} was missing value`);s.value=e.stringToValue?.(r)??r}t.push(s),r="",i="",n="protocol"}}}if(""!==i&&""!==r)throw new iu("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new iu("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach(e=>{const t=Mu.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=Mu.getProtocol(r.code),t=Mo(r.code);let n,i=0,s=0;null!=r.value&&(n=e.valueToBytes?.(r.value)??Ir(r.value),i=n.byteLength,e.size===Du&&(s=Mo(i)));const o=new Uint8Array(t+s+i);let a=0;Fo(r.code,o,a),a+=t,null!=n&&(e.size===Du&&(Fo(i,o,a),a+=s),o.set(n,a)),r.bytes=o}n.push(r.bytes),t+=r.bytes.byteLength}return Xn(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=Mu.getProtocol(e.code);if(null==t)throw new iu(`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 Ou(e);return new Ou([...this.#t,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),n=this.toString(),r=n.lastIndexOf(t);if(r<0)throw new ou(`Address ${this.toString()} does not contain subaddress: ${t}`);return new Ou(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 Ou(this.#t.slice(0,t),{validate:!1})}equals(e){return Yn(this.bytes,e.bytes)}[_u](){return`Multiaddr(${this.toString()})`}}function Bu(e){return Boolean(e?.[Nu])}function Uu(e){return new Ou(e)}function ju(e){return Array.from(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function qu(e){for(var t,n=e.reduce(function(e,t){return e+t.length},0),r=new Uint8Array(n),i=0,s=M(e);!(t=s()).done;){var o=t.value;r.set(o,i),i+=o.length}return r}function $u(e,t){var n=v.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"+ju(t)}(e)),r=w(n.toHex(),(new TextEncoder).encode(t));return ju(new Uint8Array(r))}function zu(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var Vu=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getAuthorization=function(e){return RT(e)},t.getSignedCommandParams=function(e,t,n,r,i,s){try{var o,a=function(a){if(o)return a;function d(){function o(){return Promise.resolve(FT(t)).then(function(o){return Promise.resolve(u.getNonce(e,o,r,i,s)).then(function(e){var r=(e+1).toString();return Promise.resolve(MT(t,r,n)).then(function(e){if(!e)throw new Error("Could not sign persistent storage request.");return{consumerAddress:o,nonce:r,signature:e}})})})}var a=function(){if(!s)return Promise.resolve(u.getServiceEndpoints(e,i)).then(function(e){s=e})}();return a&&a.then?a.then(o):o()}var c=function(){if(!i)return Promise.resolve(u.getEndpoints(e)).then(function(e){i=e})}();return c&&c.then?c.then(d):d()},u=this;if(LT(t))return Promise.resolve({consumerAddress:t.consumerAddress,nonce:t.nonce,signature:t.signature});var d=function(){if("string"==typeof t)return Promise.resolve(FT(t)).then(function(e){return o=1,{consumerAddress:e,nonce:void 0,signature:void 0}})}();return Promise.resolve(d&&d.then?d.then(a):a(d))}catch(e){return Promise.reject(e)}},t.resolvePersistentStorageRoute=function(e,t,n,r){for(var i,s=M(n);!(i=s()).done;){var o=this.getEndpointURL(t,i.value);if(null!=o&&o.urlPath)return o.urlPath}return e.replace(/\/+$/,"")+r},t.getEndpoints=function(e,t){try{var n=this;return Promise.resolve(zu(function(){return Promise.resolve(n.getData(e,t)).then(function(e){return Promise.resolve(e.json())})},function(e){throw q.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?zu(function(){return Promise.resolve(y(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 q.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),zu(function(){return Promise.resolve(y(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 q.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=o.getEndpointURL(i,"nonce")?o.getEndpointURL(i,"nonce").urlPath:null;return e?zu(function(){return Promise.resolve(y(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 q.error(e),new Error(e.message)}):null}var a=function(){if(!i)return Promise.resolve(o.getServiceEndpoints(e,r)).then(function(e){i=e})}();return a&&a.then?a.then(s):s()},o=this,a=function(){if(!r)return Promise.resolve(o.getEndpoints(e)).then(function(e){r=e})}();return Promise.resolve(a&&a.then?a.then(s):s())}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.getEndpoints(n)).then(function(i){return Promise.resolve(o.getServiceEndpoints(n,i)).then(function(a){return Promise.resolve(o.getSignedCommandParams(n,r,E.ENCRYPT,s,i,a)).then(function(n){var r=n.consumerAddress,i=n.nonce,u=n.signature,d=(o.getEndpointURL(a,"encrypt")?o.getEndpointURL(a,"encrypt").urlPath:null)+"?chainId="+t;return d?(i&&(d+="&nonce="+i),r&&(d+="&consumerAddress="+r),u&&(d+="&signature="+u),zu(function(){return Promise.resolve(y(d,{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 q.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(o){return Promise.resolve(s.getServiceEndpoints(n,o)).then(function(n){function o(e){var t;function n(e){return t?e:Promise.resolve(a.json()).then(function(e){throw q.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=M(e);!(n=r()).done;)d.push(n.value);return t=1,d})}();return r&&r.then?r.then(n):n(r)}var a,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=zu(function(){return Promise.resolve(y(c,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/json"},signal:i})).then(function(e){a=e})},function(e){throw q.error("File info call failed: "),q.error(e),new Error(e)});return l&&l.then?l.then(o):o()})})}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(o.json()).then(function(e){throw q.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=M(e);!(n=r()).done;)u.push(n.value);return t=1,u})}();return r&&r.then?r.then(n):n(r)}var o,a=F({},e,{checksum:n}),u=[],d=i.getEndpointURL(t,"fileinfo")?i.getEndpointURL(t,"fileinfo").urlPath:null;if(!d)return null;var c=zu(function(){return Promise.resolve(y(d,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"},signal:r})).then(function(e){o=e})},function(e){throw q.error("File info call failed: "),q.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 q.error("Fetch compute env failed: ",s.status,s.statusText,e),new Error(JSON.stringify(e))})}var s,o=null==(r=n.getEndpointURL(e,"computeEnvironments"))?void 0:r.urlPath;if(!o)return null;var a=zu(function(){return Promise.resolve(y(o,{method:"GET",headers:{"Content-Type":"application/json"},signal:t})).then(function(e){s=e})},function(e){throw q.error("Fetch compute env failed: "),q.error(e),new Error(e)});return a&&a.then?a.then(i):i()})})}catch(e){return Promise.reject(e)}},t.initialize=function(e,t,n,r,i,s,o,a,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 q.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,o&&(p+="&userdata="+encodeURI(JSON.stringify(o))),a&&(p+="&environment="+encodeURI(a)),u&&(p+="&validUntil="+u);var h=zu(function(){return Promise.resolve(y(p,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})).then(function(e){l=e})},function(e){throw q.error("Provider initialized failed: "),q.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,o,a,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 b(){function e(){var e;function t(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw q.error("Initialize compute failed: ",e.status,e.statusText,t),q.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(t))})}var i=function(t){if(null!=(t=e)&&t.ok)return Promise.resolve(e.json()).then(function(e){return n=1,e})}();return i&&i.then?i.then(r):r(i)}var n=zu(function(){return Promise.resolve(y(g,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json"},signal:c})).then(function(t){return e=t,function(){if(!e.ok)return Promise.resolve(e.text()).then(function(e){throw new Error(""+e)})}()})},function(e){throw q.error("Initialize compute failed: "),q.error(e),new Error("ComputeJob cannot be initialized: "+e.message+".")});return n&&n.then?n.then(t):t()}var t=function(){if(h)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(v.output=$u(e,JSON.stringify(h)))})}();return t&&t.then?t.then(e):e()}var g=f.getEndpointURL(m,"initializeCompute")?f.getEndpointURL(m,"initializeCompute").urlPath:null;if(!g)return null;var v={datasets:e,algorithm:t,environment:n,payment:{chainId:u,token:r,resources:a},maxJobDuration:i,consumerAddress:o};d&&(v.policyServer=d),l&&(v.queueMaxWaitTime=l);var w=function(){if(p)return Promise.resolve(f.getNodePublicKey(s)).then(function(e){e&&(v.encryptedDockerRegistryAuth=$u(e,JSON.stringify(p)))})}();return w&&w.then?w.then(b):b()})})}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,o,a){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.getSignedCommandParams(i,s,E.DOWNLOAD,void 0,d,c)).then(function(i){var s=i.consumerAddress,u=i.nonce,d=i.signature,c=l;return c+="?fileIndex="+n,c+="&documentId="+e,c+="&transferTxId="+r,c+="&serviceId="+t,s&&(c+="&consumerAddress="+s),u&&(c+="&nonce="+u),d&&(c+="&signature="+d),o&&(c+="&policyServer="+encodeURI(JSON.stringify(o))),a&&(c+="&userdata="+encodeURI(JSON.stringify(a))),c}):null})})}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h,f,m,b){try{var g=this;return Promise.resolve(g.getEndpoints(e)).then(function(v){return Promise.resolve(g.getServiceEndpoints(e,v)).then(function(w){var T=g.getEndpointURL(w,"computeStart")?g.getEndpointURL(w,"computeStart").urlPath:null;return T?Promise.resolve(g.getSignedCommandParams(e,t,E.COMPUTE_START,h,v,w)).then(function(v){var w=v.consumerAddress,P=v.nonce,x=v.signature;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 q.error("Compute start failed: ",e.status,e.statusText,t),q.error("Payload was:",S),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)}b&&(S.outputBucketId=b),p&&(S.policyServer=p),f&&(S.queueMaxWaitTime=f);var r=zu(function(){var n=g.getAuthorization(t);return Promise.resolve(y(T,{method:"POST",body:JSON.stringify(S),headers:F({"Content-Type":"application/json"},n?{Authorization:n}:{}),signal:h})).then(function(t){e=t})},function(e){throw q.error("Compute start failed:"),q.error(e),q.error("Payload was:",S),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}a&&(S.resources=a),d&&(S.metadata=d),c&&(S.additionalViewers=c);var r=function(){if(l)return Promise.resolve(g.getNodePublicKey(e)).then(function(e){e&&(S.output=$u(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var S=Object();S.consumerAddress=w,S.signature=x,S.nonce=P,S.environment=n,S.maxJobDuration=s,S.resources=a,S.dataset=r[0],S.datasets=r,S.algorithm=i,S.chainId=u,S.payment={chainId:u,token:o,maxJobDuration:s,resources:a};var A=function(){if(m)return Promise.resolve(g.getNodePublicKey(e)).then(function(e){e&&(S.encryptedDockerRegistryAuth=$u(e,JSON.stringify(m)))})}();return A&&A.then?A.then(E):E()}):(q.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,o,a,u,d,c,l,p,h){try{var f=this;return Promise.resolve(f.getEndpoints(e)).then(function(m){return Promise.resolve(f.getServiceEndpoints(e,m)).then(function(b){var g=f.getEndpointURL(b,"freeCompute")?f.getEndpointURL(b,"freeCompute").urlPath:null;return g?Promise.resolve(f.getSignedCommandParams(e,t,E.FREE_COMPUTE_START,c,m,b)).then(function(m){var b=m.consumerAddress,v=m.nonce,w=m.signature;function T(){function n(){var e;function n(t){var n;function r(t){return n?t:Promise.resolve(e.json()).then(function(t){throw q.error("Compute start failed: ",e.status,e.statusText,t),q.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)}h&&(P.outputBucketId=h),d&&(P.policyServer=d),l&&(P.queueMaxWaitTime=l);var r=zu(function(){var n=f.getAuthorization(t);return Promise.resolve(y(g,{method:"POST",body:JSON.stringify(P),headers:F({"Content-Type":"application/json"},n?{Authorization:n}:{}),signal:c})).then(function(t){e=t})},function(e){throw q.error("Compute start failed:"),q.error(e),q.error("Payload was:",P),new Error("HTTP request failed calling Provider")});return r&&r.then?r.then(n):n()}var r=function(){if(u)return Promise.resolve(f.getNodePublicKey(e)).then(function(e){e&&(P.output=$u(e,JSON.stringify(u)))})}();return r&&r.then?r.then(n):n()}var P=Object();P.consumerAddress=b,P.signature=w,P.nonce=v,P.environment=n,P.resources=s,P.dataset=r[0],P.datasets=r,P.algorithm=i,o&&(P.metadata=o),a&&(P.additionalViewers=a);var x=function(){if(p)return Promise.resolve(f.getNodePublicKey(e)).then(function(e){e&&(P.encryptedDockerRegistryAuth=$u(e,JSON.stringify(p)))})}();return x&&x.then?x.then(T):T()}):(q.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;return Promise.resolve(i.getEndpoints(e)).then(function(s){return Promise.resolve(i.getServiceEndpoints(e,s)).then(function(o){var a=i.getEndpointURL(o,"computeStreamableLogs")?i.getEndpointURL(o,"computeStreamableLogs").urlPath:null;return a?Promise.resolve(i.getSignedCommandParams(e,t,E.COMPUTE_GET_STREAMABLE_LOGS,r,s,o)).then(function(e){var s=e.consumerAddress,o=e.nonce,u=e.signature;function d(e){var t,n;if(null!=(t=c)&&t.ok||200===(null==(n=c)?void 0:n.status))return c.body;var r=q.error,i=c.statusText,s=c.status;return Promise.resolve(c.json()).then(function(e){return r.call(q,"computeStreamableLogs failed: ",s,i,e),null})}var c,l="?jobId="+n;s&&(l+="&consumerAddress="+s),u&&(l+="&signature="+u),o&&(l+="&nonce="+o);var p=zu(function(){var e=i.getAuthorization(t);return Promise.resolve(y(a+l,{method:"GET",headers:F({"Content-Type":"application/json"},e?{Authorization:e}:{}),signal:r})).then(function(e){c=e})},function(e){throw q.error("computeStreamableLogs failed:"),q.error(e),new Error("HTTP request failed calling Provider")});return p&&p.then?p.then(d):d()}):(q.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;return Promise.resolve(s.getEndpoints(t)).then(function(o){return Promise.resolve(s.getServiceEndpoints(t,o)).then(function(a){var u=s.getEndpointURL(a,"computeStop")?s.getEndpointURL(a,"computeStop").urlPath:null;return Promise.resolve(s.getSignedCommandParams(t,n,E.COMPUTE_STOP,i,o,a)).then(function(t){var o=t.consumerAddress,a=t.nonce,d=t.signature;function c(e){var t;function n(e){return t?e:Promise.resolve(p.json()).then(function(e){throw q.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;o&&l.set("consumerAddress",o),a&&l.set("nonce",a),d&&l.set("signature",d),l.set("jobId",e),r&&l.set("agreementId",r);var p,h=l.toString();if(!h)return null;var f=zu(function(){var e=s.getAuthorization(n);return Promise.resolve(y(u+"?"+h,{method:"PUT",headers:F({"Content-Type":"application/json"},e?{Authorization:e}:{}),signal:i})).then(function(e){p=e})},function(e){throw q.error("Compute stop failed:"),q.error(e),new Error("HTTP request failed calling Provider")});return f&&f.then?f.then(c):c()})})})}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{var s=this;return Promise.resolve(FT(t)).then(function(o){return Promise.resolve(s.getEndpoints(e)).then(function(a){return Promise.resolve(s.getServiceEndpoints(e,a)).then(function(e){function a(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 q.error("Get compute status failed:",u.status,u.statusText,e),new Error(JSON.stringify(e))})}q.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="+o;if(c+=r&&"&agreementId="+r||"",c+=n&&"&jobId="+n||"",!d)return null;var l=zu(function(){var e=s.getAuthorization(t);return Promise.resolve(y(d+c,{method:"GET",headers:F({"Content-Type":"application/json"},e?{Authorization:e}:{}),signal:i})).then(function(e){u=e})},function(e){throw q.error("Get compute status failed"),q.error(e),new Error(e)});return l&&l.then?l.then(a):a()})})})}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(o){return Promise.resolve(i.getServiceEndpoints(e,o)).then(function(a){var u=i.getEndpointURL(a,"computeResult")?i.getEndpointURL(a,"computeResult").urlPath:null;return Promise.resolve(i.getSignedCommandParams(e,t,E.COMPUTE_GET_RESULT,void 0,o,a)).then(function(e){var t=e.nonce,i=e.signature;if(!u)return null;var o=u;return o+="?consumerAddress="+e.consumerAddress,o+="&jobId="+n,o+="&index="+r.toString(),s||(o+="&nonce="+t,o+="&signature="+i),o})})})}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(y(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(o){var a=r.getEndpointURL(o,"generateAuthToken").urlPath||null;return Promise.resolve(r.getNonce(t,i,n,s,o)).then(function(t){var r=(t+1).toString();return Promise.resolve(MT(e,r,E.CREATE_AUTH_TOKEN)).then(function(e){return zu(function(){return Promise.resolve(y(a,{method:"POST",body:JSON.stringify({address:i,signature:e,nonce:r}),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 q.error("Generate auth token failed:"),q.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(o){return Promise.resolve(i.getServiceEndpoints(n,o)).then(function(a){var u=i.getEndpointURL(a,"invalidateAuthToken").urlPath||null;return Promise.resolve(i.getNonce(n,s,r,o,a)).then(function(n){var i=(n+1).toString();return Promise.resolve(nt(e,s+i)).then(function(e){return zu(function(){return Promise.resolve(y(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 q.error("Generate auth token failed:"),q.error(e),new Error("HTTP request failed calling Provider")})})})})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){try{return Promise.resolve(zu(function(){return Promise.resolve(y(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 q.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 q.error("PolicyServerPassthrough failed: ",s.status,s.statusText,e),q.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,o=r.getEndpointURL(e,"PolicyServerPassthrough")?r.getEndpointURL(e,"PolicyServerPassthrough").urlPath:null;if(!o)return null;var a=zu(function(){return Promise.resolve(y(o,{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 q.error("PolicyServerPassthrough failed: "),q.error(e),new Error("PolicyServerPassthrough failed: "+e.message+".")});return a&&a.then?a.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 q.error("initializePSVerification failed: ",s.status,s.statusText,e),q.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,o=r.getEndpointURL(e,"initializePSVerification")?r.getEndpointURL(e,"initializePSVerification").urlPath:null;if(!o)return null;var a=zu(function(){return Promise.resolve(y(o,{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 q.error("initializePSVerification failed: "),q.error(e),new Error("initializePSVerification failed: "+e.message+".")});return a&&a.then?a.then(i):i()})})}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,o,a,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(d.getSignedCommandParams(e,t,E.GET_LOGS,u,c,l)).then(function(e){var c=e.consumerAddress,l=e.nonce,h=e.signature;function f(e){var t;return null!=(t=m)&&t.ok?m.body:Promise.resolve(m.json()).then(function(e){throw q.error("Download node logs failed: ",m.status,m.statusText,e),new Error(JSON.stringify(e))})}var m,b=p+"?startTime="+n+"&endTime="+r;i&&(b+="&maxLogs="+i),s&&(b+="&moduleName="+s),o&&(b+="&level="+o),a&&(b+="&page="+a);var g=zu(function(){var e=d.getAuthorization(t);return Promise.resolve(y(b,{method:"POST",body:JSON.stringify({signature:h,nonce:l,address:c}),headers:F({"Content-Type":"application/json"},e?{Authorization:e}:{}),signal:u})).then(function(e){m=e})},function(e){throw q.error("Download node logs failed:"),q.error(e),new Error("HTTP request failed calling Provider")});return g&&g.then?g.then(f):f()}):(q.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 q.debug("Not input string:"),q.debug(e),new Error("["+n+"] Expected string, input type: "+typeof e);var r=e.match(t);return r?{valid:!0,output:r[1]}:(q.warn("["+n+"] Input transformation failed."),{valid:!1,output:e})},t.resolveDdo=function(e,t,n){try{return Promise.resolve(y(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(i.getSignedCommandParams(e,n,E.VALIDATE_DDO,r)).then(function(s){var o=s.consumerAddress,a=s.nonce,u=s.signature,d=i.getAuthorization(n);return Promise.resolve(y(e+"/api/aquarius/assets/ddo/validate",{method:"POST",body:JSON.stringify({ddo:t,publisherAddress:o,nonce:a,signature:u}),headers:F({"Content-Type":"application/json"},d?{Authorization:d}:{}),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(y(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 o=i.resolvePersistentStorageRoute(e,s,["persistentStorageCreateBucket"],"/api/services/persistentStorage/buckets");return Promise.resolve(i.getSignedCommandParams(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(y(o,{method:"POST",headers:s,body:JSON.stringify(F({},e,{accessLists:null!=(i=n.accessLists)?i:[],label:n.label})),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 o=i.resolvePersistentStorageRoute(e,s,["persistentStorageGetBuckets"],"/api/services/persistentStorage/buckets");return Promise.resolve(i.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_GET_BUCKETS,r)).then(function(e){var i={};"string"==typeof t&&(i.Authorization=t);var s=new URLSearchParams(F({},e,{owner:n}));return Promise.resolve(y(o+"?"+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 o=i.resolvePersistentStorageRoute(e,s,["persistentStorageListFiles"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files");return Promise.resolve(i.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(e){var n={};"string"==typeof t&&(n.Authorization=t);var i=new URLSearchParams(F({},e));return Promise.resolve(y(o+"?"+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(o){return Promise.resolve(s.getServiceEndpoints(e,o)).then(function(o){var a=s.resolvePersistentStorageRoute(e,o,["persistentStorageGetFileObject"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r)+"/object");return Promise.resolve(s.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(e){var n=new URLSearchParams(F({},e)),r={};return"string"==typeof t&&(r.Authorization=t),Promise.resolve(y(a+"?"+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 o=this;return Promise.resolve(o.getEndpoints(e)).then(function(a){return Promise.resolve(o.getServiceEndpoints(e,a)).then(function(a){var u=o.resolvePersistentStorageRoute(e,a,["persistentStorageUploadFile"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r));return Promise.resolve(o.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(e){function n(e){var n=o.getAuthorization(t);return Promise.resolve(y(u+"?"+a.toString(),{method:"POST",body:r,headers:F({"Content-Type":"application/octet-stream"},n?{Authorization: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,a=new URLSearchParams(F({},e)),d=function(){if("undefined"==typeof window)return Promise.resolve(import("stream")).then(function(e){var t=e.Readable,n=new TextEncoder,s=N(/*#__PURE__*/L().mark(function e(){var t,r,s,o,a,u,d;return L().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=!1,r=!1,e.prev=2,o=C(i);case 4:return e.next=6,D(o.next());case 6:if(!(t=!(a=e.sent).done)){e.next=25;break}if(!((u=a.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==o.return){e.next=36;break}return e.next=36,D(o.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(o){return Promise.resolve(s.getServiceEndpoints(e,o)).then(function(o){var a=s.resolvePersistentStorageRoute(e,o,["persistentStorageDeleteFile"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n)+"/files/"+encodeURIComponent(r));return Promise.resolve(s.getSignedCommandParams(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(F({},e));return Promise.resolve(y(a+"?"+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)}},t.updatePersistentStorageBucket=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getEndpoints(e)).then(function(o){return Promise.resolve(s.getServiceEndpoints(e,o)).then(function(o){var a=s.resolvePersistentStorageRoute(e,o,["persistentStorageUpdateBucket"],"/api/services/persistentStorage/buckets/"+encodeURIComponent(n));return Promise.resolve(s.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_UPDATE_BUCKET,i)).then(function(e){var n={"Content-Type":"application/json"};"string"==typeof t&&(n.Authorization=t);var s=new URLSearchParams(F({},e));return Promise.resolve(y(a+"?"+s.toString(),{method:"PATCH",headers:n,body:JSON.stringify({label: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)}},e}();async function Gu(e){if(null===e.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new dt("Private network is enforced, but no protector was provided");return e}const Ku=1e3,Wu=60*Ku,Hu=60*Wu,Qu=24*Hu,Yu=7*Qu,Ju=365.25*Qu,Zu=Ju/12;var Xu=function(e,t){if("string"==typeof e)return ed(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?nd(e):td(e)}(e,t);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(e)}`)};function ed(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*Ju;case"months":case"month":case"mo":return i*Zu;case"weeks":case"week":case"w":return i*Yu;case"days":case"day":case"d":return i*Qu;case"hours":case"hour":case"hrs":case"hr":case"h":return i*Hu;case"minutes":case"minute":case"mins":case"min":case"m":return i*Wu;case"seconds":case"second":case"secs":case"sec":case"s":return i*Ku;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 td(e){let t=Math.abs(e);return t>=Ju?`${Math.round(e/Ju)}y`:t>=Zu?`${Math.round(e/Zu)}mo`:t>=Yu?`${Math.round(e/Yu)}w`:t>=Qu?`${Math.round(e/Qu)}d`:t>=Hu?`${Math.round(e/Hu)}h`:t>=Wu?`${Math.round(e/Wu)}m`:t>=Ku?`${Math.round(e/Ku)}s`:`${e}ms`}function nd(e){let t=Math.abs(e);return t>=Ju?rd(e,t,Ju,"year"):t>=Zu?rd(e,t,Zu,"month"):t>=Yu?rd(e,t,Yu,"week"):t>=Qu?rd(e,t,Qu,"day"):t>=Hu?rd(e,t,Hu,"hour"):t>=Wu?rd(e,t,Wu,"minute"):t>=Ku?rd(e,t,Ku,"second"):`${e} ms`}function rd(e,t,n,r){let i=t>=1.5*n;return`${Math.round(e/n)} ${r}${i?"s":""}`}const id=function(){try{return localStorage}catch(e){}}(),sd=console.debug??console.log??(()=>{});var od=function(e){function t(e,r){let i,s,o,a=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 o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";o++;const s=t.formatters[i];return"function"==typeof s&&(r=s.call(n,e[o]),e.splice(o,1),o--),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!==a?a:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{a=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=Xu,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 ":" ")+"+"+Xu(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?id?.setItem("debug",e):id?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=id?.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:id,log:sd});function ad(e,t=""){const n=ld(e.message),r=ld(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 ud(e,t=""){if(function(e){return e instanceof AggregateError||"AggregateError"===e?.name&&Array.isArray(e.errors)}(e)){let n=ad(e,t);return n+=e.errors.length>0?`\n${t=`${t} `}${e.errors.map(e=>`${ud(e,`${t}`)}`).join(`\n${t}`)}`:`\n${t}[Error list was empty]`,n.trim()}return ad(e,t)}function dd(e){return{forComponent:t=>cd(t,e)}}function cd(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 od.enabled(`${e}:trace`)&&null!=od.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(n=od(`${e}:trace`,t)),Object.assign(od(e,t),{error:od(`${e}:error`,t),trace:n,newScope:n=>cd(`${e}:${n}`,t)})}function ld(e){if(null!=e&&0!==(e=e.trim()).length)return e}function pd(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 hd(e){return nu(Bn(on.decode(`z${e}`)))}od.formatters.b=e=>null==e?"undefined":on.baseEncode(e),od.formatters.t=e=>null==e?"undefined":dn.baseEncode(e),od.formatters.m=e=>null==e?"undefined":pr.baseEncode(e),od.formatters.p=e=>null==e?"undefined":e.toString(),od.formatters.c=e=>null==e?"undefined":e.toString(),od.formatters.k=e=>null==e?"undefined":e.toString(),od.formatters.a=e=>null==e?"undefined":e.toString(),od.formatters.e=e=>null==e?"undefined":ud(e);class fd{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 pd(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 pd(this.map.values(),e=>e.key)}values(){return pd(this.map.values(),e=>e.value)}get size(){return this.map.size}}class md{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 pd(this.set.entries(),e=>{const t=hd(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{const n=hd(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return pd(this.set.values(),e=>hd(e))}intersection(e){const t=new md;for(const n of e)this.has(n)&&t.add(n);return t}difference(e){const t=new md;for(const n of this)e.has(n)||t.add(n);return t}union(e){const t=new md;for(const n of e)t.add(n);for(const e of this)t.add(e);return t}}const yd={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},bd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},gd=new globalThis.TextEncoder,vd={hash:e=>Number(function(e,{size:t=32,utf8Buffer:n}={}){if(!yd[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=yd[t];let i=bd[t],s=e;for(;s.length>0;){const e=gd.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=gd.encode(e)}return function(e,t){const n=yd[t];let r=bd[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}`),Ir(t,"base16")}(vd.hash(e,t))};class wd{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=Jn(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&&Yn(this.fp,e.fp)}}function Td(e,t){return Math.floor(Math.random()*(t-e))+e}class Pd{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof wd))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof wd))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 wd))throw new TypeError("Invalid Fingerprint");const t=Td(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof wd))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex(t=>e.equals(t));return t>-1&&(this.contents[t]=null,!0)}}class xd{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??vd,this.seed=e.seed??Td(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=Ir(e));const t=new wd(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 Pd(this.bucketSize)),null==this.buckets[r]&&(this.buckets[r]=new Pd(this.bucketSize)),this.buckets[n].add(t)||this.buckets[r].add(t))return this.count++,!0;const i=[n,r];let s=i[Td(0,i.length-1)];null==this.buckets[s]&&(this.buckets[s]=new Pd(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 Pd(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=Ir(e));const t=new wd(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=Ir(e));const t=new wd(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 Ed={1:.5,2:.84,4:.95,8:.98};function Sd(e,t=.001){const n=function(e=.001){return e>.002?2:e>1e-5?4:8}(t);return{filterSize:Math.round(e/Ed[n]),bucketSize:n,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*n)),64)}}class Ad{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??vd,this.seed=e.seed??Td(0,Math.pow(2,10)),this.filterSeries=[new xd({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=Ir(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 xd({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=Ir(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=Ir(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 kd(e,t=.001,n){return new Ad({...Sd(e,t),...n??{}})}function Cd(e){const t=e.getComponents(),n={};let r=0;return"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?null:("tls"===t[r]?.name&&"sni"===t[r+1]?.name&&(n.sni=t[r+1].value,r+=2),n)}function Id(e){const t=Cd(e);if(null==t)throw new dt(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}const Dd=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Md(e,t){16===t.length&&4===e.length&&function(e){let t=0;for(const n of e)if(!(t<0)){if(t>11)break;if(255!==n)return!1;t++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t){let n=0;for(const r of e)if(!(n<0)){if(n>11)break;if(r!==t[n])return!1;n++}return!0}(e,Dd)&&(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 Fd(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 Rd{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=du(t);if(null==i&&(r=16,i=cu(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 o=Fd(s,8*r);return{network:Md(i,o),mask:o}}(e));else{const n=lu(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=lu(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=Fd(r,8*n.length);this.network=Md(n,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=lu(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 Ld(e){try{const n=Id(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 _d(e){return null!==Cd(e)}var Nd="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Od(e){var t={exports:{}};return e(t,t.exports),t.exports}var Bd=Od(function(e,t){(function(){var e,n,r,i,s,o,a,u;u=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,r,i,s,o;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=(o=n(e))[0],e=e.substring(o[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"),o=r("a"),s=r("A"),n=function(e){var t,n,a,u,d;for(u=0,t=10,n="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,n="7")),d=a;a<e.length;){if("0"<=e[a]&&e[a]<=n)u=u*t+(r(e[a])-i)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")u=u*t+(10+r(e[a])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;u=u*t+(10+r(e[a])-s)>>>0}}if(u>4294967295)throw new Error("too large");a++}if(a===d)throw new Error("empty octet");return[u,a]},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=a(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=(a(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):(a(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=a(this.first),n=a(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=a,t.long2ip=u,t.Netmask=e}).call(Nd)});const Ud=["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 Bd.Netmask(e));function jd(e){for(const t of Ud)if(t.contains(e))return!0;return!1}function qd(e){return pu(e)?jd(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 jd(`${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 jd(t[t.length-1])}(e):hu(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 $d(e){try{const t=Id(e);switch(t.type){case"ip4":case"ip6":return qd(t.host)??!1;default:return"localhost"===t.host}}catch{return!1}}function zd(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class Vd{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 Gd{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Vd(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 Vd(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 Kd extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Wd(e={}){return function(e,t){let n,r,i,s=(t=t??{}).onEnd,o=new Gd,a=zd();const u=e=>null!=r?r(e):(o.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=>(o=new Gd,null!=r?r({error:e}):(o.push({error:e}),n)))(e):u({done:!0}));if(n={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?i?{done:!0}:await new Promise((t,i)=>{r=s=>{r=null,o.push(s);try{t(e(o))}catch(e){i(e)}return n}}):e(o)}finally{o.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=zd()})}},return:()=>(o=new Gd,c(),{done:!0}),throw:e=>(c(e),{done:!0}),push:d,end:c,get readableLength(){return o.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let n,r;null!=t&&(n=new Promise((e,n)=>{r=()=>{n(new Kd)},t.addEventListener("abort",r)}));try{await Promise.race([a.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 Hd extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,Hd)}}const Qd=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Yd(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 o=[t].flat(),a=[],{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)}a.push(t),n.count===a.length&&(r(),i(a))},l=(...e)=>{r(),s(n.rejectionMultiArgs?e:e[0])};r=()=>{for(const e of o)d(e,c);for(const e of n.rejectionEvents)o.includes(e)||d(e,l)};for(const e of o)u(e,c);for(const e of n.rejectionEvents)o.includes(e)||u(e,l);n.signal&&n.signal.addEventListener("abort",()=>{l(n.signal.reason)},{once:!0}),n.resolveImmediately&&i(a)});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:o}=t;let a,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(o?.aborted)return void d(Qd(o));if(o&&(u=()=>{d(Qd(o))},o.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new Hd;a=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&&o&&o.removeEventListener("abort",u)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=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 Jd(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 Zd 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 Xd extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class ec extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class tc extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"}class nc extends Error{static name="StreamClosedError";name="StreamClosedError"}function rc(e){return e.reason}async function ic(e,t,n){if(null==t)return e;const r=n?.translateError??rc;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 sc{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=zd(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ot)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class oc{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 ot),this.cleanup())}async join(e){const t=new sc(e);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 ic(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{this.recipients.forEach(t=>{t.onProgress?.(e)})}}),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 ac extends Wt{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=Jd(this.emitEmpty.bind(this),1),this.emitIdle=Jd(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 Xd;const n=new oc(e,t);this.enqueue(n),this.safeDispatchEvent("add");const r=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});return this.tryToStartAnother(),r}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ot)}),this.clear()}async onEmpty(e){0!==this.size&&await Yd(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Yd(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Yd(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=Wd({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()},o=()=>{n(new ot("Queue aborted"))};this.addEventListener("completed",r),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",o),n()}}}const uc=4*Math.pow(2,20);class dc extends Wt{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??uc,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new rr,this.writeBuffer=new rr,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,queueMicrotask(()=>{this.processSendQueue()})),this.onDrainPromise?.resolve()}),this.addEventListener("close",e=>{this.onDrainPromise?.reject(e.error??new nc)})}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()),ic(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if("readable"!==this.readStatus&&"paused"!==this.readStatus)return;const e=Wd(),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 mt(`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 _t(e))}}pause(){if("closed"===this.readStatus||"closing"===this.readStatus)throw new mt("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 mt("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 mt(`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 mt(`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 ft;this.dispatchEvent(new Nt(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 Lt))}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 rr(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 Rt(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 yt(`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 yt(`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 cc extends dc{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 Yd(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 Yd(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}}class lc extends Wt{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 ic(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 ht;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 tc(`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 pc extends dc{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 Yd(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 Yd(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 hc(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 fc{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 mc{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new fc(t),this.failure=new fc(t),this.next=new fc(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=hc([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 yc{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=zd(),this.haveNext=zd()}[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=zd(),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=zd(),await ic(this.readNext.promise,t?.signal,t)}}function bc(...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 yc;(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 gc(e,...t){if(null==e)throw new Error("Empty pipeline");if(Pc(e)){const t=e;e=()=>t.source}else if(Tc(e)||wc(e)){const t=e;e=()=>t}const n=[e,...t];if(n.length>1&&Pc(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++)Pc(n[e])&&(n[e]=xc(n[e]));return vc(...n)}const vc=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},wc=e=>null!=e?.[Symbol.asyncIterator],Tc=e=>null!=e?.[Symbol.iterator],Pc=e=>null!=e&&null!=e.sink&&null!=e.source,xc=e=>t=>{const n=e.sink(t);if(null!=n?.then){const t=Wd({objectMode:!0});let r;n.then(()=>{t.end()},e=>{t.end(e)});const i=e.source;if(wc(i))r=async function*(){yield*i,t.end()};else{if(!Tc(i))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");r=function*(){yield*i,t.end()}}return bc(t,r())}return e.source};class Ec extends Error{static name="UnwrappedError";name="UnwrappedError"}class Sc extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Ac extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class kc extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Cc(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 Ic(e,t){const n=t?.maxBufferSize??4194304,r=new rr;let i,s=!1;if(o=e,null==o?.addEventListener||null==o?.removeEventListener||null==o?.send||null==o?.push||null==o?.log)throw new dt("Argument should be a Stream or a Multiaddr");var o;const a=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",a);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 Ec("Stream was unwrapped");if(Cc(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 ec(`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 ic(i.promise,t?.signal),Cc(e)){if(0===r.byteLength&&null==t?.bytes)return null;break}i=Promise.withResolvers()}const o=t?.bytes??r.byteLength;if(r.byteLength<o){if(Cc(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,o),new ec(`Unexpected EOF - stream closed while reading ${r.byteLength}/${o} bytes`);return c.read(t)}const a=r.sublist(0,o);return r.consume(o),a},async write(t,n){if(!0===s)throw new Ec("Stream was unwrapped");e.send(t)||await Yd(e,"drain",{signal:n?.signal,rejectionEvents:["close"]})},unwrap:()=>(s||(s=!0,e.removeEventListener("message",a),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 Dc(e,t={}){const n=Ic(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=Mo(t.maxDataLength));const r=t?.lengthDecoder??_o,i=t?.lengthEncoder??Lo;return{async read(i){let s=-1;const o=new rr;for(;;){const e=await n.read({...i,bytes:1});if(null==e)break;o.append(e);try{s=r(o)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new Sc("Invalid message length");if(null!=t?.maxLengthLength&&o.byteLength>t.maxLengthLength)throw new kc(`Message length length too long - ${o.byteLength} > ${t.maxLengthLength}`);if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new Ac(`Message length too long - ${s} > ${t.maxDataLength}`);const a=await n.read({...i,bytes:s});if(null==a)throw e.log.error("tried to read %d bytes but the stream closed",s),new ec(`Unexpected EOF - tried to read ${s} bytes but the stream closed`);if(a.byteLength!==s)throw e.log.error("read %d/%d bytes before the stream closed",a.byteLength,s),new ec(`Unexpected EOF - read ${a.byteLength}/${s} bytes before the stream closed`);return a},async write(e,t){await n.write(new rr(i(e.byteLength),e),t)},async writeV(e,t){const r=new rr(...e.flatMap(e=>[i(e.byteLength),e]));await n.write(r,t)},unwrap:()=>n.unwrap()}}function Mc(e,t){const n=Dc(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 Fc{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new rr,this.maxBufferSize=e.maxBufferSize??4194304,this.maxDataLength=e.maxDataLength??4194304,this.lengthDecoder=e.lengthDecoder??_o,this.encodingLength=e.encodingLength??Mo}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new dt(`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 Sc("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 Rc=4194304;class Lc extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}function _c(e,t){if(e.byteLength>t)throw new Lc("Message length too long")}const Nc=e=>{const t=Mo(e),n=Zn(t);return Lo(e,n),Nc.bytes=t,n};function Oc(e,t){const n=(t=t??{}).lengthEncoder??Nc,r=t?.maxDataLength??Rc;function*i(e){_c(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 Bc;Nc.bytes=0,Oc.single=(e,t)=>{const n=(t=t??{}).lengthEncoder??Nc;return _c(e,t?.maxDataLength??Rc),new rr(n(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Bc||(Bc={}));class Uc extends ac{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}class jc extends ac{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}class qc{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 $c}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 Zd("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 $c{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 zc(e,t,n){let r,i,s=!1;function o(){const a={signal:i.signal};let u;null!=n?.timeout&&(u=hc([i.signal,AbortSignal.timeout(n.timeout)]),a.signal=u),s=!0,Promise.resolve().then(async()=>{await e(a)}).catch(()=>{}).finally(()=>{null!=u&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),s=!1,i.signal.aborted||(r=setTimeout(o,t))})}const a=Jd(o,n?.debounce??100);let u=!1;return{setInterval:e=>{t!==e&&(t=e,null!=r&&(clearTimeout(r),r=setTimeout(o,t)))},setTimeout:e=>{n??={},n.timeout=e},run:()=>{s||(clearTimeout(r),a())},start:()=>{u||(u=!0,i=new AbortController,!0===n?.runImmediately?queueMicrotask(()=>{o()}):r=setTimeout(o,t))},stop:()=>{clearTimeout(r),i?.abort(),u=!1}}}class Vc 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 Gc(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Vc({name:t,metrics:n}):new Map,r}class Kc{filter;constructor(e,t){this.filter=kd(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 Wc(e,t=.001){return new Kc(e,t)}class Hc extends fd{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 Qc(e){const{name:t,metrics:n}=e;let r;return r=null!=n?new Hc({name:t,metrics:n}):new fd,r}const Yc=new Float32Array([-0]),Jc=new Uint8Array(Yc.buffer);function Zc(e,t,n){Yc[0]=e,t[n]=Jc[0],t[n+1]=Jc[1],t[n+2]=Jc[2],t[n+3]=Jc[3]}const Xc=new Float64Array([-0]),el=new Uint8Array(Xc.buffer);function tl(e,t,n){Xc[0]=e,t[n]=el[0],t[n+1]=el[1],t[n+2]=el[2],t[n+3]=el[3],t[n+4]=el[4],t[n+5]=el[5],t[n+6]=el[6],t[n+7]=el[7]}const nl=BigInt(Number.MAX_SAFE_INTEGER),rl=BigInt(Number.MIN_SAFE_INTEGER);class il{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 sl;if(e<nl&&e>rl)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>ol&&(r=0n,++n>ol&&(n=0n))),new il(Number(r),Number(n))}static fromNumber(e){if(0===e)return sl;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 il(n,r)}static from(e){return"number"==typeof e?il.fromNumber(e):"bigint"==typeof e?il.fromBigInt(e):"string"==typeof e?il.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new il(e.low>>>0,e.high>>>0):sl}}const sl=new il(0,0);sl.toBigInt=function(){return 0n},sl.zzEncode=sl.zzDecode=function(){return this},sl.length=function(){return 1};const ol=4294967296n;function al(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 ul(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function dl(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class cl{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,ul(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 ul(this,4);return dl(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ul(this,4);return 0|dl(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw ul(this,4);const e=(Jc[0]=(t=this.buf)[n=this.pos],Jc[1]=t[n+1],Jc[2]=t[n+2],Jc[3]=t[n+3],Yc[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ul(this,4);const e=(el[0]=(t=this.buf)[n=this.pos],el[1]=t[n+1],el[2]=t[n+2],el[3]=t[n+3],el[4]=t[n+4],el[5]=t[n+5],el[6]=t[n+6],el[7]=t[n+7],Xc[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 ul(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,o=0;for(;t<n;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(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[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw ul(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw ul(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 il(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw ul(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 ul(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 ul(this,8);const e=dl(this.buf,this.pos+=4),t=dl(this.buf,this.pos+=4);return new il(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=Ro(this.buf,this.pos);return this.pos+=Mo(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 ll(e){return new cl(e instanceof Uint8Array?e:e.subarray())}function pl(e,t,n){const r=ll(e);return t.decode(r,void 0,n)}class hl{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function fl(){}class ml{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const yl=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Zn(r);n+r>e&&(t=Zn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class bl{len;head;tail;states;constructor(){this.len=0,this.head=new hl(fl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new hl(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new wl((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Tl,10,il.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=il.fromBigInt(e);return this._push(Tl,t.length(),t)}uint64Number(e){return this._push(Fo,Mo(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=il.fromBigInt(e).zzEncode();return this._push(Tl,t.length(),t)}sint64Number(e){const t=il.fromNumber(e).zzEncode();return this._push(Tl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(gl,1,e?1:0)}fixed32(e){return this._push(Pl,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=il.fromBigInt(e);return this._push(Pl,4,t.lo)._push(Pl,4,t.hi)}fixed64Number(e){const t=il.fromNumber(e);return this._push(Pl,4,t.lo)._push(Pl,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(Zc,4,e)}double(e){return this._push(tl,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(gl,1,0):this.uint32(t)._push(xl,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(al,t,e):this._push(gl,1,0)}fork(){return this.states=new ml(this),this.head=this.tail=new hl(fl,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 hl(fl,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?Zn(n):yl(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function gl(e,t,n){t[n]=255&e}function vl(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class wl extends hl{next;constructor(e,t){super(vl,e,t),this.next=void 0}}function Tl(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 Pl(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 xl(e,t,n){t.set(e,n)}function El(e,t,n){t.set(e,n)}function Sl(e,t,n){e.length<40?al(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(Ir(e),n)}function Al(e,t){const n=new bl;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*kl(e,t,n){const r=ll(e);yield*t.stream(r,void 0,"$",n)}function Cl(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&&(bl.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(El,t,e),this},bl.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Sl,t,e),this});class Il extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var Dl;!function(e){let t;e.codec=()=>(null==t&&(t=Cl((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:Jn(0),payloadType:Jn(0),payload:Jn(0),signature:Jn(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 Al(t,e.codec())},e.decode=function(t,n){return pl(t,e.codec(),n)},e.stream=function(t,n){return kl(t,e.codec(),n)}}(Dl||(Dl={}));class Ml extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class Fl{static createFromProtobuf=e=>{const t=Dl.decode(e),n=Ka(t.publicKey);return new Fl({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(),o=Rl(r,i,s),a=await t.sign(o.subarray(),n);return new Fl({publicKey:t.publicKey,payloadType:i,payload:s,signature:a})};static openAndCertify=async(e,t,n)=>{const r=Fl.createFromProtobuf(e);if(!await r.validate(t,n))throw new Ml("Envelope signature is not valid for the given domain");return r};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:n,payload:r,signature:i}=e;this.publicKey=t,this.payloadType=n,this.payload=r,this.signature=i}marshal(){return null==this.marshaled&&(this.marshaled=Dl.encode({publicKey:Wa(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Yn(this.marshal(),e.marshal())}async validate(e,t){const n=Rl(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}}const Rl=(e,t,n)=>{const r=Ir(e),i=Lo(r.byteLength),s=Lo(t.length),o=Lo(n.length);return new rr(i,r,s,t,o,n)},Ll=Uint8Array.from([3,1]);var _l;!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=Cl((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:Jn(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 Al(t,e.codec())},e.decode=function(t,n){return pl(t,e.codec(),n)},e.stream=function(t,n){return kl(t,e.codec(),n)}}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=Cl((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:Jn(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 Il('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},o=null==n?t.len:t.pos+n;for(;t.pos<o;){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 Il('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 Al(t,e.codec())},e.decode=function(t,n){return pl(t,e.codec(),n)},e.stream=function(t,n){return kl(t,e.codec(),n)}}(_l||(_l={}));class Nl{static createFromProtobuf=e=>{const t=_l.decode(e),n=nu(Bn(t.peerId)),r=(t.addresses??[]).map(e=>Uu(e.multiaddr));return new Nl({peerId:n,multiaddrs:r,seqNumber:t.seq})};static DOMAIN="libp2p-peer-record";static CODEC=Ll;peerId;multiaddrs;seqNumber;domain=Nl.DOMAIN;codec=Nl.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=_l.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 Nl&&!!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 Ol(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 Bl extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}}async function Ul(e,t,n,r){const i=new Bl(r?.errorMessage);null!=r?.errorCode&&(i.code=r.errorCode);const s=r?.errorEvent??"error";return!0===n?.aborted?Promise.reject(i):new Promise((o,a)=>{function u(){ql(n,"abort",l),ql(e,t,d),ql(e,s,c)}const d=e=>{try{if(!1===r?.filter?.(e))return}catch(e){return u(),void a(e)}u(),o(e)},c=e=>{u(),e instanceof Error?a(e):a(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(),a(i)};jl(n,"abort",l),jl(e,t,d),jl(e,s,c)})}function jl(e,t,n){null!=e&&($l(e)?e.addEventListener(t,n):e.addListener(t,n))}function ql(e,t,n){null!=e&&($l(e)?e.removeEventListener(t,n):e.removeListener(t,n))}function $l(e){return"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener}class zl extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Vl{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 Bl)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Gl{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 Bl),this.cleanup())}async join(e={}){const t=new Vl(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 ic(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 Kl(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 Wl extends Wt{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=Kl(this.emitEmpty.bind(this),1),this.emitIdle=Kl(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 zl;const n=new Gl(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 Bl)}),this.clear()}async onEmpty(e){0!==this.size&&await Ul(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ul(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await Ul(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=Wd({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()},o=()=>{n(new Bl("Queue aborted"))};this.addEventListener("success",r),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("success",r),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",o),n()}}}const Hl="lock:worker:request-read",Ql="lock:worker:abort-read-request",Yl="lock:worker:release-read",Jl="lock:master:grant-read",Zl="lock:master:error-read",Xl="lock:worker:request-write",ep="lock:worker:abort-write-request",tp="lock:worker:release-write",np="lock:master:grant-write",rp="lock:master:error-write",ip="lock:worker:finalize",sp="mortice",op={singleProcess:!1},ap=(e,t,n,r,i,s,o,a,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===a&&r.data.identifier===c.identifier&&(t.removeEventListener("message",n),e())};t.addEventListener("message",n)})},onError:e=>{t.postMessage({type:o,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===ip&&e.safeDispatchEvent("finalizeRequest",{detail:{name:c.name}})};class up{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(sp)}readLock(e){return this.sendRequest(Hl,Ql,Jl,Zl,Yl,e)}writeLock(e){return this.sendRequest(Xl,ep,np,rp,tp,e)}finalize(){this.channel.postMessage({type:ip,name:this.name}),this.channel.close()}async sendRequest(e,t,n,r,i,s){s?.signal?.throwIfAborted();const o=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:o,name:this.name}),new Promise((e,a)=>{const u=()=>{this.channel.postMessage({type:t,identifier:o,name:this.name})};s?.signal?.addEventListener("abort",u,{once:!0});const d=t=>{if(t.data?.identifier===o&&(t.data?.type===n&&(this.channel.removeEventListener("message",d),s?.signal?.removeEventListener("abort",u),e(()=>{this.channel.postMessage({type:i,identifier:o,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),a(e)}};this.channel.addEventListener("message",d)})}}const dp=new Map;let cp;function lp(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}function pp(e){if(null==cp&&(cp=(e=>{if(e=Object.assign({},op,e),Boolean(globalThis.document)||e.singleProcess){const e=new BroadcastChannel(sp),t=new Wt;return e.addEventListener("message",ap(t,e,"requestReadLock","abortReadLockRequest",Hl,Ql,Zl,Yl,Jl)),e.addEventListener("message",ap(t,e,"requestWriteLock","abortWriteLockRequest",Xl,ep,rp,tp,np)),t}return new up(e.name)})(e),!lp(cp))){const e=cp;e.addEventListener("requestReadLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=dp.get(n);if(null==i)return;const s=new AbortController,o=e=>{e.detail.name===n&&e.detail.identifier===r&&s.abort()};e.addEventListener("abortReadLockRequest",o),i.readLock({signal:s.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortReadLockRequest",o)})}),e.addEventListener("requestWriteLock",t=>{const n=t.detail.name,r=t.detail.identifier,i=dp.get(n);if(null==i)return;const s=new AbortController,o=e=>{e.detail.name===n&&e.detail.identifier===r&&s.abort()};e.addEventListener("abortWriteLockRequest",o),i.writeLock({signal:s.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",o)})}),e.addEventListener("finalizeRequest",e=>{const t=dp.get(e.detail.name);null!=t&&t.finalize()})}return cp}async function hp(e,t){let n,r;const i=new Promise((e,t)=>{n=e,r=t}),s=()=>{r(new Bl)};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 fp={name:"lock",concurrency:Infinity,singleProcess:!1,autoFinalize:!1};function mp(e){const t=Object.assign({},fp,e);return((e,t)=>{let n=dp.get(e);if(null!=n)return n;const r=pp(t);if(lp(r))return n=r,dp.set(e,n),n;const i=new Wl({concurrency:1});let s;return n={async readLock(e){if(null!=s)return hp(s,e);s=new Wl({concurrency:t.concurrency,autoStart:!1});const n=s,r=hp(s,e);return i.add(async()=>{n.start(),await n.onIdle().then(()=>{s===n&&(s=null)})}),r},writeLock:async e=>(s=null,hp(i,e)),finalize:()=>{dp.delete(e)},queue:i},dp.set(e,n),!0===t.autoFinalize&&i.addEventListener("idle",()=>{n.finalize()},{once:!0}),n})(t.name,t)}const yp=new Float32Array([-0]),bp=new Uint8Array(yp.buffer);function gp(e,t,n){yp[0]=e,t[n]=bp[0],t[n+1]=bp[1],t[n+2]=bp[2],t[n+3]=bp[3]}const vp=new Float64Array([-0]),wp=new Uint8Array(vp.buffer);function Tp(e,t,n){vp[0]=e,t[n]=wp[0],t[n+1]=wp[1],t[n+2]=wp[2],t[n+3]=wp[3],t[n+4]=wp[4],t[n+5]=wp[5],t[n+6]=wp[6],t[n+7]=wp[7]}const Pp=BigInt(Number.MAX_SAFE_INTEGER),xp=BigInt(Number.MIN_SAFE_INTEGER);class Ep{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 Sp;if(e<Pp&&e>xp)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>Ap&&(r=0n,++n>Ap&&(n=0n))),new Ep(Number(r),Number(n))}static fromNumber(e){if(0===e)return Sp;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 Ep(n,r)}static from(e){return"number"==typeof e?Ep.fromNumber(e):"bigint"==typeof e?Ep.fromBigInt(e):"string"==typeof e?Ep.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Ep(e.low>>>0,e.high>>>0):Sp}}const Sp=new Ep(0,0);Sp.toBigInt=function(){return 0n},Sp.zzEncode=Sp.zzDecode=function(){return this},Sp.length=function(){return 1};const Ap=4294967296n;function kp(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 Cp(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Ip(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Dp{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,Cp(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 Cp(this,4);return Ip(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Cp(this,4);return 0|Ip(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Cp(this,4);const e=(bp[0]=(t=this.buf)[n=this.pos],bp[1]=t[n+1],bp[2]=t[n+2],bp[3]=t[n+3],yp[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Cp(this,4);const e=(wp[0]=(t=this.buf)[n=this.pos],wp[1]=t[n+1],wp[2]=t[n+2],wp[3]=t[n+3],wp[4]=t[n+4],wp[5]=t[n+5],wp[6]=t[n+6],wp[7]=t[n+7],vp[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 Cp(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,o=0;for(;t<n;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(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[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Cp(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Cp(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 Ep(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Cp(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 Cp(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 Cp(this,8);const e=Ip(this.buf,this.pos+=4),t=Ip(this.buf,this.pos+=4);return new Ep(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=Ro(this.buf,this.pos);return this.pos+=Mo(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Mp(e,t,n){const r=function(e){return new Dp(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(r,void 0,n)}class Fp{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Rp(){}class Lp{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const _p=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Zn(r);n+r>e&&(t=Zn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class Np{len;head;tail;states;constructor(){this.len=0,this.head=new Fp(Rp,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Fp(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Up((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(jp,10,Ep.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=Ep.fromBigInt(e);return this._push(jp,t.length(),t)}uint64Number(e){return this._push(Fo,Mo(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=Ep.fromBigInt(e).zzEncode();return this._push(jp,t.length(),t)}sint64Number(e){const t=Ep.fromNumber(e).zzEncode();return this._push(jp,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Op,1,e?1:0)}fixed32(e){return this._push(qp,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=Ep.fromBigInt(e);return this._push(qp,4,t.lo)._push(qp,4,t.hi)}fixed64Number(e){const t=Ep.fromNumber(e);return this._push(qp,4,t.lo)._push(qp,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(gp,4,e)}double(e){return this._push(Tp,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Op,1,0):this.uint32(t)._push($p,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(kp,t,e):this._push(Op,1,0)}fork(){return this.states=new Lp(this),this.head=this.tail=new Fp(Rp,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 Fp(Rp,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?Zn(n):_p(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function Op(e,t,n){t[n]=255&e}function Bp(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class Up extends Fp{next;constructor(e,t){super(Bp,e,t),this.next=void 0}}function jp(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 qp(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 $p(e,t,n){t.set(e,n)}function zp(e,t,n){t.set(e,n)}function Vp(e,t,n){e.length<40?kp(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(Ir(e),n)}function Gp(e,t){const n=new Np;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var Kp,Wp,Hp,Qp,Yp;function Jp(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function Zp(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Jp("enum",Kp.VARINT,function(e,n){const r=t(e);n.int32(r)},function(e){return t(e.int32())})}function Xp(e,t){return Jp("message",Kp.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Np.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(zp,t,e),this},Np.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Vp,t,e),this}),(Yp=Kp||(Kp={}))[Yp.VARINT=0]="VARINT",Yp[Yp.BIT64=1]="BIT64",Yp[Yp.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",Yp[Yp.START_GROUP=3]="START_GROUP",Yp[Yp.END_GROUP=4]="END_GROUP",Yp[Yp.BIT32=5]="BIT32";class eh extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class th extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function nh(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let n;return"RSA"===e.type&&(n=e.toMultihash()),tu(Ka(t.publicKey,n))}function rh(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:nh(e,t),addresses:t.addresses.filter(({observed:e})=>null!=e&&e>Date.now()-n).map(({multiaddr:e,isCertified:t})=>({multiaddr:Uu(e),isCertified:t??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:r}}function ih(e,t){return null==e&&null==t||null!=e&&null!=t&&Yn(e,t)}function sh(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 oh(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=Xp((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:Jn(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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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),Qp.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=Qp.codec().decode(e,e.uint32(),{limits:n.limits?.value});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Xp((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.addresses)for(const e of t.addresses)n.uint32(10),Hp.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 eh('Decode error - map field "addresses" had too many elements');i.addresses.push(Hp.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 eh('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 th('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 th('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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Wp||(Wp={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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:Jn(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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Hp||(Hp={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Qp||(Qp={}));const ah="/",uh=(new TextEncoder).encode(ah),dh=uh[0];class ch{_buf;constructor(e,t){if("string"==typeof e)this._buf=Ir(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]!==dh)throw new Error("Invalid key")}toString(e="utf8"){return Dr(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new ch(e.join(ah))}static random(){return new ch(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new ch(e):"function"==typeof e.uint8Array?new ch(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=uh),this._buf[0]!==dh){const e=new Uint8Array(this._buf.byteLength+1);e.fill(dh,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===dh;)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 ch.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(ah).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 ch(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(ah)||(e+=ah),e+=this.type(),new ch(e)}parent(){const e=this.list();return new ch(1===e.length?ah:e.slice(0,-1).join(ah))}child(e){return this.toString()===ah?e:e.toString()===ah?this:new ch(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 ch.withNamespaces([...this.namespaces(),...(t=e.map(e=>e.namespaces()),[].concat(...t))]);var t}}const lh="/peers/";function ph(e){if(!Ut(e)||null==e.type)throw new dt("Invalid PeerId");const t=e.toCID().toString();return new ch(`${lh}${t}`)}async function hh(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=Uu(r.multiaddr)),!Bu(r.multiaddr))throw new dt("Multiaddr was invalid");if(!await t(e,r.multiaddr,i))continue;const n=r.isCertified??!1,o=r.multiaddr.toString(),a=s.get(o);null!=a?r.isCertified=a.isCertified||n:s.set(o,{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===mu)?.value;return e.equals(r)&&(n=n.decapsulate(Uu(`/p2p/${e}`))),{isCertified:t,multiaddr:n.bytes}})}async function fh(e,t,n,r){if(null==t)throw new dt("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new dt("publicKey bytes do not match peer id publicKey bytes");const i=r.existingPeer?.peer;if(null!=i&&!e.equals(i.id))throw new dt("peer id did not match existing peer id");let s,o=i?.addresses??[],a=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||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(a=new Set(t.protocols)),null!=t.metadata&&(u=mh(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:yh})),null!=t.tags&&(d=mh(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:bh,map:gh})),null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)),"merge"===n){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(a=new Set([...a,...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=mh([...u.entries()],{validate:yh})}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=mh([...n.entries()],{validate:bh,map:gh})}null!=t.peerRecordEnvelope&&(c=t.peerRecordEnvelope)}null!=i?.id.publicKey?s=Wa(i.id.publicKey):null!=t.publicKey?s=Wa(t.publicKey):null!=e.publicKey&&(s=Wa(e.publicKey));const l={addresses:await hh(e,r.addressFilter??(async()=>!0),o,0,r),protocols:[...a.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=>Yn(e.multiaddr,e.multiaddr))?.observed??Date.now()}),"RSA"!==e.type&&delete l.publicKey,l}function mh(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 yh(e,t){if("string"!=typeof e)throw new dt("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new dt("Metadata value must be a Uint8Array")}function bh(e,t){if("string"!=typeof e)throw new dt("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new dt("Tag value must be an integer");if(t.value<0||t.value>100)throw new dt("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new dt("Tag ttl must be an integer");if(t.ttl<0)throw new dt("Tag ttl must be between greater than 0")}}function gh(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 vh(e){const t=e.toString().split("/")[2];return ru(zn.parse(t,dn))}function wh(e,t,n){return function(e,t,n){return rh(e,Wp.decode(t),n)}(vh(e),t,n)}class Th{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=Qc({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:mp({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(ph(e),t)}async load(e,t){const n=ph(e),r=await this.datastore.get(n,t),i=Wp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new bt;return rh(e,i,this.peerId.equals(e)?Infinity:this.maxAddressAge)}async save(e,t,n){const r=await this.#s(e,n),i=await fh(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#o(e,i,r)}async patch(e,t,n){const r=await this.#s(e,n),i=await fh(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:r});return this.#o(e,i,r)}async merge(e,t,n){const r=await this.#s(e,n),i=await fh(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:r});return this.#o(e,i,r)}async*all(e){for await(const{key:t,value:n}of this.datastore.query(function(e,t){return{prefix:lh,filters:(e.filters??[]).map(e=>({key:n,value:r})=>e(wh(n,r,t))),orders:(e.orders??[]).map(e=>(n,r)=>e(wh(n.key,n.value,t),wh(r.key,r.value,t)))}}(e??{},this.maxAddressAge),e)){const r=vh(t);if(r.equals(this.peerId))continue;const i=Wp.decode(n);this.#i(r,i)?await this.datastore.delete(t,e):yield rh(r,i,this.peerId.equals(r)?Infinity:this.maxAddressAge)}}async#s(e,t){try{const n=ph(e),r=await this.datastore.get(n,t),i=Wp.decode(r);if(this.#i(e,i))throw await this.datastore.delete(n,t),new bt;return{peerPB:i,peer:rh(e,i,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#o(e,t,n,r){t.updated=Date.now();const i=Wp.encode(t);return await this.datastore.put(ph(e),i,r),{peer:rh(e,t,this.maxAddressAge),previous:n?.peer,updated:null==n||(s=t,o=n.peerPB,!(sh(s.addresses,o.addresses,(e,t)=>e.isCertified===t.isCertified&&!!Yn(e.multiaddr,t.multiaddr))&&sh(s.protocols,o.protocols,(e,t)=>e===t)&&ih(s.publicKey,o.publicKey)&&ih(s.peerRecordEnvelope,o.peerRecordEnvelope)&&oh(s.metadata,o.metadata,(e,t)=>Yn(e,t))&&oh(s.tags,o.tags,(e,t)=>e.value===t.value&&e.expiry===t.expiry)))};var s,o}#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 Ph{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 Th(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 Ol(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.#a(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.#a(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.#a(e,r),r.peer}finally{r?.()}}async consumePeerRecord(e,t,n){const r=Ut(t)?t:Ut(t?.expectedPeer)?t.expectedPeer:void 0,i=Ut(t)||void 0===t?n:t,s=await Fl.openAndCertify(e,Nl.DOMAIN,i),o=ru(s.publicKey.toCID());if(!1===r?.equals(o))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",r,o),!1;const a=Nl.createFromProtobuf(s.payload);let u;try{u=await this.get(o,i)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u?.peerRecordEnvelope){const e=Fl.createFromProtobuf(u.peerRecordEnvelope),t=Nl.createFromProtobuf(e.payload);if(t.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:e,addresses:a.multiaddrs.map(e=>({isCertified:!0,multiaddr:e}))},i),!0}#a(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}class xh extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=xh.name;code=xh.code;constructor(e="Not Found"){super(e)}}function Eh(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);}function Sh(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 Ah(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=Sh(e),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const o=t(i,n++);if("function"==typeof o.then)return async function*(){await o&&(yield i);for(const e of r)await t(e,n++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield i);for(const e of r)a(e,n++)&&(yield e)}()}function kh(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const n=await Ol(e);yield*n.sort(t)}():function*(){const n=Ol(e);yield*n.sort(t)}()}function Ch(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 Ih{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 Eh(this.putMany(e,n)),e=[],await Eh(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=Ah(n,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>Ah(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>kh(e,t),n)),null!=e.offset){let t=0;const r=e.offset;n=Ah(n,()=>t++>=r)}return null!=e.limit&&(n=Ch(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;n=Ah(n,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((e,t)=>Ah(e,t),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((e,t)=>kh(e,t),n)),null!=e.offset){const t=e.offset;let r=0;n=Ah(n,()=>r++>=t)}return null!=e.limit&&(n=Ch(n,e.limit)),n}}class Dh extends Ih{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 xh;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 ch(e),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(const e of this.data.keys())yield new ch(e),t?.signal?.throwIfAborted()}}const Mh=e=>({match:t=>{const n=t[0];return null!=n&&n.code===e&&null==n.value&&t.slice(1)}}),Fh=(e,t)=>({match:n=>{const r=n[0];return r?.code===e&&null!=r.value&&(null==t||r.value===t)&&n.slice(1)}}),Rh=e=>({match:t=>{const n=e.match(t);return!1===n?t:n}}),Lh=(...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}}),_h=(...e)=>({match:t=>{for(const n of e){const e=n.match(t);if(!1===e)return!1;t=e}return t}});function Nh(...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 Oh=Nh(Fh(mu)),Bh=Fh(54),Uh=Fh(55),jh=Fh(56),qh=Fh(53),$h=_h(Fh(4),Rh(Fh(43))),zh=_h(Rh(Fh(42)),Fh(fu),Rh(Fh(43))),Vh=Lh($h,zh),Gh=Lh(Vh,qh,Bh,Uh,jh),Kh=Nh(Lh(Vh,_h(Lh(qh,jh,Bh,Uh),Rh(Fh(mu))))),Wh=Nh($h),Hh=Nh(zh),Qh=_h(Gh,Fh(6)),Yh=_h(Gh,Fh(273)),Jh=Nh(_h(Qh,Rh(Fh(mu)))),Zh=_h(Yh,Mh(460),Rh(Fh(mu))),Xh=_h(Yh,Mh(461),Rh(Fh(mu))),ef=Lh(Zh,Xh),tf=Nh(Xh),nf=Lh(Gh,Qh,Yh,Zh,Xh),rf=Lh(_h(nf,Mh(477),Rh(Fh(mu)))),sf=Nh(rf),of=Lh(_h(nf,Mh(478),Rh(Fh(mu))),_h(nf,Mh(yu),Rh(Fh(bu)),Mh(477),Rh(Fh(mu)))),af=Nh(of),uf=_h(Yh,Mh(280),Rh(Fh(gu)),Rh(Fh(gu)),Rh(Fh(mu))),df=Nh(uf),cf=_h(Xh,Mh(465),Rh(Fh(gu)),Rh(Fh(gu)),Rh(Fh(mu))),lf=Nh(cf),pf=Lh(rf,of,_h(Qh,Rh(Fh(mu))),_h(ef,Rh(Fh(mu))),_h(Gh,Rh(Fh(mu))),uf,cf,Fh(mu)),hf=Nh(pf);var ff;const mf=Nh(_h(Rh(pf),Mh(wu),(ff=Mh(vu),{match:e=>!1===ff.match(e)&&e}),Rh(Fh(mu)))),yf=Nh(Lh(_h(pf,Mh(wu),Mh(vu),Rh(Fh(mu))),_h(pf,Mh(vu),Rh(Fh(mu))),_h(Mh(vu),Rh(Fh(mu))))),bf=864e13;class gf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Gc({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=Id(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===qd(t);this.mappings.set(t,{domain:e,verified:n,expires:n?bf-Date.now():0,lastVerified:n?bf-Date.now():void 0})})}remove(e){const t=Id(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(!_d(r))continue;const i=Id(r);for(const[s,o]of this.mappings.entries()){if(i.host!==s)continue;const a=this.maybeAddSNIComponent(r,o.domain);null!=a&&(e.splice(n,1),n--,t.push({multiaddr:a,verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}}return t}maybeAddSNIComponent(e,t){const n=e.getComponents();for(let e=0;e<n.length;e++)if(n[e].code===yu&&n[e+1]?.code!==bu)return n.splice(e+1,0,{name:"sni",code:bu,value:t}),Uu(n)}confirm(e,t){const n=Id(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=Id(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 vf{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Gc({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=Id(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}`,o=this.mappings.get(s)??[],a={internalIp:e,internalPort:t,externalIp:n,externalPort:r,externalFamily:pu(n)?4:6,protocol:i,verified:!1,expires:0};o.push(a),this.mappings.set(s,o)}remove(e){const t=Id(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(!_d(n))continue;const e=Id(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(),o=s.findIndex(e=>4===e.code||e.code===fu),a=s.findIndex(e=>e.name===r);return o>-1&&a>-1?(s[o].value=t,s[o].code=4===n?4:fu,s[a].value=`${i}`,Uu(s)):e}confirm(e,t){if(!_d(e))return!1;const n=Id(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(!_d(e))return!1;const n=Id(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 wf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Gc({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&&($d(e)||function(e){try{const t=Id(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:Uu(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 Tf{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Gc({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if($d(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:!_d(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(!_d(e))return e.toString();const t=Id(e);return`${t.host}-${t.port}-${t.protocol}`}}const Pf=e=>e;function xf(e,t){const n=e.getComponents().findLast(e=>e.code===mu)?.value;return null!=n&&eu(n).equals(t)&&(e=e.decapsulate(Uu(`/p2p/${t.toString()}`))),e}class Ef{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 wf(e,t),this.dnsMappings=new gf(e,t),this.ipMappings=new vf(e,t),this.transportAddresses=new Tf(e,t),this.announceFilter=t.announceFilter??Pf,this.observedAddressFilter=kd(1024),this.addressVerificationTTL=t.addressVerificationTTL??6e5,this.addressVerificationRetry=t.addressVerificationRetry??3e5,this._updatePeerStoreAddresses=Jd(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===mu)?.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=>Uu(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Uu(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Uu(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){const t=Id(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=xf(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=xf(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=xf(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=Uu(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(Uu(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.add(e,t,n,r,i),this.observed.removePrefixed(`/ip${pu(n)?4:6}/${n}/${i}/${r}`)}removePublicAddressMapping(e,t,n,r=t,i="tcp"){this.ipMappings.remove(Uu(`/ip${pu(n)?4:6}/${n}/${i}/${r}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;if(!_d(e))return!1;const t=Id(e);if("ip4"!==t.type||!0===qd(t.host))return!1;const n=this.components.transportManager.getListeners(),r=[e=>sf.exactMatch(e)||af.exactMatch(e),e=>Jh.exactMatch(e),e=>tf.exactMatch(e)];for(const i of r){if(!i(e))continue;const r=n.filter(e=>e.getAddrs().filter(e=>"ip4"===Id(e).type&&i(e)).length>0);if(1!==r.length)continue;const s=r[0].getAddrs().filter(e=>!Ld(e)).pop();if(null==s)continue;const o=Id(s);return null!=o.port&&(this.observed.remove(e),this.ipMappings.add(o.host,o.port,t.host,t.port,t.protocol),!0)}return!1}}var Sf;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(Sf||(Sf={}));class Af extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class kf extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class Cf extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class If extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class Df extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class Mf extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class Ff extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class Rf extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class Lf extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class _f extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class Nf extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Of extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class Bf extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class Uf extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class jf extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class qf extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class $f extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}class zf{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=dd())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>$t(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 Vf=["metrics","connectionProtector","dns"],Gf=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Kf(e){return Array.isArray(e?.[Ht])?e[Ht]:[]}function Wf(e){return Array.isArray(e?.[Qt])?e[Qt]:[]}function Hf(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function Qf(e={}){return null==e.denyDialMultiaddr&&(e.denyDialMultiaddr=e=>!!sf.matches(e)||$d(e)),e}class Yf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Jf(e){if(Ut(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===mu)?.value;t=null==e?void 0:eu(e),n.forEach(e=>{if(!Bu(e))throw new vt("Invalid multiaddr");const n=e.getComponents().findLast(e=>e.code===mu)?.value;if(null==n){if(null!=t)throw new dt("Multiaddrs must all have the same peer id or have no peer id")}else{const e=eu(n);if(!0!==t?.equals(e))throw new dt("Multiaddrs must all have the same peer id or have no peer id")}})}return n=n.filter(e=>!Oh.exactMatch(e)),{peerId:t,multiaddrs:n}}const Zf=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Xf(e){const t=Id(e);let n=t.cidr;if("ip4"!==t.type&&"ip6"!==t.type)throw new dt(`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 dt(`Multiaddr ${e} was not an IPv4 or IPv6 address`)}return new Rd(t.host,n)}function em(e){return!mf.exactMatch(e)}function tm(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=>em(e))?void 0:r}class nm{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(e=>Xf(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 fd;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),o=[];for(const e of i)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some(t=>{if(_d(e.remoteAddr)){const n=Id(e.remoteAddr);return t.contains(n.host)}return!0})||o.push(e),o.length===s)break;await Promise.all(o.map(async e=>{await async function(e,t){const n=e?.streams?.map(e=>e.protocol)??[],r=t?.closableProtocols??Zf;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:o})}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 rm=1e4,im="last-dial-failure",sm="last-dial-success";function om(e,t){const n=Jh.exactMatch(e.multiaddr),r=Jh.exactMatch(t.multiaddr);if(n&&!r)return-1;if(!n&&r)return 1;const i=af.exactMatch(e.multiaddr),s=af.exactMatch(t.multiaddr);if(i&&!s)return-1;if(!i&&s)return 1;const o=sf.exactMatch(e.multiaddr),a=sf.exactMatch(t.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const u=yf.exactMatch(e.multiaddr),d=yf.exactMatch(t.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;const c=df.exactMatch(e.multiaddr),l=df.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const p=lf.exactMatch(e.multiaddr),h=lf.exactMatch(t.multiaddr);return p&&!h?-1:!p&&h?1:0}function am(e,t){const n=Ld(e.multiaddr),r=Ld(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function um(e,t){const n=$d(e.multiaddr),r=$d(t.multiaddr);return n&&!r?1:!n&&r?-1:0}function dm(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function cm(e,t){const n=mf.exactMatch(e.multiaddr),r=mf.exactMatch(t.multiaddr);return n&&!r?1:!n&&r?-1:0}class lm extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"}var pm=Od(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,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new i(r,s||e,o),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],a]:e._events[u].push(a):(e._events[u]=a,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.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},a.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},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,i,s,o){var a=n?n+e:e;if(!this._events[a])return!1;var u,d,c=this._events[a],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,o),!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},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return o(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||o(this,s);else{for(var u=0,d=[],c=a.length;u<c;u++)(a[u].fn!==t||i&&!a[u].once||r&&a[u].context!==r)&&d.push(a[u]);d.length?this._events[s]=1===d.length?d[0]:d:o(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&o(this,t):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}),hm=pm;class fm extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,fm)}}const mm=e=>e.reason??new DOMException("This operation was aborted.","AbortError");class ym{#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 o=r+s;n(e[o],t)<=0?(r=++o,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 bm extends hm{#d;#c;#l=0;#p;#h=!1;#f=!1;#m;#y=0;#b=0;#g;#v;#w;#T=[];#P=0;#u;#x;#E=0;#S;#A;#k=1n;#C=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:ym,strict:!1,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&0===e.interval)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#d=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#c=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#p=e.intervalCap,this.#m=e.interval,this.#w=e.strict,this.#u=new e.queueClass,this.#x=e.queueClass,this.concurrency=e.concurrency,void 0!==e.timeout&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#A=!1===e.autoStart,this.#I()}#D(e){for(;this.#P<this.#T.length;){const t=this.#T[this.#P];if(!(void 0!==t&&e-t>=this.#m))break;this.#P++}(this.#P>100&&this.#P>this.#T.length/2||this.#P===this.#T.length)&&(this.#T=this.#T.slice(this.#P),this.#P=0)}#M(e){this.#w?this.#T.push(e):this.#l++}#F(){this.#w?this.#T.length>this.#P&&this.#T.pop():this.#l>0&&this.#l--}#R(){return this.#T.length-this.#P}get#L(){return!!this.#c||(this.#w?this.#R()<this.#p:this.#l<this.#p)}get#_(){return this.#E<this.#S}#N(){this.#E--,0===this.#E&&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.#P],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.#E: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.#E){if(this.#V(),this.#w&&this.#P>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.#L&&this.#_){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.#E&&this.#g&&this.#z(),this.#l=this.#d?this.#E: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.#k++).toString()},new Promise((n,r)=>{const i=Symbol(`task-${t.id}`);this.#u.enqueue(async()=>{let s;this.#E++,this.#C.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});try{try{t.signal?.throwIfAborted()}catch(e){throw this.#W(),this.#C.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:o}=t;let a,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(o?.aborted)return void d(mm(o));if(o&&(u=()=>{d(mm(o))},o.addEventListener("abort",u,{once:!0})),e.then(t,d),n===Number.POSITIVE_INFINITY)return;const c=new fm;a=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&&o&&o.removeEventListener("abort",u)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}(Promise.resolve(r),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#E} 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 o=await r;n(o),this.emit("completed",o)}catch(e){r(e),this.emit("error",e)}finally{s&&t.signal?.removeEventListener("abort",s),this.#C.delete(i),queueMicrotask(()=>{this.#N()})}},t),this.emit("add"),this.#O()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#A?(this.#A=!1,this.#K(),this):this}pause(){this.#A=!0}clear(){this.#u=new this.#x,this.#z(),this.#H(),this.emit("empty"),0===this.#E&&(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.#E&&0===this.#u.size||await this.#Q("idle")}async onPendingZero(){0!==this.#E&&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.#E}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.#H()}))}#W(){this.#c||(this.#F(),this.#G())}#H(){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.#E===this.#S&&this.#u.size>0||this.isRateLimited&&this.#u.size>0}get runningTasks(){return[...this.#C.values()].map(e=>({...e}))}}function gm(e){const t=[xm.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function vm(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:xm[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:xm[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?Dr(e.data):e.data}))}}function wm(e,t={}){const n=new bm({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),gm(r.types).forEach(e=>{s.append("type",xm[e])}),r.onProgress?.(new Yf("dns:query",t)),i?.("GET %s",`${e}?${s}`);const o=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=vm(await t.json());return r.onProgress?.(new Yf("dns:response",n)),n},{signal:r.signal});if(null==o)throw new Error("No DNS response received");return o}}class Tm{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 vm({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:xm[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 Pm{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=new Tm(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["."]=[wm("https://cloudflare-dns.com/dns-query"),wm("https://dns.google/resolve")])}async query(e,t={}){const n=gm(t.types),r=!1!==t.cached?this.cache.get(e,n):void 0;if(null!=r)return t.onProgress?.(new Yf("dns:cache",r)),r;const i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),o=[];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){o.push(e),t.onProgress?.(new Yf("dns:error",e))}}throw new lm(o,`DNS lookup of ${e} ${n} failed`)}}var xm;!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(xm||(xm={}));const Em=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:[xm.TXT]}),s=e.getComponents().find(e=>"p2p"===e.name)?.value,o=[];for(const e of i.Answer){const t=e.data.replace(/["']/g,"").trim().split("=")[1];null!=t&&(null==s||t.includes(s))&&o.push(Uu(t))}return o}getDNS(e){return null!=e.dns?e.dns:(null==this.dns&&(this.dns=function(e={}){return new Pm(e)}()),this.dns)}};async function Sm(e,t,n){const r=n.depth??0;if(r>(n.maxRecursiveDepth??32))throw new $f("Max recursive depth reached");let i=!1;const s=[];for(const o of Object.values(t))if(o.canResolve(e)){i=!0;const a=await o.resolve(e,n);for(const e of a)s.push(...await Sm(e,t,{...n,depth:r+1}))}return!1===i&&s.push(e),s}const Am={maxParallelDials:50,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Em}};class km{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Am.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Am.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Am.dialTimeout,this.connections=t.connections??new fd,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Am.resolvers,this.shutDownController=new AbortController,this.queue=new jc({concurrency:t.maxParallelDials??Am.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",e=>{e.detail?.error.name!==ot.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}=Jf(e);if(null!=n&&!0!==t.force){const e=tm(n,this.connections.get(n),r);if(null!=e)return this.log("already connected to %a",e.remoteAddr),t.onProgress?.(new Yf("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 Yf("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new kt("Dial queue is full");return this.log("creating dial target for %p",n,r.map(e=>e.toString())),t.onProgress?.(new Yf("dial-queue:add-to-dial-queue")),this.queue.add(async e=>{e.onProgress?.(new Yf("dial-queue:start-dial"));const t=hc([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}},{peerId:n,priority:t.priority??Nm,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,o=0,a=0;const u=[];for(this.log("starting dial to %p",n);s||r.size>0;){a++,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===a?"starting":"continuing",n,d.map(e=>e.multiaddr.toString())),e?.onProgress?.(new Yf("dial-queue:calculated-addresses",d));for(const r of d){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,e.peerId),new kt("Peer had more than maxPeerAddrsToDial");o++;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:{[sm]:Ir(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:{[im]:Ir(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 St(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:Uu(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new kt("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new Rf("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 Sm(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===mu)?.value;return null==e||null==n||e.equals(n)}),o=new Map;for(const e of s){const t=e.multiaddr.toString(),n=o.get(t);null==n?o.set(t,e):n.isCertified=n.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new Nf("The dial request has no valid addresses");const u=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||u.push(e);const d=null==this.addressSorter?u.sort(om).sort(dm).sort(cm).sort(um).sort(am):u.sort(this.addressSorter);if(0===d.length)throw new Rf("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=>!mf.matches(e.multiaddr))}catch{}return!1}}const Cm=Object.prototype.toString,Im=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 Dm(e,t,{min:n=0,allowInfinity:r=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be ≥ ${n}.`)}}class Mm extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}function Fm(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Rm({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){const s=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(s instanceof Mm)throw s.originalError;const o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,a=i.maxRetryTime??Number.POSITIVE_INFINITY,u=Object.freeze({error:s,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(u),Fm(r,a)<=0)throw s;const d=await i.shouldConsumeRetry(u),c=Fm(r,a);if(c<=0||o<=0)throw s;if(s instanceof TypeError&&!function(e){const t=e&&(e=>"[object Error]"===Cm.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(")"))||Im.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 Lm{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 Uc({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);_m(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,Dm("factor",t.factor,{min:0,allowInfinity:!1}),Dm("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),Dm("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),Dm("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 Rm({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(qt)&&(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=>_m(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 _m(e){for(const t of e.tags.keys())if(t.startsWith(qt))return!0;return!1}const Nm=50;class Om{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 dt("Connection Manager maxConnections must be greater than 0");this.connections=new fd,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=>Xf(Uu(e))),this.deny=(t.deny??[]).map(e=>Xf(Uu(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new qc({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new nm({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(e=>Uu(e))}),this.dialQueue=new km(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Em},connections:this.connections}),this.reconnectQueue=new Lm({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 zt(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 Vt(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const n of t)e.push(Promise.all([Yd(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 dt("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 At("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:n,multiaddrs:r}=Jf(e);if(this.peerId.equals(n))throw new gt("Can not dial self");if(null!=n&&!0!==t.force){this.log("dial %p",n);const e=tm(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 Yf("dial-queue:already-connected")),e}const i=await this.dialQueue.dial(e,{...t,priority:t.priority??Nm});if("open"!==i.status)throw new lt("Remote closed connection during opening");let s=this.connections.get(i.remotePeer);null==s&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(const e of s)if(e.id===i.id&&(o=!0),!0!==t.force&&e.id!==i.id&&e.remoteAddr.equals(i.remoteAddr))return i.abort(new vt("Duplicate multiaddr connection")),e;return o||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([Yd(e,"close",t),e.close(t)])}catch(t){e.abort(t)}}))}acceptIncomingConnection(e){if(this.deny.some(t=>{if(_d(e.remoteAddr)){const n=Id(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(_d(e.remoteAddr)){const n=Id(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(_d(e.remoteAddr)){const t=Id(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=>Uu(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Bm{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 mc({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ht]=["@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=Ic(r);t=Date.now(),await Promise.all([i.write(wa(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 Um{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:Dr(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:Dr(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 Cf("No content routers available");const n=this,r=new md;for await(const i of bc(...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 Cf("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 Cf("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 At;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 At;return Promise.any(this.routers.filter(e=>e.get instanceof Function).map(async n=>n.get(e,t)))}}const jm=globalThis.CustomEvent??Event;async function*qm(e,t={}){let n=t.concurrency??Infinity;n<1&&(n=Infinity);const r=t.ordered??!1,i=new EventTarget,s=[];let o,a=zd(),u=zd(),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,a.resolve(),e.err;yield e.value,a.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,a.resolve(),t.err;yield t.value,a.resolve()}}for(i.addEventListener("task-complete",()=>{u.resolve()}),Promise.resolve().then(async()=>{try{for await(const t of e){if(s.length===n&&(a=zd(),await a.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 jm("task-complete"))},t=>{e.done=!0,e.err=t,i.dispatchEvent(new jm("task-complete"))})}d=!0,i.dispatchEvent(new jm("task-complete"))}catch(e){o=e,i.dispatchEvent(new jm("task-complete"))}});;){if(l()||(u=zd(),await u.promise),null!=o)throw o;if(r?yield*p():yield*h(),null!=o)throw o;if(d&&0===s.length)break}}class $m{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:Dr(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 If("No peer routers available");if(e.toString()===this.peerId.toString())throw new Df("Should not try to find self");const n=this,r=bc(...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 bt}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new If("No peer routers available");const n=this,r=kd(1024);for await(const i of qm(async function*(){const r=bc(...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 zm extends Wt{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=hc([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=zd();const e=await Yd(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=hc([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=wa(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 ic(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 Vm{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=Gc({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Mf(`No handler registered for protocol ${e}`);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&!0!==n?.force)throw new Ff(`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 dt("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 Gm{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Gc({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Gc({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Kt.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new dt("Transport must have a valid tag");if(this.transports.has(t))throw new dt(`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 qf(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Yf("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 At("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 Lf)});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 o=this.listeners.get(r)??[];null==o&&(o=[],this.listeners.set(r,o)),o.push(s),s.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:s})}),s.addEventListener("close",()=>{const e=o.findIndex(e=>e===s);o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:s})}),Wh.matches(e)?t.ipv4.attempts++:Hh.matches(e)&&t.ipv6.attempts++,n.push(s.listen(e).then(()=>{t.errors.delete(e.toString()),Wh.matches(e)&&t.ipv4.success++,Hh.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!==Kt.NO_FATAL)throw new _f(`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 Km="/multistream/1.0.0",Wm=Ir("\n");async function Hm(e,t){const n=(await e.read(t)).subarray();if(0===n.byteLength||n[n.length-1]!==Wm[0])throw new xt("Missing newline");return Dr(n).trimEnd()}async function Qm(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=Dc(e,{...n,maxDataLength:1024});for(let e=0;e<t.length;e++){const s=t[e];let o;if(0===e){r.trace('write ["%s", "%s"]',Km,s);const e=Ir(`${Km}\n`),t=Ir(`${s}\n`);if(await i.writeV([e,t],n),r.trace("reading multistream-select header"),o=await Hm(i,n),r.trace('read "%s"',o),o!==Km){r.error("did not read multistream-select header from response");break}}else r.trace('write "%s"',s),await i.write(Ir(`${s}\n`),n);if(r.trace("reading protocol response"),o=await Hm(i,n),r.trace('read "%s"',o),o===s)return r.trace('selected "%s" after negotiation',o),i.unwrap(),s}throw new Pt(`Protocol selection failed - could not negotiate ${t}`)}async function Ym(e,t,n={}){t=Array.isArray(t)?t:[t];const r=e.log.newScope("mss:handle"),i=Dc(e,{...n,maxDataLength:1024,maxLengthLength:2});for(;;){r.trace("reading incoming string");const e=await Hm(i,n);if(r.trace('read "%s"',e),e!==Km){if(t.includes(e))return r.trace('respond with "%s" for "%s"',e,e),await i.write(Ir(`${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(Ir("na\n"),n),r('responded with "na" for "%s"',e);else{const s=new rr(...t.map(e=>Oc.single(Ir(`${e}\n`))),Ir("\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"',Km,e),await i.write(Ir(`${Km}\n`),n),r.trace('responded with "%s" for "%s"',Km,e)}}class Jm extends Wt{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??rm,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??rm,this.closeTimeout=t.closeTimeout??1e3,this.direct=em(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),null==this.remoteAddr.getComponents().find(e=>e.code===mu)&&(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 Lt(e.local,e.error))})}[Symbol.toStringTag]="Connection";[it]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(null==this.muxer)throw new Uf("Connection is not multiplexed");if("open"!==this.muxer.status)throw new lt(`The connection muxer is "${this.muxer.status}" and not "open"`);if("open"!==this.maConn.status)throw new lt(`The connection is "${this.status}" and not "open"`);if(null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new It("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 Qm(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=Zm(n.protocol,"outbound",this);if(i>r){const e=new Mt(`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 Ym(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(Zm(t.protocol,"inbound",this)>e)throw new Dt(`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 It("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 Zm(e,t,n){let r=0;return n.streams.forEach(n=>{n.direction===t&&n.protocol===e&&r++}),r}class Xm{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Gc({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(e=>{this.connectionEncrypters.set(e.protocol,e)}),this.streamMuxers=Gc({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??rm,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??rm,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 Of(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){return hc([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 Bf("Connection denied");await ic(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===mu)?.value;let r;null!=n&&(r=eu(n),await ic(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,o,a=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),a=await r.protect(a,n))}try{if(function(e){return!0===e.skipEncryption}(n)){if(null==n.remotePeer)throw new vt(`${t} connection that skipped encryption must have a peer id`);o="native",r=n.remotePeer}else{const s=e.remoteAddr.getComponents().findLast(e=>e.code===mu)?.value;let u;null!=s&&(u=eu(s)),n?.onProgress?.(new Yf(`upgrader:encrypt-${t}-connection`)),({connection:a,remotePeer:r,protocol:o,streamMuxer:i}=await("inbound"===t?this._encryptInbound(a,{...n,remotePeer:u}):this._encryptOutbound(a,{...n,remotePeer:u})))}if(r.equals(this.components.peerId)){const t=new gt("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 Yf(`upgrader:multiplex-${t}-connection`)),i=await("inbound"===t?this._multiplexInbound(a,this.streamMuxers,n):this._multiplexOutbound(a,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(a)),await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",r,e);const d=this._createConnection({id:u,cryptoProtocol:o,direction:t,maConn:e,stream:a,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 Jm(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 Ym(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new jf(`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 jf(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 Qm(e,n,t),i=this.connectionEncrypters.get(r);if(null==i)throw new jf(`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 jf(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 Qm(e,r,n),s=t.get(i);if(null==s)throw new Uf(`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 Uf(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 Ym(e,r,n),s=t.get(i);if(null==s)throw new Uf(`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 ey="3.1.6",ty="js-libp2p";class ny extends Wt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Wt,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??dd(),this.log=this.logger.forComponent("libp2p"),this.services={};const r=e.nodeInfo?.name??ty,i=e.nodeInfo?.version??ey,s=this.components=function(e={}){const t=new zf(e),n=new Proxy(t,{get(e,n,r){if("string"==typeof n&&!Gf.includes(n)){const e=t.components[n];if(null==e&&!Vf.includes(n))throw new Af(`${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??(o=r,a=i,`${o??ty}/${a??ey} browser/${globalThis.navigator.userAgent}`)},logger:this.logger,events:t,datastore:e.datastore??new Dh,connectionGater:Qf(e.connectionGater),dns:e.dns});var o,a;null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new Ph(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 Xm(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 Gm(this.components,e.transportManager)),this.configureComponent("connectionManager",new Om(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Bm(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Vm(this.components)),this.configureComponent("addressManager",new Ef(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 $m(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 Um(this.components,{routers:d})),this.configureComponent("randomWalk",new zm(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[st]&&(this.log("registering service %s for content routing",t),d.push(n[st])),null!=n[jt]&&(this.log("registering service %s for peer routing",t),u.push(n[jt])),null!=n[Ot]&&(this.log("registering service %s for peer discovery",t),n[Ot].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 Kf(n))t[e]=!0;for(const n of Object.values(e.components))for(const e of Wf(n))if(!0!==t[e])throw new kf(`Service "${Hf(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 md;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 dt("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new dt("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={}){Bu(e)&&(e=eu(e.getComponents().findLast(e=>e.code===mu)?.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=Xn([Ir("/pk/"),e.toMultihash().bytes]),r=Ka(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 ry=65535,iy=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function sy(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function oy(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ay(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 uy(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 dy(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function cy(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const ly=/* @__PURE__ */(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])(),py=(e,t)=>{function n(n,...r){if(ay(n,void 0,"key"),!ly)throw new Error("Non little-endian hardware is not yet supported");void 0!==e.nonceLength&&ay(r[0],e.varSizeNonce?void 0:e.nonceLength,"nonce");const i=e.tagLength;i&&void 0!==r[1]&&ay(r[1],void 0,"AAD");const s=t(n,...r),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");ay(t,void 0,"output")}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,ay(e),o(s.encrypt.length,t),s.encrypt(e,t)},decrypt(e,t){if(ay(e),i&&e.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return o(s.decrypt.length,t),s.decrypt(e,t)}}}return Object.assign(n,e),n};function hy(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 fy(e){return Uint8Array.from(e)}const my=e=>Uint8Array.from(e.split(""),e=>e.charCodeAt(0)),yy=my("expand 16-byte k"),by=my("expand 32-byte k"),gy=dy(yy),vy=dy(by);function wy(e,t){return e<<t|e>>>32-t}function Ty(e){return e.byteOffset%4==0}const Py=2**32-1,xy=Uint32Array.of();function Ey(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=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 oy(i),oy(o),sy(s),sy(n),(t,a,u,d,c=0)=>{ay(t,void 0,"key"),ay(a,void 0,"nonce"),ay(u,void 0,"data");const l=u.length;if(void 0===d&&(d=new Uint8Array(l)),ay(d,void 0,"output"),oy(c),c<0||c>=Py)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=fy(t)),f=vy;else{if(16!==m||!n)throw ay(t,32,"arx key"),new Error("invalid key size");h=new Uint8Array(32),h.set(t),h.set(t,16),f=gy,p.push(h)}Ty(a)||p.push(a=fy(a));const y=dy(h);if(r){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");r(f,y,dy(a.subarray(0,16)),y),a=a.subarray(16)}const b=16-i;if(b!==a.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(12!==b){const e=new Uint8Array(12);e.set(a,s?0:12-a.length),p.push(a=e)}const g=dy(a);return function(e,t,n,r,i,s,o,a){const u=i.length,d=new Uint8Array(64),c=dy(d),l=Ty(i)&&Ty(s),p=l?dy(i):xy,h=l?dy(s):xy;for(let f=0;f<u;o++){if(e(t,n,r,c,o,a),o>=Py)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,o),cy(...p),d}}function Sy(e,t){return 255&e[t++]|(255&e[t++])<<8}class Ay{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=Sy(e=fy(ay(e,32,"key")),0),n=Sy(e,2),r=Sy(e,4),i=Sy(e,6),s=Sy(e,8),o=Sy(e,10),a=Sy(e,12),u=Sy(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|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|u<<8),this.r[9]=u>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Sy(e,16+2*t)}process(e,t,n=!1){const r=n?0:2048,{h:i,r:s}=this,o=s[0],a=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=Sy(e,t+0),b=Sy(e,t+2),g=Sy(e,t+4),v=Sy(e,t+6),w=Sy(e,t+8),T=Sy(e,t+10),P=Sy(e,t+12),x=Sy(e,t+14);let E=i[0]+(8191&y),S=i[1]+(8191&(y>>>13|b<<3)),A=i[2]+(8191&(b>>>10|g<<6)),k=i[3]+(8191&(g>>>7|v<<9)),C=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|P<<5)),F=i[8]+(8191&(P>>>8|x<<8)),R=i[9]+(x>>>5|r),L=0,_=L+E*o+S*(5*m)+A*(5*f)+k*(5*h)+C*(5*p);L=_>>>13,_&=8191,_+=I*(5*l)+D*(5*c)+M*(5*d)+F*(5*u)+R*(5*a),L+=_>>>13,_&=8191;let N=L+E*a+S*o+A*(5*m)+k*(5*f)+C*(5*h);L=N>>>13,N&=8191,N+=I*(5*p)+D*(5*l)+M*(5*c)+F*(5*d)+R*(5*u),L+=N>>>13,N&=8191;let O=L+E*u+S*a+A*o+k*(5*m)+C*(5*f);L=O>>>13,O&=8191,O+=I*(5*h)+D*(5*p)+M*(5*l)+F*(5*c)+R*(5*d),L+=O>>>13,O&=8191;let B=L+E*d+S*u+A*a+k*o+C*(5*m);L=B>>>13,B&=8191,B+=I*(5*f)+D*(5*h)+M*(5*p)+F*(5*l)+R*(5*c),L+=B>>>13,B&=8191;let U=L+E*c+S*d+A*u+k*a+C*o;L=U>>>13,U&=8191,U+=I*(5*m)+D*(5*f)+M*(5*h)+F*(5*p)+R*(5*l),L+=U>>>13,U&=8191;let j=L+E*l+S*c+A*d+k*u+C*a;L=j>>>13,j&=8191,j+=I*o+D*(5*m)+M*(5*f)+F*(5*h)+R*(5*p),L+=j>>>13,j&=8191;let q=L+E*p+S*l+A*c+k*d+C*u;L=q>>>13,q&=8191,q+=I*a+D*o+M*(5*m)+F*(5*f)+R*(5*h),L+=q>>>13,q&=8191;let $=L+E*h+S*p+A*l+k*c+C*d;L=$>>>13,$&=8191,$+=I*u+D*a+M*o+F*(5*m)+R*(5*f),L+=$>>>13,$&=8191;let z=L+E*f+S*h+A*p+k*l+C*c;L=z>>>13,z&=8191,z+=I*d+D*u+M*a+F*o+R*(5*m),L+=z>>>13,z&=8191;let V=L+E*m+S*f+A*h+k*p+C*l;L=V>>>13,V&=8191,V+=I*c+D*d+M*u+F*a+R*o,L+=V>>>13,V&=8191,L=(L<<2)+L|0,L=L+_|0,_=8191&L,L>>>=13,N+=L,i[0]=_,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;cy(n)}update(e){uy(this),ay(e),e=fy(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(){cy(this.h,this.r,this.buffer,this.pad)}digestInto(e){uy(this),function(e,t){ay(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 ky=/** @__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 Ay(e)))();function Cy(e,t,n,r,i,s=20){let o=e[0],a=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],P=o,x=a,E=u,S=d,A=c,k=l,C=p,I=h,D=f,M=m,F=y,R=b,L=g,_=v,N=w,O=T;for(let e=0;e<s;e+=2)P=P+A|0,L=wy(L^P,16),D=D+L|0,A=wy(A^D,12),P=P+A|0,L=wy(L^P,8),D=D+L|0,A=wy(A^D,7),x=x+k|0,_=wy(_^x,16),M=M+_|0,k=wy(k^M,12),x=x+k|0,_=wy(_^x,8),M=M+_|0,k=wy(k^M,7),E=E+C|0,N=wy(N^E,16),F=F+N|0,C=wy(C^F,12),E=E+C|0,N=wy(N^E,8),F=F+N|0,C=wy(C^F,7),S=S+I|0,O=wy(O^S,16),R=R+O|0,I=wy(I^R,12),S=S+I|0,O=wy(O^S,8),R=R+O|0,I=wy(I^R,7),P=P+k|0,O=wy(O^P,16),F=F+O|0,k=wy(k^F,12),P=P+k|0,O=wy(O^P,8),F=F+O|0,k=wy(k^F,7),x=x+C|0,L=wy(L^x,16),R=R+L|0,C=wy(C^R,12),x=x+C|0,L=wy(L^x,8),R=R+L|0,C=wy(C^R,7),E=E+I|0,_=wy(_^E,16),D=D+_|0,I=wy(I^D,12),E=E+I|0,_=wy(_^E,8),D=D+_|0,I=wy(I^D,7),S=S+A|0,N=wy(N^S,16),M=M+N|0,A=wy(A^M,12),S=S+A|0,N=wy(N^S,8),M=M+N|0,A=wy(A^M,7);let B=0;r[B++]=o+P|0,r[B++]=a+x|0,r[B++]=u+E|0,r[B++]=d+S|0,r[B++]=c+A|0,r[B++]=l+k|0,r[B++]=p+C|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+L|0,r[B++]=v+_|0,r[B++]=w+N|0,r[B++]=T+O|0}const Iy=/* @__PURE__ */Ey(Cy,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Dy=/* @__PURE__ */new Uint8Array(16),My=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(Dy.subarray(n))},Fy=/* @__PURE__ */new Uint8Array(32);function Ry(e,t,n,r,i){void 0!==i&&ay(i,void 0,"AAD");const s=e(t,n,Fy),o=function(e,t,n){sy(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),a=ky.create(s);i&&My(a,i),My(a,r),a.update(o);const u=a.digest();return cy(s,o),u}const Ly=/* @__PURE__ */py({blockSize:64,nonceLength:12,tagLength:16},(_y=Iy,(e,t,n)=>({encrypt(r,i){const s=r.length;(i=hy(s+16,i,!1)).set(r);const o=i.subarray(0,-16);_y(e,t,o,o,1);const a=Ry(_y,e,t,o,n);return i.set(a,s),cy(a),i},decrypt(r,i){i=hy(r.length-16,i,!1);const s=r.subarray(0,-16),o=r.subarray(-16),a=Ry(_y,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}(o,a))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),_y(e,t,i,i,1),cy(a),i}})));var _y;function Ny(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Oy(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 By(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");Ny(e.outputLen),Ny(e.blockLen)}function Uy(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 jy(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function qy(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function $y(e,t){return e<<32-t|e>>>t}const zy=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Vy=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Gy(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Ky(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 Wy(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 Hy=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Qy(e,t,n){return e&t^~e&n}function Yy(e,t,n){return e&t^e&n^t&n}class Jy{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=qy(this.buffer)}update(e){Uy(this),Oy(e);const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o!==r)n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=qy(e);for(;r<=i-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Uy(this),function(e,t){Oy(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,jy(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 o=qy(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<u;e++)o.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:o}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Zy=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xy=/* @__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]),eb=/* @__PURE__ */new Uint32Array(64);class tb extends Jy{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[e,t,n,r,i,s,o,a]}set(e,t,n,r,i,s,o,a){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|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)eb[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=eb[e-15],n=eb[e-2],r=$y(t,7)^$y(t,18)^t>>>3,i=$y(n,17)^$y(n,19)^n>>>10;eb[e]=i+eb[e-7]+r+eb[e-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:u,H:d}=this;for(let e=0;e<64;e++){const t=d+($y(o,6)^$y(o,11)^$y(o,25))+Qy(o,a,u)+Xy[e]+eb[e]|0,c=($y(n,2)^$y(n,13)^$y(n,22))+Yy(n,r,i)|0;d=u,u=a,a=o,o=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,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,r,i,s,o,a,u,d)}roundClean(){jy(eb)}destroy(){this.set(0,0,0,0,0,0,0,0),jy(this.buffer)}}class nb extends tb{A=0|Zy[0];B=0|Zy[1];C=0|Zy[2];D=0|Zy[3];E=0|Zy[4];F=0|Zy[5];G=0|Zy[6];H=0|Zy[7];constructor(){super(32)}}const rb=/* @__PURE__ */Ky(()=>new nb
4
+ /* @__PURE__ */,Hy(1)),ib=/* @__PURE__ */BigInt(0);function sb(e){return function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?ib:BigInt("0x"+e)}(function(e){if(Oy(e),zy)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Vy[e[n]];return t}(ob(Oy(e)).reverse()))}function ob(e){return Uint8Array.from(e)}const ab=e=>"bigint"==typeof e&&ib<=e;function ub(e,t,n,r){if(!function(e,t,n){return ab(e)&&ab(t)&&ab(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const db=/* @__PURE__ */BigInt(0);function cb(e,t){const n=e%t;return n>=db?n:t+n}function lb(e,t,n){let r=e;for(;t-- >db;)r*=r,r%=n;return r}function pb(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 hb=BigInt(0),fb=BigInt(1),mb=BigInt(2),yb=BigInt(1),bb=BigInt(2),gb=/* @__PURE__ */BigInt(3),vb=BigInt(5),wb=(BigInt(8),BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"));function Tb(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Pb=/* @__PURE__ */(()=>{const e=wb;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:o,randomBytes:a}=t,u="x25519"===i;if(!u&&"x448"!==i)throw new Error("invalid type");const d=a||Wy,c=u?255:448,l=u?32:56,p=u?BigInt(9):BigInt(5),h=u?BigInt(121665):BigInt(39081),f=u?mb**BigInt(254):mb**BigInt(447),m=u?BigInt(8)*mb**BigInt(251)-fb:BigInt(4)*mb**BigInt(445)-fb,y=f+m+fb,b=e=>cb(e,r),g=v(p);function v(e){return function(e,t){return function(e,t){Ny(t);const n=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(zy)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=Gy(e.charCodeAt(i)),s=Gy(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(!ab(e))throw new Error("positive bigint expected, got "+e)}else Ny(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){ub("u",e,hb,r),ub("scalar",t,f,y);const n=t,i=e;let s=fb,a=hb,u=e,d=fb,l=hb;for(let e=BigInt(c-1);e>=hb;e--){const t=n>>e&fb;l^=t,({x_2:s,x_3:u}=E(l,s,u)),({x_2:a,x_3:d}=E(l,a,d)),l=t;const r=s+a,o=b(r*r),c=s-a,p=b(c*c),f=o-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(o*p),a=b(f*(o+b(h*f)))}({x_2:s,x_3:u}=E(l,s,u)),({x_2:a,x_3:d}=E(l,a,d));const p=o(a);return b(s*p)}(function(e){const t=ob(Oy(e,l,"uCoordinate"));return u&&(t[31]&=127),b(sb(t))}(t),function(e){return sb(s(ob(Oy(e,l,"scalar"))))}(e));if(n===hb)throw new Error("invalid private or public key received");return v(n)}function T(e){return w(e,g)}const P=T,x=w;function E(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))=>(Oy(e,S.seed,"seed"),e),k={randomSecretKey:A};return Object.freeze({keygen:pb(A,P),getSharedSecret:x,getPublicKey:P,scalarMult:w,scalarMultBase:T,utils:k,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=wb,o=e*e%s*e%s,a=lb(o,bb,s)*o%s,u=lb(a,yb,s)*e%s,d=lb(u,vb,s)*u%s,c=lb(d,t,s)*d%s,l=lb(c,n,s)*c%s,p=lb(l,r,s)*l%s,h=lb(p,i,s)*p%s,f=lb(h,i,s)*p%s,m=lb(f,t,s)*d%s;return{pow_p_5_8:lb(m,bb,s)*e%s,b2:o}}(t);return cb(lb(n,gb,e)*r,e)},adjustScalarBytes:Tb})})();class xb{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(By(e),Oy(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),jy(r)}update(e){return Uy(this),this.iHash.update(e),this}digestInto(e){Uy(this),Oy(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:o}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=o,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 Eb=(e,t,n)=>new xb(e,t).update(n).digest();Eb.create=(e,t)=>new xb(e,t);const Sb=/* @__PURE__ */Uint8Array.of(0),Ab=/* @__PURE__ */Uint8Array.of(),kb={hashSHA256:e=>rb(e.subarray()),getHKDF(e,t){const n=function(e,t,n){return By(e),void 0===n&&(n=new Uint8Array(e.outputLen)),Eb(e,n,t)}(rb,t,e),r=function(e,t,n,r=32){By(e),Ny(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=Ab:Oy(n,void 0,"info");const o=new Uint8Array(s*i),a=Eb.create(e,t),u=a._cloneInto(),d=new Uint8Array(a.outputLen);for(let e=0;e<s;e++)Sb[0]=e+1,u.update(0===e?Ab:d).update(n).update(Sb).digestInto(d),o.set(d,i*e),a._cloneInto(u);return a.destroy(),u.destroy(),jy(d,Sb),o.slice(0,r)}(rb,n,void 0,96),i=r;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){const e=Pb.utils.randomSecretKey();return{publicKey:Pb.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Pb.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Pb.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,n,r)=>Ly(r,t,n).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,n,r,i)=>Ly(r,t,n).decrypt(e.subarray(),i)},Cb=kb,Ib=e=>{const t=Zn(2);return t[0]=e>>8,t[1]=e,t};Ib.bytes=2;const Db=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function Mb(e,t){t.enabled&&iy&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${Dr(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${Dr(e.privateKey,"hex")}`)):t("Missing local static keys."))}function Fb(e,t){t.enabled&&iy&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Dr(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Dr(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Rb(e,t){t.enabled&&iy&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Dr(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Lb(e,t,n){n.enabled&&iy&&(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&Dr(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&Dr(t.k,"hex")}`))}function _b(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");const n=Zn(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}Db.bytes=2;class Nb extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Nb.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Ob{n;bytes;view;constructor(e=0){this.n=e,this.bytes=Jn(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 Bb=Jn(0);class Ub{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Ob(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 jb{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const n=Ir(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=Jn(32);return e.set(t),e}return e.hash(t)}(e,n),this.ck=this.h,this.cs=new Ub(e)}mixKey(e){const[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Ub(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new rr(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,Bb);return[new Ub(this.crypto,e),new Ub(this.crypto,t)]}}class qb{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:n,prologue:r,initiator:i,s:s,e:o,rs:a,re:u}=e;this.crypto=t,this.ss=new jb(t,n),this.ss.mixHash(r),this.initiator=i,this.s=s,this.e=o,this.rs=a,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 $b extends qb{writeMessageA(e){return new rr(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new rr(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new rr(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Nb(`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 Nb(`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 Nb(`handshake stage 2 validation fail: ${e.message}`)}}}var zb,Vb,Gb,Kb,Wb;async function Hb(e,t,n){const r=await e.sign(Yb(t));return Vb.encode({identityKey:Wa(e.publicKey),identitySig:r,extensions:n})}async function Qb(e,t,n){try{const r=Vb.decode(e),i=Ka(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=Yb(t);if(!await i.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(e){throw new at(e.message)}}function Yb(e){const t=Ir("noise-libp2p-static-key:");return e instanceof Uint8Array?Xn([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=Xp((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 eh('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 eh('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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(zb||(zb={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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),zb.codec().encode(e.extensions,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={identityKey:Jn(0),identitySig:Jn(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=zb.codec().decode(e,e.uint32(),{limits:n.limits?.extensions});break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Vb||(Vb={}));class Jb extends dc{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 Fc({lengthDecoder:Db,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 rr;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(Ib(r.byteLength)),t.append(r)}return t}decrypt(e){const t=new rr;for(let n=0;n<e.byteLength;n+=ry){let r,i=n+ry;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 Zb(e,t,n){return new Jb(e,t,n)}class Xb{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){const{staticNoiseKey:n,extensions:r,crypto:i,prologueBytes:s}=t,{metrics:o}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const a=i??Cb;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}}(a),this.extensions={webtransportCerthashes:[],...r},this.metrics=o?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"})}}(o):void 0,this.staticKey=n?a.generateX25519KeyPairFromSeed(n):a.generateX25519KeyPair(),this.prologue=s??Jn(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ht]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const n=e.log?.newScope("noise")??this.log,r=Dc(e,{lengthEncoder:Ib,lengthDecoder:Db,maxDataLength:ry}),i=await this.performHandshakeInitiator(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Ka(i.payload.identityKey);return{connection:Zb(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:tu(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 ut("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=Dc(e,{lengthEncoder:Ib,lengthDecoder:Db,maxDataLength:ry}),i=await this.performHandshakeResponder(r,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Ka(i.payload.identityKey);return{connection:Zb(r.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:tu(s),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,r,i){let s;const o=!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:o,s:a,remoteIdentityKey:u,extensions:d}=e,c=await Hb(s,a.publicKey,d),l=new $b({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});Mb(l.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(l.writeMessageA(Bb),t),n.trace("Stage 0 - Initiator finished sending first message."),Fb(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."),Rb(l.re,n),h=l.rs,(f=n).enabled&&iy&&f(h?`REMOTE_STATIC_PUBLIC_KEY ${Dr(h.subarray(),"hex")}`:"Missing remote static public key."),n.trace("Initiator going to check remote's signature...");const m=await Qb(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 Lb(y,b,n),{payload:m,encrypt:e=>y.encryptWithAd(Bb,e),decrypt:(e,t)=>b.decryptWithAd(Bb,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:o,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 o=!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:o,s:a,remoteIdentityKey:u,extensions:d}=e,c=await Hb(s,a.publicKey,d),l=new $b({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});Mb(l.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await r.read(t)),n.trace("Stage 0 - Responder received first message."),Rb(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."),Fb(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 Qb(p,l.rs,u),[f,m]=l.ss.split();return Lb(f,m,n),{payload:h,encrypt:e=>m.encryptWithAd(Bb,e),decrypt:(e,t)=>f.decryptWithAd(Bb,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:o,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}}function eg(e={}){return t=>new Xb(t,e)}!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(Gb||(Gb={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(Kb||(Kb={})),Object.values(Kb).filter(e=>"string"!=typeof e),function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(Wb||(Wb={}));const tg=12;class ng extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}}class rg extends ng{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Wb.ProtocolError),this.name="InvalidFrameError"}}class ig extends ng{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Wb.ProtocolError),this.name="UnRequestedPingError"}}class sg extends ng{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Wb.ProtocolError),this.name="NotMatchingPingError"}}class og extends ng{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Wb.ProtocolError),this.name="ReceiveWindowExceededError"}}const ag=262144,ug=2**24;class dg{buffer;constructor(){this.buffer=new rr}*emitFrames(e){for(this.buffer.append(e);;){const e=this.readFrame();if(void 0===e)break;yield e}}readFrame(){let e=tg;if(this.buffer.byteLength<tg)return;const t=function(e){if(0!==e[0])throw new rg("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*ug+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*ug+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,tg));if(t.type===Gb.Data){if(e+=t.length,this.buffer.byteLength<e)return;const n=this.buffer.sublist(tg,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}}function cg(e){const t=new Uint8Array(tg);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 lg;!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"}(lg||(lg={}));class pg extends pc{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){const t=e.initialStreamWindowSize??ag;super({...e,maxMessageSize:t-tg}),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=lg.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(),o=e.sublist(0,i);e.consume(i);const a=this.sendFrame({type:Gb.Data,flag:s,streamID:this.streamId,length:i},o);if(this.sendWindowCapacity-=i,n+=i,!a){r=a,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:Gb.WindowUpdate,flag:Kb.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){const e=this.getSendFlags()|Kb.FIN;this.sendFrame({type:Gb.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=lg.Paused}sendResume(){this.state=lg.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-tg,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===Gb.Data&&null!==e.data}(e))throw new rg("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new og("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&Kb.ACK)===Kb.ACK&&this.state===lg.SYNSent&&(this.state=lg.Established),(e&Kb.FIN)===Kb.FIN&&this.onRemoteCloseWrite(),(e&Kb.RST)===Kb.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case lg.Init:return this.state=lg.SYNSent,Kb.SYN;case lg.SYNReceived:return this.state=lg.Established,Kb.ACK;default:return 0}}sendWindowUpdate(){if(this.state===lg.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:Gb.WindowUpdate,flag:e,streamID:this.streamId,length:r})}}function hg(e){return{type:Gb[e.type],flags:[(e.flag&Kb.SYN)===Kb.SYN?"SYN":void 0,(e.flag&Kb.ACK)===Kb.ACK?"ACK":void 0,(e.flag&Kb.FIN)===Kb.FIN?"FIN":void 0,(e.flag&Kb.RST)===Kb.RST?"RST":void 0].filter(Boolean),streamID:e.streamID,length:e.length}}const fg="/yamux/1.0.0";class mg{protocol=fg;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[Ht]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new yg(e,{...this._init})}}class yg extends lc{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:fg,name:"yamux"}),this.client="outbound"===e.direction,function(e){if(null!=e.keepAliveInterval&&e.keepAliveInterval<=0)throw new dt("keep-alive interval must be positive");if(null!=e.maxInboundStreams&&e.maxInboundStreams<0)throw new dt("max inbound streams must be larger or equal 0");if(null!=e.maxOutboundStreams&&e.maxOutboundStreams<0)throw new dt("max outbound streams must be larger or equal 0");if(null!=e.maxMessageSize&&e.maxMessageSize<1024)throw new dt("MaxMessageSize must be greater than a kilobyte");if(null!=e.streamOptions?.initialStreamWindowSize&&e.streamOptions?.initialStreamWindowSize<ag)throw new dt("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 dt("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(null!=e.streamOptions?.maxStreamWindowSize&&e.streamOptions?.maxStreamWindowSize>2**32-1)throw new dt("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 dg,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=zc(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 ht("Muxer closed remotely");if(void 0!==this.localGoAway)throw new ht("Muxer closed locally");const e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Mt("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);const t=this._newStream(e,lg.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(void 0!==this.remoteGoAway)throw new ht("Muxer closed remotely");if(void 0!==this.localGoAway)throw new ht("Muxer closed locally");if(null!=this.activePing)return ic(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 ic(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??Wb.NormalTermination;this.log.trace("muxer close reason=%s",Wb[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if("open"===this.status)try{super.abort(e);let t=Wb.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 dt("Stream already exists with that id");const r=new pg({...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",hg(e.header)),0===t)switch(n){case Gb.Ping:return void this.handlePing(e.header);case Gb.GoAway:return void this.handleGoAway(r);default:throw new rg("Invalid frame type")}else switch(e.header.type){case Gb.Data:case Gb.WindowUpdate:return void this.handleStreamMessage(e);default:throw new rg("Invalid frame type")}}handlePing(e){if(e.flag===Kb.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Kb.ACK);else{if(e.flag!==Kb.ACK)throw new rg("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 ig("ping not requested");if(this.activePing.id!==e)throw new sg("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Wb[e]??"unknown"),this.remoteGoAway=e,e===Wb.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){const{streamID:t,flag:n,type:r}=e.header;(n&Kb.SYN)===Kb.SYN&&this.incomingStream(t);const i=this.streams.find(e=>e.streamId===t);if(void 0!==i)switch(r){case Gb.WindowUpdate:return void i.handleWindowUpdate(e);case Gb.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 dt("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:Gb.WindowUpdate,flag:Kb.RST,streamID:e,length:0});if(this.numInboundStreams>=this.maxInboundStreams)return this.log("maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:Gb.WindowUpdate,flag:Kb.RST,streamID:e,length:0});const t=this._newStream(e,lg.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Gb.Data){if(null==t)throw new rg("Invalid frame");n=new rr(cg(e),t)}else n=cg(e);return this.log.trace("sending frame %o",hg(e)),this.send(n)}sendPing(e,t=Kb.SYN){this.log.trace(t===Kb.SYN?"sending ping request pingId=%s":"sending ping response pingId=%s",e),this.sendFrame({type:Gb.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Wb.NormalTermination){this.log("sending GoAway reason=%s",Wb[e]),this.localGoAway=e,this.sendFrame({type:Gb.GoAway,flag:0,streamID:0,length:e})}}function bg(e={}){return()=>new mg(e)}const gg=[6,53,56,54,55];function vg(e){return Tg("sni",e)?.value}function wg(e){const t=Tg("tcp",e)?.value;return null==t?"":`:${t}`}function Tg(e,t){return t.find(t=>t.name===e)}function Pg(e){return e.some(({code:e})=>e===yu)}function xg(e,t){const n=Eg[e.name];if(null==n)throw new Error(`Can't interpret protocol ${e.name}`);const r=n(e,t);return e.code===fu?`[${r}]`:r}const Eg={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://${xg(n,t)}:${e.value}`},udp:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`udp://${xg(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`${xg(n,t)}`},p2p:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${xg(n,t)}`},http:(e,t)=>{const n=Pg(t),r=vg(t),i=wg(t);if(n&&null!=r)return`https://${r}${i}`;const s=n?"https://":"http://",o=t.pop();if(null==o)throw new Error("Unexpected end of multiaddr");let a=xg(o,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return`${xg(n,t)}${decodeURIComponent(e.value??"")}`},tls:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return xg(n,t)},sni:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return xg(n,t)},https:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=xg(n,t);return r=r?.replace("tcp://",""),`https://${r}`},ws:(e,t)=>{const n=Pg(t),r=vg(t),i=wg(t);if(n&&null!=r)return`wss://${r}${i}`;const s=n?"wss://":"ws://",o=t.pop();if(null==o)throw new Error("Unexpected end of multiaddr");let a=xg(o,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(e,t)=>{const n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");let r=xg(n,t);return r=r?.replace("tcp://",""),`wss://${r}`}};class Sg extends cc{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??4194304,this.checkBufferedAmountTask=zc(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=Ir(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 Ag{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"})})}[Gt]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ht]=["@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 Sg(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=Uu(e).getComponents(),n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");const r=Eg[n.name];if(null==r)throw new Error(`No interpreter found for ${n.name}`);let i=r(n,t)??"";return gg.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 Yf("websockets:open-connection")),await Yd(r,"open",t)}catch(e){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new pt(`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=>sf.exactMatch(e)||af.exactMatch(e))}dialFilter(e){return this.listenFilter(e)}}function kg(e={}){return t=>new Ag(t,e)}class Cg{constructor(){throw new Error("TCP connections are not possible in browsers")}[Gt]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Ht]=["@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 Ig(e={}){return t=>new Cg(t,e)}const Dg=`${qt}-circuit-relay`;BigInt(1<<17);const Mg="/libp2p/circuit/relay/0.2.0/hop",Fg="/libp2p/circuit/relay/0.2.0/stop",Rg=new Float32Array([-0]),Lg=new Uint8Array(Rg.buffer);function _g(e,t,n){Rg[0]=e,t[n]=Lg[0],t[n+1]=Lg[1],t[n+2]=Lg[2],t[n+3]=Lg[3]}const Ng=new Float64Array([-0]),Og=new Uint8Array(Ng.buffer);function Bg(e,t,n){Ng[0]=e,t[n]=Og[0],t[n+1]=Og[1],t[n+2]=Og[2],t[n+3]=Og[3],t[n+4]=Og[4],t[n+5]=Og[5],t[n+6]=Og[6],t[n+7]=Og[7]}const Ug=BigInt(Number.MAX_SAFE_INTEGER),jg=BigInt(Number.MIN_SAFE_INTEGER);class qg{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 $g;if(e<Ug&&e>jg)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>zg&&(r=0n,++n>zg&&(n=0n))),new qg(Number(r),Number(n))}static fromNumber(e){if(0===e)return $g;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 qg(n,r)}static from(e){return"number"==typeof e?qg.fromNumber(e):"bigint"==typeof e?qg.fromBigInt(e):"string"==typeof e?qg.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new qg(e.low>>>0,e.high>>>0):$g}}const $g=new qg(0,0);$g.toBigInt=function(){return 0n},$g.zzEncode=$g.zzDecode=function(){return this},$g.length=function(){return 1};const zg=4294967296n;function Vg(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 Gg(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Kg(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Wg{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,Gg(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 Gg(this,4);return Kg(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Gg(this,4);return 0|Kg(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Gg(this,4);const e=(Lg[0]=(t=this.buf)[n=this.pos],Lg[1]=t[n+1],Lg[2]=t[n+2],Lg[3]=t[n+3],Rg[0]);var t,n;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Gg(this,4);const e=(Og[0]=(t=this.buf)[n=this.pos],Og[1]=t[n+1],Og[2]=t[n+2],Og[3]=t[n+3],Og[4]=t[n+4],Og[5]=t[n+5],Og[6]=t[n+6],Og[7]=t[n+7],Ng[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 Gg(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,o=0;for(;t<n;)s=e[t++],s<128?i[o++]=s:s>191&&s<224?i[o++]=(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[o++]=55296+(s>>10),i[o++]=56320+(1023&s)):i[o++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((r??(r=[])).push(String.fromCharCode.apply(String,i)),o=0);return null!=r?(o>0&&r.push(String.fromCharCode.apply(String,i.slice(0,o))),r.join("")):String.fromCharCode.apply(String,i.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Gg(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Gg(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 qg(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Gg(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 Gg(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 Gg(this,8);const e=Kg(this.buf,this.pos+=4),t=Kg(this.buf,this.pos+=4);return new qg(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=Ro(this.buf,this.pos);return this.pos+=Mo(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 Hg(e){return new Wg(e instanceof Uint8Array?e:e.subarray())}function Qg(e,t,n){const r=Hg(e);return t.decode(r,void 0,n)}class Yg{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}}function Jg(){}class Zg{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Xg=function(){const e=8192;let t,n=e;return function(r){if(r<1||r>4096)return Zn(r);n+r>e&&(t=Zn(e),n=0);const i=t.subarray(n,n+=r);return 7&n&&(n=1+(7|n)),i}}();class ev{len;head;tail;states;constructor(){this.len=0,this.head=new Yg(Jg,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Yg(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new rv((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(iv,10,qg.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=qg.fromBigInt(e);return this._push(iv,t.length(),t)}uint64Number(e){return this._push(Fo,Mo(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=qg.fromBigInt(e).zzEncode();return this._push(iv,t.length(),t)}sint64Number(e){const t=qg.fromNumber(e).zzEncode();return this._push(iv,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(tv,1,e?1:0)}fixed32(e){return this._push(sv,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=qg.fromBigInt(e);return this._push(sv,4,t.lo)._push(sv,4,t.hi)}fixed64Number(e){const t=qg.fromNumber(e);return this._push(sv,4,t.lo)._push(sv,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(_g,4,e)}double(e){return this._push(Bg,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(tv,1,0):this.uint32(t)._push(ov,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(Vg,t,e):this._push(tv,1,0)}fork(){return this.states=new Zg(this),this.head=this.tail=new Yg(Jg,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 Yg(Jg,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?Zn(n):Xg(n));var n;let r=0;for(;null!=e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}}function tv(e,t,n){t[n]=255&e}function nv(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e}class rv extends Yg{next;constructor(e,t){super(nv,e,t),this.next=void 0}}function iv(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 sv(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 ov(e,t,n){t.set(e,n)}function av(e,t,n){t.set(e,n)}function uv(e,t,n){e.length<40?Vg(e,t,n):null!=t.utf8Write?t.utf8Write(e,n):t.set(Ir(e),n)}function dv(e,t){const n=new ev;return t.encode(e,n,{lengthDelimited:!1}),n.finish()}function*cv(e,t,n){const r=Hg(e);yield*t.stream(r,void 0,"$",n)}function lv(e,t,n,r,i){return{name:e,type:t,encode:n,decode:r,stream:i}}function pv(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return lv("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 hv(e,t,n){return lv("message",2,e,t,n)}null!=globalThis.Buffer&&(ev.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(av,t,e),this},ev.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(uv,t,e),this});class fv extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var mv,yv,bv,gv,vv,wv,Tv,Pv,xv;!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=()=>pv(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=hv((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),bv.codec().encode(t.peer,n)),null!=t.reservation&&(n.uint32(26),gv.codec().encode(t.reservation,n)),null!=t.limit&&(n.uint32(34),vv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(40),wv.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=bv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.reservation=gv.codec().decode(t,t.uint32(),{limits:r.limits?.reservation});break;case 4:i.limit=vv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 5:i.status=wv.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*bv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*gv.codec().stream(t,t.uint32(),`${r}.reservation`,{limits:i.limits?.reservation});break;case 4:yield*vv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 5:yield{field:`${r}.status`,value:wv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(mv||(mv={})),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=()=>pv(n)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=hv((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),bv.codec().encode(t.peer,n)),null!=t.limit&&(n.uint32(26),vv.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(32),wv.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=bv.codec().decode(t,t.uint32(),{limits:r.limits?.peer});break;case 3:i.limit=vv.codec().decode(t,t.uint32(),{limits:r.limits?.limit});break;case 4:i.status=wv.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*bv.codec().stream(t,t.uint32(),`${r}.peer`,{limits:i.limits?.peer});break;case 3:yield*vv.codec().stream(t,t.uint32(),`${r}.limit`,{limits:i.limits?.limit});break;case 4:yield{field:`${r}.status`,value:wv.codec().decode(t)};break;default:t.skipType(7&n)}}})),r),e.encode=function(t){return dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(yv||(yv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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:Jn(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 fv('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 fv('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 dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(bv||(bv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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),xv.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 fv('Decode error - repeated field "addrs" had too many elements');r.addrs.push(e.bytes());break;case 3:r.voucher=xv.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 fv('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*xv.codec().stream(e,e.uint32(),`${n}.voucher`,{limits:r.limits?.voucher});break;default:e.skipType(7&t)}}})),t),e.encode=function(t){return dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(gv||(gv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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 dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(vv||(vv={})),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"}(wv||(wv={})),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"}(Tv||(Tv={})),function(e){e.codec=()=>pv(Tv)}(wv||(wv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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:Jn(0),peer:Jn(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 dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(Pv||(Pv={})),function(e){let t;e.codec=()=>(null==t&&(t=hv((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),Pv.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:Jn(0),payloadType:Jn(0),signature:Jn(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=Pv.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*Pv.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 dv(t,e.codec())},e.decode=function(t,n){return Qg(t,e.codec(),n)},e.stream=function(t,n){return cv(t,e.codec(),n)}}(xv||(xv={}));class Ev extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"}class Sv extends Error{static name="DoubleRelayError";name="DoubleRelayError"}class Av extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"}function kv(e){const t=e*BigInt(1e3),n=(new Date).getTime();return Number(t-BigInt(n))}class Cv{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 Iv=Nh(_h(hf.matchers[0],Mh(wu))),Dv=Nh(Mh(wu));class Mv extends Wt{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(Mg,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){null!=this.topologyId&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");const e=await this.components.peerStore.all({filters:[e=>e.protocols.includes(Mg)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{const n=Fv(e),r=Fv(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 Uc({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=hc([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}}function Fv(e){const t=e.metadata.get("last-dial-success");return null==t?0:new Date(Dr(t)).getTime()}class Rv extends Wt{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(Dv.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else{if(!Iv.exactMatch(e))throw new Ct(`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=>Uu(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}}class Lv extends Wt{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 fd,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??5e3,this.started=!1,this.relayFilter=kd(100),this.reserveQueue=new Uc({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(Dg)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async e=>{await this.peerStore.merge(e.id,{tags:{[Dg]: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 Ct("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Av("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 Ct("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&&kv(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 Ev("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(mf.matches(i.remoteAddr))throw new Sv("not creating reservation over relayed connection");const s=await this.#X(i,{signal:r}),o=kv(s.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+o).toString());const a=Math.min(Math.max(o-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)})},a);let d;if("discovered"===t){const e=this.pendingReservations.pop();if(null==e)throw new Ev("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:{[Dg]:{value:1,ttl:o}}}),this.#Z();const c={relay:e,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:c}),c}catch(r){throw"discovered"===t&&"HadEnoughRelaysError"===r.name||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-n,r),"DialError"!==r.name&&"UnsupportedProtocolError"!==r.name||this.relayFilter.add(e.toMultihash().bytes),this.#J(e).catch(t=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,t)}),r}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return null==e?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#X(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);const n=await e.newStream(Mg,t),r=Mc(n).pb(mv);let i;this.log.trace("send RESERVE to %p",e.remotePeer),await r.write({type:mv.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===wv.OK&&null!=i.reservation){const t=new Set;t.add(e.remoteAddr.toString());for(const n of i.reservation.addrs){let r=Uu(n);null==r.getComponents().find(e=>e.code===mu)&&(r=r.encapsulate(`/p2p/${e.remotePeer}`)),r=Uu(r.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),t.add(r.toString())}return i.reservation.addrs=[...t].map(e=>Uu(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:{[Dg]: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=kd(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}}class _v extends cc{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 Nv(e){return new _v(e)}class Ov{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??300,this.maxOutboundStopStreams=t.maxOutboundStopStreams??300,this.shutdownController=new AbortController,this.discovery=new Mv(e,{filter:t.discoveryFilter??Wc(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 Lv(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";[Ht]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Qt](){return null!=this.discovery?["@libp2p/identify"]:[]}[Gt]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.components.registrar.handle(Fg,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await zt(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Vt(this.discovery,this.reservationStore),await this.components.registrar.unhandle(Fg),this.started=!1}async dial(e,t){const n=e.toString().split("/p2p-circuit"),r=Uu(n[0]),i=Uu(n[n.length-1]),s=r.getComponents().find(e=>e.code===mu)?.value,o=i.getComponents().find(e=>e.code===mu)?.value;if(null==s||null==o){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 kt(`C${t}`)}const a=eu(s),u=eu(o);let d,c=this.components.connectionManager.getConnections(a)[0];null==c?(await this.components.peerStore.merge(a,{multiaddrs:[r]}),t.onProgress?.(new Yf("circuit-relay:open-connection")),c=await this.components.connectionManager.openConnection(a,t)):t.onProgress?.(new Yf("circuit-relay:reuse-connection"));try{t.onProgress?.(new Yf("circuit-relay:open-hop-stream")),d=await c.newStream(Mg,t);const n=Mc(d).pb(mv);t.onProgress?.(new Yf("circuit-relay:write-connect-message")),await n.write({type:mv.Type.CONNECT,peer:{id:u.toMultihash().bytes,addrs:[Uu(i).bytes]}},t),t.onProgress?.(new Yf("circuit-relay:read-connect-response"));const s=await n.read(t);if(s.status!==wv.OK)throw new xt(`failed to connect via relay with status ${s?.status?.toString()??"undefined"}`);const o=new Cv(s.limit),a=Nv({stream:n.unwrap().unwrap(),remoteAddr:e,localAddr:r.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:o.onData,onDataWrite:o.onData,log:d.log.newScope("circuit-relay:connection")}),l=await this.components.upgrader.upgradeOutbound(a,{...t,limits:o.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,a,e),d?.abort(e),e}}createListener(e){return function(e){return new Rv(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=>Iv.exactMatch(e)||Dv.exactMatch(e))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter(e=>mf.exactMatch(e))}async onStop(e,t){const n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(e){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",e)}const r=Mc(e).pb(yv),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:yv.Type.STATUS,status:wv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});if(i.type!==yv.Type.CONNECT)return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:yv.Type.STATUS,status:wv.UNEXPECTED_MESSAGE},{signal:n}),void await e.close({signal:n});if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(Uu)}catch{return!1}return!0})(i))return this.log.error("invalid stop connect request via peer %p",t.remotePeer),await r.write({type:yv.Type.STATUS,status:wv.MALFORMED_MESSAGE},{signal:n}),void await e.close({signal:n});const s=nu(Bn(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:yv.Type.STATUS,status:wv.PERMISSION_DENIED},{signal:n}),void await e.close({signal:n});this.log.trace("sending success response to %p",t.remotePeer),await r.write({type:yv.Type.STATUS,status:wv.OK},{signal:n});const o=new Cv(i.limit),a=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),u=this.components.addressManager.getAddresses()[0],d=Nv({stream:r.unwrap().unwrap(),remoteAddr:a,localAddr:u,onDataRead:o.onData,onDataWrite:o.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(d,{limits:o.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 Bv(e={}){return t=>new Ov(t,e)}class Uv extends Wt{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=>Uu(e)).filter(e=>{if(!hf.matches(e))return this.log.error("invalid multiaddr %a",e),!1;const t=e.getComponents().findLast(e=>e.code===mu)?.value;return null!=t||(this.log.error("invalid bootstrap multiaddr without peer id"),!1)}).map(e=>({id:eu(e.getComponents().findLast(e=>e.code===mu)?.value??""),multiaddrs:[e]})),this._init=t}[Ot]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Ht]=["@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 jv;!function(e){let t;e.codec=()=>(null==t&&(t=Xp((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 eh('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 eh('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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(jv||(jv={}));const qv="ipfs";async function $v(e,t,n,r,i){if(n("received identify from %p",r.remotePeer),null==i)throw new xt("message was null or undefined");const s={};if(i.listenAddrs.length>0&&(s.addresses=i.listenAddrs.map(e=>({isCertified:!1,multiaddr:Uu(e)}))),i.protocols.length>0&&(s.protocols=i.protocols),null!=i.publicKey){const e=Ka(i.publicKey);if(!tu(e).equals(r.remotePeer))throw new xt("public key did not match remote PeerId");s.publicKey=e}let o;if(null!=i.signedPeerRecord){n.trace("received signedPeerRecord from %p",r.remotePeer);let t=i.signedPeerRecord;const a=await Fl.openAndCertify(t,Nl.DOMAIN);let u=Nl.createFromProtobuf(a.payload);const d=ru(a.publicKey.toCID());if(!u.peerId.equals(d))throw new xt("signing key does not match PeerId in the PeerRecord");if(!r.remotePeer.equals(u.peerId))throw new xt("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=Fl.createFromProtobuf(c.peerRecordEnvelope),r=Nl.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})),o={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=Ir(i.agentVersion)),null!=i.protocolVersion&&(t.ProtocolVersion=Ir(i.protocolVersion)),n.trace("merging %p metadata",r.remotePeer,t),await e.merge(r.remotePeer,{metadata:t})}const a={peerId:r.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map(e=>Uu(e)),observedAddr:null==i.observedAddr?void 0:Uu(i.observedAddr),protocols:i.protocols,signedPeerRecord:o,connection:r};return t.safeDispatchEvent("peer:identify",{detail:a}),a}class zv{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??qv}/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:Ir(this.host.agentVersion),ProtocolVersion:Ir(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 Vv extends zv{connectionManager;concurrency;_push;constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??qv}/id/push/1.0.0`,log:e.logger.forComponent("libp2p:identify-push")}),this.connectionManager=e.connectionManager,this.concurrency=t.concurrency??32,this._push=Jd(this.sendPushMessage.bind(this),t.debounce??1e3),(t.runOnSelfUpdate??1)&&e.events.addEventListener("self:peer:update",e=>{this.push().catch(e=>{this.log.error("error pushing updates to peers - %e",e)})})}[Ht]=["@libp2p/identify-push"];async push(){this._push()}async sendPushMessage(){if(this.isStarted())try{const e=this.components.addressManager.getAddresses().map(e=>e.decapsulateCode(mu)),t=new Nl({peerId:this.components.peerId,multiaddrs:e}),n=await Fl.seal(t,this.components.privateKey),r=this.components.registrar.getProtocols(),i=await this.components.peerStore.get(this.components.peerId),s=Dr(i.metadata.get("AgentVersion")??Ir(this.host.agentVersion)),o=Dr(i.metadata.get("ProtocolVersion")??Ir(this.host.protocolVersion)),a=this;async function*u(){for(const t of a.connectionManager.getConnections())(await a.components.peerStore.get(t.remotePeer)).protocols.includes(a.protocol)&&(yield async()=>{let i;const u=AbortSignal.timeout(a.timeout);try{i=await t.newStream(a.protocol,{signal:u,runOnLimitedConnection:a.runOnLimitedConnection});const d=Mc(i,{maxDataLength:a.maxMessageSize}).pb(jv);await d.write({listenAddrs:e.map(e=>e.bytes),signedPeerRecord:n.marshal(),protocols:r,agentVersion:s,protocolVersion:o},{signal:u}),await i.close({signal:u})}catch(e){const t=i?.log.newScope("identify-push");t?.error("could not push identify update to peer",e),i?.abort(e)}})}await Eh(qm(u(),{concurrency:this.concurrency}))}catch(d){this.log.error("error pushing updates to peers - %e",d)}}async handleProtocol(e,t){const n=e.log.newScope("identify-push");if(this.components.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");const r={signal:AbortSignal.timeout(this.timeout)},i=Mc(e,{maxDataLength:this.maxMessageSize}).pb(jv),s=await i.read(r);await e.close(r),await $v(this.components.peerStore,this.components.events,n,t,s),n.trace("handled push from %p",t.remotePeer)}}class Gv extends zv{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??qv}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??1)&&e.events.addEventListener("connection:open",e=>{this.identify(e.detail).catch(()=>{})})}[Ht]=["@libp2p/identify"];async _identify(e,t={}){let n,r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),r=n.log.newScope("identify");const i=Mc(n,{maxDataLength:this.maxMessageSize}).pb(jv),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 xt("Public key was missing from identify message");const o=ru(Ka(r).toCID());if(!e.remotePeer.equals(o))throw new xt("Identified peer does not match the expected peer");if(this.components.peerId.equals(o))throw new xt("Identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("completed for peer %p and protocols %o",o,i),$v(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Uu(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),$d(t))return;const n=t.getComponents();n[0].code!==fu&&(42!==n[0].code||n[1].code!==fu)||function(e){try{const n=Id(e);return"ip6"===n.type&&(t=n.host,new Rd("2000::/3").contains(t))}catch{return!1}var t}(t)?Jh.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(mu));let o=i.peerRecordEnvelope;if(s.length>0&&null==o){const e=new Nl({peerId:this.components.peerId,multiaddrs:s});o=(await Fl.seal(e,this.components.privateKey,{signal:r})).marshal().subarray()}let a=t.remoteAddr.bytes;Kh.matches(t.remoteAddr)||(a=void 0);const u=Mc(e).pb(jv);n("send response"),await u.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Wa(this.components.privateKey.publicKey),listenAddrs:s.map(e=>e.bytes),signedPeerRecord:o,observedAddr:a,protocols:i.protocols},{signal:r}),n("close write"),await u.unwrap().unwrap().close({signal:r})}}function Kv(e={}){return t=>new Gv(t,e)}function Wv(e={}){return t=>new Vv(t,e)}const Hv=36e5,Qv=48*Hv,Yv=Hv,Jv=Hv,Zv=`${qt}-kad-dht`;var Xv,ew,tw,nw,rw,iw,sw,ow;function aw(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"),o=String(e.getUTCSeconds()).padStart(2,"0"),a=e.getUTCMilliseconds();return`${t}-${n}-${r}T${i}:${s}:${o}.${String(1e3*a*1e3).padStart(9,"0")}Z`}!function(e){let t;e.codec=()=>(null==t&&(t=Xp((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:Jn(0),value:Jn(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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(Xv||(Xv={}));class uw{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 Xv.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:aw(this.timeReceived)}}static deserialize(e){const t=Xv.decode(e);return new uw(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),o=parseInt(n[4],10),a=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,o,a,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 uw(e.key,e.value,t)}}function dw(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=Sh(e),{value:i,done:s}=r.next();if(!0===s)return function*(){}();const o=t(i,n++);if("function"==typeof o.then)return async function*(){yield await o;for(const e of r)yield t(e,n++)}();const a=t;return function*(){yield o;for(const e of r)yield a(e,n++)}()}class cw extends Error{constructor(e="Query error"){super(e),this.name="QueryError"}}class lw extends Error{constructor(e="Invalid record"){super(e),this.name="InvalidRecordError"}}class pw extends Error{constructor(e="No selector function configured for prefix"){super(e),this.name="MissingSelectorError"}}function hw(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 fw(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 mw(e,t={}){const n={...e,name:"FINAL_PEER",type:2};return t.onProgress?.(new CustomEvent("kad-dht:query:final-peer",{detail:n})),n}function yw(e,t={}){const n={...e,name:"QUERY_ERROR",type:3};return t.onProgress?.(new CustomEvent("kad-dht:query:query-error",{detail:n})),n}function bw(e,t={}){const n={...e,name:"PROVIDER",type:4};return t.onProgress?.(new CustomEvent("kad-dht:query:provider",{detail:n})),n}function gw(e,t={}){const n={...e,name:"VALUE",type:5};return t.onProgress?.(new CustomEvent("kad-dht:query:value",{detail:n})),n}function vw(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=Xp((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=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(ew||(ew={})),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"}(tw||(tw={})),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"}(nw||(nw={})),function(e){e.codec=()=>Zp(nw)}(tw||(tw={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(rw||(rw={})),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"}(iw||(iw={})),function(e){e.codec=()=>Zp(iw)}(rw||(rw={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((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),rw.codec().encode(e.connection,t)),!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={id:Jn(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 eh('Decode error - map field "multiaddrs" had too many elements');r.multiaddrs.push(e.bytes());break;case 3:r.connection=rw.codec().decode(e);break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(sw||(sw={})),function(e){let t;e.codec=()=>(null==t&&(t=Xp((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.type&&0!==nw[e.type]&&(t.uint32(8),tw.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),sw.codec().encode(n,t);if(null!=e.providers)for(const n of e.providers)t.uint32(74),sw.codec().encode(n,t);!1!==n.lengthDelimited&&t.ldelim()},(e,t,n={})=>{const r={type:tw.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=tw.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 eh('Decode error - map field "closer" had too many elements');r.closer.push(sw.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 eh('Decode error - map field "providers" had too many elements');r.providers.push(sw.codec().decode(e,e.uint32(),{limits:n.limits?.providers$}));break;default:e.skipType(7&t)}}return r})),t),e.encode=t=>Gp(t,e.codec()),e.decode=(t,n)=>Mp(t,e.codec(),n)}(ow||(ow={}));const ww={pk:function(e,t){return 0}};async function Tw(e,t,n){const r=t.key,i=Dr(r).split("/");if(i.length<3)return;const s=e[i[1].toString()];if(null==s)throw new dt(`No validator available for key type "${i[1]}"`);await s(r,t.value,n)}const Pw={pk:async(e,t,n)=>{if(!(e instanceof Uint8Array))throw new dt('"key" must be a Uint8Array');if(e.byteLength<5)throw new dt("Invalid public key record");if("/pk/"!==Dr(e.subarray(0,4)))throw new dt("key was not prefixed with /pk/");const r=Ka(t);if(!Yn(e.slice(4),r.toMultihash().bytes))throw new dt("public key does not match passed in key")}},xw=Ir("/pk/");function Ew(e){return{...e,multiaddrs:e.multiaddrs.filter(e=>!$d(e))}}function Sw(e){return e}async function Aw(e,t){const n=await xr.digest(e);return t?.signal?.throwIfAborted(),n.digest}async function kw(e,t){return Aw(e.toMultihash().bytes,t)}function Cw(e,t){return new ch(`${e}/${Dr(t,"base32")}`,!1)}function Iw(e,t){const n=new Date;return new uw(e,t,n).serialize()}function Dw(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:zn.createV1(85,Bn(Ir(r,"base32"))),peerId:eu(n)}}function Mw(e,t,n){const r=[e,"string"==typeof t?t:Dr(t.multihash.bytes,"base32")];return null!=n&&r.push(n.toString()),new ch(r.join("/"))}function Fw(e){return new Date(_o(e))}function Rw(e,t,n){return async function*(...r){const i=t.queryTime?.timer(n),s=t.errorTime?.timer(n);let o=!1;try{t.queries?.increment({[n]:!0}),yield*e(...r)}catch(e){throw o=!0,s?.(),t.errors?.increment({[n]:!0}),e}finally{t.queries?.decrement({[n]:!0}),o||i?.()}}}function Lw(e,t,n){return async function(...r){const i=t?.queryTime?.timer(n),s=t?.errorTime?.timer(n);let o=!1;try{return t.queries?.increment({[n]:!0}),await e(...r)}catch(e){throw o=!0,s?.(),t.errors?.increment({[n]:!0}),e}finally{t.queries?.decrement({[n]:!0}),o||i?.()}}}class _w{log;components;validators;selectors;peerRouting;queryManager;network;datastorePrefix;constructor(e,t){const{validators:n,selectors:r,peerRouting:i,queryManager:s,network:o,logPrefix:a}=t;this.components=e,this.log=e.logger.forComponent(`${a}:content-fetching`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n,this.selectors=r,this.peerRouting=i,this.queryManager=s,this.network=o,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=Cw(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=uw.deserialize(r);return await Tw(this.validators,i,t),i}async*sendCorrectionRecord(e,t,n,r){this.log("sendCorrection for %b",e);const i=Iw(e,n);for(const{value:s,from:o}of t){if(Yn(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(o)){try{const t=Cw(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 a={type:tw.PUT_VALUE,key:e,record:i};for await(const e of this.network.sendRequest(o,a,r))"PEER_RESPONSE"===e.name&&null!=e.record&&Yn(e.record.value,uw.deserialize(i).value)&&(t=!0),yield e;if(!t)throw new cw("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=Iw(e,t),i=Cw(this.datastorePrefix,e);this.log(`storing record for key ${i.toString()}`),await this.components.datastore.put(i,r.subarray(),n),yield*gc(this.peerRouting.getClosestPeers(e,{...n,signal:n.signal}),t=>dw(t,t=>async()=>{if("FINAL_PEER"!==t.name)return[t];const i=[],s={type:tw.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&&Yn(e.record.value,uw.deserialize(r).value)||i.push(yw({from:t.peer.id,error:new cw("Value not put correctly"),path:e.path},n)));return i}),e=>qm(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 dt("No records given");const r=Dr(t).split("/");if(r.length<3)throw new dt("Record key does not have a selector function");const i=e[r[1].toString()];if(null==i)throw new pw(`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 bt("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 gw({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 o of n.peerRouting.getValueOrPeers(r.id,e,{...t,signal:i,path:s}))yield o,"PEER_RESPONSE"===o.name&&null!=o.record&&(yield gw({from:r.id,value:o.record.value,path:s},t))},t)}}function Nw(e,t){const n={id:e.id.toMultihash().bytes,multiaddrs:(e.multiaddrs??[]).map(e=>e.bytes),connection:t};return n}function Ow(e){if(null==e.id)throw new Error("Invalid peer in message");return{id:nu(Bn(e.id)),multiaddrs:(e.multiaddrs??[]).map(e=>Uu(e))}}class Bw{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){const{network:n,peerRouting:r,queryManager:i,routingTable:s,providers:o,logPrefix:a}=t;this.components=e,this.log=e.logger.forComponent(`${a}:content-routing`),this.network=n,this.peerRouting=r,this.queryManager=i,this.routingTable=s,this.providers=o,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:tw.ADD_PROVIDER,key:r,providers:[Nw({id:this.components.peerId,multiaddrs:t})]};let s=0;const o=this,a=Wd({objectMode:!0}),u=new ac({concurrency:10});u.addEventListener("idle",()=>{a.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))a.push(e),"FINAL_PEER"===e.name&&t.push(e);t.forEach(t=>{u.add(async()=>{for await(const r of async function*(t){try{o.log("sending provider record for %s to %p",e,t.peer.id);for await(const r of o.network.sendMessage(t.peer.id,i,{...n,path:t.path}))"PEER_RESPONSE"===r.name&&(o.log("sent provider record for %s to %p",e,t.peer.id),s++),yield r}catch(e){o.log.error("error sending provide record to peer %p - %e",t.peer.id,e),yield yw({from:t.peer.id,error:e,path:t.path},n)}}(t))a.push(r)}).catch(e=>{this.log.error("error publishing provider record to peer - %e",e)})})}).catch(e=>{a.end(e)}),yield*a,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 o=await this.providers.getProviders(e,t);if(o.length>0){const e=[];for(const r of o.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 fw({from:this.components.peerId,messageType:tw.GET_PROVIDERS,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),yield bw({from:this.components.peerId,providers:e,path:{index:-1,queued:0,running:0,total:0}},t),r+=e.length,r>=n)return}const a=async function*({peer:e,signal:n,path:r}){const o={type:tw.GET_PROVIDERS,key:i};yield*s.network.sendRequest(e.id,o,{...t,signal:n,path:r})},u=new md(o);for await(const s of this.queryManager.run(i,a,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 bw({from:s.from,providers:i,path:s.path},t),r+=i.length,r>=n))return}}}class Uw extends Wt{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 mc({...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 dt("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 vw({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 hw({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 fw({from:e,messageType:s.type,closer:s.closer.map(Ow),providers:s.providers.map(Ow),record:null==s.record?void 0:uw.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 yw({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 dt("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 vw({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 hw({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 fw({from:e,messageType:r,path:n.path},n)}catch(t){this.metrics.errors?.increment({[r]:!0}),i?.abort(t),yield yw({from:e,error:t,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async _writeMessage(e,t,n){const r=Mc(e);await r.write(t,ow,n)}async _writeReadMessage(e,t,n){const r=Mc(e);await r.write(t,ow,n);const i=await r.read(ow,n);return i.closer.forEach(e=>{this.safeDispatchEvent("peer",{detail:Ow(e)})}),i.providers.forEach(e=>{this.safeDispatchEvent("peer",{detail:Ow(e)})}),i}}function jw(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 qw{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 kw(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:_b(this.originDhtKey,t),path:n};if(this.peerDistances.length===this.capacity){const e=this.peerDistances[this.peerDistances.length-1];if(null!=e&&-1!==jw(r.distance,e.distance))return}let i=!1;for(let e=0;e<this.peerDistances.length;e++){const t=jw(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===jw(_b(await kw(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 $w{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:tw.GET_VALUE,key:t};yield*this.network.sendRequest(e,r,n)}async*getPublicKeyFromNode(e,t={}){const n=Xn([xw,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=tu(Ka(i.record.value));if(!n.equals(e))throw new ct("public key does not match id");if(null==n.publicKey)throw new ct("public key missing");yield gw({from:e,value:i.record.value,path:r},t)}throw new cw(`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 mw({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 o={type:tw.FIND_NODE,key:e.toMultihash().bytes};for await(const a of r.network.sendRequest(n.id,o,{...t,signal:i,path:s}))if(yield a,"PEER_RESPONSE"===a.name){const n=a.closer.find(t=>t.id.equals(e));null!=n&&(yield mw({from:a.from,peer:n,path:a.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 bt("Not found")}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);const n=await Aw(e,t),r=new qw(n,this.routingTable.kBucketSize),i=this;yield*this.queryManager.run(e,async function*({peer:n,path:s,peerKadId:o,signal:a}){i.log("getClosestPeers asking %p",n.id);const u={type:tw.FIND_NODE,key:e};yield*i.network.sendRequest(n.id,u,{...t,signal:a,path:s}),r.addWithKadId(n,o,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 mw({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 yw({from:r.from,error:new cw(t),path:n.path},n);continue}yield r}}async _verifyRecordOnline(e,t){if(null==e.timeReceived)throw new lw("invalid record received");await Tw(this.validators,new uw(e.key,e.value,e.timeReceived),t)}async getClosestPeersOffline(e,t){const n=[];try{const r=nu(Bn(e)),i=await this.components.peerStore.get(r,t);n.push({id:i.id,multiaddrs:i.addresses.map(({multiaddr:e})=>e)})}catch{}const r=await Aw(e,t),i=this.routingTable.closestPeers(r,t);for(const e of i)try{n.push(await this.components.peerStore.getInfo(e,t))}catch(e){if("NotFoundError"!==e.name)throw e}return n.length>0?this.log("getClosestPeersOffline returning the %d closest peer(s) we know to %b",n.length,e):this.log("getClosestPeersOffline could not any peers close to %b with %d peers in the routing table",e,this.routingTable.size),n}}class zw{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=Mw(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=Mw(this.datastorePrefix,e,t),i=Lo(n?.time?.getTime()??Date.now());await this.datastore.put(r,i,n)}async loadProviders(e,t){const n=new fd,r=Mw(this.datastorePrefix,e);for await(const e of this.datastore.query({prefix:r.toString()},t)){const{peerId:t}=Dw(e.key);n.set(t,Fw(e.value))}return n}}async function*Vw(e){const{key:t,startingPeers:n,ourPeerId:r,query:i,alpha:s,path:o,numPaths:a,log:u,peersSeen:d,connectionManager:c,signal:l}=e,p=Wd({objectMode:!0}),h=new ac({concurrency:s,sort:(e,t)=>jw(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:o,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 ot)};l.addEventListener("abort",f);try{const y=await Aw(t,{signal:l});function m(n,s){if(null==n)return;d.add(n.id.toMultihash().bytes);const f=_b(s,y);h.add(async()=>{try{for await(const b of i({...e,key:t,peer:n,path:{index:o,queued:h.queued,running:h.running,total:h.size},numPaths:a,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 kw(e.id,{signal:l});-1===jw(_b(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:o,queued:h.queued,running:h.running,total:h.size}})}}catch(t){p.push(yw({from:n.id,error:t,path:{index:o,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 kw(e,{signal:l}))})),yield*p}finally{l.removeEventListener("abort",f)}}class Gw{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=hc([this.shutDownController.signal,r.signal,n.signal]),s=this.logger.forComponent(`${this.logPrefix}:query:`+Dr(e,"base58btc"));let o=!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 Yd(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 ic(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),s("query:start");const r=await Aw(e,{signal:i}),a=this.routingTable.closestPeers(r,{count:this.routingTable.kBucketSize}),u=a.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===a.length)return void s.error("running query with no peers");const d=kd(1024),c=u.map((r,o)=>Vw({...n,key:e,startingPeers:r,ourPeerId:this.peerId,signal:i,query:t,path:o,numPaths:u.length,alpha:this.alpha,log:s,peersSeen:d,onProgress:n.onProgress,connectionManager:this.connectionManager}));for await(const e of bc(...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}o=!0}catch(e){if(this.running)throw e}finally{o||(s("query exited early"),r.abort()),i.clear(),s("query finished")}}}function Kw(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 Ww{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=Lw(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=zd(),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=hc(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 gc(this.peerRouting.getClosestPeers(this.peerId.toMultihash().bytes,{signal:t,isSelfQuery:!0}),e=>Ch(e,this.count),async e=>Kw(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 Hw extends Wt{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 ac({concurrency:t.concurrency??10,metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_queue`}),this.reprovideTimeout=new mc({...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??Qv,this.interval=t.interval??Yv,this.contentRouting=t.contentRouting,this.running=!1,this.reprovide=Lw(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(Jv)}).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}=Dw(t.key),i=Fw(t.value).getTime()+this.validity,s=Date.now(),o=s>i,a=this.peerId.equals(r);this.log.trace("comparing: %d (now) < %d (expires) = %s %s",s,i,o,o?"(expired)":"(valid)"),o&&!a&&await this.datastore.delete(t.key,e),this.shouldReprovide(a,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(Jv)}).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 Eh(this.contentRouting.provide(e,this.addressManager.getAddresses(),t))}}class Qw{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 md,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}async start(){if(this.running)return;this.running=!0;const e=await kw(this.components.peerId);this.newPeers=new qw(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 md(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},[Zv]:{value:1}}})}),...[...n].map(async e=>{await this.components.peerStore.merge(e,{tags:{[this.closeTagName]:void 0,[Zv]:void 0}})})])}}function Yw(e){return Array.isArray(e?.peers)}class Jw{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??Xw,this.kBucketSize=t.kBucketSize??Zw,this.splitThreshold=t.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=t.numberOfOldContactsToPing??eT,this.lastPingThreshold=t.lastPingThreshold??nT,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=Qc({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 kw(e,t),lastPing:Date.now()}}async add(e,t){const n={peerId:e,kadId:await kw(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 qw(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*dw(n.peers,({peer:e})=>e.id)}count(){return function e(t){if(Yw(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){Yw(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+Dr(_b(e,t),"base16"))}_determineBucket(e){const t=Dr(e,"base2");return function e(n,r=0){return Yw(n)?n:e("0"===t[r]?n.left:n.right,r+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex(e=>Yn(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"===Dr(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 Zw=20,Xw=6,eT=3,tT="kad-peer",nT=6e5;class rT extends Wt{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??Zw,this.running=!1,this.protocol=t.protocol,this.network=t.network,this.peerTagName=t.peerTagName??tT,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 Uc({concurrency:t.pingOldContactConcurrency??20,metricName:`${t.metricsPrefix}_ping_old_contact_queue`,metrics:this.components.metrics,maxSize:t.pingOldContactMaxQueueSize??100}),this.pingOldContactTimeout=new mc({...t.pingOldContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_old_contact_time_milliseconds`}),this.pingNewContactQueue=new Uc({concurrency:t.pingNewContactConcurrency??20,metricName:`${t.metricsPrefix}_ping_new_contact_queue`,metrics:this.components.metrics,maxSize:t.pingNewContactMaxQueueSize??100}),this.pingNewContactTimeout=new mc({...t.pingNewContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_new_contact_time_milliseconds`}),this.kb=new Jw(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 Qw(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 zt(this.closestPeerTagger,this.kb))}async afterStart(){let e=0;Promise.resolve().then(async()=>{if(!this.populateFromDatastoreOnStart)return;const t=hc([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(tT)],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 Vt(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=hc([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 qm(n))null!=e&&(yield e)}async verifyNewContact(e,t){const n=this.pingNewContactTimeout.getTimeoutSignal(),r=hc([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 kw(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 kw(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(o){if(Yw(o))return o.depth>n&&(n=o.depth),t++,e+=o.peers.length,o.peers.length<r&&(r=o.peers.length),void(o.peers.length>i&&(i=o.peers.length));s(o.left),s(o.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 iT,sT=[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 oT{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e,t){const{peerRouting:n,routingTable:r,refreshInterval:i,refreshQueryTimeout:s,logPrefix:o}=t;this.log=e.logger.forComponent(`${o}: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=hc([r?.signal,AbortSignal.timeout(this.refreshQueryTimeout)]);try{const t=await Kw(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=wa(2);return nu(Bn(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=sT[(r^32768>>n)&i|t&~i],o=new ArrayBuffer(34),a=new DataView(o,0,o.byteLength);return a.setUint8(0,xr.code),a.setUint8(1,32),a.setUint32(2,s,!1),new Uint8Array(a.buffer,a.byteOffset,a.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=_b(this.routingTable.kb.localPeer.kadId,e);let n=0;for(const e of t){if(0!==e)break;n++}yield n}}}class aT{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 xt("Missing key");let n;try{n=zn.decode(t.key)}catch(e){throw new xt("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=nu(Bn(t.id)),i=t.multiaddrs.map(e=>Uu(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 uT{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 xt("Invalid FIND_NODE message received - key was missing");const n=await this.peerRouting.getClosestPeersOffline(t.key,{exclude:[e,this.peerId]});Yn(this.peerId.toMultihash().bytes,t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map(e=>e.decapsulateCode(mu))});const r={type:tw.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 dT{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 xt("Invalid GET_PROVIDERS message received - key was missing");let n;try{n=zn.decode(t.key)}catch(e){throw new xt("Invalid CID")}this.log("%p asking for providers for %s",e,n);const[r,i]=await Promise.all([Ol(dw(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:tw.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 cT{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 xt("Invalid key");const r={type:tw.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===Dr(e.subarray(0,4))}(n)){this.log("is public key");const e=function(e){return nu(Bn(e.subarray(4)))}(n);let t;try{const n=await this.peerStore.get(e);if(null==n.id.publicKey)throw new bt("No public key found in key book");t=Wa(n.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=t)return this.log("returning found public key"),r.record=new uw(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=Cw(this.datastorePrefix,e);let n;try{n=await this.datastore.get(t)}catch(e){if("NotFoundError"===e.name)return;throw e}const r=uw.deserialize(n);if(!(null==r.timeReceived||Date.now()-r.timeReceived.getTime()>Qv))return r;await this.datastore.delete(t)}}class lT{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 pT{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 xt(`Empty record from: ${e}`);try{const e=uw.deserialize(t.record);await Tw(this.validators,e),e.timeReceived=new Date;const r=Cw(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 hT{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={[tw.GET_VALUE.toString()]:new cT(e,t),[tw.PUT_VALUE.toString()]:new pT(e,t),[tw.FIND_NODE.toString()]:new uT(e,t),[tw.ADD_PROVIDER.toString()]:new aT(e,t),[tw.GET_PROVIDERS.toString()]:new dT(e,t),[tw.PING.toString()]:new lT(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 St)};let r=AbortSignal.timeout(this.incomingMessageTimeout);r.addEventListener("abort",n);const i=Mc(e).pb(ow);for(;;){if("readable"!==e.readStatus){await e.close({signal:r});break}const s=await i.read({signal:r}),o=this.metrics?.rpcTime?.timer(s.type.toString()),a=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,a?.(),e}finally{u||o?.()}r.removeEventListener("abort",n),r=AbortSignal.timeout(this.incomingMessageTimeout),r.addEventListener("abort",n)}}}class fT extends Wt{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 mT{dht;constructor(e){this.dht=e}async provide(e,t={}){await Eh(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 Eh(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 bt("Could not find value for key")}}class yT{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 bt("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 bT extends Wt{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??Zw,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??Ew,this.onPeerConnectTimeout=t.onPeerConnectTimeout??1e4,this.providers=new zw(e,{...t.providers,logPrefix:n,datastorePrefix:r}),this.validators={...Pw,...t.validators},this.selectors={...ww,...t.selectors},this.network=new Uw(e,{protocol:this.protocol,logPrefix:n,metricsPrefix:i}),this.routingTable=new rT(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 o=zd();!0===t.allowQueryWithZeroPeers&&o.resolve(),this.queryManager=new Gw(e,{disjointPaths:this.d,alpha:this.a,logPrefix:n,metricsPrefix:i,initialQuerySelfHasRun:o,routingTable:this.routingTable,allowQueryWithZeroPeers:t.allowQueryWithZeroPeers}),this.peerRouting=new $w(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:n}),this.contentFetching=new _w(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:n,datastorePrefix:r}),this.contentRouting=new Bw(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:n}),this.routingTableRefresh=new oT(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:n}),this.rpc=new hT(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 fT(e,{protocol:this.protocol,logPrefix:n}),this.querySelf=new Ww(e,{peerRouting:this.peerRouting,interval:t.querySelfInterval,initialInterval:t.initialQuerySelfInterval,logPrefix:n,initialQuerySelfHasRun:o,operationMetrics:s}),this.reprovider=new Hw(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 yT(this),this.dhtContentRouting=new mT(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})=>!$d(e)&&!mf.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=Rw(this.get.bind(this),s,"GET_VALUE"),this.findProviders=Rw(this.findProviders.bind(this),s,"FIND_PROVIDERS"),this.findPeer=Rw(this.findPeer.bind(this),s,"FIND_PEER"),this.getClosestPeers=Rw(this.getClosestPeers.bind(this),s,"GET_CLOSEST_PEERS"),this.provide=Rw(this.provide.bind(this),s,"PROVIDE"),this.put=Rw(this.put.bind(this),s,"PUT_VALUE")}[Symbol.toStringTag]="@libp2p/kad-dht";[Ht]=["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery","@libp2p/kad-dht"];[Qt]=["@libp2p/identify","@libp2p/ping"];get[st](){return this.dhtContentRouting}get[jt](){return this.dhtPeerRouting}get[Ot](){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 zt(this.routingTable,this.queryManager,this.network,this.topologyListener,this.routingTableRefresh,this.reprovider),await zt(this.querySelf))}async stop(){this.running=!1,await Vt(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 gT(e={}){return t=>new bT(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"}(iT||(iT={}));class vT{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";[Ht]=["@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 St("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 Yd(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=wa(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 rr,o=a=>{if(s.append(a.data),32===s.byteLength){r.removeEventListener("message",o);const a=Date.now()-e;Promise.all([r.closeRead(t)]).then(()=>{if(!Yn(n,s.subarray()))throw new Et(`Received wrong ping ack after ${a}ms`);i.resolve(a)}).catch(e=>{r.abort(e),i.reject(e)})}};return r.addEventListener("message",o),r.send(n),await r.close(t),await ic(i.promise,t.signal)}catch(t){throw i.error("error while pinging %o - %e",e,t),r?.abort(t),t}finally{r?.close()}}}function wT(e={}){return t=>new vT(t,e)}function TT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function PT(e,t,n){if(!e.s){if(n instanceof xT){if(!n.s)return void(n.o=PT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(PT.bind(null,e,t),PT.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var xT=/*#__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{PT(r,1,s(this.v))}catch(e){PT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?PT(r,1,t?t(i):i):n?PT(r,1,n(i)):PT(r,2,i)}catch(e){PT(r,2,e)}},r},e}();function ET(e){return e instanceof xT&&1&e.s}function ST(e,t,n){for(var r;;){var i=e();if(ET(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then){if(!ET(s)){r=1;break}s=s.s}if(t){var o=t();if(o&&o.then&&!ET(o)){r=2;break}}}var a=new xT,u=PT.bind(null,a,2);return(0===r?i.then(c):1===r?s.then(d):o.then(l)).then(void 0,u),a;function d(r){s=r;do{if(t&&(o=t())&&o.then&&!ET(o))return void o.then(l).then(void 0,u);if(!(i=e())||ET(i)&&!i.v)return void PT(a,1,s);if(i.then)return void i.then(c).then(void 0,u);ET(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):PT(a,1,s)}function l(){(i=e())?i.then?i.then(c).then(void 0,u):c(i):PT(a,1,s)}}function AT(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}var kT="/ocean/nodes/1.0.0",CT=1e4,IT=["/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"],DT=/*#__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 o(o){var a;if(s)return o;function u(t){if(a)return t;throw new Error("No multiaddrs found for peer id "+e)}var d,c=i.services.dht,l=!1,p=!1,h=AT(function(){return TT(function(){return t=C(c.findPeer(eu(e),{signal:AbortSignal.timeout(2e4)})),ST(function(){function e(e){return!a&&(l=!(n=e).done)}return a?!!e(!a&&t.next()):Promise.resolve(!a&&t.next()).then(e)},function(){return!!(l=!1)},function(){var e=n.value;if(e.type===iT.FINAL_PEER&&e.peer.multiaddrs.length>0){var t=e.peer.multiaddrs[0].toString(),i=r(t);return a=1,i}})},function(e){p=!0,d=e})},function(e,n){function r(t){if(a)return t;if(e)throw n;return n}var i=AT(function(){var e=function(){if(l&&null!=t.return)return Promise.resolve(t.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,t){if(p)throw d;if(e)throw t;return t});return i&&i.then?i.then(r):r(i)});return h&&h.then?h.then(u):u(h)}var a=i.getConnections().find(function(t){return t.remotePeer.toString()===e});if(null!=a&&a.remoteAddr){var u=a.remoteAddr.toString();return r(u)}var d=TT(function(){return Promise.resolve(i.peerStore.get(eu(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(o):o(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:IT).map(Uu);return Promise.resolve(async function(e={}){e.privateKey??=await async function(){return async function(){const{privateKey:e,publicKey:t}=function(){const e=lo.utils.randomSecretKey(),t=lo.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 vo(e,t)}()}();const t=new ny({...await Gu(e),peerId:(n=e.privateKey,tu(n.publicKey))});var n;return!1!==e.start&&await t.start(),t}(F({addresses:{listen:[]},transports:[kg(),Bv()].concat(t.p2pConfig.enableTcp?[Ig()]:[]),connectionEncrypters:[eg()],streamMuxers:[bg()],peerDiscovery:[].concat(n.length>0?[(r={list:n.map(String),timeout:1e4},e=>new Uv(e,r))]:[]),services:{identify:Kv(),identifyPush:Wv(),ping:wT(),dht:gT({peerInfoMapper:Sw,allowQueryWithZeroPeers:!1,kBucketSize:20,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){q.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=M(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.cidFromRawString=function(e){try{return Promise.resolve(xr.digest(Ir(e))).then(function(e){return zn.create(1,85,e)})}catch(e){return Promise.reject(e)}},t.getProvidersForString=function(e,t){try{var n,r,i=this;return Promise.resolve(i.getOrCreateLibp2pNode()).then(function(s){return Promise.resolve(i.cidFromRawString(e)).then(function(e){function i(e){return o.map(function(e){return{id:e.id.toString(),multiaddrs:e.multiaddrs}})}var o=[],a=TT(function(){var i,a=!1,u=!1;return AT(function(){return TT(function(){n=C(s.contentRouting.findProviders(e,{useCache:!1,useNetwork:!0,signal:t}));var i=ST(function(){return Promise.resolve(n.next()).then(function(e){return a=!(r=e).done})},function(){return!!(a=!1)},function(){o.push(r.value)});if(i&&i.then)return i.then(function(){})},function(e){u=!0,i=e})},function(e,t){function r(n){if(e)throw t;return t}var s=AT(function(){var e=function(){if(a&&null!=n.return)return Promise.resolve(n.return()).then(function(){})}();if(e&&e.then)return e.then(function(){})},function(e,t){if(u)throw i;if(e)throw t;return t});return s&&s.then?s.then(r):r()})},function(){});return a&&a.then?a.then(i):i()})})}catch(e){return Promise.reject(e)}},t.isDialable=function(e){return"undefined"==typeof window||e.toString().includes("/tls/sni")},t.isNotP2PCircuit=function(e){return!/\/p2p-circuit(\/|$)/.test(e.toString())},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,n){void 0===n&&(n=!1);try{var r=this;return Promise.resolve(r.getOrCreateLibp2pNode()).then(function(i){function s(){function e(){var e=u.filter(function(e){return r.isDialable(e)}),s=e.length;n||(e=e.filter(function(e){return r.isNotP2PCircuit(e)}));var o=e.length;if(e.length<1){if(!n&&o<s)return r.getConnection({nodeId:a?a.toString():"",multiaddress:u},t,!0);throw new Error("No valid multiaddresses, cannot connect")}return a&&(e=e.map(function(e){var t=e.toString();return t.includes("/p2p/")?e:Uu(t+"/p2p/"+a.toString())})),TT(function(){return Promise.resolve(i.dial(e,{signal:t})).then(function(e){return q.debug("[P2P] Dial SUCCESS via "+e.remoteAddr+" (limited="+(null!=e.limits)+")"),e})},function(e){var d;if(!n&&o<s)return q.debug("[P2P] Direct dial failed, falling back to relayed addresses..."),r.getConnection({nodeId:a?a.toString():"",multiaddress:u},t,!0);throw new Error("Cannot dial peer "+(null==(d=a)?void 0:d.toString())+". "+(u.length>0?"Found addrs: "+u.map(String).join(", ")+". ":"No addresses found. ")+"Active connections: "+i.getConnections().length+". "+e.message)})}var s=function(){if(!o()&&a){var e=TT(function(){return Promise.resolve(i.peerRouting.findPeer(a,{signal:t})).then(function(e){for(var t,n=M(e.multiaddrs);!(t=n()).done;)u.push(t.value);q.debug("[P2P] "+a.toString()+": DHT returned "+e.multiaddrs.length+" addrs")})},function(e){q.debug("[P2P] "+a.toString()+": DHT findPeer failed: "+e.message)});if(e&&e.then)return e.then(function(){})}}();return s&&s.then?s.then(e):e()}var o=function(){return u.some(function(e){return r.isDialable(e)})},a=null,u=[];if(e&&"string"==typeof e){try{var d=Uu(e);if(u.push(d),!a){var c=r.peerIdFromMultiaddr(d);c&&(a=eu(c))}}catch(e){}try{a||(a=eu(e))}catch(e){}}if("object"==typeof e&&null!==e&&!Array.isArray(e))if("nodeId"in e||"multiaddress"in e){var l=e;if(Array.isArray(l.multiaddress)&&l.multiaddress.length>0)for(var p,h=M(l.multiaddress);!(p=h()).done;)u.push(p.value);if(l.nodeId)try{a=eu(l.nodeId)}catch(e){}}else a=e;if(a){var f=i.getConnections(a).filter(function(e){return"open"===e.status});if(f.length>0)return q.debug("[P2P] "+a.toString()+": reusing existing connection via "+f[0].remoteAddr),f[0]}var m=function(){if(!o()&&a){var e=TT(function(){return Promise.resolve(i.peerStore.get(a)).then(function(e){if(null!=e&&e.addresses){for(var t,n=M(e.addresses);!(t=n()).done;)u.push(t.value.multiaddr);q.debug("[P2P] "+a.toString()+": "+e.addresses.length+" peerStore addrs")}})},function(){q.debug("[P2P] "+a.toString()+": not in peerStore")});if(e&&e.then)return e.then(function(){})}}();return m&&m.then?m.then(s):s()})}catch(e){return Promise.reject(e)}},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 RT(e)},t.getSignedCommandParams=function(e,t,n,r){try{var i,s=function(s){return i?s:Promise.resolve(FT(t)).then(function(i){return Promise.resolve(o.getNonce(e,i,r)).then(function(e){var r=(e+1).toString();return Promise.resolve(MT(t,r,n)).then(function(e){return{consumerAddress:i,nonce:r,signature:e}})})})},o=this;if(LT(t))return Promise.resolve({consumerAddress:t.consumerAddress,nonce:t.nonce,signature:t.signature});var a=function(){if("string"==typeof t)return Promise.resolve(FT(t)).then(function(e){return i=1,{consumerAddress:e,nonce:void 0,signature:void 0}})}();return Promise.resolve(a&&a.then?a.then(s):s(a))}catch(e){return Promise.reject(e)}},t.dialAndStream=function(e,t,n,r){try{var i,s=this,o=null!=n?n:AbortSignal.timeout(null!=(i=s.p2pConfig.dialTimeout)?i:CT);return Promise.resolve(s.getConnection(e,o)).then(function(e){return TT(function(){return Promise.resolve(e.newStream(kT,{signal:o,runOnLimitedConnection:!0})).then(function(n){var i=Dc(n),a=t;return r&&(a=F({},t,{p2pStreamBody:!0})),Promise.resolve(i.write((new TextEncoder).encode(JSON.stringify(a)),{signal:o})).then(function(){function t(){return Promise.resolve(n.close()).then(function(){return Promise.resolve(i.read({signal:o})).then(function(t){var n=s.toUint8Array(t);return{lp:i,firstBytes:n,connection:e}})})}var a=function(){if(r)return Promise.resolve(function(e,t,n){try{var r,i,s,o=function(t){return Promise.resolve(e.write(new Uint8Array(0),{signal:n})).then(function(){})},a=!1,u=!1,d=AT(function(){return TT(function(){r=C(t);var s=ST(function(){return Promise.resolve(r.next()).then(function(e){return a=!(i=e).done})},function(){return!!(a=!1)},function(){return Promise.resolve(e.write(function(e){if(e instanceof Uint8Array)return e;if("string"==typeof e)return(new TextEncoder).encode(e);if(e&&"object"==typeof e&&ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type for P2P request body")}(i.value),{signal:n})).then(function(){})});if(s&&s.then)return s.then(function(){})},function(e){u=!0,s=e})},function(e,t){function n(n){if(e)throw t;return t}var i=AT(function(){var e=function(){if(a&&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(o):o())}catch(e){return Promise.reject(e)}}(i,r,o)).then(function(){})}();return a&&a.then?a.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,o){void 0===s&&(s=0);try{var a=this;return Promise.resolve(TT(function(){var u=F({command:t,authorization:r?a.getAuthorization(r):void 0},n);return Promise.resolve(a.dialAndStream(e,u,i,o)).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=a.p2pConfig.maxRetries)?u:5))return Promise.resolve(new Promise(function(e){var t;return setTimeout(e,null!=(t=a.p2pConfig.retryDelay)?t:1e3)})).then(function(){var u=a.sendP2pCommand(e,t,n,r,i,s+1,o);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 N(/*#__PURE__*/L().mark(function e(){var t;return L().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,D(d.read({signal:AbortSignal.timeout(CT)}));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 ec){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))();var m=[c],y=TT(function(){var e=ST(function(){return!0},void 0,function(){var e;return Promise.resolve(d.read({signal:AbortSignal.timeout(null!=(e=a.p2pConfig.dialTimeout)?e:CT)})).then(function(e){m.push(a.toUint8Array(e))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof ec))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=a.p2pConfig.maxRetries)?u:5))return q.debug("[P2P] Stream reset/closed on attempt "+(s+1)+", retrying..."),Promise.resolve(et(1e3)).then(function(){var u=a.sendP2pCommand(e,t,n,r,i,s+1,o);return c=1,u})}();return h&&h.then?h.then(l):l(h)}))}catch(e){return Promise.reject(e)}},t.getEndpoints=function(e){try{var t=this;return Promise.resolve(TT(function(){return Promise.resolve(t.sendP2pCommand(e,E.STATUS,{}))},function(e){throw q.error("P2P getEndpoints (STATUS) failed:",e),e}))}catch(e){return Promise.reject(e)}},t.getNodeStatus=function(e,t){try{return Promise.resolve(this.getEndpoints(e))}catch(e){return Promise.reject(e)}},t.getNodeJobs=function(e,t,n){try{var r=this;return Promise.resolve(TT(function(){var i={};return t&&(i.fromTimestamp=t.toString()),Promise.resolve(r.sendP2pCommand(e,E.JOBS,i,null,n)).then(function(e){return Array.isArray(e)?e:[]})},function(e){return q.error("P2P getNodeJobs failed:",e),[]}))}catch(e){return Promise.reject(e)}},t.getNonce=function(e,t,n){try{var r=this;return Promise.resolve(TT(function(){return Promise.resolve(r.sendP2pCommand(e,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 q.error("P2P getNonce failed:",e),e}))}catch(e){return Promise.reject(e)}},t.encrypt=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.getSignedCommandParams(n,r,E.ENCRYPT,s)).then(function(i){return Promise.resolve(o.sendP2pCommand(n,E.ENCRYPT,{chainId:t,nonce:i.nonce,consumerAddress:i.consumerAddress,signature:i.signature,blob:"string"==typeof e?e:JSON.stringify(e)},r,s)).then(function(e){return o.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,o,a,u){try{var d={ddoId:e,serviceId:t,consumerAddress:r};return o&&(d.userdata=o),a&&(d.environment=a),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,o,a,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=$u(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:a},maxJobDuration:i,consumerAddress:o};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=$u(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,o,a){try{var u=this;return Promise.resolve(u.getSignedCommandParams(i,s,E.DOWNLOAD)).then(function(d){var c=d.consumerAddress,l=d.nonce,p=d.signature,h={command:E.DOWNLOAD,authorization:u.getAuthorization(s),fileIndex:n,documentId:e,transferTxId:r,serviceId:t,consumerAddress:c,nonce:l,signature:p};return o&&(h.policyServer=o),a&&(h.userData=a),Promise.resolve(u.dialAndStream(i,h)).then(function(e){var t=e.lp,r=e.firstBytes;function i(e){var t=qu(d);return{data:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),filename:"file"+n}}var s,o=(new TextDecoder).decode(r),a=null;try{a=JSON.parse(o)}catch(e){}if(a&&"number"==typeof a.httpStatus&&a.httpStatus>=400)throw new Error(null!=(s=a.error)?s:"P2P download error: "+a.httpStatus);var d=null===a?[new Uint8Array(r)]:[],c=TT(function(){var e=ST(function(){return!0},void 0,function(){var e;return Promise.resolve(t.read({signal:AbortSignal.timeout(null!=(e=u.p2pConfig.dialTimeout)?e:CT)})).then(function(e){d.push(new Uint8Array(u.toUint8Array(e)))})});if(e&&e.then)return e.then(function(){})},function(e){if(!(e instanceof ec))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,o,a,u,d,c,l,p,h,f,m,y){try{var b=this;return Promise.resolve(b.getSignedCommandParams(e,t,E.COMPUTE_START,h)).then(function(g){function v(){function n(){return y&&(w.outputBucketId=y),Promise.resolve(b.sendP2pCommand(e,E.COMPUTE_START,w,t,h)).then(function(e){return Array.isArray(e),e})}var r=function(){if(l)return Promise.resolve(b.getNodePublicKey(e)).then(function(e){e&&(w.output=$u(e,JSON.stringify(l)))})}();return r&&r.then?r.then(n):n()}var w={environment:n,dataset:r[0],datasets:r,algorithm:i,maxJobDuration:s,feeToken:o,resources:a,chainId:u,payment:{chainId:u,token:o,maxJobDuration:s,resources:a},consumerAddress:g.consumerAddress,nonce:g.nonce,signature:g.signature};d&&(w.metadata=d),c&&(w.additionalViewers=c),p&&(w.policyServer=p),f&&(w.queueMaxWaitTime=f);var T=function(){if(m)return Promise.resolve(b.getNodePublicKey(e)).then(function(e){e&&(w.encryptedDockerRegistryAuth=$u(e,JSON.stringify(m)))})}();return T&&T.then?T.then(v):v()})}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h){try{var f=this;return Promise.resolve(f.getSignedCommandParams(e,t,E.FREE_COMPUTE_START,c)).then(function(m){function y(){function n(){return h&&(b.outputBucketId=h),Promise.resolve(f.sendP2pCommand(e,E.FREE_COMPUTE_START,b,t,c)).then(function(e){return Array.isArray(e),e})}var r=function(){if(u)return Promise.resolve(f.getNodePublicKey(e)).then(function(e){e&&(b.output=$u(e,JSON.stringify(u)))})}();return r&&r.then?r.then(n):n()}var b={environment:n,dataset:r[0],datasets:r,algorithm:i,resources:s,consumerAddress:m.consumerAddress,nonce:m.nonce,signature:m.signature};o&&(b.metadata=o),a&&(b.additionalViewers=a),d&&(b.policyServer=d),l&&(b.queueMaxWaitTime=l);var g=function(){if(p)return Promise.resolve(f.getNodePublicKey(e)).then(function(e){e&&(b.encryptedDockerRegistryAuth=$u(e,JSON.stringify(p)))})}();return g&&g.then?g.then(y):y()})}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.getSignedCommandParams(e,t,E.COMPUTE_GET_STREAMABLE_LOGS,r)).then(function(s){return i.sendP2pCommand(e,E.COMPUTE_GET_STREAMABLE_LOGS,{jobId:n,consumerAddress:s.consumerAddress,nonce:s.nonce,signature:s.signature},t,r)})}catch(e){return Promise.reject(e)}},t.computeStop=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getSignedCommandParams(t,n,E.COMPUTE_STOP,i)).then(function(o){var a={jobId:e,consumerAddress:o.consumerAddress,nonce:o.nonce,signature:o.signature};return r&&(a.agreementId=r),s.sendP2pCommand(t,E.COMPUTE_STOP,a,n,i)})}catch(e){return Promise.reject(e)}},t.computeStatus=function(e,t,n,r,i){try{var s=this;return Promise.resolve(FT(t)).then(function(o){var a={consumerAddress:o};return n&&(a.jobId=n),r&&(a.agreementId=r),s.sendP2pCommand(e,E.COMPUTE_GET_STATUS,a,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.getSignedCommandParams(e,t,E.COMPUTE_GET_RESULT)).then(function(o){var a=o.nonce,u=o.signature,d={command:E.COMPUTE_GET_RESULT,jobId:n,index:r,offset:i,consumerAddress:o.consumerAddress};return"string"==typeof t?d.authorization=t:(d.nonce=a,d.signature=u),Promise.resolve(s.dialAndStream(e,d)).then(function(e){var t,n,r=e.lp,i=e.firstBytes,o=JSON.parse((new TextDecoder).decode(i));if("number"==typeof(null==o?void 0:o.httpStatus)&&o.httpStatus>=400)throw new Error(null!=(n=o.error)?n:"P2P compute result error: "+o.httpStatus);var a=null!=(t=s.p2pConfig.dialTimeout)?t:CT;return N(/*#__PURE__*/L().mark(function e(){var t;return L().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:e.prev=0;case 1:return e.next=4,D(r.read({signal:AbortSignal.timeout(a)}));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 ec){e.next=15;break}throw e.t0;case 15:case"end":return e.stop()}},e,null,[[0,11]])}))()})})}catch(e){return Promise.reject(e)}},t.getComputeResultUrl=function(e,t,n,r){try{var i=this;return Promise.resolve(FT(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 o=(s+1).toString();return Promise.resolve(MT(e,o,E.CREATE_AUTH_TOKEN)).then(function(e){return Promise.resolve(r.sendP2pCommand(t,E.CREATE_AUTH_TOKEN,{address:i,signature:e,nonce:o},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,s){try{return Promise.resolve(this.sendP2pCommand(r,E.CREATE_AUTH_TOKEN,{address:e,signature:t,nonce:n,validUntil:i},null,s)).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(i.getSignedCommandParams(e,n,E.VALIDATE_DDO,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.VALIDATE_DDO,{ddo:t,publisherAddress:s.consumerAddress,nonce:s.nonce,signature:s.signature},n,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(o){var a=(o+1).toString();return Promise.resolve(nt(e,s+a)).then(function(e){return i.sendP2pCommand(n,E.INVALIDATE_AUTH_TOKEN,{address:s,signature:e,token:t,nonce:a},null,r)})})})}catch(e){return Promise.reject(e)}},t.isValidProvider=function(e,t){var n=this;return Promise.resolve(TT(function(){return Promise.resolve(n.sendP2pCommand(e,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,F({},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,F({},t),null,n))}catch(e){return Promise.reject(e)}},t.downloadNodeLogs=function(e,t,n,r,i,s,o,a,u){try{var d=this;return Promise.resolve(d.getSignedCommandParams(e,t,E.GET_LOGS,u)).then(function(c){var l={startTime:n,endTime:r,signature:c.signature,nonce:c.nonce,address:c.consumerAddress};return i&&(l.maxLogs=i),s&&(l.moduleName=s),o&&(l.level=o),a&&(l.page=a),d.sendP2pCommand(e,E.GET_LOGS,l,t,u)})}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.createPersistentStorageBucket=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_CREATE_BUCKET,r)).then(function(s){var o;return i.sendP2pCommand(e,E.PERSISTENT_STORAGE_CREATE_BUCKET,F({},s,{accessLists:null!=(o=n.accessLists)?o:[],label:n.label}),t,r)})}catch(e){return Promise.reject(e)}},t.updatePersistentStorageBucket=function(e,t,n,r,i){try{var s=this;return Promise.resolve(s.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_UPDATE_BUCKET,i)).then(function(o){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_UPDATE_BUCKET,F({},o,{bucketId:n,label:r}),t,i)})}catch(e){return Promise.reject(e)}},t.getPersistentStorageBuckets=function(e,t,n,r){try{var i=this;return Promise.resolve(i.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_GET_BUCKETS,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.PERSISTENT_STORAGE_GET_BUCKETS,F({},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.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_LIST_FILES,r)).then(function(s){return Promise.resolve(i.sendP2pCommand(e,E.PERSISTENT_STORAGE_LIST_FILES,F({},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.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,i)).then(function(o){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_GET_FILE_OBJECT,F({},o,{bucketId:n,fileName:r}),t,i)})}catch(e){return Promise.reject(e)}},t.uploadPersistentStorageFile=function(e,t,n,r,i,s){try{var o=this;return Promise.resolve(o.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_UPLOAD_FILE,s)).then(function(a){return o.sendP2pCommand(e,E.PERSISTENT_STORAGE_UPLOAD_FILE,F({},a,{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.getSignedCommandParams(e,t,E.PERSISTENT_STORAGE_DELETE_FILE,i)).then(function(o){return s.sendP2pCommand(e,E.PERSISTENT_STORAGE_DELETE_FILE,F({},o,{bucketId:n,fileName:r}),t,i)})}catch(e){return Promise.reject(e)}},e}(),MT=function(e,t,n){try{if("string"==typeof e)return Promise.resolve(null);if(LT(e))return Promise.resolve(e.signature);var r=String,i=String;return Promise.resolve(e.getAddress()).then(function(s){var o=r(i(s)+String(t)+String(n));return nt(e,o)})}catch(e){return Promise.reject(e)}},FT=function(e){try{return LT(e)?Promise.resolve(e.consumerAddress):Promise.resolve("string"==typeof e?function(e){try{return g.decode(e,{json:!0})}catch(e){throw new Error("Error decoding JWT")}}(e).address:e.getAddress())}catch(e){return Promise.reject(e)}};function RT(e){return"string"==typeof e?e:void 0}function LT(e){return!!e&&"object"==typeof e&&"string"==typeof e.consumerAddress&&"string"==typeof e.nonce&&"string"==typeof e.signature}function _T(e){try{return Uu(e),!0}catch(e){}try{return eu(e),!0}catch(e){return!1}}function NT(e){if(!e)return!1;if("string"==typeof e)return _T(e);if("object"==typeof e&&("nodeId"in e||"multiaddress"in e)){var t=e;if(Array.isArray(t.multiaddress)&&t.multiaddress.length>0)return!0;if(t.nodeId)return _T(t.nodeId)}if("object"==typeof e&&"function"==typeof e.toString){var n=String(e.toString());try{return eu(n),!0}catch(e){return!1}}return!1}var OT=/*#__PURE__*/function(){function e(){this.httpProvider=new Vu,this.p2pProvider=new DT}var t=e.prototype;return t.getImpl=function(e){return NT(e)?this.p2pProvider:this.httpProvider},t.getP2PProvider=function(){return this.p2pProvider},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,o,a,u){try{return Promise.resolve(this.getImpl(i).initialize(e,t,n,r,i,s,o,a,u))}catch(e){return Promise.reject(e)}},t.initializeCompute=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h){try{return Promise.resolve(this.getImpl(s).initializeCompute(e,t,n,r,i,s,o,a,u,d,c,l,p,h))}catch(e){return Promise.reject(e)}},t.getDownloadUrl=function(e,t,n,r,i,s,o,a){try{return Promise.resolve(this.getImpl(i).getDownloadUrl(e,t,n,r,i,s,o,a))}catch(e){return Promise.reject(e)}},t.computeStart=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h,f,m,y){try{return Promise.resolve(this.getImpl(e).computeStart(e,t,n,r,i,s,o,a,u,d,c,l,p,h,f,m,y))}catch(e){return Promise.reject(e)}},t.freeComputeStart=function(e,t,n,r,i,s,o,a,u,d,c,l,p,h){try{return Promise.resolve(this.getImpl(e).freeComputeStart(e,t,n,r,i,s,o,a,u,d,c,l,p,h))}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,s){try{return Promise.resolve(this.p2pProvider.generateSignedAuthToken(e,t,n,r,i,s))}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,o,a,u){try{return Promise.resolve(this.getImpl(e).downloadNodeLogs(e,t,n,r,i,s,o,a,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.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.updatePersistentStorageBucket=function(e,t,n,r,i){try{return Promise.resolve(this.getImpl(e).updatePersistentStorageBucket(e,t,n,r,i))}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 OT;function UT(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function jT(e,t,n){if(!e.s){if(n instanceof qT){if(!n.s)return void(n.o=jT.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(jT.bind(null,e,t),jT.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var qT=/*#__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{jT(r,1,s(this.v))}catch(e){jT(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?jT(r,1,t?t(i):i):n?jT(r,1,n(i)):jT(r,2,i)}catch(e){jT(r,2,e)}},r},e}();function $T(e){return e instanceof qT&&1&e.s}var zT=/*#__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 o=s.aquariusURL+"/api/aquarius/assets/ddo/"+e;return UT(function(){return Promise.resolve(y(o,{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 q.error(e),new Error("HTTP request failed")})},s=this,o=function(){if(NT(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(o&&o.then?o.then(i):i(o))}catch(e){return Promise.reject(e)}},t.waitForIndexer=function(e,t,n,r,i,s){void 0===r&&(r=3e4),void 0===i&&(i=100);try{var o,a=this,u=0;i>500&&(q.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);var d=NT(a.aquariusURL),c=function(e,t){var n;do{var r=e();if(r&&r.then){if(!$T(r)){n=!0;break}r=r.v}var i=t();if($T(i)&&(i=i.v),!i)return r}while(!i.then);var s=new qT,o=jT.bind(null,s,2);return(n?r.then(a):i.then(u)).then(void 0,o),s;function a(n){for(r=n;$T(i=t())&&(i=i.v),i;){if(i.then)return void i.then(u).then(void 0,o);if((r=e())&&r.then){if(!$T(r))return void r.then(a).then(void 0,o);r=r.v}}jT(s,1,r)}function u(n){if(n){do{if((r=e())&&r.then){if(!$T(r))return void r.then(a).then(void 0,o);r=r.v}if($T(n=t())&&(n=n.v),!n)return void jT(s,1,r)}while(!n.then);n.then(u).then(void 0,o)}else jT(s,1,r)}}(function(){function i(e){return o?e:Promise.resolve(et(r)).then(function(){u++})}var c=UT(function(){function r(){if(i){var e=b.getDDOClass(i).getAssetFields().indexedMetadata;if(!t)return o=1,i;if(e.event&&e.event.txid===t)return o=1,i}}var i,u=d?Promise.resolve(BT.resolveDdo(a.aquariusURL,e,n)).then(function(e){i=e}):Promise.resolve(y(a.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 u&&u.then?u.then(r):r()},function(){});return c&&c.then?c.then(i):i(c)},function(){return!o&&u<i});return Promise.resolve(c&&c.then?c.then(function(e){return o?e:null}):o?c:null)}catch(e){return Promise.reject(e)}},t.validate=function(e,t,n,r,i){try{if(NT(n))return Promise.resolve(BT.validateDdo(n,e,t,r));var s=n+"/api/aquarius/assets/ddo/validate",o=n+"/api/services/nonce";return Promise.resolve(UT(function(){return Promise.resolve(t.getAddress()).then(function(n){return Promise.resolve(y(o+"?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 o=i.nonce;o&&null!==o||(o="0");var a=(Number(o)+1).toString(),u=String,d=String;return Promise.resolve(t.getAddress()).then(function(i){var o=u(d(i)+String(a)+String(E.VALIDATE_DDO));return Promise.resolve(nt(t,o)).then(function(i){return Promise.resolve(y(s,{method:"POST",body:JSON.stringify({ddo:e,publisherAddress:n,nonce:a,signature:i}),headers:{"Content-Type":"application/json",Authorization:RT(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){q.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(UT(function(){return Promise.resolve(y(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 q.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(UT(function(){return Promise.resolve(y(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 q.error("Error querying metadata: ",e),new Error("Error querying metadata: "+e)}))}catch(e){return Promise.reject(e)}},e}();function VT(e,t){return e=d(e),"did:op:"+T(e+t.toString(10)).toString()}function GT(e){return T(e).toString()}var KT=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)}};function WT(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()}var HT=function(e,n){try{var r=new t.Contract(n,X,e);return Promise.resolve(r.decimals()).then(Number)}catch(e){return Promise.reject(e)}},QT=function(e,n,r,i){try{var s=new t.Contract(n,X,e);return Promise.resolve(s.allowance(r,i))}catch(e){return Promise.reject(e)}},YT=function(e,n,r,i){try{var s=new t.Contract(n,X,e);return Promise.resolve(s.balanceOf(r)).then(function(t){return Promise.resolve(ae(e,n,t,i))})}catch(e){return Promise.reject(e)}},JT=function(e,n,r,i,s){try{var o=new t.Contract(n,X,e);return Promise.resolve(o.allowance(r,i)).then(function(t){return Promise.resolve(ae(e,n,t,s))})}catch(e){return Promise.reject(e)}},ZT=function(e,n,r,i,s,o,a){try{var u=new t.Contract(r,X,e);return Promise.resolve(oe(e,r,s,o)).then(function(t){return Promise.resolve(u.transfer.estimateGas(i,t)).then(function(r){return a?r:Promise.resolve(se(r,e,null==n?void 0:n.gasFeeMultiplier,u.transfer,i,t))})})}catch(e){return Promise.reject(e)}},XT=function(e,n,r,i,s,o,a,u){void 0===a&&(a=!1);try{var d,c=function(t){if(d)return t;var r=null;return Promise.resolve(l.approve.estimateGas(s,o)).then(function(t){if(u)return t;var i=function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(function(){return Promise.resolve(se(t,e,null==n?void 0:n.gasFeeMultiplier,l.approve,s,o)).then(function(e){r=e})},function(e){q.error("ERROR: Failed to approve spender to spend tokens : "+e.message)});return i&&i.then?i.then(function(){return r}):r})},l=new t.Contract(i,X,e),p=function(){if(!a)return Promise.resolve(QT(e,i,r,s)).then(function(e){if(new f(e).isGreaterThan(new f(o))){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)}},eP=function(e,n,r,i,s,o,a,u,d){void 0===a&&(a=!1);try{var c,l=function(t){return c?t:Promise.resolve(oe(e,i,o,u)).then(function(t){return Promise.resolve(p.approve.estimateGas(s,t)).then(function(r){return d?new m(r.toString()):Promise.resolve(se(r,e,null==n?void 0:n.gasFeeMultiplier,p.approve,s,t))})})},p=new t.Contract(i,X,e),h=function(){if(!a)return Promise.resolve(JT(e,i,r,s)).then(function(e){if(new m(e).greaterThanOrEqualTo(new m(o))){var t=new m(e).toNumber();return c=1,t}})}();return Promise.resolve(h&&h.then?h.then(l):l(h))}catch(e){return Promise.reject(e)}},tP={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 nP(e){try{var t=JSON.parse(e),n=Object.keys(t)[0];if("error"===n){var r,i=t[n];return(null==(r=tP[n])?void 0:r[i])||"Provider request failed: "+i}var s=t[n];return t[Object.keys(t)[1]]+" : "+s}catch(t){return q.error("[getErrorMessage] error: ",t),e}}function rP(e,t,n){if(!e.s){if(n instanceof iP){if(!n.s)return void(n.o=rP.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(rP.bind(null,e,t),rP.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var iP=/*#__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{rP(r,1,s(this.v))}catch(e){rP(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?rP(r,1,t?t(i):i):n?rP(r,1,n(i)):rP(r,2,i)}catch(e){rP(r,2,e)}},r},e}(),sP=function(e,t,n,r,i,s,o,a,u,d,c,l){void 0===u&&(u="0"),void 0===d&&(d=0),void 0===c&&(c=0),void 0===l&&(l=0);try{var p=b.getDDOClass(e),h=p.getAssetFields().datatokens,f=p.getDDOFields(),y=f.chainId,g=f.services;return o||(o={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"}),Promise.resolve(t.provider.getNetwork()).then(function(p){if(y!==Number(p.chainId))throw new Error("Chain ID from DDO is different than the configured network.");if(!h[d].address)throw new Error("The datatoken with index: "+d+" does not exist for the asset with did: "+e.id);if(!g[c].id)throw new Error("There is no service with index: "+c+" defined for the asset with did: "+e.id);return Promise.resolve(r.getId(h[d].address)).then(function(p){return Promise.resolve(r.getFixedRates(h[d].address)).then(function(f){return Promise.resolve(r.getDispensers(h[d].address)).then(function(y){return Promise.resolve(r.getPublishingMarketFee(h[d].address)).then(function(b){function v(e){return a?e:Promise.resolve(P.call(BT,E,x,0,e,i||n.oceanNodeUri)).then(w)}function w(i){function y(i){function a(i){var s,a={consumer:i,serviceIndex:c,_providerFee:v,_consumeMarketFee:o};return function(e,t){var n,r=-1;e:{for(var i=0;i<t.length;i++){var s=t[i][0];if(s){var o=s();if(o&&o.then)break e;if(o===e){r=i;break}}else r=i}if(-1!==r){do{for(var a=t[r][1];!a;)r++,a=t[r][1];var u=a();if(u&&u.then){n=!0;break e}var d=t[r][2];r++}while(d&&!d());return u}}var c=new iP,l=rP.bind(null,c,2);return(n?u.then(p):o.then(function n(o){for(;;){if(o===e){r=i;break}if(++i===t.length){if(-1!==r)break;return void rP(c,1,u)}if(s=t[i][0]){if((o=s())&&o.then)return void o.then(n).then(void 0,l)}else r=i}do{for(var a=t[r][1];!a;)r++,a=t[r][1];var u=a();if(u&&u.then)return void u.then(p).then(void 0,l);var d=t[r][2];r++}while(d&&!d());rP(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)}rP(c,1,e)}}(T,[[function(){return"free"},function(){var e=function(e){var t;if(s)return e;function i(e){if(t)return e}var o=function(){if(2===p||4===p)return Promise.resolve(r.buyFromDispenserAndOrder(g[c].datatokenAddress,a,n.dispenserAddress)).then(function(e){return t=1,e})}();return o&&o.then?o.then(i):i(o)},i=function(){if(1===p){var e=new Pe(n.dispenserAddress,t),i=e.dispense,o=h[d].address;return Promise.resolve(t.getAddress()).then(function(t){return Promise.resolve(i.call(e,o,"1",t)).then(function(e){if(!e)throw new Error("Failed to dispense !");return Promise.resolve(e.wait()).then(function(){return Promise.resolve(r.startOrder(h[d].address,a.consumer,a.serviceIndex,a._providerFee,a._consumeMarketFee)).then(function(e){return s=1,e})})})})}}();return i&&i.then?i.then(e):e(i)}],[function(){return"fixed"},function(){var i=new ke(n.fixedRateExchangeAddress,t);if(!f[l].id)throw new Error("There is no fixed rate exchange with index: "+c+" for the asset with did: "+e.id);return Promise.resolve(i.getFeesInfo(f[l].id)).then(function(e){return Promise.resolve(i.getExchange(f[l].id)).then(function(s){return Promise.resolve(i.calcBaseInGivenDatatokensOut(e.exchangeId,"1",o.consumeMarketFeeAmount)).then(function(c){var l;function f(e){var i;if(l)return e;function o(e){if(i)return e}var u=function(){if(2===p||4===p)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(eP(t,n,e,s.baseToken,h[d].address,y,!1)).then(function(e){function t(e){if(!e)throw new Error("Failed to confirm/mine approval transaction!");return Promise.resolve(r.buyFromFreAndOrder(h[d].address,a,g)).then(function(e){return i=1,e})}if(!e)throw new Error("Failed to approve "+s.baseToken+" !");return"number"!=typeof e?Promise.resolve("number"!=typeof e?e.wait():e).then(t):t("number"!=typeof e?e.wait():e)})})}();return u&&u.then?u.then(o):o(u)}var y=new m(+c.baseTokenAmount||0).add(new m(o.consumeMarketFeeAmount||0)).add(new m(+b.publishMarketFeeAmount||0)).toString(),g={exchangeContract:n.fixedRateExchangeAddress,exchangeId:e.exchangeId,maxBaseTokenAmount:y,baseTokenAddress:s.baseToken,baseTokenDecimals:parseInt(s.btDecimals)||18,swapMarketFee:u,marketFeeAddress:b.publishMarketFeeAddress},v=function(){if(1===p)return Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(eP(t,n,e,s.baseToken,n.fixedRateExchangeAddress,y,!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",y,b.publishMarketFeeAddress,u)).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(h[d].address,a.consumer,a.serviceIndex,a._providerFee,a._consumeMarketFee)).then(function(e){return l=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(f):f(v)})})})}],[void 0,function(){throw new Error("Pricing schema not supported !")}]])}return s?a(s):Promise.resolve(t.getAddress()).then(a)}var v=a||i.providerFee,w=function(){if(v&&v.providerFeeAddress!==xe&&v.providerFeeAmount&&parseInt(v.providerFeeAmount)>0)return function(e,r){try{var i=Promise.resolve(t.getAddress()).then(function(e){return Promise.resolve(XT(t,n,e,v.providerFeeToken,g[0].datatokenAddress,v.providerFeeAmount)).then(function(){})})}catch(e){return r()}return i&&i.then?i.then(void 0,r):i}(0,function(){throw new Error("Failed to approve provider fee token "+v.providerFeeToken)})}();return w&&w.then?w.then(y):y()}var T=f.length>0?"fixed":y.length>0?"free":"NOT_ALLOWED",P=a||BT.initialize,x=a||g[c].id,E=a||e.id;return a?v(w(a)):Promise.resolve(t.getAddress()).then(v)})})})})})}catch(e){return Promise.reject(e)}};function oP(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var aP=function(e,n,r){try{var i=new t.Contract(e,Z,n);return Promise.resolve(n.getAddress()).then(function(e){var t,n=oP(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=ge(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)}},uP=function(e,n,r,i,o,u,d,c,l,h,f,m,y,g,v){void 0===d&&(d=!0);try{var w,P,x=this,E=b.getDDOClass(u),S=E.getAssetFields().indexedMetadata,A=(null==(w=E.getDDOData())||null==(w=w.stats)||null==(w=w.price)?void 0:w.value)||(null==S||null==(P=S.stats[0])||null==(P=P.prices[0])?void 0:P.price),k=E.getDDOFields(),C=k.chainId,I=k.nftAddress,D=E.getDDOFields().services;if("string"!=typeof o&&"number"!=typeof o)throw new Error('Invalid template! Must be a "number" or a "string"');return Promise.resolve(r.provider.getNetwork()).then(function(b){var w=b.chainId;if(C&&C!==Number(w))throw new Error("Chain ID from DDO is different than the configured network.");var P=(new K).getConfig(parseInt(String(w)));return Promise.resolve(Be(r,P.nftFactoryAddress,o,Number(w))).then(function(o){if(o<1){if(Number(w)!==dP)throw new Error("Invalid template index: "+o);o=1}var b=new qe(r,Number(w)),S=new Re(P.nftFactoryAddress,r,Number(w));return Promise.resolve(r.getAddress()).then(function(k){var M;function F(e){return M?e:Promise.resolve(R.wait()).then(function(e){var n;function i(e){if(n)return e;function t(){function e(){var e=b.setMetadata,s=I;return Promise.resolve(r.getAddress()).then(function(r){return Promise.resolve(e.call(b,s,r,0,c,"",p(i),t,n)).then(function(){return u.id})})}D[0].datatokenAddress=m,D[0].serviceEndpoint=c;var t,n,i,o=E.makeDid(I=f,C.toString());u=E.updateFields({id:o,nftAddress:I});var l=function(){if(d)return Promise.resolve(BT.encrypt(u,Number(w),c,r,null)).then(function(e){return t=e,Promise.resolve(h.validate(u,r,c)).then(function(e){n=e.hash,i=2})});var e=JSON.stringify(u);t=a(s(e)),n="0x"+T(t).toString(),i=0}();return l&&l.then?l.then(e):e()}var i=function(){if("oasis"!==P.sdk)return Promise.resolve(BT.encrypt(N,Number(w),c,r,null)).then(function(e){D[0].files=e});D[0].files=""}();return i&&i.then?i.then(t):t()}var o=ge(e,"NFTCreated"),l=ge(e,"TokenCreated"),f=o.args.newTokenAddress,m=l.args.newTokenAddress;N.datatokenAddress=m,N.nftAddress=f;var y=function(){if("oasis"===P.sdk){var e=new t.Contract(m,ze,r);return oP(function(){return Promise.resolve(e.setFilesObject(s(JSON.stringify(N)))).then(function(e){var t=function(){if(e.wait)return Promise.resolve(e.wait()).then(function(){})}();if(t&&t.then)return t.then(function(){})})},function(e){return console.log("Error updating files object with data token and nft addresses: ",e),n=1,null})}}();return y&&y.then?y.then(i):i(y)})}var R,L={name:e,symbol:n,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:k},_={templateIndex:o,cap:"100000",feeAmount:"0",paymentCollector:k,feeToken:l||P.oceanTokenAddress,minter:k,mpFeeAddress:xe},N={nftAddress:"0x0",datatokenAddress:"0x0",files:i};"oasis"===P.sdk&&(_.filesObject=N,_.accessListFactory=f||P.accessListFactory,_.allowAccessList=m,_.denyAccessList=y);var O=oP(function(){var e=function(){if(!A)return Promise.resolve(S.createNftWithDatatoken(L,_)).then(function(e){R=e});var e=function(){if("0"===A.toString())return Promise.resolve(S.createNftWithDatatokenWithDispenser(L,_,{dispenserAddress:P.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:xe})).then(function(e){R=e});var e=g||P.oceanTokenAddress;return Promise.resolve(ue(x.signer,e)).then(function(t){v||(v=t);var n={fixedRateAddress:P.fixedRateExchangeAddress,baseTokenAddress:e,owner:k,marketFeeCollector:k,baseTokenDecimals:v,datatokenDecimals:18,fixedRate:A.toString(),marketFee:"0",allowedConsumer:k,withMint:!0};return Promise.resolve(S.createNftWithDatatokenWithFixedRate(L,_,n)).then(function(e){R=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),M=1,null});return O&&O.then?O.then(F):F(O)})})})}catch(e){return Promise.reject(e)}},dP=8996;function cP(e){var t=(new K).getConfig(e);return t&&"oasis"===t.sdk}export{Ke as AccessListContract,We as AccesslistFactory,zT as Aquarius,S as Config,K as ConfigHelper,dP as DEVELOPMENT_CHAIN_ID,$e as Datatoken,Ve as Datatoken4,Pe as Dispenser,x as EncryptMethod,Xe as EnterpriseFeeCollectorContract,Je as EscrowContract,Ae as FEE_HISTORY_NOT_SUPPORTED,P as FileObjectType,ke as FixedRateExchange,Ee as GASLIMIT_DEFAULT,V as KNOWN_CONFIDENTIAL_EVMS,B as LogLevel,j as Logger,q as LoggerInstance,Se as MAX_UINT_256,qe as Nft,Re as NftFactory,kT as OCEAN_P2P_PROTOCOL,E as PROTOCOL_COMMANDS,OT as Provider,BT as ProviderInstance,Ie as Router,ve as SmartContract,we as SmartContractWithAddress,xe as ZERO_ADDRESS,JT as allowance,QT as allowanceWei,oe as amountToUnits,eP as approve,XT as approveWei,YT as balance,ie as buildTxOverrides,re as buildUnsignedTx,ju as bytesToHex,Be as calculateActiveTemplateIndex,qu as concatUint8Arrays,z as configHelperNetworks,aP as createAccessListFactory,uP as createAsset,HT as decimals,KT as downloadFile,WT as downloadFileBrowser,VT as generateDid,Me as generateDtName,nP as getErrorMessage,ge as getEventFromTx,de as getFairGasPrice,GT as getHash,G as getNodeEndpointConfig,Ue as getOceanArtifactsAddresses,je as getOceanArtifactsAddressesByChainId,ue as getTokenDecimals,tt as isDefined,NT as isP2pUri,X as minAbi,sP as orderAsset,te as sendPreparedTransaction,ne as sendPreparedTx,se as sendTx,be as setContractDefaults,rt as signHash,nt as signRequest,et as sleep,ZT as transfer,ae as unitsToAmount,cP as useOasisSDK};
5
5
  //# sourceMappingURL=lib.module.mjs.map