@oceanprotocol/lib 7.0.0-next.2 → 7.0.0-next.3

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,4 +1,4 @@
1
- import t from"@oceanprotocol/contracts/addresses/address.json";import e from"fs";import{ethers as r,formatUnits as n,parseUnits as i,EventLog as s,toUtf8Bytes as a,keccak256 as o,hexlify as c,toUtf8String as u,getAddress as l,parseEther as d,getBytes as h,toBeHex as f}from"ethers";import*as g from"@oasisprotocol/sapphire-paratime";import p from"bignumber.js";import w from"decimal.js";import m from"@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json";import y from"@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json";import b from"@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json";import v from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json";import E from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json";import S from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json";import A from"@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json";import T from"@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json";import x from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template4.sol/ERC20Template4.json";import k from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessList.sol/AccessList.json";import C from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessListFactory.sol/AccessListFactory.json";import F from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import D from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import O from"cross-fetch";import{DDOManager as P}from"@oceanprotocol/ddo-js";import{allocUnsafe as I,alloc as N}from"uint8arrays/alloc";import{concat as L}from"uint8arrays/concat";import{equals as U}from"uint8arrays/equals";import{fromString as R}from"uint8arrays/from-string";import{toString as M}from"uint8arrays/to-string";import{multiaddr as B}from"@multiformats/multiaddr";import _ from"jsonwebtoken";import{PublicKey as G,encrypt as $}from"eciesjs";import{createLibp2p as j}from"libp2p";import{noise as q}from"@chainsafe/libp2p-noise";import{yamux as V}from"@chainsafe/libp2p-yamux";import{webSockets as z}from"@libp2p/websockets";import{tcp as H}from"@libp2p/tcp";import{circuitRelayTransport as K}from"@libp2p/circuit-relay-v2";import{bootstrap as Z}from"@libp2p/bootstrap";import{identify as J}from"@libp2p/identify";import{EventTypes as W,kadDHT as Y}from"@libp2p/kad-dht";import X from"crypto-js/sha256.js";import{createHash as Q}from"crypto";var tt,et;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave",t.S3="s3",t.FTP="ftp"}(tt||(tt={})),function(t){t.AES="AES",t.ECIES="ECIES"}(et||(et={}));const rt={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"};class nt{constructor(){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 it(t,e){this.v=t,this.k=e}function st(t){function e(t){if(Object(t)!==t)return Promise.reject(new TypeError(t+" is not an object."));var e=t.done;return Promise.resolve(t.value).then(function(t){return{value:t,done:e}})}return st=function(t){this.s=t,this.n=t.next},st.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(t){var r=this.s.return;return void 0===r?Promise.resolve({value:t,done:!0}):e(r.apply(this.s,arguments))},throw:function(t){var r=this.s.return;return void 0===r?Promise.reject(t):e(r.apply(this.s,arguments))}},new st(t)}function at(t){return new it(t,0)}function ot(){return ot=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)({}).hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},ot.apply(null,arguments)}function ct(t){return function(){return new ut(t.apply(this,arguments))}}function ut(t){var e,r;function n(e,r){try{var s=t[e](r),a=s.value,o=a instanceof it;Promise.resolve(o?a.v:a).then(function(r){if(o){var c="return"===e?"return":"next";if(!a.k||r.done)return n(c,r);r=t[c](r).value}i(s.done?"return":"normal",r)},function(t){n("throw",t)})}catch(t){i("throw",t)}}function i(t,i){switch(t){case"return":e.resolve({value:i,done:!0});break;case"throw":e.reject(i);break;default:e.resolve({value:i,done:!1})}(e=e.next)?n(e.key,e.arg):r=null}this._invoke=function(t,i){return new Promise(function(s,a){var o={key:t,arg:i,resolve:s,reject:a,next:null};r?r=r.next=o:(e=r=o,n(t,i))})},"function"!=typeof t.return&&(this.return=void 0)}var lt;ut.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},ut.prototype.next=function(t){return this._invoke("next",t)},ut.prototype.throw=function(t){return this._invoke("throw",t)},ut.prototype.return=function(t){return this._invoke("return",t)},function(t){t[t.None=-1]="None",t[t.Error=0]="Error",t[t.Warn=1]="Warn",t[t.Log=2]="Log",t[t.Verbose=3]="Verbose"}(lt||(lt={}));class dt{constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||lt.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",lt.Verbose,...t)}log(...t){this.dispatch("log",lt.Log,...t)}warn(...t){this.dispatch("warn",lt.Warn,...t)}error(...t){this.dispatch("error",lt.Error,...t)}dispatch(t,e,...r){this.logLevel>=e&&console[t](...r)}}const ht=new dt,ft={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},gt=[ot({},ft),ot({},ft,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),ot({},ft,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),ot({},ft,{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"}),ot({},ft,{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"}),ot({},ft,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),ot({},ft,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),ot({},ft,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),ot({},ft,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),ot({},ft,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),ot({},ft,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),ot({},ft,{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"}),ot({},ft,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),ot({},ft,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),ot({},ft,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),ot({},ft,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),ot({},ft,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],pt=[23294,23295],wt=()=>process.env.NODE_ENDPOINT||process.env.NODE_URL?{oceanNodeUri:process.env.NODE_ENDPOINT||process.env.NODE_URL}:{};class mt{getAddressesFromEnv(e,r){let n;if(r&&r[e]){const{FixedPrice:t,Dispenser:i,ERC721Factory:s,OPFCommunityFeeCollector:a,Ocean:o,chainId:c,startBlock:u,Router:l,AccessListFactory:d,Escrow:h,EnterpriseFeeCollector:f}=r[e];n=ot({nftFactoryAddress:s,opfCommunityFeeCollector:a,fixedRateExchangeAddress:t,dispenserAddress:i,oceanTokenAddress:o,routerFactoryAddress:l,chainId:c,startBlock:u,accessListFactory:d,escrow:h,EnterpriseFeeCollector:f},wt())}else if(t[e]){const{FixedPrice:r,Dispenser:i,OPFCommunityFeeCollector:s,ERC721Factory:a,Ocean:o,chainId:c,startBlock:u,Router:l,AccessListFactory:d,Escrow:h,EnterpriseFeeCollector:f}=t[e];n=ot({nftFactoryAddress:a,opfCommunityFeeCollector:s,fixedRateExchangeAddress:r,dispenserAddress:i,oceanTokenAddress:o,routerFactoryAddress:l,chainId:c,startBlock:u,accessListFactory:d,escrow:h,EnterpriseFeeCollector:f},wt())}return n}getConfig(t,r){const n="string"==typeof t?"network":"chainId";let i,s=gt.find(e=>e[n]===t);if(!s)return ht.error(`No config found for given network '${t}'`),null;try{i=process.env.ADDRESS_FILE?JSON.parse(e.readFileSync(process.env.ADDRESS_FILE,"utf8")):null}catch(t){console.log(t),i=null}let a=this.getAddressesFromEnv(s.network,i);return!a&&pt.includes(s.chainId)&&(a=this.getAddressesFromEnv(s.network.replace("sapph","saph"),i)),"sdk"in s&&null!==s.sdk||(s.sdk=pt.includes(s.chainId)?"oasis":"evm"),a&&"accessListFactory"in a&&(s.accessListFactory=a.accessListFactory),s=ot({},s,a),ot({},s,{nodeUri:r?`${s.nodeUri}/${r}`:s.nodeUri})}}const yt=[{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"}],bt=3e10,vt=4e9,Et=1e10,St=11155111;function At(t,e){return t}async function Tt(t,e){const r=(await t.provider.getFeeData()).gasPrice,n=BigInt(r.toString());return e?(n*BigInt(e)).toString(10):n.toString()}async function xt(t,e){return new r.Contract(e,yt,t).decimals()}async function kt(t,e,r,i){let s=i||await xt(t,e);return"0"===s&&(s=18),n(r,s).toString()}async function Ct(t,e,r,n){let s=n||await xt(t,e);return"0"===s&&(s=18),i(r,s).toString()}function Ft(t,e){if(t&&t.logs)return t.logs.filter(t=>t instanceof s&&t.eventName===e)[0]}async function Dt(t,e,r,n,...i){const{chainId:s}=await e.provider.getNetwork(),a=await e.provider.getFeeData();let o={};if(a.maxPriorityFeePerGas){let t=a.maxPriorityFeePerGas.toString(),e=a.maxFeePerGas.toString();r>1&&(t=Math.round(Number(a.maxPriorityFeePerGas)*r).toString(),e=Math.round(Number(a.maxFeePerGas)*r).toString()),o={maxPriorityFeePerGas:(80001===Number(s)||137===Number(s))&&Number(t)<bt?bt:Number(s)===St&&Number(t)<vt?vt:pt.includes(Number(s))&&Number(t)<Et?Et:Number(t),maxFeePerGas:(80001===Number(s)||137===Number(s))&&Number(e)<bt?bt:Number(s)===St&&Number(e)<vt?vt:pt.includes(Number(s))&&Number(e)<Et?Et:Number(e)}}else o={gasPrice:a.gasPrice};o.gasLimit=BigInt(new p(t).plus(20000n).toString());try{const t=await n(...i,o);return await t.wait(),t}catch(t){return ht.error("Send tx error: ",t),null}}class Ot{constructor(t,e,r,n){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=r||(new mt).getConfig(e),this.abi=n||this.getDefaultAbi()}getSignerAccordingSdk(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?g.wrap(this.signer):this.signer}async amountToUnits(t,e,r){return Ct(this.signer,t,e,r)}async unitsToAmount(t,e,r){return kt(this.signer,t,e,r)}async getFairGasPrice(){var t;return Tt(this.signer,null==(t=this.config)?void 0:t.gasFeeMultiplier)}getContract(t,e){if(!t)throw new Error("Contract address is required but not provided");return At(new r.Contract(t,new r.Interface(JSON.stringify(e||this.abi)),this.signer))}}class Pt extends Ot{constructor(t,e,r,n,i){super(e,r,n,i),this.address=void 0,this.contract=void 0,this.address=t,this.contract=this.getContract(this.address)}}class It extends Pt{getDefaultAbi(){return m.abi}async status(t){const e=await this.contract.status(t);if(!e)throw new Error("Np dispenser found for the given datatoken address");return{active:e.active,owner:e.owner,isMinter:e.isMinter,maxTokens:await this.unitsToAmount(null,e.maxTokens,18),maxBalance:await this.unitsToAmount(null,e.maxBalance,18),balance:await this.unitsToAmount(null,e.balance,18),allowedSwapper:e.allowedSwapper}}async create(t,e,r,n,i,s){var a;const o=await this.contract.create.estimateGas(t,this.amountToUnits(null,r,18),this.amountToUnits(null,n,18),e,i);return s?o:await Dt(o,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.create,t,this.amountToUnits(null,r,18),this.amountToUnits(null,n,18),e,i)}async activate(t,e,r,n){var i;const s=await this.contract.activate.estimateGas(t,this.amountToUnits(null,e,18),this.amountToUnits(null,r,18));return n?s:await Dt(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.activate,t,this.amountToUnits(null,e,18),this.amountToUnits(null,r,18))}async deactivate(t,e){var r;const n=await this.contract.deactivate.estimateGas(t);return e?n:await Dt(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.deactivate,t)}async setAllowedSwapper(t,e,r){var n;const i=await this.contract.setAllowedSwapper.estimateGas(t,e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async dispense(t,e="1",r,n){var i;const s=await this.contract.dispense.estimateGas(t,this.amountToUnits(null,e,18),r);return n?s:await Dt(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.dispense,t,this.amountToUnits(null,e,18),r)}async ownerWithdraw(t,e){var r;const n=await this.contract.ownerWithdraw.estimateGas(t);return e?n:await Dt(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.ownerWithdraw,t)}async isDispensable(t,e,r,n="1"){const i=await this.status(t);return!(!i||!1===i.active||new w(await e.balance(t,r)).greaterThanOrEqualTo(i.maxBalance)||new w(String(n)).greaterThan(i.maxTokens)||!new w(i.balance).greaterThanOrEqualTo(n)&&!0!==i.isMinter)}}const Nt="0x0000000000000000000000000000000000000000",Lt=1e6,Ut="115792089237316195423570985008687907853269984665640564039457584007913129639934",Rt="Returned error: Method eth_feeHistory not supported.";class Mt extends Pt{getDefaultAbi(){return y.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,r,n=Nt,i="0",s){var a;const o=await this.getExchange(t),c=await this.amountToUnits(null,i,18),u=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),l=await this.amountToUnits(o.baseToken,r,Number(o.btDecimals)),d=await this.contract.buyDT.estimateGas(t,u,l,n,c);return s?d:await Dt(d,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.buyDT,t,u,l,n,c)}async sellDatatokens(t,e,r,n=Nt,i="0",s){var a;const o=await this.getExchange(t),c=await this.amountToUnits(null,i,18),u=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),l=await this.amountToUnits(o.baseToken,r,Number(o.btDecimals)),d=await this.contract.sellDT.estimateGas(t,u,l,n,c);return s?d:await Dt(d,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.sellDT,t,u,l,n,c)}async getNumberOfExchanges(){const t=await this.contract.getNumberOfExchanges();return Number(t)}async setRate(t,e,r){var n;const i=await this.contract.setRate.estimateGas(t,await this.amountToUnits(null,e,18));return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setRate,t,await this.amountToUnits(null,e,18))}async setAllowedSwapper(t,e,r){var n;const i=await this.contract.setAllowedSwapper.estimateGas(t,e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async activate(t,e){var r;const n=await this.getExchange(t);if(!n)return null;if(!0===n.active)return null;const i=await this.contract.toggleExchangeState.estimateGas(t);return e?i:await Dt(i,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async deactivate(t,e){var r;const n=await this.getExchange(t);if(!n)return null;if(!1===n.active)return null;const i=await this.contract.toggleExchangeState.estimateGas(t);return e?i:await Dt(i,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async getRate(t){const e=await this.contract.getRate(t);return await this.unitsToAmount(null,e,18)}async getDatatokenSupply(t){const e=await this.contract.getDTSupply(t),r=await this.getExchange(t);return await this.unitsToAmount(r.datatoken,e,Number(r.dtDecimals))}async getBasetokenSupply(t){const e=await this.contract.getBTSupply(t),r=await this.getExchange(t);return await this.unitsToAmount(r.baseToken,e,Number(r.btDecimals))}async getAllowedSwapper(t){return await this.contract.getAllowedSwapper(t)}async calcBaseInGivenDatatokensOut(t,e,r="0"){const n=await this.getExchange(t),i=await this.contract.calcBaseInGivenOutDT(t,await this.amountToUnits(n.datatoken,e,Number(n.dtDecimals)),await this.amountToUnits(null,r,18));return{baseTokenAmount:await this.unitsToAmount(n.baseToken,i.baseTokenAmount,Number(n.btDecimals)),marketFeeAmount:await this.unitsToAmount(n.baseToken,i.publishMarketFeeAmount,Number(n.btDecimals)),oceanFeeAmount:await this.unitsToAmount(n.baseToken,i.oceanFeeAmount,Number(n.btDecimals)),consumeMarketFeeAmount:await this.unitsToAmount(n.baseToken,i.consumeMarketFeeAmount,Number(n.btDecimals))}}async getAmountBasetokensOut(t,e,r="0"){const n=await this.getExchange(t),i=await this.contract.calcBaseOutGivenInDT(t,await this.amountToUnits(n.datatoken,e,Number(n.dtDecimals)),await this.amountToUnits(null,r,18));return await this.unitsToAmount(n.baseToken,i[0],Number(n.btDecimals))}async getExchange(t){const e=await this.contract.getExchange(t);return{active:e.active,datatoken:e.datatoken,baseToken:e.baseToken,withMint:e.withMint,exchangeOwner:e.exchangeOwner,allowedSwapper:e.allowedSwapper,dtDecimals:e.dtDecimals.toString(),btDecimals:e.btDecimals.toString(),dtBalance:await this.unitsToAmount(e.datatoken,e.dtBalance,Number(e.dtDecimals)),btBalance:await this.unitsToAmount(e.baseToken,e.btBalance,Number(e.btDecimals)),dtSupply:await this.unitsToAmount(e.datatoken,e.dtSupply,Number(e.dtDecimals)),btSupply:await this.unitsToAmount(e.baseToken,e.btSupply,Number(e.btDecimals)),fixedRate:await this.unitsToAmount(null,e.fixedRate,18),exchangeId:t}}async getFeesInfo(t){const e=await this.contract.getFeesInfo(t),r=await this.getExchange(t);return{opcFee:await this.unitsToAmount(null,e.opcFee.toString(),18),marketFee:await this.unitsToAmount(null,e.marketFee.toString(),18),marketFeeCollector:e.marketFeeCollector,marketFeeAvailable:await this.unitsToAmount(r.baseToken,e.marketFeeAvailable,Number(r.btDecimals)),oceanFeeAvailable:await this.unitsToAmount(r.baseToken,e.oceanFeeAvailable,Number(r.btDecimals)),exchangeId:t}}async getExchanges(){return await this.contract.getExchanges()}async isActive(t){return await this.contract.isActive(t)}async activateMint(t,e){var r;const n=await this.getExchange(t);if(!n)return null;if(!0===n.withMint)return null;const i=await this.contract.toggleMintState.estimateGas(t,!0);return e?i:await Dt(i,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.toggleMintState,t,!0)}async deactivateMint(t,e){var r;const n=await this.getExchange(t);if(!n)return null;if(!1===n.withMint)return null;const i=await this.contract.toggleMintState.estimateGas(t,!1);return e?i:await Dt(i,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.toggleMintState,t,!1)}async collectBasetokens(t,e,r){var n;if(!await this.getExchange(t))return null;const i=await this.contract.getExchange(t),s=await this.amountToUnits(i.baseToken,e,Number(i.btDecimals)),a=await this.contract.collectBT.estimateGas(t,s);return r?a:await Dt(a,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.collectBT,t,s)}async collectDatatokens(t,e,r){var n;if(!await this.getExchange(t))return null;const i=await this.contract.getExchange(t),s=await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),a=await this.contract.collectDT.estimateGas(t,s);return r?a:await Dt(a,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.collectDT,t,s)}async collectMarketFee(t,e){var r;if(!await this.getExchange(t))return null;const n=await this.contract.collectMarketFee.estimateGas(t);return e?n:await Dt(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.collectMarketFee,t)}async collectOceanFee(t,e){var r;if(!await this.getExchange(t))return null;const n=await this.contract.collectOceanFee.estimateGas(t);return e?n:await Dt(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.collectOceanFee,t)}async getOPCCollector(){return await this.contract.opcCollector()}async getRouter(){return await this.contract.router()}async getExchangeOwner(t){return(await this.getExchange(t)).exchangeOwner}async updateMarketFee(t,e,r){var n;const i=await this.contract.updateMarketFee.estimateGas(t,await this.amountToUnits(null,e,18));return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.updateMarketFee,t,await this.amountToUnits(null,e,18))}async updateMarketFeeCollector(t,e,r){var n;const i=await this.contract.updateMarketFeeCollector.estimateGas(t,e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class Bt extends Pt{getDefaultAbi(){return b.abi}async buyDatatokenBatch(t,e){var r;const n=await this.contract.buyDTBatch.estimateGas(t);return e?n:await Dt(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.buyDTBatch,t)}async isApprovedToken(t){return await this.contract.isApprovedToken(t)}async isFixedPrice(t){return await this.contract.isFixedRateContract(t)}async getOwner(){return await this.contract.routerOwner()}async getNFTFactory(){return await this.contract.factory()}async addApprovedToken(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.addApprovedToken.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.addApprovedToken,e)}async removeApprovedToken(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.removeApprovedToken.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.removeApprovedToken,e)}async addFixedRateContract(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.addFixedRateContract.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.addFixedRateContract,e)}async removeFixedRateContract(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.removeFixedRateContract.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.removeFixedRateContract,e)}async addDispenserContract(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.addDispenserContract.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.addDispenserContract,e)}async removeDispenserContract(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.removeDispenserContract.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.removeDispenserContract,e)}async getOPCFee(t){const e=await this.contract.getOPCFee(t);return Number(e)}async getCurrentOPCFee(){const t=await this.contract.swapOceanFee();return Number(t)}async updateOPCFee(t,e,r,n,i,s){var a;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const o=await this.contract.updateOPCFee.estimateGas(e,r,n,i);return s?o:await Dt(o,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.updateOPCFee,e,r,n,i)}}var _t={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 Gt(t){const e=t||_t,r=Math.floor(Math.random()*e.adjectives.length),n=Math.floor(Math.random()*e.nouns.length),i=Math.floor(100*Math.random()),s=e.adjectives[r].replace(/^\w/,t=>t.toUpperCase()),a=e.nouns[n].replace(/^\w/,t=>t.toUpperCase());return{name:`${s} ${a} Token`,symbol:`${(s.substring(0,3)+a.substring(0,3)).toUpperCase()}-${i}`}}class $t extends Pt{getDefaultAbi(){return A.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:r}=Gt();t.name=e,t.symbol=r}if(t.templateIndex>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t.templateIndex)throw new Error("Template index cannot be ZERO");if(!1===(await this.getNFTTemplate(t.templateIndex)).isActive)throw new Error("Template is not active");const r=await this.contract.deployERC721Contract.estimateGas(t.name,t.symbol,t.templateIndex,Nt,Nt,t.tokenURI,t.transferable,t.owner);if(e)return r;try{var n;const e=await Dt(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,Nt,Nt,t.tokenURI,t.transferable,t.owner);if(!e){const t="Tx for deploying new NFT contract does not exist or status is not successful.";throw console.error(t),t}return Ft(await e.wait(),"NFTCreated").args[0]}catch(t){console.error(`Creation of NFT failed: ${t}`)}}async getCurrentNFTCount(){const t=await this.contract.getCurrentNFTCount();return Number(t)}async getCurrentTokenCount(){const t=await this.contract.getCurrentTokenCount();return Number(t)}async getOwner(){return await this.contract.owner()}async getCurrentNFTTemplateCount(){const t=await this.contract.getCurrentNFTTemplateCount();return Number(t)}async getCurrentTokenTemplateCount(){const t=await this.contract.getCurrentTemplateCount();return Number(t)}async getNFTTemplate(t){if(t>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return await this.contract.getNFTTemplate(t)}async getTokenTemplate(t){return await this.contract.getTokenTemplate(t)}async checkDatatoken(t){return await this.contract.erc20List(t)}async checkNFT(t){return await this.contract.erc721List(t)}async addNFTTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===Nt)throw new Error("Template cannot be ZERO address");const i=await this.contract.add721TokenTemplate.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.add721TokenTemplate,e)}async disableNFTTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const i=await this.contract.disable721TokenTemplate.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.disable721TokenTemplate,e)}async reactivateNFTTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const i=await this.contract.reactivate721TokenTemplate.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.reactivate721TokenTemplate,e)}async addTokenTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===Nt)throw new Error("Template cannot be address ZERO");const i=await this.contract.addTokenTemplate.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.addTokenTemplate,e)}async disableTokenTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!1===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already disabled");const i=await this.contract.disableTokenTemplate.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.disableTokenTemplate,e)}async reactivateTokenTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!0===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already active");const i=await this.contract.reactivateTokenTemplate.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.reactivateTokenTemplate,e)}async startMultipleTokenOrder(t,e){var r;if(t.length>50)throw new Error("Too many orders");const n=await this.contract.startMultipleTokenOrder.estimateGas(t);return e?n:await Dt(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.startMultipleTokenOrder,t)}async createNftWithDatatoken(t,e,r){var n;const i=await this.getErcCreationParams(e),s=await this.contract.createNftWithErc20.estimateGas(t,i);return r?s:await Dt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.createNftWithErc20,t,i)}async createNftWithDatatokenWithFixedRate(t,e,r,n){var i;const s=await this.getErcCreationParams(e),a=await this.getFreCreationParams(r),o=await this.contract.createNftWithErc20WithFixedRate.estimateGas(t,s,a);return n?o:await Dt(o,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.createNftWithErc20WithFixedRate,t,s,a)}async createNftWithDatatokenWithDispenser(t,e,r,n){var i;const s=await this.getErcCreationParams(e);r.maxBalance=await this.amountToUnits(null,r.maxBalance,18),r.maxTokens=await this.amountToUnits(null,r.maxTokens,18);const a=await this.contract.createNftWithErc20WithDispenser.estimateGas(t,s,r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.createNftWithErc20WithDispenser,t,s,r)}async getErcCreationParams(t){let e,r;t.name&&t.symbol||({name:e,symbol:r}=Gt());let n=18;if(t.feeToken!==Nt)try{n=await xt(this.signer,t.feeToken)}catch(t){ht.error("getTokenDecimals error",t)}const i=[t.minter,t.paymentCollector,t.mpFeeAddress,t.feeToken];return t.filesObject&&(t.accessListFactory&&i.push(t.accessListFactory),t.allowAccessList&&i.push(t.allowAccessList),t.denyAccessList&&i.push(t.denyAccessList)),{templateIndex:t.templateIndex,strings:[t.name||e,t.symbol||r],addresses:i,uints:[await this.amountToUnits(null,t.cap,18),await this.amountToUnits(null,t.feeAmount,n)],bytess:t.filesObject?[a(JSON.stringify(t.filesObject))]:[]}}async getFreCreationParams(t){t.allowedConsumer||(t.allowedConsumer=Nt);const e=!1===t.withMint?0:1;return{fixedPriceAddress:t.fixedRateAddress,addresses:[t.baseTokenAddress,t.owner,t.marketFeeCollector,t.allowedConsumer],uints:[t.baseTokenDecimals,t.datatokenDecimals,await this.amountToUnits(null,t.fixedRate,t.datatokenDecimals),await this.amountToUnits(null,t.marketFee,t.datatokenDecimals),e]}}}function jt(){try{if(process.env.ADDRESS_FILE){const t=e.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(t)}return t}catch(e){return t}}function qt(t){try{const e=jt();if(e){const r=Object.keys(e);for(const n of r)if(e[n].chainId===t)return e[n]}}catch(t){console.error(t)}return null}async function Vt(t,e,n,i){const s="number"==typeof n,a=new $t(e,t,i),o=await a.getCurrentTokenTemplateCount();for(let e=1;e<=o;e++){const i=await a.getTokenTemplate(e),o=new r.Contract(i.templateAddress,T.abi,t);if(s){const t=await o.getId();if(i.isActive&&t.toString()===n.toString())return e}else if(i.isActive&&i.templateAddress===n.toString())return e}return-1}class zt extends Ot{getDefaultAbi(){return S.abi}async createDatatoken(t,e,r,n,i,s,o,c,u,l,d,h,f,g,p,w){var m;if(!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not DatatokenDeployer");d||(d=1),u&&l||({name:u,symbol:l}=Gt());const y=this.getContract(t);if(!this.signer.provider)throw new Error("Provider is required but not available");const{chainId:b}=await this.signer.provider.getNetwork(),v=qt(Number(b));h&&(d=await Vt(this.signer,v.ERC721Factory,4,Number(b)));const E=await y.createERC20.estimateGas(d,[u,l],[r,n,i,s],[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],[]);if(w)return E;const S=[r,n,i,s];f&&(S.push(f.toLowerCase()),S.push(g?g.toLowerCase():Nt),S.push(p||Nt));const A=await Dt(E,this.getSignerAccordingSdk(),null==(m=this.config)?void 0:m.gasFeeMultiplier,y.createERC20,d,[u,l],S,[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],h?[a(h)]:[]),T=Ft(await A.wait(),"TokenCreated");return null==T?void 0:T.args[0]}async addManager(t,e,r,n){var i;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const a=await s.addManager.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addManager,r)}async removeManager(t,e,r,n){var i;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const a=await s.removeManager.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeManager,r)}async addDatatokenDeployer(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const a=await s.addToCreateERC20List.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addToCreateERC20List,r)}async removeDatatokenDeployer(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e===r&&!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not Manager nor DatatokenDeployer");const a=await s.removeFromCreateERC20List.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeFromCreateERC20List,r)}async addMetadataUpdater(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const a=await s.addToMetadataList.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addToMetadataList,r)}async removeMetadataUpdater(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==r&&!0!==(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Manager nor Metadata Updater");const a=await s.removeFromMetadataList.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeFromMetadataList,r)}async addStoreUpdater(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const a=await s.addTo725StoreList.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addTo725StoreList,r)}async removeStoreUpdater(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==r&&!0!==(await this.getNftPermissions(t,e)).store)throw new Error("Caller is not Manager nor storeUpdater");const a=await s.removeFrom725StoreList.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeFrom725StoreList,r)}async cleanPermissions(t,e,r){var n;const i=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await i.cleanPermissions.estimateGas();return r?s:await Dt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,i.cleanPermissions)}async transferNft(t,e,r,n,i){var s;const a=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=n||1,c=await a.transferFrom.estimateGas(e,r,o);return i?c:await Dt(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,a.transferFrom,e,r,o)}async safeTransferNft(t,e,r,n,i){var s;const a=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=n||1,c=await a.safeTransferFrom.estimateGas(e,r,o);return i?c:await Dt(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,a.safeTransferFrom,e,r,o)}async setMetadata(t,e,r,n,i,s,a,o,c,u){var l;const d=this.getContract(t);if(c||(c=[]),!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");let h=n;if(null!=n&&n.includes("/p2p/")){var f;const t=n.match(/\/p2p\/([^/]+)/);h=null!=(f=null==t?void 0:t[1])?f:n}const g=await d.setMetaData.estimateGas(r,h,i,s,a,o,c);return u?g:await Dt(g,this.signer,null==(l=this.config)?void 0:l.gasFeeMultiplier,d.setMetaData,r,h,i,s,a,o,c)}async setMetadataAndTokenURI(t,e,r,n){var i;const s=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const a=ot({},r,{metadataProofs:r.metadataProofs||[]}),o=await s.setMetaDataAndTokenURI.estimateGas(a);return n?o:await Dt(o,this.signer,null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setMetaDataAndTokenURI,a)}async setMetadataState(t,e,r,n){var i;const s=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const a=await s.setMetaDataState.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setMetaDataState,r)}async setTokenURI(t,e,r){var n;const i=this.getContract(t),s=await i.setTokenURI.estimateGas("1",e);return r?s:await Dt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,i.setTokenURI,"1",e)}async getNftOwner(t){const e=this.getContract(t);return await e.ownerOf(1)}async getNftPermissions(t,e){const r=this.getContract(t);return await r.getPermissions(e)}async getMetadata(t){const e=this.getContract(t);return await e.getMetaData()}async isDatatokenDeployer(t,e){const r=this.getContract(t);return await r.isERC20Deployer(e)}async setData(t,e,r,n,i){var s;if(!0!==(await this.getNftPermissions(t,e)).store)throw new Error("User is not ERC20 store updater");const u=this.getContract(t),l=o(r),d=c(a(n)),h=await u.setNewData.estimateGas(l,d);return i?h:await Dt(h,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,u.setNewData,l,d)}async getData(t,e){const r=this.getContract(t),n=o(e),i=await r.getData(n);return i?u(i):null}async getTokenURI(t,e){const r=this.getContract(t);return await r.tokenURI(e)}async isDatatokenDeployed(t,e){const r=this.getContract(t);return await r.isDeployed(e)}}class Ht extends Ot{getDefaultAbi(){return v.abi}constructor(t,e,r,n,i){super(t,e,r,n),this.abiEnterprise=void 0,this.nft=void 0,this.abiEnterprise=i||E.abi,this.nft=new zt(this.signer,e)}async approve(t,e,r,n){var i;const s=this.getContract(t),a=await s.approve.estimateGas(e,Ct(null,null,r,18));return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.approve,e,Ct(null,null,r,18))}async createFixedRate(t,e,r,n){var i;const s=this.getContract(t);if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");r.allowedConsumer||(r.allowedConsumer=Nt);const a=!1===r.withMint?0:1,o=await s.createFixedRate.estimateGas(r.fixedRateAddress,[r.baseTokenAddress,r.owner,r.marketFeeCollector,r.allowedConsumer],[r.baseTokenDecimals,r.datatokenDecimals,r.fixedRate,r.marketFee,a]);return n?o:await Dt(o,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.createFixedRate,r.fixedRateAddress,[r.baseTokenAddress,r.owner,r.marketFeeCollector,r.allowedConsumer],[r.baseTokenDecimals,r.datatokenDecimals,r.fixedRate,r.marketFee,a])}async createDispenser(t,e,r,n,i){var s;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const a=this.getContract(t);n.allowedSwapper||(n.allowedSwapper=Nt),n.withMint=!1!==n.withMint;const o=await a.createDispenser.estimateGas(r,n.maxTokens,n.maxBalance,n.withMint,n.allowedSwapper);return i?o:await Dt(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,a.createDispenser,r,n.maxTokens,n.maxBalance,n.withMint,n.allowedSwapper)}async mint(t,e,r,n,i){const s=this.getContract(t);if(!0!==(await this.getPermissions(t,e)).minter)throw new Error("Caller is not Minter");const a=await this.getCap(t);if(new w(a).gte(r)){var o;const t=await s.mint.estimateGas(n||e,Ct(null,null,r,18));return i?t:await Dt(t,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,s.mint,n||e,Ct(null,null,r,18))}throw new Error("Mint amount exceeds cap available")}async addMinter(t,e,r,n){var i;const s=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const a=await s.addMinter.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addMinter,r)}async removeMinter(t,e,r,n){var i;const s=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const a=await s.removeMinter.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeMinter,r)}async addPaymentManager(t,e,r,n){var i;const s=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const a=await s.addPaymentManager.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addPaymentManager,r)}async removePaymentManager(t,e,r,n){var i;const s=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const a=await s.removePaymentManager.estimateGas(r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removePaymentManager,r)}async setPaymentCollector(t,e,r,n){var i;const s=this.getContract(t),a=(await this.getPermissions(t,e)).paymentManager,o=!a&&await this.getNFTAddress(t),c=o&&await this.nft.getNftOwner(o)===e,u=o&&!c&&await this.nft.getNftPermissions(o,e);if(!a&&!c&&!(null==u?void 0:u.deployERC20))throw new Error("Caller is not Fee Manager, owner or Datatoken Deployer");const l=await s.setPaymentCollector.estimateGas(r);return n?l:await Dt(l,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setPaymentCollector,r)}async getPaymentCollector(t){const e=this.getContract(t);return await e.getPaymentCollector()}async transfer(t,e,r,n){return this.transferWei(t,e,await Ct(null,null,r,18),n)}async transferWei(t,e,r,n){var i;const s=this.getContract(t),a=await s.transfer.estimateGas(e,r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.transfer,e,r)}async startOrder(t,e,r,n,i,s){var a;const o=this.getContract(t,this.abi);i||(i={consumeMarketFeeAddress:Nt,consumeMarketFeeToken:Nt,consumeMarketFeeAmount:"0"});const c=await o.startOrder.estimateGas(e,r,n,i);return s?c:await Dt(c,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,o.startOrder,e,r,n,i)}async reuseOrder(t,e,r,n){var i;const s=this.getContract(t),a=await s.reuseOrder.estimateGas(e,r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.reuseOrder,e,r)}async buyFromFreAndOrder(t,e,r,n){var i;const s=this.getContract(t,this.abiEnterprise),a=await this.getFreOrderParams(r),o=await s.buyFromFreAndOrder.estimateGas(e,a);return n?o:await Dt(o,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.buyFromFreAndOrder,e,a)}async buyFromDispenserAndOrder(t,e,r,n){var i;const s=this.getContract(t,this.abiEnterprise),a=await s.buyFromDispenserAndOrder.estimateGas(e,r);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.buyFromDispenserAndOrder,e,r)}async setData(t,e,r,n){var i;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t),o=c(a(r)),u=await s.setData.estimateGas(o);return n?u:await Dt(u,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setData,o)}async cleanPermissions(t,e,r){var n;if(await this.nft.getNftOwner(await this.getNFTAddress(t))!==e)throw new Error("Caller is NOT Nft Owner");const i=this.getContract(t),s=await i.cleanPermissions.estimateGas();return r?s:await Dt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,i.cleanPermissions)}async getPermissions(t,e){const r=this.getContract(t);return await r.permissions(e)}async getCap(t){const e=this.getContract(t),r=await e.cap();return await this.unitsToAmount(null,r,18)}async getDecimals(t){const e=this.getContract(t),r=await e.decimals();return Number(r)}async getId(t){const e=this.getContract(t),r=await e.getId();return Number(r)}async getSymbol(t){const e=this.getContract(t);return await e.symbol()}async getName(t){const e=this.getContract(t);return await e.name()}async getNFTAddress(t){const e=this.getContract(t);return await e.getERC721Address()}async getFixedRates(t){const e=this.getContract(t);return await e.getFixedRates()}async getDispensers(t){const e=this.getContract(t);return await e.getDispensers()}async isDatatokenDeployer(t,e){const r=this.getContract(t);return await r.isERC20Deployer(e)}async balance(t,e){const r=this.getContract(t),n=await r.balanceOf(e);return await this.unitsToAmount(null,n,18)}async allowance(t,e,r,n=18){const i=this.getContract(t),s=await i.allowance(e,r);return await this.unitsToAmount(null,s,n)}async setPublishingMarketFee(t,e,r,n,i,s){var a;const o=this.getContract(t);if((await o.getPublishingMarketFee())[0]!==i)throw new Error("Caller is not the Publishing Market Fee Address");const c=await o.setPublishingMarketFee.estimateGas(e,r,n);return s?c:await Dt(c,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,o.setPublishingMarketFee,e,r,n)}async getPublishingMarketFee(t){const e=this.getContract(t),r=await e.getPublishingMarketFee();return{publishMarketFeeAddress:r[0],publishMarketFeeToken:r[1],publishMarketFeeAmount:r[2].toString()}}async getFreOrderParams(t){return{exchangeContract:t.exchangeContract,exchangeId:t.exchangeId,maxBaseTokenAmount:await Ct(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await Ct(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class Kt extends Ht{getDefaultAbi(){return x.abi}constructor(t,e,r,n,i){super(t,r,n,i),this.accessList=void 0,this.fileObject=void 0,this.abi=this.getDefaultAbi(),this.fileObject=e}setFileObj(t){this.fileObject=t}async getAllowlistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getAllowListContract()}async getDenylistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getDenyListContract()}async setAllowListContract(t,e,r,n){var i;if(!await this.isDatatokenDeployer(t,r))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t),a=await s.setAllowListContract.estimateGas(e);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setAllowListContract,e)}async setDenyListContract(t,e,r,n){var i;if(!await this.isDatatokenDeployer(t,r))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t),a=await s.setDenyListContract.estimateGas(e);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setDenyListContract,e)}async setFileObject(t,e,r){var n;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const i=this.getContract(t),s=await i.setFilesObject.estimateGas(this.fileObject);return r?s:await Dt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,i.setFilesObject,this.fileObject)}async getFileObject(t,e,r,n,i,s,a){const o=this.getContract(t,this.getDefaultAbi());return await o.getFileObject(e,r,n,i,s,a)}}class Zt extends Pt{getDefaultAbi(){return k.abi}constructor(t,e,r,n,i){super(t,e,r,n,i),this.abiEnterprise=void 0,this.abi=i||this.getDefaultAbi()}async getTokenUri(t){return await this.contract.tokenURI(t)}async getOwner(){return await this.contract.owner()}async getId(){const t=await this.contract.getId();return Number(t)}async getName(){return await this.contract.name()}async getSymbol(){return await this.contract.symbol()}async balance(t){const e=await this.contract.balanceOf(t);return await this.unitsToAmount(null,e,18)}async mint(t,e,r){var n;const i=await this.contract.mint.estimateGas(t,e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.mint,t,e)}async batchMint(t,e,r){var n;const i=await this.contract.batchMint.estimateGas(t,e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.batchMint,t,e)}async burn(t,e){var r;const n=await this.contract.burn.estimateGas(t);return e?n:await Dt(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.burn,t)}async transferOwnership(t,e){var r;const n=await this.contract.transferOwnership.estimateGas(t);return e?n:await Dt(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.transferOwnership,t)}async renounceOwnership(t){var e;const r=await this.contract.renounceOwnership.estimateGas();return t?r:await Dt(r,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class Jt extends Pt{getDefaultAbi(){return C.abi}constructor(t,e,r,n,i){super(t,e,r,n,i),this.abi=i||this.getDefaultAbi()}async deployAccessListContract(t,e,r,n=!1,i,s,a){if(!t||!e){const{name:r,symbol:n}=Gt();t=r,e=n}const o=await this.contract.deployAccessListContract.estimateGas(t,e,n,i,s,r);if(a)return o;try{var c;const a=await Dt(o,this.getSignerAccordingSdk(),null==(c=this.config)?void 0:c.gasFeeMultiplier,this.contract.deployAccessListContract,t,e,n,i,s,r);if(!a){const t="Tx for deploying new access list was not processed on chain.";throw console.error(t),t}return Ft(await a.wait(),"NewAccessList").args[0]}catch(t){console.error(`Creation of AccessList failed: ${t}`)}}async getOwner(){return await this.contract.owner()}async isSoulbound(t){return await this.contract.isSoulBound(t)}async isDeployed(t){return await this.contract.isDeployed(t)}async changeTemplateAddress(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===Nt)throw new Error("Template address cannot be ZERO address");const i=await this.contract.changeTemplateAddress.estimateGas(e);return r?i:await Dt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.changeTemplateAddress,e)}}class Wt extends Pt{getDefaultAbi(){return F.abi}constructor(t,e,r,n,i){super(t,e,r,n,i),this.abiEnterprise=void 0,this.abi=i||this.getDefaultAbi()}async getFunds(t){return await this.contract.getFunds(t)}async getUserFunds(t,e){return await this.contract.getUserFunds(t,e)}async getUserTokens(t){return await this.contract.getUserTokens(t)}async getLocks(t,e,r){return await this.contract.getLocks(t,e,r)}async getAuthorizations(t,e,r){return await this.contract.getAuthorizations(t,e,r)}async verifyFundsForEscrowPayment(t,e,r,n,i,s,a){var o;const c=await(null==(o=this.signer.provider)?void 0:o.getBalance(l(e)));if(new p(c).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};const u=new Ht(this.signer),h=await u.allowance(t,await this.signer.getAddress(),this.contract.target.toString(),a);new p(await this.amountToUnits(t,h,18)).isLessThan(new p(n))&&await u.approve(l(t),l(this.contract.target.toString()),n);const f=await u.balance(t,await this.signer.getAddress());if(new p(f).isZero())return{isValid:!1,message:"Payment token balance is 0. Please add funds"};const g=await this.getAuthorizations(t,await this.signer.getAddress(),e),w=await this.getUserFunds(await this.signer.getAddress(),t);return new p(w[0]).isZero()&&(r&&new p(d(f)).isLessThanOrEqualTo(new p(d(r)))&&new p(d(r)).isGreaterThan(new p(n))?await this.deposit(t,r,a):new p(d(f)).isLessThanOrEqualTo(new p(d(n)))?await this.deposit(t,await this.unitsToAmount(t,n,a),a):await this.deposit(t,f,a)),0===g.length&&await this.authorize(l(t),l(e),(Number(n)/2).toString(),i,s),{isValid:!0,message:""}}async deposit(t,e,r,n){var i;const s=await this.amountToUnits(t,e,r),a=await this.contract.deposit.estimateGas(t,s);return n?a:await Dt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deposit,t,s)}async withdraw(t,e,r,n){var i;const s=[],a=[];if(t.length!==e.length)throw new Error("Tokens and amounts arrays must have the same length");const o=await this.signer.getAddress();for(let r=0;r<t.length;r++){const n=t[r],i=new p(e[r]),c=await this.getUserFunds(o,n),u=new p(c[0]);i.isGreaterThan(0)&&i.isLessThanOrEqualTo(u)?(s.push(n),a.push(e[r])):console.log(`Insufficient funds for token ${n}`)}const c=await Promise.all(a.map((t,e)=>this.amountToUnits(s[e],t,r))),u=await this.contract.withdraw.estimateGas(t,c);return n?u:await Dt(u,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.withdraw,s,c)}async authorize(t,e,r,n,i,s,a){var o;if(0!==(await this.getAuthorizations(t,await this.signer.getAddress(),e)).length)return console.log(`Payee ${e} already authorized`),null;const c=await this.amountToUnits(t,r,s),u=await this.amountToUnits(t,n,s),l=await this.amountToUnits(t,i,s),d=await this.contract.authorize.estimateGas(t,e,c,u,l);return a?d:await Dt(d,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,this.contract.authorize,t,e,c,u,l)}async cancelExpiredLocks(t,e,r,n,i){var s;const a=await this.contract.cancelExpiredLocks.estimateGas(t,e,r,n);return i?a:await Dt(a,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,r,n)}}class Yt extends Pt{getDefaultAbi(){return D.abi}constructor(t,e,r,n,i){super(t,e,r,n,i),this.abi=i||this.getDefaultAbi()}async isTokenAllowed(t){return await this.contract.isTokenAllowed(t)}async getToken(t){return await this.contract.getToken(t)}async calculateFee(t,e,r){const n=this.amountToUnits(t,e.toString(),r),i=await this.contract.calculateFee(t,n);return this.unitsToAmount(t,i,r)}}async function Xt(t){return new Promise(e=>{setTimeout(e,t)})}function Qt(t){return null!=t}async function te(t,e){const r=h(e);let n=await t._legacySignMessage(r);n=n.substr(2);const i="0x"+n.slice(0,64),s="0x"+n.slice(64,128);let a="0x"+n.slice(128,130);return"0x00"===a&&(a="0x1b"),"0x01"===a&&(a="0x1c"),{v:a,r:i,s}}async function ee(t,e){const n=r.solidityPackedKeccak256(["bytes"],[r.hexlify(r.toUtf8Bytes(e))]),i=r.toBeArray(n);try{return await t.signMessage(i)}catch(e){const r=await t.provider.getNetwork(),n=Number(r.chainId);if(8996===Number(n))return console.log("Signing message with _legacySignMessage"),await t._legacySignMessage(i)}}class re extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}}class ne extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}}class ie extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}}class se extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}}class ae extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}}class oe extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}}class ce extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}}const ue=Symbol.for("@libp2p/peer-id"),le=Symbol.for("@libp2p/service-capabilities");function de(t){if(t instanceof Uint8Array&&"Uint8Array"===t.constructor.name)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}class he{name;prefix;baseEncode;constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class fe{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,r){this.name=t,this.prefix=e;const n=e.codePointAt(0);if(void 0===n)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(t){if("string"==typeof t){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(t){return pe(this,t)}}class ge{decoders;constructor(t){this.decoders=t}or(t){return pe(this,t)}decode(t){const e=this.decoders[t[0]];if(null!=e)return e.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function pe(t,e){return new ge({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class we{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new he(t,e,r),this.decoder=new fe(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}function me({name:t,prefix:e,encode:r,decode:n}){return new we(t,e,r,n)}function ye({name:t,prefix:e,alphabet:r}){const{encode:n,decode:i}=function(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),a=s.charCodeAt(0);if(255!==r[a])throw new TypeError(s+" is ambiguous");r[a]=i}var o=t.length,c=t.charAt(0),u=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function d(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return new Uint8Array;var e=0;if(" "!==t[e]){for(var n=0,i=0;t[e]===c;)n++,e++;for(var s=(t.length-e)*u+1>>>0,a=new Uint8Array(s);t[e];){var l=r[t.charCodeAt(e)];if(255===l)return;for(var d=0,h=s-1;(0!==l||d<i)&&-1!==h;h--,d++)a[h]=(l+=o*a[h]>>>0)%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");i=d,e++}if(" "!==t[e]){for(var f=s-i;f!==s&&0===a[f];)f++;for(var g=new Uint8Array(n+(s-f)),p=n;f!==s;)g[p++]=a[f++];return g}}}return{encode:function(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===e.length)return"";for(var r=0,n=0,i=0,s=e.length;i!==s&&0===e[i];)i++,r++;for(var a=(s-i)*l+1>>>0,u=new Uint8Array(a);i!==s;){for(var d=e[i],h=0,f=a-1;(0!==d||h<n)&&-1!==f;f--,h++)u[f]=(d+=256*u[f]>>>0)%o>>>0,d=d/o>>>0;if(0!==d)throw new Error("Non-zero carry");n=h,i++}for(var g=a-n;g!==a&&0===u[g];)g++;for(var p=c.repeat(r);g<a;++g)p+=t.charAt(u[g]);return p},decodeUnsafe:d,decode:function(t){var r=d(t);if(r)return r;throw new Error(`Non-${e} character`)}}}(r,t);return me({prefix:e,name:t,encode:n,decode:t=>de(i(t))})}function be({name:t,prefix:e,bitsPerChar:r,alphabet:n}){const i=function(t){const e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}(n);return me({prefix:e,name:t,encode:t=>function(t,e,r){const n="="===e[e.length-1],i=(1<<r)-1;let s="",a=0,o=0;for(let n=0;n<t.length;++n)for(o=o<<8|t[n],a+=8;a>r;)a-=r,s+=e[i&o>>a];if(0!==a&&(s+=e[i&o<<r-a]),n)for(;s.length*r&7;)s+="=";return s}(t,n,r),decode:e=>function(t,e,r,n){let i=t.length;for(;"="===t[i-1];)--i;const s=new Uint8Array(i*r/8|0);let a=0,o=0,c=0;for(let u=0;u<i;++u){const i=e[t[u]];if(void 0===i)throw new SyntaxError(`Non-${n} character`);o=o<<r|i,a+=r,a>=8&&(a-=8,s[c++]=255&o>>a)}if(a>=r||255&o<<8-a)throw new SyntaxError("Unexpected end of data");return s}(e,i,r,t)})}const ve=ye({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});ye({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});const Ee=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});const Se=ye({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"});ye({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ae=Math.pow(2,31),Te=Math.pow(2,7),xe=Math.pow(2,14),ke=Math.pow(2,21),Ce=Math.pow(2,28),Fe=Math.pow(2,35),De=Math.pow(2,42),Oe=Math.pow(2,49),Pe=Math.pow(2,56),Ie=Math.pow(2,63),Ne={encode:function t(e,r,n){r=r||[];for(var i=n=n||0;e>=Ae;)r[n++]=255&e|128,e/=128;for(;-128&e;)r[n++]=255&e|128,e>>>=7;return r[n]=0|e,t.bytes=n-i+1,r},decode:function t(e,r){var n,i=0,s=0,a=r=r||0,o=e.length;do{if(a>=o)throw t.bytes=0,new RangeError("Could not decode varint");n=e[a++],i+=s<28?(127&n)<<s:(127&n)*Math.pow(2,s),s+=7}while(n>=128);return t.bytes=a-r,i},encodingLength:function(t){return t<Te?1:t<xe?2:t<ke?3:t<Ce?4:t<Fe?5:t<De?6:t<Oe?7:t<Pe?8:t<Ie?9:10}};function Le(t,e=0){return[Ne.decode(t,e),Ne.decode.bytes]}function Ue(t,e,r=0){return Ne.encode(t,e,r),e}function Re(t){return Ne.encodingLength(t)}function Me(t,e){const r=e.byteLength,n=Re(t),i=n+Re(r),s=new Uint8Array(i+r);return Ue(t,s,0),Ue(r,s,n),s.set(e,i),new _e(t,r,e,s)}function Be(t){const e=de(t),[r,n]=Le(e),[i,s]=Le(e.subarray(n)),a=e.subarray(n+s);if(a.byteLength!==i)throw new Error("Incorrect length");return new _e(r,i,a,e)}class _e{code;size;digest;bytes;constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}}function Ge(t,e){const{bytes:r,version:n}=t;return 0===n?function(t,e,r){const{prefix:n}=r;if(n!==ve.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const i=e.get(n);if(null==i){const i=r.encode(t).slice(1);return e.set(n,i),i}return i}(r,je(t),e??ve.encoder):function(t,e,r){const{prefix:n}=r,i=e.get(n);if(null==i){const i=r.encode(t);return e.set(n,i),i}return i}(r,je(t),e??Ee.encoder)}const $e=new WeakMap;function je(t){const e=$e.get(t);if(null==e){const e=new Map;return $e.set(t,e),e}return e}class qe{code;version;multihash;bytes;"/";constructor(t,e,r,n){this.code=e,this.version=t,this.multihash=r,this.bytes=n,this["/"]=n}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:t,multihash:e}=this;if(t!==Ve)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==ze)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return qe.createV0(e)}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:t,digest:e}=this.multihash,r=Me(t,e);return qe.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return qe.equals(this,t)}static equals(t,e){return null!=e&&t.code===e.code&&t.version===e.version&&((r=t.multihash)===(n=e.multihash)||r.code===n.code&&r.size===n.size&&n.bytes instanceof Uint8Array&&function(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}(r.bytes,n.bytes));var r,n}toString(t){return Ge(this,t)}toJSON(){return{"/":Ge(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(null==t)return null;const e=t;if(e instanceof qe)return e;if(null!=e["/"]&&e["/"]===e.bytes||e.asCID===e){const{version:t,code:r,multihash:n,bytes:i}=e;return new qe(t,r,n,i??He(t,r,n.bytes))}if(!0===e[Ke]){const{version:t,multihash:r,code:n}=e,i=Be(r);return qe.create(t,n,i)}return null}static create(t,e,r){if("number"!=typeof e)throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:if(e!==Ve)throw new Error(`Version 0 CID must use dag-pb (code: ${Ve}) block encoding`);return new qe(t,e,r,r.bytes);case 1:{const n=He(t,e,r.bytes);return new qe(t,e,r,n)}default:throw new Error("Invalid version")}}static createV0(t){return qe.create(0,Ve,t)}static createV1(t,e){return qe.create(1,t,e)}static decode(t){const[e,r]=qe.decodeFirst(t);if(0!==r.length)throw new Error("Incorrect length");return e}static decodeFirst(t){const e=qe.inspectBytes(t),r=e.size-e.multihashSize,n=de(t.subarray(r,r+e.multihashSize));if(n.byteLength!==e.multihashSize)throw new Error("Incorrect length");const i=n.subarray(e.multihashSize-e.digestSize),s=new _e(e.multihashCode,e.digestSize,i,n);return[0===e.version?qe.createV0(s):qe.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0;const r=()=>{const[r,n]=Le(t.subarray(e));return e+=n,r};let n=r(),i=Ve;if(18===n?(n=0,e=0):i=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const s=e,a=r(),o=r(),c=e+o;return{version:n,codec:i,multihashCode:a,digestSize:o,multihashSize:c-s,size:c}}static parse(t,e){const[r,n]=function(t,e){switch(t[0]){case"Q":return[ve.prefix,(e??ve).decode(`${ve.prefix}${t}`)];case ve.prefix:return[ve.prefix,(e??ve).decode(t)];case Ee.prefix:return[Ee.prefix,(e??Ee).decode(t)];case Se.prefix:return[Se.prefix,(e??Se).decode(t)];default:if(null==e)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}(t,e),i=qe.decode(n);if(0===i.version&&"Q"!==t[0])throw Error("Version 0 CID string must not include multibase prefix");return je(i).set(r,t),i}}const Ve=112,ze=18;function He(t,e,r){const n=Re(t),i=n+Re(e),s=new Uint8Array(i+r.byteLength);return Ue(t,s,0),Ue(e,s,n),s.set(r,i),s}const Ke=Symbol.for("@ipld/js-cid/CID"),Ze=de,Je=function(t,e){if(null!=e?.truncate&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Me(0,Ze(t))},We=Symbol.for("@achingbrain/uint8arraylist");function Ye(t,e){if(null==e||e<0)throw new RangeError("index is out of bounds");let r=0;for(const n of t){const t=r+n.byteLength;if(e<t)return{buf:n,index:e-r};r=t}throw new RangeError("index is out of bounds")}function Xe(t){return Boolean(t?.[We])}class Qe{bufs;length;[We]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(const r of t)if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.push(r);else{if(!Xe(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");e+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(const r of t.reverse())if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.unshift(r);else{if(!Xe(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");e+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=e}get(t){const e=Ye(this.bufs,t);return e.buf[e.index]}set(t,e){const r=Ye(this.bufs,t);r.buf[r.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(e+r,t[r]);else{if(!Xe(t))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<t.length;r++)this.set(e+r,t.get(r))}}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(t>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(t,e){const{bufs:r,length:n}=this._subList(t,e);return L(r,n)}subarray(t,e){const{bufs:r,length:n}=this._subList(t,e);return 1===r.length?r[0]:L(r,n)}sublist(t,e){const{bufs:r,length:n}=this._subList(t,e),i=new Qe;return i.length=n,i.bufs=[...r],i}_subList(t,e){if((t=t??0)<0&&(t=this.length+t),(e=e??this.length)<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(0===t&&e===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let i=0;i<this.bufs.length;i++){const s=this.bufs[i],a=n,o=a+s.byteLength;if(n=o,t>=o)continue;const c=t>=a&&t<o,u=e>a&&e<=o;if(c&&u){if(t===a&&e===o){r.push(s);break}const n=t-a;r.push(s.subarray(n,n+(e-t)));break}if(c){if(0===t){r.push(s);continue}r.push(s.subarray(t-a))}else{if(u){if(e===o){r.push(s);break}r.push(s.subarray(0,e-a));break}r.push(s)}}return{bufs:r,length:e-t}}indexOf(t,e=0){if(!(Xe(t)||t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),0===t.length)return e>this.length?this.length:e;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const i=new Int32Array(256);for(let t=0;t<256;t++)i[t]=-1;for(let t=0;t<n;t++)i[r[t]]=t;const s=i,a=this.byteLength-r.byteLength,o=r.byteLength-1;let c;for(let t=e;t<=a;t+=c){c=0;for(let e=o;e>=0;e--){const n=this.get(t+e);if(r[e]!==n){c=Math.max(1,e-s[n]);break}}if(0===c)return t}return-1}getInt8(t){const e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){const r=I(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,e),this.write(r,t)}getInt16(t,e){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,e)}setInt16(t,e,r){const n=N(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,e,r),this.write(n,t)}getInt32(t,e){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,e)}setInt32(t,e,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,e,r),this.write(n,t)}getBigInt64(t,e){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,e)}setBigInt64(t,e,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,e,r),this.write(n,t)}getUint8(t){const e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){const r=I(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,e),this.write(r,t)}getUint16(t,e){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,e)}setUint16(t,e,r){const n=N(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,e,r),this.write(n,t)}getUint32(t,e){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,e)}setUint32(t,e,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,e,r),this.write(n,t)}getBigUint64(t,e){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,e)}setBigUint64(t,e,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,e,r),this.write(n,t)}getFloat32(t,e){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,e)}setFloat32(t,e,r){const n=N(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,e,r),this.write(n,t)}getFloat64(t,e){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,e)}setFloat64(t,e,r){const n=N(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,e,r),this.write(n,t)}equals(t){if(null==t)return!1;if(!(t instanceof Qe))return!1;if(t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!U(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){const r=new Qe;return r.bufs=t,null==e&&(e=t.reduce((t,e)=>t+e.byteLength,0)),r.length=e,r}}const tr=parseInt("11111",2),er=parseInt("10000000",2),rr=parseInt("01111111",2),nr={0:ar,1:ar,2:function(t,e){const r=sr(t,e),n=e.offset,i=e.offset+r,s=[];for(let e=n;e<i;e++)e===n&&0===t[e]||s.push(t[e]);return e.offset+=r,Uint8Array.from(s)},3:function(t,e){const r=sr(t,e),n=t[e.offset];e.offset++;const i=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,0!==n)throw new Error("Unused bits in bit string is unimplemented");return i},4:function(t,e){const r=sr(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n},5:function(t,e){return e.offset++,null},6:function(t,e){const r=sr(t,e),n=e.offset+r,i=t[e.offset];e.offset++;let s=0,a=0;i<40?(s=0,a=i):i<80?(s=1,a=i-40):(s=2,a=i-80);let o=`${s}.${a}`,c=[];for(;e.offset<n;){const r=t[e.offset];if(e.offset++,c.push(127&r),r<128){c.reverse();let t=0;for(let e=0;e<c.length;e++)t+=c[e]<<7*e;o+=`.${t}`,c=[]}}return o},16:ar,22:ar,48:ar};function ir(t,e={offset:0}){const r=t[e.offset]&tr;if(e.offset++,null!=nr[r])return nr[r](t,e);throw new Error("No decoder for tag "+r)}function sr(t,e){let r=0;if((t[e.offset]&er)===er){const n=t[e.offset]&rr;let i="0x";e.offset++;for(let r=0;r<n;r++,e.offset++)i+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(i,16)}else r=t[e.offset],e.offset++;return r}function ar(t,e){sr(t,e);const r=[];for(;!(e.offset>=t.byteLength);){const n=ir(t,e);if(null===n)break;r.push(n)}return r}function or(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=function(t){let e=t.toString(16);e.length%2==1&&(e="0"+e);const r=new Qe;for(let t=0;t<e.length;t+=2)r.append(Uint8Array.from([parseInt(`${e[t]}${e[t+1]}`,16)]));return r}(t.byteLength);return new Qe(Uint8Array.from([e.byteLength|er]),e)}function cr(t){const e=new Qe;return!(128&~t.subarray()[0])&&e.append(Uint8Array.from([0])),e.append(t),new Qe(Uint8Array.from([2]),or(e),e)}function ur(t){const e=Uint8Array.from([0]),r=new Qe(e,t);return new Qe(Uint8Array.from([3]),or(r),r)}function lr(t,e=48){const r=new Qe;for(const e of t)r.append(e);return new Qe(Uint8Array.from([e]),or(r),r)}const dr=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),hr=Uint8Array.from([6,5,43,129,4,0,34]),fr=Uint8Array.from([6,5,43,129,4,0,35]),gr={ext:!0,kty:"EC",crv:"P-256"},pr={ext:!0,kty:"EC",crv:"P-384"},wr={ext:!0,kty:"EC",crv:"P-521"};function mr(t){if("P-256"===t)return dr;if("P-384"===t)return hr;if("P-521"===t)return fr;throw new re(`Invalid curve ${t}`)}class yr{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){var t;return null==this._raw&&(this._raw=(t=this.jwk,lr([cr(Uint8Array.from([1])),lr([mr(t.crv)],160),lr([ur(new Qe(Uint8Array.from([4]),R(t.x??"","base64url"),R(t.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return Je(ha(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return ve.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&U(this.raw,t.raw)}async verify(t,e,r){return async function(t,e,r,n){const i=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,e,r.subarray());return n?.signal?.throwIfAborted(),s}(this.jwk,e,t,r)}}function br(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function vr(t,e=""){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e&&`"${e}" `}expected integer >= 0, got ${t}`)}function Er(t,e,r=""){const n=br(t),i=t?.length,s=void 0!==e;if(!n||s&&i!==e)throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(s?` of length ${e}`:"")+", got "+(n?`length=${i}`:"type="+typeof t));return t}function Sr(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash must wrapped by utils.createHasher");vr(t.outputLen),vr(t.blockLen)}function Ar(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Tr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function xr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function kr(t,e){return t<<32-e|t>>>e}const Cr=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Fr=/* @__PURE__ */Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Dr(t){if(Er(t),Cr)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Fr[t[r]];return e}function Or(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Pr(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(Cr)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let e=0,i=0;e<r;e++,i+=2){const r=Or(t.charCodeAt(i)),s=Or(t.charCodeAt(i+1));if(void 0===r||void 0===s)throw new Error('hex string expected, got non-hex character "'+(t[i]+t[i+1])+'" at index '+i);n[e]=16*r+s}return n}function Ir(...t){let e=0;for(let r=0;r<t.length;r++){const n=t[r];Er(n),e+=n.length}const r=new Uint8Array(e);for(let e=0,n=0;e<t.length;e++){const i=t[e];r.set(i,n),n+=i.length}return r}function Nr(t,e={}){const r=(e,r)=>t(r).update(e).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=e=>t(e),Object.assign(r,e),Object.freeze(r)}function Lr(t=32){const e="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof e?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}const Ur=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Rr(t,e,r){return t&e^t&r^e&r}class Mr{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,r,n){this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(t),this.view=xr(this.buffer)}update(t){Ar(this),Er(t);const{view:e,buffer:r,blockLen:n}=this,i=t.length;for(let s=0;s<i;){const a=Math.min(n-this.pos,i-s);if(a!==n)r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n&&(this.process(e,0),this.pos=0);else{const e=xr(t);for(;n<=i-s;s+=n)this.process(e,s)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){Ar(this),function(t,e){Er(t,void 0,"digestInto() output");const r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}(t,this),this.finished=!0;const{buffer:e,view:r,blockLen:n,isLE:i}=this;let{pos:s}=this;e[s++]=128,Tr(this.buffer.subarray(s)),this.padOffset>n-s&&(this.process(r,0),s=0);for(let t=s;t<n;t++)e[t]=0;r.setBigUint64(n-8,BigInt(8*this.length),i),this.process(r,0);const a=xr(t),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const c=o/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<c;t++)a.setUint32(4*t,u[t],i)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||=new this.constructor,t.set(...this.get());const{blockLen:e,buffer:r,length:n,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=n,t.pos=a,n%e&&t.buffer.set(r),t}clone(){return this._cloneInto()}}const Br=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_r=/* @__PURE__ */Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Gr=/* @__PURE__ */BigInt(2**32-1),$r=/* @__PURE__ */BigInt(32);function jr(t,e=!1){return e?{h:Number(t&Gr),l:Number(t>>$r&Gr)}:{h:0|Number(t>>$r&Gr),l:0|Number(t&Gr)}}const qr=(t,e,r)=>t>>>r,Vr=(t,e,r)=>t<<32-r|e>>>r,zr=(t,e,r)=>t>>>r|e<<32-r,Hr=(t,e,r)=>t<<32-r|e>>>r,Kr=(t,e,r)=>t<<64-r|e>>>r-32,Zr=(t,e,r)=>t>>>r-32|e<<64-r;function Jr(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:0|i}}const Wr=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Yr=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Xr=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Qr=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,tn=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),en=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,rn=/* @__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]),nn=/* @__PURE__ */new Uint32Array(64);class sn extends Mr{constructor(t){super(64,t,8,!1)}get(){const{A:t,B:e,C:r,D:n,E:i,F:s,G:a,H:o}=this;return[t,e,r,n,i,s,a,o]}set(t,e,r,n,i,s,a,o){this.A=0|t,this.B=0|e,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|a,this.H=0|o}process(t,e){for(let r=0;r<16;r++,e+=4)nn[r]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=nn[t-15],r=nn[t-2],n=kr(e,7)^kr(e,18)^e>>>3,i=kr(r,17)^kr(r,19)^r>>>10;nn[t]=i+nn[t-7]+n+nn[t-16]|0}let{A:r,B:n,C:i,D:s,E:a,F:o,G:c,H:u}=this;for(let t=0;t<64;t++){const e=u+(kr(a,6)^kr(a,11)^kr(a,25))+((l=a)&o^~l&c)+rn[t]+nn[t]|0,d=(kr(r,2)^kr(r,13)^kr(r,22))+Rr(r,n,i)|0;u=c,c=o,o=a,a=s+e|0,s=i,i=n,n=r,r=e+d|0}var l;r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,s,a,o,c,u)}roundClean(){Tr(nn)}destroy(){this.set(0,0,0,0,0,0,0,0),Tr(this.buffer)}}class an extends sn{A=0|Br[0];B=0|Br[1];C=0|Br[2];D=0|Br[3];E=0|Br[4];F=0|Br[5];G=0|Br[6];H=0|Br[7];constructor(){super(32)}}const on=/* @__PURE__ */(()=>function(t,e=!1){const r=t.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:r,l:a}=jr(t[s],e);[n[s],i[s]]=[r,a]}return[n,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(t=>BigInt(t))))(),cn=/* @__PURE__ */(()=>on[0])(),un=/* @__PURE__ */(()=>on[1])(),ln=/* @__PURE__ */new Uint32Array(80),dn=/* @__PURE__ */new Uint32Array(80);class hn extends Mr{constructor(t){super(128,t,16,!1)}get(){const{Ah:t,Al:e,Bh:r,Bl:n,Ch:i,Cl:s,Dh:a,Dl:o,Eh:c,El:u,Fh:l,Fl:d,Gh:h,Gl:f,Hh:g,Hl:p}=this;return[t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p]}set(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p){this.Ah=0|t,this.Al=0|e,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|d,this.Gh=0|h,this.Gl=0|f,this.Hh=0|g,this.Hl=0|p}process(t,e){for(let r=0;r<16;r++,e+=4)ln[r]=t.getUint32(e),dn[r]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|ln[t-15],r=0|dn[t-15],n=zr(e,r,1)^zr(e,r,8)^qr(e,0,7),i=Hr(e,r,1)^Hr(e,r,8)^Vr(e,r,7),s=0|ln[t-2],a=0|dn[t-2],o=zr(s,a,19)^Kr(s,a,61)^qr(s,0,6),c=Hr(s,a,19)^Zr(s,a,61)^Vr(s,a,6),u=Xr(i,c,dn[t-7],dn[t-16]),l=Qr(u,n,o,ln[t-7],ln[t-16]);ln[t]=0|l,dn[t]=0|u}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:a,Cl:o,Dh:c,Dl:u,Eh:l,El:d,Fh:h,Fl:f,Gh:g,Gl:p,Hh:w,Hl:m}=this;for(let t=0;t<80;t++){const e=zr(l,d,14)^zr(l,d,18)^Kr(l,d,41),y=Hr(l,d,14)^Hr(l,d,18)^Zr(l,d,41),b=l&h^~l&g,v=tn(m,y,d&f^~d&p,un[t],dn[t]),E=en(v,w,e,b,cn[t],ln[t]),S=0|v,A=zr(r,n,28)^Kr(r,n,34)^Kr(r,n,39),T=Hr(r,n,28)^Zr(r,n,34)^Zr(r,n,39),x=r&i^r&a^i&a,k=n&s^n&o^s&o;w=0|g,m=0|p,g=0|h,p=0|f,h=0|l,f=0|d,({h:l,l:d}=Jr(0|c,0|u,0|E,0|S)),c=0|a,u=0|o,a=0|i,o=0|s,i=0|r,s=0|n;const C=Wr(S,T,k);r=Yr(C,E,A,x),n=0|C}({h:r,l:n}=Jr(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=Jr(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=Jr(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=Jr(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:d}=Jr(0|this.Eh,0|this.El,0|l,0|d)),({h,l:f}=Jr(0|this.Fh,0|this.Fl,0|h,0|f)),({h:g,l:p}=Jr(0|this.Gh,0|this.Gl,0|g,0|p)),({h:w,l:m}=Jr(0|this.Hh,0|this.Hl,0|w,0|m)),this.set(r,n,i,s,a,o,c,u,l,d,h,f,g,p,w,m)}roundClean(){Tr(ln,dn)}destroy(){Tr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class fn extends hn{Ah=0|_r[0];Al=0|_r[1];Bh=0|_r[2];Bl=0|_r[3];Ch=0|_r[4];Cl=0|_r[5];Dh=0|_r[6];Dl=0|_r[7];Eh=0|_r[8];El=0|_r[9];Fh=0|_r[10];Fl=0|_r[11];Gh=0|_r[12];Gl=0|_r[13];Hh=0|_r[14];Hl=0|_r[15];constructor(){super(64)}}const gn=/* @__PURE__ */Nr(()=>new an
2
- /* @__PURE__ */,Ur(1)),pn=/* @__PURE__ */Nr(()=>new fn
3
- /* @__PURE__ */,Ur(3)),wn=/* @__PURE__ */BigInt(0),mn=/* @__PURE__ */BigInt(1);function yn(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}" `)+"expected boolean, got type="+typeof t);return t}function bn(t){if("bigint"==typeof t){if(!Cn(t))throw new Error("positive bigint expected, got "+t)}else vr(t);return t}function vn(t){const e=bn(t).toString(16);return 1&e.length?"0"+e:e}function En(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?wn:BigInt("0x"+t)}function Sn(t){return En(Dr(t))}function An(t){return En(Dr(kn(Er(t)).reverse()))}function Tn(t,e){vr(e);const r=Pr((t=bn(t)).toString(16).padStart(2*e,"0"));if(r.length!==e)throw new Error("number too large");return r}function xn(t,e){return Tn(t,e).reverse()}function kn(t){return Uint8Array.from(t)}const Cn=t=>"bigint"==typeof t&&wn<=t;function Fn(t,e,r,n){if(!function(t,e,r){return Cn(t)&&Cn(e)&&Cn(r)&&e<=t&&t<r}(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}const Dn=t=>(mn<<BigInt(t))-mn;function On(t,e={},r={}){if(!t||"object"!=typeof t)throw new Error("expected valid options object");const n=(e,r)=>Object.entries(e).forEach(([e,n])=>function(e,r,n){const i=t[e];if(n&&void 0===i)return;const s=typeof i;if(s!==r||null===i)throw new Error(`param "${e}" is invalid: expected ${r}, got ${s}`)}(e,n,r));n(e,!1),n(r,!0)}function Pn(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(void 0!==i)return i;const s=t(r,...n);return e.set(r,s),s}}const In=/* @__PURE__ */BigInt(0),Nn=/* @__PURE__ */BigInt(1),Ln=/* @__PURE__ */BigInt(2),Un=/* @__PURE__ */BigInt(3),Rn=/* @__PURE__ */BigInt(4),Mn=/* @__PURE__ */BigInt(5),Bn=/* @__PURE__ */BigInt(7),_n=/* @__PURE__ */BigInt(8),Gn=/* @__PURE__ */BigInt(9),$n=/* @__PURE__ */BigInt(16);function jn(t,e){const r=t%e;return r>=In?r:e+r}function qn(t,e,r){let n=t;for(;e-- >In;)n*=n,n%=r;return n}function Vn(t,e){if(t===In)throw new Error("invert: expected non-zero number");if(e<=In)throw new Error("invert: expected positive modulus, got "+e);let r=jn(t,e),n=e,i=In,s=Nn;for(;r!==In;){const t=n%r,e=i-s*(n/r);n=r,r=t,i=s,s=e}if(n!==Nn)throw new Error("invert: does not exist");return jn(i,e)}function zn(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Hn(t,e){const r=t.pow(e,(t.ORDER+Nn)/Rn);return zn(t,r,e),r}function Kn(t,e){const r=(t.ORDER-Mn)/_n,n=t.mul(e,Ln),i=t.pow(n,r),s=t.mul(e,i),a=t.mul(t.mul(s,Ln),i),o=t.mul(s,t.sub(a,t.ONE));return zn(t,o,e),o}function Zn(t){if(t<Un)throw new Error("sqrt is not defined for small field");let e=t-Nn,r=0;for(;e%Ln===In;)e/=Ln,r++;let n=Ln;const i=Qn(t);for(;1===Yn(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Hn;let s=i.pow(n,e);const a=(e+Nn)/Ln;return function(t,n){if(t.is0(n))return n;if(1!==Yn(t,n))throw new Error("Cannot find square root");let i=r,o=t.mul(t.ONE,s),c=t.pow(n,e),u=t.pow(n,a);for(;!t.eql(c,t.ONE);){if(t.is0(c))return t.ZERO;let e=1,r=t.sqr(c);for(;!t.eql(r,t.ONE);)if(e++,r=t.sqr(r),e===i)throw new Error("Cannot find square root");const n=Nn<<BigInt(i-e-1),s=t.pow(o,n);i=e,o=t.sqr(s),c=t.mul(c,o),u=t.mul(u,s)}return u}}const Jn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Wn(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((e,r,i)=>t.is0(r)?e:(n[i]=e,t.mul(e,r)),t.ONE),s=t.inv(i);return e.reduceRight((e,r,i)=>t.is0(r)?e:(n[i]=t.mul(e,n[i]),t.mul(e,r)),s),n}function Yn(t,e){const r=t.pow(e,(t.ORDER-Nn)/Ln),n=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!n&&!i&&!s)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}class Xn{ORDER;BITS;BYTES;isLE;ZERO=In;ONE=Nn;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=In)throw new Error("invalid field: expected ORDER > 0, got "+t);let r;this.isLE=!1,null!=e&&"object"==typeof e&&("number"==typeof e.BITS&&(r=e.BITS),"function"==typeof e.sqrt&&(this.sqrt=e.sqrt),"boolean"==typeof e.isLE&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),"boolean"==typeof e.modFromBytes&&(this._mod=e.modFromBytes));const{nBitLength:n,nByteLength:i}=function(t,e){void 0!==e&&vr(e);const r=void 0!==e?e:t.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return jn(t,this.ORDER)}isValid(t){if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return In<=t&&t<this.ORDER}is0(t){return t===In}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&Nn)===Nn}neg(t){return jn(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return jn(t*t,this.ORDER)}add(t,e){return jn(t+e,this.ORDER)}sub(t,e){return jn(t-e,this.ORDER)}mul(t,e){return jn(t*e,this.ORDER)}pow(t,e){return function(t,e,r){if(r<In)throw new Error("invalid exponent, negatives unsupported");if(r===In)return t.ONE;if(r===Nn)return e;let n=t.ONE,i=e;for(;r>In;)r&Nn&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Nn;return n}(this,t,e)}div(t,e){return jn(t*Vn(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Vn(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=(e=this.ORDER)%Rn===Un?Hn:e%_n===Mn?Kn:e%$n===Gn?function(t){const e=Qn(t),r=Zn(t),n=r(e,e.neg(e.ONE)),i=r(e,n),s=r(e,e.neg(n)),a=(t+Bn)/$n;return(t,e)=>{let r=t.pow(e,a),o=t.mul(r,n);const c=t.mul(r,i),u=t.mul(r,s),l=t.eql(t.sqr(o),e),d=t.eql(t.sqr(c),e);r=t.cmov(r,o,l),o=t.cmov(u,c,d);const h=t.eql(t.sqr(o),e),f=t.cmov(r,o,h);return zn(t,f,e),f}}(e):Zn(e)),this._sqrt(this,t);var e}toBytes(t){return this.isLE?xn(t,this.BYTES):Tn(t,this.BYTES)}fromBytes(t,e=!1){Er(t);const{_lengths:r,BYTES:n,isLE:i,ORDER:s,_mod:a}=this;if(r){if(!r.includes(t.length)||t.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);const e=new Uint8Array(n);e.set(t,i?0:e.length-t.length),t=e}if(t.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let o=i?An(t):Sn(t);if(a&&(o=jn(o,s)),!e&&!this.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o}invertBatch(t){return Wn(this,t)}cmov(t,e,r){return r?e:t}}function Qn(t,e={}){return new Xn(t,e)}function ti(t){if("bigint"!=typeof t)throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function ei(t){const e=ti(t);return e+Math.ceil(e/2)}const ri=/* @__PURE__ */BigInt(0),ni=/* @__PURE__ */BigInt(1);function ii(t,e){const r=e.negate();return t?r:e}function si(t,e){const r=Wn(t.Fp,e.map(t=>t.Z));return e.map((e,n)=>t.fromAffine(e.toAffine(r[n])))}function ai(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function oi(t,e){ai(t,e);const r=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:Dn(t),maxNumber:r,shiftBy:BigInt(t)}}function ci(t,e,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:a}=r;let o=Number(t&i),c=t>>a;o>n&&(o-=s,c+=ni);const u=e*n;return{nextN:c,offset:u+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:e%2!=0,offsetF:u}}const ui=new WeakMap,li=new WeakMap;function di(t){return li.get(t)||1}function hi(t){if(t!==ri)throw new Error("invalid wNAF")}class fi{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,r=this.ZERO){let n=t;for(;e>ri;)e&ni&&(r=r.add(n)),n=n.double(),e>>=ni;return r}precomputeWindow(t,e){const{windows:r,windowSize:n}=oi(e,this.bits),i=[];let s=t,a=s;for(let t=0;t<r;t++){a=s,i.push(a);for(let t=1;t<n;t++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,e,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const s=oi(t,this.bits);for(let t=0;t<s.windows;t++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:l,offsetF:d}=ci(r,t,s);r=a,c?i=i.add(ii(l,e[d])):n=n.add(ii(u,e[o]))}return hi(r),{p:n,f:i}}wNAFUnsafe(t,e,r,n=this.ZERO){const i=oi(t,this.bits);for(let t=0;t<i.windows&&r!==ri;t++){const{nextN:s,offset:a,isZero:o,isNeg:c}=ci(r,t,i);if(r=s,!o){const t=e[a];n=n.add(c?t.negate():t)}}return hi(r),n}getPrecomputes(t,e,r){let n=ui.get(e);return n||(n=this.precomputeWindow(e,t),1!==t&&("function"==typeof r&&(n=r(n)),ui.set(e,n))),n}cached(t,e,r){const n=di(t);return this.wNAF(n,this.getPrecomputes(n,t,r),e)}unsafe(t,e,r,n){const i=di(t);return 1===i?this._unsafeLadder(t,e,n):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),e,n)}createCache(t,e){ai(e,this.bits),li.set(t,e),ui.delete(t)}hasCache(t){return 1!==di(t)}}function gi(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(t){On(t,Jn.reduce((t,e)=>(t[e]="function",t),{ORDER:"bigint",BYTES:"number",BITS:"number"}))}(e),e}return Qn(t,{isLE:r})}function pi(t,e,r={},n){if(void 0===n&&(n="edwards"===t),!e||"object"!=typeof e)throw new Error(`expected valid ${t} CURVE object`);for(const t of["p","n","h"]){const r=e[t];if(!("bigint"==typeof r&&r>ri))throw new Error(`CURVE.${t} must be positive bigint`)}const i=gi(e.p,r.Fp,n),s=gi(e.n,r.Fn,n),a=["Gx","Gy","a","weierstrass"===t?"b":"d"];for(const t of a)if(!i.isValid(e[t]))throw new Error(`CURVE.${t} must be valid field element of CURVE.Fp`);return{CURVE:e=Object.freeze(Object.assign({},e)),Fp:i,Fn:s}}function wi(t,e){return function(r){const n=t(r);return{secretKey:n,publicKey:e(n)}}}const mi=BigInt(0),yi=BigInt(1),bi=BigInt(2),vi=BigInt(8);function Ei(t,e={}){const r=pi("edwards",t,e,e.FpFnLE),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:a}=s;On(e,{},{uvRatio:"function"});const o=bi<<BigInt(8*i.BYTES)-yi,c=t=>n.create(t),u=e.uvRatio||((t,e)=>{try{return{isValid:!0,value:n.sqrt(n.div(t,e))}}catch(t){return{isValid:!1,value:mi}}});if(!function(t,e,r,n){const i=t.sqr(r),s=t.sqr(n),a=t.add(t.mul(e.a,i),s),o=t.add(t.ONE,t.mul(e.d,t.mul(i,s)));return t.eql(a,o)}(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(t,e,r=!1){return Fn("coordinate "+t,e,r?yi:mi,o),e}function d(t){if(!(t instanceof g))throw new Error("EdwardsPoint expected")}const h=Pn((t,e)=>{const{X:r,Y:i,Z:s}=t,a=t.is0();null==e&&(e=a?vi:n.inv(s));const o=c(r*e),u=c(i*e),l=n.mul(s,e);if(a)return{x:mi,y:yi};if(l!==yi)throw new Error("invZ was invalid");return{x:o,y:u}}),f=Pn(t=>{const{a:e,d:r}=s;if(t.is0())throw new Error("bad point: ZERO");const{X:n,Y:i,Z:a,T:o}=t,u=c(n*n),l=c(i*i),d=c(a*a),h=c(d*d),f=c(u*e);if(c(d*c(f+l))!==c(h+c(r*c(u*l))))throw new Error("bad point: equation left != right (1)");if(c(n*i)!==c(a*o))throw new Error("bad point: equation left != right (2)");return!0});class g{static BASE=new g(s.Gx,s.Gy,yi,c(s.Gx*s.Gy));static ZERO=new g(mi,yi,yi,mi);static Fp=n;static Fn=i;X;Y;Z;T;constructor(t,e,r,n){this.X=l("x",t),this.Y=l("y",e),this.Z=l("z",r,!0),this.T=l("t",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){if(t instanceof g)throw new Error("extended point not allowed");const{x:e,y:r}=t||{};return l("x",e),l("y",r),new g(e,r,yi,c(e*r))}static fromBytes(t,e=!1){const r=n.BYTES,{a:i,d:a}=s;t=kn(Er(t,r,"point")),yn(e,"zip215");const l=kn(t),d=t[r-1];l[r-1]=-129&d;const h=An(l);Fn("point.y",h,mi,e?o:n.ORDER);const f=c(h*h),p=c(f-yi),w=c(a*f-i);let{isValid:m,value:y}=u(p,w);if(!m)throw new Error("bad point: invalid y coordinate");const b=(y&yi)===yi,v=!!(128&d);if(!e&&y===mi&&v)throw new Error("bad point: x=0 and x_0=1");return v!==b&&(y=c(-y)),g.fromAffine({x:y,y:h})}static fromHex(t,e=!1){return g.fromBytes(Pr(t),e)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return p.createCache(this,t),e||this.multiply(bi),this}assertValidity(){f(this)}equals(t){d(t);const{X:e,Y:r,Z:n}=this,{X:i,Y:s,Z:a}=t,o=c(e*a),u=c(i*n),l=c(r*a),h=c(s*n);return o===u&&l===h}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:t}=s,{X:e,Y:r,Z:n}=this,i=c(e*e),a=c(r*r),o=c(bi*c(n*n)),u=c(t*i),l=e+r,d=c(c(l*l)-i-a),h=u+a,f=h-o,p=u-a,w=c(d*f),m=c(h*p),y=c(d*p),b=c(f*h);return new g(w,m,b,y)}add(t){d(t);const{a:e,d:r}=s,{X:n,Y:i,Z:a,T:o}=this,{X:u,Y:l,Z:h,T:f}=t,p=c(n*u),w=c(i*l),m=c(o*r*f),y=c(a*h),b=c((n+i)*(u+l)-p-w),v=y-m,E=y+m,S=c(w-e*p),A=c(b*v),T=c(E*S),x=c(b*S),k=c(v*E);return new g(A,T,k,x)}subtract(t){return this.add(t.negate())}multiply(t){if(!i.isValidNot0(t))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:e,f:r}=p.cached(this,t,t=>si(g,t));return si(g,[e,r])[0]}multiplyUnsafe(t,e=g.ZERO){if(!i.isValid(t))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return t===mi?g.ZERO:this.is0()||t===yi?this:p.unsafe(this,t,t=>si(g,t),e)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return p.unsafe(this,s.n).is0()}toAffine(t){return h(this,t)}clearCofactor(){return a===yi?this:this.multiplyUnsafe(a)}toBytes(){const{x:t,y:e}=this.toAffine(),r=n.toBytes(e);return r[r.length-1]|=t&yi?128:0,r}toHex(){return Dr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const p=new fi(g,i.BITS);return g.BASE.precompute(8),g}const Si=BigInt(1),Ai=BigInt(2),Ti=BigInt(5),xi=BigInt(8),ki=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ci=/* @__PURE__ */(()=>({p:ki,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xi,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Fi(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Di=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Oi=/* @__PURE__ */Ei(Ci,{uvRatio:function(t,e){const r=ki,n=jn(e*e*e,r),i=function(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=ki,a=t*t%s*t%s,o=qn(a,Ai,s)*a%s,c=qn(o,Si,s)*t%s,u=qn(c,Ti,s)*c%s,l=qn(u,e,s)*u%s,d=qn(l,r,s)*l%s,h=qn(d,n,s)*d%s,f=qn(h,i,s)*h%s,g=qn(f,i,s)*h%s,p=qn(g,e,s)*u%s;return{pow_p_5_8:qn(p,Ai,s)*t%s,b2:a}}(t*jn(n*n*e,r)).pow_p_5_8;let s=jn(t*n*i,r);const a=jn(e*s*s,r),o=s,c=jn(s*Di,r),u=a===t,l=a===jn(-t,r),d=a===jn(-t*Di,r);return u&&(s=o),(l||d)&&(s=c),(jn(s,r)&Nn)===Nn&&(s=jn(-s,r)),{isValid:u||l,value:s}}});function Pi(t){return function(t,e,r={}){if("function"!=typeof e)throw new Error('"hash" function param is required');On(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:i,Fp:s,Fn:a}=t,o=r.randomBytes||Lr,c=r.adjustScalarBytes||(t=>t),u=r.domain||((t,e,r)=>{if(yn(r,"phflag"),e.length||r)throw new Error("Contexts/pre-hash are not supported");return t});function l(t){return a.create(An(t))}function d(t){const{head:r,prefix:n,scalar:s}=function(t){const r=w.secretKey;Er(t,w.secretKey,"secretKey");const n=Er(e(t),2*r,"hashedSecretKey"),i=c(n.slice(0,r));return{head:i,prefix:n.slice(r,2*r),scalar:l(i)}}(t),a=i.multiply(s),o=a.toBytes();return{head:r,prefix:n,scalar:s,point:a,pointBytes:o}}function h(t){return d(t).pointBytes}function f(t=Uint8Array.of(),...r){const i=Ir(...r);return l(e(u(i,Er(t,void 0,"context"),!!n)))}const g={zip215:!0},p=s.BYTES,w={secretKey:p,publicKey:p,signature:2*p,seed:p};function m(t=o(w.seed)){return Er(t,w.seed,"seed")}const y={getExtendedPublicKey:d,randomSecretKey:m,isValidSecretKey:function(t){return br(t)&&t.length===a.BYTES},isValidPublicKey:function(e,r){try{return!!t.fromBytes(e,r)}catch(t){return!1}},toMontgomery(e){const{y:r}=t.fromBytes(e),n=w.publicKey,i=32===n;if(!i&&57!==n)throw new Error("only defined for 25519 and 448");const a=i?s.div(yi+r,yi-r):s.div(r-yi,r+yi);return s.toBytes(a)},toMontgomerySecret(t){const r=w.secretKey;Er(t,r);const n=e(t.subarray(0,r));return c(n).subarray(0,r)}};return Object.freeze({keygen:wi(m,h),getPublicKey:h,sign:function(t,e,r={}){t=Er(t,void 0,"message"),n&&(t=n(t));const{prefix:s,scalar:o,pointBytes:c}=d(e),u=f(r.context,s,t),l=i.multiply(u).toBytes(),h=f(r.context,l,c,t),g=a.create(u+h*o);if(!a.isValid(g))throw new Error("sign failed: invalid s");return Er(Ir(l,a.toBytes(g)),w.signature,"result")},verify:function(e,r,s,a=g){const{context:o,zip215:c}=a,u=w.signature;e=Er(e,u,"signature"),r=Er(r,void 0,"message"),s=Er(s,w.publicKey,"publicKey"),void 0!==c&&yn(c,"zip215"),n&&(r=n(r));const l=u/2,d=e.subarray(0,l),h=An(e.subarray(l,u));let p,m,y;try{p=t.fromBytes(s,c),m=t.fromBytes(d,c),y=i.multiplyUnsafe(h)}catch(t){return!1}if(!c&&p.isSmallOrder())return!1;const b=f(o,m.toBytes(),p.toBytes(),r);return m.add(p.multiplyUnsafe(b)).subtract(y).clearCofactor().is0()},utils:y,Point:t,lengths:w})}(Oi,pn,Object.assign({adjustScalarBytes:Fi},t))}const Ii=/* @__PURE__ */Pi({});class Ni extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}}class Li extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}}var Ui={get(t=globalThis){const e=t.crypto;if(null==e?.subtle)throw new Li("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 e}};let Ri;const Mi=(async()=>{try{return await Ui.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Bi(t){return null!=t&&"function"==typeof t.then&&"function"==typeof t.catch&&"function"==typeof t.finally}class _i{type="Ed25519";raw;constructor(t){this.raw=Gi(t,32)}toMultihash(){return Je(ha(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return ve.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&U(this.raw,t.raw)}verify(t,e,r){r?.signal?.throwIfAborted();const n=async function(t,e,r){return null==Ri&&(Ri=await Mi),Ri?async function(t,e,r){if(t.buffer instanceof ArrayBuffer){const n=await Ui.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ui.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(t,e,r):function(t,e,r){return Ii.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}(t,e,r)}(this.raw,e,t);return Bi(n)?n.then(t=>(r?.signal?.throwIfAborted(),t)):n}}function Gi(t,e){if((t=Uint8Array.from(t??[])).length!==e)throw new re(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const $i=Math.pow(2,7),ji=Math.pow(2,14),qi=Math.pow(2,21),Vi=Math.pow(2,28),zi=Math.pow(2,35),Hi=Math.pow(2,42),Ki=Math.pow(2,49),Zi=128,Ji=127;function Wi(t){if(t<$i)return 1;if(t<ji)return 2;if(t<qi)return 3;if(t<Vi)return 4;if(t<zi)return 5;if(t<Hi)return 6;if(t<Ki)return 7;if(null!=Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Yi(t,e,r=0){switch(Wi(t)){case 8:e[r++]=255&t|Zi,t/=128;case 7:e[r++]=255&t|Zi,t/=128;case 6:e[r++]=255&t|Zi,t/=128;case 5:e[r++]=255&t|Zi,t/=128;case 4:e[r++]=255&t|Zi,t>>>=7;case 3:e[r++]=255&t|Zi,t>>>=7;case 2:e[r++]=255&t|Zi,t>>>=7;case 1:e[r++]=255&t,t>>>=7;break;default:throw new Error("unreachable")}return e}function Xi(t,e){let r=t[e],n=0;if(n+=r&Ji,r<Zi)return n;if(r=t[e+1],n+=(r&Ji)<<7,r<Zi)return n;if(r=t[e+2],n+=(r&Ji)<<14,r<Zi)return n;if(r=t[e+3],n+=(r&Ji)<<21,r<Zi)return n;if(r=t[e+4],n+=(r&Ji)*Vi,r<Zi)return n;if(r=t[e+5],n+=(r&Ji)*zi,r<Zi)return n;if(r=t[e+6],n+=(r&Ji)*Hi,r<Zi)return n;if(r=t[e+7],n+=(r&Ji)*Ki,r<Zi)return n;throw new RangeError("Could not decode varint")}function Qi(t,e,r=0){return null==e&&(e=I(Wi(t))),e instanceof Uint8Array?Yi(t,e,r):function(t,e,r=0){switch(Wi(t)){case 8:e.set(r++,255&t|Zi),t/=128;case 7:e.set(r++,255&t|Zi),t/=128;case 6:e.set(r++,255&t|Zi),t/=128;case 5:e.set(r++,255&t|Zi),t/=128;case 4:e.set(r++,255&t|Zi),t>>>=7;case 3:e.set(r++,255&t|Zi),t>>>=7;case 2:e.set(r++,255&t|Zi),t>>>=7;case 1:e.set(r++,255&t),t>>>=7;break;default:throw new Error("unreachable")}return e}(t,e,r)}function ts(t,e=0){return t instanceof Uint8Array?Xi(t,e):function(t,e){let r=t.get(e),n=0;if(n+=r&Ji,r<Zi)return n;if(r=t.get(e+1),n+=(r&Ji)<<7,r<Zi)return n;if(r=t.get(e+2),n+=(r&Ji)<<14,r<Zi)return n;if(r=t.get(e+3),n+=(r&Ji)<<21,r<Zi)return n;if(r=t.get(e+4),n+=(r&Ji)*Vi,r<Zi)return n;if(r=t.get(e+5),n+=(r&Ji)*zi,r<Zi)return n;if(r=t.get(e+6),n+=(r&Ji)*Hi,r<Zi)return n;if(r=t.get(e+7),n+=(r&Ji)*Ki,r<Zi)return n;throw new RangeError("Could not decode varint")}(t,e)}const es=new Float32Array([-0]),rs=new Uint8Array(es.buffer);function ns(t,e,r){es[0]=t,e[r]=rs[0],e[r+1]=rs[1],e[r+2]=rs[2],e[r+3]=rs[3]}const is=new Float64Array([-0]),ss=new Uint8Array(is.buffer);function as(t,e,r){is[0]=t,e[r]=ss[0],e[r+1]=ss[1],e[r+2]=ss[2],e[r+3]=ss[3],e[r+4]=ss[4],e[r+5]=ss[5],e[r+6]=ss[6],e[r+7]=ss[7]}const os=BigInt(Number.MAX_SAFE_INTEGER),cs=BigInt(Number.MIN_SAFE_INTEGER);class us{lo;hi;constructor(t,e){this.lo=0|t,this.hi=0|e}toNumber(t=!1){if(!t&&this.hi>>>31>0){const t=1+~this.lo>>>0;let e=~this.hi>>>0;return 0===t&&(e=e+1>>>0),-(t+4294967296*e)}return this.lo+4294967296*this.hi}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const t=1+~this.lo>>>0;let e=~this.hi>>>0;return 0===t&&(e=e+1>>>0),-(BigInt(t)+(BigInt(e)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){const t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){const t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){const t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:r<128?9:10}static fromBigInt(t){if(0n===t)return ls;if(t<os&&t>cs)return this.fromNumber(Number(t));const e=t<0n;e&&(t=-t);let r=t>>32n,n=t-(r<<32n);return e&&(r=0n|~r,n=0n|~n,++n>ds&&(n=0n,++r>ds&&(r=0n))),new us(Number(n),Number(r))}static fromNumber(t){if(0===t)return ls;const e=t<0;e&&(t=-t);let r=t>>>0,n=(t-r)/4294967296>>>0;return e&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new us(r,n)}static from(t){return"number"==typeof t?us.fromNumber(t):"bigint"==typeof t?us.fromBigInt(t):"string"==typeof t?us.fromBigInt(BigInt(t)):null!=t.low||null!=t.high?new us(t.low>>>0,t.high>>>0):ls}}const ls=new us(0,0);ls.toBigInt=function(){return 0n},ls.zzEncode=ls.zzDecode=function(){return this},ls.length=function(){return 1};const ds=4294967296n;function hs(t,e,r){const n=r;let i,s;for(let n=0;n<t.length;++n)i=t.charCodeAt(n),i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=t.charCodeAt(n+1)))?(i=65536+((1023&i)<<10)+(1023&s),++n,e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=63&i|128):(e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=63&i|128);return r-n}function fs(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function gs(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class ps{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return t;if((this.pos+=5)>this.len)throw this.pos=this.len,fs(this,10);return t}int32(){return 0|this.uint32()}sint32(){const t=this.uint32();return t>>>1^-(1&t)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw fs(this,4);return gs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw fs(this,4);return 0|gs(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw fs(this,4);const t=(rs[0]=(e=this.buf)[r=this.pos],rs[1]=e[r+1],rs[2]=e[r+2],rs[3]=e[r+3],es[0]);var e,r;return this.pos+=4,t}double(){if(this.pos+8>this.len)throw fs(this,4);const t=(ss[0]=(e=this.buf)[r=this.pos],ss[1]=e[r+1],ss[2]=e[r+2],ss[3]=e[r+3],ss[4]=e[r+4],ss[5]=e[r+5],ss[6]=e[r+6],ss[7]=e[r+7],is[0]);var e,r;return this.pos+=8,t}bytes(){const t=this.uint32(),e=this.pos,r=this.pos+t;if(r>this.len)throw fs(this,t);return this.pos+=t,e===r?new Uint8Array(0):this.buf.subarray(e,r)}string(){const t=this.bytes();return function(t,e,r){if(r-e<1)return"";let n;const i=[];let s,a=0;for(;e<r;)s=t[e++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&t[e++]:s>239&&s<365?(s=((7&s)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&t[e++])<<6|63&t[e++],a>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=n?(a>0&&n.push(String.fromCharCode.apply(String,i.slice(0,a))),n.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(t,0,t.length)}skip(t){if("number"==typeof t){if(this.pos+t>this.len)throw fs(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw fs(this)}while(128&this.buf[this.pos++]);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){const t=new us(0,0);let e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw fs(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw fs(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw fs(this,8);const t=gs(this.buf,this.pos+=4),e=gs(this.buf,this.pos+=4);return new us(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const t=Xi(this.buf,this.pos);return this.pos+=Wi(t),t}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 ws(t){return new ps(t instanceof Uint8Array?t:t.subarray())}function ms(t,e,r){const n=ws(t);return e.decode(n,void 0,r)}class ys{fn;len;next;val;constructor(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}}function bs(){}class vs{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}const Es=function(){const t=8192;let e,r=t;return function(n){if(n<1||n>4096)return I(n);r+n>t&&(e=I(t),r=0);const i=e.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),i}}();class Ss{len;head;tail;states;constructor(){this.len=0,this.head=new ys(bs,0,0),this.tail=this.head,this.states=null}_push(t,e,r){return this.tail=this.tail.next=new ys(t,e,r),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new xs((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ks,10,us.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){const e=us.fromBigInt(t);return this._push(ks,e.length(),e)}uint64Number(t){return this._push(Yi,Wi(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){const e=us.fromBigInt(t).zzEncode();return this._push(ks,e.length(),e)}sint64Number(t){const e=us.fromNumber(t).zzEncode();return this._push(ks,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(As,1,t?1:0)}fixed32(t){return this._push(Cs,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){const e=us.fromBigInt(t);return this._push(Cs,4,e.lo)._push(Cs,4,e.hi)}fixed64Number(t){const e=us.fromNumber(t);return this._push(Cs,4,e.lo)._push(Cs,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(ns,4,t)}double(t){return this._push(as,8,t)}bytes(t){const e=t.length>>>0;return 0===e?this._push(As,1,0):this.uint32(e)._push(Fs,e,t)}string(t){const e=function(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:55296==(64512&r)&&56320==(64512&t.charCodeAt(n+1))?(++n,e+=4):e+=3;return e}(t);return 0!==e?this.uint32(e)._push(hs,e,t):this._push(As,1,0)}fork(){return this.states=new vs(this),this.head=this.tail=new ys(bs,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 ys(bs,0,0),this.len=0),this}ldelim(){const t=this.head,e=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=t.next,this.tail=e,this.len+=r),this}finish(){let t=this.head.next;const e=(r=this.len,null!=globalThis.Buffer?I(r):Es(r));var r;let n=0;for(;null!=t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}}function As(t,e,r){e[r]=255&t}function Ts(t,e,r){for(;t>127;)e[r++]=127&t|128,t>>>=7;e[r]=t}class xs extends ys{next;constructor(t,e){super(Ts,t,e),this.next=void 0}}function ks(t,e,r){for(;0!==t.hi;)e[r++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=127&t.lo|128,t.lo=t.lo>>>7;e[r++]=t.lo}function Cs(t,e,r){e[r]=255&t,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Fs(t,e,r){e.set(t,r)}function Ds(t,e,r){e.set(t,r)}function Os(t,e,r){t.length<40?hs(t,e,r):null!=e.utf8Write?e.utf8Write(t,r):e.set(R(t),r)}function Ps(t,e){const r=new Ss;return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*Is(t,e,r){const n=ws(t);yield*e.stream(n,void 0,"$",r)}function Ns(t,e,r,n,i){return{name:t,type:e,encode:r,decode:n,stream:i}}function Ls(t,e,r){return Ns("message",2,t,e,r)}var Us,Rs,Ms,Bs;null!=globalThis.Buffer&&(Ss.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(Ds,e,t),this},Ss.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Os,e,t),this}),function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"}(Us||(Us={})),function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"}(Rs||(Rs={})),function(t){t.codec=()=>function(t){function e(e){if(null==t[e.toString()])throw new Error("Invalid enum value");return t[e]}return Ns("enum",0,function(t,r){const n=e(t);r.int32(n)},function(t){return e(t.int32())},function*(t){const r=t.int32();yield e(r)})}(Rs)}(Us||(Us={})),function(t){let e;t.codec=()=>(null==e&&(e=Ls((t,e,r={})=>{!1!==r.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),Us.codec().encode(t.Type,e)),null!=t.Data&&(e.uint32(18),e.bytes(t.Data)),!1!==r.lengthDelimited&&e.ldelim()},(t,e,r={})=>{const n={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:n.Type=Us.codec().decode(t);break;case 2:n.Data=t.bytes();break;default:t.skipType(7&e)}}return n},function*(t,e,r,n={}){const i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:yield{field:`${r}.Type`,value:Us.codec().decode(t)};break;case 2:yield{field:`${r}.Data`,value:t.bytes()};break;default:t.skipType(7&e)}}})),e),t.encode=function(e){return Ps(e,t.codec())},t.decode=function(e,r){return ms(e,t.codec(),r)},t.stream=function(e,r){return Is(e,t.codec(),r)}}(Ms||(Ms={})),function(t){let e;t.codec=()=>(null==e&&(e=Ls((t,e,r={})=>{!1!==r.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),Us.codec().encode(t.Type,e)),null!=t.Data&&(e.uint32(18),e.bytes(t.Data)),!1!==r.lengthDelimited&&e.ldelim()},(t,e,r={})=>{const n={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:n.Type=Us.codec().decode(t);break;case 2:n.Data=t.bytes();break;default:t.skipType(7&e)}}return n},function*(t,e,r,n={}){const i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:yield{field:`${r}.Type`,value:Us.codec().decode(t)};break;case 2:yield{field:`${r}.Data`,value:t.bytes()};break;default:t.skipType(7&e)}}})),e),t.encode=function(e){return Ps(e,t.codec())},t.decode=function(e,r){return ms(e,t.codec(),r)},t.stream=function(e,r){return Is(e,t.codec(),r)}}(Bs||(Bs={}));class _s{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(Sr(t),Er(e,void 0,"key"),this.iHash=t.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 r=this.blockLen,n=new Uint8Array(r);n.set(e.length>r?t.create().update(e).digest():e);for(let t=0;t<n.length;t++)n[t]^=54;this.iHash.update(n),this.oHash=t.create();for(let t=0;t<n.length;t++)n[t]^=106;this.oHash.update(n),Tr(n)}update(t){return Ar(this),this.iHash.update(t),this}digestInto(t){Ar(this),Er(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:e,iHash:r,finished:n,destroyed:i,blockLen:s,outputLen:a}=this;return t.finished=n,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Gs=(t,e,r)=>new _s(t,e).update(r).digest();Gs.create=(t,e)=>new _s(t,e);const $s=(t,e)=>(t+(t>=0?e:-e)/Zs)/e;function js(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function qs(t,e){const r={};for(let n of Object.keys(e))r[n]=void 0===t[n]?e[n]:t[n];return yn(r.lowS,"lowS"),yn(r.prehash,"prehash"),void 0!==r.format&&js(r.format),r}class Vs extends Error{constructor(t=""){super(t)}}const zs={Err:Vs,_tlv:{encode:(t,e)=>{const{Err:r}=zs;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(1&e.length)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=vn(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?vn(i.length/2|128):"";return vn(t)+s+i+e},decode(t,e){const{Err:r}=zs;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++];let s=0;if(128&i){const t=127&i;if(!t)throw new r("tlv.decode(long): indefinite length not supported");if(t>4)throw new r("tlv.decode(long): byte length is too big");const a=e.subarray(n,n+t);if(a.length!==t)throw new r("tlv.decode: length bytes not complete");if(0===a[0])throw new r("tlv.decode(long): zero leftmost byte");for(const t of a)s=s<<8|t;if(n+=t,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const a=e.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(t){const{Err:e}=zs;if(t<Hs)throw new e("integer: negative integers are not allowed");let r=vn(t);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=zs;if(128&t[0])throw new e("invalid signature integer: negative");if(0===t[0]&&!(128&t[1]))throw new e("invalid signature integer: unnecessary leading zero");return Sn(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=zs,i=Er(t,void 0,"signature"),{v:s,l:a}=n.decode(48,i);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:o,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(o),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=zs,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s));return e.encode(48,n+i)}},Hs=BigInt(0),Ks=BigInt(1),Zs=BigInt(2),Js=BigInt(3),Ws=BigInt(4);function Ys(t,e={}){const r=pi("weierstrass",t,e),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:a,n:o}=s;On(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!n.is0(s.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Qs(n,i);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=e.toBytes||function(t,e,r){const{x:i,y:s}=e.toAffine(),a=n.toBytes(i);return yn(r,"isCompressed"),r?(l(),Ir(Xs(!n.isOdd(s)),a)):Ir(Uint8Array.of(4),a,n.toBytes(s))},h=e.fromBytes||function(t){Er(t,void 0,"Point");const{publicKey:e,publicKeyUncompressed:r}=u,i=t.length,s=t[0],a=t.subarray(1);if(i!==e||2!==s&&3!==s){if(i===r&&4===s){const t=n.BYTES,e=n.fromBytes(a.subarray(0,t)),r=n.fromBytes(a.subarray(t,2*t));if(!g(e,r))throw new Error("bad point: is not on curve");return{x:e,y:r}}throw new Error(`bad point: got length ${i}, expected compressed=${e} or uncompressed=${r}`)}{const t=n.fromBytes(a);if(!n.isValid(t))throw new Error("bad point: is not on curve, wrong x");const e=f(t);let r;try{r=n.sqrt(e)}catch(t){const e=t instanceof Error?": "+t.message:"";throw new Error("bad point: is not on curve, sqrt error"+e)}return l(),!(1&~s)!==n.isOdd(r)&&(r=n.neg(r)),{x:t,y:r}}};function f(t){const e=n.sqr(t),r=n.mul(e,t);return n.add(n.add(r,n.mul(t,s.a)),s.b)}function g(t,e){const r=n.sqr(e),i=f(t);return n.eql(r,i)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const p=n.mul(n.pow(s.a,Js),Ws),w=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(p,w)))throw new Error("bad curve params: a or b");function m(t,e,r=!1){if(!n.isValid(e)||r&&n.is0(e))throw new Error(`bad point coordinate ${t}`);return e}function y(t){if(!(t instanceof A))throw new Error("Weierstrass Point expected")}function b(t){if(!c||!c.basises)throw new Error("no endo");return function(t,e,r){const[[n,i],[s,a]]=e,o=$s(a*t,r),c=$s(-i*t,r);let u=t-o*n-c*s,l=-o*i-c*a;const d=u<Hs,h=l<Hs;d&&(u=-u),h&&(l=-l);const f=Dn(Math.ceil(function(t){let e;for(e=0;t>wn;t>>=mn,e+=1);return e}(r)/2))+Ks;if(u<Hs||u>=f||l<Hs||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:d,k1:u,k2neg:h,k2:l}}(t,c.basises,i.ORDER)}const v=Pn((t,e)=>{const{X:r,Y:i,Z:s}=t;if(n.eql(s,n.ONE))return{x:r,y:i};const a=t.is0();null==e&&(e=a?n.ONE:n.inv(s));const o=n.mul(r,e),c=n.mul(i,e),u=n.mul(s,e);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(u,n.ONE))throw new Error("invZ was invalid");return{x:o,y:c}}),E=Pn(t=>{if(t.is0()){if(e.allowInfinityPoint&&!n.is0(t.Y))return;throw new Error("bad point: ZERO")}const{x:r,y:i}=t.toAffine();if(!n.isValid(r)||!n.isValid(i))throw new Error("bad point: x or y not field elements");if(!g(r,i))throw new Error("bad point: equation left != right");if(!t.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(t,e,r,i,s){return r=new A(n.mul(r.X,t),r.Y,r.Z),e=ii(i,e),r=ii(s,r),e.add(r)}class A{static BASE=new A(s.Gx,s.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;constructor(t,e,r){this.X=m("x",t),this.Y=m("y",e,!0),this.Z=m("z",r),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){const{x:e,y:r}=t||{};if(!t||!n.isValid(e)||!n.isValid(r))throw new Error("invalid affine point");if(t instanceof A)throw new Error("projective point not allowed");return n.is0(e)&&n.is0(r)?A.ZERO:new A(e,r,n.ONE)}static fromBytes(t){const e=A.fromAffine(h(Er(t,void 0,"point")));return e.assertValidity(),e}static fromHex(t){return A.fromBytes(Pr(t))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return x.createCache(this,t),e||this.multiply(Js),this}assertValidity(){E(this)}hasEvenY(){const{y:t}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(t)}equals(t){y(t);const{X:e,Y:r,Z:i}=this,{X:s,Y:a,Z:o}=t,c=n.eql(n.mul(e,o),n.mul(s,i)),u=n.eql(n.mul(r,o),n.mul(a,i));return c&&u}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){const{a:t,b:e}=s,r=n.mul(e,Js),{X:i,Y:a,Z:o}=this;let c=n.ZERO,u=n.ZERO,l=n.ZERO,d=n.mul(i,i),h=n.mul(a,a),f=n.mul(o,o),g=n.mul(i,a);return g=n.add(g,g),l=n.mul(i,o),l=n.add(l,l),c=n.mul(t,l),u=n.mul(r,f),u=n.add(c,u),c=n.sub(h,u),u=n.add(h,u),u=n.mul(c,u),c=n.mul(g,c),l=n.mul(r,l),f=n.mul(t,f),g=n.sub(d,f),g=n.mul(t,g),g=n.add(g,l),l=n.add(d,d),d=n.add(l,d),d=n.add(d,f),d=n.mul(d,g),u=n.add(u,d),f=n.mul(a,o),f=n.add(f,f),d=n.mul(f,g),c=n.sub(c,d),l=n.mul(f,h),l=n.add(l,l),l=n.add(l,l),new A(c,u,l)}add(t){y(t);const{X:e,Y:r,Z:i}=this,{X:a,Y:o,Z:c}=t;let u=n.ZERO,l=n.ZERO,d=n.ZERO;const h=s.a,f=n.mul(s.b,Js);let g=n.mul(e,a),p=n.mul(r,o),w=n.mul(i,c),m=n.add(e,r),b=n.add(a,o);m=n.mul(m,b),b=n.add(g,p),m=n.sub(m,b),b=n.add(e,i);let v=n.add(a,c);return b=n.mul(b,v),v=n.add(g,w),b=n.sub(b,v),v=n.add(r,i),u=n.add(o,c),v=n.mul(v,u),u=n.add(p,w),v=n.sub(v,u),d=n.mul(h,b),u=n.mul(f,w),d=n.add(u,d),u=n.sub(p,d),d=n.add(p,d),l=n.mul(u,d),p=n.add(g,g),p=n.add(p,g),w=n.mul(h,w),b=n.mul(f,b),p=n.add(p,w),w=n.sub(g,w),w=n.mul(h,w),b=n.add(b,w),g=n.mul(p,b),l=n.add(l,g),g=n.mul(v,b),u=n.mul(m,u),u=n.sub(u,g),g=n.mul(m,p),d=n.mul(v,d),d=n.add(d,g),new A(u,l,d)}subtract(t){return this.add(t.negate())}is0(){return this.equals(A.ZERO)}multiply(t){const{endo:r}=e;if(!i.isValidNot0(t))throw new Error("invalid scalar: out of range");let n,s;const a=t=>x.cached(this,t,t=>si(A,t));if(r){const{k1neg:e,k1:i,k2neg:o,k2:c}=b(t),{p:u,f:l}=a(i),{p:d,f:h}=a(c);s=l.add(h),n=S(r.beta,u,d,e,o)}else{const{p:e,f:r}=a(t);n=e,s=r}return si(A,[n,s])[0]}multiplyUnsafe(t){const{endo:r}=e,n=this;if(!i.isValid(t))throw new Error("invalid scalar: out of range");if(t===Hs||n.is0())return A.ZERO;if(t===Ks)return n;if(x.hasCache(this))return this.multiply(t);if(r){const{k1neg:e,k1:i,k2neg:s,k2:a}=b(t),{p1:o,p2:c}=function(t,e,r,n){let i=e,s=t.ZERO,a=t.ZERO;for(;r>ri||n>ri;)r&ni&&(s=s.add(i)),n&ni&&(a=a.add(i)),i=i.double(),r>>=ni,n>>=ni;return{p1:s,p2:a}}(A,n,i,a);return S(r.beta,o,c,e,s)}return x.unsafe(n,t)}toAffine(t){return v(this,t)}isTorsionFree(){const{isTorsionFree:t}=e;return a===Ks||(t?t(A,this):x.unsafe(this,o).is0())}clearCofactor(){const{clearCofactor:t}=e;return a===Ks?this:t?t(A,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(t=!0){return yn(t,"isCompressed"),this.assertValidity(),d(A,this,t)}toHex(t=!0){return Dr(this.toBytes(t))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const T=i.BITS,x=new fi(A,e.endo?Math.ceil(T/2):T);return A.BASE.precompute(8),A}function Xs(t){return Uint8Array.of(t?2:3)}function Qs(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ta(t,e,r={}){Sr(e),On(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=(r=Object.assign({},r)).randomBytes||Lr,i=r.hmac||((t,r)=>Gs(e,t,r)),{Fp:s,Fn:a}=t,{ORDER:o,BITS:c}=a,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=function(t,e={}){const{Fn:r}=t,n=e.randomBytes||Lr,i=Object.assign(Qs(t.Fp,r),{seed:ei(r.ORDER)});function s(t=n(i.seed)){return function(t,e,r=!1){Er(t);const n=t.length,i=ti(e),s=ei(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const a=jn(r?An(t):Sn(t),e-Nn)+Nn;return r?xn(a,i):Tn(a,i)}(Er(t,i.seed,"seed"),r.ORDER)}function a(e,n=!0){return t.BASE.multiply(r.fromBytes(e)).toBytes(n)}function o(t){const{secretKey:e,publicKey:n,publicKeyUncompressed:s}=i;if(!br(t))return;if("_lengths"in r&&r._lengths||e===n)return;const a=Er(t,void 0,"key").length;return a===n||a===s}const c={isValidSecretKey:function(t){try{const e=r.fromBytes(t);return r.isValidNot0(e)}catch(t){return!1}},isValidPublicKey:function(e,r){const{publicKey:n,publicKeyUncompressed:s}=i;try{const i=e.length;return!(!0===r&&i!==n||!1===r&&i!==s||!t.fromBytes(e))}catch(t){return!1}},randomSecretKey:s},u=wi(s,a);return Object.freeze({getPublicKey:a,getSharedSecret:function(e,n,i=!0){if(!0===o(e))throw new Error("first arg must be private key");if(!1===o(n))throw new Error("second arg must be public key");const s=r.fromBytes(e);return t.fromBytes(n).multiply(s).toBytes(i)},keygen:u,Point:t,utils:c,lengths:i})}(t,r),g={prehash:!0,lowS:"boolean"!=typeof r.lowS||r.lowS,format:"compact",extraEntropy:!1},p=o*Zs<s.ORDER;function w(t){return t>o>>Ks}function m(t,e){if(!a.isValidNot0(e))throw new Error(`invalid signature ${t}: out of range 1..Point.Fn.ORDER`);return e}function y(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(t,e){js(e);const r=f.signature;return Er(t,"compact"===e?r:"recovered"===e?r+1:void 0)}class v{r;s;recovery;constructor(t,e,r){if(this.r=m("r",t),this.s=m("s",e),null!=r){if(y(),![0,1,2,3].includes(r))throw new Error("invalid recovery id");this.recovery=r}Object.freeze(this)}static fromBytes(t,e=g.format){let r;if(b(t,e),"der"===e){const{r:e,s:r}=zs.toSig(Er(t));return new v(e,r)}"recovered"===e&&(r=t[0],e="compact",t=t.subarray(1));const n=f.signature/2,i=t.subarray(0,n),s=t.subarray(n,2*n);return new v(a.fromBytes(i),a.fromBytes(s),r)}static fromHex(t,e){return this.fromBytes(Pr(t),e)}assertRecovery(){const{recovery:t}=this;if(null==t)throw new Error("invalid recovery id: must be present");return t}addRecoveryBit(t){return new v(this.r,this.s,t)}recoverPublicKey(e){const{r,s:n}=this,i=this.assertRecovery(),c=2===i||3===i?r+o:r;if(!s.isValid(c))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const u=s.toBytes(c),l=t.fromBytes(Ir(Xs(!(1&i)),u)),d=a.inv(c),h=S(Er(e,void 0,"msgHash")),f=a.create(-h*d),g=a.create(n*d),p=t.BASE.multiplyUnsafe(f).add(l.multiplyUnsafe(g));if(p.is0())throw new Error("invalid recovery: point at infinify");return p.assertValidity(),p}hasHighS(){return w(this.s)}toBytes(t=g.format){if(js(t),"der"===t)return Pr(zs.hexFromSig(this));const{r:e,s:r}=this,n=a.toBytes(e),i=a.toBytes(r);return"recovered"===t?(y(),Ir(Uint8Array.of(this.assertRecovery()),n,i)):Ir(n,i)}toHex(t){return Dr(this.toBytes(t))}}const E=r.bits2int||function(t){if(t.length>8192)throw new Error("input is too large");const e=Sn(t),r=8*t.length-c;return r>0?e>>BigInt(r):e},S=r.bits2int_modN||function(t){return a.create(E(t))},A=Dn(c);function T(t){return Fn("num < 2^"+c,t,Hs,A),a.toBytes(t)}function x(t,r){return Er(t,void 0,"message"),r?Er(e(t),void 0,"prehashed message"):t}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f,Point:t,sign:function(r,s,o={}){const{seed:c,k2sig:u}=function(e,r,i){const{lowS:s,prehash:o,extraEntropy:c}=qs(i,g);e=x(e,o);const u=S(e),l=a.fromBytes(r);if(!a.isValidNot0(l))throw new Error("invalid private key");const d=[T(l),T(u)];if(null!=c&&!1!==c){const t=!0===c?n(f.secretKey):c;d.push(Er(t,void 0,"extraEntropy"))}const h=Ir(...d),m=u;return{seed:h,k2sig:function(e){const r=E(e);if(!a.isValidNot0(r))return;const n=a.inv(r),i=t.BASE.multiply(r).toAffine(),o=a.create(i.x);if(o===Hs)return;const c=a.create(n*a.create(m+o*l));if(c===Hs)return;let u=(i.x===o?0:2)|Number(i.y&Ks),d=c;return s&&w(c)&&(d=a.neg(c),u^=1),new v(o,d,p?void 0:u)}}}(r,s,o);return function(t,e,r){if(vr(t,"hashLen"),vr(e,"qByteLen"),"function"!=typeof r)throw new Error("hmacFn must be a function");const n=t=>new Uint8Array(t),i=Uint8Array.of(),s=Uint8Array.of(0),a=Uint8Array.of(1);let o=n(t),c=n(t),u=0;const l=()=>{o.fill(1),c.fill(0),u=0},d=(...t)=>r(c,Ir(o,...t)),h=(t=i)=>{c=d(s,t),o=d(),0!==t.length&&(c=d(a,t),o=d())},f=()=>{if(u++>=1e3)throw new Error("drbg: tried max amount of iterations");let t=0;const r=[];for(;t<e;){o=d();const e=o.slice();r.push(e),t+=o.length}return Ir(...r)};return(t,e)=>{let r;for(l(),h(t);!(r=e(f()));)h();return l(),r}}(e.outputLen,a.BYTES,i)(c,u).toBytes(o.format)},verify:function(e,r,n,i={}){const{lowS:s,prehash:o,format:c}=qs(i,g);if(n=Er(n,void 0,"publicKey"),r=x(r,o),!br(e))throw new Error("verify expects Uint8Array signature"+(e instanceof v?", use sig.toBytes()":""));b(e,c);try{const i=v.fromBytes(e,c),o=t.fromBytes(n);if(s&&i.hasHighS())return!1;const{r:u,s:l}=i,d=S(r),h=a.inv(l),f=a.create(d*h),g=a.create(u*h),p=t.BASE.multiplyUnsafe(f).add(o.multiplyUnsafe(g));return!p.is0()&&a.create(p.x)===u}catch(t){return!1}},recoverPublicKey:function(t,e,r={}){const{prehash:n}=qs(r,g);return e=x(e,n),v.fromBytes(t,"recovered").recoverPublicKey(e).toBytes()},Signature:v,hash:e})}const ea={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ra={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},na=/* @__PURE__ */BigInt(2),ia=Qn(ea.p,{sqrt:function(t){const e=ea.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,d=qn(l,r,e)*l%e,h=qn(d,r,e)*l%e,f=qn(h,na,e)*u%e,g=qn(f,i,e)*f%e,p=qn(g,s,e)*g%e,w=qn(p,o,e)*p%e,m=qn(w,c,e)*w%e,y=qn(m,o,e)*p%e,b=qn(y,r,e)*l%e,v=qn(b,a,e)*g%e,E=qn(v,n,e)*u%e,S=qn(E,na,e);if(!ia.eql(ia.sqr(S),t))throw new Error("Cannot find square root");return S}}),sa=/* @__PURE__ */ta(/* @__PURE__ */Ys(ea,{Fp:ia,endo:ra}),gn);function aa({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:i}){return new oa(t,e,r,n,i)}class oa{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,r,n,i){this.name=t,this.code=e,this.encode=r,this.minDigestLength=n??20,this.maxDigestLength=i}digest(t,e){if(null!=e?.truncate){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(null!=this.maxDigestLength&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?ca(r,this.code,e?.truncate):r.then(t=>ca(t,this.code,e?.truncate))}throw Error("Unknown type, must be binary type")}}function ca(t,e,r){if(null!=r&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Me(e,t)}function ua(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const la=aa({name:"sha2-256",code:18,encode:ua("SHA-256")});aa({name:"sha2-512",code:19,encode:ua("SHA-512")});class da{type="secp256k1";raw;_key;constructor(t){this._key=function(t){try{return sa.Point.fromBytes(t),t}catch(t){throw new ne(String(t))}}(t),this.raw=function(t){return sa.Point.fromBytes(t).toBytes()}(this._key)}toMultihash(){return Je(ha(this))}toCID(){return qe.createV1(114,this.toMultihash())}toString(){return ve.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&U(this.raw,t.raw)}verify(t,e,r){return function(t,e,r,n){const i=la.digest(r instanceof Uint8Array?r:r.subarray());if(Bi(i))return i.then(({digest:r})=>(n?.signal?.throwIfAborted(),sa.verify(e,r,t,{prehash:!1,format:"der"}))).catch(t=>{if("AbortError"===t.name)throw t;throw new Ni(String(t))});try{return n?.signal?.throwIfAborted(),sa.verify(e,i.digest,t,{prehash:!1,format:"der"})}catch(t){throw new Ni(String(t))}}(this._key,e,t,r)}}function ha(t){return Ms.encode({Type:Us[t.type],Data:t.raw})}const fa=Symbol.for("nodejs.util.inspect.custom");class ga{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ue]=!0;toString(){return null==this.string&&(this.string=ve.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return qe.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(t){if(null==t)return!1;if(t instanceof Uint8Array)return U(this.multihash.bytes,t);if("string"==typeof t)return this.toString()===t;if(null!=t?.toMultihash()?.bytes)return U(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[fa](){return`PeerId(${this.toString()})`}}class pa extends ga{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}}class wa extends ga{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}}class ma extends ga{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}}class ya{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Je(R(this.url))}[fa](){return`PeerId(${this.url})`}[ue]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return qe.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(t){return null!=t&&(t instanceof Uint8Array&&(t=M(t)),t.toString()===this.toString())}}function ba(t,e){let r;if("1"===t.charAt(0)||"Q"===t.charAt(0))r=Be(ve.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return function(t){if(null==t?.multihash||null==t.version||1===t.version&&114!==t.code&&2336!==t.code)throw new ie("Supplied PeerID CID is invalid");if(2336===t.code){const e=M(t.multihash.digest);return new ya(new URL(e))}return va(t.multihash)}(qe.parse(t));if(null==e)throw new re('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Be(e.decode(t))}return va(r)}function va(t){if(function(t){return t.code===la.code}(t))return new pa({multihash:t});if(function(t){return 0===t.code}(t))try{const e=function(t){const{Type:e,Data:r}=Ms.decode(t.digest),n=r??new Uint8Array;switch(e){case Us.Ed25519:return i=Gi(i=n,32),new _i(i);case Us.secp256k1:return function(t){return new da(t)}(n);case Us.ECDSA:return function(t){return function(t){const e=t[1][1][0];let r,n;if(65===e.byteLength)return r=M(e.subarray(1,33),"base64url"),n=M(e.subarray(33),"base64url"),new yr({...gr,key_ops:["verify"],x:r,y:n});if(97===e.byteLength)return r=M(e.subarray(1,49),"base64url"),n=M(e.subarray(49),"base64url"),new yr({...pr,key_ops:["verify"],x:r,y:n});if(133===e.byteLength)return r=M(e.subarray(1,67),"base64url"),n=M(e.subarray(67),"base64url"),new yr({...wr,key_ops:["verify"],x:r,y:n});throw new re(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}(ir(t))}(n);default:throw new ce}var i}(t);if("Ed25519"===e.type)return new wa({multihash:t,publicKey:e});if("secp256k1"===e.type)return new ma({multihash:t,publicKey:e})}catch(e){const r=M(t.digest);return new ya(new URL(r))}throw new se("Supplied PeerID Multihash is invalid")}function Ea(t,e){const r=G.fromHex(function(t){if("string"==typeof t)return t.startsWith("0x")?t:`0x${t}`;const e=t instanceof Uint8Array?t:Array.isArray(t)?Uint8Array.from(t):Uint8Array.from(Object.keys(t).sort((t,e)=>Number(t)-Number(e)).map(e=>t[Number(e)]));return`0x${Buffer.from(e).toString("hex")}`}(t)),n=$(r.toHex(),Buffer.from(e));return Buffer.from(n).toString("hex")}class Sa{getConsumerAddress(t){return Ga(t)}getSignature(t,e,r){return $a(t,e,r)}getAuthorization(t){return ja(t)}async getEndpoints(t,e){try{const r=await this.getData(t,e);return await r.json()}catch(t){throw ht.error("Finding the service endpoints failed:",t),new Error("HTTP request failed calling Provider")}}async getNodePublicKey(t){return(await this.getEndpoints(t)).nodePublicKey}getEndpointURL(t,e){return t?t.find(t=>t.serviceName.toLowerCase()===e.toLowerCase()):null}async getServiceEndpoints(t,e){const r=[];for(const n in e.serviceEndpoints){const i={serviceName:n,method:e.serviceEndpoints[n][0],urlPath:t.replace(/\/+$/,"")+"/"+e.serviceEndpoints[n][1].replace(/^\/+/,"")};r.push(i)}return r}async getNonce(t,e,r,n,i){n||(n=await this.getEndpoints(t)),i||(i=await this.getServiceEndpoints(t,n));const s=this.getEndpointURL(i,"nonce")?this.getEndpointURL(i,"nonce").urlPath:null;if(!s)return null;try{const t=await O(s+`?userAddress=${e}`,{method:"GET",headers:{"Content-Type":"application/json"},signal:r}),{nonce:n}=await t.json();return n&&null!==n?Number(n):0}catch(t){throw ht.error(t),new Error(t.message)}}async encrypt(t,e,r,n,i,s){const a=await this.getEndpoints(r),o=await this.getServiceEndpoints(r,a),c=await this.getConsumerAddress(n),u=(await this.getNonce(r,c,s,a,o)+1).toString(),l=await this.getSignature(n,u,rt.ENCRYPT);let d=(this.getEndpointURL(o,"encrypt")?this.getEndpointURL(o,"encrypt").urlPath:null)+`?chainId=${e}`;if(!d)return null;d+=`&nonce=${u}`,d+=`&consumerAddress=${c}`,d+=`&signature=${l}`;try{const e=await O(d,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:s});return await e.text()}catch(t){throw ht.error(t),new Error("HTTP request failed calling Provider")}}async checkDidFiles(t,e,r,n=!1,i){var s;const a=await this.getEndpoints(r),o=await this.getServiceEndpoints(r,a),c={did:t,serviceId:e,checksum:n},u=[],l=this.getEndpointURL(o,"fileinfo")?this.getEndpointURL(o,"fileinfo").urlPath:null;if(!l)return null;let d;try{d=await O(l,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw ht.error("File info call failed: "),ht.error(t),new Error(t)}if(null!=(s=d)&&s.ok){const t=await d.json();for(const e of t)u.push(e);return u}const h=await d.json();throw ht.error("File info call failed: ",d.status,d.statusText,h),new Error(JSON.stringify(h))}async getFileInfo(t,e,r=!1,n){var i;const s=await this.getEndpoints(e),a=await this.getServiceEndpoints(e,s),o=ot({},t,{checksum:r}),c=[],u=this.getEndpointURL(a,"fileinfo")?this.getEndpointURL(a,"fileinfo").urlPath:null;if(!u)return null;let l;try{l=await O(u,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw ht.error("File info call failed: "),ht.error(t),new Error(t)}if(null!=(i=l)&&i.ok){const t=await l.json();for(const e of t)c.push(e);return c}const d=await l.json();throw ht.error("File info call failed: ",l.status,l.statusText,d),new Error(JSON.stringify(d))}async getComputeEnvironments(t,e){var r,n;const i=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,i),a=null==(r=this.getEndpointURL(s,"computeEnvironments"))?void 0:r.urlPath;if(!a)return null;let o;try{o=await O(a,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw ht.error("Fetch compute env failed: "),ht.error(t),new Error(t)}if(null!=(n=o)&&n.ok)return o.json();const c=await o.json();throw ht.error("Fetch compute env failed: ",o.status,o.statusText,c),new Error(JSON.stringify(c))}async initialize(t,e,r,n,i,s,a,o,c){var u;const l=await this.getEndpoints(i),d=await this.getServiceEndpoints(i,l);let h,f=this.getEndpointURL(d,"initialize")?this.getEndpointURL(d,"initialize").urlPath:null;if(!f)return null;f+=`?documentId=${t}`,f+=`&serviceId=${e}`,f+=`&fileIndex=${r}`,f+=`&consumerAddress=${n}`,a&&(f+="&userdata="+encodeURI(JSON.stringify(a))),o&&(f+="&environment="+encodeURI(o)),c&&(f+="&validUntil="+c);try{h=await O(f,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})}catch(t){throw ht.error("Provider initialized failed: "),ht.error(t),new Error(`Provider initialize failed url: ${f} `)}if(200===(null==(u=h)?void 0:u.status))return await h.json();const g=await h.json();throw ht.error("Provider initialized failed: ",h.status,h.statusText,g),new Error(JSON.stringify(g))}async initializeCompute(t,e,r,n,i,s,a,o,c,u,l){var d;const h=await this.getEndpoints(s),f=await this.getServiceEndpoints(s,h),g=this.getEndpointURL(f,"initializeCompute")?this.getEndpointURL(f,"initializeCompute").urlPath:null;if(!g)return null;const p={datasets:t,algorithm:e,environment:r,payment:{chainId:c,token:n,resources:o},maxJobDuration:i,consumerAddress:a};let w;u&&(p.policyServer=u);try{if(w=await O(g,{method:"POST",body:JSON.stringify(p),headers:{"Content-Type":"application/json"},signal:l}),!w.ok){const t=await w.text();throw new Error(`${t}`)}}catch(t){throw ht.error("Initialize compute failed: "),ht.error(t),new Error(`ComputeJob cannot be initialized: ${t.message}.`)}if(null!=(d=w)&&d.ok)return await w.json();const m=await w.json();throw ht.error("Initialize compute failed: ",w.status,w.statusText,m),ht.error("Payload was:",JSON.stringify(p)),new Error(JSON.stringify(m))}async getDownloadUrl(t,e,r,n,i,s,a,o){const c=await this.getEndpoints(i),u=await this.getServiceEndpoints(i,c),l=this.getEndpointURL(u,"download")?this.getEndpointURL(u,"download").urlPath:null;if(!l)return null;const d=await this.getConsumerAddress(s),h=(await this.getNonce(i,d,null,c,u)+1).toString(),f=await this.getSignature(s,h,rt.DOWNLOAD);let g=l;return g+=`?fileIndex=${r}`,g+=`&documentId=${t}`,g+=`&transferTxId=${n}`,g+=`&serviceId=${e}`,g+=`&consumerAddress=${d}`,g+=`&nonce=${h}`,a&&(g+="&policyServer="+encodeURI(JSON.stringify(a))),g+=`&signature=${f}`,o&&(g+="&userdata="+encodeURI(JSON.stringify(o))),g}async computeStart(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p){var w;const m=await this.getEndpoints(t),y=await this.getServiceEndpoints(t,m),b=this.getEndpointURL(y,"computeStart")?this.getEndpointURL(y,"computeStart").urlPath:null;if(!b)return ht.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const v=await this.getConsumerAddress(e),E=(await this.getNonce(t,v,f,m,y)+1).toString(),S=await this.getSignature(e,E,rt.COMPUTE_START),A=Object();if(A.consumerAddress=v,A.signature=S,A.nonce=E,A.environment=r,A.maxJobDuration=s,A.resources=o,A.dataset=n[0],A.datasets=n,A.algorithm=i,A.chainId=c,A.payment={chainId:c,token:a,maxJobDuration:s,resources:o},p){const e=await this.getNodePublicKey(t);e&&(A.dockerRegistryAuth=Ea(e,JSON.stringify(p)))}if(o&&(A.resources=o),u&&(A.metadata=u),l&&(A.additionalViewers=l),d){const e=await this.getNodePublicKey(t);e&&(A.output=Ea(e,JSON.stringify(d)))}let T;h&&(A.policyServer=h),g&&(A.queueMaxWaitTime=g);try{T=await O(b,{method:"POST",body:JSON.stringify(A),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:f})}catch(t){throw ht.error("Compute start failed:"),ht.error(t),ht.error("Payload was:",A),new Error("HTTP request failed calling Provider")}if(null!=(w=T)&&w.ok)return await T.json();const x=await T.json();throw ht.error("Compute start failed: ",T.status,T.statusText,x),ht.error("Payload was:",A),new Error(JSON.stringify(x))}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,d,h){var f;const g=await this.getEndpoints(t),p=await this.getServiceEndpoints(t,g),w=this.getEndpointURL(p,"freeCompute")?this.getEndpointURL(p,"freeCompute").urlPath:null;if(!w)return ht.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const m=await this.getConsumerAddress(e),y=(await this.getNonce(t,m,l,g,p)+1).toString(),b=await this.getSignature(e,y,rt.FREE_COMPUTE_START),v=Object();if(v.consumerAddress=m,v.signature=b,v.nonce=y,v.environment=r,v.resources=s,v.dataset=n[0],v.datasets=n,v.algorithm=i,a&&(v.metadata=a),o&&(v.additionalViewers=o),h){const e=await this.getNodePublicKey(t);e&&(v.dockerRegistryAuth=Ea(e,JSON.stringify(h)))}if(c){const e=await this.getNodePublicKey(t);e&&(v.output=Ea(e,JSON.stringify(c)))}let E;u&&(v.policyServer=u),d&&(v.queueMaxWaitTime=d);try{E=await O(w,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:l})}catch(t){throw ht.error("Compute start failed:"),ht.error(t),ht.error("Payload was:",v),new Error("HTTP request failed calling Provider")}if(null!=(f=E)&&f.ok)return await E.json();const S=await E.json();throw ht.error("Compute start failed: ",E.status,E.statusText,S),ht.error("Payload was:",v),new Error(JSON.stringify(S))}async computeStreamableLogs(t,e,r,n){var i,s;const a="string"==typeof e,o=await this.getEndpoints(t),c=await this.getServiceEndpoints(t,o),u=this.getEndpointURL(c,"computeStreamableLogs")?this.getEndpointURL(c,"computeStreamableLogs").urlPath:null;if(!u)return ht.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null;const l=await this.getConsumerAddress(e),d=(await this.getNonce(t,l,n,o,c)+1).toString();let h,f=`?consumerAddress=${l}&jobId=${r}`;a||(f+=`&signature=${await this.getSignature(e,d,rt.COMPUTE_GET_STREAMABLE_LOGS)}`,f+=`&nonce=${d}`);try{h=await O(u+f,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:n})}catch(t){throw ht.error("computeStreamableLogs failed:"),ht.error(t),new Error("HTTP request failed calling Provider")}return null!=(i=h)&&i.ok||200===(null==(s=h)?void 0:s.status)?h.body:(ht.error("computeStreamableLogs failed: ",h.status,h.statusText,await h.json()),null)}async computeStop(t,e,r,n,i){var s;const a="string"==typeof r,o=await this.getEndpoints(e),c=await this.getServiceEndpoints(e,o),u=this.getEndpointURL(c,"computeStop")?this.getEndpointURL(c,"computeStop").urlPath:null,l=await this.getConsumerAddress(r),d=(await this.getNonce(e,l,i,o,c)+1).toString(),h=await this.getSignature(r,d,rt.COMPUTE_STOP),f=new URLSearchParams;f.set("consumerAddress",l),f.set("nonce",d),f.set("jobId",t),a||f.set("signature",h),n&&f.set("agreementId",n);const g=f.toString();if(!g)return null;let p;try{p=await O(u+"?"+g,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(r)},signal:i})}catch(t){throw ht.error("Compute stop failed:"),ht.error(t),new Error("HTTP request failed calling Provider")}if(null!=(s=p)&&s.ok)return await p.json();const w=await p.json();throw ht.error("Compute stop failed: ",p.status,p.statusText,w),new Error(JSON.stringify(w))}async computeStatus(t,e,r,n,i){var s,a;const o=await Ga(e),c=ja(e),u=await this.getEndpoints(t),l=await this.getServiceEndpoints(t,u),d=this.getEndpointURL(l,"computeStatus")?this.getEndpointURL(l,"computeStatus").urlPath:null;let h,f=`?consumerAddress=${o}`;if(f+=n&&`&agreementId=${n}`||"",f+=r&&`&jobId=${r}`||"",!d)return null;try{h=await O(d+f,{method:"GET",headers:{"Content-Type":"application/json",Authorization:c},signal:i})}catch(t){throw ht.error("Get compute status failed"),ht.error(t),new Error(t)}if(null!=(s=h)&&s.ok)return await h.json();if(ht.error("Get compute status failed:",h.status,h.statusText),null!=(a=h)&&a.ok)return await h.json();const g=await h.json();throw ht.error("Get compute status failed:",h.status,h.statusText,g),new Error(JSON.stringify(g))}async getComputeResultUrl(t,e,r,n){const i="string"==typeof e,s=await this.getEndpoints(t),a=await this.getServiceEndpoints(t,s),o=this.getEndpointURL(a,"computeResult")?this.getEndpointURL(a,"computeResult").urlPath:null,c=await this.getConsumerAddress(e),u=(await this.getNonce(t,c,null,s,a)+1).toString(),l=await this.getSignature(e,u,rt.COMPUTE_GET_RESULT);if(!o)return null;let d=o;return d+=`?consumerAddress=${c}`,d+=`&jobId=${r}`,d+=`&index=${n.toString()}`,i||(d+=`&nonce=${u}`,d+=`&signature=${l}`),d}async getComputeResult(t,e,r,n,i=0){const s=await this.getComputeResultUrl(t,e,r,n);if(!s)throw new Error("Could not retrieve compute result URL");const a=await O(s,{headers:i>0?{Range:`bytes=${i}-`}:{}});if(!a.ok)throw new Error(`Failed to fetch compute result: ${a.status}`);return a.body}async generateAuthToken(t,e,r){const n=await t.getAddress(),i=await this.getEndpoints(e),s=await this.getServiceEndpoints(e,i),a=this.getEndpointURL(s,"generateAuthToken").urlPath||null,o=(await this.getNonce(e,n,r,i,s)+1).toString(),c=await this.getSignature(t,o,rt.CREATE_AUTH_TOKEN);try{const t=await O(a,{method:"POST",body:JSON.stringify({address:n,signature:c,nonce:o}),headers:{"Content-Type":"application/json"},signal:r});if(null==t||!t.ok)throw new Error(`Failed to generate auth token: ${t.status} ${t.statusText}`);const e=await t.json();return null==e?void 0:e.token}catch(t){throw ht.error("Generate auth token failed:"),ht.error(t),new Error("HTTP request failed calling Provider")}}async invalidateAuthToken(t,e,r,n){const i=await t.getAddress(),s=await this.getEndpoints(r),a=await this.getServiceEndpoints(r,s),o=this.getEndpointURL(a,"invalidateAuthToken").urlPath||null,c=(await this.getNonce(r,i,n,s,a)+1).toString(),u=i+c,l=await ee(t,u);try{const t=await O(o,{method:"POST",body:JSON.stringify({address:i,signature:l,token:e,nonce:c}),headers:{"Content-Type":"application/json"},signal:n});if(null==t||!t.ok)throw new Error(`Failed to invalidate auth token: ${t.status} ${t.statusText}`);return await t.json()}catch(t){throw ht.error("Generate auth token failed:"),ht.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const r=await O(t,{method:"GET",headers:{"Content-Type":"application/json"},signal:e});if(null!=r&&r.ok){const t=await r.json();if(t&&(t.providerAddress||t.providerAddresses))return!0}return!1}catch(t){return ht.error(`Error validating provider: ${t.message}`),!1}}async PolicyServerPassthrough(t,e,r){var n;const i=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,i),a=this.getEndpointURL(s,"PolicyServerPassthrough")?this.getEndpointURL(s,"PolicyServerPassthrough").urlPath:null;if(!a)return null;let o;try{if(o=await O(a,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:r}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw ht.error("PolicyServerPassthrough failed: "),ht.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(n=o)&&n.ok)return await o.json();const c=await o.json();throw ht.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),ht.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async initializePSVerification(t,e,r){var n;const i=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,i),a=this.getEndpointURL(s,"initializePSVerification")?this.getEndpointURL(s,"initializePSVerification").urlPath:null;if(!a)return null;let o;try{if(o=await O(a,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:r}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw ht.error("initializePSVerification failed: "),ht.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(n=o)&&n.ok)return await o.json();const c=await o.json();throw ht.error("initializePSVerification failed: ",o.status,o.statusText,c),ht.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async downloadNodeLogs(t,e,r,n,i,s,a,o,c){var u;const l=await this.getEndpoints(t),d=await this.getServiceEndpoints(t,l),h=this.getEndpointURL(d,"logs")?this.getEndpointURL(d,"logs").urlPath:null;if(!h)return ht.error("Download node logs failed: Cannot get proper logs route (perhaps not implemented on provider?)"),null;const f=await e.getAddress(),g=(await this.getNonce(t,f,c,l,d)+1).toString(),p=await this.getSignature(e,g,rt.GET_LOGS);let w,m=h+`?startTime=${r}&endTime=${n}`;i&&(m+=`&maxLogs=${i}`),s&&(m+=`&moduleName=${s}`),a&&(m+=`&level=${a}`),o&&(m+=`&page=${o}`);try{w=await O(m,{method:"POST",body:JSON.stringify({signature:p,nonce:g,address:f}),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw ht.error("Download node logs failed:"),ht.error(t),new Error("HTTP request failed calling Provider")}if(null!=(u=w)&&u.ok)return w.body;const y=await w.json();throw ht.error("Download node logs failed: ",w.status,w.statusText,y),new Error(JSON.stringify(y))}noZeroX(t){return this.zeroXTransformer(t,!1)}zeroXTransformer(t="",e){const{valid:r,output:n}=this.inputMatch(t,/^(?:0x)*([a-f0-9]+)$/i,"zeroXTransformer");return(e&&r?"0x":"")+n}inputMatch(t,e,r){if("string"!=typeof t)throw ht.debug("Not input string:"),ht.debug(t),new Error(`[${r}] Expected string, input type: ${typeof t}`);const n=t.match(e);return n?{valid:!0,output:n[1]}:(ht.warn(`[${r}] Input transformation failed.`),{valid:!1,output:t})}async resolveDdo(t,e,r){const n=t+"/api/aquarius/assets/ddo/"+e,i=await O(n,{method:"GET",headers:{"Content-Type":"application/json"},signal:r});return i.ok?i.json():null}async validateDdo(t,e,r,n){var i;const s=await r.getAddress(),a=await(await this.getData(`${t}/api/services/nonce?userAddress=${s}`)).json(),o=(Number(null!=(i=a.nonce)?i:0)+1).toString(),c=s+o+rt.VALIDATE_DDO,u=await ee(r,c),l=await O(`${t}/api/aquarius/assets/ddo/validate`,{method:"POST",body:JSON.stringify({ddo:e,publisherAddress:s,nonce:o,signature:u}),headers:{"Content-Type":"application/json"},signal:n});if(!l.ok)return null;const d=await l.json();return{valid:!0,hash:d.hash,proof:{validatorAddress:d.publicKey,r:d.r[0],s:d.s[0],v:d.v}}}async getData(t,e){return O(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}class Aa extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,Aa)}}const Ta=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function xa(t,e,r){"function"==typeof r&&(r={filter:r});const n=function(t,e,r){let n;const i=new Promise((i,s)=>{if(!((r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r}).count>=0)||r.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(r.count))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const a=[e].flat(),o=[],{addListener:c,removeListener:u}=(t=>{const e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}})(t),l=async(...t)=>{const e=r.multiArgs?t:t[0];if(r.filter)try{if(!await r.filter(e))return}catch(t){return n(),void s(t)}o.push(e),r.count===o.length&&(n(),i(o))},d=(...t)=>{n(),s(r.rejectionMultiArgs?t:t[0])};n=()=>{for(const t of a)u(t,l);for(const t of r.rejectionEvents)a.includes(t)||u(t,d)};for(const t of a)c(t,l);for(const t of r.rejectionEvents)a.includes(t)||c(t,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&i(o)});if(i.cancel=n,"number"==typeof r.timeout){const t=function(t,e){const{milliseconds:r,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout},signal:a}=e;let o,c;const u=new Promise((e,u)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(a?.aborted)return void u(Ta(a));if(a&&(c=()=>{u(Ta(a))},a.addEventListener("abort",c,{once:!0})),t.then(e,u),r===Number.POSITIVE_INFINITY)return;const l=new Aa;o=s.setTimeout.call(void 0,()=>{if(n)try{e(n())}catch(t){u(t)}else"function"==typeof t.cancel&&t.cancel(),!1===i?e():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${r} milliseconds`,u(l))},r)}).finally(()=>{u.clear(),c&&a&&a.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},u}(i,{milliseconds:r.timeout});return t.cancel=()=>{n(),t.clear()},t}return i}(t,e,r={...r,count:1,resolveImmediately:!1}),i=n.then(t=>t[0]);return i.cancel=n.cancel,i}function ka(t){return t.reason}async function Ca(t,e,r){if(null==e)return t;const n=r?.translateError??ka;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([t,new Promise((t,r)=>{i=()=>{r(n(e))},e.addEventListener("abort",i)})])}finally{null!=i&&e.removeEventListener("abort",i)}}class Fa{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(t,e={}){this.components=t,this.started=!1,this.protocol=`/${e.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=e.timeout??1e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??1,this.runOnLimitedConnection=e.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[le]=["@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(t,e){const r=t.log.newScope("ping");r.trace("ping from %p",e.remotePeer);const n=AbortSignal.timeout(this.timeout);n.addEventListener("abort",()=>{t.abort(new oe("Ping timed out"))});const i=Date.now();for await(const e of t){if("open"!==t.status){r("stream status changed to %s",t.status);break}t.send(e)||(r("waiting for stream to drain"),await xa(t,"drain",{rejectionEvents:["close"],signal:n}),r("stream drained"))}r("ping from %p complete in %dms",e.remotePeer,Date.now()-i),await t.close({signal:n})}async ping(t,e={}){const r=function(){if(isNaN(32))throw new re("random bytes length must be a Number bigger than 0");return Lr(32)}(),n=await this.components.connectionManager.openStream(t,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...e}),i=n.log.newScope("ping");try{const t=Date.now(),i=Promise.withResolvers(),s=new Qe,a=o=>{if(s.append(o.data),32===s.byteLength){n.removeEventListener("message",a);const o=Date.now()-t;Promise.all([n.closeRead(e)]).then(()=>{if(!U(r,s.subarray()))throw new ae(`Received wrong ping ack after ${o}ms`);i.resolve(o)}).catch(t=>{n.abort(t),i.reject(t)})}};return n.addEventListener("message",a),n.send(r),await n.close(e),await Ca(i.promise,e.signal)}catch(e){throw i.error("error while pinging %o - %e",t,e),n?.abort(e),e}finally{n?.close()}}}function Da(t={}){return e=>new Fa(e,t)}class Oa extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class Pa extends Error{static name="UnwrappedError";name="UnwrappedError"}class Ia extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Na extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class La extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Ua(t){return function(t){return"function"==typeof t?.closeRead}(t)?"writable"!==t.remoteWriteStatus&&0===t.readBufferLength:!!function(t){return"function"==typeof t?.close}(t)&&"open"!==t.status}const Ra="/ocean/nodes/1.0.0",Ma=1e4,Ba=["/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"];class _a{constructor(){this.p2pConfig={},this.libp2pNode=null,this.discoveredNodes=new Map}async setupP2P(t){this.p2pConfig=t,this.discoveredNodes.clear(),this.libp2pNode&&(Promise.resolve(this.libp2pNode.stop()).catch(()=>{}),this.libp2pNode=null),await this.getOrCreateLibp2pNode()}async getMultiaddrFromPeerId(t){const e=t=>t.includes("/p2p/")?t:`${t}/p2p/${t}`,r=await this.getOrCreateLibp2pNode(),n=r.getConnections().find(e=>e.remotePeer.toString()===t);if(null!=n&&n.remoteAddr)return e(n.remoteAddr.toString());const i=this.discoveredNodes.get(t);if(i&&i.length>0)return e(i[0]);const s=r.services.dht;var a,o=!1,c=!1;try{for(var u,l=function(t){var e,r,n,i=2;for("undefined"!=typeof Symbol&&(r=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(r&&null!=(e=t[r]))return e.call(t);if(n&&null!=(e=t[n]))return new st(e.call(t));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}(s.findPeer(ba(t),{signal:AbortSignal.timeout(2e4)}));o=!(u=await l.next()).done;o=!1){const t=u.value;if(t.type===W.FINAL_PEER&&t.peer.multiaddrs.length>0)return e(t.peer.multiaddrs[0].toString())}}catch(t){c=!0,a=t}finally{try{o&&null!=l.return&&await l.return()}finally{if(c)throw a}}throw new Error(`No multiaddrs found for peer id ${t}`)}getDiscoveredNodes(){return Array.from(this.discoveredNodes.entries()).map(([t,e])=>({peerId:t,multiaddrs:e}))}bufToHex(t){var e;if("string"==typeof t)try{t=JSON.parse(t)}catch(e){return t}return"Buffer"===(null==(e=t)?void 0:e.type)&&Array.isArray(t.data)?Buffer.from(t.data).toString():t instanceof Uint8Array||Buffer.isBuffer(t)?Buffer.from(t).toString():t}async getOrCreateLibp2pNode(){var t;if(this.libp2pNode)return this.libp2pNode;const e=(null!=(t=this.p2pConfig.bootstrapPeers)?t:Ba).map(B),r=await j(ot({addresses:{listen:[]},transports:[z(),K(),...this.p2pConfig.enableTcp?[H()]:[]],connectionEncrypters:[q()],streamMuxers:[V()],peerDiscovery:[...e.length>0?[Z({list:e.map(String),timeout:1e4})]:[]],services:{identify:J(),ping:Da(),dht:Y({protocol:"/ocean/nodes/1.0.0/kad/1.0.0",clientMode:!0})},connectionManager:{maxConnections:100},connectionMonitor:{abortConnectionOnPingFailure:!1}},this.p2pConfig.libp2p));return await r.start(),r.addEventListener("peer:discovery",t=>{var e;const n=t.detail;if(null==n||!n.id)return;const i=n.id.toString();this.discoveredNodes.set(i,(null!=(e=n.multiaddrs)?e:[]).map(t=>t.toString())),r.getConnections().length<100&&0===r.getConnections(n.id).length&&r.dial(n.id,{signal:AbortSignal.timeout(1e4)}).catch(t=>{ht.debug(`Failed to dial discovered peer ${i}: ${t.message}`)})}),this.libp2pNode=r,r}toUint8Array(t){return t instanceof Uint8Array?t:t.subarray()}isDialable(t){return"undefined"==typeof window||t.toString().includes("/tls/sni")}peerIdFromMultiaddr(t){const e=t.toString().split("/p2p/");return e.length>1?e[e.length-1]:null}async getConnection(t,e){const r=await this.getOrCreateLibp2pNode();if(Array.isArray(t)){const n=t.filter(t=>this.isDialable(t));if(n.length>0){ht.debug(`[P2P] dial array: ${n.length} dialable addrs`);try{const t=await r.dial(n,{signal:e});return ht.debug(`[P2P] dial array SUCCESS via ${t.remoteAddr}`),t}catch(t){ht.debug(`[P2P] dial array failed: ${t.message}`)}}for(const n of t){const t=this.peerIdFromMultiaddr(n);if(t)return ht.debug(`[P2P] Not multiaddrs, fallback to peerId: ${t}`),this.dialByPeerId(r,t,e)}throw new Error("No valid addresses and no peer ID in multiaddrs")}try{const n=B(t);if(this.isDialable(n)){ht.debug(`[P2P] dial single addr: ${n}`);try{const t=await r.dial(n,{signal:e});return ht.debug(`[P2P] dial single SUCCESS via ${t.remoteAddr}`),t}catch(t){ht.debug(`[P2P] dial single failed: ${t.message}`)}}const i=this.peerIdFromMultiaddr(n);if(i)return ht.debug(`[P2P] single fallback -> dialByPeerId ${i}`),this.dialByPeerId(r,i,e);throw new Error(`Cannot dial address: ${t}`)}catch(t){var n;if(null!=(n=t.message)&&n.includes("Cannot dial"))throw t}return ht.debug(`[P2P] bare peerId -> dialByPeerId ${t}`),this.dialByPeerId(r,t,e)}async dialByPeerId(t,e,r){const n=ba(e),i=t.getConnections(n).filter(t=>"open"===t.status);if(i.length>0)return ht.debug(`[P2P] ${e}: reusing existing connection via ${i[0].remoteAddr}`),i[0];if(0===t.getConnections().length){ht.debug(`[P2P] ${e}: no connections yet, waiting for bootstrap...`),await Xt(3e3);const r=t.getConnections(n);if(r.length>0)return ht.debug(`[P2P] ${e}: connected during bootstrap wait`),r[0]}const s=new Set,a=[],o=t=>{const e=t.toString();s.has(e)||(s.add(e),a.push(t))},c=this.discoveredNodes.get(e);if(c){for(const t of c)try{o(B(t))}catch(t){}ht.debug(`[P2P] ${e}: ${c.length} cached addrs`)}const u=a.filter(t=>this.isDialable(t));if(0===u.length){ht.debug(`[P2P] ${e}: no cached dialable addrs, querying DHT...`);try{var l;const r=AbortSignal.timeout(null!=(l=this.p2pConfig.dhtLookupTimeout)?l:6e4),i=await t.peerRouting.findPeer(n,{signal:r});for(const t of i.multiaddrs)o(t);ht.debug(`[P2P] ${e}: DHT returned ${i.multiaddrs.length} addrs`)}catch(t){ht.debug(`[P2P] ${e}: DHT findPeer failed: ${t.message}`)}}else ht.debug(`[P2P] ${e}: ${u.length} cached dialable addrs, skipping DHT`);const d=a.filter(t=>this.isDialable(t)).map(t=>{const r=t.toString();return r.includes("/p2p/")?t:B(`${r}/p2p/${e}`)});if(ht.debug(`[P2P] ${e}: ${d.length}/${a.length} addrs are dialable`),d.length>0){ht.debug(`[P2P] ${e}: dialing ${d.map(String)}`);try{const n=await t.dial(d,{signal:r});return ht.debug(`[P2P] ${e}: SUCCESS via ${n.remoteAddr} (limited=${null!=n.limits})`),n}catch(t){ht.debug(`[P2P] ${e}: direct dial failed: ${t.message}`)}}ht.debug(`[P2P] ${e}: last resort dial by peerId`);try{const r=await t.dial(n,{signal:AbortSignal.timeout(1e4)});return ht.debug(`[P2P] ${e}: peerId dial SUCCESS via ${r.remoteAddr} (limited=${null!=r.limits})`),r}catch(r){throw new Error(`Cannot reach peer ${e}. `+(a.length>0?`Found addrs: ${a.map(String).join(", ")} (none browser-dialable). `:"No addresses found. ")+`Active connections: ${t.getConnections().length}.`)}}getConsumerAddress(t){return Ga(t)}getSignature(t,e,r){return $a(t,e,r)}async getNodePublicKey(t){const e=await this.getEndpoints(t);return null==e?void 0:e.nodePublicKey}getAuthorization(t){return ja(t)}async dialAndStream(t,e,r){var n;const i=null!=r?r:AbortSignal.timeout(null!=(n=this.p2pConfig.dialTimeout)?n:Ma),s=await this.getConnection(t,i);try{const t=await s.newStream(Ra,{signal:i,runOnLimitedConnection:!0}),r=function(t,e={}){const r=function(t,e){const r=e?.maxBufferSize??4194304,n=new Qe;let i,s=!1;if(a=t,null==a?.addEventListener||null==a?.removeEventListener||null==a?.send||null==a?.push||null==a?.log)throw new re("Argument should be a Stream or a Multiaddr");var a;const o=t=>{if(n.append(t.data),n.byteLength>r){const t=n.byteLength;n.consume(n.byteLength),i?.reject(new Error(`Read buffer overflow - ${t} > ${r}`))}i?.resolve()};t.addEventListener("message",o);const c=t=>{null!=t.error?i?.reject(t.error):i?.resolve()};t.addEventListener("close",c);const u=()=>{i?.resolve()};t.addEventListener("remoteCloseWrite",u);const l={readBuffer:n,async read(e){if(!0===s)throw new Pa("Stream was unwrapped");if(Ua(t)){if(0===n.byteLength&&null==e?.bytes)return null;if(null!=e?.bytes&&n.byteLength<e.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,e.bytes),new Oa(`Unexpected EOF - stream closed after reading ${n.byteLength}/${e.bytes} bytes`)}const r=e?.bytes??1;for(i=Promise.withResolvers();;){if(n.byteLength>=r){i.resolve();break}if(await Ca(i.promise,e?.signal),Ua(t)){if(0===n.byteLength&&null==e?.bytes)return null;break}i=Promise.withResolvers()}const a=e?.bytes??n.byteLength;if(n.byteLength<a){if(Ua(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,a),new Oa(`Unexpected EOF - stream closed while reading ${n.byteLength}/${a} bytes`);return l.read(e)}const o=n.sublist(0,a);return n.consume(a),o},async write(e,r){if(!0===s)throw new Pa("Stream was unwrapped");t.send(e)||await xa(t,"drain",{signal:r?.signal,rejectionEvents:["close"]})},unwrap:()=>(s||(s=!0,t.removeEventListener("message",o),t.removeEventListener("close",c),t.removeEventListener("remoteCloseWrite",u),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t)};return l}(t,e);null!=e.maxDataLength&&null==e.maxLengthLength&&(e.maxLengthLength=Wi(e.maxDataLength));const n=e?.lengthDecoder??ts,i=e?.lengthEncoder??Qi;return{async read(i){let s=-1;const a=new Qe;for(;;){const t=await r.read({...i,bytes:1});if(null==t)break;a.append(t);try{s=n(a)}catch(t){if(t instanceof RangeError)continue;throw t}if(s<0)throw new Ia("Invalid message length");if(null!=e?.maxLengthLength&&a.byteLength>e.maxLengthLength)throw new La(`Message length length too long - ${a.byteLength} > ${e.maxLengthLength}`);if(s>-1)break}if(null!=e?.maxDataLength&&s>e.maxDataLength)throw new Na(`Message length too long - ${s} > ${e.maxDataLength}`);const o=await r.read({...i,bytes:s});if(null==o)throw t.log.error("tried to read %d bytes but the stream closed",s),new Oa(`Unexpected EOF - tried to read ${s} bytes but the stream closed`);if(o.byteLength!==s)throw t.log.error("read %d/%d bytes before the stream closed",o.byteLength,s),new Oa(`Unexpected EOF - read ${o.byteLength}/${s} bytes before the stream closed`);return o},async write(t,e){await r.write(new Qe(i(t.byteLength),t),e)},async writeV(t,e){const n=new Qe(...t.flatMap(t=>[i(t.byteLength),t]));await r.write(n,e)},unwrap:()=>r.unwrap()}}(t);await r.write(R(JSON.stringify(e)),{signal:i}),await t.close();const n=await r.read({signal:i});return{lp:r,firstBytes:this.toUint8Array(n),connection:s}}catch(t){try{s.abort(new Error("stream failed"))}catch(t){}throw t}}async sendP2pCommand(t,e,r,n,i,s=0){try{var a,o;const l=ot({command:e,authorization:n?this.getAuthorization(n):void 0},r),{lp:d,firstBytes:h}=await this.dialAndStream(t,l,i);if(!h.length)throw new Error("Gateway node error: no response from peer");const f=M(h);try{const t=JSON.parse(f);var c;if("number"==typeof(null==t?void 0:t.httpStatus)&&t.httpStatus>=400)throw new Error(null!=(c=t.error)?c:`Gateway node error: ${t.httpStatus}`)}catch(t){}if(e===rt.COMPUTE_GET_STREAMABLE_LOGS||e===rt.COMPUTE_GET_RESULT)return ct(function*(){try{for(;;){const t=yield at(d.read({signal:AbortSignal.timeout(Ma)}));yield t instanceof Uint8Array?t:t.subarray()}}catch(t){if(!(t instanceof Oa))throw t}})();const g=[h];try{for(;;){var u;const t=await d.read({signal:AbortSignal.timeout(null!=(u=this.p2pConfig.dialTimeout)?u:Ma)});g.push(this.toUint8Array(t))}}catch(t){if(!(t instanceof Oa))throw t}let p;for(let t=0;t<g.length;t++){const e=M(g[t]);try{p=JSON.parse(e)}catch(e){p=g[t]}}const w=p;if("number"==typeof(null==w?void 0:w.httpStatus)&&w.httpStatus>=400)throw new Error("string"==typeof w.error?w.error:JSON.stringify(w.error));return(null!=(a="string"==typeof p?p:null==w?void 0:w.error)?a:"").includes("Cannot connect to peer")&&s<(null!=(o=this.p2pConfig.maxRetries)?o:5)?(await new Promise(t=>{var e;return setTimeout(t,null!=(e=this.p2pConfig.retryDelay)?e:1e3)}),this.sendP2pCommand(t,e,r,n,i,s+1)):p}catch(a){var l,d;const o=null!=(l=null==a?void 0:a.message)?l:"";if((o.includes("closed")||o.includes("reset"))&&s<(null!=(d=this.p2pConfig.maxRetries)?d:5))return ht.debug(`[P2P] Stream reset/closed on attempt ${s+1}, retrying...`),await Xt(1e3),this.sendP2pCommand(t,e,r,n,i,s+1);throw new Error(`P2P command error: ${o}`)}}async getEndpoints(t){try{return await this.sendP2pCommand(t,rt.STATUS,{})}catch(t){throw ht.error("P2P getEndpoints (STATUS) failed:",t),t}}async getNonce(t,e,r){try{var n,i;const s=await this.sendP2pCommand(t,rt.NONCE,{address:e},null,r),a="number"==typeof s?s:null!=(n=null!=(i=null==s?void 0:s.nonce)?i:s)?n:0;return a&&null!==a?Number(a):0}catch(t){throw ht.error("P2P getNonce failed:",t),t}}async encrypt(t,e,r,n,i,s){const a=await this.getConsumerAddress(n),o=(await this.getNonce(r,a,s)+1).toString(),c=await this.getSignature(n,o,rt.ENCRYPT),u=await this.sendP2pCommand(r,rt.ENCRYPT,{chainId:e,nonce:o,consumerAddress:a,signature:c,blob:"string"==typeof t?t:JSON.stringify(t)},n,s);return this.bufToHex(u)}async checkDidFiles(t,e,r,n=!1,i){const s=await this.sendP2pCommand(r,rt.FILE_INFO,{did:t,serviceId:e,checksum:n},null,i);return Array.isArray(s)?s:[s]}async getFileInfo(t,e,r=!1,n){const i=await this.sendP2pCommand(e,rt.FILE_INFO,{file:t,type:t.type,checksum:r},null,n);return Array.isArray(i)?i:[i]}async getComputeEnvironments(t,e){const r=await this.sendP2pCommand(t,rt.COMPUTE_GET_ENVIRONMENTS,{},null,e);return Array.isArray(r)?r:[r]}async initialize(t,e,r,n,i,s,a,o,c){const u={ddoId:t,serviceId:e,consumerAddress:n};return a&&(u.userdata=a),o&&(u.environment=o),c&&(u.validUntil=c),this.sendP2pCommand(i,rt.GET_FEES,u,null,s)}async initializeCompute(t,e,r,n,i,s,a,o,c,u,l){const d={datasets:t,algorithm:e,environment:r,payment:{chainId:c,token:n,resources:o},maxJobDuration:i,consumerAddress:a};return u&&(d.policyServer=u),this.sendP2pCommand(s,rt.COMPUTE_INITIALIZE,d,null,l)}async getDownloadUrl(t,e,r,n,i,s,a,o){const c=await this.getConsumerAddress(s),u=(await this.getNonce(i,c)+1).toString(),l=await this.getSignature(s,u,rt.DOWNLOAD),d={command:rt.DOWNLOAD,authorization:this.getAuthorization(s),fileIndex:r,documentId:t,transferTxId:n,serviceId:e,consumerAddress:c,nonce:u,signature:l};a&&(d.policyServer=a),o&&(d.userData=o);const{lp:h,firstBytes:f}=await this.dialAndStream(i,d),g=M(f);let p=null;try{p=JSON.parse(g)}catch(t){}var w;if(p&&"number"==typeof p.httpStatus&&p.httpStatus>=400)throw new Error(null!=(w=p.error)?w:`P2P download error: ${p.httpStatus}`);const m=null===p?[Buffer.from(f)]:[];try{for(;;){var y;const t=await h.read({signal:AbortSignal.timeout(null!=(y=this.p2pConfig.dialTimeout)?y:Ma)});m.push(Buffer.from(this.toUint8Array(t)))}}catch(t){if(!(t instanceof Oa))throw t}const b=Buffer.concat(m);return{data:b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength),filename:`file${r}`}}async computeStart(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p){const w=await this.getConsumerAddress(e),m=(await this.getNonce(t,w,f)+1).toString(),y=await this.getSignature(e,m,rt.COMPUTE_START),b={environment:r,dataset:n[0],datasets:n,algorithm:i,maxJobDuration:s,feeToken:a,resources:o,chainId:c,payment:{chainId:c,token:a,maxJobDuration:s,resources:o},consumerAddress:w,nonce:m,signature:y};if(u&&(b.metadata=u),l&&(b.additionalViewers=l),h&&(b.policyServer=h),g&&(b.queueMaxWaitTime=g),p){const e=await this.getNodePublicKey(t);e&&(b.dockerRegistryAuth=Ea(e,JSON.stringify(p)))}if(d){const e=await this.getNodePublicKey(t);e&&(b.output=Ea(e,JSON.stringify(d)))}const v=await this.sendP2pCommand(t,rt.COMPUTE_START,b,e,f);return Array.isArray(v),v}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,d,h){const f=await this.getConsumerAddress(e),g=(await this.getNonce(t,f,l)+1).toString(),p=await this.getSignature(e,g,rt.FREE_COMPUTE_START),w={environment:r,dataset:n[0],datasets:n,algorithm:i,resources:s,consumerAddress:f,nonce:g,signature:p};if(a&&(w.metadata=a),o&&(w.additionalViewers=o),u&&(w.policyServer=u),d&&(w.queueMaxWaitTime=d),h){const e=await this.getNodePublicKey(t);e&&(w.dockerRegistryAuth=Ea(e,JSON.stringify(h)))}if(c){const e=await this.getNodePublicKey(t);e&&(w.output=Ea(e,JSON.stringify(c)))}const m=await this.sendP2pCommand(t,rt.FREE_COMPUTE_START,w,e,l);return Array.isArray(m),m}async computeStreamableLogs(t,e,r,n){if("string"==typeof e)return this.sendP2pCommand(t,rt.COMPUTE_GET_STREAMABLE_LOGS,{jobId:r},e,n);const i=await this.getConsumerAddress(e),s=(await this.getNonce(t,i,n)+1).toString(),a=await this.getSignature(e,s,rt.COMPUTE_GET_STREAMABLE_LOGS);return this.sendP2pCommand(t,rt.COMPUTE_GET_STREAMABLE_LOGS,{jobId:r,consumerAddress:i,nonce:s,signature:a},e,n)}async computeStop(t,e,r,n,i){const s=await this.getConsumerAddress(r),a=(await this.getNonce(e,s,i)+1).toString(),o={jobId:t,consumerAddress:s,nonce:a,signature:await this.getSignature(r,a,rt.COMPUTE_STOP)};return n&&(o.agreementId=n),this.sendP2pCommand(e,rt.COMPUTE_STOP,o,r,i)}async computeStatus(t,e,r,n,i){const s={consumerAddress:await this.getConsumerAddress(e)};return r&&(s.jobId=r),n&&(s.agreementId=n),this.sendP2pCommand(t,rt.COMPUTE_GET_STATUS,s,e,i)}async getComputeResult(t,e,r,n,i=0){var s;const a=await this.getConsumerAddress(e),o={command:rt.COMPUTE_GET_RESULT,jobId:r,index:n,offset:i,consumerAddress:a};if("string"==typeof e)o.authorization=e;else{const r=(await this.getNonce(t,a)+1).toString();o.nonce=r,o.signature=await this.getSignature(e,r,rt.COMPUTE_GET_RESULT)}const{lp:c,firstBytes:u}=await this.dialAndStream(t,o),l=JSON.parse(M(u));var d;if("number"==typeof(null==l?void 0:l.httpStatus)&&l.httpStatus>=400)throw new Error(null!=(d=l.error)?d:`P2P compute result error: ${l.httpStatus}`);const h=null!=(s=this.p2pConfig.dialTimeout)?s:Ma;return ct(function*(){try{for(;;){const t=yield at(c.read({signal:AbortSignal.timeout(h)}));yield t instanceof Uint8Array?t:t.subarray()}}catch(t){if(!(t instanceof Oa))throw t}})()}async getComputeResultUrl(t,e,r,n){const i=await this.getConsumerAddress(e);return await this.sendP2pCommand(t,rt.COMPUTE_GET_RESULT,{jobId:r,index:n,consumerAddress:i},e)}async generateAuthToken(t,e,r){var n;const i=await t.getAddress(),s=(await this.getNonce(e,i,r)+1).toString(),a=await this.getSignature(t,s,rt.CREATE_AUTH_TOKEN),o=await this.sendP2pCommand(e,rt.CREATE_AUTH_TOKEN,{address:i,signature:a,nonce:s},null,r);return null!=(n=null==o?void 0:o.token)?n:o}async resolveDdo(t,e,r){return this.sendP2pCommand(t,rt.GET_DDO,{id:e},null,r)}async validateDdo(t,e,r,n){var i,s,a,o;const c=await r.getAddress(),u=(await this.getNonce(t,c,n)+1).toString(),l=c+u+rt.VALIDATE_DDO,d=await ee(r,l),h=await this.sendP2pCommand(t,rt.VALIDATE_DDO,{ddo:e,publisherAddress:c,nonce:u,signature:d},null,n);return!h||h.error?null:{valid:!0,hash:this.bufToHex(h.hash),proof:{validatorAddress:this.bufToHex(h.publicKey),r:this.bufToHex(null!=(i=null==(s=h.r)?void 0:s[0])?i:h.r),s:this.bufToHex(null!=(a=null==(o=h.s)?void 0:o[0])?a:h.s),v:h.v}}}async invalidateAuthToken(t,e,r,n){const i=await t.getAddress(),s=(await this.getNonce(r,i,n)+1).toString(),a=i+s,o=await ee(t,a);return this.sendP2pCommand(r,rt.INVALIDATE_AUTH_TOKEN,{address:i,signature:o,token:e,nonce:s},null,n)}async isValidProvider(t,e){try{const r=await this.sendP2pCommand(t,rt.STATUS,{},null,e);return!(!r||!(r.address||r.providerAddress||r.providerAddresses))}catch(t){return!1}}async PolicyServerPassthrough(t,e,r){return this.sendP2pCommand(t,rt.POLICY_SERVER_PASSTHROUGH,ot({},e),null,r)}async initializePSVerification(t,e,r){return this.sendP2pCommand(t,rt.POLICY_SERVER_PASSTHROUGH,ot({},e),null,r)}async downloadNodeLogs(t,e,r,n,i,s,a,o,c){const u=await e.getAddress(),l=(await this.getNonce(t,u,c)+1).toString(),d={startTime:r,endTime:n,signature:await this.getSignature(e,l,rt.GET_LOGS),nonce:l,address:u};return i&&(d.maxLogs=i),s&&(d.moduleName=s),a&&(d.level=a),o&&(d.page=o),this.sendP2pCommand(t,rt.GET_LOGS,d,e,c)}async fetchConfig(t,e){return this.sendP2pCommand(t,rt.FETCH_CONFIG,e)}async pushConfig(t,e){return this.sendP2pCommand(t,rt.PUSH_CONFIG,e)}}async function Ga(t){return"string"==typeof t?function(t){try{return _.decode(t,{json:!0})}catch(t){throw new Error("Error decoding JWT")}}(t).address:t.getAddress()}async function $a(t,e,r){if("string"==typeof t)return null;const n=String(String(await t.getAddress())+String(e)+String(r));return ee(t,n)}function ja(t){return"string"==typeof t?t:void 0}function qa(t){if(Array.isArray(t))return!0;if(!t)return!1;try{return B(t),!0}catch(t){}try{return ba(t),!0}catch(t){return!1}}class Va{constructor(){this.httpProvider=new Sa,this.p2pProvider=new _a}getImpl(t){return Array.isArray(t)||qa(t)?this.p2pProvider:this.httpProvider}async getNonce(t,e,r,n,i){return this.getImpl(t).getNonce(t,e,r,n,i)}async encrypt(t,e,r,n,i,s){return this.getImpl(r).encrypt(t,e,r,n,i,s)}async checkDidFiles(t,e,r,n=!1,i){return this.getImpl(r).checkDidFiles(t,e,r,n,i)}async getFileInfo(t,e,r=!1,n){return this.getImpl(e).getFileInfo(t,e,r,n)}async getComputeEnvironments(t,e){return this.getImpl(t).getComputeEnvironments(t,e)}async initialize(t,e,r,n,i,s,a,o,c){return this.getImpl(i).initialize(t,e,r,n,i,s,a,o,c)}async initializeCompute(t,e,r,n,i,s,a,o,c,u,l){return this.getImpl(s).initializeCompute(t,e,r,n,i,s,a,o,c,u,l)}async getDownloadUrl(t,e,r,n,i,s,a,o){return this.getImpl(i).getDownloadUrl(t,e,r,n,i,s,a,o)}async computeStart(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p){return this.getImpl(t).computeStart(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p)}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,d,h){return this.getImpl(t).freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,d,h)}async computeStreamableLogs(t,e,r,n){return this.getImpl(t).computeStreamableLogs(t,e,r,n)}async computeStop(t,e,r,n,i){return this.getImpl(e).computeStop(t,e,r,n,i)}async computeStatus(t,e,r,n,i){return this.getImpl(t).computeStatus(t,e,r,n,i)}async getComputeResultUrl(t,e,r,n){return this.getImpl(t).getComputeResultUrl(t,e,r,n)}async getComputeResult(t,e,r,n,i=0){return this.getImpl(t).getComputeResult(t,e,r,n,i)}async generateAuthToken(t,e,r){return this.getImpl(e).generateAuthToken(t,e,r)}async invalidateAuthToken(t,e,r,n){return this.getImpl(r).invalidateAuthToken(t,e,r,n)}async resolveDdo(t,e,r){return this.getImpl(t).resolveDdo(t,e,r)}async validateDdo(t,e,r,n){return this.getImpl(t).validateDdo(t,e,r,n)}async isValidProvider(t,e){return this.getImpl(t).isValidProvider(t,e)}async PolicyServerPassthrough(t,e,r){return this.getImpl(t).PolicyServerPassthrough(t,e,r)}async initializePSVerification(t,e,r){return this.getImpl(t).initializePSVerification(t,e,r)}async downloadNodeLogs(t,e,r,n,i,s,a,o,c){return this.getImpl(t).downloadNodeLogs(t,e,r,n,i,s,a,o,c)}async setupP2P(t){return this.p2pProvider.setupP2P(t)}getDiscoveredNodes(){return this.p2pProvider.getDiscoveredNodes()}async getMultiaddrFromPeerId(t){return this.p2pProvider.getMultiaddrFromPeerId(t)}async fetchConfig(t,e){return this.p2pProvider.fetchConfig(t,e)}async pushConfig(t,e){return this.p2pProvider.pushConfig(t,e)}}const za=new Va;class Ha{constructor(t){this.aquariusURL=void 0,this.aquariusURL=t}async resolve(t,e,r){if(qa(this.aquariusURL)){const r=await za.resolveDdo(this.aquariusURL,t,e);if(r)return r;throw new Error("P2P request failed")}const n=this.aquariusURL+"/api/aquarius/assets/ddo/"+t;try{const t=await O(n,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:e});if(t.ok)return await t.json();throw new Error("HTTP request failed with status "+t.status)}catch(t){throw ht.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,r,n=3e4,i=100,s){let a=0;i>500&&(ht.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);const o=qa(this.aquariusURL);do{try{let n;if(o)n=await za.resolveDdo(this.aquariusURL,t,r);else{const e=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,i=await O(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:s},signal:r});i.ok&&(n=await i.json())}if(n){const t=P.getDDOClass(n),{indexedMetadata:r}=t.getAssetFields();if(!e)return n;if(r.event&&r.event.txid===e)return n}}catch(t){}await Xt(n),a++}while(a<i);return null}async validate(t,e,r,n,i){if(qa(r))return za.validateDdo(r,t,e,n);const s=r+"/api/aquarius/assets/ddo/validate",a=r+"/api/services/nonce";try{const r=await e.getAddress(),o=await O(a+`?userAddress=${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:i},signal:n});let{nonce:c}=await o.json();c&&null!==c||(c="0");const u=(Number(c)+1).toString(),l=String(String(await e.getAddress())+String(u)+String(rt.VALIDATE_DDO)),d={ddo:t,publisherAddress:r,nonce:u,signature:await ee(e,l)},h=await O(s,{method:"POST",body:JSON.stringify(d),headers:{"Content-Type":"application/json",Authorization:ja(e)},signal:n}),f=await h.json();if(200!==h.status)throw new Error("Metadata validation failed");return{valid:!0,hash:f.hash,proof:{validatorAddress:f.publicKey,r:f.r[0],s:f.s[0],v:f.v}}}catch(t){ht.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,r){const n=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await O(n,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:e});if(t.ok)return t.json();throw new Error("getAssetMetadata failed: "+t.status+t.statusText)}catch(t){throw ht.error("Error getting metadata: ",t),new Error("Error getting metadata: "+t)}}async querySearch(t,e,r){const n=this.aquariusURL+"/api/aquarius/assets/query";try{const i=await O(n,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:r},signal:e});if(i.ok)return i.json();throw new Error("querySearch failed: "+i.status+i.statusText)}catch(t){throw ht.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}function Ka(t,e){return t=l(t),`did:op:${X(t+e.toString(10)).toString()}`}function Za(t){return X(t).toString()}function Ja(t){const e=new XMLHttpRequest;e.responseType="blob",e.open("GET",t),e.onload=()=>{const t=e.getResponseHeader("content-disposition"),r=null==t?void 0:t.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/),n=r&&r[1]?r[1]:"file",i=window.URL.createObjectURL(e.response),s=document.createElement("a");s.href=i,s.setAttribute("download",n),document.body.appendChild(s),s.click(),s.remove(),window.URL.revokeObjectURL(i)},e.send()}async function Wa(t,e){if("string"!=typeof t)return t;const r=await fetch(t);if(!r.ok)throw new Error("Response error.");let n;try{n=r.headers.get("content-disposition").match(/attachment;filename=(.+)/)[1]}catch(r){try{n=t.split("/").pop()}catch(t){n=`file${e}`}}return{data:await r.arrayBuffer(),filename:n}}async function Ya(t,e,n,i,s,a,o=!1,c,u){const l=new r.Contract(i,yt,t);if(!o){const e=await to(t,i,n,s);if(new w(e).greaterThanOrEqualTo(new w(a)))return new w(e).toNumber()}const d=await Ct(t,i,a,c),h=await l.approve.estimateGas(s,d);return u?new w(h.toString()):await Dt(h,t,null==e?void 0:e.gasFeeMultiplier,l.approve,s,d)}async function Xa(t,e,n,i,s,a,o=!1,c){const u=new r.Contract(i,yt,t);if(!o){const e=await ro(t,i,n,s);if(new p(e).isGreaterThan(new p(a)))return BigInt(e)}let l=null;const d=await u.approve.estimateGas(s,a);if(c)return d;try{l=await Dt(d,t,null==e?void 0:e.gasFeeMultiplier,u.approve,s,a)}catch(t){ht.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return l}async function Qa(t,e,n,i,s,a,o){const c=new r.Contract(n,yt,t),u=await Ct(t,n,s,a),l=await c.transfer.estimateGas(i,u);return o?l:await Dt(l,t,null==e?void 0:e.gasFeeMultiplier,c.transfer,i,u)}async function to(t,e,n,i,s){const a=new r.Contract(e,yt,t),o=await a.allowance(n,i);return await kt(t,e,o,s)}async function eo(t,e,n,i){const s=new r.Contract(e,yt,t),a=await s.balanceOf(n);return await kt(t,e,a,i)}async function ro(t,e,n,i){const s=new r.Contract(e,yt,t);return await s.allowance(n,i)}async function no(t,e){const n=new r.Contract(e,yt,t),i=await n.decimals();return Number(i)}const io={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 so(t){try{const r=JSON.parse(t),n=Object.keys(r)[0];if("error"===n){var e;const t=r[n];return(null==(e=io[n])?void 0:e[t])||`Provider request failed: ${t}`}{const t=r[n];return`${r[Object.keys(r)[1]]} : ${t}`}}catch(e){return ht.error("[getErrorMessage] error: ",e),t}}async function ao(t,e,r,n,i,s,a,o,c="0",u=0,l=0,d=0){const h=P.getDDOClass(t),{datatokens:f}=h.getAssetFields(),{chainId:g,services:p}=h.getDDOFields();a||(a={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"});const m=(await e.provider.getNetwork()).chainId;if(g!==Number(m))throw new Error("Chain ID from DDO is different than the configured network.");if(!f[u].address)throw new Error(`The datatoken with index: ${u} does not exist for the asset with did: ${t.id}`);if(!p[l].id)throw new Error(`There is no service with index: ${l} defined for the asset with did: ${t.id}`);const y=await n.getId(f[u].address),b=await n.getFixedRates(f[u].address),v=await n.getDispensers(f[u].address),E=await n.getPublishingMarketFee(f[u].address),S=b.length>0?"fixed":v.length>0?"free":"NOT_ALLOWED",A=o||(await za.initialize(t.id,p[l].id,0,await e.getAddress(),i||r.oceanNodeUri)).providerFee;if(A&&A.providerFeeAddress!==Nt&&A.providerFeeAmount&&parseInt(A.providerFeeAmount)>0)try{await Xa(e,r,await e.getAddress(),A.providerFeeToken,p[0].datatokenAddress,A.providerFeeAmount)}catch(t){throw new Error(`Failed to approve provider fee token ${A.providerFeeToken}`)}const T={consumer:s||await e.getAddress(),serviceIndex:l,_providerFee:A,_consumeMarketFee:a};switch(S){case"free":if(1===y){const t=new It(r.dispenserAddress,e),i=await t.dispense(f[u].address,"1",await e.getAddress());if(!i)throw new Error("Failed to dispense !");return await i.wait(),await n.startOrder(f[u].address,T.consumer,T.serviceIndex,T._providerFee,T._consumeMarketFee)}if(2===y||4===y)return await n.buyFromDispenserAndOrder(p[l].datatokenAddress,T,r.dispenserAddress);break;case"fixed":{const i=new Mt(r.fixedRateExchangeAddress,e);if(!b[d].id)throw new Error(`There is no fixed rate exchange with index: ${l} for the asset with did: ${t.id}`);const s=await i.getFeesInfo(b[d].id),o=await i.getExchange(b[d].id),{baseTokenAmount:h}=await i.calcBaseInGivenDatatokensOut(s.exchangeId,"1",a.consumeMarketFeeAmount),g=new w(+h||0).add(new w(a.consumeMarketFeeAmount||0)).add(new w(+E.publishMarketFeeAmount||0)).toString(),p={exchangeContract:r.fixedRateExchangeAddress,exchangeId:s.exchangeId,maxBaseTokenAmount:g,baseTokenAddress:o.baseToken,baseTokenDecimals:parseInt(o.btDecimals)||18,swapMarketFee:c,marketFeeAddress:E.publishMarketFeeAddress};if(1===y){const t=await Ya(e,r,await e.getAddress(),o.baseToken,r.fixedRateExchangeAddress,g,!1);if(!("number"!=typeof t?await t.wait():t))throw new Error(`Failed to approve ${o.baseToken} !`);const s=await i.buyDatatokens(o.exchangeId,"1",g,E.publishMarketFeeAddress,c);if(!await s.wait())throw new Error("Failed to buy datatoken from fixed rate!");return await n.startOrder(f[u].address,T.consumer,T.serviceIndex,T._providerFee,T._consumeMarketFee)}if(2===y||4===y){const t=await Ya(e,r,await e.getAddress(),o.baseToken,f[u].address,g,!1);if(!t)throw new Error(`Failed to approve ${o.baseToken} !`);if(!("number"!=typeof t?await t.wait():t))throw new Error("Failed to confirm/mine approval transaction!");return await n.buyFromFreAndOrder(f[u].address,T,p)}break}default:throw new Error("Pricing schema not supported !")}}const oo=8996;function co(t){const e=(new mt).getConfig(t);return e&&"oasis"===e.sdk}async function uo(t,e,n,i,s,o,u=!0,l,d,h,g,p,w,m,y){var b,v;const E=P.getDDOClass(o),{indexedMetadata:S}=E.getAssetFields(),A=(null==(b=E.getDDOData())||null==(b=b.stats)||null==(b=b.price)?void 0:b.value)||(null==S||null==(v=S.stats[0])||null==(v=v.prices[0])?void 0:v.price);let{chainId:T,nftAddress:k}=E.getDDOFields();const{services:C}=E.getDDOFields();if("string"!=typeof s&&"number"!=typeof s)throw new Error('Invalid template! Must be a "number" or a "string"');const F=(await n.provider.getNetwork()).chainId;if(T&&T!==Number(F))throw new Error("Chain ID from DDO is different than the configured network.");const D=(new mt).getConfig(parseInt(String(F)));let O=await Vt(n,D.nftFactoryAddress,s,Number(F));if(O<1){if(8996!==Number(F))throw new Error(`Invalid template index: ${O}`);O=1}const I=new zt(n,Number(F)),N=new $t(D.nftFactoryAddress,n,Number(F)),L=await n.getAddress(),U={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:L},R={templateIndex:O,cap:"100000",feeAmount:"0",paymentCollector:L,feeToken:d||D.oceanTokenAddress,minter:L,mpFeeAddress:Nt},M={nftAddress:"0x0",datatokenAddress:"0x0",files:i};let B;"oasis"===D.sdk&&(R.filesObject=M,R.accessListFactory=g||D.accessListFactory,R.allowAccessList=p,R.denyAccessList=w);try{if(A)if("0"===A.toString()){const t={dispenserAddress:D.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:Nt};B=await N.createNftWithDatatokenWithDispenser(U,R,t)}else{const t=m||D.oceanTokenAddress;y||(y=await xt(this.signer,t));const e={fixedRateAddress:D.fixedRateExchangeAddress,baseTokenAddress:t,owner:L,marketFeeCollector:L,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:A.toString(),marketFee:"0",allowedConsumer:L,withMint:!0};B=await N.createNftWithDatatokenWithFixedRate(U,R,e)}else B=await N.createNftWithDatatoken(U,R)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const _=await B.wait(),G=Ft(_,"NFTCreated"),$=Ft(_,"TokenCreated"),j=G.args.newTokenAddress,q=$.args.newTokenAddress;if(M.datatokenAddress=q,M.nftAddress=j,"oasis"===D.sdk){const t=new r.Contract(q,x.abi,n);try{const e=await t.setFilesObject(a(JSON.stringify(M)));e.wait&&await e.wait()}catch(t){return console.log("Error updating files object with data token and nft addresses: ",t),null}}C[0].files="oasis"===D.sdk?"":await za.encrypt(M,Number(F),l,n,null),C[0].datatokenAddress=q,C[0].serviceEndpoint=l,k=j;const V=E.makeDid(k,T.toString());let z,H,K;if(o=E.updateFields({id:V,nftAddress:k}),u)z=await za.encrypt(o,Number(F),l,n,null),H=(await h.validate(o,n,l)).hash,K=2;else{const t=JSON.stringify(o),e=Buffer.from(t);z=c(e),H="0x"+Q("sha256").update(z).digest("hex"),K=0}return await I.setMetadata(k,await n.getAddress(),0,l,"",f(K),z,H),o.id}async function lo(t,e,n){const i=new r.Contract(t,C.abi,e),s=await e.getAddress();try{const t=await i.deployAccessListContract("AllowList","ALLOW",!0,s,n||[s],["https://oceanprotocol.com/nft/"]);if(t&&t.wait)return Ft(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{Zt as AccessListContract,Jt as AccesslistFactory,Ha as Aquarius,nt as Config,mt as ConfigHelper,oo as DEVELOPMENT_CHAIN_ID,Ht as Datatoken,Kt as Datatoken4,It as Dispenser,et as EncryptMethod,Yt as EnterpriseFeeCollectorContract,Wt as EscrowContract,Rt as FEE_HISTORY_NOT_SUPPORTED,tt as FileObjectType,Mt as FixedRateExchange,Lt as GASLIMIT_DEFAULT,pt as KNOWN_CONFIDENTIAL_EVMS,lt as LogLevel,dt as Logger,ht as LoggerInstance,Ut as MAX_UINT_256,zt as Nft,$t as NftFactory,Ra as OCEAN_P2P_PROTOCOL,rt as PROTOCOL_COMMANDS,Va as Provider,za as ProviderInstance,Bt as Router,Ot as SmartContract,Pt as SmartContractWithAddress,Nt as ZERO_ADDRESS,to as allowance,ro as allowanceWei,Ct as amountToUnits,Ya as approve,Xa as approveWei,eo as balance,Vt as calculateActiveTemplateIndex,gt as configHelperNetworks,lo as createAccessListFactory,uo as createAsset,no as decimals,Wa as downloadFile,Ja as downloadFileBrowser,Ka as generateDid,Gt as generateDtName,so as getErrorMessage,Ft as getEventFromTx,Tt as getFairGasPrice,Za as getHash,wt as getNodeEndpointConfig,jt as getOceanArtifactsAddresses,qt as getOceanArtifactsAddressesByChainId,xt as getTokenDecimals,Qt as isDefined,qa as isP2pUri,yt as minAbi,ao as orderAsset,Dt as sendTx,At as setContractDefaults,te as signHash,ee as signRequest,Xt as sleep,Qa as transfer,kt as unitsToAmount,co as useOasisSDK};
1
+ import t from"@oceanprotocol/contracts/addresses/address.json";import e from"fs";import{ethers as r,formatUnits as n,parseUnits as i,EventLog as s,toUtf8Bytes as a,keccak256 as o,hexlify as c,toUtf8String as u,getAddress as l,parseEther as d,getBytes as h,toBeHex as f}from"ethers";import*as g from"@oasisprotocol/sapphire-paratime";import p from"bignumber.js";import w from"decimal.js";import m from"@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json";import y from"@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json";import b from"@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json";import v from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json";import E from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json";import S from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json";import A from"@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json";import T from"@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json";import x from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template4.sol/ERC20Template4.json";import C from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessList.sol/AccessList.json";import k from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessListFactory.sol/AccessListFactory.json";import F from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import D from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import O from"cross-fetch";import{DDOManager as P}from"@oceanprotocol/ddo-js";import{multiaddr as I}from"@multiformats/multiaddr";import N from"jsonwebtoken";import{PublicKey as L,encrypt as U}from"eciesjs";import{createLibp2p as R}from"libp2p";import{noise as M}from"@chainsafe/libp2p-noise";import{yamux as B}from"@chainsafe/libp2p-yamux";import{webSockets as _}from"@libp2p/websockets";import{tcp as $}from"@libp2p/tcp";import{circuitRelayTransport as G}from"@libp2p/circuit-relay-v2";import{bootstrap as j}from"@libp2p/bootstrap";import{identify as q}from"@libp2p/identify";import{EventTypes as V,kadDHT as z}from"@libp2p/kad-dht";import H from"crypto-js/sha256.js";import{createHash as K}from"crypto";var Z,J;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave",t.S3="s3",t.FTP="ftp"}(Z||(Z={})),function(t){t.AES="AES",t.ECIES="ECIES"}(J||(J={}));const W={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"};class Y{constructor(){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 X(t,e){this.v=t,this.k=e}function Q(t){function e(t){if(Object(t)!==t)return Promise.reject(new TypeError(t+" is not an object."));var e=t.done;return Promise.resolve(t.value).then(function(t){return{value:t,done:e}})}return Q=function(t){this.s=t,this.n=t.next},Q.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(t){var r=this.s.return;return void 0===r?Promise.resolve({value:t,done:!0}):e(r.apply(this.s,arguments))},throw:function(t){var r=this.s.return;return void 0===r?Promise.reject(t):e(r.apply(this.s,arguments))}},new Q(t)}function tt(t){return new X(t,0)}function et(){return et=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)({}).hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},et.apply(null,arguments)}function rt(t){return function(){return new nt(t.apply(this,arguments))}}function nt(t){var e,r;function n(e,r){try{var s=t[e](r),a=s.value,o=a instanceof X;Promise.resolve(o?a.v:a).then(function(r){if(o){var c="return"===e?"return":"next";if(!a.k||r.done)return n(c,r);r=t[c](r).value}i(s.done?"return":"normal",r)},function(t){n("throw",t)})}catch(t){i("throw",t)}}function i(t,i){switch(t){case"return":e.resolve({value:i,done:!0});break;case"throw":e.reject(i);break;default:e.resolve({value:i,done:!1})}(e=e.next)?n(e.key,e.arg):r=null}this._invoke=function(t,i){return new Promise(function(s,a){var o={key:t,arg:i,resolve:s,reject:a,next:null};r?r=r.next=o:(e=r=o,n(t,i))})},"function"!=typeof t.return&&(this.return=void 0)}var it;nt.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},nt.prototype.next=function(t){return this._invoke("next",t)},nt.prototype.throw=function(t){return this._invoke("throw",t)},nt.prototype.return=function(t){return this._invoke("return",t)},function(t){t[t.None=-1]="None",t[t.Error=0]="Error",t[t.Warn=1]="Warn",t[t.Log=2]="Log",t[t.Verbose=3]="Verbose"}(it||(it={}));class st{constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||it.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",it.Verbose,...t)}log(...t){this.dispatch("log",it.Log,...t)}warn(...t){this.dispatch("warn",it.Warn,...t)}error(...t){this.dispatch("error",it.Error,...t)}dispatch(t,e,...r){this.logLevel>=e&&console[t](...r)}}const at=new st,ot={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},ct=[et({},ot),et({},ot,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),et({},ot,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),et({},ot,{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"}),et({},ot,{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"}),et({},ot,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),et({},ot,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),et({},ot,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),et({},ot,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),et({},ot,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),et({},ot,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),et({},ot,{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"}),et({},ot,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),et({},ot,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),et({},ot,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),et({},ot,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),et({},ot,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],ut=[23294,23295],lt=()=>process.env.NODE_ENDPOINT||process.env.NODE_URL?{oceanNodeUri:process.env.NODE_ENDPOINT||process.env.NODE_URL}:{};class dt{getAddressesFromEnv(e,r){let n;if(r&&r[e]){const{FixedPrice:t,Dispenser:i,ERC721Factory:s,OPFCommunityFeeCollector:a,Ocean:o,chainId:c,startBlock:u,Router:l,AccessListFactory:d,Escrow:h,EnterpriseFeeCollector:f}=r[e];n=et({nftFactoryAddress:s,opfCommunityFeeCollector:a,fixedRateExchangeAddress:t,dispenserAddress:i,oceanTokenAddress:o,routerFactoryAddress:l,chainId:c,startBlock:u,accessListFactory:d,escrow:h,EnterpriseFeeCollector:f},lt())}else if(t[e]){const{FixedPrice:r,Dispenser:i,OPFCommunityFeeCollector:s,ERC721Factory:a,Ocean:o,chainId:c,startBlock:u,Router:l,AccessListFactory:d,Escrow:h,EnterpriseFeeCollector:f}=t[e];n=et({nftFactoryAddress:a,opfCommunityFeeCollector:s,fixedRateExchangeAddress:r,dispenserAddress:i,oceanTokenAddress:o,routerFactoryAddress:l,chainId:c,startBlock:u,accessListFactory:d,escrow:h,EnterpriseFeeCollector:f},lt())}return n}getConfig(t,r){const n="string"==typeof t?"network":"chainId";let i,s=ct.find(e=>e[n]===t);if(!s)return at.error(`No config found for given network '${t}'`),null;try{i=process.env.ADDRESS_FILE?JSON.parse(e.readFileSync(process.env.ADDRESS_FILE,"utf8")):null}catch(t){console.log(t),i=null}let a=this.getAddressesFromEnv(s.network,i);return!a&&ut.includes(s.chainId)&&(a=this.getAddressesFromEnv(s.network.replace("sapph","saph"),i)),"sdk"in s&&null!==s.sdk||(s.sdk=ut.includes(s.chainId)?"oasis":"evm"),a&&"accessListFactory"in a&&(s.accessListFactory=a.accessListFactory),s=et({},s,a),et({},s,{nodeUri:r?`${s.nodeUri}/${r}`:s.nodeUri})}}const ht=[{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"}],ft=3e10,gt=4e9,pt=1e10,wt=11155111;function mt(t,e){return t}async function yt(t,e){const r=(await t.provider.getFeeData()).gasPrice,n=BigInt(r.toString());return e?(n*BigInt(e)).toString(10):n.toString()}async function bt(t,e){return new r.Contract(e,ht,t).decimals()}async function vt(t,e,r,i){let s=i||await bt(t,e);return"0"===s&&(s=18),n(r,s).toString()}async function Et(t,e,r,n){let s=n||await bt(t,e);return"0"===s&&(s=18),i(r,s).toString()}function St(t,e){if(t&&t.logs)return t.logs.filter(t=>t instanceof s&&t.eventName===e)[0]}async function At(t,e,r,n,...i){const{chainId:s}=await e.provider.getNetwork(),a=await e.provider.getFeeData();let o={};if(a.maxPriorityFeePerGas){let t=a.maxPriorityFeePerGas.toString(),e=a.maxFeePerGas.toString();r>1&&(t=Math.round(Number(a.maxPriorityFeePerGas)*r).toString(),e=Math.round(Number(a.maxFeePerGas)*r).toString()),o={maxPriorityFeePerGas:(80001===Number(s)||137===Number(s))&&Number(t)<ft?ft:Number(s)===wt&&Number(t)<gt?gt:ut.includes(Number(s))&&Number(t)<pt?pt:Number(t),maxFeePerGas:(80001===Number(s)||137===Number(s))&&Number(e)<ft?ft:Number(s)===wt&&Number(e)<gt?gt:ut.includes(Number(s))&&Number(e)<pt?pt:Number(e)}}else o={gasPrice:a.gasPrice};o.gasLimit=BigInt(new p(t).plus(20000n).toString());try{const t=await n(...i,o);return await t.wait(),t}catch(t){return at.error("Send tx error: ",t),null}}class Tt{constructor(t,e,r,n){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=r||(new dt).getConfig(e),this.abi=n||this.getDefaultAbi()}getSignerAccordingSdk(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?g.wrap(this.signer):this.signer}async amountToUnits(t,e,r){return Et(this.signer,t,e,r)}async unitsToAmount(t,e,r){return vt(this.signer,t,e,r)}async getFairGasPrice(){var t;return yt(this.signer,null==(t=this.config)?void 0:t.gasFeeMultiplier)}getContract(t,e){if(!t)throw new Error("Contract address is required but not provided");return mt(new r.Contract(t,new r.Interface(JSON.stringify(e||this.abi)),this.signer))}}class xt extends Tt{constructor(t,e,r,n,i){super(e,r,n,i),this.address=void 0,this.contract=void 0,this.address=t,this.contract=this.getContract(this.address)}}class Ct extends xt{getDefaultAbi(){return m.abi}async status(t){const e=await this.contract.status(t);if(!e)throw new Error("Np dispenser found for the given datatoken address");return{active:e.active,owner:e.owner,isMinter:e.isMinter,maxTokens:await this.unitsToAmount(null,e.maxTokens,18),maxBalance:await this.unitsToAmount(null,e.maxBalance,18),balance:await this.unitsToAmount(null,e.balance,18),allowedSwapper:e.allowedSwapper}}async create(t,e,r,n,i,s){var a;const o=await this.contract.create.estimateGas(t,this.amountToUnits(null,r,18),this.amountToUnits(null,n,18),e,i);return s?o:await At(o,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.create,t,this.amountToUnits(null,r,18),this.amountToUnits(null,n,18),e,i)}async activate(t,e,r,n){var i;const s=await this.contract.activate.estimateGas(t,this.amountToUnits(null,e,18),this.amountToUnits(null,r,18));return n?s:await At(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.activate,t,this.amountToUnits(null,e,18),this.amountToUnits(null,r,18))}async deactivate(t,e){var r;const n=await this.contract.deactivate.estimateGas(t);return e?n:await At(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.deactivate,t)}async setAllowedSwapper(t,e,r){var n;const i=await this.contract.setAllowedSwapper.estimateGas(t,e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async dispense(t,e="1",r,n){var i;const s=await this.contract.dispense.estimateGas(t,this.amountToUnits(null,e,18),r);return n?s:await At(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.dispense,t,this.amountToUnits(null,e,18),r)}async ownerWithdraw(t,e){var r;const n=await this.contract.ownerWithdraw.estimateGas(t);return e?n:await At(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.ownerWithdraw,t)}async isDispensable(t,e,r,n="1"){const i=await this.status(t);return!(!i||!1===i.active||new w(await e.balance(t,r)).greaterThanOrEqualTo(i.maxBalance)||new w(String(n)).greaterThan(i.maxTokens)||!new w(i.balance).greaterThanOrEqualTo(n)&&!0!==i.isMinter)}}const kt="0x0000000000000000000000000000000000000000",Ft=1e6,Dt="115792089237316195423570985008687907853269984665640564039457584007913129639934",Ot="Returned error: Method eth_feeHistory not supported.";class Pt extends xt{getDefaultAbi(){return y.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,r,n=kt,i="0",s){var a;const o=await this.getExchange(t),c=await this.amountToUnits(null,i,18),u=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),l=await this.amountToUnits(o.baseToken,r,Number(o.btDecimals)),d=await this.contract.buyDT.estimateGas(t,u,l,n,c);return s?d:await At(d,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.buyDT,t,u,l,n,c)}async sellDatatokens(t,e,r,n=kt,i="0",s){var a;const o=await this.getExchange(t),c=await this.amountToUnits(null,i,18),u=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),l=await this.amountToUnits(o.baseToken,r,Number(o.btDecimals)),d=await this.contract.sellDT.estimateGas(t,u,l,n,c);return s?d:await At(d,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.sellDT,t,u,l,n,c)}async getNumberOfExchanges(){const t=await this.contract.getNumberOfExchanges();return Number(t)}async setRate(t,e,r){var n;const i=await this.contract.setRate.estimateGas(t,await this.amountToUnits(null,e,18));return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setRate,t,await this.amountToUnits(null,e,18))}async setAllowedSwapper(t,e,r){var n;const i=await this.contract.setAllowedSwapper.estimateGas(t,e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async activate(t,e){var r;const n=await this.getExchange(t);if(!n)return null;if(!0===n.active)return null;const i=await this.contract.toggleExchangeState.estimateGas(t);return e?i:await At(i,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async deactivate(t,e){var r;const n=await this.getExchange(t);if(!n)return null;if(!1===n.active)return null;const i=await this.contract.toggleExchangeState.estimateGas(t);return e?i:await At(i,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async getRate(t){const e=await this.contract.getRate(t);return await this.unitsToAmount(null,e,18)}async getDatatokenSupply(t){const e=await this.contract.getDTSupply(t),r=await this.getExchange(t);return await this.unitsToAmount(r.datatoken,e,Number(r.dtDecimals))}async getBasetokenSupply(t){const e=await this.contract.getBTSupply(t),r=await this.getExchange(t);return await this.unitsToAmount(r.baseToken,e,Number(r.btDecimals))}async getAllowedSwapper(t){return await this.contract.getAllowedSwapper(t)}async calcBaseInGivenDatatokensOut(t,e,r="0"){const n=await this.getExchange(t),i=await this.contract.calcBaseInGivenOutDT(t,await this.amountToUnits(n.datatoken,e,Number(n.dtDecimals)),await this.amountToUnits(null,r,18));return{baseTokenAmount:await this.unitsToAmount(n.baseToken,i.baseTokenAmount,Number(n.btDecimals)),marketFeeAmount:await this.unitsToAmount(n.baseToken,i.publishMarketFeeAmount,Number(n.btDecimals)),oceanFeeAmount:await this.unitsToAmount(n.baseToken,i.oceanFeeAmount,Number(n.btDecimals)),consumeMarketFeeAmount:await this.unitsToAmount(n.baseToken,i.consumeMarketFeeAmount,Number(n.btDecimals))}}async getAmountBasetokensOut(t,e,r="0"){const n=await this.getExchange(t),i=await this.contract.calcBaseOutGivenInDT(t,await this.amountToUnits(n.datatoken,e,Number(n.dtDecimals)),await this.amountToUnits(null,r,18));return await this.unitsToAmount(n.baseToken,i[0],Number(n.btDecimals))}async getExchange(t){const e=await this.contract.getExchange(t);return{active:e.active,datatoken:e.datatoken,baseToken:e.baseToken,withMint:e.withMint,exchangeOwner:e.exchangeOwner,allowedSwapper:e.allowedSwapper,dtDecimals:e.dtDecimals.toString(),btDecimals:e.btDecimals.toString(),dtBalance:await this.unitsToAmount(e.datatoken,e.dtBalance,Number(e.dtDecimals)),btBalance:await this.unitsToAmount(e.baseToken,e.btBalance,Number(e.btDecimals)),dtSupply:await this.unitsToAmount(e.datatoken,e.dtSupply,Number(e.dtDecimals)),btSupply:await this.unitsToAmount(e.baseToken,e.btSupply,Number(e.btDecimals)),fixedRate:await this.unitsToAmount(null,e.fixedRate,18),exchangeId:t}}async getFeesInfo(t){const e=await this.contract.getFeesInfo(t),r=await this.getExchange(t);return{opcFee:await this.unitsToAmount(null,e.opcFee.toString(),18),marketFee:await this.unitsToAmount(null,e.marketFee.toString(),18),marketFeeCollector:e.marketFeeCollector,marketFeeAvailable:await this.unitsToAmount(r.baseToken,e.marketFeeAvailable,Number(r.btDecimals)),oceanFeeAvailable:await this.unitsToAmount(r.baseToken,e.oceanFeeAvailable,Number(r.btDecimals)),exchangeId:t}}async getExchanges(){return await this.contract.getExchanges()}async isActive(t){return await this.contract.isActive(t)}async activateMint(t,e){var r;const n=await this.getExchange(t);if(!n)return null;if(!0===n.withMint)return null;const i=await this.contract.toggleMintState.estimateGas(t,!0);return e?i:await At(i,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.toggleMintState,t,!0)}async deactivateMint(t,e){var r;const n=await this.getExchange(t);if(!n)return null;if(!1===n.withMint)return null;const i=await this.contract.toggleMintState.estimateGas(t,!1);return e?i:await At(i,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.toggleMintState,t,!1)}async collectBasetokens(t,e,r){var n;if(!await this.getExchange(t))return null;const i=await this.contract.getExchange(t),s=await this.amountToUnits(i.baseToken,e,Number(i.btDecimals)),a=await this.contract.collectBT.estimateGas(t,s);return r?a:await At(a,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.collectBT,t,s)}async collectDatatokens(t,e,r){var n;if(!await this.getExchange(t))return null;const i=await this.contract.getExchange(t),s=await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),a=await this.contract.collectDT.estimateGas(t,s);return r?a:await At(a,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.collectDT,t,s)}async collectMarketFee(t,e){var r;if(!await this.getExchange(t))return null;const n=await this.contract.collectMarketFee.estimateGas(t);return e?n:await At(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.collectMarketFee,t)}async collectOceanFee(t,e){var r;if(!await this.getExchange(t))return null;const n=await this.contract.collectOceanFee.estimateGas(t);return e?n:await At(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.collectOceanFee,t)}async getOPCCollector(){return await this.contract.opcCollector()}async getRouter(){return await this.contract.router()}async getExchangeOwner(t){return(await this.getExchange(t)).exchangeOwner}async updateMarketFee(t,e,r){var n;const i=await this.contract.updateMarketFee.estimateGas(t,await this.amountToUnits(null,e,18));return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.updateMarketFee,t,await this.amountToUnits(null,e,18))}async updateMarketFeeCollector(t,e,r){var n;const i=await this.contract.updateMarketFeeCollector.estimateGas(t,e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class It extends xt{getDefaultAbi(){return b.abi}async buyDatatokenBatch(t,e){var r;const n=await this.contract.buyDTBatch.estimateGas(t);return e?n:await At(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.buyDTBatch,t)}async isApprovedToken(t){return await this.contract.isApprovedToken(t)}async isFixedPrice(t){return await this.contract.isFixedRateContract(t)}async getOwner(){return await this.contract.routerOwner()}async getNFTFactory(){return await this.contract.factory()}async addApprovedToken(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.addApprovedToken.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.addApprovedToken,e)}async removeApprovedToken(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.removeApprovedToken.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.removeApprovedToken,e)}async addFixedRateContract(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.addFixedRateContract.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.addFixedRateContract,e)}async removeFixedRateContract(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.removeFixedRateContract.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.removeFixedRateContract,e)}async addDispenserContract(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.addDispenserContract.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.addDispenserContract,e)}async removeDispenserContract(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const i=await this.contract.removeDispenserContract.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.removeDispenserContract,e)}async getOPCFee(t){const e=await this.contract.getOPCFee(t);return Number(e)}async getCurrentOPCFee(){const t=await this.contract.swapOceanFee();return Number(t)}async updateOPCFee(t,e,r,n,i,s){var a;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const o=await this.contract.updateOPCFee.estimateGas(e,r,n,i);return s?o:await At(o,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.updateOPCFee,e,r,n,i)}}var Nt={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 Lt(t){const e=t||Nt,r=Math.floor(Math.random()*e.adjectives.length),n=Math.floor(Math.random()*e.nouns.length),i=Math.floor(100*Math.random()),s=e.adjectives[r].replace(/^\w/,t=>t.toUpperCase()),a=e.nouns[n].replace(/^\w/,t=>t.toUpperCase());return{name:`${s} ${a} Token`,symbol:`${(s.substring(0,3)+a.substring(0,3)).toUpperCase()}-${i}`}}class Ut extends xt{getDefaultAbi(){return A.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:r}=Lt();t.name=e,t.symbol=r}if(t.templateIndex>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t.templateIndex)throw new Error("Template index cannot be ZERO");if(!1===(await this.getNFTTemplate(t.templateIndex)).isActive)throw new Error("Template is not active");const r=await this.contract.deployERC721Contract.estimateGas(t.name,t.symbol,t.templateIndex,kt,kt,t.tokenURI,t.transferable,t.owner);if(e)return r;try{var n;const e=await At(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,kt,kt,t.tokenURI,t.transferable,t.owner);if(!e){const t="Tx for deploying new NFT contract does not exist or status is not successful.";throw console.error(t),t}return St(await e.wait(),"NFTCreated").args[0]}catch(t){console.error(`Creation of NFT failed: ${t}`)}}async getCurrentNFTCount(){const t=await this.contract.getCurrentNFTCount();return Number(t)}async getCurrentTokenCount(){const t=await this.contract.getCurrentTokenCount();return Number(t)}async getOwner(){return await this.contract.owner()}async getCurrentNFTTemplateCount(){const t=await this.contract.getCurrentNFTTemplateCount();return Number(t)}async getCurrentTokenTemplateCount(){const t=await this.contract.getCurrentTemplateCount();return Number(t)}async getNFTTemplate(t){if(t>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return await this.contract.getNFTTemplate(t)}async getTokenTemplate(t){return await this.contract.getTokenTemplate(t)}async checkDatatoken(t){return await this.contract.erc20List(t)}async checkNFT(t){return await this.contract.erc721List(t)}async addNFTTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===kt)throw new Error("Template cannot be ZERO address");const i=await this.contract.add721TokenTemplate.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.add721TokenTemplate,e)}async disableNFTTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const i=await this.contract.disable721TokenTemplate.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.disable721TokenTemplate,e)}async reactivateNFTTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const i=await this.contract.reactivate721TokenTemplate.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.reactivate721TokenTemplate,e)}async addTokenTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===kt)throw new Error("Template cannot be address ZERO");const i=await this.contract.addTokenTemplate.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.addTokenTemplate,e)}async disableTokenTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!1===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already disabled");const i=await this.contract.disableTokenTemplate.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.disableTokenTemplate,e)}async reactivateTokenTemplate(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!0===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already active");const i=await this.contract.reactivateTokenTemplate.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.reactivateTokenTemplate,e)}async startMultipleTokenOrder(t,e){var r;if(t.length>50)throw new Error("Too many orders");const n=await this.contract.startMultipleTokenOrder.estimateGas(t);return e?n:await At(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.startMultipleTokenOrder,t)}async createNftWithDatatoken(t,e,r){var n;const i=await this.getErcCreationParams(e),s=await this.contract.createNftWithErc20.estimateGas(t,i);return r?s:await At(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.createNftWithErc20,t,i)}async createNftWithDatatokenWithFixedRate(t,e,r,n){var i;const s=await this.getErcCreationParams(e),a=await this.getFreCreationParams(r),o=await this.contract.createNftWithErc20WithFixedRate.estimateGas(t,s,a);return n?o:await At(o,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.createNftWithErc20WithFixedRate,t,s,a)}async createNftWithDatatokenWithDispenser(t,e,r,n){var i;const s=await this.getErcCreationParams(e);r.maxBalance=await this.amountToUnits(null,r.maxBalance,18),r.maxTokens=await this.amountToUnits(null,r.maxTokens,18);const a=await this.contract.createNftWithErc20WithDispenser.estimateGas(t,s,r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.createNftWithErc20WithDispenser,t,s,r)}async getErcCreationParams(t){let e,r;t.name&&t.symbol||({name:e,symbol:r}=Lt());let n=18;if(t.feeToken!==kt)try{n=await bt(this.signer,t.feeToken)}catch(t){at.error("getTokenDecimals error",t)}const i=[t.minter,t.paymentCollector,t.mpFeeAddress,t.feeToken];return t.filesObject&&(t.accessListFactory&&i.push(t.accessListFactory),t.allowAccessList&&i.push(t.allowAccessList),t.denyAccessList&&i.push(t.denyAccessList)),{templateIndex:t.templateIndex,strings:[t.name||e,t.symbol||r],addresses:i,uints:[await this.amountToUnits(null,t.cap,18),await this.amountToUnits(null,t.feeAmount,n)],bytess:t.filesObject?[a(JSON.stringify(t.filesObject))]:[]}}async getFreCreationParams(t){t.allowedConsumer||(t.allowedConsumer=kt);const e=!1===t.withMint?0:1;return{fixedPriceAddress:t.fixedRateAddress,addresses:[t.baseTokenAddress,t.owner,t.marketFeeCollector,t.allowedConsumer],uints:[t.baseTokenDecimals,t.datatokenDecimals,await this.amountToUnits(null,t.fixedRate,t.datatokenDecimals),await this.amountToUnits(null,t.marketFee,t.datatokenDecimals),e]}}}function Rt(){try{if(process.env.ADDRESS_FILE){const t=e.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(t)}return t}catch(e){return t}}function Mt(t){try{const e=Rt();if(e){const r=Object.keys(e);for(const n of r)if(e[n].chainId===t)return e[n]}}catch(t){console.error(t)}return null}async function Bt(t,e,n,i){const s="number"==typeof n,a=new Ut(e,t,i),o=await a.getCurrentTokenTemplateCount();for(let e=1;e<=o;e++){const i=await a.getTokenTemplate(e),o=new r.Contract(i.templateAddress,T.abi,t);if(s){const t=await o.getId();if(i.isActive&&t.toString()===n.toString())return e}else if(i.isActive&&i.templateAddress===n.toString())return e}return-1}class _t extends Tt{getDefaultAbi(){return S.abi}async createDatatoken(t,e,r,n,i,s,o,c,u,l,d,h,f,g,p,w){var m;if(!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not DatatokenDeployer");d||(d=1),u&&l||({name:u,symbol:l}=Lt());const y=this.getContract(t);if(!this.signer.provider)throw new Error("Provider is required but not available");const{chainId:b}=await this.signer.provider.getNetwork(),v=Mt(Number(b));h&&(d=await Bt(this.signer,v.ERC721Factory,4,Number(b)));const E=await y.createERC20.estimateGas(d,[u,l],[r,n,i,s],[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],[]);if(w)return E;const S=[r,n,i,s];f&&(S.push(f.toLowerCase()),S.push(g?g.toLowerCase():kt),S.push(p||kt));const A=await At(E,this.getSignerAccordingSdk(),null==(m=this.config)?void 0:m.gasFeeMultiplier,y.createERC20,d,[u,l],S,[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],h?[a(h)]:[]),T=St(await A.wait(),"TokenCreated");return null==T?void 0:T.args[0]}async addManager(t,e,r,n){var i;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const a=await s.addManager.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addManager,r)}async removeManager(t,e,r,n){var i;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const a=await s.removeManager.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeManager,r)}async addDatatokenDeployer(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const a=await s.addToCreateERC20List.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addToCreateERC20List,r)}async removeDatatokenDeployer(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e===r&&!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not Manager nor DatatokenDeployer");const a=await s.removeFromCreateERC20List.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeFromCreateERC20List,r)}async addMetadataUpdater(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const a=await s.addToMetadataList.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addToMetadataList,r)}async removeMetadataUpdater(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==r&&!0!==(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Manager nor Metadata Updater");const a=await s.removeFromMetadataList.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeFromMetadataList,r)}async addStoreUpdater(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const a=await s.addTo725StoreList.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addTo725StoreList,r)}async removeStoreUpdater(t,e,r,n){var i;const s=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==r&&!0!==(await this.getNftPermissions(t,e)).store)throw new Error("Caller is not Manager nor storeUpdater");const a=await s.removeFrom725StoreList.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeFrom725StoreList,r)}async cleanPermissions(t,e,r){var n;const i=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await i.cleanPermissions.estimateGas();return r?s:await At(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,i.cleanPermissions)}async transferNft(t,e,r,n,i){var s;const a=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=n||1,c=await a.transferFrom.estimateGas(e,r,o);return i?c:await At(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,a.transferFrom,e,r,o)}async safeTransferNft(t,e,r,n,i){var s;const a=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=n||1,c=await a.safeTransferFrom.estimateGas(e,r,o);return i?c:await At(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,a.safeTransferFrom,e,r,o)}async setMetadata(t,e,r,n,i,s,a,o,c,u){var l;const d=this.getContract(t);if(c||(c=[]),!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");let h=n;if(null!=n&&n.includes("/p2p/")){var f;const t=n.match(/\/p2p\/([^/]+)/);h=null!=(f=null==t?void 0:t[1])?f:n}const g=await d.setMetaData.estimateGas(r,h,i,s,a,o,c);return u?g:await At(g,this.signer,null==(l=this.config)?void 0:l.gasFeeMultiplier,d.setMetaData,r,h,i,s,a,o,c)}async setMetadataAndTokenURI(t,e,r,n){var i;const s=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const a=et({},r,{metadataProofs:r.metadataProofs||[]}),o=await s.setMetaDataAndTokenURI.estimateGas(a);return n?o:await At(o,this.signer,null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setMetaDataAndTokenURI,a)}async setMetadataState(t,e,r,n){var i;const s=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const a=await s.setMetaDataState.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setMetaDataState,r)}async setTokenURI(t,e,r){var n;const i=this.getContract(t),s=await i.setTokenURI.estimateGas("1",e);return r?s:await At(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,i.setTokenURI,"1",e)}async getNftOwner(t){const e=this.getContract(t);return await e.ownerOf(1)}async getNftPermissions(t,e){const r=this.getContract(t);return await r.getPermissions(e)}async getMetadata(t){const e=this.getContract(t);return await e.getMetaData()}async isDatatokenDeployer(t,e){const r=this.getContract(t);return await r.isERC20Deployer(e)}async setData(t,e,r,n,i){var s;if(!0!==(await this.getNftPermissions(t,e)).store)throw new Error("User is not ERC20 store updater");const u=this.getContract(t),l=o(r),d=c(a(n)),h=await u.setNewData.estimateGas(l,d);return i?h:await At(h,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,u.setNewData,l,d)}async getData(t,e){const r=this.getContract(t),n=o(e),i=await r.getData(n);return i?u(i):null}async getTokenURI(t,e){const r=this.getContract(t);return await r.tokenURI(e)}async isDatatokenDeployed(t,e){const r=this.getContract(t);return await r.isDeployed(e)}}class $t extends Tt{getDefaultAbi(){return v.abi}constructor(t,e,r,n,i){super(t,e,r,n),this.abiEnterprise=void 0,this.nft=void 0,this.abiEnterprise=i||E.abi,this.nft=new _t(this.signer,e)}async approve(t,e,r,n){var i;const s=this.getContract(t),a=await s.approve.estimateGas(e,Et(null,null,r,18));return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.approve,e,Et(null,null,r,18))}async createFixedRate(t,e,r,n){var i;const s=this.getContract(t);if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");r.allowedConsumer||(r.allowedConsumer=kt);const a=!1===r.withMint?0:1,o=await s.createFixedRate.estimateGas(r.fixedRateAddress,[r.baseTokenAddress,r.owner,r.marketFeeCollector,r.allowedConsumer],[r.baseTokenDecimals,r.datatokenDecimals,r.fixedRate,r.marketFee,a]);return n?o:await At(o,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.createFixedRate,r.fixedRateAddress,[r.baseTokenAddress,r.owner,r.marketFeeCollector,r.allowedConsumer],[r.baseTokenDecimals,r.datatokenDecimals,r.fixedRate,r.marketFee,a])}async createDispenser(t,e,r,n,i){var s;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const a=this.getContract(t);n.allowedSwapper||(n.allowedSwapper=kt),n.withMint=!1!==n.withMint;const o=await a.createDispenser.estimateGas(r,n.maxTokens,n.maxBalance,n.withMint,n.allowedSwapper);return i?o:await At(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,a.createDispenser,r,n.maxTokens,n.maxBalance,n.withMint,n.allowedSwapper)}async mint(t,e,r,n,i){const s=this.getContract(t);if(!0!==(await this.getPermissions(t,e)).minter)throw new Error("Caller is not Minter");const a=await this.getCap(t);if(new w(a).gte(r)){var o;const t=await s.mint.estimateGas(n||e,Et(null,null,r,18));return i?t:await At(t,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,s.mint,n||e,Et(null,null,r,18))}throw new Error("Mint amount exceeds cap available")}async addMinter(t,e,r,n){var i;const s=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const a=await s.addMinter.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addMinter,r)}async removeMinter(t,e,r,n){var i;const s=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const a=await s.removeMinter.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removeMinter,r)}async addPaymentManager(t,e,r,n){var i;const s=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const a=await s.addPaymentManager.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.addPaymentManager,r)}async removePaymentManager(t,e,r,n){var i;const s=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const a=await s.removePaymentManager.estimateGas(r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.removePaymentManager,r)}async setPaymentCollector(t,e,r,n){var i;const s=this.getContract(t),a=(await this.getPermissions(t,e)).paymentManager,o=!a&&await this.getNFTAddress(t),c=o&&await this.nft.getNftOwner(o)===e,u=o&&!c&&await this.nft.getNftPermissions(o,e);if(!a&&!c&&!(null==u?void 0:u.deployERC20))throw new Error("Caller is not Fee Manager, owner or Datatoken Deployer");const l=await s.setPaymentCollector.estimateGas(r);return n?l:await At(l,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setPaymentCollector,r)}async getPaymentCollector(t){const e=this.getContract(t);return await e.getPaymentCollector()}async transfer(t,e,r,n){return this.transferWei(t,e,await Et(null,null,r,18),n)}async transferWei(t,e,r,n){var i;const s=this.getContract(t),a=await s.transfer.estimateGas(e,r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.transfer,e,r)}async startOrder(t,e,r,n,i,s){var a;const o=this.getContract(t,this.abi);i||(i={consumeMarketFeeAddress:kt,consumeMarketFeeToken:kt,consumeMarketFeeAmount:"0"});const c=await o.startOrder.estimateGas(e,r,n,i);return s?c:await At(c,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,o.startOrder,e,r,n,i)}async reuseOrder(t,e,r,n){var i;const s=this.getContract(t),a=await s.reuseOrder.estimateGas(e,r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.reuseOrder,e,r)}async buyFromFreAndOrder(t,e,r,n){var i;const s=this.getContract(t,this.abiEnterprise),a=await this.getFreOrderParams(r),o=await s.buyFromFreAndOrder.estimateGas(e,a);return n?o:await At(o,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.buyFromFreAndOrder,e,a)}async buyFromDispenserAndOrder(t,e,r,n){var i;const s=this.getContract(t,this.abiEnterprise),a=await s.buyFromDispenserAndOrder.estimateGas(e,r);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.buyFromDispenserAndOrder,e,r)}async setData(t,e,r,n){var i;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t),o=c(a(r)),u=await s.setData.estimateGas(o);return n?u:await At(u,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setData,o)}async cleanPermissions(t,e,r){var n;if(await this.nft.getNftOwner(await this.getNFTAddress(t))!==e)throw new Error("Caller is NOT Nft Owner");const i=this.getContract(t),s=await i.cleanPermissions.estimateGas();return r?s:await At(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,i.cleanPermissions)}async getPermissions(t,e){const r=this.getContract(t);return await r.permissions(e)}async getCap(t){const e=this.getContract(t),r=await e.cap();return await this.unitsToAmount(null,r,18)}async getDecimals(t){const e=this.getContract(t),r=await e.decimals();return Number(r)}async getId(t){const e=this.getContract(t),r=await e.getId();return Number(r)}async getSymbol(t){const e=this.getContract(t);return await e.symbol()}async getName(t){const e=this.getContract(t);return await e.name()}async getNFTAddress(t){const e=this.getContract(t);return await e.getERC721Address()}async getFixedRates(t){const e=this.getContract(t);return await e.getFixedRates()}async getDispensers(t){const e=this.getContract(t);return await e.getDispensers()}async isDatatokenDeployer(t,e){const r=this.getContract(t);return await r.isERC20Deployer(e)}async balance(t,e){const r=this.getContract(t),n=await r.balanceOf(e);return await this.unitsToAmount(null,n,18)}async allowance(t,e,r,n=18){const i=this.getContract(t),s=await i.allowance(e,r);return await this.unitsToAmount(null,s,n)}async setPublishingMarketFee(t,e,r,n,i,s){var a;const o=this.getContract(t);if((await o.getPublishingMarketFee())[0]!==i)throw new Error("Caller is not the Publishing Market Fee Address");const c=await o.setPublishingMarketFee.estimateGas(e,r,n);return s?c:await At(c,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,o.setPublishingMarketFee,e,r,n)}async getPublishingMarketFee(t){const e=this.getContract(t),r=await e.getPublishingMarketFee();return{publishMarketFeeAddress:r[0],publishMarketFeeToken:r[1],publishMarketFeeAmount:r[2].toString()}}async getFreOrderParams(t){return{exchangeContract:t.exchangeContract,exchangeId:t.exchangeId,maxBaseTokenAmount:await Et(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await Et(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class Gt extends $t{getDefaultAbi(){return x.abi}constructor(t,e,r,n,i){super(t,r,n,i),this.accessList=void 0,this.fileObject=void 0,this.abi=this.getDefaultAbi(),this.fileObject=e}setFileObj(t){this.fileObject=t}async getAllowlistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getAllowListContract()}async getDenylistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getDenyListContract()}async setAllowListContract(t,e,r,n){var i;if(!await this.isDatatokenDeployer(t,r))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t),a=await s.setAllowListContract.estimateGas(e);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setAllowListContract,e)}async setDenyListContract(t,e,r,n){var i;if(!await this.isDatatokenDeployer(t,r))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t),a=await s.setDenyListContract.estimateGas(e);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.setDenyListContract,e)}async setFileObject(t,e,r){var n;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const i=this.getContract(t),s=await i.setFilesObject.estimateGas(this.fileObject);return r?s:await At(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,i.setFilesObject,this.fileObject)}async getFileObject(t,e,r,n,i,s,a){const o=this.getContract(t,this.getDefaultAbi());return await o.getFileObject(e,r,n,i,s,a)}}class jt extends xt{getDefaultAbi(){return C.abi}constructor(t,e,r,n,i){super(t,e,r,n,i),this.abiEnterprise=void 0,this.abi=i||this.getDefaultAbi()}async getTokenUri(t){return await this.contract.tokenURI(t)}async getOwner(){return await this.contract.owner()}async getId(){const t=await this.contract.getId();return Number(t)}async getName(){return await this.contract.name()}async getSymbol(){return await this.contract.symbol()}async balance(t){const e=await this.contract.balanceOf(t);return await this.unitsToAmount(null,e,18)}async mint(t,e,r){var n;const i=await this.contract.mint.estimateGas(t,e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.mint,t,e)}async batchMint(t,e,r){var n;const i=await this.contract.batchMint.estimateGas(t,e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.batchMint,t,e)}async burn(t,e){var r;const n=await this.contract.burn.estimateGas(t);return e?n:await At(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.burn,t)}async transferOwnership(t,e){var r;const n=await this.contract.transferOwnership.estimateGas(t);return e?n:await At(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.transferOwnership,t)}async renounceOwnership(t){var e;const r=await this.contract.renounceOwnership.estimateGas();return t?r:await At(r,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class qt extends xt{getDefaultAbi(){return k.abi}constructor(t,e,r,n,i){super(t,e,r,n,i),this.abi=i||this.getDefaultAbi()}async deployAccessListContract(t,e,r,n=!1,i,s,a){if(!t||!e){const{name:r,symbol:n}=Lt();t=r,e=n}const o=await this.contract.deployAccessListContract.estimateGas(t,e,n,i,s,r);if(a)return o;try{var c;const a=await At(o,this.getSignerAccordingSdk(),null==(c=this.config)?void 0:c.gasFeeMultiplier,this.contract.deployAccessListContract,t,e,n,i,s,r);if(!a){const t="Tx for deploying new access list was not processed on chain.";throw console.error(t),t}return St(await a.wait(),"NewAccessList").args[0]}catch(t){console.error(`Creation of AccessList failed: ${t}`)}}async getOwner(){return await this.contract.owner()}async isSoulbound(t){return await this.contract.isSoulBound(t)}async isDeployed(t){return await this.contract.isDeployed(t)}async changeTemplateAddress(t,e,r){var n;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===kt)throw new Error("Template address cannot be ZERO address");const i=await this.contract.changeTemplateAddress.estimateGas(e);return r?i:await At(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.changeTemplateAddress,e)}}class Vt extends xt{getDefaultAbi(){return F.abi}constructor(t,e,r,n,i){super(t,e,r,n,i),this.abiEnterprise=void 0,this.abi=i||this.getDefaultAbi()}async getFunds(t){return await this.contract.getFunds(t)}async getUserFunds(t,e){return await this.contract.getUserFunds(t,e)}async getUserTokens(t){return await this.contract.getUserTokens(t)}async getLocks(t,e,r){return await this.contract.getLocks(t,e,r)}async getAuthorizations(t,e,r){return await this.contract.getAuthorizations(t,e,r)}async verifyFundsForEscrowPayment(t,e,r,n,i,s,a){var o;const c=await(null==(o=this.signer.provider)?void 0:o.getBalance(l(e)));if(new p(c).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};const u=new $t(this.signer),h=await u.allowance(t,await this.signer.getAddress(),this.contract.target.toString(),a);new p(await this.amountToUnits(t,h,18)).isLessThan(new p(n))&&await u.approve(l(t),l(this.contract.target.toString()),n);const f=await u.balance(t,await this.signer.getAddress());if(new p(f).isZero())return{isValid:!1,message:"Payment token balance is 0. Please add funds"};const g=await this.getAuthorizations(t,await this.signer.getAddress(),e),w=await this.getUserFunds(await this.signer.getAddress(),t);return new p(w[0]).isZero()&&(r&&new p(d(f)).isLessThanOrEqualTo(new p(d(r)))&&new p(d(r)).isGreaterThan(new p(n))?await this.deposit(t,r,a):new p(d(f)).isLessThanOrEqualTo(new p(d(n)))?await this.deposit(t,await this.unitsToAmount(t,n,a),a):await this.deposit(t,f,a)),0===g.length&&await this.authorize(l(t),l(e),(Number(n)/2).toString(),i,s),{isValid:!0,message:""}}async deposit(t,e,r,n){var i;const s=await this.amountToUnits(t,e,r),a=await this.contract.deposit.estimateGas(t,s);return n?a:await At(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deposit,t,s)}async withdraw(t,e,r,n){var i;const s=[],a=[];if(t.length!==e.length)throw new Error("Tokens and amounts arrays must have the same length");const o=await this.signer.getAddress();for(let r=0;r<t.length;r++){const n=t[r],i=new p(e[r]),c=await this.getUserFunds(o,n),u=new p(c[0]);i.isGreaterThan(0)&&i.isLessThanOrEqualTo(u)?(s.push(n),a.push(e[r])):console.log(`Insufficient funds for token ${n}`)}const c=await Promise.all(a.map((t,e)=>this.amountToUnits(s[e],t,r))),u=await this.contract.withdraw.estimateGas(t,c);return n?u:await At(u,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.withdraw,s,c)}async authorize(t,e,r,n,i,s,a){var o;if(0!==(await this.getAuthorizations(t,await this.signer.getAddress(),e)).length)return console.log(`Payee ${e} already authorized`),null;const c=await this.amountToUnits(t,r,s),u=await this.amountToUnits(t,n,s),l=await this.amountToUnits(t,i,s),d=await this.contract.authorize.estimateGas(t,e,c,u,l);return a?d:await At(d,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,this.contract.authorize,t,e,c,u,l)}async cancelExpiredLocks(t,e,r,n,i){var s;const a=await this.contract.cancelExpiredLocks.estimateGas(t,e,r,n);return i?a:await At(a,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,r,n)}}class zt extends xt{getDefaultAbi(){return D.abi}constructor(t,e,r,n,i){super(t,e,r,n,i),this.abi=i||this.getDefaultAbi()}async isTokenAllowed(t){return await this.contract.isTokenAllowed(t)}async getToken(t){return await this.contract.getToken(t)}async calculateFee(t,e,r){const n=this.amountToUnits(t,e.toString(),r),i=await this.contract.calculateFee(t,n);return this.unitsToAmount(t,i,r)}}async function Ht(t){return new Promise(e=>{setTimeout(e,t)})}function Kt(t){return null!=t}async function Zt(t,e){const r=h(e);let n=await t._legacySignMessage(r);n=n.substr(2);const i="0x"+n.slice(0,64),s="0x"+n.slice(64,128);let a="0x"+n.slice(128,130);return"0x00"===a&&(a="0x1b"),"0x01"===a&&(a="0x1c"),{v:a,r:i,s}}async function Jt(t,e){const n=r.solidityPackedKeccak256(["bytes"],[r.hexlify(r.toUtf8Bytes(e))]),i=r.toBeArray(n);try{return await t.signMessage(i)}catch(e){const r=await t.provider.getNetwork(),n=Number(r.chainId);if(8996===Number(n))return console.log("Signing message with _legacySignMessage"),await t._legacySignMessage(i)}}class Wt extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}}class Yt extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}}class Xt extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}}class Qt extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}}class te extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}}class ee extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}}class re extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}}const ne=Symbol.for("@libp2p/peer-id"),ie=Symbol.for("@libp2p/service-capabilities");function se(t){if(t instanceof Uint8Array&&"Uint8Array"===t.constructor.name)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}class ae{name;prefix;baseEncode;constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class oe{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,r){this.name=t,this.prefix=e;const n=e.codePointAt(0);if(void 0===n)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(t){if("string"==typeof t){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(t){return ue(this,t)}}class ce{decoders;constructor(t){this.decoders=t}or(t){return ue(this,t)}decode(t){const e=this.decoders[t[0]];if(null!=e)return e.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function ue(t,e){return new ce({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class le{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new ae(t,e,r),this.decoder=new oe(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}function de({name:t,prefix:e,encode:r,decode:n}){return new le(t,e,r,n)}function he({name:t,prefix:e,alphabet:r}){const{encode:n,decode:i}=function(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),a=s.charCodeAt(0);if(255!==r[a])throw new TypeError(s+" is ambiguous");r[a]=i}var o=t.length,c=t.charAt(0),u=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function d(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return new Uint8Array;var e=0;if(" "!==t[e]){for(var n=0,i=0;t[e]===c;)n++,e++;for(var s=(t.length-e)*u+1>>>0,a=new Uint8Array(s);t[e];){var l=r[t.charCodeAt(e)];if(255===l)return;for(var d=0,h=s-1;(0!==l||d<i)&&-1!==h;h--,d++)a[h]=(l+=o*a[h]>>>0)%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");i=d,e++}if(" "!==t[e]){for(var f=s-i;f!==s&&0===a[f];)f++;for(var g=new Uint8Array(n+(s-f)),p=n;f!==s;)g[p++]=a[f++];return g}}}return{encode:function(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===e.length)return"";for(var r=0,n=0,i=0,s=e.length;i!==s&&0===e[i];)i++,r++;for(var a=(s-i)*l+1>>>0,u=new Uint8Array(a);i!==s;){for(var d=e[i],h=0,f=a-1;(0!==d||h<n)&&-1!==f;f--,h++)u[f]=(d+=256*u[f]>>>0)%o>>>0,d=d/o>>>0;if(0!==d)throw new Error("Non-zero carry");n=h,i++}for(var g=a-n;g!==a&&0===u[g];)g++;for(var p=c.repeat(r);g<a;++g)p+=t.charAt(u[g]);return p},decodeUnsafe:d,decode:function(t){var r=d(t);if(r)return r;throw new Error(`Non-${e} character`)}}}(r,t);return de({prefix:e,name:t,encode:n,decode:t=>se(i(t))})}function fe({name:t,prefix:e,bitsPerChar:r,alphabet:n}){const i=function(t){const e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}(n);return de({prefix:e,name:t,encode:t=>function(t,e,r){const n="="===e[e.length-1],i=(1<<r)-1;let s="",a=0,o=0;for(let n=0;n<t.length;++n)for(o=o<<8|t[n],a+=8;a>r;)a-=r,s+=e[i&o>>a];if(0!==a&&(s+=e[i&o<<r-a]),n)for(;s.length*r&7;)s+="=";return s}(t,n,r),decode:e=>function(t,e,r,n){let i=t.length;for(;"="===t[i-1];)--i;const s=new Uint8Array(i*r/8|0);let a=0,o=0,c=0;for(let u=0;u<i;++u){const i=e[t[u]];if(void 0===i)throw new SyntaxError(`Non-${n} character`);o=o<<r|i,a+=r,a>=8&&(a-=8,s[c++]=255&o>>a)}if(a>=r||255&o<<8-a)throw new SyntaxError("Unexpected end of data");return s}(e,i,r,t)})}const ge=he({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pe=he({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var we={__proto__:null,base58btc:ge,base58flickr:pe};const me=fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ye=fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),be=fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ve=fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ee=fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Se=fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ae=fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Te=fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xe=fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ce={__proto__:null,base32:me,base32upper:ye,base32pad:be,base32padupper:ve,base32hex:Ee,base32hexupper:Se,base32hexpad:Ae,base32hexpadupper:Te,base32z:xe};const ke=he({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Fe=he({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var De={__proto__:null,base36:ke,base36upper:Fe},Oe=Math.pow(2,31),Pe=Math.pow(2,7),Ie=Math.pow(2,14),Ne=Math.pow(2,21),Le=Math.pow(2,28),Ue=Math.pow(2,35),Re=Math.pow(2,42),Me=Math.pow(2,49),Be=Math.pow(2,56),_e=Math.pow(2,63),$e={encode:function t(e,r,n){r=r||[];for(var i=n=n||0;e>=Oe;)r[n++]=255&e|128,e/=128;for(;-128&e;)r[n++]=255&e|128,e>>>=7;return r[n]=0|e,t.bytes=n-i+1,r},decode:function t(e,r){var n,i=0,s=0,a=r=r||0,o=e.length;do{if(a>=o)throw t.bytes=0,new RangeError("Could not decode varint");n=e[a++],i+=s<28?(127&n)<<s:(127&n)*Math.pow(2,s),s+=7}while(n>=128);return t.bytes=a-r,i},encodingLength:function(t){return t<Pe?1:t<Ie?2:t<Ne?3:t<Le?4:t<Ue?5:t<Re?6:t<Me?7:t<Be?8:t<_e?9:10}};function Ge(t,e=0){return[$e.decode(t,e),$e.decode.bytes]}function je(t,e,r=0){return $e.encode(t,e,r),e}function qe(t){return $e.encodingLength(t)}function Ve(t,e){const r=e.byteLength,n=qe(t),i=n+qe(r),s=new Uint8Array(i+r);return je(t,s,0),je(r,s,n),s.set(e,i),new He(t,r,e,s)}function ze(t){const e=se(t),[r,n]=Ge(e),[i,s]=Ge(e.subarray(n)),a=e.subarray(n+s);if(a.byteLength!==i)throw new Error("Incorrect length");return new He(r,i,a,e)}class He{code;size;digest;bytes;constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}}function Ke(t,e){const{bytes:r,version:n}=t;return 0===n?function(t,e,r){const{prefix:n}=r;if(n!==ge.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const i=e.get(n);if(null==i){const i=r.encode(t).slice(1);return e.set(n,i),i}return i}(r,Je(t),e??ge.encoder):function(t,e,r){const{prefix:n}=r,i=e.get(n);if(null==i){const i=r.encode(t);return e.set(n,i),i}return i}(r,Je(t),e??me.encoder)}const Ze=new WeakMap;function Je(t){const e=Ze.get(t);if(null==e){const e=new Map;return Ze.set(t,e),e}return e}class We{code;version;multihash;bytes;"/";constructor(t,e,r,n){this.code=e,this.version=t,this.multihash=r,this.bytes=n,this["/"]=n}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:t,multihash:e}=this;if(t!==Ye)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Xe)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return We.createV0(e)}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:t,digest:e}=this.multihash,r=Ve(t,e);return We.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return We.equals(this,t)}static equals(t,e){return null!=e&&t.code===e.code&&t.version===e.version&&((r=t.multihash)===(n=e.multihash)||r.code===n.code&&r.size===n.size&&n.bytes instanceof Uint8Array&&function(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}(r.bytes,n.bytes));var r,n}toString(t){return Ke(this,t)}toJSON(){return{"/":Ke(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(null==t)return null;const e=t;if(e instanceof We)return e;if(null!=e["/"]&&e["/"]===e.bytes||e.asCID===e){const{version:t,code:r,multihash:n,bytes:i}=e;return new We(t,r,n,i??Qe(t,r,n.bytes))}if(!0===e[tr]){const{version:t,multihash:r,code:n}=e,i=ze(r);return We.create(t,n,i)}return null}static create(t,e,r){if("number"!=typeof e)throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:if(e!==Ye)throw new Error(`Version 0 CID must use dag-pb (code: ${Ye}) block encoding`);return new We(t,e,r,r.bytes);case 1:{const n=Qe(t,e,r.bytes);return new We(t,e,r,n)}default:throw new Error("Invalid version")}}static createV0(t){return We.create(0,Ye,t)}static createV1(t,e){return We.create(1,t,e)}static decode(t){const[e,r]=We.decodeFirst(t);if(0!==r.length)throw new Error("Incorrect length");return e}static decodeFirst(t){const e=We.inspectBytes(t),r=e.size-e.multihashSize,n=se(t.subarray(r,r+e.multihashSize));if(n.byteLength!==e.multihashSize)throw new Error("Incorrect length");const i=n.subarray(e.multihashSize-e.digestSize),s=new He(e.multihashCode,e.digestSize,i,n);return[0===e.version?We.createV0(s):We.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0;const r=()=>{const[r,n]=Ge(t.subarray(e));return e+=n,r};let n=r(),i=Ye;if(18===n?(n=0,e=0):i=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const s=e,a=r(),o=r(),c=e+o;return{version:n,codec:i,multihashCode:a,digestSize:o,multihashSize:c-s,size:c}}static parse(t,e){const[r,n]=function(t,e){switch(t[0]){case"Q":return[ge.prefix,(e??ge).decode(`${ge.prefix}${t}`)];case ge.prefix:return[ge.prefix,(e??ge).decode(t)];case me.prefix:return[me.prefix,(e??me).decode(t)];case ke.prefix:return[ke.prefix,(e??ke).decode(t)];default:if(null==e)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}(t,e),i=We.decode(n);if(0===i.version&&"Q"!==t[0])throw Error("Version 0 CID string must not include multibase prefix");return Je(i).set(r,t),i}}const Ye=112,Xe=18;function Qe(t,e,r){const n=qe(t),i=n+qe(e),s=new Uint8Array(i+r.byteLength);return je(t,s,0),je(e,s,n),s.set(r,i),s}const tr=Symbol.for("@ipld/js-cid/CID"),er=se,rr=function(t,e){if(null!=e?.truncate&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Ve(0,er(t))};function nr(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function ir(t=0){return new Uint8Array(t)}function sr(t=0){return new Uint8Array(t)}function ar(t,e){null==e&&(e=t.reduce((t,e)=>t+e.length,0));const r=sr(e);let n=0;for(const e of t)r.set(e,n),n+=e.length;return r}const or=Symbol.for("@achingbrain/uint8arraylist");function cr(t,e){if(null==e||e<0)throw new RangeError("index is out of bounds");let r=0;for(const n of t){const t=r+n.byteLength;if(e<t)return{buf:n,index:e-r};r=t}throw new RangeError("index is out of bounds")}function ur(t){return Boolean(t?.[or])}class lr{bufs;length;[or]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(const r of t)if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.push(r);else{if(!ur(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");e+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(const r of t.reverse())if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.unshift(r);else{if(!ur(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");e+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=e}get(t){const e=cr(this.bufs,t);return e.buf[e.index]}set(t,e){const r=cr(this.bufs,t);r.buf[r.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(e+r,t[r]);else{if(!ur(t))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<t.length;r++)this.set(e+r,t.get(r))}}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(t>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(t,e){const{bufs:r,length:n}=this._subList(t,e);return ar(r,n)}subarray(t,e){const{bufs:r,length:n}=this._subList(t,e);return 1===r.length?r[0]:ar(r,n)}sublist(t,e){const{bufs:r,length:n}=this._subList(t,e),i=new lr;return i.length=n,i.bufs=[...r],i}_subList(t,e){if((t=t??0)<0&&(t=this.length+t),(e=e??this.length)<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(0===t&&e===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let i=0;i<this.bufs.length;i++){const s=this.bufs[i],a=n,o=a+s.byteLength;if(n=o,t>=o)continue;const c=t>=a&&t<o,u=e>a&&e<=o;if(c&&u){if(t===a&&e===o){r.push(s);break}const n=t-a;r.push(s.subarray(n,n+(e-t)));break}if(c){if(0===t){r.push(s);continue}r.push(s.subarray(t-a))}else{if(u){if(e===o){r.push(s);break}r.push(s.subarray(0,e-a));break}r.push(s)}}return{bufs:r,length:e-t}}indexOf(t,e=0){if(!(ur(t)||t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),0===t.length)return e>this.length?this.length:e;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const i=new Int32Array(256);for(let t=0;t<256;t++)i[t]=-1;for(let t=0;t<n;t++)i[r[t]]=t;const s=i,a=this.byteLength-r.byteLength,o=r.byteLength-1;let c;for(let t=e;t<=a;t+=c){c=0;for(let e=o;e>=0;e--){const n=this.get(t+e);if(r[e]!==n){c=Math.max(1,e-s[n]);break}}if(0===c)return t}return-1}getInt8(t){const e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){const r=sr(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,e),this.write(r,t)}getInt16(t,e){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,e)}setInt16(t,e,r){const n=ir(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,e,r),this.write(n,t)}getInt32(t,e){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,e)}setInt32(t,e,r){const n=ir(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,e,r),this.write(n,t)}getBigInt64(t,e){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,e)}setBigInt64(t,e,r){const n=ir(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,e,r),this.write(n,t)}getUint8(t){const e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){const r=sr(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,e),this.write(r,t)}getUint16(t,e){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,e)}setUint16(t,e,r){const n=ir(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,e,r),this.write(n,t)}getUint32(t,e){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,e)}setUint32(t,e,r){const n=ir(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,e,r),this.write(n,t)}getBigUint64(t,e){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,e)}setBigUint64(t,e,r){const n=ir(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,e,r),this.write(n,t)}getFloat32(t,e){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,e)}setFloat32(t,e,r){const n=ir(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,e,r),this.write(n,t)}getFloat64(t,e){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,e)}setFloat64(t,e,r){const n=ir(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,e,r),this.write(n,t)}equals(t){if(null==t)return!1;if(!(t instanceof lr))return!1;if(t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!nr(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){const r=new lr;return r.bufs=t,null==e&&(e=t.reduce((t,e)=>t+e.byteLength,0)),r.length=e,r}}var dr={__proto__:null,base10:he({prefix:"9",name:"base10",alphabet:"0123456789"})},hr={__proto__:null,base16:fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),base16upper:fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})},fr={__proto__:null,base2:fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})};const gr=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),pr=gr.reduce((t,e,r)=>(t[r]=e,t),[]),wr=gr.reduce((t,e,r)=>{const n=e.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);var mr={__proto__:null,base256emoji:de({prefix:"🚀",name:"base256emoji",encode:function(t){return t.reduce((t,e)=>t+pr[e],"")},decode:function(t){const e=[];for(const r of t){const t=r.codePointAt(0);if(null==t)throw new Error(`Invalid character: ${r}`);const n=wr[t];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}})},yr={__proto__:null,base64:fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),base64pad:fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),base64url:fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),base64urlpad:fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})},br={__proto__:null,base8:fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})},vr={__proto__:null,identity:de({prefix:"\0",name:"identity",encode:t=>{return e=t,(new TextDecoder).decode(e);var e},decode:t=>function(t){return(new TextEncoder).encode(t)}(t)})};function Er({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:i}){return new Sr(t,e,r,n,i)}new TextEncoder,new TextDecoder;class Sr{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,r,n,i){this.name=t,this.code=e,this.encode=r,this.minDigestLength=n??20,this.maxDigestLength=i}digest(t,e){if(null!=e?.truncate){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(null!=this.maxDigestLength&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?Ar(r,this.code,e?.truncate):r.then(t=>Ar(t,this.code,e?.truncate))}throw Error("Unknown type, must be binary type")}}function Ar(t,e,r){if(null!=r&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Ve(e,t)}function Tr(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const xr=Er({name:"sha2-256",code:18,encode:Tr("SHA-256")});Er({name:"sha2-512",code:19,encode:Tr("SHA-512")});const Cr={...vr,...fr,...br,...dr,...hr,...Ce,...De,...we,...yr,...mr};function kr(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Fr=kr("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>(new TextEncoder).encode(t.substring(1))),Dr=kr("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{const e=sr((t=t.substring(1)).length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Or={utf8:Fr,"utf-8":Fr,hex:Cr.base16,latin1:Dr,ascii:Dr,binary:Dr,...Cr};function Pr(t,e="utf8"){const r=Or[e];if(null==r)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function Ir(t,e="utf8"){const r=Or[e];if(null==r)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}const Nr=parseInt("11111",2),Lr=parseInt("10000000",2),Ur=parseInt("01111111",2),Rr={0:_r,1:_r,2:function(t,e){const r=Br(t,e),n=e.offset,i=e.offset+r,s=[];for(let e=n;e<i;e++)e===n&&0===t[e]||s.push(t[e]);return e.offset+=r,Uint8Array.from(s)},3:function(t,e){const r=Br(t,e),n=t[e.offset];e.offset++;const i=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,0!==n)throw new Error("Unused bits in bit string is unimplemented");return i},4:function(t,e){const r=Br(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n},5:function(t,e){return e.offset++,null},6:function(t,e){const r=Br(t,e),n=e.offset+r,i=t[e.offset];e.offset++;let s=0,a=0;i<40?(s=0,a=i):i<80?(s=1,a=i-40):(s=2,a=i-80);let o=`${s}.${a}`,c=[];for(;e.offset<n;){const r=t[e.offset];if(e.offset++,c.push(127&r),r<128){c.reverse();let t=0;for(let e=0;e<c.length;e++)t+=c[e]<<7*e;o+=`.${t}`,c=[]}}return o},16:_r,22:_r,48:_r};function Mr(t,e={offset:0}){const r=t[e.offset]&Nr;if(e.offset++,null!=Rr[r])return Rr[r](t,e);throw new Error("No decoder for tag "+r)}function Br(t,e){let r=0;if((t[e.offset]&Lr)===Lr){const n=t[e.offset]&Ur;let i="0x";e.offset++;for(let r=0;r<n;r++,e.offset++)i+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(i,16)}else r=t[e.offset],e.offset++;return r}function _r(t,e){Br(t,e);const r=[];for(;!(e.offset>=t.byteLength);){const n=Mr(t,e);if(null===n)break;r.push(n)}return r}function $r(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=function(t){let e=t.toString(16);e.length%2==1&&(e="0"+e);const r=new lr;for(let t=0;t<e.length;t+=2)r.append(Uint8Array.from([parseInt(`${e[t]}${e[t+1]}`,16)]));return r}(t.byteLength);return new lr(Uint8Array.from([e.byteLength|Lr]),e)}function Gr(t){const e=new lr;return!(128&~t.subarray()[0])&&e.append(Uint8Array.from([0])),e.append(t),new lr(Uint8Array.from([2]),$r(e),e)}function jr(t){const e=Uint8Array.from([0]),r=new lr(e,t);return new lr(Uint8Array.from([3]),$r(r),r)}function qr(t,e=48){const r=new lr;for(const e of t)r.append(e);return new lr(Uint8Array.from([e]),$r(r),r)}const Vr=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),zr=Uint8Array.from([6,5,43,129,4,0,34]),Hr=Uint8Array.from([6,5,43,129,4,0,35]),Kr={ext:!0,kty:"EC",crv:"P-256"},Zr={ext:!0,kty:"EC",crv:"P-384"},Jr={ext:!0,kty:"EC",crv:"P-521"};function Wr(t){if("P-256"===t)return Vr;if("P-384"===t)return zr;if("P-521"===t)return Hr;throw new Wt(`Invalid curve ${t}`)}class Yr{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){var t;return null==this._raw&&(this._raw=(t=this.jwk,qr([Gr(Uint8Array.from([1])),qr([Wr(t.crv)],160),qr([jr(new lr(Uint8Array.from([4]),Pr(t.x??"","base64url"),Pr(t.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return rr($a(this))}toCID(){return We.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&nr(this.raw,t.raw)}async verify(t,e,r){return async function(t,e,r,n){const i=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,e,r.subarray());return n?.signal?.throwIfAborted(),s}(this.jwk,e,t,r)}}function Xr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function Qr(t,e=""){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e&&`"${e}" `}expected integer >= 0, got ${t}`)}function tn(t,e,r=""){const n=Xr(t),i=t?.length,s=void 0!==e;if(!n||s&&i!==e)throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(s?` of length ${e}`:"")+", got "+(n?`length=${i}`:"type="+typeof t));return t}function en(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash must wrapped by utils.createHasher");Qr(t.outputLen),Qr(t.blockLen)}function rn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function nn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function sn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function an(t,e){return t<<32-e|t>>>e}const on=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),cn=/* @__PURE__ */Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function un(t){if(tn(t),on)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=cn[t[r]];return e}function ln(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function dn(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(on)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let e=0,i=0;e<r;e++,i+=2){const r=ln(t.charCodeAt(i)),s=ln(t.charCodeAt(i+1));if(void 0===r||void 0===s)throw new Error('hex string expected, got non-hex character "'+(t[i]+t[i+1])+'" at index '+i);n[e]=16*r+s}return n}function hn(...t){let e=0;for(let r=0;r<t.length;r++){const n=t[r];tn(n),e+=n.length}const r=new Uint8Array(e);for(let e=0,n=0;e<t.length;e++){const i=t[e];r.set(i,n),n+=i.length}return r}function fn(t,e={}){const r=(e,r)=>t(r).update(e).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=e=>t(e),Object.assign(r,e),Object.freeze(r)}function gn(t=32){const e="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof e?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}const pn=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function wn(t,e,r){return t&e^t&r^e&r}class mn{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,r,n){this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(t),this.view=sn(this.buffer)}update(t){rn(this),tn(t);const{view:e,buffer:r,blockLen:n}=this,i=t.length;for(let s=0;s<i;){const a=Math.min(n-this.pos,i-s);if(a!==n)r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n&&(this.process(e,0),this.pos=0);else{const e=sn(t);for(;n<=i-s;s+=n)this.process(e,s)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){rn(this),function(t,e){tn(t,void 0,"digestInto() output");const r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}(t,this),this.finished=!0;const{buffer:e,view:r,blockLen:n,isLE:i}=this;let{pos:s}=this;e[s++]=128,nn(this.buffer.subarray(s)),this.padOffset>n-s&&(this.process(r,0),s=0);for(let t=s;t<n;t++)e[t]=0;r.setBigUint64(n-8,BigInt(8*this.length),i),this.process(r,0);const a=sn(t),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const c=o/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<c;t++)a.setUint32(4*t,u[t],i)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||=new this.constructor,t.set(...this.get());const{blockLen:e,buffer:r,length:n,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=n,t.pos=a,n%e&&t.buffer.set(r),t}clone(){return this._cloneInto()}}const yn=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),bn=/* @__PURE__ */Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),vn=/* @__PURE__ */BigInt(2**32-1),En=/* @__PURE__ */BigInt(32);function Sn(t,e=!1){return e?{h:Number(t&vn),l:Number(t>>En&vn)}:{h:0|Number(t>>En&vn),l:0|Number(t&vn)}}const An=(t,e,r)=>t>>>r,Tn=(t,e,r)=>t<<32-r|e>>>r,xn=(t,e,r)=>t>>>r|e<<32-r,Cn=(t,e,r)=>t<<32-r|e>>>r,kn=(t,e,r)=>t<<64-r|e>>>r-32,Fn=(t,e,r)=>t>>>r-32|e<<64-r;function Dn(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:0|i}}const On=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Pn=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,In=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Nn=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,Ln=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Un=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,Rn=/* @__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]),Mn=/* @__PURE__ */new Uint32Array(64);class Bn extends mn{constructor(t){super(64,t,8,!1)}get(){const{A:t,B:e,C:r,D:n,E:i,F:s,G:a,H:o}=this;return[t,e,r,n,i,s,a,o]}set(t,e,r,n,i,s,a,o){this.A=0|t,this.B=0|e,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|s,this.G=0|a,this.H=0|o}process(t,e){for(let r=0;r<16;r++,e+=4)Mn[r]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=Mn[t-15],r=Mn[t-2],n=an(e,7)^an(e,18)^e>>>3,i=an(r,17)^an(r,19)^r>>>10;Mn[t]=i+Mn[t-7]+n+Mn[t-16]|0}let{A:r,B:n,C:i,D:s,E:a,F:o,G:c,H:u}=this;for(let t=0;t<64;t++){const e=u+(an(a,6)^an(a,11)^an(a,25))+((l=a)&o^~l&c)+Rn[t]+Mn[t]|0,d=(an(r,2)^an(r,13)^an(r,22))+wn(r,n,i)|0;u=c,c=o,o=a,a=s+e|0,s=i,i=n,n=r,r=e+d|0}var l;r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,s,a,o,c,u)}roundClean(){nn(Mn)}destroy(){this.set(0,0,0,0,0,0,0,0),nn(this.buffer)}}class _n extends Bn{A=0|yn[0];B=0|yn[1];C=0|yn[2];D=0|yn[3];E=0|yn[4];F=0|yn[5];G=0|yn[6];H=0|yn[7];constructor(){super(32)}}const $n=/* @__PURE__ */(()=>function(t,e=!1){const r=t.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:r,l:a}=Sn(t[s],e);[n[s],i[s]]=[r,a]}return[n,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(t=>BigInt(t))))(),Gn=/* @__PURE__ */(()=>$n[0])(),jn=/* @__PURE__ */(()=>$n[1])(),qn=/* @__PURE__ */new Uint32Array(80),Vn=/* @__PURE__ */new Uint32Array(80);class zn extends mn{constructor(t){super(128,t,16,!1)}get(){const{Ah:t,Al:e,Bh:r,Bl:n,Ch:i,Cl:s,Dh:a,Dl:o,Eh:c,El:u,Fh:l,Fl:d,Gh:h,Gl:f,Hh:g,Hl:p}=this;return[t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p]}set(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p){this.Ah=0|t,this.Al=0|e,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|d,this.Gh=0|h,this.Gl=0|f,this.Hh=0|g,this.Hl=0|p}process(t,e){for(let r=0;r<16;r++,e+=4)qn[r]=t.getUint32(e),Vn[r]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|qn[t-15],r=0|Vn[t-15],n=xn(e,r,1)^xn(e,r,8)^An(e,0,7),i=Cn(e,r,1)^Cn(e,r,8)^Tn(e,r,7),s=0|qn[t-2],a=0|Vn[t-2],o=xn(s,a,19)^kn(s,a,61)^An(s,0,6),c=Cn(s,a,19)^Fn(s,a,61)^Tn(s,a,6),u=In(i,c,Vn[t-7],Vn[t-16]),l=Nn(u,n,o,qn[t-7],qn[t-16]);qn[t]=0|l,Vn[t]=0|u}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:a,Cl:o,Dh:c,Dl:u,Eh:l,El:d,Fh:h,Fl:f,Gh:g,Gl:p,Hh:w,Hl:m}=this;for(let t=0;t<80;t++){const e=xn(l,d,14)^xn(l,d,18)^kn(l,d,41),y=Cn(l,d,14)^Cn(l,d,18)^Fn(l,d,41),b=l&h^~l&g,v=Ln(m,y,d&f^~d&p,jn[t],Vn[t]),E=Un(v,w,e,b,Gn[t],qn[t]),S=0|v,A=xn(r,n,28)^kn(r,n,34)^kn(r,n,39),T=Cn(r,n,28)^Fn(r,n,34)^Fn(r,n,39),x=r&i^r&a^i&a,C=n&s^n&o^s&o;w=0|g,m=0|p,g=0|h,p=0|f,h=0|l,f=0|d,({h:l,l:d}=Dn(0|c,0|u,0|E,0|S)),c=0|a,u=0|o,a=0|i,o=0|s,i=0|r,s=0|n;const k=On(S,T,C);r=Pn(k,E,A,x),n=0|k}({h:r,l:n}=Dn(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=Dn(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=Dn(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=Dn(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:d}=Dn(0|this.Eh,0|this.El,0|l,0|d)),({h,l:f}=Dn(0|this.Fh,0|this.Fl,0|h,0|f)),({h:g,l:p}=Dn(0|this.Gh,0|this.Gl,0|g,0|p)),({h:w,l:m}=Dn(0|this.Hh,0|this.Hl,0|w,0|m)),this.set(r,n,i,s,a,o,c,u,l,d,h,f,g,p,w,m)}roundClean(){nn(qn,Vn)}destroy(){nn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Hn extends zn{Ah=0|bn[0];Al=0|bn[1];Bh=0|bn[2];Bl=0|bn[3];Ch=0|bn[4];Cl=0|bn[5];Dh=0|bn[6];Dl=0|bn[7];Eh=0|bn[8];El=0|bn[9];Fh=0|bn[10];Fl=0|bn[11];Gh=0|bn[12];Gl=0|bn[13];Hh=0|bn[14];Hl=0|bn[15];constructor(){super(64)}}const Kn=/* @__PURE__ */fn(()=>new _n
2
+ /* @__PURE__ */,pn(1)),Zn=/* @__PURE__ */fn(()=>new Hn
3
+ /* @__PURE__ */,pn(3)),Jn=/* @__PURE__ */BigInt(0),Wn=/* @__PURE__ */BigInt(1);function Yn(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}" `)+"expected boolean, got type="+typeof t);return t}function Xn(t){if("bigint"==typeof t){if(!ai(t))throw new Error("positive bigint expected, got "+t)}else Qr(t);return t}function Qn(t){const e=Xn(t).toString(16);return 1&e.length?"0"+e:e}function ti(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?Jn:BigInt("0x"+t)}function ei(t){return ti(un(t))}function ri(t){return ti(un(si(tn(t)).reverse()))}function ni(t,e){Qr(e);const r=dn((t=Xn(t)).toString(16).padStart(2*e,"0"));if(r.length!==e)throw new Error("number too large");return r}function ii(t,e){return ni(t,e).reverse()}function si(t){return Uint8Array.from(t)}const ai=t=>"bigint"==typeof t&&Jn<=t;function oi(t,e,r,n){if(!function(t,e,r){return ai(t)&&ai(e)&&ai(r)&&e<=t&&t<r}(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}const ci=t=>(Wn<<BigInt(t))-Wn;function ui(t,e={},r={}){if(!t||"object"!=typeof t)throw new Error("expected valid options object");const n=(e,r)=>Object.entries(e).forEach(([e,n])=>function(e,r,n){const i=t[e];if(n&&void 0===i)return;const s=typeof i;if(s!==r||null===i)throw new Error(`param "${e}" is invalid: expected ${r}, got ${s}`)}(e,n,r));n(e,!1),n(r,!0)}function li(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(void 0!==i)return i;const s=t(r,...n);return e.set(r,s),s}}const di=/* @__PURE__ */BigInt(0),hi=/* @__PURE__ */BigInt(1),fi=/* @__PURE__ */BigInt(2),gi=/* @__PURE__ */BigInt(3),pi=/* @__PURE__ */BigInt(4),wi=/* @__PURE__ */BigInt(5),mi=/* @__PURE__ */BigInt(7),yi=/* @__PURE__ */BigInt(8),bi=/* @__PURE__ */BigInt(9),vi=/* @__PURE__ */BigInt(16);function Ei(t,e){const r=t%e;return r>=di?r:e+r}function Si(t,e,r){let n=t;for(;e-- >di;)n*=n,n%=r;return n}function Ai(t,e){if(t===di)throw new Error("invert: expected non-zero number");if(e<=di)throw new Error("invert: expected positive modulus, got "+e);let r=Ei(t,e),n=e,i=di,s=hi;for(;r!==di;){const t=n%r,e=i-s*(n/r);n=r,r=t,i=s,s=e}if(n!==hi)throw new Error("invert: does not exist");return Ei(i,e)}function Ti(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function xi(t,e){const r=t.pow(e,(t.ORDER+hi)/pi);return Ti(t,r,e),r}function Ci(t,e){const r=(t.ORDER-wi)/yi,n=t.mul(e,fi),i=t.pow(n,r),s=t.mul(e,i),a=t.mul(t.mul(s,fi),i),o=t.mul(s,t.sub(a,t.ONE));return Ti(t,o,e),o}function ki(t){if(t<gi)throw new Error("sqrt is not defined for small field");let e=t-hi,r=0;for(;e%fi===di;)e/=fi,r++;let n=fi;const i=Ii(t);for(;1===Oi(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return xi;let s=i.pow(n,e);const a=(e+hi)/fi;return function(t,n){if(t.is0(n))return n;if(1!==Oi(t,n))throw new Error("Cannot find square root");let i=r,o=t.mul(t.ONE,s),c=t.pow(n,e),u=t.pow(n,a);for(;!t.eql(c,t.ONE);){if(t.is0(c))return t.ZERO;let e=1,r=t.sqr(c);for(;!t.eql(r,t.ONE);)if(e++,r=t.sqr(r),e===i)throw new Error("Cannot find square root");const n=hi<<BigInt(i-e-1),s=t.pow(o,n);i=e,o=t.sqr(s),c=t.mul(c,o),u=t.mul(u,s)}return u}}const Fi=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Di(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((e,r,i)=>t.is0(r)?e:(n[i]=e,t.mul(e,r)),t.ONE),s=t.inv(i);return e.reduceRight((e,r,i)=>t.is0(r)?e:(n[i]=t.mul(e,n[i]),t.mul(e,r)),s),n}function Oi(t,e){const r=t.pow(e,(t.ORDER-hi)/fi),n=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!n&&!i&&!s)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}class Pi{ORDER;BITS;BYTES;isLE;ZERO=di;ONE=hi;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=di)throw new Error("invalid field: expected ORDER > 0, got "+t);let r;this.isLE=!1,null!=e&&"object"==typeof e&&("number"==typeof e.BITS&&(r=e.BITS),"function"==typeof e.sqrt&&(this.sqrt=e.sqrt),"boolean"==typeof e.isLE&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),"boolean"==typeof e.modFromBytes&&(this._mod=e.modFromBytes));const{nBitLength:n,nByteLength:i}=function(t,e){void 0!==e&&Qr(e);const r=void 0!==e?e:t.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return Ei(t,this.ORDER)}isValid(t){if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return di<=t&&t<this.ORDER}is0(t){return t===di}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&hi)===hi}neg(t){return Ei(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return Ei(t*t,this.ORDER)}add(t,e){return Ei(t+e,this.ORDER)}sub(t,e){return Ei(t-e,this.ORDER)}mul(t,e){return Ei(t*e,this.ORDER)}pow(t,e){return function(t,e,r){if(r<di)throw new Error("invalid exponent, negatives unsupported");if(r===di)return t.ONE;if(r===hi)return e;let n=t.ONE,i=e;for(;r>di;)r&hi&&(n=t.mul(n,i)),i=t.sqr(i),r>>=hi;return n}(this,t,e)}div(t,e){return Ei(t*Ai(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Ai(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=(e=this.ORDER)%pi===gi?xi:e%yi===wi?Ci:e%vi===bi?function(t){const e=Ii(t),r=ki(t),n=r(e,e.neg(e.ONE)),i=r(e,n),s=r(e,e.neg(n)),a=(t+mi)/vi;return(t,e)=>{let r=t.pow(e,a),o=t.mul(r,n);const c=t.mul(r,i),u=t.mul(r,s),l=t.eql(t.sqr(o),e),d=t.eql(t.sqr(c),e);r=t.cmov(r,o,l),o=t.cmov(u,c,d);const h=t.eql(t.sqr(o),e),f=t.cmov(r,o,h);return Ti(t,f,e),f}}(e):ki(e)),this._sqrt(this,t);var e}toBytes(t){return this.isLE?ii(t,this.BYTES):ni(t,this.BYTES)}fromBytes(t,e=!1){tn(t);const{_lengths:r,BYTES:n,isLE:i,ORDER:s,_mod:a}=this;if(r){if(!r.includes(t.length)||t.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);const e=new Uint8Array(n);e.set(t,i?0:e.length-t.length),t=e}if(t.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let o=i?ri(t):ei(t);if(a&&(o=Ei(o,s)),!e&&!this.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o}invertBatch(t){return Di(this,t)}cmov(t,e,r){return r?e:t}}function Ii(t,e={}){return new Pi(t,e)}function Ni(t){if("bigint"!=typeof t)throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function Li(t){const e=Ni(t);return e+Math.ceil(e/2)}const Ui=/* @__PURE__ */BigInt(0),Ri=/* @__PURE__ */BigInt(1);function Mi(t,e){const r=e.negate();return t?r:e}function Bi(t,e){const r=Di(t.Fp,e.map(t=>t.Z));return e.map((e,n)=>t.fromAffine(e.toAffine(r[n])))}function _i(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function $i(t,e){_i(t,e);const r=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:ci(t),maxNumber:r,shiftBy:BigInt(t)}}function Gi(t,e,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:a}=r;let o=Number(t&i),c=t>>a;o>n&&(o-=s,c+=Ri);const u=e*n;return{nextN:c,offset:u+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:e%2!=0,offsetF:u}}const ji=new WeakMap,qi=new WeakMap;function Vi(t){return qi.get(t)||1}function zi(t){if(t!==Ui)throw new Error("invalid wNAF")}class Hi{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,r=this.ZERO){let n=t;for(;e>Ui;)e&Ri&&(r=r.add(n)),n=n.double(),e>>=Ri;return r}precomputeWindow(t,e){const{windows:r,windowSize:n}=$i(e,this.bits),i=[];let s=t,a=s;for(let t=0;t<r;t++){a=s,i.push(a);for(let t=1;t<n;t++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,e,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const s=$i(t,this.bits);for(let t=0;t<s.windows;t++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:l,offsetF:d}=Gi(r,t,s);r=a,c?i=i.add(Mi(l,e[d])):n=n.add(Mi(u,e[o]))}return zi(r),{p:n,f:i}}wNAFUnsafe(t,e,r,n=this.ZERO){const i=$i(t,this.bits);for(let t=0;t<i.windows&&r!==Ui;t++){const{nextN:s,offset:a,isZero:o,isNeg:c}=Gi(r,t,i);if(r=s,!o){const t=e[a];n=n.add(c?t.negate():t)}}return zi(r),n}getPrecomputes(t,e,r){let n=ji.get(e);return n||(n=this.precomputeWindow(e,t),1!==t&&("function"==typeof r&&(n=r(n)),ji.set(e,n))),n}cached(t,e,r){const n=Vi(t);return this.wNAF(n,this.getPrecomputes(n,t,r),e)}unsafe(t,e,r,n){const i=Vi(t);return 1===i?this._unsafeLadder(t,e,n):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),e,n)}createCache(t,e){_i(e,this.bits),qi.set(t,e),ji.delete(t)}hasCache(t){return 1!==Vi(t)}}function Ki(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(t){ui(t,Fi.reduce((t,e)=>(t[e]="function",t),{ORDER:"bigint",BYTES:"number",BITS:"number"}))}(e),e}return Ii(t,{isLE:r})}function Zi(t,e,r={},n){if(void 0===n&&(n="edwards"===t),!e||"object"!=typeof e)throw new Error(`expected valid ${t} CURVE object`);for(const t of["p","n","h"]){const r=e[t];if(!("bigint"==typeof r&&r>Ui))throw new Error(`CURVE.${t} must be positive bigint`)}const i=Ki(e.p,r.Fp,n),s=Ki(e.n,r.Fn,n),a=["Gx","Gy","a","weierstrass"===t?"b":"d"];for(const t of a)if(!i.isValid(e[t]))throw new Error(`CURVE.${t} must be valid field element of CURVE.Fp`);return{CURVE:e=Object.freeze(Object.assign({},e)),Fp:i,Fn:s}}function Ji(t,e){return function(r){const n=t(r);return{secretKey:n,publicKey:e(n)}}}const Wi=BigInt(0),Yi=BigInt(1),Xi=BigInt(2),Qi=BigInt(8);function ts(t,e={}){const r=Zi("edwards",t,e,e.FpFnLE),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:a}=s;ui(e,{},{uvRatio:"function"});const o=Xi<<BigInt(8*i.BYTES)-Yi,c=t=>n.create(t),u=e.uvRatio||((t,e)=>{try{return{isValid:!0,value:n.sqrt(n.div(t,e))}}catch(t){return{isValid:!1,value:Wi}}});if(!function(t,e,r,n){const i=t.sqr(r),s=t.sqr(n),a=t.add(t.mul(e.a,i),s),o=t.add(t.ONE,t.mul(e.d,t.mul(i,s)));return t.eql(a,o)}(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(t,e,r=!1){return oi("coordinate "+t,e,r?Yi:Wi,o),e}function d(t){if(!(t instanceof g))throw new Error("EdwardsPoint expected")}const h=li((t,e)=>{const{X:r,Y:i,Z:s}=t,a=t.is0();null==e&&(e=a?Qi:n.inv(s));const o=c(r*e),u=c(i*e),l=n.mul(s,e);if(a)return{x:Wi,y:Yi};if(l!==Yi)throw new Error("invZ was invalid");return{x:o,y:u}}),f=li(t=>{const{a:e,d:r}=s;if(t.is0())throw new Error("bad point: ZERO");const{X:n,Y:i,Z:a,T:o}=t,u=c(n*n),l=c(i*i),d=c(a*a),h=c(d*d),f=c(u*e);if(c(d*c(f+l))!==c(h+c(r*c(u*l))))throw new Error("bad point: equation left != right (1)");if(c(n*i)!==c(a*o))throw new Error("bad point: equation left != right (2)");return!0});class g{static BASE=new g(s.Gx,s.Gy,Yi,c(s.Gx*s.Gy));static ZERO=new g(Wi,Yi,Yi,Wi);static Fp=n;static Fn=i;X;Y;Z;T;constructor(t,e,r,n){this.X=l("x",t),this.Y=l("y",e),this.Z=l("z",r,!0),this.T=l("t",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){if(t instanceof g)throw new Error("extended point not allowed");const{x:e,y:r}=t||{};return l("x",e),l("y",r),new g(e,r,Yi,c(e*r))}static fromBytes(t,e=!1){const r=n.BYTES,{a:i,d:a}=s;t=si(tn(t,r,"point")),Yn(e,"zip215");const l=si(t),d=t[r-1];l[r-1]=-129&d;const h=ri(l);oi("point.y",h,Wi,e?o:n.ORDER);const f=c(h*h),p=c(f-Yi),w=c(a*f-i);let{isValid:m,value:y}=u(p,w);if(!m)throw new Error("bad point: invalid y coordinate");const b=(y&Yi)===Yi,v=!!(128&d);if(!e&&y===Wi&&v)throw new Error("bad point: x=0 and x_0=1");return v!==b&&(y=c(-y)),g.fromAffine({x:y,y:h})}static fromHex(t,e=!1){return g.fromBytes(dn(t),e)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return p.createCache(this,t),e||this.multiply(Xi),this}assertValidity(){f(this)}equals(t){d(t);const{X:e,Y:r,Z:n}=this,{X:i,Y:s,Z:a}=t,o=c(e*a),u=c(i*n),l=c(r*a),h=c(s*n);return o===u&&l===h}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:t}=s,{X:e,Y:r,Z:n}=this,i=c(e*e),a=c(r*r),o=c(Xi*c(n*n)),u=c(t*i),l=e+r,d=c(c(l*l)-i-a),h=u+a,f=h-o,p=u-a,w=c(d*f),m=c(h*p),y=c(d*p),b=c(f*h);return new g(w,m,b,y)}add(t){d(t);const{a:e,d:r}=s,{X:n,Y:i,Z:a,T:o}=this,{X:u,Y:l,Z:h,T:f}=t,p=c(n*u),w=c(i*l),m=c(o*r*f),y=c(a*h),b=c((n+i)*(u+l)-p-w),v=y-m,E=y+m,S=c(w-e*p),A=c(b*v),T=c(E*S),x=c(b*S),C=c(v*E);return new g(A,T,C,x)}subtract(t){return this.add(t.negate())}multiply(t){if(!i.isValidNot0(t))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:e,f:r}=p.cached(this,t,t=>Bi(g,t));return Bi(g,[e,r])[0]}multiplyUnsafe(t,e=g.ZERO){if(!i.isValid(t))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return t===Wi?g.ZERO:this.is0()||t===Yi?this:p.unsafe(this,t,t=>Bi(g,t),e)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return p.unsafe(this,s.n).is0()}toAffine(t){return h(this,t)}clearCofactor(){return a===Yi?this:this.multiplyUnsafe(a)}toBytes(){const{x:t,y:e}=this.toAffine(),r=n.toBytes(e);return r[r.length-1]|=t&Yi?128:0,r}toHex(){return un(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const p=new Hi(g,i.BITS);return g.BASE.precompute(8),g}const es=BigInt(1),rs=BigInt(2),ns=BigInt(5),is=BigInt(8),ss=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),as=/* @__PURE__ */(()=>({p:ss,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:is,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function os(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const cs=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),us=/* @__PURE__ */ts(as,{uvRatio:function(t,e){const r=ss,n=Ei(e*e*e,r),i=function(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=ss,a=t*t%s*t%s,o=Si(a,rs,s)*a%s,c=Si(o,es,s)*t%s,u=Si(c,ns,s)*c%s,l=Si(u,e,s)*u%s,d=Si(l,r,s)*l%s,h=Si(d,n,s)*d%s,f=Si(h,i,s)*h%s,g=Si(f,i,s)*h%s,p=Si(g,e,s)*u%s;return{pow_p_5_8:Si(p,rs,s)*t%s,b2:a}}(t*Ei(n*n*e,r)).pow_p_5_8;let s=Ei(t*n*i,r);const a=Ei(e*s*s,r),o=s,c=Ei(s*cs,r),u=a===t,l=a===Ei(-t,r),d=a===Ei(-t*cs,r);return u&&(s=o),(l||d)&&(s=c),(Ei(s,r)&hi)===hi&&(s=Ei(-s,r)),{isValid:u||l,value:s}}});function ls(t){return function(t,e,r={}){if("function"!=typeof e)throw new Error('"hash" function param is required');ui(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:i,Fp:s,Fn:a}=t,o=r.randomBytes||gn,c=r.adjustScalarBytes||(t=>t),u=r.domain||((t,e,r)=>{if(Yn(r,"phflag"),e.length||r)throw new Error("Contexts/pre-hash are not supported");return t});function l(t){return a.create(ri(t))}function d(t){const{head:r,prefix:n,scalar:s}=function(t){const r=w.secretKey;tn(t,w.secretKey,"secretKey");const n=tn(e(t),2*r,"hashedSecretKey"),i=c(n.slice(0,r));return{head:i,prefix:n.slice(r,2*r),scalar:l(i)}}(t),a=i.multiply(s),o=a.toBytes();return{head:r,prefix:n,scalar:s,point:a,pointBytes:o}}function h(t){return d(t).pointBytes}function f(t=Uint8Array.of(),...r){const i=hn(...r);return l(e(u(i,tn(t,void 0,"context"),!!n)))}const g={zip215:!0},p=s.BYTES,w={secretKey:p,publicKey:p,signature:2*p,seed:p};function m(t=o(w.seed)){return tn(t,w.seed,"seed")}const y={getExtendedPublicKey:d,randomSecretKey:m,isValidSecretKey:function(t){return Xr(t)&&t.length===a.BYTES},isValidPublicKey:function(e,r){try{return!!t.fromBytes(e,r)}catch(t){return!1}},toMontgomery(e){const{y:r}=t.fromBytes(e),n=w.publicKey,i=32===n;if(!i&&57!==n)throw new Error("only defined for 25519 and 448");const a=i?s.div(Yi+r,Yi-r):s.div(r-Yi,r+Yi);return s.toBytes(a)},toMontgomerySecret(t){const r=w.secretKey;tn(t,r);const n=e(t.subarray(0,r));return c(n).subarray(0,r)}};return Object.freeze({keygen:Ji(m,h),getPublicKey:h,sign:function(t,e,r={}){t=tn(t,void 0,"message"),n&&(t=n(t));const{prefix:s,scalar:o,pointBytes:c}=d(e),u=f(r.context,s,t),l=i.multiply(u).toBytes(),h=f(r.context,l,c,t),g=a.create(u+h*o);if(!a.isValid(g))throw new Error("sign failed: invalid s");return tn(hn(l,a.toBytes(g)),w.signature,"result")},verify:function(e,r,s,a=g){const{context:o,zip215:c}=a,u=w.signature;e=tn(e,u,"signature"),r=tn(r,void 0,"message"),s=tn(s,w.publicKey,"publicKey"),void 0!==c&&Yn(c,"zip215"),n&&(r=n(r));const l=u/2,d=e.subarray(0,l),h=ri(e.subarray(l,u));let p,m,y;try{p=t.fromBytes(s,c),m=t.fromBytes(d,c),y=i.multiplyUnsafe(h)}catch(t){return!1}if(!c&&p.isSmallOrder())return!1;const b=f(o,m.toBytes(),p.toBytes(),r);return m.add(p.multiplyUnsafe(b)).subtract(y).clearCofactor().is0()},utils:y,Point:t,lengths:w})}(us,Zn,Object.assign({adjustScalarBytes:os},t))}const ds=/* @__PURE__ */ls({});class hs extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}}class fs extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}}var gs={get(t=globalThis){const e=t.crypto;if(null==e?.subtle)throw new fs("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 e}};let ps;const ws=(async()=>{try{return await gs.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function ms(t){return null!=t&&"function"==typeof t.then&&"function"==typeof t.catch&&"function"==typeof t.finally}class ys{type="Ed25519";raw;constructor(t){this.raw=bs(t,32)}toMultihash(){return rr($a(this))}toCID(){return We.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&nr(this.raw,t.raw)}verify(t,e,r){r?.signal?.throwIfAborted();const n=async function(t,e,r){return null==ps&&(ps=await ws),ps?async function(t,e,r){if(t.buffer instanceof ArrayBuffer){const n=await gs.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await gs.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(t,e,r):function(t,e,r){return ds.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}(t,e,r)}(this.raw,e,t);return ms(n)?n.then(t=>(r?.signal?.throwIfAborted(),t)):n}}function bs(t,e){if((t=Uint8Array.from(t??[])).length!==e)throw new Wt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const vs=Math.pow(2,7),Es=Math.pow(2,14),Ss=Math.pow(2,21),As=Math.pow(2,28),Ts=Math.pow(2,35),xs=Math.pow(2,42),Cs=Math.pow(2,49),ks=128,Fs=127;function Ds(t){if(t<vs)return 1;if(t<Es)return 2;if(t<Ss)return 3;if(t<As)return 4;if(t<Ts)return 5;if(t<xs)return 6;if(t<Cs)return 7;if(null!=Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Os(t,e,r=0){switch(Ds(t)){case 8:e[r++]=255&t|ks,t/=128;case 7:e[r++]=255&t|ks,t/=128;case 6:e[r++]=255&t|ks,t/=128;case 5:e[r++]=255&t|ks,t/=128;case 4:e[r++]=255&t|ks,t>>>=7;case 3:e[r++]=255&t|ks,t>>>=7;case 2:e[r++]=255&t|ks,t>>>=7;case 1:e[r++]=255&t,t>>>=7;break;default:throw new Error("unreachable")}return e}function Ps(t,e){let r=t[e],n=0;if(n+=r&Fs,r<ks)return n;if(r=t[e+1],n+=(r&Fs)<<7,r<ks)return n;if(r=t[e+2],n+=(r&Fs)<<14,r<ks)return n;if(r=t[e+3],n+=(r&Fs)<<21,r<ks)return n;if(r=t[e+4],n+=(r&Fs)*As,r<ks)return n;if(r=t[e+5],n+=(r&Fs)*Ts,r<ks)return n;if(r=t[e+6],n+=(r&Fs)*xs,r<ks)return n;if(r=t[e+7],n+=(r&Fs)*Cs,r<ks)return n;throw new RangeError("Could not decode varint")}function Is(t,e,r=0){return null==e&&(e=sr(Ds(t))),e instanceof Uint8Array?Os(t,e,r):function(t,e,r=0){switch(Ds(t)){case 8:e.set(r++,255&t|ks),t/=128;case 7:e.set(r++,255&t|ks),t/=128;case 6:e.set(r++,255&t|ks),t/=128;case 5:e.set(r++,255&t|ks),t/=128;case 4:e.set(r++,255&t|ks),t>>>=7;case 3:e.set(r++,255&t|ks),t>>>=7;case 2:e.set(r++,255&t|ks),t>>>=7;case 1:e.set(r++,255&t),t>>>=7;break;default:throw new Error("unreachable")}return e}(t,e,r)}function Ns(t,e=0){return t instanceof Uint8Array?Ps(t,e):function(t,e){let r=t.get(e),n=0;if(n+=r&Fs,r<ks)return n;if(r=t.get(e+1),n+=(r&Fs)<<7,r<ks)return n;if(r=t.get(e+2),n+=(r&Fs)<<14,r<ks)return n;if(r=t.get(e+3),n+=(r&Fs)<<21,r<ks)return n;if(r=t.get(e+4),n+=(r&Fs)*As,r<ks)return n;if(r=t.get(e+5),n+=(r&Fs)*Ts,r<ks)return n;if(r=t.get(e+6),n+=(r&Fs)*xs,r<ks)return n;if(r=t.get(e+7),n+=(r&Fs)*Cs,r<ks)return n;throw new RangeError("Could not decode varint")}(t,e)}const Ls=new Float32Array([-0]),Us=new Uint8Array(Ls.buffer);function Rs(t,e,r){Ls[0]=t,e[r]=Us[0],e[r+1]=Us[1],e[r+2]=Us[2],e[r+3]=Us[3]}const Ms=new Float64Array([-0]),Bs=new Uint8Array(Ms.buffer);function _s(t,e,r){Ms[0]=t,e[r]=Bs[0],e[r+1]=Bs[1],e[r+2]=Bs[2],e[r+3]=Bs[3],e[r+4]=Bs[4],e[r+5]=Bs[5],e[r+6]=Bs[6],e[r+7]=Bs[7]}const $s=BigInt(Number.MAX_SAFE_INTEGER),Gs=BigInt(Number.MIN_SAFE_INTEGER);class js{lo;hi;constructor(t,e){this.lo=0|t,this.hi=0|e}toNumber(t=!1){if(!t&&this.hi>>>31>0){const t=1+~this.lo>>>0;let e=~this.hi>>>0;return 0===t&&(e=e+1>>>0),-(t+4294967296*e)}return this.lo+4294967296*this.hi}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const t=1+~this.lo>>>0;let e=~this.hi>>>0;return 0===t&&(e=e+1>>>0),-(BigInt(t)+(BigInt(e)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){const t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){const t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){const t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:r<128?9:10}static fromBigInt(t){if(0n===t)return qs;if(t<$s&&t>Gs)return this.fromNumber(Number(t));const e=t<0n;e&&(t=-t);let r=t>>32n,n=t-(r<<32n);return e&&(r=0n|~r,n=0n|~n,++n>Vs&&(n=0n,++r>Vs&&(r=0n))),new js(Number(n),Number(r))}static fromNumber(t){if(0===t)return qs;const e=t<0;e&&(t=-t);let r=t>>>0,n=(t-r)/4294967296>>>0;return e&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new js(r,n)}static from(t){return"number"==typeof t?js.fromNumber(t):"bigint"==typeof t?js.fromBigInt(t):"string"==typeof t?js.fromBigInt(BigInt(t)):null!=t.low||null!=t.high?new js(t.low>>>0,t.high>>>0):qs}}const qs=new js(0,0);qs.toBigInt=function(){return 0n},qs.zzEncode=qs.zzDecode=function(){return this},qs.length=function(){return 1};const Vs=4294967296n;function zs(t,e,r){const n=r;let i,s;for(let n=0;n<t.length;++n)i=t.charCodeAt(n),i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=63&i|128):55296==(64512&i)&&56320==(64512&(s=t.charCodeAt(n+1)))?(i=65536+((1023&i)<<10)+(1023&s),++n,e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=63&i|128):(e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=63&i|128);return r-n}function Hs(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Ks(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Zs{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return t;if(t=(t|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Hs(this,10);return t}int32(){return 0|this.uint32()}sint32(){const t=this.uint32();return t>>>1^-(1&t)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Hs(this,4);return Ks(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Hs(this,4);return 0|Ks(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Hs(this,4);const t=(Us[0]=(e=this.buf)[r=this.pos],Us[1]=e[r+1],Us[2]=e[r+2],Us[3]=e[r+3],Ls[0]);var e,r;return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Hs(this,4);const t=(Bs[0]=(e=this.buf)[r=this.pos],Bs[1]=e[r+1],Bs[2]=e[r+2],Bs[3]=e[r+3],Bs[4]=e[r+4],Bs[5]=e[r+5],Bs[6]=e[r+6],Bs[7]=e[r+7],Ms[0]);var e,r;return this.pos+=8,t}bytes(){const t=this.uint32(),e=this.pos,r=this.pos+t;if(r>this.len)throw Hs(this,t);return this.pos+=t,e===r?new Uint8Array(0):this.buf.subarray(e,r)}string(){const t=this.bytes();return function(t,e,r){if(r-e<1)return"";let n;const i=[];let s,a=0;for(;e<r;)s=t[e++],s<128?i[a++]=s:s>191&&s<224?i[a++]=(31&s)<<6|63&t[e++]:s>239&&s<365?(s=((7&s)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,i[a++]=55296+(s>>10),i[a++]=56320+(1023&s)):i[a++]=(15&s)<<12|(63&t[e++])<<6|63&t[e++],a>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,i)),a=0);return null!=n?(a>0&&n.push(String.fromCharCode.apply(String,i.slice(0,a))),n.join("")):String.fromCharCode.apply(String,i.slice(0,a))}(t,0,t.length)}skip(t){if("number"==typeof t){if(this.pos+t>this.len)throw Hs(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw Hs(this)}while(128&this.buf[this.pos++]);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){const t=new js(0,0);let e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw Hs(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Hs(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Hs(this,8);const t=Ks(this.buf,this.pos+=4),e=Ks(this.buf,this.pos+=4);return new js(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const t=Ps(this.buf,this.pos);return this.pos+=Ds(t),t}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 Js(t){return new Zs(t instanceof Uint8Array?t:t.subarray())}function Ws(t,e,r){const n=Js(t);return e.decode(n,void 0,r)}class Ys{fn;len;next;val;constructor(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}}function Xs(){}class Qs{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}const ta=function(){const t=8192;let e,r=t;return function(n){if(n<1||n>4096)return sr(n);r+n>t&&(e=sr(t),r=0);const i=e.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),i}}();class ea{len;head;tail;states;constructor(){this.len=0,this.head=new Ys(Xs,0,0),this.tail=this.head,this.states=null}_push(t,e,r){return this.tail=this.tail.next=new Ys(t,e,r),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ia((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(sa,10,js.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){const e=js.fromBigInt(t);return this._push(sa,e.length(),e)}uint64Number(t){return this._push(Os,Ds(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){const e=js.fromBigInt(t).zzEncode();return this._push(sa,e.length(),e)}sint64Number(t){const e=js.fromNumber(t).zzEncode();return this._push(sa,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ra,1,t?1:0)}fixed32(t){return this._push(aa,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){const e=js.fromBigInt(t);return this._push(aa,4,e.lo)._push(aa,4,e.hi)}fixed64Number(t){const e=js.fromNumber(t);return this._push(aa,4,e.lo)._push(aa,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Rs,4,t)}double(t){return this._push(_s,8,t)}bytes(t){const e=t.length>>>0;return 0===e?this._push(ra,1,0):this.uint32(e)._push(oa,e,t)}string(t){const e=function(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:55296==(64512&r)&&56320==(64512&t.charCodeAt(n+1))?(++n,e+=4):e+=3;return e}(t);return 0!==e?this.uint32(e)._push(zs,e,t):this._push(ra,1,0)}fork(){return this.states=new Qs(this),this.head=this.tail=new Ys(Xs,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 Ys(Xs,0,0),this.len=0),this}ldelim(){const t=this.head,e=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=t.next,this.tail=e,this.len+=r),this}finish(){let t=this.head.next;const e=(r=this.len,null!=globalThis.Buffer?sr(r):ta(r));var r;let n=0;for(;null!=t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}}function ra(t,e,r){e[r]=255&t}function na(t,e,r){for(;t>127;)e[r++]=127&t|128,t>>>=7;e[r]=t}class ia extends Ys{next;constructor(t,e){super(na,t,e),this.next=void 0}}function sa(t,e,r){for(;0!==t.hi;)e[r++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=127&t.lo|128,t.lo=t.lo>>>7;e[r++]=t.lo}function aa(t,e,r){e[r]=255&t,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function oa(t,e,r){e.set(t,r)}function ca(t,e,r){e.set(t,r)}function ua(t,e,r){t.length<40?zs(t,e,r):null!=e.utf8Write?e.utf8Write(t,r):e.set(Pr(t),r)}function la(t,e){const r=new ea;return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*da(t,e,r){const n=Js(t);yield*e.stream(n,void 0,"$",r)}function ha(t,e,r,n,i){return{name:t,type:e,encode:r,decode:n,stream:i}}function fa(t,e,r){return ha("message",2,t,e,r)}var ga,pa,wa,ma;null!=globalThis.Buffer&&(ea.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(ca,e,t),this},ea.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(ua,e,t),this}),function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"}(ga||(ga={})),function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"}(pa||(pa={})),function(t){t.codec=()=>function(t){function e(e){if(null==t[e.toString()])throw new Error("Invalid enum value");return t[e]}return ha("enum",0,function(t,r){const n=e(t);r.int32(n)},function(t){return e(t.int32())},function*(t){const r=t.int32();yield e(r)})}(pa)}(ga||(ga={})),function(t){let e;t.codec=()=>(null==e&&(e=fa((t,e,r={})=>{!1!==r.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),ga.codec().encode(t.Type,e)),null!=t.Data&&(e.uint32(18),e.bytes(t.Data)),!1!==r.lengthDelimited&&e.ldelim()},(t,e,r={})=>{const n={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:n.Type=ga.codec().decode(t);break;case 2:n.Data=t.bytes();break;default:t.skipType(7&e)}}return n},function*(t,e,r,n={}){const i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:yield{field:`${r}.Type`,value:ga.codec().decode(t)};break;case 2:yield{field:`${r}.Data`,value:t.bytes()};break;default:t.skipType(7&e)}}})),e),t.encode=function(e){return la(e,t.codec())},t.decode=function(e,r){return Ws(e,t.codec(),r)},t.stream=function(e,r){return da(e,t.codec(),r)}}(wa||(wa={})),function(t){let e;t.codec=()=>(null==e&&(e=fa((t,e,r={})=>{!1!==r.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),ga.codec().encode(t.Type,e)),null!=t.Data&&(e.uint32(18),e.bytes(t.Data)),!1!==r.lengthDelimited&&e.ldelim()},(t,e,r={})=>{const n={},i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:n.Type=ga.codec().decode(t);break;case 2:n.Data=t.bytes();break;default:t.skipType(7&e)}}return n},function*(t,e,r,n={}){const i=null==e?t.len:t.pos+e;for(;t.pos<i;){const e=t.uint32();switch(e>>>3){case 1:yield{field:`${r}.Type`,value:ga.codec().decode(t)};break;case 2:yield{field:`${r}.Data`,value:t.bytes()};break;default:t.skipType(7&e)}}})),e),t.encode=function(e){return la(e,t.codec())},t.decode=function(e,r){return Ws(e,t.codec(),r)},t.stream=function(e,r){return da(e,t.codec(),r)}}(ma||(ma={}));class ya{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(en(t),tn(e,void 0,"key"),this.iHash=t.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 r=this.blockLen,n=new Uint8Array(r);n.set(e.length>r?t.create().update(e).digest():e);for(let t=0;t<n.length;t++)n[t]^=54;this.iHash.update(n),this.oHash=t.create();for(let t=0;t<n.length;t++)n[t]^=106;this.oHash.update(n),nn(n)}update(t){return rn(this),this.iHash.update(t),this}digestInto(t){rn(this),tn(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:e,iHash:r,finished:n,destroyed:i,blockLen:s,outputLen:a}=this;return t.finished=n,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ba=(t,e,r)=>new ya(t,e).update(r).digest();ba.create=(t,e)=>new ya(t,e);const va=(t,e)=>(t+(t>=0?e:-e)/ka)/e;function Ea(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Sa(t,e){const r={};for(let n of Object.keys(e))r[n]=void 0===t[n]?e[n]:t[n];return Yn(r.lowS,"lowS"),Yn(r.prehash,"prehash"),void 0!==r.format&&Ea(r.format),r}class Aa extends Error{constructor(t=""){super(t)}}const Ta={Err:Aa,_tlv:{encode:(t,e)=>{const{Err:r}=Ta;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(1&e.length)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=Qn(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Qn(i.length/2|128):"";return Qn(t)+s+i+e},decode(t,e){const{Err:r}=Ta;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++];let s=0;if(128&i){const t=127&i;if(!t)throw new r("tlv.decode(long): indefinite length not supported");if(t>4)throw new r("tlv.decode(long): byte length is too big");const a=e.subarray(n,n+t);if(a.length!==t)throw new r("tlv.decode: length bytes not complete");if(0===a[0])throw new r("tlv.decode(long): zero leftmost byte");for(const t of a)s=s<<8|t;if(n+=t,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=i;const a=e.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(t){const{Err:e}=Ta;if(t<xa)throw new e("integer: negative integers are not allowed");let r=Qn(t);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=Ta;if(128&t[0])throw new e("invalid signature integer: negative");if(0===t[0]&&!(128&t[1]))throw new e("invalid signature integer: unnecessary leading zero");return ei(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=Ta,i=tn(t,void 0,"signature"),{v:s,l:a}=n.decode(48,i);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:o,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(o),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=Ta,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s));return e.encode(48,n+i)}},xa=BigInt(0),Ca=BigInt(1),ka=BigInt(2),Fa=BigInt(3),Da=BigInt(4);function Oa(t,e={}){const r=Zi("weierstrass",t,e),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:a,n:o}=s;ui(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!n.is0(s.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Ia(n,i);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=e.toBytes||function(t,e,r){const{x:i,y:s}=e.toAffine(),a=n.toBytes(i);return Yn(r,"isCompressed"),r?(l(),hn(Pa(!n.isOdd(s)),a)):hn(Uint8Array.of(4),a,n.toBytes(s))},h=e.fromBytes||function(t){tn(t,void 0,"Point");const{publicKey:e,publicKeyUncompressed:r}=u,i=t.length,s=t[0],a=t.subarray(1);if(i!==e||2!==s&&3!==s){if(i===r&&4===s){const t=n.BYTES,e=n.fromBytes(a.subarray(0,t)),r=n.fromBytes(a.subarray(t,2*t));if(!g(e,r))throw new Error("bad point: is not on curve");return{x:e,y:r}}throw new Error(`bad point: got length ${i}, expected compressed=${e} or uncompressed=${r}`)}{const t=n.fromBytes(a);if(!n.isValid(t))throw new Error("bad point: is not on curve, wrong x");const e=f(t);let r;try{r=n.sqrt(e)}catch(t){const e=t instanceof Error?": "+t.message:"";throw new Error("bad point: is not on curve, sqrt error"+e)}return l(),!(1&~s)!==n.isOdd(r)&&(r=n.neg(r)),{x:t,y:r}}};function f(t){const e=n.sqr(t),r=n.mul(e,t);return n.add(n.add(r,n.mul(t,s.a)),s.b)}function g(t,e){const r=n.sqr(e),i=f(t);return n.eql(r,i)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const p=n.mul(n.pow(s.a,Fa),Da),w=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(p,w)))throw new Error("bad curve params: a or b");function m(t,e,r=!1){if(!n.isValid(e)||r&&n.is0(e))throw new Error(`bad point coordinate ${t}`);return e}function y(t){if(!(t instanceof A))throw new Error("Weierstrass Point expected")}function b(t){if(!c||!c.basises)throw new Error("no endo");return function(t,e,r){const[[n,i],[s,a]]=e,o=va(a*t,r),c=va(-i*t,r);let u=t-o*n-c*s,l=-o*i-c*a;const d=u<xa,h=l<xa;d&&(u=-u),h&&(l=-l);const f=ci(Math.ceil(function(t){let e;for(e=0;t>Jn;t>>=Wn,e+=1);return e}(r)/2))+Ca;if(u<xa||u>=f||l<xa||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:d,k1:u,k2neg:h,k2:l}}(t,c.basises,i.ORDER)}const v=li((t,e)=>{const{X:r,Y:i,Z:s}=t;if(n.eql(s,n.ONE))return{x:r,y:i};const a=t.is0();null==e&&(e=a?n.ONE:n.inv(s));const o=n.mul(r,e),c=n.mul(i,e),u=n.mul(s,e);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(u,n.ONE))throw new Error("invZ was invalid");return{x:o,y:c}}),E=li(t=>{if(t.is0()){if(e.allowInfinityPoint&&!n.is0(t.Y))return;throw new Error("bad point: ZERO")}const{x:r,y:i}=t.toAffine();if(!n.isValid(r)||!n.isValid(i))throw new Error("bad point: x or y not field elements");if(!g(r,i))throw new Error("bad point: equation left != right");if(!t.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(t,e,r,i,s){return r=new A(n.mul(r.X,t),r.Y,r.Z),e=Mi(i,e),r=Mi(s,r),e.add(r)}class A{static BASE=new A(s.Gx,s.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;constructor(t,e,r){this.X=m("x",t),this.Y=m("y",e,!0),this.Z=m("z",r),Object.freeze(this)}static CURVE(){return s}static fromAffine(t){const{x:e,y:r}=t||{};if(!t||!n.isValid(e)||!n.isValid(r))throw new Error("invalid affine point");if(t instanceof A)throw new Error("projective point not allowed");return n.is0(e)&&n.is0(r)?A.ZERO:new A(e,r,n.ONE)}static fromBytes(t){const e=A.fromAffine(h(tn(t,void 0,"point")));return e.assertValidity(),e}static fromHex(t){return A.fromBytes(dn(t))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return x.createCache(this,t),e||this.multiply(Fa),this}assertValidity(){E(this)}hasEvenY(){const{y:t}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(t)}equals(t){y(t);const{X:e,Y:r,Z:i}=this,{X:s,Y:a,Z:o}=t,c=n.eql(n.mul(e,o),n.mul(s,i)),u=n.eql(n.mul(r,o),n.mul(a,i));return c&&u}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){const{a:t,b:e}=s,r=n.mul(e,Fa),{X:i,Y:a,Z:o}=this;let c=n.ZERO,u=n.ZERO,l=n.ZERO,d=n.mul(i,i),h=n.mul(a,a),f=n.mul(o,o),g=n.mul(i,a);return g=n.add(g,g),l=n.mul(i,o),l=n.add(l,l),c=n.mul(t,l),u=n.mul(r,f),u=n.add(c,u),c=n.sub(h,u),u=n.add(h,u),u=n.mul(c,u),c=n.mul(g,c),l=n.mul(r,l),f=n.mul(t,f),g=n.sub(d,f),g=n.mul(t,g),g=n.add(g,l),l=n.add(d,d),d=n.add(l,d),d=n.add(d,f),d=n.mul(d,g),u=n.add(u,d),f=n.mul(a,o),f=n.add(f,f),d=n.mul(f,g),c=n.sub(c,d),l=n.mul(f,h),l=n.add(l,l),l=n.add(l,l),new A(c,u,l)}add(t){y(t);const{X:e,Y:r,Z:i}=this,{X:a,Y:o,Z:c}=t;let u=n.ZERO,l=n.ZERO,d=n.ZERO;const h=s.a,f=n.mul(s.b,Fa);let g=n.mul(e,a),p=n.mul(r,o),w=n.mul(i,c),m=n.add(e,r),b=n.add(a,o);m=n.mul(m,b),b=n.add(g,p),m=n.sub(m,b),b=n.add(e,i);let v=n.add(a,c);return b=n.mul(b,v),v=n.add(g,w),b=n.sub(b,v),v=n.add(r,i),u=n.add(o,c),v=n.mul(v,u),u=n.add(p,w),v=n.sub(v,u),d=n.mul(h,b),u=n.mul(f,w),d=n.add(u,d),u=n.sub(p,d),d=n.add(p,d),l=n.mul(u,d),p=n.add(g,g),p=n.add(p,g),w=n.mul(h,w),b=n.mul(f,b),p=n.add(p,w),w=n.sub(g,w),w=n.mul(h,w),b=n.add(b,w),g=n.mul(p,b),l=n.add(l,g),g=n.mul(v,b),u=n.mul(m,u),u=n.sub(u,g),g=n.mul(m,p),d=n.mul(v,d),d=n.add(d,g),new A(u,l,d)}subtract(t){return this.add(t.negate())}is0(){return this.equals(A.ZERO)}multiply(t){const{endo:r}=e;if(!i.isValidNot0(t))throw new Error("invalid scalar: out of range");let n,s;const a=t=>x.cached(this,t,t=>Bi(A,t));if(r){const{k1neg:e,k1:i,k2neg:o,k2:c}=b(t),{p:u,f:l}=a(i),{p:d,f:h}=a(c);s=l.add(h),n=S(r.beta,u,d,e,o)}else{const{p:e,f:r}=a(t);n=e,s=r}return Bi(A,[n,s])[0]}multiplyUnsafe(t){const{endo:r}=e,n=this;if(!i.isValid(t))throw new Error("invalid scalar: out of range");if(t===xa||n.is0())return A.ZERO;if(t===Ca)return n;if(x.hasCache(this))return this.multiply(t);if(r){const{k1neg:e,k1:i,k2neg:s,k2:a}=b(t),{p1:o,p2:c}=function(t,e,r,n){let i=e,s=t.ZERO,a=t.ZERO;for(;r>Ui||n>Ui;)r&Ri&&(s=s.add(i)),n&Ri&&(a=a.add(i)),i=i.double(),r>>=Ri,n>>=Ri;return{p1:s,p2:a}}(A,n,i,a);return S(r.beta,o,c,e,s)}return x.unsafe(n,t)}toAffine(t){return v(this,t)}isTorsionFree(){const{isTorsionFree:t}=e;return a===Ca||(t?t(A,this):x.unsafe(this,o).is0())}clearCofactor(){const{clearCofactor:t}=e;return a===Ca?this:t?t(A,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(t=!0){return Yn(t,"isCompressed"),this.assertValidity(),d(A,this,t)}toHex(t=!0){return un(this.toBytes(t))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const T=i.BITS,x=new Hi(A,e.endo?Math.ceil(T/2):T);return A.BASE.precompute(8),A}function Pa(t){return Uint8Array.of(t?2:3)}function Ia(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Na(t,e,r={}){en(e),ui(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=(r=Object.assign({},r)).randomBytes||gn,i=r.hmac||((t,r)=>ba(e,t,r)),{Fp:s,Fn:a}=t,{ORDER:o,BITS:c}=a,{keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f}=function(t,e={}){const{Fn:r}=t,n=e.randomBytes||gn,i=Object.assign(Ia(t.Fp,r),{seed:Li(r.ORDER)});function s(t=n(i.seed)){return function(t,e,r=!1){tn(t);const n=t.length,i=Ni(e),s=Li(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const a=Ei(r?ri(t):ei(t),e-hi)+hi;return r?ii(a,i):ni(a,i)}(tn(t,i.seed,"seed"),r.ORDER)}function a(e,n=!0){return t.BASE.multiply(r.fromBytes(e)).toBytes(n)}function o(t){const{secretKey:e,publicKey:n,publicKeyUncompressed:s}=i;if(!Xr(t))return;if("_lengths"in r&&r._lengths||e===n)return;const a=tn(t,void 0,"key").length;return a===n||a===s}const c={isValidSecretKey:function(t){try{const e=r.fromBytes(t);return r.isValidNot0(e)}catch(t){return!1}},isValidPublicKey:function(e,r){const{publicKey:n,publicKeyUncompressed:s}=i;try{const i=e.length;return!(!0===r&&i!==n||!1===r&&i!==s||!t.fromBytes(e))}catch(t){return!1}},randomSecretKey:s},u=Ji(s,a);return Object.freeze({getPublicKey:a,getSharedSecret:function(e,n,i=!0){if(!0===o(e))throw new Error("first arg must be private key");if(!1===o(n))throw new Error("second arg must be public key");const s=r.fromBytes(e);return t.fromBytes(n).multiply(s).toBytes(i)},keygen:u,Point:t,utils:c,lengths:i})}(t,r),g={prehash:!0,lowS:"boolean"!=typeof r.lowS||r.lowS,format:"compact",extraEntropy:!1},p=o*ka<s.ORDER;function w(t){return t>o>>Ca}function m(t,e){if(!a.isValidNot0(e))throw new Error(`invalid signature ${t}: out of range 1..Point.Fn.ORDER`);return e}function y(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(t,e){Ea(e);const r=f.signature;return tn(t,"compact"===e?r:"recovered"===e?r+1:void 0)}class v{r;s;recovery;constructor(t,e,r){if(this.r=m("r",t),this.s=m("s",e),null!=r){if(y(),![0,1,2,3].includes(r))throw new Error("invalid recovery id");this.recovery=r}Object.freeze(this)}static fromBytes(t,e=g.format){let r;if(b(t,e),"der"===e){const{r:e,s:r}=Ta.toSig(tn(t));return new v(e,r)}"recovered"===e&&(r=t[0],e="compact",t=t.subarray(1));const n=f.signature/2,i=t.subarray(0,n),s=t.subarray(n,2*n);return new v(a.fromBytes(i),a.fromBytes(s),r)}static fromHex(t,e){return this.fromBytes(dn(t),e)}assertRecovery(){const{recovery:t}=this;if(null==t)throw new Error("invalid recovery id: must be present");return t}addRecoveryBit(t){return new v(this.r,this.s,t)}recoverPublicKey(e){const{r,s:n}=this,i=this.assertRecovery(),c=2===i||3===i?r+o:r;if(!s.isValid(c))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const u=s.toBytes(c),l=t.fromBytes(hn(Pa(!(1&i)),u)),d=a.inv(c),h=S(tn(e,void 0,"msgHash")),f=a.create(-h*d),g=a.create(n*d),p=t.BASE.multiplyUnsafe(f).add(l.multiplyUnsafe(g));if(p.is0())throw new Error("invalid recovery: point at infinify");return p.assertValidity(),p}hasHighS(){return w(this.s)}toBytes(t=g.format){if(Ea(t),"der"===t)return dn(Ta.hexFromSig(this));const{r:e,s:r}=this,n=a.toBytes(e),i=a.toBytes(r);return"recovered"===t?(y(),hn(Uint8Array.of(this.assertRecovery()),n,i)):hn(n,i)}toHex(t){return un(this.toBytes(t))}}const E=r.bits2int||function(t){if(t.length>8192)throw new Error("input is too large");const e=ei(t),r=8*t.length-c;return r>0?e>>BigInt(r):e},S=r.bits2int_modN||function(t){return a.create(E(t))},A=ci(c);function T(t){return oi("num < 2^"+c,t,xa,A),a.toBytes(t)}function x(t,r){return tn(t,void 0,"message"),r?tn(e(t),void 0,"prehashed message"):t}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:d,utils:h,lengths:f,Point:t,sign:function(r,s,o={}){const{seed:c,k2sig:u}=function(e,r,i){const{lowS:s,prehash:o,extraEntropy:c}=Sa(i,g);e=x(e,o);const u=S(e),l=a.fromBytes(r);if(!a.isValidNot0(l))throw new Error("invalid private key");const d=[T(l),T(u)];if(null!=c&&!1!==c){const t=!0===c?n(f.secretKey):c;d.push(tn(t,void 0,"extraEntropy"))}const h=hn(...d),m=u;return{seed:h,k2sig:function(e){const r=E(e);if(!a.isValidNot0(r))return;const n=a.inv(r),i=t.BASE.multiply(r).toAffine(),o=a.create(i.x);if(o===xa)return;const c=a.create(n*a.create(m+o*l));if(c===xa)return;let u=(i.x===o?0:2)|Number(i.y&Ca),d=c;return s&&w(c)&&(d=a.neg(c),u^=1),new v(o,d,p?void 0:u)}}}(r,s,o);return function(t,e,r){if(Qr(t,"hashLen"),Qr(e,"qByteLen"),"function"!=typeof r)throw new Error("hmacFn must be a function");const n=t=>new Uint8Array(t),i=Uint8Array.of(),s=Uint8Array.of(0),a=Uint8Array.of(1);let o=n(t),c=n(t),u=0;const l=()=>{o.fill(1),c.fill(0),u=0},d=(...t)=>r(c,hn(o,...t)),h=(t=i)=>{c=d(s,t),o=d(),0!==t.length&&(c=d(a,t),o=d())},f=()=>{if(u++>=1e3)throw new Error("drbg: tried max amount of iterations");let t=0;const r=[];for(;t<e;){o=d();const e=o.slice();r.push(e),t+=o.length}return hn(...r)};return(t,e)=>{let r;for(l(),h(t);!(r=e(f()));)h();return l(),r}}(e.outputLen,a.BYTES,i)(c,u).toBytes(o.format)},verify:function(e,r,n,i={}){const{lowS:s,prehash:o,format:c}=Sa(i,g);if(n=tn(n,void 0,"publicKey"),r=x(r,o),!Xr(e))throw new Error("verify expects Uint8Array signature"+(e instanceof v?", use sig.toBytes()":""));b(e,c);try{const i=v.fromBytes(e,c),o=t.fromBytes(n);if(s&&i.hasHighS())return!1;const{r:u,s:l}=i,d=S(r),h=a.inv(l),f=a.create(d*h),g=a.create(u*h),p=t.BASE.multiplyUnsafe(f).add(o.multiplyUnsafe(g));return!p.is0()&&a.create(p.x)===u}catch(t){return!1}},recoverPublicKey:function(t,e,r={}){const{prehash:n}=Sa(r,g);return e=x(e,n),v.fromBytes(t,"recovered").recoverPublicKey(e).toBytes()},Signature:v,hash:e})}const La={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ua={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ra=/* @__PURE__ */BigInt(2),Ma=Ii(La.p,{sqrt:function(t){const e=La.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,d=Si(l,r,e)*l%e,h=Si(d,r,e)*l%e,f=Si(h,Ra,e)*u%e,g=Si(f,i,e)*f%e,p=Si(g,s,e)*g%e,w=Si(p,o,e)*p%e,m=Si(w,c,e)*w%e,y=Si(m,o,e)*p%e,b=Si(y,r,e)*l%e,v=Si(b,a,e)*g%e,E=Si(v,n,e)*u%e,S=Si(E,Ra,e);if(!Ma.eql(Ma.sqr(S),t))throw new Error("Cannot find square root");return S}}),Ba=/* @__PURE__ */Na(/* @__PURE__ */Oa(La,{Fp:Ma,endo:Ua}),Kn);class _a{type="secp256k1";raw;_key;constructor(t){this._key=function(t){try{return Ba.Point.fromBytes(t),t}catch(t){throw new Yt(String(t))}}(t),this.raw=function(t){return Ba.Point.fromBytes(t).toBytes()}(this._key)}toMultihash(){return rr($a(this))}toCID(){return We.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(t){return null!=t&&t.raw instanceof Uint8Array&&nr(this.raw,t.raw)}verify(t,e,r){return function(t,e,r,n){const i=xr.digest(r instanceof Uint8Array?r:r.subarray());if(ms(i))return i.then(({digest:r})=>(n?.signal?.throwIfAborted(),Ba.verify(e,r,t,{prehash:!1,format:"der"}))).catch(t=>{if("AbortError"===t.name)throw t;throw new hs(String(t))});try{return n?.signal?.throwIfAborted(),Ba.verify(e,i.digest,t,{prehash:!1,format:"der"})}catch(t){throw new hs(String(t))}}(this._key,e,t,r)}}function $a(t){return wa.encode({Type:ga[t.type],Data:t.raw})}const Ga=Symbol.for("nodejs.util.inspect.custom");class ja{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ne]=!0;toString(){return null==this.string&&(this.string=ge.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return We.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(t){if(null==t)return!1;if(t instanceof Uint8Array)return nr(this.multihash.bytes,t);if("string"==typeof t)return this.toString()===t;if(null!=t?.toMultihash()?.bytes)return nr(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Ga](){return`PeerId(${this.toString()})`}}class qa extends ja{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}}class Va extends ja{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}}class za extends ja{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}}class Ha{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=rr(Pr(this.url))}[Ga](){return`PeerId(${this.url})`}[ne]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return We.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(t){return null!=t&&(t instanceof Uint8Array&&(t=Ir(t)),t.toString()===this.toString())}}function Ka(t,e){let r;if("1"===t.charAt(0)||"Q"===t.charAt(0))r=ze(ge.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return function(t){if(null==t?.multihash||null==t.version||1===t.version&&114!==t.code&&2336!==t.code)throw new Xt("Supplied PeerID CID is invalid");if(2336===t.code){const e=Ir(t.multihash.digest);return new Ha(new URL(e))}return Za(t.multihash)}(We.parse(t));if(null==e)throw new Wt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=ze(e.decode(t))}return Za(r)}function Za(t){if(function(t){return t.code===xr.code}(t))return new qa({multihash:t});if(function(t){return 0===t.code}(t))try{const e=function(t){const{Type:e,Data:r}=wa.decode(t.digest),n=r??new Uint8Array;switch(e){case ga.Ed25519:return i=bs(i=n,32),new ys(i);case ga.secp256k1:return function(t){return new _a(t)}(n);case ga.ECDSA:return function(t){return function(t){const e=t[1][1][0];let r,n;if(65===e.byteLength)return r=Ir(e.subarray(1,33),"base64url"),n=Ir(e.subarray(33),"base64url"),new Yr({...Kr,key_ops:["verify"],x:r,y:n});if(97===e.byteLength)return r=Ir(e.subarray(1,49),"base64url"),n=Ir(e.subarray(49),"base64url"),new Yr({...Zr,key_ops:["verify"],x:r,y:n});if(133===e.byteLength)return r=Ir(e.subarray(1,67),"base64url"),n=Ir(e.subarray(67),"base64url"),new Yr({...Jr,key_ops:["verify"],x:r,y:n});throw new Wt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}(Mr(t))}(n);default:throw new re}var i}(t);if("Ed25519"===e.type)return new Va({multihash:t,publicKey:e});if("secp256k1"===e.type)return new za({multihash:t,publicKey:e})}catch(e){const r=Ir(t.digest);return new Ha(new URL(r))}throw new Qt("Supplied PeerID Multihash is invalid")}function Ja(t,e){const r=L.fromHex(function(t){if("string"==typeof t)return t.startsWith("0x")?t:`0x${t}`;const e=t instanceof Uint8Array?t:Array.isArray(t)?Uint8Array.from(t):Uint8Array.from(Object.keys(t).sort((t,e)=>Number(t)-Number(e)).map(e=>t[Number(e)]));return`0x${Buffer.from(e).toString("hex")}`}(t)),n=U(r.toHex(),Buffer.from(e));return Buffer.from(n).toString("hex")}class Wa{getConsumerAddress(t){return po(t)}getSignature(t,e,r){return wo(t,e,r)}getAuthorization(t){return mo(t)}async getEndpoints(t,e){try{const r=await this.getData(t,e);return await r.json()}catch(t){throw at.error("Finding the service endpoints failed:",t),new Error("HTTP request failed calling Provider")}}async getNodePublicKey(t){return(await this.getEndpoints(t)).nodePublicKey}getEndpointURL(t,e){return t?t.find(t=>t.serviceName.toLowerCase()===e.toLowerCase()):null}async getServiceEndpoints(t,e){const r=[];for(const n in e.serviceEndpoints){const i={serviceName:n,method:e.serviceEndpoints[n][0],urlPath:t.replace(/\/+$/,"")+"/"+e.serviceEndpoints[n][1].replace(/^\/+/,"")};r.push(i)}return r}async getNonce(t,e,r,n,i){n||(n=await this.getEndpoints(t)),i||(i=await this.getServiceEndpoints(t,n));const s=this.getEndpointURL(i,"nonce")?this.getEndpointURL(i,"nonce").urlPath:null;if(!s)return null;try{const t=await O(s+`?userAddress=${e}`,{method:"GET",headers:{"Content-Type":"application/json"},signal:r}),{nonce:n}=await t.json();return n&&null!==n?Number(n):0}catch(t){throw at.error(t),new Error(t.message)}}async encrypt(t,e,r,n,i,s){const a=await this.getEndpoints(r),o=await this.getServiceEndpoints(r,a),c=await this.getConsumerAddress(n),u=(await this.getNonce(r,c,s,a,o)+1).toString(),l=await this.getSignature(n,u,W.ENCRYPT);let d=(this.getEndpointURL(o,"encrypt")?this.getEndpointURL(o,"encrypt").urlPath:null)+`?chainId=${e}`;if(!d)return null;d+=`&nonce=${u}`,d+=`&consumerAddress=${c}`,d+=`&signature=${l}`;try{const e=await O(d,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:s});return await e.text()}catch(t){throw at.error(t),new Error("HTTP request failed calling Provider")}}async checkDidFiles(t,e,r,n=!1,i){var s;const a=await this.getEndpoints(r),o=await this.getServiceEndpoints(r,a),c={did:t,serviceId:e,checksum:n},u=[],l=this.getEndpointURL(o,"fileinfo")?this.getEndpointURL(o,"fileinfo").urlPath:null;if(!l)return null;let d;try{d=await O(l,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw at.error("File info call failed: "),at.error(t),new Error(t)}if(null!=(s=d)&&s.ok){const t=await d.json();for(const e of t)u.push(e);return u}const h=await d.json();throw at.error("File info call failed: ",d.status,d.statusText,h),new Error(JSON.stringify(h))}async getFileInfo(t,e,r=!1,n){var i;const s=await this.getEndpoints(e),a=await this.getServiceEndpoints(e,s),o=et({},t,{checksum:r}),c=[],u=this.getEndpointURL(a,"fileinfo")?this.getEndpointURL(a,"fileinfo").urlPath:null;if(!u)return null;let l;try{l=await O(u,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw at.error("File info call failed: "),at.error(t),new Error(t)}if(null!=(i=l)&&i.ok){const t=await l.json();for(const e of t)c.push(e);return c}const d=await l.json();throw at.error("File info call failed: ",l.status,l.statusText,d),new Error(JSON.stringify(d))}async getComputeEnvironments(t,e){var r,n;const i=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,i),a=null==(r=this.getEndpointURL(s,"computeEnvironments"))?void 0:r.urlPath;if(!a)return null;let o;try{o=await O(a,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw at.error("Fetch compute env failed: "),at.error(t),new Error(t)}if(null!=(n=o)&&n.ok)return o.json();const c=await o.json();throw at.error("Fetch compute env failed: ",o.status,o.statusText,c),new Error(JSON.stringify(c))}async initialize(t,e,r,n,i,s,a,o,c){var u;const l=await this.getEndpoints(i),d=await this.getServiceEndpoints(i,l);let h,f=this.getEndpointURL(d,"initialize")?this.getEndpointURL(d,"initialize").urlPath:null;if(!f)return null;f+=`?documentId=${t}`,f+=`&serviceId=${e}`,f+=`&fileIndex=${r}`,f+=`&consumerAddress=${n}`,a&&(f+="&userdata="+encodeURI(JSON.stringify(a))),o&&(f+="&environment="+encodeURI(o)),c&&(f+="&validUntil="+c);try{h=await O(f,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})}catch(t){throw at.error("Provider initialized failed: "),at.error(t),new Error(`Provider initialize failed url: ${f} `)}if(200===(null==(u=h)?void 0:u.status))return await h.json();const g=await h.json();throw at.error("Provider initialized failed: ",h.status,h.statusText,g),new Error(JSON.stringify(g))}async initializeCompute(t,e,r,n,i,s,a,o,c,u,l){var d;const h=await this.getEndpoints(s),f=await this.getServiceEndpoints(s,h),g=this.getEndpointURL(f,"initializeCompute")?this.getEndpointURL(f,"initializeCompute").urlPath:null;if(!g)return null;const p={datasets:t,algorithm:e,environment:r,payment:{chainId:c,token:n,resources:o},maxJobDuration:i,consumerAddress:a};let w;u&&(p.policyServer=u);try{if(w=await O(g,{method:"POST",body:JSON.stringify(p),headers:{"Content-Type":"application/json"},signal:l}),!w.ok){const t=await w.text();throw new Error(`${t}`)}}catch(t){throw at.error("Initialize compute failed: "),at.error(t),new Error(`ComputeJob cannot be initialized: ${t.message}.`)}if(null!=(d=w)&&d.ok)return await w.json();const m=await w.json();throw at.error("Initialize compute failed: ",w.status,w.statusText,m),at.error("Payload was:",JSON.stringify(p)),new Error(JSON.stringify(m))}async getDownloadUrl(t,e,r,n,i,s,a,o){const c=await this.getEndpoints(i),u=await this.getServiceEndpoints(i,c),l=this.getEndpointURL(u,"download")?this.getEndpointURL(u,"download").urlPath:null;if(!l)return null;const d=await this.getConsumerAddress(s),h=(await this.getNonce(i,d,null,c,u)+1).toString(),f=await this.getSignature(s,h,W.DOWNLOAD);let g=l;return g+=`?fileIndex=${r}`,g+=`&documentId=${t}`,g+=`&transferTxId=${n}`,g+=`&serviceId=${e}`,g+=`&consumerAddress=${d}`,g+=`&nonce=${h}`,a&&(g+="&policyServer="+encodeURI(JSON.stringify(a))),g+=`&signature=${f}`,o&&(g+="&userdata="+encodeURI(JSON.stringify(o))),g}async computeStart(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p){var w;const m=await this.getEndpoints(t),y=await this.getServiceEndpoints(t,m),b=this.getEndpointURL(y,"computeStart")?this.getEndpointURL(y,"computeStart").urlPath:null;if(!b)return at.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const v=await this.getConsumerAddress(e),E=(await this.getNonce(t,v,f,m,y)+1).toString(),S=await this.getSignature(e,E,W.COMPUTE_START),A=Object();if(A.consumerAddress=v,A.signature=S,A.nonce=E,A.environment=r,A.maxJobDuration=s,A.resources=o,A.dataset=n[0],A.datasets=n,A.algorithm=i,A.chainId=c,A.payment={chainId:c,token:a,maxJobDuration:s,resources:o},p){const e=await this.getNodePublicKey(t);e&&(A.dockerRegistryAuth=Ja(e,JSON.stringify(p)))}if(o&&(A.resources=o),u&&(A.metadata=u),l&&(A.additionalViewers=l),d){const e=await this.getNodePublicKey(t);e&&(A.output=Ja(e,JSON.stringify(d)))}let T;h&&(A.policyServer=h),g&&(A.queueMaxWaitTime=g);try{T=await O(b,{method:"POST",body:JSON.stringify(A),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:f})}catch(t){throw at.error("Compute start failed:"),at.error(t),at.error("Payload was:",A),new Error("HTTP request failed calling Provider")}if(null!=(w=T)&&w.ok)return await T.json();const x=await T.json();throw at.error("Compute start failed: ",T.status,T.statusText,x),at.error("Payload was:",A),new Error(JSON.stringify(x))}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,d,h){var f;const g=await this.getEndpoints(t),p=await this.getServiceEndpoints(t,g),w=this.getEndpointURL(p,"freeCompute")?this.getEndpointURL(p,"freeCompute").urlPath:null;if(!w)return at.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const m=await this.getConsumerAddress(e),y=(await this.getNonce(t,m,l,g,p)+1).toString(),b=await this.getSignature(e,y,W.FREE_COMPUTE_START),v=Object();if(v.consumerAddress=m,v.signature=b,v.nonce=y,v.environment=r,v.resources=s,v.dataset=n[0],v.datasets=n,v.algorithm=i,a&&(v.metadata=a),o&&(v.additionalViewers=o),h){const e=await this.getNodePublicKey(t);e&&(v.dockerRegistryAuth=Ja(e,JSON.stringify(h)))}if(c){const e=await this.getNodePublicKey(t);e&&(v.output=Ja(e,JSON.stringify(c)))}let E;u&&(v.policyServer=u),d&&(v.queueMaxWaitTime=d);try{E=await O(w,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:l})}catch(t){throw at.error("Compute start failed:"),at.error(t),at.error("Payload was:",v),new Error("HTTP request failed calling Provider")}if(null!=(f=E)&&f.ok)return await E.json();const S=await E.json();throw at.error("Compute start failed: ",E.status,E.statusText,S),at.error("Payload was:",v),new Error(JSON.stringify(S))}async computeStreamableLogs(t,e,r,n){var i,s;const a="string"==typeof e,o=await this.getEndpoints(t),c=await this.getServiceEndpoints(t,o),u=this.getEndpointURL(c,"computeStreamableLogs")?this.getEndpointURL(c,"computeStreamableLogs").urlPath:null;if(!u)return at.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null;const l=await this.getConsumerAddress(e),d=(await this.getNonce(t,l,n,o,c)+1).toString();let h,f=`?consumerAddress=${l}&jobId=${r}`;a||(f+=`&signature=${await this.getSignature(e,d,W.COMPUTE_GET_STREAMABLE_LOGS)}`,f+=`&nonce=${d}`);try{h=await O(u+f,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:n})}catch(t){throw at.error("computeStreamableLogs failed:"),at.error(t),new Error("HTTP request failed calling Provider")}return null!=(i=h)&&i.ok||200===(null==(s=h)?void 0:s.status)?h.body:(at.error("computeStreamableLogs failed: ",h.status,h.statusText,await h.json()),null)}async computeStop(t,e,r,n,i){var s;const a="string"==typeof r,o=await this.getEndpoints(e),c=await this.getServiceEndpoints(e,o),u=this.getEndpointURL(c,"computeStop")?this.getEndpointURL(c,"computeStop").urlPath:null,l=await this.getConsumerAddress(r),d=(await this.getNonce(e,l,i,o,c)+1).toString(),h=await this.getSignature(r,d,W.COMPUTE_STOP),f=new URLSearchParams;f.set("consumerAddress",l),f.set("nonce",d),f.set("jobId",t),a||f.set("signature",h),n&&f.set("agreementId",n);const g=f.toString();if(!g)return null;let p;try{p=await O(u+"?"+g,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(r)},signal:i})}catch(t){throw at.error("Compute stop failed:"),at.error(t),new Error("HTTP request failed calling Provider")}if(null!=(s=p)&&s.ok)return await p.json();const w=await p.json();throw at.error("Compute stop failed: ",p.status,p.statusText,w),new Error(JSON.stringify(w))}async computeStatus(t,e,r,n,i){var s,a;const o=await po(e),c=mo(e),u=await this.getEndpoints(t),l=await this.getServiceEndpoints(t,u),d=this.getEndpointURL(l,"computeStatus")?this.getEndpointURL(l,"computeStatus").urlPath:null;let h,f=`?consumerAddress=${o}`;if(f+=n&&`&agreementId=${n}`||"",f+=r&&`&jobId=${r}`||"",!d)return null;try{h=await O(d+f,{method:"GET",headers:{"Content-Type":"application/json",Authorization:c},signal:i})}catch(t){throw at.error("Get compute status failed"),at.error(t),new Error(t)}if(null!=(s=h)&&s.ok)return await h.json();if(at.error("Get compute status failed:",h.status,h.statusText),null!=(a=h)&&a.ok)return await h.json();const g=await h.json();throw at.error("Get compute status failed:",h.status,h.statusText,g),new Error(JSON.stringify(g))}async getComputeResultUrl(t,e,r,n){const i="string"==typeof e,s=await this.getEndpoints(t),a=await this.getServiceEndpoints(t,s),o=this.getEndpointURL(a,"computeResult")?this.getEndpointURL(a,"computeResult").urlPath:null,c=await this.getConsumerAddress(e),u=(await this.getNonce(t,c,null,s,a)+1).toString(),l=await this.getSignature(e,u,W.COMPUTE_GET_RESULT);if(!o)return null;let d=o;return d+=`?consumerAddress=${c}`,d+=`&jobId=${r}`,d+=`&index=${n.toString()}`,i||(d+=`&nonce=${u}`,d+=`&signature=${l}`),d}async getComputeResult(t,e,r,n,i=0){const s=await this.getComputeResultUrl(t,e,r,n);if(!s)throw new Error("Could not retrieve compute result URL");const a=await O(s,{headers:i>0?{Range:`bytes=${i}-`}:{}});if(!a.ok)throw new Error(`Failed to fetch compute result: ${a.status}`);return a.body}async generateAuthToken(t,e,r){const n=await t.getAddress(),i=await this.getEndpoints(e),s=await this.getServiceEndpoints(e,i),a=this.getEndpointURL(s,"generateAuthToken").urlPath||null,o=(await this.getNonce(e,n,r,i,s)+1).toString(),c=await this.getSignature(t,o,W.CREATE_AUTH_TOKEN);try{const t=await O(a,{method:"POST",body:JSON.stringify({address:n,signature:c,nonce:o}),headers:{"Content-Type":"application/json"},signal:r});if(null==t||!t.ok)throw new Error(`Failed to generate auth token: ${t.status} ${t.statusText}`);const e=await t.json();return null==e?void 0:e.token}catch(t){throw at.error("Generate auth token failed:"),at.error(t),new Error("HTTP request failed calling Provider")}}async invalidateAuthToken(t,e,r,n){const i=await t.getAddress(),s=await this.getEndpoints(r),a=await this.getServiceEndpoints(r,s),o=this.getEndpointURL(a,"invalidateAuthToken").urlPath||null,c=(await this.getNonce(r,i,n,s,a)+1).toString(),u=i+c,l=await Jt(t,u);try{const t=await O(o,{method:"POST",body:JSON.stringify({address:i,signature:l,token:e,nonce:c}),headers:{"Content-Type":"application/json"},signal:n});if(null==t||!t.ok)throw new Error(`Failed to invalidate auth token: ${t.status} ${t.statusText}`);return await t.json()}catch(t){throw at.error("Generate auth token failed:"),at.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const r=await O(t,{method:"GET",headers:{"Content-Type":"application/json"},signal:e});if(null!=r&&r.ok){const t=await r.json();if(t&&(t.providerAddress||t.providerAddresses))return!0}return!1}catch(t){return at.error(`Error validating provider: ${t.message}`),!1}}async PolicyServerPassthrough(t,e,r){var n;const i=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,i),a=this.getEndpointURL(s,"PolicyServerPassthrough")?this.getEndpointURL(s,"PolicyServerPassthrough").urlPath:null;if(!a)return null;let o;try{if(o=await O(a,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:r}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw at.error("PolicyServerPassthrough failed: "),at.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(n=o)&&n.ok)return await o.json();const c=await o.json();throw at.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),at.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async initializePSVerification(t,e,r){var n;const i=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,i),a=this.getEndpointURL(s,"initializePSVerification")?this.getEndpointURL(s,"initializePSVerification").urlPath:null;if(!a)return null;let o;try{if(o=await O(a,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:r}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw at.error("initializePSVerification failed: "),at.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(n=o)&&n.ok)return await o.json();const c=await o.json();throw at.error("initializePSVerification failed: ",o.status,o.statusText,c),at.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async downloadNodeLogs(t,e,r,n,i,s,a,o,c){var u;const l=await this.getEndpoints(t),d=await this.getServiceEndpoints(t,l),h=this.getEndpointURL(d,"logs")?this.getEndpointURL(d,"logs").urlPath:null;if(!h)return at.error("Download node logs failed: Cannot get proper logs route (perhaps not implemented on provider?)"),null;const f=await e.getAddress(),g=(await this.getNonce(t,f,c,l,d)+1).toString(),p=await this.getSignature(e,g,W.GET_LOGS);let w,m=h+`?startTime=${r}&endTime=${n}`;i&&(m+=`&maxLogs=${i}`),s&&(m+=`&moduleName=${s}`),a&&(m+=`&level=${a}`),o&&(m+=`&page=${o}`);try{w=await O(m,{method:"POST",body:JSON.stringify({signature:p,nonce:g,address:f}),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw at.error("Download node logs failed:"),at.error(t),new Error("HTTP request failed calling Provider")}if(null!=(u=w)&&u.ok)return w.body;const y=await w.json();throw at.error("Download node logs failed: ",w.status,w.statusText,y),new Error(JSON.stringify(y))}noZeroX(t){return this.zeroXTransformer(t,!1)}zeroXTransformer(t="",e){const{valid:r,output:n}=this.inputMatch(t,/^(?:0x)*([a-f0-9]+)$/i,"zeroXTransformer");return(e&&r?"0x":"")+n}inputMatch(t,e,r){if("string"!=typeof t)throw at.debug("Not input string:"),at.debug(t),new Error(`[${r}] Expected string, input type: ${typeof t}`);const n=t.match(e);return n?{valid:!0,output:n[1]}:(at.warn(`[${r}] Input transformation failed.`),{valid:!1,output:t})}async resolveDdo(t,e,r){const n=t+"/api/aquarius/assets/ddo/"+e,i=await O(n,{method:"GET",headers:{"Content-Type":"application/json"},signal:r});return i.ok?i.json():null}async validateDdo(t,e,r,n){var i;const s=await r.getAddress(),a=await(await this.getData(`${t}/api/services/nonce?userAddress=${s}`)).json(),o=(Number(null!=(i=a.nonce)?i:0)+1).toString(),c=s+o+W.VALIDATE_DDO,u=await Jt(r,c),l=await O(`${t}/api/aquarius/assets/ddo/validate`,{method:"POST",body:JSON.stringify({ddo:e,publisherAddress:s,nonce:o,signature:u}),headers:{"Content-Type":"application/json"},signal:n});if(!l.ok)return null;const d=await l.json();return{valid:!0,hash:d.hash,proof:{validatorAddress:d.publicKey,r:d.r[0],s:d.s[0],v:d.v}}}async getData(t,e){return O(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}class Ya extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,Ya)}}const Xa=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Qa(t,e,r){"function"==typeof r&&(r={filter:r});const n=function(t,e,r){let n;const i=new Promise((i,s)=>{if(!((r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r}).count>=0)||r.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(r.count))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const a=[e].flat(),o=[],{addListener:c,removeListener:u}=(t=>{const e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}})(t),l=async(...t)=>{const e=r.multiArgs?t:t[0];if(r.filter)try{if(!await r.filter(e))return}catch(t){return n(),void s(t)}o.push(e),r.count===o.length&&(n(),i(o))},d=(...t)=>{n(),s(r.rejectionMultiArgs?t:t[0])};n=()=>{for(const t of a)u(t,l);for(const t of r.rejectionEvents)a.includes(t)||u(t,d)};for(const t of a)c(t,l);for(const t of r.rejectionEvents)a.includes(t)||c(t,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&i(o)});if(i.cancel=n,"number"==typeof r.timeout){const t=function(t,e){const{milliseconds:r,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout},signal:a}=e;let o,c;const u=new Promise((e,u)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(a?.aborted)return void u(Xa(a));if(a&&(c=()=>{u(Xa(a))},a.addEventListener("abort",c,{once:!0})),t.then(e,u),r===Number.POSITIVE_INFINITY)return;const l=new Ya;o=s.setTimeout.call(void 0,()=>{if(n)try{e(n())}catch(t){u(t)}else"function"==typeof t.cancel&&t.cancel(),!1===i?e():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${r} milliseconds`,u(l))},r)}).finally(()=>{u.clear(),c&&a&&a.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},u}(i,{milliseconds:r.timeout});return t.cancel=()=>{n(),t.clear()},t}return i}(t,e,r={...r,count:1,resolveImmediately:!1}),i=n.then(t=>t[0]);return i.cancel=n.cancel,i}function to(t){return t.reason}async function eo(t,e,r){if(null==e)return t;const n=r?.translateError??to;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([t,new Promise((t,r)=>{i=()=>{r(n(e))},e.addEventListener("abort",i)})])}finally{null!=i&&e.removeEventListener("abort",i)}}class ro{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(t,e={}){this.components=t,this.started=!1,this.protocol=`/${e.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=e.timeout??1e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??1,this.runOnLimitedConnection=e.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[ie]=["@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(t,e){const r=t.log.newScope("ping");r.trace("ping from %p",e.remotePeer);const n=AbortSignal.timeout(this.timeout);n.addEventListener("abort",()=>{t.abort(new ee("Ping timed out"))});const i=Date.now();for await(const e of t){if("open"!==t.status){r("stream status changed to %s",t.status);break}t.send(e)||(r("waiting for stream to drain"),await Qa(t,"drain",{rejectionEvents:["close"],signal:n}),r("stream drained"))}r("ping from %p complete in %dms",e.remotePeer,Date.now()-i),await t.close({signal:n})}async ping(t,e={}){const r=function(){if(isNaN(32))throw new Wt("random bytes length must be a Number bigger than 0");return gn(32)}(),n=await this.components.connectionManager.openStream(t,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...e}),i=n.log.newScope("ping");try{const t=Date.now(),i=Promise.withResolvers(),s=new lr,a=o=>{if(s.append(o.data),32===s.byteLength){n.removeEventListener("message",a);const o=Date.now()-t;Promise.all([n.closeRead(e)]).then(()=>{if(!nr(r,s.subarray()))throw new te(`Received wrong ping ack after ${o}ms`);i.resolve(o)}).catch(t=>{n.abort(t),i.reject(t)})}};return n.addEventListener("message",a),n.send(r),await n.close(e),await eo(i.promise,e.signal)}catch(e){throw i.error("error while pinging %o - %e",t,e),n?.abort(e),e}finally{n?.close()}}}function no(t={}){return e=>new ro(e,t)}class io extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class so extends Error{static name="UnwrappedError";name="UnwrappedError"}class ao extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class oo extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class co extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function uo(t){return function(t){return"function"==typeof t?.closeRead}(t)?"writable"!==t.remoteWriteStatus&&0===t.readBufferLength:!!function(t){return"function"==typeof t?.close}(t)&&"open"!==t.status}const lo="/ocean/nodes/1.0.0",ho=1e4,fo=["/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"];class go{constructor(){this.p2pConfig={},this.libp2pNode=null,this.discoveredNodes=new Map}async setupP2P(t){this.p2pConfig=t,this.discoveredNodes.clear(),this.libp2pNode&&(Promise.resolve(this.libp2pNode.stop()).catch(()=>{}),this.libp2pNode=null),await this.getOrCreateLibp2pNode()}async getMultiaddrFromPeerId(t){const e=t=>t.includes("/p2p/")?t:`${t}/p2p/${t}`,r=await this.getOrCreateLibp2pNode(),n=r.getConnections().find(e=>e.remotePeer.toString()===t);if(null!=n&&n.remoteAddr)return e(n.remoteAddr.toString());const i=this.discoveredNodes.get(t);if(i&&i.length>0)return e(i[0]);const s=r.services.dht;var a,o=!1,c=!1;try{for(var u,l=function(t){var e,r,n,i=2;for("undefined"!=typeof Symbol&&(r=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(r&&null!=(e=t[r]))return e.call(t);if(n&&null!=(e=t[n]))return new Q(e.call(t));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}(s.findPeer(Ka(t),{signal:AbortSignal.timeout(2e4)}));o=!(u=await l.next()).done;o=!1){const t=u.value;if(t.type===V.FINAL_PEER&&t.peer.multiaddrs.length>0)return e(t.peer.multiaddrs[0].toString())}}catch(t){c=!0,a=t}finally{try{o&&null!=l.return&&await l.return()}finally{if(c)throw a}}throw new Error(`No multiaddrs found for peer id ${t}`)}getDiscoveredNodes(){return Array.from(this.discoveredNodes.entries()).map(([t,e])=>({peerId:t,multiaddrs:e}))}bufToHex(t){var e;if("string"==typeof t)try{t=JSON.parse(t)}catch(e){return t}return"Buffer"===(null==(e=t)?void 0:e.type)&&Array.isArray(t.data)?Buffer.from(t.data).toString():t instanceof Uint8Array||Buffer.isBuffer(t)?Buffer.from(t).toString():t}async getOrCreateLibp2pNode(){var t;if(this.libp2pNode)return this.libp2pNode;const e=(null!=(t=this.p2pConfig.bootstrapPeers)?t:fo).map(I),r=await R(et({addresses:{listen:[]},transports:[_(),G(),...this.p2pConfig.enableTcp?[$()]:[]],connectionEncrypters:[M()],streamMuxers:[B()],peerDiscovery:[...e.length>0?[j({list:e.map(String),timeout:1e4})]:[]],services:{identify:q(),ping:no(),dht:z({protocol:"/ocean/nodes/1.0.0/kad/1.0.0",clientMode:!0})},connectionManager:{maxConnections:100},connectionMonitor:{abortConnectionOnPingFailure:!1}},this.p2pConfig.libp2p));return await r.start(),r.addEventListener("peer:discovery",t=>{var e;const n=t.detail;if(null==n||!n.id)return;const i=n.id.toString();this.discoveredNodes.set(i,(null!=(e=n.multiaddrs)?e:[]).map(t=>t.toString())),r.getConnections().length<100&&0===r.getConnections(n.id).length&&r.dial(n.id,{signal:AbortSignal.timeout(1e4)}).catch(t=>{at.debug(`Failed to dial discovered peer ${i}: ${t.message}`)})}),this.libp2pNode=r,r}toUint8Array(t){return t instanceof Uint8Array?t:t.subarray()}isDialable(t){return"undefined"==typeof window||t.toString().includes("/tls/sni")}peerIdFromMultiaddr(t){const e=t.toString().split("/p2p/");return e.length>1?e[e.length-1]:null}async getConnection(t,e){const r=await this.getOrCreateLibp2pNode();if(Array.isArray(t)){const n=t.filter(t=>this.isDialable(t));if(n.length>0){at.debug(`[P2P] dial array: ${n.length} dialable addrs`);try{const t=await r.dial(n,{signal:e});return at.debug(`[P2P] dial array SUCCESS via ${t.remoteAddr}`),t}catch(t){at.debug(`[P2P] dial array failed: ${t.message}`)}}for(const n of t){const t=this.peerIdFromMultiaddr(n);if(t)return at.debug(`[P2P] Not multiaddrs, fallback to peerId: ${t}`),this.dialByPeerId(r,t,e)}throw new Error("No valid addresses and no peer ID in multiaddrs")}try{const n=I(t);if(this.isDialable(n)){at.debug(`[P2P] dial single addr: ${n}`);try{const t=await r.dial(n,{signal:e});return at.debug(`[P2P] dial single SUCCESS via ${t.remoteAddr}`),t}catch(t){at.debug(`[P2P] dial single failed: ${t.message}`)}}const i=this.peerIdFromMultiaddr(n);if(i)return at.debug(`[P2P] single fallback -> dialByPeerId ${i}`),this.dialByPeerId(r,i,e);throw new Error(`Cannot dial address: ${t}`)}catch(t){var n;if(null!=(n=t.message)&&n.includes("Cannot dial"))throw t}return at.debug(`[P2P] bare peerId -> dialByPeerId ${t}`),this.dialByPeerId(r,t,e)}async dialByPeerId(t,e,r){const n=Ka(e),i=t.getConnections(n).filter(t=>"open"===t.status);if(i.length>0)return at.debug(`[P2P] ${e}: reusing existing connection via ${i[0].remoteAddr}`),i[0];if(0===t.getConnections().length){at.debug(`[P2P] ${e}: no connections yet, waiting for bootstrap...`),await Ht(3e3);const r=t.getConnections(n);if(r.length>0)return at.debug(`[P2P] ${e}: connected during bootstrap wait`),r[0]}const s=new Set,a=[],o=t=>{const e=t.toString();s.has(e)||(s.add(e),a.push(t))},c=this.discoveredNodes.get(e);if(c){for(const t of c)try{o(I(t))}catch(t){}at.debug(`[P2P] ${e}: ${c.length} cached addrs`)}const u=a.filter(t=>this.isDialable(t));if(0===u.length){at.debug(`[P2P] ${e}: no cached dialable addrs, querying DHT...`);try{var l;const r=AbortSignal.timeout(null!=(l=this.p2pConfig.dhtLookupTimeout)?l:6e4),i=await t.peerRouting.findPeer(n,{signal:r});for(const t of i.multiaddrs)o(t);at.debug(`[P2P] ${e}: DHT returned ${i.multiaddrs.length} addrs`)}catch(t){at.debug(`[P2P] ${e}: DHT findPeer failed: ${t.message}`)}}else at.debug(`[P2P] ${e}: ${u.length} cached dialable addrs, skipping DHT`);const d=a.filter(t=>this.isDialable(t)).map(t=>{const r=t.toString();return r.includes("/p2p/")?t:I(`${r}/p2p/${e}`)});if(at.debug(`[P2P] ${e}: ${d.length}/${a.length} addrs are dialable`),d.length>0){at.debug(`[P2P] ${e}: dialing ${d.map(String)}`);try{const n=await t.dial(d,{signal:r});return at.debug(`[P2P] ${e}: SUCCESS via ${n.remoteAddr} (limited=${null!=n.limits})`),n}catch(t){at.debug(`[P2P] ${e}: direct dial failed: ${t.message}`)}}at.debug(`[P2P] ${e}: last resort dial by peerId`);try{const r=await t.dial(n,{signal:AbortSignal.timeout(1e4)});return at.debug(`[P2P] ${e}: peerId dial SUCCESS via ${r.remoteAddr} (limited=${null!=r.limits})`),r}catch(r){throw new Error(`Cannot reach peer ${e}. `+(a.length>0?`Found addrs: ${a.map(String).join(", ")} (none browser-dialable). `:"No addresses found. ")+`Active connections: ${t.getConnections().length}.`)}}getConsumerAddress(t){return po(t)}getSignature(t,e,r){return wo(t,e,r)}async getNodePublicKey(t){const e=await this.getEndpoints(t);return null==e?void 0:e.nodePublicKey}getAuthorization(t){return mo(t)}async dialAndStream(t,e,r){var n;const i=null!=r?r:AbortSignal.timeout(null!=(n=this.p2pConfig.dialTimeout)?n:ho),s=await this.getConnection(t,i);try{const t=await s.newStream(lo,{signal:i,runOnLimitedConnection:!0}),r=function(t,e={}){const r=function(t,e){const r=e?.maxBufferSize??4194304,n=new lr;let i,s=!1;if(a=t,null==a?.addEventListener||null==a?.removeEventListener||null==a?.send||null==a?.push||null==a?.log)throw new Wt("Argument should be a Stream or a Multiaddr");var a;const o=t=>{if(n.append(t.data),n.byteLength>r){const t=n.byteLength;n.consume(n.byteLength),i?.reject(new Error(`Read buffer overflow - ${t} > ${r}`))}i?.resolve()};t.addEventListener("message",o);const c=t=>{null!=t.error?i?.reject(t.error):i?.resolve()};t.addEventListener("close",c);const u=()=>{i?.resolve()};t.addEventListener("remoteCloseWrite",u);const l={readBuffer:n,async read(e){if(!0===s)throw new so("Stream was unwrapped");if(uo(t)){if(0===n.byteLength&&null==e?.bytes)return null;if(null!=e?.bytes&&n.byteLength<e.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,e.bytes),new io(`Unexpected EOF - stream closed after reading ${n.byteLength}/${e.bytes} bytes`)}const r=e?.bytes??1;for(i=Promise.withResolvers();;){if(n.byteLength>=r){i.resolve();break}if(await eo(i.promise,e?.signal),uo(t)){if(0===n.byteLength&&null==e?.bytes)return null;break}i=Promise.withResolvers()}const a=e?.bytes??n.byteLength;if(n.byteLength<a){if(uo(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,a),new io(`Unexpected EOF - stream closed while reading ${n.byteLength}/${a} bytes`);return l.read(e)}const o=n.sublist(0,a);return n.consume(a),o},async write(e,r){if(!0===s)throw new so("Stream was unwrapped");t.send(e)||await Qa(t,"drain",{signal:r?.signal,rejectionEvents:["close"]})},unwrap:()=>(s||(s=!0,t.removeEventListener("message",o),t.removeEventListener("close",c),t.removeEventListener("remoteCloseWrite",u),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t)};return l}(t,e);null!=e.maxDataLength&&null==e.maxLengthLength&&(e.maxLengthLength=Ds(e.maxDataLength));const n=e?.lengthDecoder??Ns,i=e?.lengthEncoder??Is;return{async read(i){let s=-1;const a=new lr;for(;;){const t=await r.read({...i,bytes:1});if(null==t)break;a.append(t);try{s=n(a)}catch(t){if(t instanceof RangeError)continue;throw t}if(s<0)throw new ao("Invalid message length");if(null!=e?.maxLengthLength&&a.byteLength>e.maxLengthLength)throw new co(`Message length length too long - ${a.byteLength} > ${e.maxLengthLength}`);if(s>-1)break}if(null!=e?.maxDataLength&&s>e.maxDataLength)throw new oo(`Message length too long - ${s} > ${e.maxDataLength}`);const o=await r.read({...i,bytes:s});if(null==o)throw t.log.error("tried to read %d bytes but the stream closed",s),new io(`Unexpected EOF - tried to read ${s} bytes but the stream closed`);if(o.byteLength!==s)throw t.log.error("read %d/%d bytes before the stream closed",o.byteLength,s),new io(`Unexpected EOF - read ${o.byteLength}/${s} bytes before the stream closed`);return o},async write(t,e){await r.write(new lr(i(t.byteLength),t),e)},async writeV(t,e){const n=new lr(...t.flatMap(t=>[i(t.byteLength),t]));await r.write(n,e)},unwrap:()=>r.unwrap()}}(t);await r.write((new TextEncoder).encode(JSON.stringify(e)),{signal:i}),await t.close();const n=await r.read({signal:i});return{lp:r,firstBytes:this.toUint8Array(n),connection:s}}catch(t){try{s.abort(new Error("stream failed"))}catch(t){}throw t}}async sendP2pCommand(t,e,r,n,i,s=0){try{var a,o;const l=et({command:e,authorization:n?this.getAuthorization(n):void 0},r),{lp:d,firstBytes:h}=await this.dialAndStream(t,l,i);if(!h.length)throw new Error("Gateway node error: no response from peer");const f=(new TextDecoder).decode(h);try{const t=JSON.parse(f);var c;if("number"==typeof(null==t?void 0:t.httpStatus)&&t.httpStatus>=400)throw new Error(null!=(c=t.error)?c:`Gateway node error: ${t.httpStatus}`)}catch(t){}if(e===W.COMPUTE_GET_STREAMABLE_LOGS||e===W.COMPUTE_GET_RESULT)return rt(function*(){try{for(;;){const t=yield tt(d.read({signal:AbortSignal.timeout(ho)}));yield t instanceof Uint8Array?t:t.subarray()}}catch(t){if(!(t instanceof io))throw t}})();const g=[h];try{for(;;){var u;const t=await d.read({signal:AbortSignal.timeout(null!=(u=this.p2pConfig.dialTimeout)?u:ho)});g.push(this.toUint8Array(t))}}catch(t){if(!(t instanceof io))throw t}let p;for(let t=0;t<g.length;t++){const e=(new TextDecoder).decode(g[t]);try{p=JSON.parse(e)}catch(e){p=g[t]}}const w=p;if("number"==typeof(null==w?void 0:w.httpStatus)&&w.httpStatus>=400)throw new Error("string"==typeof w.error?w.error:JSON.stringify(w.error));return(null!=(a="string"==typeof p?p:null==w?void 0:w.error)?a:"").includes("Cannot connect to peer")&&s<(null!=(o=this.p2pConfig.maxRetries)?o:5)?(await new Promise(t=>{var e;return setTimeout(t,null!=(e=this.p2pConfig.retryDelay)?e:1e3)}),this.sendP2pCommand(t,e,r,n,i,s+1)):p}catch(a){var l,d;const o=null!=(l=null==a?void 0:a.message)?l:"";if((o.includes("closed")||o.includes("reset"))&&s<(null!=(d=this.p2pConfig.maxRetries)?d:5))return at.debug(`[P2P] Stream reset/closed on attempt ${s+1}, retrying...`),await Ht(1e3),this.sendP2pCommand(t,e,r,n,i,s+1);throw new Error(`P2P command error: ${o}`)}}async getEndpoints(t){try{return await this.sendP2pCommand(t,W.STATUS,{})}catch(t){throw at.error("P2P getEndpoints (STATUS) failed:",t),t}}async getNonce(t,e,r){try{var n,i;const s=await this.sendP2pCommand(t,W.NONCE,{address:e},null,r),a="number"==typeof s?s:null!=(n=null!=(i=null==s?void 0:s.nonce)?i:s)?n:0;return a&&null!==a?Number(a):0}catch(t){throw at.error("P2P getNonce failed:",t),t}}async encrypt(t,e,r,n,i,s){const a=await this.getConsumerAddress(n),o=(await this.getNonce(r,a,s)+1).toString(),c=await this.getSignature(n,o,W.ENCRYPT),u=await this.sendP2pCommand(r,W.ENCRYPT,{chainId:e,nonce:o,consumerAddress:a,signature:c,blob:"string"==typeof t?t:JSON.stringify(t)},n,s);return this.bufToHex(u)}async checkDidFiles(t,e,r,n=!1,i){const s=await this.sendP2pCommand(r,W.FILE_INFO,{did:t,serviceId:e,checksum:n},null,i);return Array.isArray(s)?s:[s]}async getFileInfo(t,e,r=!1,n){const i=await this.sendP2pCommand(e,W.FILE_INFO,{file:t,type:t.type,checksum:r},null,n);return Array.isArray(i)?i:[i]}async getComputeEnvironments(t,e){const r=await this.sendP2pCommand(t,W.COMPUTE_GET_ENVIRONMENTS,{},null,e);return Array.isArray(r)?r:[r]}async initialize(t,e,r,n,i,s,a,o,c){const u={ddoId:t,serviceId:e,consumerAddress:n};return a&&(u.userdata=a),o&&(u.environment=o),c&&(u.validUntil=c),this.sendP2pCommand(i,W.GET_FEES,u,null,s)}async initializeCompute(t,e,r,n,i,s,a,o,c,u,l){const d={datasets:t,algorithm:e,environment:r,payment:{chainId:c,token:n,resources:o},maxJobDuration:i,consumerAddress:a};return u&&(d.policyServer=u),this.sendP2pCommand(s,W.COMPUTE_INITIALIZE,d,null,l)}async getDownloadUrl(t,e,r,n,i,s,a,o){const c=await this.getConsumerAddress(s),u=(await this.getNonce(i,c)+1).toString(),l=await this.getSignature(s,u,W.DOWNLOAD),d={command:W.DOWNLOAD,authorization:this.getAuthorization(s),fileIndex:r,documentId:t,transferTxId:n,serviceId:e,consumerAddress:c,nonce:u,signature:l};a&&(d.policyServer=a),o&&(d.userData=o);const{lp:h,firstBytes:f}=await this.dialAndStream(i,d),g=(new TextDecoder).decode(f);let p=null;try{p=JSON.parse(g)}catch(t){}var w;if(p&&"number"==typeof p.httpStatus&&p.httpStatus>=400)throw new Error(null!=(w=p.error)?w:`P2P download error: ${p.httpStatus}`);const m=null===p?[Buffer.from(f)]:[];try{for(;;){var y;const t=await h.read({signal:AbortSignal.timeout(null!=(y=this.p2pConfig.dialTimeout)?y:ho)});m.push(Buffer.from(this.toUint8Array(t)))}}catch(t){if(!(t instanceof io))throw t}const b=Buffer.concat(m);return{data:b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength),filename:`file${r}`}}async computeStart(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p){const w=await this.getConsumerAddress(e),m=(await this.getNonce(t,w,f)+1).toString(),y=await this.getSignature(e,m,W.COMPUTE_START),b={environment:r,dataset:n[0],datasets:n,algorithm:i,maxJobDuration:s,feeToken:a,resources:o,chainId:c,payment:{chainId:c,token:a,maxJobDuration:s,resources:o},consumerAddress:w,nonce:m,signature:y};if(u&&(b.metadata=u),l&&(b.additionalViewers=l),h&&(b.policyServer=h),g&&(b.queueMaxWaitTime=g),p){const e=await this.getNodePublicKey(t);e&&(b.dockerRegistryAuth=Ja(e,JSON.stringify(p)))}if(d){const e=await this.getNodePublicKey(t);e&&(b.output=Ja(e,JSON.stringify(d)))}const v=await this.sendP2pCommand(t,W.COMPUTE_START,b,e,f);return Array.isArray(v),v}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,d,h){const f=await this.getConsumerAddress(e),g=(await this.getNonce(t,f,l)+1).toString(),p=await this.getSignature(e,g,W.FREE_COMPUTE_START),w={environment:r,dataset:n[0],datasets:n,algorithm:i,resources:s,consumerAddress:f,nonce:g,signature:p};if(a&&(w.metadata=a),o&&(w.additionalViewers=o),u&&(w.policyServer=u),d&&(w.queueMaxWaitTime=d),h){const e=await this.getNodePublicKey(t);e&&(w.dockerRegistryAuth=Ja(e,JSON.stringify(h)))}if(c){const e=await this.getNodePublicKey(t);e&&(w.output=Ja(e,JSON.stringify(c)))}const m=await this.sendP2pCommand(t,W.FREE_COMPUTE_START,w,e,l);return Array.isArray(m),m}async computeStreamableLogs(t,e,r,n){if("string"==typeof e)return this.sendP2pCommand(t,W.COMPUTE_GET_STREAMABLE_LOGS,{jobId:r},e,n);const i=await this.getConsumerAddress(e),s=(await this.getNonce(t,i,n)+1).toString(),a=await this.getSignature(e,s,W.COMPUTE_GET_STREAMABLE_LOGS);return this.sendP2pCommand(t,W.COMPUTE_GET_STREAMABLE_LOGS,{jobId:r,consumerAddress:i,nonce:s,signature:a},e,n)}async computeStop(t,e,r,n,i){const s=await this.getConsumerAddress(r),a=(await this.getNonce(e,s,i)+1).toString(),o={jobId:t,consumerAddress:s,nonce:a,signature:await this.getSignature(r,a,W.COMPUTE_STOP)};return n&&(o.agreementId=n),this.sendP2pCommand(e,W.COMPUTE_STOP,o,r,i)}async computeStatus(t,e,r,n,i){const s={consumerAddress:await this.getConsumerAddress(e)};return r&&(s.jobId=r),n&&(s.agreementId=n),this.sendP2pCommand(t,W.COMPUTE_GET_STATUS,s,e,i)}async getComputeResult(t,e,r,n,i=0){var s;const a=await this.getConsumerAddress(e),o={command:W.COMPUTE_GET_RESULT,jobId:r,index:n,offset:i,consumerAddress:a};if("string"==typeof e)o.authorization=e;else{const r=(await this.getNonce(t,a)+1).toString();o.nonce=r,o.signature=await this.getSignature(e,r,W.COMPUTE_GET_RESULT)}const{lp:c,firstBytes:u}=await this.dialAndStream(t,o),l=JSON.parse((new TextDecoder).decode(u));var d;if("number"==typeof(null==l?void 0:l.httpStatus)&&l.httpStatus>=400)throw new Error(null!=(d=l.error)?d:`P2P compute result error: ${l.httpStatus}`);const h=null!=(s=this.p2pConfig.dialTimeout)?s:ho;return rt(function*(){try{for(;;){const t=yield tt(c.read({signal:AbortSignal.timeout(h)}));yield t instanceof Uint8Array?t:t.subarray()}}catch(t){if(!(t instanceof io))throw t}})()}async getComputeResultUrl(t,e,r,n){const i=await this.getConsumerAddress(e);return await this.sendP2pCommand(t,W.COMPUTE_GET_RESULT,{jobId:r,index:n,consumerAddress:i},e)}async generateAuthToken(t,e,r){var n;const i=await t.getAddress(),s=(await this.getNonce(e,i,r)+1).toString(),a=await this.getSignature(t,s,W.CREATE_AUTH_TOKEN),o=await this.sendP2pCommand(e,W.CREATE_AUTH_TOKEN,{address:i,signature:a,nonce:s},null,r);return null!=(n=null==o?void 0:o.token)?n:o}async resolveDdo(t,e,r){return this.sendP2pCommand(t,W.GET_DDO,{id:e},null,r)}async validateDdo(t,e,r,n){var i,s,a,o;const c=await r.getAddress(),u=(await this.getNonce(t,c,n)+1).toString(),l=c+u+W.VALIDATE_DDO,d=await Jt(r,l),h=await this.sendP2pCommand(t,W.VALIDATE_DDO,{ddo:e,publisherAddress:c,nonce:u,signature:d},null,n);return!h||h.error?null:{valid:!0,hash:this.bufToHex(h.hash),proof:{validatorAddress:this.bufToHex(h.publicKey),r:this.bufToHex(null!=(i=null==(s=h.r)?void 0:s[0])?i:h.r),s:this.bufToHex(null!=(a=null==(o=h.s)?void 0:o[0])?a:h.s),v:h.v}}}async invalidateAuthToken(t,e,r,n){const i=await t.getAddress(),s=(await this.getNonce(r,i,n)+1).toString(),a=i+s,o=await Jt(t,a);return this.sendP2pCommand(r,W.INVALIDATE_AUTH_TOKEN,{address:i,signature:o,token:e,nonce:s},null,n)}async isValidProvider(t,e){try{const r=await this.sendP2pCommand(t,W.STATUS,{},null,e);return!(!r||!(r.address||r.providerAddress||r.providerAddresses))}catch(t){return!1}}async PolicyServerPassthrough(t,e,r){return this.sendP2pCommand(t,W.POLICY_SERVER_PASSTHROUGH,et({},e),null,r)}async initializePSVerification(t,e,r){return this.sendP2pCommand(t,W.POLICY_SERVER_PASSTHROUGH,et({},e),null,r)}async downloadNodeLogs(t,e,r,n,i,s,a,o,c){const u=await e.getAddress(),l=(await this.getNonce(t,u,c)+1).toString(),d={startTime:r,endTime:n,signature:await this.getSignature(e,l,W.GET_LOGS),nonce:l,address:u};return i&&(d.maxLogs=i),s&&(d.moduleName=s),a&&(d.level=a),o&&(d.page=o),this.sendP2pCommand(t,W.GET_LOGS,d,e,c)}async fetchConfig(t,e){return this.sendP2pCommand(t,W.FETCH_CONFIG,e)}async pushConfig(t,e){return this.sendP2pCommand(t,W.PUSH_CONFIG,e)}}async function po(t){return"string"==typeof t?function(t){try{return N.decode(t,{json:!0})}catch(t){throw new Error("Error decoding JWT")}}(t).address:t.getAddress()}async function wo(t,e,r){if("string"==typeof t)return null;const n=String(String(await t.getAddress())+String(e)+String(r));return Jt(t,n)}function mo(t){return"string"==typeof t?t:void 0}function yo(t){if(Array.isArray(t))return!0;if(!t)return!1;try{return I(t),!0}catch(t){}try{return Ka(t),!0}catch(t){return!1}}class bo{constructor(){this.httpProvider=new Wa,this.p2pProvider=new go}getImpl(t){return Array.isArray(t)||yo(t)?this.p2pProvider:this.httpProvider}async getNonce(t,e,r,n,i){return this.getImpl(t).getNonce(t,e,r,n,i)}async encrypt(t,e,r,n,i,s){return this.getImpl(r).encrypt(t,e,r,n,i,s)}async checkDidFiles(t,e,r,n=!1,i){return this.getImpl(r).checkDidFiles(t,e,r,n,i)}async getFileInfo(t,e,r=!1,n){return this.getImpl(e).getFileInfo(t,e,r,n)}async getComputeEnvironments(t,e){return this.getImpl(t).getComputeEnvironments(t,e)}async initialize(t,e,r,n,i,s,a,o,c){return this.getImpl(i).initialize(t,e,r,n,i,s,a,o,c)}async initializeCompute(t,e,r,n,i,s,a,o,c,u,l){return this.getImpl(s).initializeCompute(t,e,r,n,i,s,a,o,c,u,l)}async getDownloadUrl(t,e,r,n,i,s,a,o){return this.getImpl(i).getDownloadUrl(t,e,r,n,i,s,a,o)}async computeStart(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p){return this.getImpl(t).computeStart(t,e,r,n,i,s,a,o,c,u,l,d,h,f,g,p)}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,d,h){return this.getImpl(t).freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,d,h)}async computeStreamableLogs(t,e,r,n){return this.getImpl(t).computeStreamableLogs(t,e,r,n)}async computeStop(t,e,r,n,i){return this.getImpl(e).computeStop(t,e,r,n,i)}async computeStatus(t,e,r,n,i){return this.getImpl(t).computeStatus(t,e,r,n,i)}async getComputeResultUrl(t,e,r,n){return this.getImpl(t).getComputeResultUrl(t,e,r,n)}async getComputeResult(t,e,r,n,i=0){return this.getImpl(t).getComputeResult(t,e,r,n,i)}async generateAuthToken(t,e,r){return this.getImpl(e).generateAuthToken(t,e,r)}async invalidateAuthToken(t,e,r,n){return this.getImpl(r).invalidateAuthToken(t,e,r,n)}async resolveDdo(t,e,r){return this.getImpl(t).resolveDdo(t,e,r)}async validateDdo(t,e,r,n){return this.getImpl(t).validateDdo(t,e,r,n)}async isValidProvider(t,e){return this.getImpl(t).isValidProvider(t,e)}async PolicyServerPassthrough(t,e,r){return this.getImpl(t).PolicyServerPassthrough(t,e,r)}async initializePSVerification(t,e,r){return this.getImpl(t).initializePSVerification(t,e,r)}async downloadNodeLogs(t,e,r,n,i,s,a,o,c){return this.getImpl(t).downloadNodeLogs(t,e,r,n,i,s,a,o,c)}async setupP2P(t){return this.p2pProvider.setupP2P(t)}getDiscoveredNodes(){return this.p2pProvider.getDiscoveredNodes()}async getMultiaddrFromPeerId(t){return this.p2pProvider.getMultiaddrFromPeerId(t)}async fetchConfig(t,e){return this.p2pProvider.fetchConfig(t,e)}async pushConfig(t,e){return this.p2pProvider.pushConfig(t,e)}}const vo=new bo;class Eo{constructor(t){this.aquariusURL=void 0,this.aquariusURL=t}async resolve(t,e,r){if(yo(this.aquariusURL)){const r=await vo.resolveDdo(this.aquariusURL,t,e);if(r)return r;throw new Error("P2P request failed")}const n=this.aquariusURL+"/api/aquarius/assets/ddo/"+t;try{const t=await O(n,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:e});if(t.ok)return await t.json();throw new Error("HTTP request failed with status "+t.status)}catch(t){throw at.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,r,n=3e4,i=100,s){let a=0;i>500&&(at.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);const o=yo(this.aquariusURL);do{try{let n;if(o)n=await vo.resolveDdo(this.aquariusURL,t,r);else{const e=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,i=await O(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:s},signal:r});i.ok&&(n=await i.json())}if(n){const t=P.getDDOClass(n),{indexedMetadata:r}=t.getAssetFields();if(!e)return n;if(r.event&&r.event.txid===e)return n}}catch(t){}await Ht(n),a++}while(a<i);return null}async validate(t,e,r,n,i){if(yo(r))return vo.validateDdo(r,t,e,n);const s=r+"/api/aquarius/assets/ddo/validate",a=r+"/api/services/nonce";try{const r=await e.getAddress(),o=await O(a+`?userAddress=${r}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:i},signal:n});let{nonce:c}=await o.json();c&&null!==c||(c="0");const u=(Number(c)+1).toString(),l=String(String(await e.getAddress())+String(u)+String(W.VALIDATE_DDO)),d={ddo:t,publisherAddress:r,nonce:u,signature:await Jt(e,l)},h=await O(s,{method:"POST",body:JSON.stringify(d),headers:{"Content-Type":"application/json",Authorization:mo(e)},signal:n}),f=await h.json();if(200!==h.status)throw new Error("Metadata validation failed");return{valid:!0,hash:f.hash,proof:{validatorAddress:f.publicKey,r:f.r[0],s:f.s[0],v:f.v}}}catch(t){at.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,r){const n=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await O(n,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:e});if(t.ok)return t.json();throw new Error("getAssetMetadata failed: "+t.status+t.statusText)}catch(t){throw at.error("Error getting metadata: ",t),new Error("Error getting metadata: "+t)}}async querySearch(t,e,r){const n=this.aquariusURL+"/api/aquarius/assets/query";try{const i=await O(n,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:r},signal:e});if(i.ok)return i.json();throw new Error("querySearch failed: "+i.status+i.statusText)}catch(t){throw at.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}function So(t,e){return t=l(t),`did:op:${H(t+e.toString(10)).toString()}`}function Ao(t){return H(t).toString()}function To(t){const e=new XMLHttpRequest;e.responseType="blob",e.open("GET",t),e.onload=()=>{const t=e.getResponseHeader("content-disposition"),r=null==t?void 0:t.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/),n=r&&r[1]?r[1]:"file",i=window.URL.createObjectURL(e.response),s=document.createElement("a");s.href=i,s.setAttribute("download",n),document.body.appendChild(s),s.click(),s.remove(),window.URL.revokeObjectURL(i)},e.send()}async function xo(t,e){if("string"!=typeof t)return t;const r=await fetch(t);if(!r.ok)throw new Error("Response error.");let n;try{n=r.headers.get("content-disposition").match(/attachment;filename=(.+)/)[1]}catch(r){try{n=t.split("/").pop()}catch(t){n=`file${e}`}}return{data:await r.arrayBuffer(),filename:n}}async function Co(t,e,n,i,s,a,o=!1,c,u){const l=new r.Contract(i,ht,t);if(!o){const e=await Do(t,i,n,s);if(new w(e).greaterThanOrEqualTo(new w(a)))return new w(e).toNumber()}const d=await Et(t,i,a,c),h=await l.approve.estimateGas(s,d);return u?new w(h.toString()):await At(h,t,null==e?void 0:e.gasFeeMultiplier,l.approve,s,d)}async function ko(t,e,n,i,s,a,o=!1,c){const u=new r.Contract(i,ht,t);if(!o){const e=await Po(t,i,n,s);if(new p(e).isGreaterThan(new p(a)))return BigInt(e)}let l=null;const d=await u.approve.estimateGas(s,a);if(c)return d;try{l=await At(d,t,null==e?void 0:e.gasFeeMultiplier,u.approve,s,a)}catch(t){at.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return l}async function Fo(t,e,n,i,s,a,o){const c=new r.Contract(n,ht,t),u=await Et(t,n,s,a),l=await c.transfer.estimateGas(i,u);return o?l:await At(l,t,null==e?void 0:e.gasFeeMultiplier,c.transfer,i,u)}async function Do(t,e,n,i,s){const a=new r.Contract(e,ht,t),o=await a.allowance(n,i);return await vt(t,e,o,s)}async function Oo(t,e,n,i){const s=new r.Contract(e,ht,t),a=await s.balanceOf(n);return await vt(t,e,a,i)}async function Po(t,e,n,i){const s=new r.Contract(e,ht,t);return await s.allowance(n,i)}async function Io(t,e){const n=new r.Contract(e,ht,t),i=await n.decimals();return Number(i)}const No={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 Lo(t){try{const r=JSON.parse(t),n=Object.keys(r)[0];if("error"===n){var e;const t=r[n];return(null==(e=No[n])?void 0:e[t])||`Provider request failed: ${t}`}{const t=r[n];return`${r[Object.keys(r)[1]]} : ${t}`}}catch(e){return at.error("[getErrorMessage] error: ",e),t}}async function Uo(t,e,r,n,i,s,a,o,c="0",u=0,l=0,d=0){const h=P.getDDOClass(t),{datatokens:f}=h.getAssetFields(),{chainId:g,services:p}=h.getDDOFields();a||(a={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"});const m=(await e.provider.getNetwork()).chainId;if(g!==Number(m))throw new Error("Chain ID from DDO is different than the configured network.");if(!f[u].address)throw new Error(`The datatoken with index: ${u} does not exist for the asset with did: ${t.id}`);if(!p[l].id)throw new Error(`There is no service with index: ${l} defined for the asset with did: ${t.id}`);const y=await n.getId(f[u].address),b=await n.getFixedRates(f[u].address),v=await n.getDispensers(f[u].address),E=await n.getPublishingMarketFee(f[u].address),S=b.length>0?"fixed":v.length>0?"free":"NOT_ALLOWED",A=o||(await vo.initialize(t.id,p[l].id,0,await e.getAddress(),i||r.oceanNodeUri)).providerFee;if(A&&A.providerFeeAddress!==kt&&A.providerFeeAmount&&parseInt(A.providerFeeAmount)>0)try{await ko(e,r,await e.getAddress(),A.providerFeeToken,p[0].datatokenAddress,A.providerFeeAmount)}catch(t){throw new Error(`Failed to approve provider fee token ${A.providerFeeToken}`)}const T={consumer:s||await e.getAddress(),serviceIndex:l,_providerFee:A,_consumeMarketFee:a};switch(S){case"free":if(1===y){const t=new Ct(r.dispenserAddress,e),i=await t.dispense(f[u].address,"1",await e.getAddress());if(!i)throw new Error("Failed to dispense !");return await i.wait(),await n.startOrder(f[u].address,T.consumer,T.serviceIndex,T._providerFee,T._consumeMarketFee)}if(2===y||4===y)return await n.buyFromDispenserAndOrder(p[l].datatokenAddress,T,r.dispenserAddress);break;case"fixed":{const i=new Pt(r.fixedRateExchangeAddress,e);if(!b[d].id)throw new Error(`There is no fixed rate exchange with index: ${l} for the asset with did: ${t.id}`);const s=await i.getFeesInfo(b[d].id),o=await i.getExchange(b[d].id),{baseTokenAmount:h}=await i.calcBaseInGivenDatatokensOut(s.exchangeId,"1",a.consumeMarketFeeAmount),g=new w(+h||0).add(new w(a.consumeMarketFeeAmount||0)).add(new w(+E.publishMarketFeeAmount||0)).toString(),p={exchangeContract:r.fixedRateExchangeAddress,exchangeId:s.exchangeId,maxBaseTokenAmount:g,baseTokenAddress:o.baseToken,baseTokenDecimals:parseInt(o.btDecimals)||18,swapMarketFee:c,marketFeeAddress:E.publishMarketFeeAddress};if(1===y){const t=await Co(e,r,await e.getAddress(),o.baseToken,r.fixedRateExchangeAddress,g,!1);if(!("number"!=typeof t?await t.wait():t))throw new Error(`Failed to approve ${o.baseToken} !`);const s=await i.buyDatatokens(o.exchangeId,"1",g,E.publishMarketFeeAddress,c);if(!await s.wait())throw new Error("Failed to buy datatoken from fixed rate!");return await n.startOrder(f[u].address,T.consumer,T.serviceIndex,T._providerFee,T._consumeMarketFee)}if(2===y||4===y){const t=await Co(e,r,await e.getAddress(),o.baseToken,f[u].address,g,!1);if(!t)throw new Error(`Failed to approve ${o.baseToken} !`);if(!("number"!=typeof t?await t.wait():t))throw new Error("Failed to confirm/mine approval transaction!");return await n.buyFromFreAndOrder(f[u].address,T,p)}break}default:throw new Error("Pricing schema not supported !")}}const Ro=8996;function Mo(t){const e=(new dt).getConfig(t);return e&&"oasis"===e.sdk}async function Bo(t,e,n,i,s,o,u=!0,l,d,h,g,p,w,m,y){var b,v;const E=P.getDDOClass(o),{indexedMetadata:S}=E.getAssetFields(),A=(null==(b=E.getDDOData())||null==(b=b.stats)||null==(b=b.price)?void 0:b.value)||(null==S||null==(v=S.stats[0])||null==(v=v.prices[0])?void 0:v.price);let{chainId:T,nftAddress:C}=E.getDDOFields();const{services:k}=E.getDDOFields();if("string"!=typeof s&&"number"!=typeof s)throw new Error('Invalid template! Must be a "number" or a "string"');const F=(await n.provider.getNetwork()).chainId;if(T&&T!==Number(F))throw new Error("Chain ID from DDO is different than the configured network.");const D=(new dt).getConfig(parseInt(String(F)));let O=await Bt(n,D.nftFactoryAddress,s,Number(F));if(O<1){if(8996!==Number(F))throw new Error(`Invalid template index: ${O}`);O=1}const I=new _t(n,Number(F)),N=new Ut(D.nftFactoryAddress,n,Number(F)),L=await n.getAddress(),U={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:L},R={templateIndex:O,cap:"100000",feeAmount:"0",paymentCollector:L,feeToken:d||D.oceanTokenAddress,minter:L,mpFeeAddress:kt},M={nftAddress:"0x0",datatokenAddress:"0x0",files:i};let B;"oasis"===D.sdk&&(R.filesObject=M,R.accessListFactory=g||D.accessListFactory,R.allowAccessList=p,R.denyAccessList=w);try{if(A)if("0"===A.toString()){const t={dispenserAddress:D.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:kt};B=await N.createNftWithDatatokenWithDispenser(U,R,t)}else{const t=m||D.oceanTokenAddress;y||(y=await bt(this.signer,t));const e={fixedRateAddress:D.fixedRateExchangeAddress,baseTokenAddress:t,owner:L,marketFeeCollector:L,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:A.toString(),marketFee:"0",allowedConsumer:L,withMint:!0};B=await N.createNftWithDatatokenWithFixedRate(U,R,e)}else B=await N.createNftWithDatatoken(U,R)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const _=await B.wait(),$=St(_,"NFTCreated"),G=St(_,"TokenCreated"),j=$.args.newTokenAddress,q=G.args.newTokenAddress;if(M.datatokenAddress=q,M.nftAddress=j,"oasis"===D.sdk){const t=new r.Contract(q,x.abi,n);try{const e=await t.setFilesObject(a(JSON.stringify(M)));e.wait&&await e.wait()}catch(t){return console.log("Error updating files object with data token and nft addresses: ",t),null}}k[0].files="oasis"===D.sdk?"":await vo.encrypt(M,Number(F),l,n,null),k[0].datatokenAddress=q,k[0].serviceEndpoint=l,C=j;const V=E.makeDid(C,T.toString());let z,H,Z;if(o=E.updateFields({id:V,nftAddress:C}),u)z=await vo.encrypt(o,Number(F),l,n,null),H=(await h.validate(o,n,l)).hash,Z=2;else{const t=JSON.stringify(o),e=Buffer.from(t);z=c(e),H="0x"+K("sha256").update(z).digest("hex"),Z=0}return await I.setMetadata(C,await n.getAddress(),0,l,"",f(Z),z,H),o.id}async function _o(t,e,n){const i=new r.Contract(t,k.abi,e),s=await e.getAddress();try{const t=await i.deployAccessListContract("AllowList","ALLOW",!0,s,n||[s],["https://oceanprotocol.com/nft/"]);if(t&&t.wait)return St(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{jt as AccessListContract,qt as AccesslistFactory,Eo as Aquarius,Y as Config,dt as ConfigHelper,Ro as DEVELOPMENT_CHAIN_ID,$t as Datatoken,Gt as Datatoken4,Ct as Dispenser,J as EncryptMethod,zt as EnterpriseFeeCollectorContract,Vt as EscrowContract,Ot as FEE_HISTORY_NOT_SUPPORTED,Z as FileObjectType,Pt as FixedRateExchange,Ft as GASLIMIT_DEFAULT,ut as KNOWN_CONFIDENTIAL_EVMS,it as LogLevel,st as Logger,at as LoggerInstance,Dt as MAX_UINT_256,_t as Nft,Ut as NftFactory,lo as OCEAN_P2P_PROTOCOL,W as PROTOCOL_COMMANDS,bo as Provider,vo as ProviderInstance,It as Router,Tt as SmartContract,xt as SmartContractWithAddress,kt as ZERO_ADDRESS,Do as allowance,Po as allowanceWei,Et as amountToUnits,Co as approve,ko as approveWei,Oo as balance,Bt as calculateActiveTemplateIndex,ct as configHelperNetworks,_o as createAccessListFactory,Bo as createAsset,Io as decimals,xo as downloadFile,To as downloadFileBrowser,So as generateDid,Lt as generateDtName,Lo as getErrorMessage,St as getEventFromTx,yt as getFairGasPrice,Ao as getHash,lt as getNodeEndpointConfig,Rt as getOceanArtifactsAddresses,Mt as getOceanArtifactsAddressesByChainId,bt as getTokenDecimals,Kt as isDefined,yo as isP2pUri,ht as minAbi,Uo as orderAsset,At as sendTx,mt as setContractDefaults,Zt as signHash,Jt as signRequest,Ht as sleep,Fo as transfer,vt as unitsToAmount,Mo as useOasisSDK};
4
4
  //# sourceMappingURL=lib.modern.js.map