@oceanprotocol/lib 7.0.0-next.0 → 7.0.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -5
- package/ComputeExamples.md +1 -1
- package/dist/lib.cjs +3 -3
- package/dist/lib.cjs.map +1 -1
- package/dist/lib.modern.js +3 -3
- package/dist/lib.modern.js.map +1 -1
- package/dist/lib.module.mjs +3 -3
- package/dist/lib.module.mjs.map +1 -1
- package/dist/lib.umd.js +3 -3
- package/dist/lib.umd.js.map +1 -1
- package/dist/types/services/providers/BaseProvider.d.ts +30 -29
- package/dist/types/services/providers/HttpProvider.d.ts +1 -1
- package/dist/types/services/providers/P2pProvider.d.ts +33 -32
- package/package.json +3 -2
package/dist/lib.modern.js
CHANGED
|
@@ -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 h,getBytes as d,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 O from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import F from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import D from"cross-fetch";import{DDOManager as I}from"@oceanprotocol/ddo-js";import{allocUnsafe as N,alloc as L}from"uint8arrays/alloc";import{concat as P}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 B from"jsonwebtoken";import{PublicKey as _,encrypt as G}from"eciesjs";import{createLibp2p as j}from"libp2p";import{noise as $}from"@chainsafe/libp2p-noise";import{yamux as V}from"@chainsafe/libp2p-yamux";import{webSockets as q}from"@libp2p/websockets";import{tcp as z}from"@libp2p/tcp";import{bootstrap as H}from"@libp2p/bootstrap";import{identify as K}from"@libp2p/identify";import{kadDHT as Z}from"@libp2p/kad-dht";import{multiaddr as J}from"@multiformats/multiaddr";import W from"crypto-js/sha256.js";import{createHash as Y}from"crypto";var X,Q;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave",t.S3="s3",t.FTP="ftp"}(X||(X={})),function(t){t.AES="AES",t.ECIES="ECIES"}(Q||(Q={}));const tt={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 et{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 rt(t,e){this.v=t,this.k=e}function nt(t){return new rt(t,0)}function it(){return it=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},it.apply(null,arguments)}function st(t){return function(){return new at(t.apply(this,arguments))}}function at(t){var e,r;function n(e,r){try{var s=t[e](r),a=s.value,o=a instanceof rt;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 ot;at.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},at.prototype.next=function(t){return this._invoke("next",t)},at.prototype.throw=function(t){return this._invoke("throw",t)},at.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"}(ot||(ot={}));class ct{constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||ot.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",ot.Verbose,...t)}log(...t){this.dispatch("log",ot.Log,...t)}warn(...t){this.dispatch("warn",ot.Warn,...t)}error(...t){this.dispatch("error",ot.Error,...t)}dispatch(t,e,...r){this.logLevel>=e&&console[t](...r)}}const ut=new ct,lt={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},ht=[it({},lt),it({},lt,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),it({},lt,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),it({},lt,{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"}),it({},lt,{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"}),it({},lt,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),it({},lt,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),it({},lt,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),it({},lt,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),it({},lt,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),it({},lt,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),it({},lt,{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"}),it({},lt,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),it({},lt,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),it({},lt,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),it({},lt,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),it({},lt,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],dt=[23294,23295],ft=()=>process.env.NODE_ENDPOINT||process.env.NODE_URL?{oceanNodeUri:process.env.NODE_ENDPOINT||process.env.NODE_URL}:{};class gt{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:h,Escrow:d,EnterpriseFeeCollector:f}=r[e];n=it({nftFactoryAddress:s,opfCommunityFeeCollector:a,fixedRateExchangeAddress:t,dispenserAddress:i,oceanTokenAddress:o,routerFactoryAddress:l,chainId:c,startBlock:u,accessListFactory:h,escrow:d,EnterpriseFeeCollector:f},ft())}else if(t[e]){const{FixedPrice:r,Dispenser:i,OPFCommunityFeeCollector:s,ERC721Factory:a,Ocean:o,chainId:c,startBlock:u,Router:l,AccessListFactory:h,Escrow:d,EnterpriseFeeCollector:f}=t[e];n=it({nftFactoryAddress:a,opfCommunityFeeCollector:s,fixedRateExchangeAddress:r,dispenserAddress:i,oceanTokenAddress:o,routerFactoryAddress:l,chainId:c,startBlock:u,accessListFactory:h,escrow:d,EnterpriseFeeCollector:f},ft())}return n}getConfig(t,r){const n="string"==typeof t?"network":"chainId";let i,s=ht.find(e=>e[n]===t);if(!s)return ut.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&&dt.includes(s.chainId)&&(a=this.getAddressesFromEnv(s.network.replace("sapph","saph"),i)),"sdk"in s&&null!==s.sdk||(s.sdk=dt.includes(s.chainId)?"oasis":"evm"),a&&"accessListFactory"in a&&(s.accessListFactory=a.accessListFactory),s=it({},s,a),it({},s,{nodeUri:r?`${s.nodeUri}/${r}`:s.nodeUri})}}const pt=[{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"}],wt=3e10,mt=4e9,yt=1e10,bt=11155111;function vt(t,e){return t}async function Et(t,e){const r=(await t.provider.getFeeData()).gasPrice,n=BigInt(r.toString());return e?(n*BigInt(e)).toString(10):n.toString()}async function St(t,e){return new r.Contract(e,pt,t).decimals()}async function At(t,e,r,i){let s=i||await St(t,e);return"0"===s&&(s=18),n(r,s).toString()}async function Tt(t,e,r,n){let s=n||await St(t,e);return"0"===s&&(s=18),i(r,s).toString()}function xt(t,e){if(t&&t.logs)return t.logs.filter(t=>t instanceof s&&t.eventName===e)[0]}async function kt(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)<wt?wt:Number(s)===bt&&Number(t)<mt?mt:dt.includes(Number(s))&&Number(t)<yt?yt:Number(t),maxFeePerGas:(80001===Number(s)||137===Number(s))&&Number(e)<wt?wt:Number(s)===bt&&Number(e)<mt?mt:dt.includes(Number(s))&&Number(e)<yt?yt: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 ut.error("Send tx error: ",t),null}}class Ct{constructor(t,e,r,n){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=r||(new gt).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 Tt(this.signer,t,e,r)}async unitsToAmount(t,e,r){return At(this.signer,t,e,r)}async getFairGasPrice(){var t;return Et(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 vt(new r.Contract(t,new r.Interface(JSON.stringify(e||this.abi)),this.signer))}}class Ot extends Ct{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 Ft extends Ot{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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 Dt="0x0000000000000000000000000000000000000000",It=1e6,Nt="115792089237316195423570985008687907853269984665640564039457584007913129639934",Lt="Returned error: Method eth_feeHistory not supported.";class Pt extends Ot{getDefaultAbi(){return y.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,r,n=Dt,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)),h=await this.contract.buyDT.estimateGas(t,u,l,n,c);return s?h:await kt(h,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.buyDT,t,u,l,n,c)}async sellDatatokens(t,e,r,n=Dt,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)),h=await this.contract.sellDT.estimateGas(t,u,l,n,c);return s?h:await kt(h,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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class Ut extends Ot{getDefaultAbi(){return b.abi}async buyDatatokenBatch(t,e){var r;const n=await this.contract.buyDTBatch.estimateGas(t);return e?n:await kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(o,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.updateOPCFee,e,r,n,i)}}var Rt={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 Mt(t){const e=t||Rt,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 Bt extends Ot{getDefaultAbi(){return A.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:r}=Mt();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,Dt,Dt,t.tokenURI,t.transferable,t.owner);if(e)return r;try{var n;const e=await kt(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,Dt,Dt,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 xt(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===Dt)throw new Error("Template cannot be ZERO address");const i=await this.contract.add721TokenTemplate.estimateGas(e);return r?i:await kt(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 kt(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 kt(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===Dt)throw new Error("Template cannot be address ZERO");const i=await this.contract.addTokenTemplate.estimateGas(e);return r?i:await kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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}=Mt());let n=18;if(t.feeToken!==Dt)try{n=await St(this.signer,t.feeToken)}catch(t){ut.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=Dt);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 _t(){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 Gt(t){try{const e=_t();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 jt(t,e,n,i){const s="number"==typeof n,a=new Bt(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 Ct{getDefaultAbi(){return S.abi}async createDatatoken(t,e,r,n,i,s,o,c,u,l,h,d,f,g,p,w){var m;if(!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not DatatokenDeployer");h||(h=1),u&&l||({name:u,symbol:l}=Mt());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=Gt(Number(b));d&&(h=await jt(this.signer,v.ERC721Factory,4,Number(b)));const E=await y.createERC20.estimateGas(h,[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():Dt),S.push(p||Dt));const A=await kt(E,this.getSignerAccordingSdk(),null==(m=this.config)?void 0:m.gasFeeMultiplier,y.createERC20,h,[u,l],S,[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],d?[a(d)]:[]),T=xt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 h=this.getContract(t);if(c||(c=[]),!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");let d=n;if(null!=n&&n.includes("/p2p/")){var f;const t=n.match(/\/p2p\/([^/]+)/);d=null!=(f=null==t?void 0:t[1])?f:n}const g=await h.setMetaData.estimateGas(r,d,i,s,a,o,c);return u?g:await kt(g,this.signer,null==(l=this.config)?void 0:l.gasFeeMultiplier,h.setMetaData,r,d,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=it({},r,{metadataProofs:r.metadataProofs||[]}),o=await s.setMetaDataAndTokenURI.estimateGas(a);return n?o:await kt(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 kt(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 kt(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),h=c(a(n)),d=await u.setNewData.estimateGas(l,h);return i?d:await kt(d,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,u.setNewData,l,h)}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 Vt extends Ct{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,Tt(null,null,r,18));return n?a:await kt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,s.approve,e,Tt(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=Dt);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 kt(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=Dt),n.withMint=!1!==n.withMint;const o=await a.createDispenser.estimateGas(r,n.maxTokens,n.maxBalance,n.withMint,n.allowedSwapper);return i?o:await kt(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,Tt(null,null,r,18));return i?t:await kt(t,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,s.mint,n||e,Tt(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 kt(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 kt(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 kt(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 kt(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 kt(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 Tt(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 kt(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:Dt,consumeMarketFeeToken:Dt,consumeMarketFeeAmount:"0"});const c=await o.startOrder.estimateGas(e,r,n,i);return s?c:await kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 kt(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 Tt(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await Tt(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class qt extends Vt{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 kt(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 kt(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 kt(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 Ot{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 kt(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 kt(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 kt(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 kt(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 kt(r,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class Ht extends Ot{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}=Mt();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 kt(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 xt(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===Dt)throw new Error("Template address cannot be ZERO address");const i=await this.contract.changeTemplateAddress.estimateGas(e);return r?i:await kt(i,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.changeTemplateAddress,e)}}class Kt extends Ot{getDefaultAbi(){return O.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 Vt(this.signer),d=await u.allowance(t,await this.signer.getAddress(),this.contract.target.toString(),a);new p(await this.amountToUnits(t,d,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(h(f)).isLessThanOrEqualTo(new p(h(r)))&&new p(h(r)).isGreaterThan(new p(n))?await this.deposit(t,r,a):new p(h(f)).isLessThanOrEqualTo(new p(h(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 kt(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 kt(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),h=await this.contract.authorize.estimateGas(t,e,c,u,l);return a?h:await kt(h,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 kt(a,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,r,n)}}class Zt extends Ot{getDefaultAbi(){return F.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 Jt(t){return new Promise(e=>{setTimeout(e,t)})}function Wt(t){return null!=t}async function Yt(t,e){const r=d(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 Xt(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 Qt extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}}class te extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}}class ee extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}}class re extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}}class ne extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}}class ie extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}}class se extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}}const ae=Symbol.for("@libp2p/peer-id"),oe=Symbol.for("@libp2p/service-capabilities");function ce(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 ue{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 le{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 de(this,t)}}class he{decoders;constructor(t){this.decoders=t}or(t){return de(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 de(t,e){return new he({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class fe{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 ue(t,e,r),this.decoder=new le(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}function ge({name:t,prefix:e,encode:r,decode:n}){return new fe(t,e,r,n)}function pe({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 h(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 h=0,d=s-1;(0!==l||h<i)&&-1!==d;d--,h++)a[d]=(l+=o*a[d]>>>0)%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");i=h,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 h=e[i],d=0,f=a-1;(0!==h||d<n)&&-1!==f;f--,d++)u[f]=(h+=256*u[f]>>>0)%o>>>0,h=h/o>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,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:h,decode:function(t){var r=h(t);if(r)return r;throw new Error(`Non-${e} character`)}}}(r,t);return ge({prefix:e,name:t,encode:n,decode:t=>ce(i(t))})}function we({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 ge({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 me=pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});const ye=we({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});we({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),we({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),we({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),we({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),we({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),we({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),we({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),we({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});const be=pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"});pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ve=Math.pow(2,31),Ee=Math.pow(2,7),Se=Math.pow(2,14),Ae=Math.pow(2,21),Te=Math.pow(2,28),xe=Math.pow(2,35),ke=Math.pow(2,42),Ce=Math.pow(2,49),Oe=Math.pow(2,56),Fe=Math.pow(2,63),De={encode:function t(e,r,n){r=r||[];for(var i=n=n||0;e>=ve;)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<Ee?1:t<Se?2:t<Ae?3:t<Te?4:t<xe?5:t<ke?6:t<Ce?7:t<Oe?8:t<Fe?9:10}};function Ie(t,e=0){return[De.decode(t,e),De.decode.bytes]}function Ne(t,e,r=0){return De.encode(t,e,r),e}function Le(t){return De.encodingLength(t)}function Pe(t,e){const r=e.byteLength,n=Le(t),i=n+Le(r),s=new Uint8Array(i+r);return Ne(t,s,0),Ne(r,s,n),s.set(e,i),new Re(t,r,e,s)}function Ue(t){const e=ce(t),[r,n]=Ie(e),[i,s]=Ie(e.subarray(n)),a=e.subarray(n+s);if(a.byteLength!==i)throw new Error("Incorrect length");return new Re(r,i,a,e)}class Re{code;size;digest;bytes;constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}}function Me(t,e){const{bytes:r,version:n}=t;return 0===n?function(t,e,r){const{prefix:n}=r;if(n!==me.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,_e(t),e??me.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,_e(t),e??ye.encoder)}const Be=new WeakMap;function _e(t){const e=Be.get(t);if(null==e){const e=new Map;return Be.set(t,e),e}return e}class Ge{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!==je)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==$e)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ge.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=Pe(t,e);return Ge.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 Ge.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 Me(this,t)}toJSON(){return{"/":Me(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 Ge)return e;if(null!=e["/"]&&e["/"]===e.bytes||e.asCID===e){const{version:t,code:r,multihash:n,bytes:i}=e;return new Ge(t,r,n,i??Ve(t,r,n.bytes))}if(!0===e[qe]){const{version:t,multihash:r,code:n}=e,i=Ue(r);return Ge.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!==je)throw new Error(`Version 0 CID must use dag-pb (code: ${je}) block encoding`);return new Ge(t,e,r,r.bytes);case 1:{const n=Ve(t,e,r.bytes);return new Ge(t,e,r,n)}default:throw new Error("Invalid version")}}static createV0(t){return Ge.create(0,je,t)}static createV1(t,e){return Ge.create(1,t,e)}static decode(t){const[e,r]=Ge.decodeFirst(t);if(0!==r.length)throw new Error("Incorrect length");return e}static decodeFirst(t){const e=Ge.inspectBytes(t),r=e.size-e.multihashSize,n=ce(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 Re(e.multihashCode,e.digestSize,i,n);return[0===e.version?Ge.createV0(s):Ge.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0;const r=()=>{const[r,n]=Ie(t.subarray(e));return e+=n,r};let n=r(),i=je;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[me.prefix,(e??me).decode(`${me.prefix}${t}`)];case me.prefix:return[me.prefix,(e??me).decode(t)];case ye.prefix:return[ye.prefix,(e??ye).decode(t)];case be.prefix:return[be.prefix,(e??be).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=Ge.decode(n);if(0===i.version&&"Q"!==t[0])throw Error("Version 0 CID string must not include multibase prefix");return _e(i).set(r,t),i}}const je=112,$e=18;function Ve(t,e,r){const n=Le(t),i=n+Le(e),s=new Uint8Array(i+r.byteLength);return Ne(t,s,0),Ne(e,s,n),s.set(r,i),s}const qe=Symbol.for("@ipld/js-cid/CID"),ze=ce,He=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 Pe(0,ze(t))},Ke=Symbol.for("@achingbrain/uint8arraylist");function Ze(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 Je(t){return Boolean(t?.[Ke])}class We{bufs;length;[Ke]=!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(!Je(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(!Je(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=Ze(this.bufs,t);return e.buf[e.index]}set(t,e){const r=Ze(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(!Je(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 P(r,n)}subarray(t,e){const{bufs:r,length:n}=this._subList(t,e);return 1===r.length?r[0]:P(r,n)}sublist(t,e){const{bufs:r,length:n}=this._subList(t,e),i=new We;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(!(Je(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=N(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=L(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=L(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=L(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=N(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=L(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=L(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=L(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=L(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=L(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 We))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 We;return r.bufs=t,null==e&&(e=t.reduce((t,e)=>t+e.byteLength,0)),r.length=e,r}}const Ye=parseInt("11111",2),Xe=parseInt("10000000",2),Qe=parseInt("01111111",2),tr={0:nr,1:nr,2:function(t,e){const r=rr(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=rr(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=rr(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=rr(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:nr,22:nr,48:nr};function er(t,e={offset:0}){const r=t[e.offset]&Ye;if(e.offset++,null!=tr[r])return tr[r](t,e);throw new Error("No decoder for tag "+r)}function rr(t,e){let r=0;if((t[e.offset]&Xe)===Xe){const n=t[e.offset]&Qe;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 nr(t,e){rr(t,e);const r=[];for(;!(e.offset>=t.byteLength);){const n=er(t,e);if(null===n)break;r.push(n)}return r}function ir(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 We;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 We(Uint8Array.from([e.byteLength|Xe]),e)}function sr(t){const e=new We;return!(128&~t.subarray()[0])&&e.append(Uint8Array.from([0])),e.append(t),new We(Uint8Array.from([2]),ir(e),e)}function ar(t){const e=Uint8Array.from([0]),r=new We(e,t);return new We(Uint8Array.from([3]),ir(r),r)}function or(t,e=48){const r=new We;for(const e of t)r.append(e);return new We(Uint8Array.from([e]),ir(r),r)}const cr=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ur=Uint8Array.from([6,5,43,129,4,0,34]),lr=Uint8Array.from([6,5,43,129,4,0,35]),hr={ext:!0,kty:"EC",crv:"P-256"},dr={ext:!0,kty:"EC",crv:"P-384"},fr={ext:!0,kty:"EC",crv:"P-521"};function gr(t){if("P-256"===t)return cr;if("P-384"===t)return ur;if("P-521"===t)return lr;throw new Qt(`Invalid curve ${t}`)}class pr{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){var t;return null==this._raw&&(this._raw=(t=this.jwk,or([sr(Uint8Array.from([1])),or([gr(t.crv)],160),or([ar(new We(Uint8Array.from([4]),R(t.x??"","base64url"),R(t.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return He(ca(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.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 wr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function mr(t,e=""){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e&&`"${e}" `}expected integer >= 0, got ${t}`)}function yr(t,e,r=""){const n=wr(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 br(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash must wrapped by utils.createHasher");mr(t.outputLen),mr(t.blockLen)}function vr(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 Er(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Sr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ar(t,e){return t<<32-e|t>>>e}const Tr=/* @__PURE__ */(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),xr=/* @__PURE__ */Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function kr(t){if(yr(t),Tr)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=xr[t[r]];return e}function Cr(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Or(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(Tr)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=Cr(t.charCodeAt(i)),s=Cr(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 Fr(...t){let e=0;for(let r=0;r<t.length;r++){const n=t[r];yr(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 Dr(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 Ir(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 Nr=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Lr(t,e,r){return t&e^t&r^e&r}class Pr{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=Sr(this.buffer)}update(t){vr(this),yr(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=Sr(t);for(;n<=i-s;s+=n)this.process(e,s)}}return this.length+=t.length,this.roundClean(),this}digestInto(t){vr(this),function(t,e){yr(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,Er(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=Sr(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 Ur=/* @__PURE__ */Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Rr=/* @__PURE__ */Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Mr=/* @__PURE__ */BigInt(2**32-1),Br=/* @__PURE__ */BigInt(32);function _r(t,e=!1){return e?{h:Number(t&Mr),l:Number(t>>Br&Mr)}:{h:0|Number(t>>Br&Mr),l:0|Number(t&Mr)}}const Gr=(t,e,r)=>t>>>r,jr=(t,e,r)=>t<<32-r|e>>>r,$r=(t,e,r)=>t>>>r|e<<32-r,Vr=(t,e,r)=>t<<32-r|e>>>r,qr=(t,e,r)=>t<<64-r|e>>>r-32,zr=(t,e,r)=>t>>>r-32|e<<64-r;function Hr(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:0|i}}const Kr=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Zr=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Jr=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Wr=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,Yr=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Xr=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,Qr=/* @__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]),tn=/* @__PURE__ */new Uint32Array(64);class en extends Pr{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)tn[r]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=tn[t-15],r=tn[t-2],n=Ar(e,7)^Ar(e,18)^e>>>3,i=Ar(r,17)^Ar(r,19)^r>>>10;tn[t]=i+tn[t-7]+n+tn[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+(Ar(a,6)^Ar(a,11)^Ar(a,25))+((l=a)&o^~l&c)+Qr[t]+tn[t]|0,h=(Ar(r,2)^Ar(r,13)^Ar(r,22))+Lr(r,n,i)|0;u=c,c=o,o=a,a=s+e|0,s=i,i=n,n=r,r=e+h|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(){Er(tn)}destroy(){this.set(0,0,0,0,0,0,0,0),Er(this.buffer)}}class rn extends en{A=0|Ur[0];B=0|Ur[1];C=0|Ur[2];D=0|Ur[3];E=0|Ur[4];F=0|Ur[5];G=0|Ur[6];H=0|Ur[7];constructor(){super(32)}}const nn=/* @__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}=_r(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))))(),sn=/* @__PURE__ */(()=>nn[0])(),an=/* @__PURE__ */(()=>nn[1])(),on=/* @__PURE__ */new Uint32Array(80),cn=/* @__PURE__ */new Uint32Array(80);class un extends Pr{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:h,Gh:d,Gl:f,Hh:g,Hl:p}=this;return[t,e,r,n,i,s,a,o,c,u,l,h,d,f,g,p]}set(t,e,r,n,i,s,a,o,c,u,l,h,d,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|h,this.Gh=0|d,this.Gl=0|f,this.Hh=0|g,this.Hl=0|p}process(t,e){for(let r=0;r<16;r++,e+=4)on[r]=t.getUint32(e),cn[r]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|on[t-15],r=0|cn[t-15],n=$r(e,r,1)^$r(e,r,8)^Gr(e,0,7),i=Vr(e,r,1)^Vr(e,r,8)^jr(e,r,7),s=0|on[t-2],a=0|cn[t-2],o=$r(s,a,19)^qr(s,a,61)^Gr(s,0,6),c=Vr(s,a,19)^zr(s,a,61)^jr(s,a,6),u=Jr(i,c,cn[t-7],cn[t-16]),l=Wr(u,n,o,on[t-7],on[t-16]);on[t]=0|l,cn[t]=0|u}let{Ah:r,Al:n,Bh:i,Bl:s,Ch:a,Cl:o,Dh:c,Dl:u,Eh:l,El:h,Fh:d,Fl:f,Gh:g,Gl:p,Hh:w,Hl:m}=this;for(let t=0;t<80;t++){const e=$r(l,h,14)^$r(l,h,18)^qr(l,h,41),y=Vr(l,h,14)^Vr(l,h,18)^zr(l,h,41),b=l&d^~l&g,v=Yr(m,y,h&f^~h&p,an[t],cn[t]),E=Xr(v,w,e,b,sn[t],on[t]),S=0|v,A=$r(r,n,28)^qr(r,n,34)^qr(r,n,39),T=Vr(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|d,p=0|f,d=0|l,f=0|h,({h:l,l:h}=Hr(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=Kr(S,T,k);r=Zr(C,E,A,x),n=0|C}({h:r,l:n}=Hr(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:s}=Hr(0|this.Bh,0|this.Bl,0|i,0|s)),({h:a,l:o}=Hr(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=Hr(0|this.Dh,0|this.Dl,0|c,0|u)),({h:l,l:h}=Hr(0|this.Eh,0|this.El,0|l,0|h)),({h:d,l:f}=Hr(0|this.Fh,0|this.Fl,0|d,0|f)),({h:g,l:p}=Hr(0|this.Gh,0|this.Gl,0|g,0|p)),({h:w,l:m}=Hr(0|this.Hh,0|this.Hl,0|w,0|m)),this.set(r,n,i,s,a,o,c,u,l,h,d,f,g,p,w,m)}roundClean(){Er(on,cn)}destroy(){Er(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class ln extends un{Ah=0|Rr[0];Al=0|Rr[1];Bh=0|Rr[2];Bl=0|Rr[3];Ch=0|Rr[4];Cl=0|Rr[5];Dh=0|Rr[6];Dl=0|Rr[7];Eh=0|Rr[8];El=0|Rr[9];Fh=0|Rr[10];Fl=0|Rr[11];Gh=0|Rr[12];Gl=0|Rr[13];Hh=0|Rr[14];Hl=0|Rr[15];constructor(){super(64)}}const hn=/* @__PURE__ */Dr(()=>new rn
|
|
2
|
-
/* @__PURE__ */,
|
|
3
|
-
/* @__PURE__ */,Nr(3)),fn=/* @__PURE__ */BigInt(0),gn=/* @__PURE__ */BigInt(1);function pn(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}" `)+"expected boolean, got type="+typeof t);return t}function wn(t){if("bigint"==typeof t){if(!Tn(t))throw new Error("positive bigint expected, got "+t)}else mr(t);return t}function mn(t){const e=wn(t).toString(16);return 1&e.length?"0"+e:e}function yn(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?fn:BigInt("0x"+t)}function bn(t){return yn(kr(t))}function vn(t){return yn(kr(An(yr(t)).reverse()))}function En(t,e){mr(e);const r=Or((t=wn(t)).toString(16).padStart(2*e,"0"));if(r.length!==e)throw new Error("number too large");return r}function Sn(t,e){return En(t,e).reverse()}function An(t){return Uint8Array.from(t)}const Tn=t=>"bigint"==typeof t&&fn<=t;function xn(t,e,r,n){if(!function(t,e,r){return Tn(t)&&Tn(e)&&Tn(r)&&e<=t&&t<r}(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}const kn=t=>(gn<<BigInt(t))-gn;function Cn(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 On(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 Fn=/* @__PURE__ */BigInt(0),Dn=/* @__PURE__ */BigInt(1),In=/* @__PURE__ */BigInt(2),Nn=/* @__PURE__ */BigInt(3),Ln=/* @__PURE__ */BigInt(4),Pn=/* @__PURE__ */BigInt(5),Un=/* @__PURE__ */BigInt(7),Rn=/* @__PURE__ */BigInt(8),Mn=/* @__PURE__ */BigInt(9),Bn=/* @__PURE__ */BigInt(16);function _n(t,e){const r=t%e;return r>=Fn?r:e+r}function Gn(t,e,r){let n=t;for(;e-- >Fn;)n*=n,n%=r;return n}function jn(t,e){if(t===Fn)throw new Error("invert: expected non-zero number");if(e<=Fn)throw new Error("invert: expected positive modulus, got "+e);let r=_n(t,e),n=e,i=Fn,s=Dn;for(;r!==Fn;){const t=n%r,e=i-s*(n/r);n=r,r=t,i=s,s=e}if(n!==Dn)throw new Error("invert: does not exist");return _n(i,e)}function $n(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Vn(t,e){const r=t.pow(e,(t.ORDER+Dn)/Ln);return $n(t,r,e),r}function qn(t,e){const r=(t.ORDER-Pn)/Rn,n=t.mul(e,In),i=t.pow(n,r),s=t.mul(e,i),a=t.mul(t.mul(s,In),i),o=t.mul(s,t.sub(a,t.ONE));return $n(t,o,e),o}function zn(t){if(t<Nn)throw new Error("sqrt is not defined for small field");let e=t-Dn,r=0;for(;e%In===Fn;)e/=In,r++;let n=In;const i=Wn(t);for(;1===Zn(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Vn;let s=i.pow(n,e);const a=(e+Dn)/In;return function(t,n){if(t.is0(n))return n;if(1!==Zn(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=Dn<<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 Hn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kn(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 Zn(t,e){const r=t.pow(e,(t.ORDER-Dn)/In),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 Jn{ORDER;BITS;BYTES;isLE;ZERO=Fn;ONE=Dn;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=Fn)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&&mr(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 _n(t,this.ORDER)}isValid(t){if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Fn<=t&&t<this.ORDER}is0(t){return t===Fn}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&Dn)===Dn}neg(t){return _n(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return _n(t*t,this.ORDER)}add(t,e){return _n(t+e,this.ORDER)}sub(t,e){return _n(t-e,this.ORDER)}mul(t,e){return _n(t*e,this.ORDER)}pow(t,e){return function(t,e,r){if(r<Fn)throw new Error("invalid exponent, negatives unsupported");if(r===Fn)return t.ONE;if(r===Dn)return e;let n=t.ONE,i=e;for(;r>Fn;)r&Dn&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Dn;return n}(this,t,e)}div(t,e){return _n(t*jn(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 jn(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=(e=this.ORDER)%Ln===Nn?Vn:e%Rn===Pn?qn:e%Bn===Mn?function(t){const e=Wn(t),r=zn(t),n=r(e,e.neg(e.ONE)),i=r(e,n),s=r(e,e.neg(n)),a=(t+Un)/Bn;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),h=t.eql(t.sqr(c),e);r=t.cmov(r,o,l),o=t.cmov(u,c,h);const d=t.eql(t.sqr(o),e),f=t.cmov(r,o,d);return $n(t,f,e),f}}(e):zn(e)),this._sqrt(this,t);var e}toBytes(t){return this.isLE?Sn(t,this.BYTES):En(t,this.BYTES)}fromBytes(t,e=!1){yr(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?vn(t):bn(t);if(a&&(o=_n(o,s)),!e&&!this.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o}invertBatch(t){return Kn(this,t)}cmov(t,e,r){return r?e:t}}function Wn(t,e={}){return new Jn(t,e)}function Yn(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 Xn(t){const e=Yn(t);return e+Math.ceil(e/2)}const Qn=/* @__PURE__ */BigInt(0),ti=/* @__PURE__ */BigInt(1);function ei(t,e){const r=e.negate();return t?r:e}function ri(t,e){const r=Kn(t.Fp,e.map(t=>t.Z));return e.map((e,n)=>t.fromAffine(e.toAffine(r[n])))}function ni(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ii(t,e){ni(t,e);const r=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:kn(t),maxNumber:r,shiftBy:BigInt(t)}}function si(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+=ti);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 ai=new WeakMap,oi=new WeakMap;function ci(t){return oi.get(t)||1}function ui(t){if(t!==Qn)throw new Error("invalid wNAF")}class li{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>Qn;)e&ti&&(r=r.add(n)),n=n.double(),e>>=ti;return r}precomputeWindow(t,e){const{windows:r,windowSize:n}=ii(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=ii(t,this.bits);for(let t=0;t<s.windows;t++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:l,offsetF:h}=si(r,t,s);r=a,c?i=i.add(ei(l,e[h])):n=n.add(ei(u,e[o]))}return ui(r),{p:n,f:i}}wNAFUnsafe(t,e,r,n=this.ZERO){const i=ii(t,this.bits);for(let t=0;t<i.windows&&r!==Qn;t++){const{nextN:s,offset:a,isZero:o,isNeg:c}=si(r,t,i);if(r=s,!o){const t=e[a];n=n.add(c?t.negate():t)}}return ui(r),n}getPrecomputes(t,e,r){let n=ai.get(e);return n||(n=this.precomputeWindow(e,t),1!==t&&("function"==typeof r&&(n=r(n)),ai.set(e,n))),n}cached(t,e,r){const n=ci(t);return this.wNAF(n,this.getPrecomputes(n,t,r),e)}unsafe(t,e,r,n){const i=ci(t);return 1===i?this._unsafeLadder(t,e,n):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),e,n)}createCache(t,e){ni(e,this.bits),oi.set(t,e),ai.delete(t)}hasCache(t){return 1!==ci(t)}}function hi(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(t){Cn(t,Hn.reduce((t,e)=>(t[e]="function",t),{ORDER:"bigint",BYTES:"number",BITS:"number"}))}(e),e}return Wn(t,{isLE:r})}function di(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>Qn))throw new Error(`CURVE.${t} must be positive bigint`)}const i=hi(e.p,r.Fp,n),s=hi(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 fi(t,e){return function(r){const n=t(r);return{secretKey:n,publicKey:e(n)}}}const gi=BigInt(0),pi=BigInt(1),wi=BigInt(2),mi=BigInt(8);function yi(t,e={}){const r=di("edwards",t,e,e.FpFnLE),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:a}=s;Cn(e,{},{uvRatio:"function"});const o=wi<<BigInt(8*i.BYTES)-pi,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:gi}}});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 xn("coordinate "+t,e,r?pi:gi,o),e}function h(t){if(!(t instanceof g))throw new Error("EdwardsPoint expected")}const d=On((t,e)=>{const{X:r,Y:i,Z:s}=t,a=t.is0();null==e&&(e=a?mi:n.inv(s));const o=c(r*e),u=c(i*e),l=n.mul(s,e);if(a)return{x:gi,y:pi};if(l!==pi)throw new Error("invZ was invalid");return{x:o,y:u}}),f=On(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),h=c(a*a),d=c(h*h),f=c(u*e);if(c(h*c(f+l))!==c(d+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,pi,c(s.Gx*s.Gy));static ZERO=new g(gi,pi,pi,gi);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,pi,c(e*r))}static fromBytes(t,e=!1){const r=n.BYTES,{a:i,d:a}=s;t=An(yr(t,r,"point")),pn(e,"zip215");const l=An(t),h=t[r-1];l[r-1]=-129&h;const d=vn(l);xn("point.y",d,gi,e?o:n.ORDER);const f=c(d*d),p=c(f-pi),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&pi)===pi,v=!!(128&h);if(!e&&y===gi&&v)throw new Error("bad point: x=0 and x_0=1");return v!==b&&(y=c(-y)),g.fromAffine({x:y,y:d})}static fromHex(t,e=!1){return g.fromBytes(Or(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(wi),this}assertValidity(){f(this)}equals(t){h(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),d=c(s*n);return o===u&&l===d}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(wi*c(n*n)),u=c(t*i),l=e+r,h=c(c(l*l)-i-a),d=u+a,f=d-o,p=u-a,w=c(h*f),m=c(d*p),y=c(h*p),b=c(f*d);return new g(w,m,b,y)}add(t){h(t);const{a:e,d:r}=s,{X:n,Y:i,Z:a,T:o}=this,{X:u,Y:l,Z:d,T:f}=t,p=c(n*u),w=c(i*l),m=c(o*r*f),y=c(a*d),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=>ri(g,t));return ri(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===gi?g.ZERO:this.is0()||t===pi?this:p.unsafe(this,t,t=>ri(g,t),e)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return p.unsafe(this,s.n).is0()}toAffine(t){return d(this,t)}clearCofactor(){return a===pi?this:this.multiplyUnsafe(a)}toBytes(){const{x:t,y:e}=this.toAffine(),r=n.toBytes(e);return r[r.length-1]|=t&pi?128:0,r}toHex(){return kr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const p=new li(g,i.BITS);return g.BASE.precompute(8),g}const bi=BigInt(1),vi=BigInt(2),Ei=BigInt(5),Si=BigInt(8),Ai=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ti=/* @__PURE__ */(()=>({p:Ai,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Si,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function xi(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ki=/* @__PURE__ */BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Ci=/* @__PURE__ */yi(Ti,{uvRatio:function(t,e){const r=Ai,n=_n(e*e*e,r),i=function(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Ai,a=t*t%s*t%s,o=Gn(a,vi,s)*a%s,c=Gn(o,bi,s)*t%s,u=Gn(c,Ei,s)*c%s,l=Gn(u,e,s)*u%s,h=Gn(l,r,s)*l%s,d=Gn(h,n,s)*h%s,f=Gn(d,i,s)*d%s,g=Gn(f,i,s)*d%s,p=Gn(g,e,s)*u%s;return{pow_p_5_8:Gn(p,vi,s)*t%s,b2:a}}(t*_n(n*n*e,r)).pow_p_5_8;let s=_n(t*n*i,r);const a=_n(e*s*s,r),o=s,c=_n(s*ki,r),u=a===t,l=a===_n(-t,r),h=a===_n(-t*ki,r);return u&&(s=o),(l||h)&&(s=c),(_n(s,r)&Dn)===Dn&&(s=_n(-s,r)),{isValid:u||l,value:s}}});function Oi(t){return function(t,e,r={}){if("function"!=typeof e)throw new Error('"hash" function param is required');Cn(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||Ir,c=r.adjustScalarBytes||(t=>t),u=r.domain||((t,e,r)=>{if(pn(r,"phflag"),e.length||r)throw new Error("Contexts/pre-hash are not supported");return t});function l(t){return a.create(vn(t))}function h(t){const{head:r,prefix:n,scalar:s}=function(t){const r=w.secretKey;yr(t,w.secretKey,"secretKey");const n=yr(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 d(t){return h(t).pointBytes}function f(t=Uint8Array.of(),...r){const i=Fr(...r);return l(e(u(i,yr(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 yr(t,w.seed,"seed")}const y={getExtendedPublicKey:h,randomSecretKey:m,isValidSecretKey:function(t){return wr(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(pi+r,pi-r):s.div(r-pi,r+pi);return s.toBytes(a)},toMontgomerySecret(t){const r=w.secretKey;yr(t,r);const n=e(t.subarray(0,r));return c(n).subarray(0,r)}};return Object.freeze({keygen:fi(m,d),getPublicKey:d,sign:function(t,e,r={}){t=yr(t,void 0,"message"),n&&(t=n(t));const{prefix:s,scalar:o,pointBytes:c}=h(e),u=f(r.context,s,t),l=i.multiply(u).toBytes(),d=f(r.context,l,c,t),g=a.create(u+d*o);if(!a.isValid(g))throw new Error("sign failed: invalid s");return yr(Fr(l,a.toBytes(g)),w.signature,"result")},verify:function(e,r,s,a=g){const{context:o,zip215:c}=a,u=w.signature;e=yr(e,u,"signature"),r=yr(r,void 0,"message"),s=yr(s,w.publicKey,"publicKey"),void 0!==c&&pn(c,"zip215"),n&&(r=n(r));const l=u/2,h=e.subarray(0,l),d=vn(e.subarray(l,u));let p,m,y;try{p=t.fromBytes(s,c),m=t.fromBytes(h,c),y=i.multiplyUnsafe(d)}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})}(Ci,dn,Object.assign({adjustScalarBytes:xi},t))}const Fi=/* @__PURE__ */Oi({});class Di extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}}class Ii extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}}var Ni={get(t=globalThis){const e=t.crypto;if(null==e?.subtle)throw new Ii("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 Li;const Pi=(async()=>{try{return await Ni.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Ui(t){return null!=t&&"function"==typeof t.then&&"function"==typeof t.catch&&"function"==typeof t.finally}class Ri{type="Ed25519";raw;constructor(t){this.raw=Mi(t,32)}toMultihash(){return He(ca(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.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==Li&&(Li=await Pi),Li?async function(t,e,r){if(t.buffer instanceof ArrayBuffer){const n=await Ni.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ni.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 Fi.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}(t,e,r)}(this.raw,e,t);return Ui(n)?n.then(t=>(r?.signal?.throwIfAborted(),t)):n}}function Mi(t,e){if((t=Uint8Array.from(t??[])).length!==e)throw new Qt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const Bi=Math.pow(2,7),_i=Math.pow(2,14),Gi=Math.pow(2,21),ji=Math.pow(2,28),$i=Math.pow(2,35),Vi=Math.pow(2,42),qi=Math.pow(2,49),zi=128,Hi=127;function Ki(t){if(t<Bi)return 1;if(t<_i)return 2;if(t<Gi)return 3;if(t<ji)return 4;if(t<$i)return 5;if(t<Vi)return 6;if(t<qi)return 7;if(null!=Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Zi(t,e,r=0){switch(Ki(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 Ji(t,e){let r=t[e],n=0;if(n+=r&Hi,r<zi)return n;if(r=t[e+1],n+=(r&Hi)<<7,r<zi)return n;if(r=t[e+2],n+=(r&Hi)<<14,r<zi)return n;if(r=t[e+3],n+=(r&Hi)<<21,r<zi)return n;if(r=t[e+4],n+=(r&Hi)*ji,r<zi)return n;if(r=t[e+5],n+=(r&Hi)*$i,r<zi)return n;if(r=t[e+6],n+=(r&Hi)*Vi,r<zi)return n;if(r=t[e+7],n+=(r&Hi)*qi,r<zi)return n;throw new RangeError("Could not decode varint")}function Wi(t,e,r=0){return null==e&&(e=N(Ki(t))),e instanceof Uint8Array?Zi(t,e,r):function(t,e,r=0){switch(Ki(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 Yi(t,e=0){return t instanceof Uint8Array?Ji(t,e):function(t,e){let r=t.get(e),n=0;if(n+=r&Hi,r<zi)return n;if(r=t.get(e+1),n+=(r&Hi)<<7,r<zi)return n;if(r=t.get(e+2),n+=(r&Hi)<<14,r<zi)return n;if(r=t.get(e+3),n+=(r&Hi)<<21,r<zi)return n;if(r=t.get(e+4),n+=(r&Hi)*ji,r<zi)return n;if(r=t.get(e+5),n+=(r&Hi)*$i,r<zi)return n;if(r=t.get(e+6),n+=(r&Hi)*Vi,r<zi)return n;if(r=t.get(e+7),n+=(r&Hi)*qi,r<zi)return n;throw new RangeError("Could not decode varint")}(t,e)}const Xi=new Float32Array([-0]),Qi=new Uint8Array(Xi.buffer);function ts(t,e,r){Xi[0]=t,e[r]=Qi[0],e[r+1]=Qi[1],e[r+2]=Qi[2],e[r+3]=Qi[3]}const es=new Float64Array([-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],e[r+4]=rs[4],e[r+5]=rs[5],e[r+6]=rs[6],e[r+7]=rs[7]}const is=BigInt(Number.MAX_SAFE_INTEGER),ss=BigInt(Number.MIN_SAFE_INTEGER);class as{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 os;if(t<is&&t>ss)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>cs&&(n=0n,++r>cs&&(r=0n))),new as(Number(n),Number(r))}static fromNumber(t){if(0===t)return os;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 as(r,n)}static from(t){return"number"==typeof t?as.fromNumber(t):"bigint"==typeof t?as.fromBigInt(t):"string"==typeof t?as.fromBigInt(BigInt(t)):null!=t.low||null!=t.high?new as(t.low>>>0,t.high>>>0):os}}const os=new as(0,0);os.toBigInt=function(){return 0n},os.zzEncode=os.zzDecode=function(){return this},os.length=function(){return 1};const cs=4294967296n;function us(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 ls(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function hs(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class ds{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,ls(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 ls(this,4);return hs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ls(this,4);return 0|hs(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw ls(this,4);const t=(Qi[0]=(e=this.buf)[r=this.pos],Qi[1]=e[r+1],Qi[2]=e[r+2],Qi[3]=e[r+3],Xi[0]);var e,r;return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ls(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],rs[4]=e[r+4],rs[5]=e[r+5],rs[6]=e[r+6],rs[7]=e[r+7],es[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 ls(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 ls(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw ls(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 as(0,0);let e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw ls(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 ls(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 ls(this,8);const t=hs(this.buf,this.pos+=4),e=hs(this.buf,this.pos+=4);return new as(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=Ji(this.buf,this.pos);return this.pos+=Ki(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 fs(t,e,r){const n=function(t){return new ds(t instanceof Uint8Array?t:t.subarray())}(t);return e.decode(n,void 0,r)}class gs{fn;len;next;val;constructor(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}}function ps(){}class ws{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}const ms=function(){const t=8192;let e,r=t;return function(n){if(n<1||n>4096)return N(n);r+n>t&&(e=N(t),r=0);const i=e.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),i}}();class ys{len;head;tail;states;constructor(){this.len=0,this.head=new gs(ps,0,0),this.tail=this.head,this.states=null}_push(t,e,r){return this.tail=this.tail.next=new gs(t,e,r),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Es((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Ss,10,as.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){const e=as.fromBigInt(t);return this._push(Ss,e.length(),e)}uint64Number(t){return this._push(Zi,Ki(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=as.fromBigInt(t).zzEncode();return this._push(Ss,e.length(),e)}sint64Number(t){const e=as.fromNumber(t).zzEncode();return this._push(Ss,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(bs,1,t?1:0)}fixed32(t){return this._push(As,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){const e=as.fromBigInt(t);return this._push(As,4,e.lo)._push(As,4,e.hi)}fixed64Number(t){const e=as.fromNumber(t);return this._push(As,4,e.lo)._push(As,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(ts,4,t)}double(t){return this._push(ns,8,t)}bytes(t){const e=t.length>>>0;return 0===e?this._push(bs,1,0):this.uint32(e)._push(Ts,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(us,e,t):this._push(bs,1,0)}fork(){return this.states=new ws(this),this.head=this.tail=new gs(ps,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 gs(ps,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?N(r):ms(r));var r;let n=0;for(;null!=t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}}function bs(t,e,r){e[r]=255&t}function vs(t,e,r){for(;t>127;)e[r++]=127&t|128,t>>>=7;e[r]=t}class Es extends gs{next;constructor(t,e){super(vs,t,e),this.next=void 0}}function Ss(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 As(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 Ts(t,e,r){e.set(t,r)}function xs(t,e,r){e.set(t,r)}function ks(t,e,r){t.length<40?us(t,e,r):null!=e.utf8Write?e.utf8Write(t,r):e.set(R(t),r)}function Cs(t,e){const r=new ys;return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var Os,Fs,Ds,Is,Ns;function Ls(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Ps(t,e){return Ls("message",Os.LENGTH_DELIMITED,t,e)}null!=globalThis.Buffer&&(ys.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(xs,e,t),this},ys.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(ks,e,t),this}),function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"}(Os||(Os={})),function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"}(Fs||(Fs={})),function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"}(Ds||(Ds={})),function(t){t.codec=()=>function(t){function e(e){if(null==t[e.toString()])throw new Error("Invalid enum value");return t[e]}return Ls("enum",Os.VARINT,function(t,r){const n=e(t);r.int32(n)},function(t){return e(t.int32())})}(Ds)}(Fs||(Fs={})),function(t){let e;t.codec=()=>(null==e&&(e=Ps((t,e,r={})=>{!1!==r.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),Fs.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=Fs.codec().decode(t);break;case 2:n.Data=t.bytes();break;default:t.skipType(7&e)}}return n})),e),t.encode=e=>Cs(e,t.codec()),t.decode=(e,r)=>fs(e,t.codec(),r)}(Is||(Is={})),function(t){let e;t.codec=()=>(null==e&&(e=Ps((t,e,r={})=>{!1!==r.lengthDelimited&&e.fork(),null!=t.Type&&(e.uint32(8),Fs.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=Fs.codec().decode(t);break;case 2:n.Data=t.bytes();break;default:t.skipType(7&e)}}return n})),e),t.encode=e=>Cs(e,t.codec()),t.decode=(e,r)=>fs(e,t.codec(),r)}(Ns||(Ns={}));class Us{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(br(t),yr(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),Er(n)}update(t){return vr(this),this.iHash.update(t),this}digestInto(t){vr(this),yr(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 Rs=(t,e,r)=>new Us(t,e).update(r).digest();Rs.create=(t,e)=>new Us(t,e);const Ms=(t,e)=>(t+(t>=0?e:-e)/qs)/e;function Bs(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function _s(t,e){const r={};for(let n of Object.keys(e))r[n]=void 0===t[n]?e[n]:t[n];return pn(r.lowS,"lowS"),pn(r.prehash,"prehash"),void 0!==r.format&&Bs(r.format),r}class Gs extends Error{constructor(t=""){super(t)}}const js={Err:Gs,_tlv:{encode:(t,e)=>{const{Err:r}=js;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=mn(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?mn(i.length/2|128):"";return mn(t)+s+i+e},decode(t,e){const{Err:r}=js;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}=js;if(t<$s)throw new e("integer: negative integers are not allowed");let r=mn(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}=js;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 bn(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=js,i=yr(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}=js,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s));return e.encode(48,n+i)}},$s=BigInt(0),Vs=BigInt(1),qs=BigInt(2),zs=BigInt(3),Hs=BigInt(4);function Ks(t,e={}){const r=di("weierstrass",t,e),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:a,n:o}=s;Cn(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=Js(n,i);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=e.toBytes||function(t,e,r){const{x:i,y:s}=e.toAffine(),a=n.toBytes(i);return pn(r,"isCompressed"),r?(l(),Fr(Zs(!n.isOdd(s)),a)):Fr(Uint8Array.of(4),a,n.toBytes(s))},d=e.fromBytes||function(t){yr(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,zs),Hs),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=Ms(a*t,r),c=Ms(-i*t,r);let u=t-o*n-c*s,l=-o*i-c*a;const h=u<$s,d=l<$s;h&&(u=-u),d&&(l=-l);const f=kn(Math.ceil(function(t){let e;for(e=0;t>fn;t>>=gn,e+=1);return e}(r)/2))+Vs;if(u<$s||u>=f||l<$s||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:u,k2neg:d,k2:l}}(t,c.basises,i.ORDER)}const v=On((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=On(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=ei(i,e),r=ei(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(d(yr(t,void 0,"point")));return e.assertValidity(),e}static fromHex(t){return A.fromBytes(Or(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(zs),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,zs),{X:i,Y:a,Z:o}=this;let c=n.ZERO,u=n.ZERO,l=n.ZERO,h=n.mul(i,i),d=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(d,u),u=n.add(d,u),u=n.mul(c,u),c=n.mul(g,c),l=n.mul(r,l),f=n.mul(t,f),g=n.sub(h,f),g=n.mul(t,g),g=n.add(g,l),l=n.add(h,h),h=n.add(l,h),h=n.add(h,f),h=n.mul(h,g),u=n.add(u,h),f=n.mul(a,o),f=n.add(f,f),h=n.mul(f,g),c=n.sub(c,h),l=n.mul(f,d),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,h=n.ZERO;const d=s.a,f=n.mul(s.b,zs);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),h=n.mul(d,b),u=n.mul(f,w),h=n.add(u,h),u=n.sub(p,h),h=n.add(p,h),l=n.mul(u,h),p=n.add(g,g),p=n.add(p,g),w=n.mul(d,w),b=n.mul(f,b),p=n.add(p,w),w=n.sub(g,w),w=n.mul(d,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),h=n.mul(v,h),h=n.add(h,g),new A(u,l,h)}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=>ri(A,t));if(r){const{k1neg:e,k1:i,k2neg:o,k2:c}=b(t),{p:u,f:l}=a(i),{p:h,f:d}=a(c);s=l.add(d),n=S(r.beta,u,h,e,o)}else{const{p:e,f:r}=a(t);n=e,s=r}return ri(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===$s||n.is0())return A.ZERO;if(t===Vs)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>Qn||n>Qn;)r&ti&&(s=s.add(i)),n&ti&&(a=a.add(i)),i=i.double(),r>>=ti,n>>=ti;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===Vs||(t?t(A,this):x.unsafe(this,o).is0())}clearCofactor(){const{clearCofactor:t}=e;return a===Vs?this:t?t(A,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(t=!0){return pn(t,"isCompressed"),this.assertValidity(),h(A,this,t)}toHex(t=!0){return kr(this.toBytes(t))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const T=i.BITS,x=new li(A,e.endo?Math.ceil(T/2):T);return A.BASE.precompute(8),A}function Zs(t){return Uint8Array.of(t?2:3)}function Js(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ws(t,e,r={}){br(e),Cn(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=(r=Object.assign({},r)).randomBytes||Ir,i=r.hmac||((t,r)=>Rs(e,t,r)),{Fp:s,Fn:a}=t,{ORDER:o,BITS:c}=a,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,lengths:f}=function(t,e={}){const{Fn:r}=t,n=e.randomBytes||Ir,i=Object.assign(Js(t.Fp,r),{seed:Xn(r.ORDER)});function s(t=n(i.seed)){return function(t,e,r=!1){yr(t);const n=t.length,i=Yn(e),s=Xn(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const a=_n(r?vn(t):bn(t),e-Dn)+Dn;return r?Sn(a,i):En(a,i)}(yr(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(!wr(t))return;if("_lengths"in r&&r._lengths||e===n)return;const a=yr(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=fi(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*qs<s.ORDER;function w(t){return t>o>>Vs}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){Bs(e);const r=f.signature;return yr(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}=js.toSig(yr(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(Or(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(Fr(Zs(!(1&i)),u)),h=a.inv(c),d=S(yr(e,void 0,"msgHash")),f=a.create(-d*h),g=a.create(n*h),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(Bs(t),"der"===t)return Or(js.hexFromSig(this));const{r:e,s:r}=this,n=a.toBytes(e),i=a.toBytes(r);return"recovered"===t?(y(),Fr(Uint8Array.of(this.assertRecovery()),n,i)):Fr(n,i)}toHex(t){return kr(this.toBytes(t))}}const E=r.bits2int||function(t){if(t.length>8192)throw new Error("input is too large");const e=bn(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=kn(c);function T(t){return xn("num < 2^"+c,t,$s,A),a.toBytes(t)}function x(t,r){return yr(t,void 0,"message"),r?yr(e(t),void 0,"prehashed message"):t}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:h,utils:d,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}=_s(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 h=[T(l),T(u)];if(null!=c&&!1!==c){const t=!0===c?n(f.secretKey):c;h.push(yr(t,void 0,"extraEntropy"))}const d=Fr(...h),m=u;return{seed:d,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===$s)return;const c=a.create(n*a.create(m+o*l));if(c===$s)return;let u=(i.x===o?0:2)|Number(i.y&Vs),h=c;return s&&w(c)&&(h=a.neg(c),u^=1),new v(o,h,p?void 0:u)}}}(r,s,o);return function(t,e,r){if(mr(t,"hashLen"),mr(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},h=(...t)=>r(c,Fr(o,...t)),d=(t=i)=>{c=h(s,t),o=h(),0!==t.length&&(c=h(a,t),o=h())},f=()=>{if(u++>=1e3)throw new Error("drbg: tried max amount of iterations");let t=0;const r=[];for(;t<e;){o=h();const e=o.slice();r.push(e),t+=o.length}return Fr(...r)};return(t,e)=>{let r;for(l(),d(t);!(r=e(f()));)d();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}=_s(i,g);if(n=yr(n,void 0,"publicKey"),r=x(r,o),!wr(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,h=S(r),d=a.inv(l),f=a.create(h*d),g=a.create(u*d),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}=_s(r,g);return e=x(e,n),v.fromBytes(t,"recovered").recoverPublicKey(e).toBytes()},Signature:v,hash:e})}const Ys={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Xs={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Qs=/* @__PURE__ */BigInt(2),ta=Wn(Ys.p,{sqrt:function(t){const e=Ys.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,h=Gn(l,r,e)*l%e,d=Gn(h,r,e)*l%e,f=Gn(d,Qs,e)*u%e,g=Gn(f,i,e)*f%e,p=Gn(g,s,e)*g%e,w=Gn(p,o,e)*p%e,m=Gn(w,c,e)*w%e,y=Gn(m,o,e)*p%e,b=Gn(y,r,e)*l%e,v=Gn(b,a,e)*g%e,E=Gn(v,n,e)*u%e,S=Gn(E,Qs,e);if(!ta.eql(ta.sqr(S),t))throw new Error("Cannot find square root");return S}}),ea=/* @__PURE__ */Ws(/* @__PURE__ */Ks(Ys,{Fp:ta,endo:Xs}),hn);function ra({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:i}){return new na(t,e,r,n,i)}class na{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?ia(r,this.code,e?.truncate):r.then(t=>ia(t,this.code,e?.truncate))}throw Error("Unknown type, must be binary type")}}function ia(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 Pe(e,t)}function sa(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const aa=ra({name:"sha2-256",code:18,encode:sa("SHA-256")});ra({name:"sha2-512",code:19,encode:sa("SHA-512")});class oa{type="secp256k1";raw;_key;constructor(t){this._key=function(t){try{return ea.Point.fromBytes(t),t}catch(t){throw new te(String(t))}}(t),this.raw=function(t){return ea.Point.fromBytes(t).toBytes()}(this._key)}toMultihash(){return He(ca(this))}toCID(){return Ge.createV1(114,this.toMultihash())}toString(){return me.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=aa.digest(r instanceof Uint8Array?r:r.subarray());if(Ui(i))return i.then(({digest:r})=>(n?.signal?.throwIfAborted(),ea.verify(e,r,t,{prehash:!1,format:"der"}))).catch(t=>{if("AbortError"===t.name)throw t;throw new Di(String(t))});try{return n?.signal?.throwIfAborted(),ea.verify(e,i.digest,t,{prehash:!1,format:"der"})}catch(t){throw new Di(String(t))}}(this._key,e,t,r)}}function ca(t){return Is.encode({Type:Fs[t.type],Data:t.raw})}const ua=Symbol.for("nodejs.util.inspect.custom");class la{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()})`}[ae]=!0;toString(){return null==this.string&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ge.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")}[ua](){return`PeerId(${this.toString()})`}}class ha extends la{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}}class da extends la{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}}class fa extends la{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}}class ga{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=He(R(this.url))}[ua](){return`PeerId(${this.url})`}[ae]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ge.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(t){return null!=t&&(t instanceof Uint8Array&&(t=M(t)),t.toString()===this.toString())}}function pa(t,e){let r;if("1"===t.charAt(0)||"Q"===t.charAt(0))r=Ue(me.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 ee("Supplied PeerID CID is invalid");if(2336===t.code){const e=M(t.multihash.digest);return new ga(new URL(e))}return wa(t.multihash)}(Ge.parse(t));if(null==e)throw new Qt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Ue(e.decode(t))}return wa(r)}function wa(t){if(function(t){return t.code===aa.code}(t))return new ha({multihash:t});if(function(t){return 0===t.code}(t))try{const e=function(t){const{Type:e,Data:r}=Is.decode(t.digest),n=r??new Uint8Array;switch(e){case Fs.Ed25519:return i=Mi(i=n,32),new Ri(i);case Fs.secp256k1:return function(t){return new oa(t)}(n);case Fs.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 pr({...hr,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 pr({...dr,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 pr({...fr,key_ops:["verify"],x:r,y:n});throw new Qt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}(er(t))}(n);default:throw new se}var i}(t);if("Ed25519"===e.type)return new da({multihash:t,publicKey:e});if("secp256k1"===e.type)return new fa({multihash:t,publicKey:e})}catch(e){const r=M(t.digest);return new ga(new URL(r))}throw new re("Supplied PeerID Multihash is invalid")}function ma(t,e){const r=_.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=G(r.toHex(),Buffer.from(e));return Buffer.from(n).toString("hex")}class ya{getConsumerAddress(t){return Ra(t)}getSignature(t,e,r){return Ma(t,e,r)}getAuthorization(t){return Ba(t)}async getEndpoints(t,e){try{const r=await this.getData(t,e);return await r.json()}catch(t){throw ut.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 D(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 ut.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,tt.ENCRYPT);let h=(this.getEndpointURL(o,"encrypt")?this.getEndpointURL(o,"encrypt").urlPath:null)+`?chainId=${e}`;if(!h)return null;h+=`&nonce=${u}`,h+=`&consumerAddress=${c}`,h+=`&signature=${l}`;try{const e=await D(h,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:s});return await e.text()}catch(t){throw ut.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 h;try{h=await D(l,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw ut.error("File info call failed: "),ut.error(t),new Error(t)}if(null!=(s=h)&&s.ok){const t=await h.json();for(const e of t)u.push(e);return u}const d=await h.json();throw ut.error("File info call failed: ",h.status,h.statusText,d),new Error(JSON.stringify(d))}async getFileInfo(t,e,r=!1,n){var i;const s=await this.getEndpoints(e),a=await this.getServiceEndpoints(e,s),o=it({},t,{checksum:r}),c=[],u=this.getEndpointURL(a,"fileinfo")?this.getEndpointURL(a,"fileinfo").urlPath:null;if(!u)return null;let l;try{l=await D(u,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw ut.error("File info call failed: "),ut.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 h=await l.json();throw ut.error("File info call failed: ",l.status,l.statusText,h),new Error(JSON.stringify(h))}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 D(a,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw ut.error("Fetch compute env failed: "),ut.error(t),new Error(t)}if(null!=(n=o)&&n.ok)return o.json();const c=await o.json();throw ut.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),h=await this.getServiceEndpoints(i,l);let d,f=this.getEndpointURL(h,"initialize")?this.getEndpointURL(h,"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{d=await D(f,{method:"GET",headers:{"Content-Type":"application/json"},signal:s})}catch(t){throw ut.error("Provider initialized failed: "),ut.error(t),new Error(`Provider initialize failed url: ${f} `)}if(200===(null==(u=d)?void 0:u.status))return await d.json();const g=await d.json();throw ut.error("Provider initialized failed: ",d.status,d.statusText,g),new Error(JSON.stringify(g))}async initializeCompute(t,e,r,n,i,s,a,o,c,u,l,h,d){var f;const g=await this.getEndpoints(s),p=await this.getServiceEndpoints(s,g),w=this.getEndpointURL(p,"initializeCompute")?this.getEndpointURL(p,"initializeCompute").urlPath:null;if(!w)return null;const m=await this.getConsumerAddress(a),y=(await this.getNonce(s,m,l,g,p)+1).toString();let b;if("string"!=typeof a){var v;let e=m;e+=null==(v=t[0])?void 0:v.documentId,e+=y,b=await Xt(a,e)}const E={datasets:t,algorithm:e,environment:r,payment:{chainId:c,token:n,resources:o},maxJobDuration:i,consumerAddress:m,signature:b};if(d){const t=await this.getNodePublicKey(s);t&&(E.dockerRegistryAuth=ma(t,JSON.stringify(d)))}if(u&&(E.policyServer=u),h){const t=await this.getNodePublicKey(s);t&&(E.output=ma(t,JSON.stringify(h)))}let S;try{if(S=await D(w,{method:"POST",body:JSON.stringify(E),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(a)},signal:l}),!S.ok){const t=await S.text();throw new Error(`${t}`)}}catch(t){throw ut.error("Initialize compute failed: "),ut.error(t),new Error(`ComputeJob cannot be initialized: ${t.message}.`)}if(null!=(f=S)&&f.ok)return await S.json();const A=await S.json();throw ut.error("Initialize compute failed: ",S.status,S.statusText,A),ut.error("Payload was:",JSON.stringify(E)),new Error(JSON.stringify(A))}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 h=await this.getConsumerAddress(s),d=(await this.getNonce(i,h,null,c,u)+1).toString(),f=await this.getSignature(s,d,tt.DOWNLOAD);let g=l;return g+=`?fileIndex=${r}`,g+=`&documentId=${t}`,g+=`&transferTxId=${n}`,g+=`&serviceId=${e}`,g+=`&consumerAddress=${h}`,g+=`&nonce=${d}`,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,h,d,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 ut.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,tt.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=ma(e,JSON.stringify(p)))}if(o&&(A.resources=o),u&&(A.metadata=u),l&&(A.additionalViewers=l),h){const e=await this.getNodePublicKey(t);e&&(A.output=ma(e,JSON.stringify(h)))}let T;d&&(A.policyServer=d),g&&(A.queueMaxWaitTime=g);try{T=await D(b,{method:"POST",body:JSON.stringify(A),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:f})}catch(t){throw ut.error("Compute start failed:"),ut.error(t),ut.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 ut.error("Compute start failed: ",T.status,T.statusText,x),ut.error("Payload was:",A),new Error(JSON.stringify(x))}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,h,d){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 ut.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,tt.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),d){const e=await this.getNodePublicKey(t);e&&(v.dockerRegistryAuth=ma(e,JSON.stringify(d)))}if(c){const e=await this.getNodePublicKey(t);e&&(v.output=ma(e,JSON.stringify(c)))}let E;u&&(v.policyServer=u),h&&(v.queueMaxWaitTime=h);try{E=await D(w,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:l})}catch(t){throw ut.error("Compute start failed:"),ut.error(t),ut.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 ut.error("Compute start failed: ",E.status,E.statusText,S),ut.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 ut.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null;const l=await this.getConsumerAddress(e),h=(await this.getNonce(t,l,n,o,c)+1).toString();let d,f=`?consumerAddress=${l}&jobId=${r}`;a||(f+=`&signature=${await this.getSignature(e,h,tt.COMPUTE_GET_STREAMABLE_LOGS)}`,f+=`&nonce=${h}`);try{d=await D(u+f,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:n})}catch(t){throw ut.error("computeStreamableLogs failed:"),ut.error(t),new Error("HTTP request failed calling Provider")}return null!=(i=d)&&i.ok||200===(null==(s=d)?void 0:s.status)?d.body:(ut.error("computeStreamableLogs failed: ",d.status,d.statusText,await d.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),h=(await this.getNonce(e,l,i,o,c)+1).toString(),d=await this.getSignature(r,h,tt.COMPUTE_STOP),f=new URLSearchParams;f.set("consumerAddress",l),f.set("nonce",h),f.set("jobId",t),a||f.set("signature",d),n&&f.set("agreementId",n);const g=f.toString();if(!g)return null;let p;try{p=await D(u+"?"+g,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(r)},signal:i})}catch(t){throw ut.error("Compute stop failed:"),ut.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 ut.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 Ra(e),c=Ba(e),u=await this.getEndpoints(t),l=await this.getServiceEndpoints(t,u),h=this.getEndpointURL(l,"computeStatus")?this.getEndpointURL(l,"computeStatus").urlPath:null;let d,f=`?consumerAddress=${o}`;if(f+=n&&`&agreementId=${n}`||"",f+=r&&`&jobId=${r}`||"",!h)return null;try{d=await D(h+f,{method:"GET",headers:{"Content-Type":"application/json",Authorization:c},signal:i})}catch(t){throw ut.error("Get compute status failed"),ut.error(t),new Error(t)}if(null!=(s=d)&&s.ok)return await d.json();if(ut.error("Get compute status failed:",d.status,d.statusText),null!=(a=d)&&a.ok)return await d.json();const g=await d.json();throw ut.error("Get compute status failed:",d.status,d.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,tt.COMPUTE_GET_RESULT);if(!o)return null;let h=o;return h+=`?consumerAddress=${c}`,h+=`&jobId=${r}`,h+=`&index=${n.toString()}`,i||(h+=`&nonce=${u}`,h+=`&signature=${l}`),h}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 D(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,tt.CREATE_AUTH_TOKEN);try{const t=await D(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 ut.error("Generate auth token failed:"),ut.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 Xt(t,u);try{const t=await D(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 ut.error("Generate auth token failed:"),ut.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const r=await D(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 ut.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 D(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 ut.error("PolicyServerPassthrough failed: "),ut.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(n=o)&&n.ok)return await o.json();const c=await o.json();throw ut.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),ut.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 D(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 ut.error("initializePSVerification failed: "),ut.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(n=o)&&n.ok)return await o.json();const c=await o.json();throw ut.error("initializePSVerification failed: ",o.status,o.statusText,c),ut.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),h=await this.getServiceEndpoints(t,l),d=this.getEndpointURL(h,"logs")?this.getEndpointURL(h,"logs").urlPath:null;if(!d)return ut.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,h)+1).toString(),p=await this.getSignature(e,g,tt.GET_LOGS);let w,m=d+`?startTime=${r}&endTime=${n}`;i&&(m+=`&maxLogs=${i}`),s&&(m+=`&moduleName=${s}`),a&&(m+=`&level=${a}`),o&&(m+=`&page=${o}`);try{w=await D(m,{method:"POST",body:JSON.stringify({signature:p,nonce:g,address:f}),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw ut.error("Download node logs failed:"),ut.error(t),new Error("HTTP request failed calling Provider")}if(null!=(u=w)&&u.ok)return w.body;const y=await w.json();throw ut.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 ut.debug("Not input string:"),ut.debug(t),new Error(`[${r}] Expected string, input type: ${typeof t}`);const n=t.match(e);return n?{valid:!0,output:n[1]}:(ut.warn(`[${r}] Input transformation failed.`),{valid:!1,output:t})}async resolveDdo(t,e,r){const n=t+"/api/aquarius/assets/ddo/"+e,i=await D(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+tt.VALIDATE_DDO,u=await Xt(r,c),l=await D(`${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 h=await l.json();return{valid:!0,hash:h.hash,proof:{validatorAddress:h.publicKey,r:h.r[0],s:h.s[0],v:h.v}}}async getData(t,e){return D(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}class ba extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,ba)}}const va=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Ea(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))},h=(...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,h)};for(const t of a)c(t,l);for(const t of r.rejectionEvents)a.includes(t)||c(t,h);r.signal&&r.signal.addEventListener("abort",()=>{h(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(va(a));if(a&&(c=()=>{u(va(a))},a.addEventListener("abort",c,{once:!0})),t.then(e,u),r===Number.POSITIVE_INFINITY)return;const l=new ba;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 Sa(t){return t.reason}async function Aa(t,e,r){if(null==e)return t;const n=r?.translateError??Sa;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 Ta{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";[oe]=["@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 ie("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 Ea(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 Qt("random bytes length must be a Number bigger than 0");return Ir(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 We,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 ne(`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 Aa(i.promise,e.signal)}catch(e){throw i.error("error while pinging %o - %e",t,e),n?.abort(e),e}finally{n?.close()}}}function xa(t={}){return e=>new Ta(e,t)}class ka extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class Ca extends Error{static name="UnwrappedError";name="UnwrappedError"}class Oa extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Fa extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Da extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Ia(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 Na="/ocean/nodes/1.0.0",La=1e4,Pa=["/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 Ua{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()}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:Pa).map(J),r=await j(it({addresses:{listen:[]},transports:[q(),...this.p2pConfig.enableTcp?[z()]:[]],connectionEncrypters:[$()],streamMuxers:[V()],peerDiscovery:[...e.length>0?[H({list:e.map(String),timeout:1e4})]:[]],services:{identify:K(),ping:xa(),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=>{ut.debug(`Failed to dial discovered peer ${i}: ${t.message}`)})}),this.libp2pNode=r,r}toUint8Array(t){return t instanceof Uint8Array?t:t.subarray()}async getConnection(t,e){var r;if(t.startsWith("/")){const r=J(t);return(await this.getOrCreateLibp2pNode()).dial(r,{signal:e})}const n=pa(t),i=await this.getOrCreateLibp2pNode(),s=i.getConnections(n);if(s.length>0)return s[0];const a=AbortSignal.timeout(null!=(r=this.p2pConfig.dhtLookupTimeout)?r:6e4);return await i.peerRouting.findPeer(n,{signal:a}).catch(()=>{}),i.dial(n,{signal:e})}getConsumerAddress(t){return Ra(t)}getSignature(t,e,r){return Ma(t,e,r)}async getNodePublicKey(t){const e=await this.getEndpoints(t);return null==e?void 0:e.nodePublicKey}getAuthorization(t){return Ba(t)}async dialAndStream(t,e,r){var n;const i=null!=r?r:AbortSignal.timeout(null!=(n=this.p2pConfig.dialTimeout)?n:La),s=await this.getConnection(t,i),a=await s.newStream(Na,{signal:i}),o=function(t,e={}){const r=function(t,e){const r=e?.maxBufferSize??4194304,n=new We;let i,s=!1;if(a=t,null==a?.addEventListener||null==a?.removeEventListener||null==a?.send||null==a?.push||null==a?.log)throw new Qt("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 Ca("Stream was unwrapped");if(Ia(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 ka(`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 Aa(i.promise,e?.signal),Ia(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(Ia(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,a),new ka(`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 Ca("Stream was unwrapped");t.send(e)||await Ea(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=Ki(e.maxDataLength));const n=e?.lengthDecoder??Yi,i=e?.lengthEncoder??Wi;return{async read(i){let s=-1;const a=new We;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 Oa("Invalid message length");if(null!=e?.maxLengthLength&&a.byteLength>e.maxLengthLength)throw new Da(`Message length length too long - ${a.byteLength} > ${e.maxLengthLength}`);if(s>-1)break}if(null!=e?.maxDataLength&&s>e.maxDataLength)throw new Fa(`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 ka(`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 ka(`Unexpected EOF - read ${o.byteLength}/${s} bytes before the stream closed`);return o},async write(t,e){await r.write(new We(i(t.byteLength),t),e)},async writeV(t,e){const n=new We(...t.flatMap(t=>[i(t.byteLength),t]));await r.write(n,e)},unwrap:()=>r.unwrap()}}(a);await o.write(R(JSON.stringify(e)),{signal:i}),await a.close();const c=await o.read({signal:i});return{lp:o,firstBytes:this.toUint8Array(c),connection:s}}async sendP2pCommand(t,e,r,n,i,s=0){let a;try{var o,c;const h=it({command:e,authorization:n?this.getAuthorization(n):void 0},r),{lp:d,firstBytes:f,connection:g}=await this.dialAndStream(t,h,i);if(a=g,!f.length)throw new Error("Gateway node error: no response from peer");const p=M(f);try{const t=JSON.parse(p);var u;if("number"==typeof(null==t?void 0:t.httpStatus)&&t.httpStatus>=400)throw new Error(null!=(u=t.error)?u:`Gateway node error: ${t.httpStatus}`)}catch(t){}if(e===tt.COMPUTE_GET_STREAMABLE_LOGS||e===tt.COMPUTE_GET_RESULT)return st(function*(){try{for(;;){const t=yield nt(d.read({signal:AbortSignal.timeout(La)}));yield t instanceof Uint8Array?t:t.subarray()}}catch(t){if(!(t instanceof ka))throw t}})();const w=[f];try{for(;;){var l;const t=await d.read({signal:AbortSignal.timeout(null!=(l=this.p2pConfig.dialTimeout)?l:La)});w.push(this.toUint8Array(t))}}catch(t){if(!(t instanceof ka))throw t}let m;for(let t=0;t<w.length;t++){const e=M(w[t]);try{m=JSON.parse(e)}catch(e){m=w[t]}}const y=m;if("number"==typeof(null==y?void 0:y.httpStatus)&&y.httpStatus>=400)throw new Error("string"==typeof y.error?y.error:JSON.stringify(y.error));return(null!=(o="string"==typeof m?m:null==y?void 0:y.error)?o:"").includes("Cannot connect to peer")&&s<(null!=(c=this.p2pConfig.maxRetries)?c: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)):m}catch(o){var h,d;const c=null!=(h=null==o?void 0:o.message)?h:"";if((c.includes("closed")||c.includes("reset"))&&s<(null!=(d=this.p2pConfig.maxRetries)?d:5)){try{var f;await(null==(f=a)?void 0:f.close())}catch(t){}return this.sendP2pCommand(t,e,r,n,i,s+1)}throw new Error(`P2P command error: ${c}`)}}async getEndpoints(t){try{return await this.sendP2pCommand(t,tt.STATUS,{})}catch(t){throw ut.error("P2P getEndpoints (STATUS) failed:",t),t}}async getNonce(t,e,r){try{var n,i;const s=await this.sendP2pCommand(t,tt.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 ut.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,tt.ENCRYPT),u=await this.sendP2pCommand(r,tt.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,tt.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,tt.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,tt.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,tt.GET_FEES,u,null,s)}async initializeCompute(t,e,r,n,i,s,a,o,c,u,l,h,d){const f=await this.getConsumerAddress(a),g=(await this.getNonce(s,f,l)+1).toString();let p;if("string"!=typeof a){var w;let e=f;e+=null==(w=t[0])?void 0:w.documentId,e+=g,p=await Xt(a,e)}const m={datasets:t,algorithm:e,environment:r,payment:{chainId:c,token:n,resources:o},maxJobDuration:i,consumerAddress:f,nonce:g,signature:p};if(d){const t=await this.getNodePublicKey(s);t&&(m.dockerRegistryAuth=ma(t,JSON.stringify(d)))}if(u&&(m.policyServer=u),h){const t=await this.getNodePublicKey(s);t&&(m.output=ma(t,JSON.stringify(h)))}return this.sendP2pCommand(s,tt.COMPUTE_INITIALIZE,m,a,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,tt.DOWNLOAD),h={command:tt.DOWNLOAD,authorization:this.getAuthorization(s),fileIndex:r,documentId:t,transferTxId:n,serviceId:e,consumerAddress:c,nonce:u,signature:l};a&&(h.policyServer=a),o&&(h.userData=o);const{lp:d,firstBytes:f}=await this.dialAndStream(i,h),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 d.read({signal:AbortSignal.timeout(null!=(y=this.p2pConfig.dialTimeout)?y:La)});m.push(Buffer.from(this.toUint8Array(t)))}}catch(t){if(!(t instanceof ka))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,h,d,f,g,p){const w=await this.getConsumerAddress(e),m=(await this.getNonce(t,w,f)+1).toString(),y=await this.getSignature(e,m,tt.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),d&&(b.policyServer=d),g&&(b.queueMaxWaitTime=g),p){const e=await this.getNodePublicKey(t);e&&(b.dockerRegistryAuth=ma(e,JSON.stringify(p)))}if(h){const e=await this.getNodePublicKey(t);e&&(b.output=ma(e,JSON.stringify(h)))}const v=await this.sendP2pCommand(t,tt.COMPUTE_START,b,e,f);return Array.isArray(v),v}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,h,d){const f=await this.getConsumerAddress(e),g=(await this.getNonce(t,f,l)+1).toString(),p=await this.getSignature(e,g,tt.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),h&&(w.queueMaxWaitTime=h),d){const e=await this.getNodePublicKey(t);e&&(w.dockerRegistryAuth=ma(e,JSON.stringify(d)))}if(c){const e=await this.getNodePublicKey(t);e&&(w.output=ma(e,JSON.stringify(c)))}const m=await this.sendP2pCommand(t,tt.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,tt.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,tt.COMPUTE_GET_STREAMABLE_LOGS);return this.sendP2pCommand(t,tt.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,tt.COMPUTE_STOP)};return n&&(o.agreementId=n),this.sendP2pCommand(e,tt.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,tt.COMPUTE_GET_STATUS,s,e,i)}async getComputeResult(t,e,r,n,i=0){var s;const a=await this.getConsumerAddress(e),o={command:tt.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,tt.COMPUTE_GET_RESULT)}const{lp:c,firstBytes:u}=await this.dialAndStream(t,o),l=JSON.parse(M(u));var h;if("number"==typeof(null==l?void 0:l.httpStatus)&&l.httpStatus>=400)throw new Error(null!=(h=l.error)?h:`P2P compute result error: ${l.httpStatus}`);const d=null!=(s=this.p2pConfig.dialTimeout)?s:La;return st(function*(){try{for(;;){const t=yield nt(c.read({signal:AbortSignal.timeout(d)}));yield t instanceof Uint8Array?t:t.subarray()}}catch(t){if(!(t instanceof ka))throw t}})()}async getComputeResultUrl(t,e,r,n){const i=await this.getConsumerAddress(e);return await this.sendP2pCommand(t,tt.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,tt.CREATE_AUTH_TOKEN),o=await this.sendP2pCommand(e,tt.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,tt.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+tt.VALIDATE_DDO,h=await Xt(r,l),d=await this.sendP2pCommand(t,tt.VALIDATE_DDO,{ddo:e,publisherAddress:c,nonce:u,signature:h},null,n);return!d||d.error?null:{valid:!0,hash:this.bufToHex(d.hash),proof:{validatorAddress:this.bufToHex(d.publicKey),r:this.bufToHex(null!=(i=null==(s=d.r)?void 0:s[0])?i:d.r),s:this.bufToHex(null!=(a=null==(o=d.s)?void 0:o[0])?a:d.s),v:d.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 Xt(t,a);return this.sendP2pCommand(r,tt.INVALIDATE_AUTH_TOKEN,{address:i,signature:o,token:e,nonce:s},null,n)}async isValidProvider(t,e){try{const r=await this.sendP2pCommand(t,tt.STATUS,{},null,e);return!(!r||!(r.address||r.providerAddress||r.providerAddresses))}catch(t){return!1}}async PolicyServerPassthrough(t,e,r){return this.sendP2pCommand(t,tt.POLICY_SERVER_PASSTHROUGH,it({},e),null,r)}async initializePSVerification(t,e,r){return this.sendP2pCommand(t,tt.POLICY_SERVER_PASSTHROUGH,it({},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(),h={startTime:r,endTime:n,signature:await this.getSignature(e,l,tt.GET_LOGS),nonce:l,address:u};return i&&(h.maxLogs=i),s&&(h.moduleName=s),a&&(h.level=a),o&&(h.page=o),this.sendP2pCommand(t,tt.GET_LOGS,h,e,c)}async fetchConfig(t,e){return this.sendP2pCommand(t,tt.FETCH_CONFIG,e)}async pushConfig(t,e){return this.sendP2pCommand(t,tt.PUSH_CONFIG,e)}}async function Ra(t){return"string"==typeof t?function(t){try{return B.decode(t,{json:!0})}catch(t){throw new Error("Error decoding JWT")}}(t).address:t.getAddress()}async function Ma(t,e,r){if("string"==typeof t)return null;const n=String(String(await t.getAddress())+String(e)+String(r));return Xt(t,n)}function Ba(t){return"string"==typeof t?t:void 0}const _a=["/ip4/","/ip6/","/dns4/","/dns6/","/dns/","/dnsaddr/"];function Ga(t){if(!t)return!1;if(_a.some(e=>t.startsWith(e)))return!0;try{return pa(t),!0}catch(t){return!1}}class ja{constructor(){this.httpProvider=new ya,this.p2pProvider=new Ua}getImpl(t){return Ga(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,h,d){return this.getImpl(s).initializeCompute(t,e,r,n,i,s,a,o,c,u,l,h,d)}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,h,d,f,g,p){return this.getImpl(t).computeStart(t,e,r,n,i,s,a,o,c,u,l,h,d,f,g,p)}async freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,h,d){return this.getImpl(t).freeComputeStart(t,e,r,n,i,s,a,o,c,u,l,h,d)}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 fetchConfig(t,e){return this.p2pProvider.fetchConfig(t,e)}async pushConfig(t,e){return this.p2pProvider.pushConfig(t,e)}}const $a=new ja;class Va{constructor(t){this.aquariusURL=void 0,this.aquariusURL=t}async resolve(t,e,r){if(Ga(this.aquariusURL)){const r=await $a.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 D(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 ut.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,r,n=3e4,i=100,s){let a=0;i>500&&(ut.warn("Max Limit exceeded, defaulting to 500 retries."),i=500);const o=Ga(this.aquariusURL);do{try{let n;if(o)n=await $a.resolveDdo(this.aquariusURL,t,r);else{const e=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,i=await D(e,{method:"GET",headers:{"Content-Type":"application/json",Authorization:s},signal:r});i.ok&&(n=await i.json())}if(n){const t=I.getDDOClass(n),{indexedMetadata:r}=t.getAssetFields();if(!e)return n;if(r.event&&r.event.txid===e)return n}}catch(t){}await Jt(n),a++}while(a<i);return null}async validate(t,e,r,n,i){if(Ga(r))return $a.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 D(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(tt.VALIDATE_DDO)),h={ddo:t,publisherAddress:r,nonce:u,signature:await Xt(e,l)},d=await D(s,{method:"POST",body:JSON.stringify(h),headers:{"Content-Type":"application/json",Authorization:Ba(e)},signal:n}),f=await d.json();if(200!==d.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){ut.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,r){const n=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await D(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 ut.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 D(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 ut.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}function qa(t,e){return t=l(t),`did:op:${W(t+e.toString(10)).toString()}`}function za(t){return W(t).toString()}function Ha(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 Ka(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 Za(t,e,n,i,s,a,o=!1,c,u){const l=new r.Contract(i,pt,t);if(!o){const e=await Ya(t,i,n,s);if(new w(e).greaterThanOrEqualTo(new w(a)))return new w(e).toNumber()}const h=await Tt(t,i,a,c),d=await l.approve.estimateGas(s,h);return u?new w(d.toString()):await kt(d,t,null==e?void 0:e.gasFeeMultiplier,l.approve,s,h)}async function Ja(t,e,n,i,s,a,o=!1,c){const u=new r.Contract(i,pt,t);if(!o){const e=await Qa(t,i,n,s);if(new p(e).isGreaterThan(new p(a)))return BigInt(e)}let l=null;const h=await u.approve.estimateGas(s,a);if(c)return h;try{l=await kt(h,t,null==e?void 0:e.gasFeeMultiplier,u.approve,s,a)}catch(t){ut.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return l}async function Wa(t,e,n,i,s,a,o){const c=new r.Contract(n,pt,t),u=await Tt(t,n,s,a),l=await c.transfer.estimateGas(i,u);return o?l:await kt(l,t,null==e?void 0:e.gasFeeMultiplier,c.transfer,i,u)}async function Ya(t,e,n,i,s){const a=new r.Contract(e,pt,t),o=await a.allowance(n,i);return await At(t,e,o,s)}async function Xa(t,e,n,i){const s=new r.Contract(e,pt,t),a=await s.balanceOf(n);return await At(t,e,a,i)}async function Qa(t,e,n,i){const s=new r.Contract(e,pt,t);return await s.allowance(n,i)}async function to(t,e){const n=new r.Contract(e,pt,t),i=await n.decimals();return Number(i)}const eo={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 ro(t){try{const r=JSON.parse(t),n=Object.keys(r)[0];if("error"===n){var e;const t=r[n];return(null==(e=eo[n])?void 0:e[t])||`Provider request failed: ${t}`}{const t=r[n];return`${r[Object.keys(r)[1]]} : ${t}`}}catch(e){return ut.error("[getErrorMessage] error: ",e),t}}async function no(t,e,r,n,i,s,a,o,c="0",u=0,l=0,h=0){const d=I.getDDOClass(t),{datatokens:f}=d.getAssetFields(),{chainId:g,services:p}=d.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 $a.initialize(t.id,p[l].id,0,await e.getAddress(),i||r.oceanNodeUri)).providerFee;if(A&&A.providerFeeAddress!==Dt&&A.providerFeeAmount&&parseInt(A.providerFeeAmount)>0)try{await Ja(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 Ft(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[h].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[h].id),o=await i.getExchange(b[h].id),{baseTokenAmount:d}=await i.calcBaseInGivenDatatokensOut(s.exchangeId,"1",a.consumeMarketFeeAmount),g=new w(+d||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 Za(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 Za(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 io=8996;function so(t){const e=(new gt).getConfig(t);return e&&"oasis"===e.sdk}async function ao(t,e,n,i,s,o,u=!0,l,h,d,g,p,w,m,y){var b,v;const E=I.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 O=(await n.provider.getNetwork()).chainId;if(T&&T!==Number(O))throw new Error("Chain ID from DDO is different than the configured network.");const F=(new gt).getConfig(parseInt(String(O)));let D=await jt(n,F.nftFactoryAddress,s,Number(O));if(D<1){if(8996!==Number(O))throw new Error(`Invalid template index: ${D}`);D=1}const N=new $t(n,Number(O)),L=new Bt(F.nftFactoryAddress,n,Number(O)),P=await n.getAddress(),U={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:P},R={templateIndex:D,cap:"100000",feeAmount:"0",paymentCollector:P,feeToken:h||F.oceanTokenAddress,minter:P,mpFeeAddress:Dt},M={nftAddress:"0x0",datatokenAddress:"0x0",files:i};let B;"oasis"===F.sdk&&(R.filesObject=M,R.accessListFactory=g||F.accessListFactory,R.allowAccessList=p,R.denyAccessList=w);try{if(A)if("0"===A.toString()){const t={dispenserAddress:F.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:Dt};B=await L.createNftWithDatatokenWithDispenser(U,R,t)}else{const t=m||F.oceanTokenAddress;y||(y=await St(this.signer,t));const e={fixedRateAddress:F.fixedRateExchangeAddress,baseTokenAddress:t,owner:P,marketFeeCollector:P,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:A.toString(),marketFee:"0",allowedConsumer:P,withMint:!0};B=await L.createNftWithDatatokenWithFixedRate(U,R,e)}else B=await L.createNftWithDatatoken(U,R)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const _=await B.wait(),G=xt(_,"NFTCreated"),j=xt(_,"TokenCreated"),$=G.args.newTokenAddress,V=j.args.newTokenAddress;if(M.datatokenAddress=V,M.nftAddress=$,"oasis"===F.sdk){const t=new r.Contract(V,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"===F.sdk?"":await $a.encrypt(M,Number(O),l,n,null),C[0].datatokenAddress=V,C[0].serviceEndpoint=l,k=$;const q=E.makeDid(k,T.toString());let z,H,K;if(o=E.updateFields({id:q,nftAddress:k}),u)z=await $a.encrypt(o,Number(O),l,n,null),H=(await d.validate(o,n,l)).hash,K=2;else{const t=JSON.stringify(o),e=Buffer.from(t);z=c(e),H="0x"+Y("sha256").update(z).digest("hex"),K=0}return await N.setMetadata(k,await n.getAddress(),0,l,"",f(K),z,H),o.id}async function oo(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 xt(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{zt as AccessListContract,Ht as AccesslistFactory,Va as Aquarius,et as Config,gt as ConfigHelper,io as DEVELOPMENT_CHAIN_ID,Vt as Datatoken,qt as Datatoken4,Ft as Dispenser,Q as EncryptMethod,Zt as EnterpriseFeeCollectorContract,Kt as EscrowContract,Lt as FEE_HISTORY_NOT_SUPPORTED,X as FileObjectType,Pt as FixedRateExchange,It as GASLIMIT_DEFAULT,dt as KNOWN_CONFIDENTIAL_EVMS,ot as LogLevel,ct as Logger,ut as LoggerInstance,Nt as MAX_UINT_256,$t as Nft,Bt as NftFactory,Na as OCEAN_P2P_PROTOCOL,tt as PROTOCOL_COMMANDS,ja as Provider,$a as ProviderInstance,Ut as Router,Ct as SmartContract,Ot as SmartContractWithAddress,Dt as ZERO_ADDRESS,Ya as allowance,Qa as allowanceWei,Tt as amountToUnits,Za as approve,Ja as approveWei,Xa as balance,jt as calculateActiveTemplateIndex,ht as configHelperNetworks,oo as createAccessListFactory,ao as createAsset,to as decimals,Ka as downloadFile,Ha as downloadFileBrowser,qa as generateDid,Mt as generateDtName,ro as getErrorMessage,xt as getEventFromTx,Et as getFairGasPrice,za as getHash,ft as getNodeEndpointConfig,_t as getOceanArtifactsAddresses,Gt as getOceanArtifactsAddressesByChainId,St as getTokenDecimals,Wt as isDefined,Ga as isP2pUri,pt as minAbi,no as orderAsset,kt as sendTx,vt as setContractDefaults,Yt as signHash,Xt as signRequest,Jt as sleep,Wa as transfer,At as unitsToAmount,so 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 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};
|
|
4
4
|
//# sourceMappingURL=lib.modern.js.map
|