From a7b68be04b859832c5a003cc95ab9ed598acb456 Mon Sep 17 00:00:00 2001 From: Cafe137 <77121044+Cafe137@users.noreply.github.com> Date: Sun, 2 Jun 2024 15:16:21 -0700 Subject: [PATCH] feat!: merge api (#920) * test: add shape tests * feat: merge api --- .depcheckrc.json | 6 - .gitignore | 3 + README.md | 172 ++-- build-fixup | 12 +- package-lock.json | 287 +------ package.json | 21 +- src/bee-debug.ts | 780 ------------------ src/bee.ts | 737 ++++++++++++++++- src/chunk/cac.ts | 8 +- src/chunk/serialize.ts | 16 - src/chunk/soc.ts | 12 +- src/chunk/span.ts | 12 +- src/feed/identifier.ts | 7 +- src/feed/index.ts | 11 +- src/feed/retrievable.ts | 6 +- src/index.ts | 4 +- src/modules/bytes.ts | 6 +- src/modules/bzz.ts | 35 +- src/modules/chunk.ts | 4 +- src/modules/debug/balance.ts | 8 +- src/modules/debug/chequebook.ts | 16 +- src/modules/debug/chunk.ts | 23 +- src/modules/debug/connectivity.ts | 1 + src/modules/debug/settlements.ts | 4 +- src/modules/debug/stake.ts | 6 +- src/modules/debug/states.ts | 24 +- src/modules/debug/status.ts | 48 +- src/modules/debug/tag.ts | 2 +- src/modules/debug/transactions.ts | 8 +- src/modules/feed.ts | 17 +- src/modules/pinning.ts | 8 +- src/modules/pss.ts | 2 +- src/modules/soc.ts | 2 +- src/modules/status.ts | 2 +- src/modules/stewardship.ts | 2 +- src/types/debug.ts | 3 - src/types/index.ts | 29 +- src/types/tar-js.d.ts | 1 - src/types/webpack-bundle-analyzer/index.d.ts | 13 - src/utils/collection.browser.ts | 2 +- src/utils/collection.node.ts | 9 +- src/utils/collection.ts | 41 +- src/utils/data.browser.ts | 58 -- src/utils/data.ts | 3 +- src/utils/error.ts | 12 +- src/utils/eth.ts | 2 +- src/utils/expose.ts | 9 - src/utils/file.ts | 1 - src/utils/http.ts | 6 +- src/utils/redundancy.ts | 1 + src/utils/stream.ts | 163 ---- src/utils/tar-uploader.browser.ts | 31 + src/utils/tar-uploader.ts | 33 + src/utils/tar-writer.browser.ts | 15 + src/utils/tar-writer.ts | 21 + src/utils/tar.browser.ts | 68 ++ src/utils/tar.ts | 65 +- src/utils/type.ts | 7 +- src/utils/uint64.ts | 31 - src/utils/url.ts | 8 +- test/integration/bee-class.spec.ts | 104 +-- test/integration/bee-debug-class.spec.ts | 61 +- test/integration/chunk/soc.spec.ts | 8 +- test/integration/modules/bzz.spec.ts | 16 +- .../integration/modules/debug/balance.spec.ts | 12 +- .../modules/debug/chequebook.spec.ts | 12 +- .../modules/debug/connectivity.spec.ts | 14 +- .../modules/debug/settlements.spec.ts | 6 +- test/integration/modules/debug/states.spec.ts | 8 +- test/integration/modules/debug/status.spec.ts | 31 +- test/integration/modules/debug/tag.spec.ts | 28 - .../modules/debug/transactions.spec.ts | 4 +- test/integration/modules/feed.spec.ts | 14 +- test/integration/modules/pinning.spec.ts | 2 +- test/integration/modules/pss.spec.ts | 27 +- test/integration/modules/stewardship.spec.ts | 2 +- test/shape/get-addresses.ts | 12 + test/shape/get-balances.ts | 6 + test/shape/get-batches.ts | 6 + test/shape/get-chainstate.ts | 8 + test/shape/get-chequebook-address.ts | 5 + test/shape/get-chequebook-balance.ts | 6 + test/shape/get-chequebook-cheque.ts | 6 + test/shape/get-health.ts | 7 + test/shape/get-node.ts | 7 + test/shape/get-peers.ts | 6 + test/shape/get-readiness.ts | 10 + test/shape/get-redistributionstate.ts | 19 + test/shape/get-reservestate.ts | 7 + test/shape/get-settlements.ts | 8 + test/shape/get-stake.ts | 5 + test/shape/get-stamps.ts | 6 + test/shape/get-status.ts | 15 + test/shape/get-timesettlements.ts | 8 + test/shape/get-topology.ts | 16 + test/shape/get-wallet.ts | 9 + test/shape/get-welcome-message.ts | 5 + test/shape/global-stamp.ts | 12 + test/shape/payment.ts | 7 + test/shape/peer-accounting.ts | 11 + test/shape/peer-cheques.ts | 9 + test/shape/peer-metrics.ts | 12 + test/shape/peer-with-balance.ts | 8 + test/shape/peer-with-metrics.ts | 7 + test/shape/peer.ts | 6 + test/shape/settlement.ts | 7 + test/shape/shape.spec.ts | 57 ++ test/shape/stamp.ts | 15 + test/shape/topology-bin-property.ts | 11 + test/shape/topology-bins.ts | 37 + test/shape/types.ts | 267 ++++++ test/shape/wrapped-address.ts | 5 + test/tests-setup.ts | 16 +- test/unit/bee-debug-class.spec.ts | 106 +-- test/unit/chunk/cac.spec.ts | 12 +- test/unit/chunk/serialize.spec.ts | 25 - test/unit/utils/stream.spec.ts | 31 - test/unit/utils/uint64.spec.ts | 103 --- test/utils.ts | 95 +-- webpack.config.ts | 3 +- 120 files changed, 2041 insertions(+), 2291 deletions(-) delete mode 100644 src/bee-debug.ts delete mode 100644 src/chunk/serialize.ts delete mode 100644 src/types/tar-js.d.ts delete mode 100644 src/types/webpack-bundle-analyzer/index.d.ts delete mode 100644 src/utils/stream.ts create mode 100644 src/utils/tar-uploader.browser.ts create mode 100644 src/utils/tar-uploader.ts create mode 100644 src/utils/tar-writer.browser.ts create mode 100644 src/utils/tar-writer.ts create mode 100644 src/utils/tar.browser.ts delete mode 100644 src/utils/uint64.ts delete mode 100644 test/integration/modules/debug/tag.spec.ts create mode 100644 test/shape/get-addresses.ts create mode 100644 test/shape/get-balances.ts create mode 100644 test/shape/get-batches.ts create mode 100644 test/shape/get-chainstate.ts create mode 100644 test/shape/get-chequebook-address.ts create mode 100644 test/shape/get-chequebook-balance.ts create mode 100644 test/shape/get-chequebook-cheque.ts create mode 100644 test/shape/get-health.ts create mode 100644 test/shape/get-node.ts create mode 100644 test/shape/get-peers.ts create mode 100644 test/shape/get-readiness.ts create mode 100644 test/shape/get-redistributionstate.ts create mode 100644 test/shape/get-reservestate.ts create mode 100644 test/shape/get-settlements.ts create mode 100644 test/shape/get-stake.ts create mode 100644 test/shape/get-stamps.ts create mode 100644 test/shape/get-status.ts create mode 100644 test/shape/get-timesettlements.ts create mode 100644 test/shape/get-topology.ts create mode 100644 test/shape/get-wallet.ts create mode 100644 test/shape/get-welcome-message.ts create mode 100644 test/shape/global-stamp.ts create mode 100644 test/shape/payment.ts create mode 100644 test/shape/peer-accounting.ts create mode 100644 test/shape/peer-cheques.ts create mode 100644 test/shape/peer-metrics.ts create mode 100644 test/shape/peer-with-balance.ts create mode 100644 test/shape/peer-with-metrics.ts create mode 100644 test/shape/peer.ts create mode 100644 test/shape/settlement.ts create mode 100644 test/shape/shape.spec.ts create mode 100644 test/shape/stamp.ts create mode 100644 test/shape/topology-bin-property.ts create mode 100644 test/shape/topology-bins.ts create mode 100644 test/shape/types.ts create mode 100644 test/shape/wrapped-address.ts delete mode 100644 test/unit/chunk/serialize.spec.ts delete mode 100644 test/unit/utils/stream.spec.ts delete mode 100644 test/unit/utils/uint64.spec.ts diff --git a/.depcheckrc.json b/.depcheckrc.json index 50bb4ee5..2215a376 100644 --- a/.depcheckrc.json +++ b/.depcheckrc.json @@ -8,16 +8,10 @@ "@babel/preset-typescript", "@commitlint/cli", "@commitlint/config-conventional", - "@types/content-disposition", - "@types/debug", "babel-jest", "babel-loader", - "bufferutil", - "cross-blob", - "debug", "husky", "ts-node", - "utf-8-validate", "webpack-cli", "playwright-test" ] diff --git a/.gitignore b/.gitignore index 8890ce66..92ab4c16 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,6 @@ node_modules # Generated files docs + +*.shape +shaper.ts \ No newline at end of file diff --git a/README.md b/README.md index 779c2c61..dbf4822f 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,47 @@ -# Bee-js +# Bee-JS -[![Tests](https://github.com/ethersphere/bee-js/actions/workflows/tests.yaml/badge.svg)](https://github.com/ethersphere/bee-js/actions/workflows/tests.yaml) -[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fethersphere%2Fbee-js.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fethersphere%2Fbee-js?ref=badge_shield) [![](https://img.shields.io/badge/made%20by-Swarm-blue.svg?style=flat-square)](https://swarm.ethereum.org/) +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fethersphere%2Fbee-js.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fethersphere%2Fbee-js?ref=badge_shield) [![standard-readme compliant](https://img.shields.io/badge/standard--readme-OK-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard) -![](https://img.shields.io/badge/npm-%3E%3D6.9.0-orange.svg?style=flat-square) -![](https://img.shields.io/badge/Node.js-%3E%3D14.0.0-orange.svg?style=flat-square) +![](https://img.shields.io/badge/Node.js-%3E%3D18.0.0-orange.svg?style=flat-square) ![](https://img.shields.io/badge/runs%20in-browser%20%7C%20node%20%7C%20webworker%20%7C%20electron-orange) -> Client library for connecting to Bee decentralised storage +> JavaScript SDK for connecting to a Bee node in the Swarm decentralised storage. -**Warning: This project is in beta state. There might (and most probably will) be changes in the future to its API and working. Also, no guarantees can be made about its stability, efficiency, and security at this stage.** +> Supports Node.js 18+, Vite and Webpack. -This project is intended to be used with **Bee version 1.13.0**. Using it with older or newer Bee versions is not recommended and may not work. Stay up to date by joining the [official Discord](https://discord.gg/GU22h2utj6) and by keeping an eye on the [releases tab](https://github.com/ethersphere/bee-js/releases). +> Write your code in CJS, MJS or TypeScript. -## Table of Contents - -- [Install](#install) - - [npm](#npm) - - [Use in Node.js](#use-in-nodejs) - - [Use in a browser with browserify, webpack or any other bundler](#use-in-a-browser-with-browserify-webpack-or-any-other-bundler) - - [Use in a browser Using a script tag](#use-in-a-browser-using-a-script-tag) -- [Usage](#usage) -- [API](#api) -- [Contribute](#contribute) - - [Setup](#setup) - - [Test](#test) -- [License](#license) +> Intended to be used with Bee version 2.1.0. ## Install -### npm - ```sh -> npm install @ethersphere/bee-js --save +npm install @ethersphere/bee-js ``` -### yarn +or ```sh -> yarn add @ethersphere/bee-js +yarn add @ethersphere/bee-js ``` -Be aware, if you are running Yarn v1 and are attempting to install this repo using GitHub URL, this won't unfortunately -work as it does not correctly handle execution of `prepare` script. +## Import -### Use in Node.js - -**We require Node.js's version of at least 12.x** +### CJS ```js -var BeeJs = require("@ethersphere/bee-js"); +const { Bee } = require('@ethersphere/bee-js') ``` -### Use in a browser with browserify, webpack or any other bundler +### MJS and TypeScript -```js -var BeeJs = require("@ethersphere/bee-js"); +```ts +import { Bee } from '@ethersphere/bee-js' ``` -### Use in a browser Using a script tag +### Script tag Loading this module through a script tag will make the `BeeJs` object available in the global namespace. @@ -70,33 +51,101 @@ Loading this module through a script tag will make the `BeeJs` object available ## Usage +### Create or select an existing postage batch + +Swarm incentivizes nodes in the network to store content, therefor all uploads require a paid +[postage batch](https://docs.ethswarm.org/docs/learn/technology/contracts/postage-stamp). + +```js +import { Bee } from '@ethersphere/bee-js' + +async function getOrCreatePostageBatch() { + const bee = new Bee('http://localhost:1633') + let batchId + + const batches = await bee.getAllPostageBatch() + const usable = batches.find(x => x.usable) + + if (usable) { + batchId = usable.batchID + } else { + batchId = await bee.createPostageBatch('500000000', 20) + } +} +``` + +> The following examples all assume an existing batchId. + +### Upload simple data (Browser + Node.js) + ```js -import { Bee, BeeDebug } from '@ethersphere/bee-js' +import { Bee } from '@ethersphere/bee-js' const bee = new Bee('http://localhost:1633') -const beeDebug = new BeeDebug('http://localhost:1635') -// Be aware, this creates on-chain transactions that spend Eth and BZZ! -const batchId = await bee.createPostageBatch('2000', 20) -const uploadResult = await bee.uploadData(batchId, "Bee is awesome!") +const uploadResult = await bee.uploadData(batchId, 'Bee is awesome!') const data = await bee.downloadData(uploadResult.reference) console.log(data.text()) // prints 'Bee is awesome!' ``` +### Upload data from a file input (React) + +```js +import { Bee } from '@ethersphere/bee-js' + +const bee = new Bee('http://localhost:1633') +const result = await bee.uploadFile(batchId, file) +``` + +### Upload multiple files or a directory (React) + +```js +import { Bee } from '@ethersphere/bee-js' + +const bee = new Bee('http://localhost:1633') +const result = await bee.uploadFiles(batchId, fileList) +``` + +### Upload arbitrary large file (Node.js) + +```js +import { Bee } from '@ethersphere/bee-js' +import { createReadStream } from 'fs' + +const bee = new Bee('http://localhost:1633') +const readable = createReadStream('./path/to/large.bin') +const uploadResult = await bee.uploadFile(batchId, readable) +``` + +### Upload arbitrary large directories (Node.js) + +```js +import { Bee } from '@ethersphere/bee-js' +import { createReadStream } from 'fs' + +const bee = new Bee('http://localhost:1633') +const uploadResult = await bee.uploadFilesFromDirectory(batchId, './path/to/gallery/') +``` + [**Check out our examples repo for some more ideas on how to use `bee-js`**](https://github.com/ethersphere/examples-js) ## Documentation -You can find the full documentation [here](https://bee-js.ethswarm.org/docs). The API reference documentation can be found [here](https://bee-js.ethswarm.org/docs/api). +You can find the full documentation [here](https://bee-js.ethswarm.org/docs). The API reference documentation can be +found [here](https://bee-js.ethswarm.org/docs/api). ## Contribute +Stay up to date by joining the [official Discord](https://discord.gg/GU22h2utj6) and by keeping an eye on the +[releases tab](https://github.com/ethersphere/bee-js/releases). + There are some ways you can make this module better: - Consult our [open issues](https://github.com/ethersphere/bee-js/issues) and take on one of them - Help our tests reach 100% coverage! -- Join us in our [Discord chat](https://discord.gg/wdghaQsGq5) in the #develop-on-swarm channel if you have questions or want to give feedback +- Join us in our [Discord chat](https://discord.gg/wdghaQsGq5) in the #develop-on-swarm channel if you have questions or + want to give feedback ### Setup @@ -106,35 +155,32 @@ Install project dependencies with npm i ``` -### Node 18 - -Node 18 came with its own fetch's native implementation called Undici. If you want to run bee-js tests under Node 18, then disable -the native's fetch implementation otherwise unit tests will fail as they capture HTTP calls with library called `nock` that does -not support native fetch yet. - -``` -export NODE_OPTIONS='--no-experimental-fetch' -``` - ### Test The tests run in both context: node and dom with Jest. -To run the integration tests, you need to spin up local Bee cluster using our [`bee-factory`](https://github.com/ethersphere/bee-factory/) project. -In order to do that you have to have locally Docker running on your machine, but afterwards you can just simply run `npm run bee`, which spins up the -cluster and display Queen's logs. If you want to exit hit `CTRL+C`. +To run the integration tests, you need to spin up local Bee cluster using our +[`fdp-play`](https://github.com/fairDataSociety/fdp-play/) project. In order to do that you have to have locally Docker +running on your machine, but afterwards you can just simply run `npm run bee`, which spins up the cluster and display +Queen's logs. If you want to exit hit `CTRL+C`. -If you want to skip creation of postage stamps every run of integration tests you can create stamps for both nodes and set them under env. variables `BEE_POSTAGE` and `BEE_PEER_POSTAGE`. +If you want to skip creation of postage stamps every run of integration tests you can create stamps for both nodes and +set them under env. variables `BEE_POSTAGE` and `BEE_PEER_POSTAGE`. -By default, for integration tests two bee nodes are expected to run on localhost on addresses `http://localhost:1633` and `http://localhost:11633`. These are the default values for the `bee-factory` script. -If you want to use custom setup, you can change the behavior of tests to different addresses using environment variables `BEE_API_URL`, `BEE_DEBUG_API_URL`, `BEE_PEER_DEBUG_API_URL` and `BEE_PEER_API_URL`. +By default, for integration tests two bee nodes are expected to run on localhost on addresses `http://localhost:1633` +and `http://localhost:11633`. These are the default values for the `fdp-play` script. If you want to use custom setup, +you can change the behavior of tests to different addresses using environment variables `BEE_API_URL` and +`BEE_PEER_API_URL`. There are also browser tests by Puppeteer, which also provide integrity testing. + ```sh npm run test:browser ``` -The test HTML file which Puppeteer uses is the [test/testpage/testpage.html](test/testpage/testpage.html). -To open and manually test BeeJS with developer console, it is necessary to build the library first with `npm run compile:browser` (running the browser tests `npm run test:browser` also builds the library). + +The test HTML file which Puppeteer uses is the [test/testpage/testpage.html](test/testpage/testpage.html). To open and +manually test BeeJS with developer console, it is necessary to build the library first with `npm run compile:browser` +(running the browser tests `npm run test:browser` also builds the library). ### Compile code @@ -146,12 +192,8 @@ or for Browsers `npm run compile:browser` -## Maintainers - - ## License [BSD-3-Clause](./LICENSE) - [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fethersphere%2Fbee-js.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fethersphere%2Fbee-js?ref=badge_large) diff --git a/build-fixup b/build-fixup index 15370057..8dfa0f4f 100755 --- a/build-fixup +++ b/build-fixup @@ -9,6 +9,10 @@ cat >dist/cjs/package.json <dist/mjs/package.json <=14.0.0", - "npm": ">=6.0.0" } }, "node_modules/@ampproject/remapping": { @@ -2705,19 +2689,6 @@ "@types/chai": "*" } }, - "node_modules/@types/content-disposition": { - "version": "0.5.4", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/debug": { - "version": "4.1.7", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/ms": "*" - } - }, "node_modules/@types/elliptic": { "version": "6.4.14", "dev": true, @@ -2792,13 +2763,9 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/ms": { - "version": "0.7.31", - "dev": true, - "license": "MIT" - }, "node_modules/@types/node": { "version": "18.11.11", + "dev": true, "license": "MIT" }, "node_modules/@types/normalize-package-data": { @@ -2811,14 +2778,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/readable-stream": { - "version": "2.3.13", - "license": "MIT", - "dependencies": { - "@types/node": "*", - "safe-buffer": "*" - } - }, "node_modules/@types/semver": { "version": "7.3.13", "dev": true, @@ -3531,9 +3490,9 @@ } }, "node_modules/axios": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.28.0.tgz", - "integrity": "sha512-Tu7NYoGY4Yoc7I+Npf9HhUMtEEpV7ZiLH9yndTCoNhcpBH0kwcvFbzYN9/u5QKI5A6uefjsNNWaz5olJVYS62Q==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.28.1.tgz", + "integrity": "sha512-iUcGA5a7p0mVb4Gm/sy+FSECNkPFT4y7wt6OM/CDpO/OnNCvSs3PoMG8ibrC9jRoGYU0gUK5pXVC4NPXq6lHRQ==", "dependencies": { "follow-redirects": "^1.15.0", "form-data": "^4.0.0", @@ -3651,11 +3610,6 @@ "node": ">=8" } }, - "node_modules/blob-polyfill": { - "version": "5.0.20210201", - "dev": true, - "license": "MIT" - }, "node_modules/bluebird": { "version": "3.7.2", "dev": true, @@ -3727,9 +3681,9 @@ "license": "MIT" }, "node_modules/cafe-utility": { - "version": "15.0.2", - "resolved": "https://registry.npmjs.org/cafe-utility/-/cafe-utility-15.0.2.tgz", - "integrity": "sha512-TNKSfA/q/XRd86NwYtF5QImQB8U5n/hKZuWblYFgYW4aveHcSg2RGOfR3+xquXRXF7BCeNoAXe2/snWFKviPzw==" + "version": "21.3.1", + "resolved": "https://registry.npmjs.org/cafe-utility/-/cafe-utility-21.3.1.tgz", + "integrity": "sha512-6e5dovyMdaWNbWOY+gvpb8LnIwyO7D53uf5At0abjeAbp998B3hohE5aePRSPRSY8nzbNNTsUFmExKpUQaR7Bw==" }, "node_modules/call-bind": { "version": "1.0.2", @@ -4191,18 +4145,6 @@ "dev": true, "license": "MIT" }, - "node_modules/cross-blob": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "blob-polyfill": "^5.0.20210201", - "fetch-blob": "^2.1.2" - }, - "engines": { - "node": "^10.17.0 || >=12.3.0" - } - }, "node_modules/cross-env": { "version": "7.0.3", "dev": true, @@ -4525,11 +4467,6 @@ "ignored": "bin/ignored" } }, - "node_modules/duplexer": { - "version": "0.1.2", - "dev": true, - "license": "MIT" - }, "node_modules/electron-to-chromium": { "version": "1.4.284", "dev": true, @@ -5227,18 +5164,6 @@ "reusify": "^1.0.4" } }, - "node_modules/fetch-blob": { - "version": "2.1.2", - "license": "MIT", - "engines": { - "node": "^10.17.0 || >=12.3.0" - }, - "peerDependenciesMeta": { - "domexception": { - "optional": true - } - } - }, "node_modules/file-entry-cache": { "version": "6.0.1", "dev": true, @@ -5318,9 +5243,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.15.2", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", - "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", + "version": "1.15.6", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz", + "integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==", "funding": [ { "type": "individual", @@ -5584,20 +5509,6 @@ "dev": true, "license": "ISC" }, - "node_modules/gzip-size": { - "version": "6.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "duplexer": "^0.1.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/hard-rejection": { "version": "2.1.0", "dev": true, @@ -7124,17 +7035,6 @@ "node": ">=8.6" } }, - "node_modules/mime": { - "version": "2.5.2", - "dev": true, - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4.0.0" - } - }, "node_modules/mime-db": { "version": "1.47.0", "license": "MIT", @@ -7589,14 +7489,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/opener": { - "version": "1.5.2", - "dev": true, - "license": "(WTFPL OR MIT)", - "bin": { - "opener": "bin/opener-bin.js" - } - }, "node_modules/optionator": { "version": "0.9.1", "dev": true, @@ -8896,6 +8788,7 @@ }, "node_modules/safe-buffer": { "version": "5.1.2", + "dev": true, "license": "MIT" }, "node_modules/safe-regex-test": { @@ -9129,19 +9022,6 @@ "node": ">=8" } }, - "node_modules/sirv": { - "version": "1.0.11", - "dev": true, - "license": "MIT", - "dependencies": { - "@polka/url": "^1.0.0-next.9", - "mime": "^2.3.1", - "totalist": "^1.0.0" - }, - "engines": { - "node": ">= 10" - } - }, "node_modules/slash": { "version": "3.0.0", "dev": true, @@ -9479,9 +9359,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/tar-js": { - "version": "0.3.0" - }, "node_modules/temp-dir": { "version": "2.0.0", "dev": true, @@ -9682,14 +9559,6 @@ "node": ">=8.0" } }, - "node_modules/totalist": { - "version": "1.1.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/trim-newlines": { "version": "3.0.1", "dev": true, @@ -9998,14 +9867,6 @@ "defaults": "^1.0.3" } }, - "node_modules/web-streams-polyfill": { - "version": "4.0.0-beta.3", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", - "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", - "engines": { - "node": ">= 14" - } - }, "node_modules/webpack": { "version": "5.75.0", "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.75.0.tgz", @@ -10053,128 +9914,6 @@ } } }, - "node_modules/webpack-bundle-analyzer": { - "version": "4.5.0", - "dev": true, - "license": "MIT", - "dependencies": { - "acorn": "^8.0.4", - "acorn-walk": "^8.0.0", - "chalk": "^4.1.0", - "commander": "^7.2.0", - "gzip-size": "^6.0.0", - "lodash": "^4.17.20", - "opener": "^1.5.2", - "sirv": "^1.0.7", - "ws": "^7.3.1" - }, - "bin": { - "webpack-bundle-analyzer": "lib/bin/analyzer.js" - }, - "engines": { - "node": ">= 10.13.0" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/acorn-walk": { - "version": "8.0.2", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/ansi-styles": { - "version": "4.3.0", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/chalk": { - "version": "4.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/color-convert": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/color-name": { - "version": "1.1.4", - "dev": true, - "license": "MIT" - }, - "node_modules/webpack-bundle-analyzer/node_modules/commander": { - "version": "7.2.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/has-flag": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/supports-color": { - "version": "7.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/webpack-bundle-analyzer/node_modules/ws": { - "version": "7.5.7", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, "node_modules/webpack-cli": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-5.0.1.tgz", diff --git a/package.json b/package.json index bc55069a..8a88965a 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "types": "dist/types/index.d.ts", "browser": { "stream": false, + "fs": false, "./src/utils/data.ts": "./src/utils/data.browser.ts", "./dist/cjs/utils/data.js": "./dist/cjs/utils/data.browser.js", "./dist/mjs/utils/data.js": "./dist/mjs/utils/data.browser.js", @@ -60,16 +61,12 @@ }, "dependencies": { "@ethersphere/swarm-cid": "^0.1.0", - "@types/readable-stream": "^2.3.13", - "axios": "^0.28.0", - "cafe-utility": "^15.0.2", + "axios": "^0.28.1", + "cafe-utility": "^21.3.1", "elliptic": "^6.5.4", - "fetch-blob": "2.1.2", "isomorphic-ws": "^4.0.1", "js-sha3": "^0.8.0", "semver": "^7.3.5", - "tar-js": "^0.3.0", - "web-streams-polyfill": "^4.0.0-beta.3", "ws": "^8.7.0" }, "devDependencies": { @@ -85,8 +82,6 @@ "@naholyr/cross-env": "^1.0.0", "@types/chai": "^4.3.4", "@types/chai-as-promised": "^7.1.5", - "@types/content-disposition": "^0.5.4", - "@types/debug": "^4.1.7", "@types/elliptic": "^6.4.14", "@types/mocha": "^10.0.1", "@types/node": "^18.11.11", @@ -101,9 +96,7 @@ "chai": "^4.3.7", "chai-as-promised": "^7.1.1", "chai-parentheses": "^0.0.2", - "cross-blob": "^2.0.1", "cross-env": "^7.0.3", - "debug": "^4.3.4", "depcheck": "^1.4.3", "eslint": "^8.13.0", "eslint-config-prettier": "^8.5.0", @@ -122,14 +115,6 @@ "ts-node": "^10.9.1", "typescript": "^4.9.5", "webpack": "^5.75.0", - "webpack-bundle-analyzer": "^4.5.0", "webpack-cli": "^5.0.1" - }, - "engines": { - "node": ">=14.0.0", - "npm": ">=6.0.0", - "beeApiVersion": "4.0.0", - "beeDebugApiVersion": "4.0.0", - "bee": "1.18.2-759f56f" } } diff --git a/src/bee-debug.ts b/src/bee-debug.ts deleted file mode 100644 index 3d5a0134..00000000 --- a/src/bee-debug.ts +++ /dev/null @@ -1,780 +0,0 @@ -import * as balance from './modules/debug/balance' -import * as chequebook from './modules/debug/chequebook' -import * as connectivity from './modules/debug/connectivity' -import * as settlements from './modules/debug/settlements' -import * as stake from './modules/debug/stake' -import * as states from './modules/debug/states' -import * as status from './modules/debug/status' -import * as transactions from './modules/debug/transactions' - -import { Objects, System } from 'cafe-utility' -import * as stamps from './modules/debug/stamps' -import * as tag from './modules/debug/tag' -import type { - Address, - AllSettlements, - BalanceResponse, - BeeRequestOptions, - BeeVersions, - ChainState, - ChequebookAddressResponse, - ChequebookBalanceResponse, - DebugStatus, - ExtendedTag, - Health, - LastCashoutActionResponse, - LastChequesForPeerResponse, - LastChequesResponse, - NodeAddresses, - NodeInfo, - NumberString, - Peer, - PeerBalance, - PingResponse, - PostageBatch, - PostageBatchBuckets, - RedistributionState, - RemovePeerResponse, - ReserveState, - Settlements, - Topology, - TransactionHash, - TransactionInfo, - WalletBalance, -} from './types' -import { - BatchId, - BeeOptions, - CashoutOptions, - PostageBatchOptions, - STAMPS_DEPTH_MAX, - STAMPS_DEPTH_MIN, - Tag, - TransactionOptions, -} from './types' -import { BeeArgumentError, BeeError } from './utils/error' -import { - assertAddress, - assertBatchId, - assertCashoutOptions, - assertNonNegativeInteger, - assertPositiveInteger, - assertPostageBatchOptions, - assertRequestOptions, - assertTransactionHash, - assertTransactionOptions, - isTag, -} from './utils/type' -import { assertBeeUrl, stripLastSlash } from './utils/url' - -export class BeeDebug { - /** - * URL on which is the Debug API of Bee node exposed - */ - public readonly url: string - - /** - * Ky instance that defines connection to Bee node - * @private - */ - private readonly requestOptions: BeeRequestOptions - - constructor(url: string, options?: BeeOptions) { - assertBeeUrl(url) - - // Remove last slash if present, as our endpoint strings starts with `/...` - // which could lead to double slash in URL to which Bee responds with - // unnecessary redirects. - this.url = stripLastSlash(url) - - this.requestOptions = { - baseURL: this.url, - timeout: options?.timeout ?? false, - headers: options?.headers, - onRequest: options?.onRequest, - adapter: options?.adapter, - } - } - - async getNodeAddresses(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return connectivity.getNodeAddresses(this.getRequestOptionsForCall(options)) - } - - async getBlocklist(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return connectivity.getBlocklist(this.getRequestOptionsForCall(options)) - } - - /** - * Retrieve tag extended information from Bee node - * - * @param tagUid UID or tag object to be retrieved - * @throws TypeError if tagUid is in not correct format - * - * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/access-the-swarm/syncing) - * @see [Bee API reference - `GET /tags/{uid}`](https://docs.ethswarm.org/debug-api/#tag/Tag) - * - */ - async retrieveExtendedTag(tagUid: number | Tag, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - if (isTag(tagUid)) { - tagUid = tagUid.uid - } else if (typeof tagUid === 'number') { - assertNonNegativeInteger(tagUid, 'UID') - } else { - throw new TypeError('tagUid has to be either Tag or a number (UID)!') - } - - return tag.retrieveExtendedTag(this.getRequestOptionsForCall(options), tagUid) - } - - /** - * Get list of peers for this node - */ - async getPeers(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return connectivity.getPeers(this.getRequestOptionsForCall(options)) - } - - async removePeer(peer: string | Address, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - assertAddress(peer) - - return connectivity.removePeer(this.getRequestOptionsForCall(options), peer) - } - - async getTopology(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return connectivity.getTopology(this.getRequestOptionsForCall(options)) - } - - async pingPeer(peer: string | Address, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - assertAddress(peer) - - return connectivity.pingPeer(this.getRequestOptionsForCall(options), peer) - } - - /* - * Balance endpoints - */ - - /** - * Get the balances with all known peers including prepaid services - */ - async getAllBalances(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return balance.getAllBalances(this.getRequestOptionsForCall(options)) - } - - /** - * Get the balances with a specific peer including prepaid services - * - * @param address Swarm address of peer - */ - async getPeerBalance(address: Address | string, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - assertAddress(address) - - return balance.getPeerBalance(this.getRequestOptionsForCall(options), address) - } - - /** - * Get the past due consumption balances with all known peers - */ - async getPastDueConsumptionBalances(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return balance.getPastDueConsumptionBalances(this.getRequestOptionsForCall(options)) - } - - /** - * Get the past due consumption balance with a specific peer - * - * @param address Swarm address of peer - */ - async getPastDueConsumptionPeerBalance(address: Address | string, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - assertAddress(address) - - return balance.getPastDueConsumptionPeerBalance(this.getRequestOptionsForCall(options), address) - } - - /* - * Chequebook endpoints - */ - - /** - * Get the address of the chequebook contract used. - * - * **Warning:** The address is returned with 0x prefix unlike all other calls. - * https://github.com/ethersphere/bee/issues/1443 - */ - async getChequebookAddress(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return chequebook.getChequebookAddress(this.getRequestOptionsForCall(options)) - } - - /** - * Get the balance of the chequebook - */ - async getChequebookBalance(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return chequebook.getChequebookBalance(this.getRequestOptionsForCall(options)) - } - - /** - * Get last cheques for all peers - */ - async getLastCheques(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return chequebook.getLastCheques(this.getRequestOptionsForCall(options)) - } - - /** - * Get last cheques for the peer - * - * @param address Swarm address of peer - */ - async getLastChequesForPeer( - address: Address | string, - options?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertAddress(address) - - return chequebook.getLastChequesForPeer(this.getRequestOptionsForCall(options), address) - } - - /** - * Get last cashout action for the peer - * - * @param address Swarm address of peer - */ - async getLastCashoutAction( - address: Address | string, - options?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertAddress(address) - - return chequebook.getLastCashoutAction(this.getRequestOptionsForCall(options), address) - } - - /** - * Cashout the last cheque for the peer - * - * @param address Swarm address of peer - * @param options - * @param options.gasPrice Gas price for the cashout transaction in WEI - * @param options.gasLimit Gas limit for the cashout transaction in WEI - */ - async cashoutLastCheque( - address: string | Address, - options?: CashoutOptions, - requestOptions?: BeeRequestOptions, - ): Promise { - assertCashoutOptions(options) - assertAddress(address) - - return chequebook.cashoutLastCheque(this.getRequestOptionsForCall(requestOptions), address, options) - } - - /** - * Deposit tokens from overlay address into chequebook - * - * @param amount Amount of tokens to deposit (must be positive integer) - * @param gasPrice Gas Price in WEI for the transaction call - * @return string Hash of the transaction - */ - async depositTokens( - amount: number | NumberString, - gasPrice?: NumberString, - options?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertNonNegativeInteger(amount) - - if (gasPrice) { - assertNonNegativeInteger(gasPrice) - } - - return chequebook.depositTokens(this.getRequestOptionsForCall(options), amount, gasPrice) - } - - /** - * Withdraw tokens from the chequebook to the overlay address - * - * @param amount Amount of tokens to withdraw (must be positive integer) - * @param gasPrice Gas Price in WEI for the transaction call - * @return string Hash of the transaction - */ - async withdrawTokens( - amount: number | NumberString, - gasPrice?: NumberString, - options?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertNonNegativeInteger(amount) - - if (gasPrice) { - assertNonNegativeInteger(gasPrice) - } - - return chequebook.withdrawTokens(this.getRequestOptionsForCall(options), amount, gasPrice) - } - - /* - * Settlements endpoint - */ - - /** - * Get amount of sent and received from settlements with a peer - * - * @param address Swarm address of peer - */ - async getSettlements(address: Address | string, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - assertAddress(address) - - return settlements.getSettlements(this.getRequestOptionsForCall(options), address) - } - - /** - * Get settlements with all known peers and total amount sent or received - */ - async getAllSettlements(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return settlements.getAllSettlements(this.getRequestOptionsForCall(options)) - } - - /** - * Get status of node - */ - async getStatus(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return status.getDebugStatus(this.getRequestOptionsForCall(options)) - } - - /** - * Get health of node - */ - async getHealth(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return status.getHealth(this.getRequestOptionsForCall(options)) - } - - /** - * Get readiness of node - */ - async getReadiness(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return status.getReadiness(this.getRequestOptionsForCall(options)) - } - - /** - * Get mode information of node - */ - async getNodeInfo(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return status.getNodeInfo(this.getRequestOptionsForCall(options)) - } - - /** - * Connnects to a node and checks if it is a supported Bee version by the bee-js - * - * @returns true if the Bee node version is supported - * @deprecated Use `BeeDebug.isSupportedExactVersion()` instead - */ - async isSupportedVersion(options?: BeeRequestOptions): Promise | never { - assertRequestOptions(options) - - return status.isSupportedVersion(this.getRequestOptionsForCall(options)) - } - - /** - * Connects to a node and checks if its version matches with the one that bee-js supports. - * - * Be aware that this is the most strict version check and most probably - * you will want to use more relaxed API-versions based checks like - * `BeeDebug.isSupportedApiVersion()`, `BeeDebug.isSupportedMainApiVersion()` or `BeeDebug.isSupportedDebugApiVersion()` - * based on your use-case. - * - * @param options - */ - async isSupportedExactVersion(options?: BeeRequestOptions): Promise | never { - assertRequestOptions(options) - - return status.isSupportedExactVersion(this.getRequestOptionsForCall(options)) - } - - /** - * Connects to a node and checks if its main's API version matches with the one that bee-js supports. - * - * This is useful if you are not using `BeeDebug` class (for anything else then this check) - * and want to make sure about compatibility. - * - * @param options - */ - async isSupportedMainApiVersion(options?: BeeRequestOptions): Promise | never { - assertRequestOptions(options) - - return status.isSupportedMainApiVersion(this.getRequestOptionsForCall(options)) - } - - /** - * Connects to a node and checks if its Debug API version matches with the one that bee-js supports. - * - * This is useful if you are not using `Bee` class in your application and want to make sure - * about compatibility. - * - * @param options - */ - async isSupportedDebugApiVersion(options?: BeeRequestOptions): Promise | never { - assertRequestOptions(options) - - return status.isSupportedDebugApiVersion(this.getRequestOptionsForCall(options)) - } - - /** - * - * Connects to a node and checks if its Main and Debug API versions matches with the one that bee-js supports. - * - * This should be the main way how to check compatibility for your app and Bee node. - * - * @param options - */ - async isSupportedApiVersion(options?: BeeRequestOptions): Promise | never { - assertRequestOptions(options) - - return status.isSupportedDebugApiVersion(this.getRequestOptionsForCall(options)) - } - - /** - * Returns object with all versions specified by the connected Bee node (properties prefixed with `bee*`) - * and versions that bee-js supports (properties prefixed with `supported*`). - * - * @param options - */ - async getVersions(options?: BeeRequestOptions): Promise | never { - assertRequestOptions(options) - - return status.getVersions(this.getRequestOptionsForCall(options)) - } - - /** - * Get reserve state - */ - async getReserveState(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return states.getReserveState(this.getRequestOptionsForCall(options)) - } - - /** - * Get chain state - */ - async getChainState(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return states.getChainState(this.getRequestOptionsForCall(options)) - } - - /** - * Get wallet balances for xDai and BZZ of the Bee node - * - * @param options - */ - async getWalletBalance(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return states.getWalletBalance(this.getRequestOptionsForCall(options)) - } - - /** - * Creates new postage batch from the funds that the node has available in its Ethereum account. - * - * For better understanding what each parameter means and what are the optimal values please see - * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive). - * - * **WARNING: THIS CREATES TRANSACTIONS THAT SPENDS MONEY** - * - * @param amount Amount that represents the value per chunk, has to be greater or equal zero. - * @param depth Logarithm of the number of chunks that can be stamped with the batch. - * @param options Options for creation of postage batch - * @throws BeeArgumentError when negative amount or depth is specified - * @throws TypeError if non-integer value is passed to amount or depth - * - * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) - * @see [Bee Debug API reference - `POST /stamps`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1{amount}~1{depth}/post) - */ - async createPostageBatch( - amount: NumberString, - depth: number, - options?: PostageBatchOptions, - requestOptions?: BeeRequestOptions, - ): Promise { - assertPostageBatchOptions(options) - assertPositiveInteger(amount) - assertNonNegativeInteger(depth) - - if (depth < STAMPS_DEPTH_MIN) { - throw new BeeArgumentError(`Depth has to be at least ${STAMPS_DEPTH_MIN}`, depth) - } - - if (depth > STAMPS_DEPTH_MAX) { - throw new BeeArgumentError(`Depth has to be at most ${STAMPS_DEPTH_MAX}`, depth) - } - - const stamp = await stamps.createPostageBatch(this.getRequestOptionsForCall(requestOptions), amount, depth, options) - - if (options?.waitForUsable !== false) { - await this.waitForUsablePostageStamp(stamp, options?.waitForUsableTimeout) - } - - return stamp - } - - /** - * Topup a fresh amount of BZZ to given Postage Batch. - * - * For better understanding what each parameter means and what are the optimal values please see - * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive). - * - * **WARNING: THIS CREATES TRANSACTIONS THAT SPENDS MONEY** - * - * @param postageBatchId Batch ID - * @param amount Amount to be added to the batch - * @param options Request options - * - * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) - * @see [Bee Debug API reference - `PATCH /stamps/topup/${id}/${amount}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1topup~1{id}~1{amount}/patch) - */ - async topUpBatch(postageBatchId: BatchId | string, amount: NumberString, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - assertNonNegativeInteger(amount, 'Amount') - assertBatchId(postageBatchId) - - await stamps.topUpBatch(this.getRequestOptionsForCall(options), postageBatchId, amount) - } - - /** - * Dilute given Postage Batch with new depth (that has to be bigger then the original depth), which allows - * the Postage Batch to be used for more chunks. - * - * For better understanding what each parameter means and what are the optimal values please see - * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive). - * - * **WARNING: THIS CREATES TRANSACTIONS THAT SPENDS MONEY** - * - * @param postageBatchId Batch ID - * @param depth Amount to be added to the batch - * @param options Request options - * - * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) - * @see [Bee Debug API reference - `PATCH /stamps/topup/${id}/${amount}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1topup~1{id}~1{amount}/patch) - */ - async diluteBatch(postageBatchId: BatchId | string, depth: number, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - assertNonNegativeInteger(depth, 'Depth') - assertBatchId(postageBatchId) - - await stamps.diluteBatch(this.getRequestOptionsForCall(options), postageBatchId, depth) - } - - /** - * Return details for specific postage batch. - * - * @param postageBatchId Batch ID - * - * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) - * @see [Bee Debug API reference - `GET /stamps/${id}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1{id}/get) - */ - async getPostageBatch(postageBatchId: BatchId | string, options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - assertBatchId(postageBatchId) - - return stamps.getPostageBatch(this.getRequestOptionsForCall(options), postageBatchId) - } - - /** - * Return detailed information related to buckets for specific postage batch. - * - * @param postageBatchId Batch ID - * - * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) - * @see [Bee Debug API reference - `GET /stamps/${id}/buckets`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1{id}~1buckets/get) - */ - async getPostageBatchBuckets( - postageBatchId: BatchId | string, - options?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertBatchId(postageBatchId) - - return stamps.getPostageBatchBuckets(this.getRequestOptionsForCall(options), postageBatchId) - } - - /** - * Return all postage batches that has the node available. - * - * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) - * @see [Bee Debug API reference - `GET /stamps`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps/get) - */ - async getAllPostageBatch(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return stamps.getAllPostageBatches(this.getRequestOptionsForCall(options)) - } - - /** - * Return all globally available postage batches. - */ - async getAllGlobalPostageBatch(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return stamps.getGlobalPostageBatches(this.getRequestOptionsForCall(options)) - } - - /** - * Return lists of all current pending transactions that the Bee made - */ - async getAllPendingTransactions(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return transactions.getAllTransactions(this.getRequestOptionsForCall(options)) - } - - /** - * Return transaction information for specific transaction - * @param transactionHash - */ - async getPendingTransaction( - transactionHash: TransactionHash | string, - options?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertTransactionHash(transactionHash) - - return transactions.getTransaction(this.getRequestOptionsForCall(options), transactionHash) - } - - /** - * Rebroadcast already created transaction. - * This is mainly needed when your transaction fall off mempool from other reason is not incorporated into block. - * - * @param transactionHash - */ - async rebroadcastPendingTransaction( - transactionHash: TransactionHash | string, - options?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertTransactionHash(transactionHash) - - return transactions.rebroadcastTransaction(this.getRequestOptionsForCall(options), transactionHash) - } - - /** - * Cancel currently pending transaction - * @param transactionHash - * @param gasPrice - */ - async cancelPendingTransaction( - transactionHash: TransactionHash | string, - gasPrice?: NumberString, - options?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertTransactionHash(transactionHash) - - if (gasPrice) { - assertNonNegativeInteger(gasPrice) - } - - return transactions.cancelTransaction(this.getRequestOptionsForCall(options), transactionHash, gasPrice) - } - - /** - * Gets the staked amount of BZZ (in PLUR unit) as number string. - * - * @param options - */ - async getStake(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return stake.getStake(this.getRequestOptionsForCall(options)) - } - - /** - * Deposits given amount of BZZ token (in PLUR unit). - * - * Be aware that staked BZZ tokens can **not** be withdrawn. - * - * @param amount Amount of BZZ token (in PLUR unit) to be staked. Minimum is 100_000_000_000_000_000 PLUR (10 BZZ). - * @param options - */ - async depositStake( - amount: NumberString, - options?: TransactionOptions, - requestOptions?: BeeRequestOptions, - ): Promise { - assertRequestOptions(options) - assertTransactionOptions(options) - - await stake.stake(this.getRequestOptionsForCall(requestOptions), amount, options) - } - - /** - * Get current status of node in redistribution game - * - * @param options - */ - async getRedistributionState(options?: BeeRequestOptions): Promise { - assertRequestOptions(options) - - return stake.getRedistributionState(this.getRequestOptionsForCall(options)) - } - - private async waitForUsablePostageStamp(id: BatchId, timeout = 240_000): Promise { - const TIME_STEP = 2_000 - for (let time = 0; time < timeout; time += TIME_STEP) { - try { - const stamp = await this.getPostageBatch(id) - - if (stamp.usable) { - return - } - } catch (error: any) { - const message = error?.response?.data?.message || error?.message || '' - - if (!message.includes('batch not usable')) { - throw error - } - } - - await System.sleepMillis(TIME_STEP) - } - - throw new BeeError('Timeout on waiting for postage stamp to become usable') - } - - private getRequestOptionsForCall(options?: BeeRequestOptions): BeeRequestOptions { - return options ? Objects.deepMerge2(this.requestOptions, options) : this.requestOptions - } -} diff --git a/src/bee.ts b/src/bee.ts index 53ac7517..603a78b8 100644 --- a/src/bee.ts +++ b/src/bee.ts @@ -1,5 +1,6 @@ import { ReferenceType } from '@ethersphere/swarm-cid' -import { Objects } from 'cafe-utility' +import { Objects, System } from 'cafe-utility' +import { Readable } from 'stream' import { makeSigner } from './chunk/signer' import { downloadSingleOwnerChunk, uploadSingleOwnerChunkData } from './chunk/soc' import { Index, IndexBytes, makeFeedReader, makeFeedWriter } from './feed' @@ -10,6 +11,16 @@ import { DEFAULT_FEED_TYPE, FeedType, assertFeedType } from './feed/type' import * as bytes from './modules/bytes' import * as bzz from './modules/bzz' import * as chunk from './modules/chunk' +import * as balance from './modules/debug/balance' +import * as chequebook from './modules/debug/chequebook' +import * as connectivity from './modules/debug/connectivity' +import * as settlements from './modules/debug/settlements' +import * as stake from './modules/debug/stake' +import * as stamps from './modules/debug/stamps' +import * as states from './modules/debug/states' +import * as debugStatus from './modules/debug/status' +import * as debugTag from './modules/debug/tag' +import * as transactions from './modules/debug/transactions' import { createFeedManifest } from './modules/feed' import * as pinning from './modules/pinning' import * as pss from './modules/pss' @@ -17,41 +28,75 @@ import * as status from './modules/status' import * as stewardship from './modules/stewardship' import * as tag from './modules/tag' import type { + Address, AddressPrefix, + AllSettlements, AnyJson, + BalanceResponse, BatchId, BeeOptions, BeeRequestOptions, + BeeVersions, + ChainState, + ChequebookAddressResponse, + ChequebookBalanceResponse, CollectionUploadOptions, Data, + DebugStatus, + ExtendedTag, FeedReader, FeedWriter, FileData, FileUploadOptions, + Health, JsonFeedOptions, + LastCashoutActionResponse, + LastChequesForPeerResponse, + LastChequesResponse, + NodeAddresses, + NodeInfo, + NumberString, + Peer, + PeerBalance, Pin, + PingResponse, + PostageBatch, + PostageBatchBuckets, PssMessageHandler, PssSubscription, PublicKey, + RedistributionState, Reference, + RemovePeerResponse, + ReserveState, SOCReader, SOCWriter, + Settlements, Signer, Tag, Topic, + Topology, + TransactionHash, + TransactionInfo, UploadOptions, UploadRedundancyOptions, UploadResultWithCid, + WalletBalance, } from './types' import { AllTagsOptions, CHUNK_SIZE, + CashoutOptions, Collection, FeedManifestResult, - Readable, + PostageBatchOptions, ReferenceCidOrEns, ReferenceOrEns, SPAN_SIZE, + STAMPS_AMOUNT_MIN, + STAMPS_DEPTH_MAX, + STAMPS_DEPTH_MIN, + TransactionOptions, UploadResult, } from './types' import { wrapBytesWithHelpers } from './utils/bytes' @@ -61,22 +106,30 @@ import { prepareWebsocketData } from './utils/data' import { BeeArgumentError, BeeError } from './utils/error' import { EthAddress, makeEthAddress, makeHexEthAddress } from './utils/eth' import { fileArrayBuffer, isFile } from './utils/file' -import { isReadable } from './utils/stream' import { addCidConversionFunction, + assertAddress, assertAddressPrefix, assertAllTagsOptions, assertBatchId, + assertCashoutOptions, assertCollectionUploadOptions, assertData, assertFileData, assertFileUploadOptions, + assertNonNegativeInteger, + assertPositiveInteger, + assertPostageBatchOptions, assertPssMessageHandler, assertPublicKey, assertReference, assertReferenceOrEns, assertRequestOptions, + assertTransactionHash, + assertTransactionOptions, assertUploadOptions, + isReadable, + isTag, makeReferenceOrEns, makeTagUid, } from './utils/type' @@ -100,7 +153,7 @@ export class Bee { public readonly signer?: Signer /** - * Ky instance that defines connection to Bee node + * Options for making requests * @private */ private readonly requestOptions: BeeRequestOptions @@ -126,7 +179,6 @@ export class Bee { timeout: options?.timeout ?? false, headers: options?.headers, onRequest: options?.onRequest, - adapter: options?.adapter, } } @@ -405,7 +457,7 @@ export class Bee { */ async uploadCollection( postageBatchId: string | BatchId, - collection: Collection, + collection: Collection, options?: CollectionUploadOptions & UploadRedundancyOptions, ): Promise { assertBatchId(postageBatchId) @@ -893,9 +945,6 @@ export class Bee { canonicalOwner, canonicalTopic, postageBatchId, - { - type, - }, ) return addCidConversionFunction({ reference }, ReferenceType.FEED) @@ -1113,6 +1162,676 @@ export class Bee { return true } + // Legacy debug API + + async getNodeAddresses(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return connectivity.getNodeAddresses(this.getRequestOptionsForCall(options)) + } + + async getBlocklist(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return connectivity.getBlocklist(this.getRequestOptionsForCall(options)) + } + + /** + * Retrieve tag extended information from Bee node + * + * @param tagUid UID or tag object to be retrieved + * @throws TypeError if tagUid is in not correct format + * + * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/access-the-swarm/syncing) + * @see [Bee API reference - `GET /tags/{uid}`](https://docs.ethswarm.org/debug-api/#tag/Tag) + * + */ + async retrieveExtendedTag(tagUid: number | Tag, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + if (isTag(tagUid)) { + tagUid = tagUid.uid + } else if (typeof tagUid === 'number') { + assertNonNegativeInteger(tagUid, 'UID') + } else { + throw new TypeError('tagUid has to be either Tag or a number (UID)!') + } + + return debugTag.retrieveExtendedTag(this.getRequestOptionsForCall(options), tagUid) + } + + /** + * Get list of peers for this node + */ + async getPeers(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return connectivity.getPeers(this.getRequestOptionsForCall(options)) + } + + async removePeer(peer: string | Address, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + assertAddress(peer) + + return connectivity.removePeer(this.getRequestOptionsForCall(options), peer) + } + + async getTopology(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return connectivity.getTopology(this.getRequestOptionsForCall(options)) + } + + async pingPeer(peer: string | Address, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + assertAddress(peer) + + return connectivity.pingPeer(this.getRequestOptionsForCall(options), peer) + } + + /* + * Balance endpoints + */ + + /** + * Get the balances with all known peers including prepaid services + */ + async getAllBalances(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return balance.getAllBalances(this.getRequestOptionsForCall(options)) + } + + /** + * Get the balances with a specific peer including prepaid services + * + * @param address Swarm address of peer + */ + async getPeerBalance(address: Address | string, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + assertAddress(address) + + return balance.getPeerBalance(this.getRequestOptionsForCall(options), address) + } + + /** + * Get the past due consumption balances with all known peers + */ + async getPastDueConsumptionBalances(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return balance.getPastDueConsumptionBalances(this.getRequestOptionsForCall(options)) + } + + /** + * Get the past due consumption balance with a specific peer + * + * @param address Swarm address of peer + */ + async getPastDueConsumptionPeerBalance(address: Address | string, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + assertAddress(address) + + return balance.getPastDueConsumptionPeerBalance(this.getRequestOptionsForCall(options), address) + } + + /* + * Chequebook endpoints + */ + + /** + * Get the address of the chequebook contract used. + * + * **Warning:** The address is returned with 0x prefix unlike all other calls. + * https://github.com/ethersphere/bee/issues/1443 + */ + async getChequebookAddress(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return chequebook.getChequebookAddress(this.getRequestOptionsForCall(options)) + } + + /** + * Get the balance of the chequebook + */ + async getChequebookBalance(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return chequebook.getChequebookBalance(this.getRequestOptionsForCall(options)) + } + + /** + * Get last cheques for all peers + */ + async getLastCheques(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return chequebook.getLastCheques(this.getRequestOptionsForCall(options)) + } + + /** + * Get last cheques for the peer + * + * @param address Swarm address of peer + */ + async getLastChequesForPeer( + address: Address | string, + options?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertAddress(address) + + return chequebook.getLastChequesForPeer(this.getRequestOptionsForCall(options), address) + } + + /** + * Get last cashout action for the peer + * + * @param address Swarm address of peer + */ + async getLastCashoutAction( + address: Address | string, + options?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertAddress(address) + + return chequebook.getLastCashoutAction(this.getRequestOptionsForCall(options), address) + } + + /** + * Cashout the last cheque for the peer + * + * @param address Swarm address of peer + * @param options + * @param options.gasPrice Gas price for the cashout transaction in WEI + * @param options.gasLimit Gas limit for the cashout transaction in WEI + */ + async cashoutLastCheque( + address: string | Address, + options?: CashoutOptions, + requestOptions?: BeeRequestOptions, + ): Promise { + assertCashoutOptions(options) + assertAddress(address) + + return chequebook.cashoutLastCheque(this.getRequestOptionsForCall(requestOptions), address, options) + } + + /** + * Deposit tokens from overlay address into chequebook + * + * @param amount Amount of tokens to deposit (must be positive integer) + * @param gasPrice Gas Price in WEI for the transaction call + * @return string Hash of the transaction + */ + async depositTokens( + amount: number | NumberString, + gasPrice?: NumberString, + options?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertNonNegativeInteger(amount) + + if (gasPrice) { + assertNonNegativeInteger(gasPrice) + } + + return chequebook.depositTokens(this.getRequestOptionsForCall(options), amount, gasPrice) + } + + /** + * Withdraw tokens from the chequebook to the overlay address + * + * @param amount Amount of tokens to withdraw (must be positive integer) + * @param gasPrice Gas Price in WEI for the transaction call + * @return string Hash of the transaction + */ + async withdrawTokens( + amount: number | NumberString, + gasPrice?: NumberString, + options?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertNonNegativeInteger(amount) + + if (gasPrice) { + assertNonNegativeInteger(gasPrice) + } + + return chequebook.withdrawTokens(this.getRequestOptionsForCall(options), amount, gasPrice) + } + + /* + * Settlements endpoint + */ + + /** + * Get amount of sent and received from settlements with a peer + * + * @param address Swarm address of peer + */ + async getSettlements(address: Address | string, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + assertAddress(address) + + return settlements.getSettlements(this.getRequestOptionsForCall(options), address) + } + + /** + * Get settlements with all known peers and total amount sent or received + */ + async getAllSettlements(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return settlements.getAllSettlements(this.getRequestOptionsForCall(options)) + } + + /** + * Get status of node + */ + async getStatus(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return debugStatus.getDebugStatus(this.getRequestOptionsForCall(options)) + } + + /** + * Get health of node + */ + async getHealth(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return debugStatus.getHealth(this.getRequestOptionsForCall(options)) + } + + /** + * Get readiness of node + */ + async getReadiness(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return debugStatus.getReadiness(this.getRequestOptionsForCall(options)) + } + + /** + * Get mode information of node + */ + async getNodeInfo(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return debugStatus.getNodeInfo(this.getRequestOptionsForCall(options)) + } + + /** + * Connnects to a node and checks if it is a supported Bee version by the bee-js + * + * @returns true if the Bee node version is supported + * @deprecated Use `BeeDebug.isSupportedExactVersion()` instead + */ + async isSupportedVersion(options?: BeeRequestOptions): Promise | never { + assertRequestOptions(options) + + return debugStatus.isSupportedVersion(this.getRequestOptionsForCall(options)) + } + + /** + * Connects to a node and checks if its version matches with the one that bee-js supports. + * + * Be aware that this is the most strict version check and most probably + * you will want to use more relaxed API-versions based checks like + * `BeeDebug.isSupportedApiVersion()`, `BeeDebug.isSupportedMainApiVersion()` or `BeeDebug.isSupportedDebugApiVersion()` + * based on your use-case. + * + * @param options + */ + async isSupportedExactVersion(options?: BeeRequestOptions): Promise | never { + assertRequestOptions(options) + + return debugStatus.isSupportedExactVersion(this.getRequestOptionsForCall(options)) + } + + /** + * Connects to a node and checks if its main's API version matches with the one that bee-js supports. + * + * This is useful if you are not using `BeeDebug` class (for anything else then this check) + * and want to make sure about compatibility. + * + * @param options + */ + async isSupportedMainApiVersion(options?: BeeRequestOptions): Promise | never { + assertRequestOptions(options) + + return debugStatus.isSupportedMainApiVersion(this.getRequestOptionsForCall(options)) + } + + /** + * + * Connects to a node and checks if its Main API version matches with the one that bee-js supports. + * + * This should be the main way how to check compatibility for your app and Bee node. + * + * @param options + */ + async isSupportedApiVersion(options?: BeeRequestOptions): Promise | never { + assertRequestOptions(options) + + return debugStatus.isSupportedApiVersion(this.getRequestOptionsForCall(options)) + } + + /** + * Returns object with all versions specified by the connected Bee node (properties prefixed with `bee*`) + * and versions that bee-js supports (properties prefixed with `supported*`). + * + * @param options + */ + async getVersions(options?: BeeRequestOptions): Promise | never { + assertRequestOptions(options) + + return debugStatus.getVersions(this.getRequestOptionsForCall(options)) + } + + /** + * Get reserve state + */ + async getReserveState(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return states.getReserveState(this.getRequestOptionsForCall(options)) + } + + /** + * Get chain state + */ + async getChainState(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return states.getChainState(this.getRequestOptionsForCall(options)) + } + + /** + * Get wallet balances for xDai and BZZ of the Bee node + * + * @param options + */ + async getWalletBalance(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return states.getWalletBalance(this.getRequestOptionsForCall(options)) + } + + /** + * Creates new postage batch from the funds that the node has available in its Ethereum account. + * + * For better understanding what each parameter means and what are the optimal values please see + * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive). + * + * **WARNING: THIS CREATES TRANSACTIONS THAT SPENDS MONEY** + * + * @param amount Amount that represents the value per chunk, has to be greater or equal zero. + * @param depth Logarithm of the number of chunks that can be stamped with the batch. + * @param options Options for creation of postage batch + * @throws BeeArgumentError when negative amount or depth is specified + * @throws TypeError if non-integer value is passed to amount or depth + * + * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) + * @see [Bee Debug API reference - `POST /stamps`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1{amount}~1{depth}/post) + */ + async createPostageBatch( + amount: NumberString, + depth: number, + options?: PostageBatchOptions, + requestOptions?: BeeRequestOptions, + ): Promise { + assertPostageBatchOptions(options) + assertPositiveInteger(amount) + assertNonNegativeInteger(depth) + + if (depth < STAMPS_DEPTH_MIN) { + throw new BeeArgumentError(`Depth has to be at least ${STAMPS_DEPTH_MIN}`, depth) + } + + if (depth > STAMPS_DEPTH_MAX) { + throw new BeeArgumentError(`Depth has to be at most ${STAMPS_DEPTH_MAX}`, depth) + } + + if (parseInt(amount, 10) < STAMPS_AMOUNT_MIN) { + throw new BeeArgumentError(`Amount has to be at least ${STAMPS_AMOUNT_MIN} (1 day)`, amount) + } + + const stamp = await stamps.createPostageBatch(this.getRequestOptionsForCall(requestOptions), amount, depth, options) + + if (options?.waitForUsable !== false) { + await this.waitForUsablePostageStamp(stamp, options?.waitForUsableTimeout) + } + + return stamp + } + + /** + * Topup a fresh amount of BZZ to given Postage Batch. + * + * For better understanding what each parameter means and what are the optimal values please see + * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive). + * + * **WARNING: THIS CREATES TRANSACTIONS THAT SPENDS MONEY** + * + * @param postageBatchId Batch ID + * @param amount Amount to be added to the batch + * @param options Request options + * + * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) + * @see [Bee Debug API reference - `PATCH /stamps/topup/${id}/${amount}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1topup~1{id}~1{amount}/patch) + */ + async topUpBatch(postageBatchId: BatchId | string, amount: NumberString, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + assertNonNegativeInteger(amount, 'Amount') + assertBatchId(postageBatchId) + + await stamps.topUpBatch(this.getRequestOptionsForCall(options), postageBatchId, amount) + } + + /** + * Dilute given Postage Batch with new depth (that has to be bigger then the original depth), which allows + * the Postage Batch to be used for more chunks. + * + * For better understanding what each parameter means and what are the optimal values please see + * [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive). + * + * **WARNING: THIS CREATES TRANSACTIONS THAT SPENDS MONEY** + * + * @param postageBatchId Batch ID + * @param depth Amount to be added to the batch + * @param options Request options + * + * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) + * @see [Bee Debug API reference - `PATCH /stamps/topup/${id}/${amount}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1topup~1{id}~1{amount}/patch) + */ + async diluteBatch(postageBatchId: BatchId | string, depth: number, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + assertNonNegativeInteger(depth, 'Depth') + assertBatchId(postageBatchId) + + await stamps.diluteBatch(this.getRequestOptionsForCall(options), postageBatchId, depth) + } + + /** + * Return details for specific postage batch. + * + * @param postageBatchId Batch ID + * + * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) + * @see [Bee Debug API reference - `GET /stamps/${id}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1{id}/get) + */ + async getPostageBatch(postageBatchId: BatchId | string, options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + assertBatchId(postageBatchId) + + return stamps.getPostageBatch(this.getRequestOptionsForCall(options), postageBatchId) + } + + /** + * Return detailed information related to buckets for specific postage batch. + * + * @param postageBatchId Batch ID + * + * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) + * @see [Bee Debug API reference - `GET /stamps/${id}/buckets`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1{id}~1buckets/get) + */ + async getPostageBatchBuckets( + postageBatchId: BatchId | string, + options?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertBatchId(postageBatchId) + + return stamps.getPostageBatchBuckets(this.getRequestOptionsForCall(options), postageBatchId) + } + + /** + * Return all postage batches that has the node available. + * + * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) + * @see [Bee Debug API reference - `GET /stamps`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps/get) + */ + async getAllPostageBatch(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return stamps.getAllPostageBatches(this.getRequestOptionsForCall(options)) + } + + /** + * Return all globally available postage batches. + */ + async getAllGlobalPostageBatch(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return stamps.getGlobalPostageBatches(this.getRequestOptionsForCall(options)) + } + + /** + * Return lists of all current pending transactions that the Bee made + */ + async getAllPendingTransactions(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return transactions.getAllTransactions(this.getRequestOptionsForCall(options)) + } + + /** + * Return transaction information for specific transaction + * @param transactionHash + */ + async getPendingTransaction( + transactionHash: TransactionHash | string, + options?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertTransactionHash(transactionHash) + + return transactions.getTransaction(this.getRequestOptionsForCall(options), transactionHash) + } + + /** + * Rebroadcast already created transaction. + * This is mainly needed when your transaction fall off mempool from other reason is not incorporated into block. + * + * @param transactionHash + */ + async rebroadcastPendingTransaction( + transactionHash: TransactionHash | string, + options?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertTransactionHash(transactionHash) + + return transactions.rebroadcastTransaction(this.getRequestOptionsForCall(options), transactionHash) + } + + /** + * Cancel currently pending transaction + * @param transactionHash + * @param gasPrice + */ + async cancelPendingTransaction( + transactionHash: TransactionHash | string, + gasPrice?: NumberString, + options?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertTransactionHash(transactionHash) + + if (gasPrice) { + assertNonNegativeInteger(gasPrice) + } + + return transactions.cancelTransaction(this.getRequestOptionsForCall(options), transactionHash, gasPrice) + } + + /** + * Gets the staked amount of BZZ (in PLUR unit) as number string. + * + * @param options + */ + async getStake(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return stake.getStake(this.getRequestOptionsForCall(options)) + } + + /** + * Deposits given amount of BZZ token (in PLUR unit). + * + * Be aware that staked BZZ tokens can **not** be withdrawn. + * + * @param amount Amount of BZZ token (in PLUR unit) to be staked. Minimum is 100_000_000_000_000_000 PLUR (10 BZZ). + * @param options + */ + async depositStake( + amount: NumberString, + options?: TransactionOptions, + requestOptions?: BeeRequestOptions, + ): Promise { + assertRequestOptions(options) + assertTransactionOptions(options) + + await stake.stake(this.getRequestOptionsForCall(requestOptions), amount, options) + } + + /** + * Get current status of node in redistribution game + * + * @param options + */ + async getRedistributionState(options?: BeeRequestOptions): Promise { + assertRequestOptions(options) + + return stake.getRedistributionState(this.getRequestOptionsForCall(options)) + } + + private async waitForUsablePostageStamp(id: BatchId, timeout = 240_000): Promise { + const TIME_STEP = 2_000 + for (let time = 0; time < timeout; time += TIME_STEP) { + try { + const stamp = await this.getPostageBatch(id) + + if (stamp.usable) { + return + } + } catch (error: any) { + const message = error?.response?.data?.message || error?.message || '' + + if (!message.includes('batch not usable')) { + throw error + } + } + + await System.sleepMillis(TIME_STEP) + } + + throw new BeeError('Timeout on waiting for postage stamp to become usable') + } + /** * @param signer * @private diff --git a/src/chunk/cac.ts b/src/chunk/cac.ts index 93c072e5..0dfea9fc 100644 --- a/src/chunk/cac.ts +++ b/src/chunk/cac.ts @@ -1,9 +1,9 @@ +import { Binary } from 'cafe-utility' import { BrandedType, PlainBytesReference } from '../types' +import { Bytes, FlexBytes, assertFlexBytes, bytesEqual, flexBytesAtOffset } from '../utils/bytes' import { BeeError } from '../utils/error' import { bmtHash } from './bmt' -import { assertFlexBytes, Bytes, bytesEqual, FlexBytes, flexBytesAtOffset } from '../utils/bytes' -import { serializeBytes } from './serialize' -import { makeSpan, SPAN_SIZE } from './span' +import { SPAN_SIZE, makeSpan } from './span' export const MIN_PAYLOAD_SIZE = 1 export const MAX_PAYLOAD_SIZE = 4096 @@ -38,7 +38,7 @@ type ValidChunkData = BrandedType export function makeContentAddressedChunk(payloadBytes: Uint8Array): Chunk { const span = makeSpan(payloadBytes.length) assertFlexBytes(payloadBytes, MIN_PAYLOAD_SIZE, MAX_PAYLOAD_SIZE) - const data = serializeBytes(span, payloadBytes) as ValidChunkData + const data = Binary.concatBytes(span, payloadBytes) as ValidChunkData return { data, diff --git a/src/chunk/serialize.ts b/src/chunk/serialize.ts deleted file mode 100644 index ce32834a..00000000 --- a/src/chunk/serialize.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Helper function for serialize byte arrays - * - * @param arrays Any number of byte array arguments - */ -export function serializeBytes(...arrays: Uint8Array[]): Uint8Array { - const length = arrays.reduce((prev, curr) => prev + curr.length, 0) - const buffer = new Uint8Array(length) - let offset = 0 - arrays.forEach(arr => { - buffer.set(arr, offset) - offset += arr.length - }) - - return buffer -} diff --git a/src/chunk/soc.ts b/src/chunk/soc.ts index fb91f7fc..53bba1f6 100644 --- a/src/chunk/soc.ts +++ b/src/chunk/soc.ts @@ -1,3 +1,4 @@ +import { Binary } from 'cafe-utility' import * as chunkAPI from '../modules/chunk' import * as socAPI from '../modules/soc' import { BatchId, BeeRequestOptions, PlainBytesReference, Reference, Signature, Signer, UploadOptions } from '../types' @@ -8,8 +9,7 @@ import { keccak256Hash } from '../utils/hash' import { bytesToHex } from '../utils/hex' import { assertAddress } from '../utils/type' import { bmtHash } from './bmt' -import { assertValidChunkData, Chunk, makeContentAddressedChunk, MAX_PAYLOAD_SIZE, MIN_PAYLOAD_SIZE } from './cac' -import { serializeBytes } from './serialize' +import { Chunk, MAX_PAYLOAD_SIZE, MIN_PAYLOAD_SIZE, assertValidChunkData, makeContentAddressedChunk } from './cac' import { recoverAddress, sign } from './signer' import { SPAN_SIZE } from './span' @@ -101,7 +101,7 @@ export async function makeSingleOwnerChunk( const digest = keccak256Hash(identifier, chunkAddress) const signature = await sign(signer, digest) - const data = serializeBytes(identifier, signature, chunk.span(), chunk.payload()) + const data = Binary.concatBytes(identifier, signature, chunk.span(), chunk.payload()) const address = makeSOCAddress(identifier, signer.address) return { @@ -120,7 +120,7 @@ export async function makeSingleOwnerChunk( * * It uses the Chunk API and calculates the address before uploading. * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param chunk A chunk object * @param postageBatchId Postage BatchId that will be assigned to uploaded data * @param options Upload options @@ -134,7 +134,7 @@ export async function uploadSingleOwnerChunk( const owner = bytesToHex(chunk.owner()) const identifier = bytesToHex(chunk.identifier()) const signature = bytesToHex(chunk.signature()) - const data = serializeBytes(chunk.span(), chunk.payload()) + const data = Binary.concatBytes(chunk.span(), chunk.payload()) return socAPI.upload(requestOptions, owner, identifier, signature, data, postageBatchId, options) } @@ -142,7 +142,7 @@ export async function uploadSingleOwnerChunk( /** * Helper function to create and upload SOC. * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param signer The singer interface for signing the chunk * @param postageBatchId * @param identifier The identifier of the chunk diff --git a/src/chunk/span.ts b/src/chunk/span.ts index 0cbdd7c9..9995eea9 100644 --- a/src/chunk/span.ts +++ b/src/chunk/span.ts @@ -1,5 +1,6 @@ -import { BeeArgumentError } from '../utils/error' +import { Binary } from 'cafe-utility' import { Bytes } from '../utils/bytes' +import { BeeArgumentError } from '../utils/error' export const SPAN_SIZE = 8 @@ -22,12 +23,5 @@ export function makeSpan(length: number): Bytes<8> { throw new BeeArgumentError('invalid length (> MAX_SPAN_LENGTH)', length) } - const span = new Uint8Array(SPAN_SIZE) - const dataView = new DataView(span.buffer) - const littleEndian = true - const lengthLower32 = length & 0xffffffff - - dataView.setUint32(0, lengthLower32, littleEndian) - - return span as Bytes<8> + return Binary.numberToUint64LE(length) as Bytes<8> } diff --git a/src/feed/identifier.ts b/src/feed/identifier.ts index e2561520..a3ef4dad 100644 --- a/src/feed/identifier.ts +++ b/src/feed/identifier.ts @@ -1,8 +1,9 @@ -import { FEED_INDEX_HEX_LENGTH, Topic } from '../types' +import { Binary } from 'cafe-utility' import { Identifier } from '../chunk/soc' +import { FEED_INDEX_HEX_LENGTH, Topic } from '../types' +import { Bytes } from '../utils/expose' import { keccak256Hash } from '../utils/hash' import { hexToBytes, makeHexString } from '../utils/hex' -import { writeUint64BigEndian } from '../utils/uint64' import { Epoch, Index, IndexBytes } from './index' function isEpoch(epoch: unknown): epoch is Epoch { @@ -14,7 +15,7 @@ function hashFeedIdentifier(topic: Topic, index: IndexBytes): Identifier { } function makeSequentialFeedIdentifier(topic: Topic, index: number): Identifier { - const indexBytes = writeUint64BigEndian(index) + const indexBytes = Binary.numberToUint64BE(index) as Bytes<8> return hashFeedIdentifier(topic, indexBytes) } diff --git a/src/feed/index.ts b/src/feed/index.ts index fa1d59a4..dc1903ec 100644 --- a/src/feed/index.ts +++ b/src/feed/index.ts @@ -1,4 +1,4 @@ -import { serializeBytes } from '../chunk/serialize' +import { Binary } from 'cafe-utility' import { makeSingleOwnerChunkFromData, uploadSingleOwnerChunkData } from '../chunk/soc' import * as chunkAPI from '../modules/chunk' import { FeedUpdateOptions, FetchFeedUpdateResponse, fetchLatestFeedUpdate } from '../modules/feed' @@ -22,7 +22,6 @@ import { keccak256Hash } from '../utils/hash' import { HexString, bytesToHex, hexToBytes, makeHexString } from '../utils/hex' import { makeBytesReference } from '../utils/reference' import { assertAddress } from '../utils/type' -import { readUint64BigEndian, writeUint64BigEndian } from '../utils/uint64' import { makeFeedIdentifier } from './identifier' import type { FeedType } from './type' @@ -80,8 +79,8 @@ export async function updateFeed( const identifier = makeFeedIdentifier(topic, nextIndex) const at = options?.at ?? Date.now() / 1000.0 - const timestamp = writeUint64BigEndian(at) - const payloadBytes = serializeBytes(timestamp, reference) + const timestamp = Binary.numberToUint64BE(at) + const payloadBytes = Binary.concatBytes(timestamp, reference) return uploadSingleOwnerChunkData(requestOptions, signer, postageBatchId, identifier, payloadBytes, options) } @@ -104,7 +103,7 @@ export async function downloadFeedUpdate( const soc = makeSingleOwnerChunkFromData(data, address) const payload = soc.payload() const timestampBytes = bytesAtOffset(payload, TIMESTAMP_PAYLOAD_OFFSET, TIMESTAMP_PAYLOAD_SIZE) - const timestamp = readUint64BigEndian(timestampBytes) + const timestamp = Binary.uint64BEToNumber(timestampBytes) const reference = makeBytesReference(payload, REFERENCE_PAYLOAD_OFFSET) return { @@ -125,7 +124,7 @@ export function makeFeedReader( topic, async download(options?: FeedUpdateOptions): Promise { if (!options?.index && options?.index !== 0) { - return fetchLatestFeedUpdate(requestOptions, owner, topic, { ...options, type }) + return fetchLatestFeedUpdate(requestOptions, owner, topic) } const update = await downloadFeedUpdate(requestOptions, hexToBytes(owner), topic, options.index) diff --git a/src/feed/retrievable.ts b/src/feed/retrievable.ts index ecd0fb34..9ccb1669 100644 --- a/src/feed/retrievable.ts +++ b/src/feed/retrievable.ts @@ -1,13 +1,13 @@ +import { Binary } from 'cafe-utility' import { Bee } from '../bee' import { BeeRequestOptions, Reference, Topic } from '../types' import { EthAddress } from '../utils/eth' import { bytesToHex } from '../utils/hex' -import { readUint64BigEndian } from '../utils/uint64' -import { getFeedUpdateChunkReference, Index } from './index' +import { Index, getFeedUpdateChunkReference } from './index' function makeNumericIndex(index: Index): number { if (index instanceof Uint8Array) { - return readUint64BigEndian(index) + return Binary.uint64BEToNumber(index) } if (typeof index === 'string') { diff --git a/src/index.ts b/src/index.ts index 239660d0..ca9b058f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,10 @@ import { Bee } from './bee' -import { BeeDebug } from './bee-debug' export { SUPPORTED_BEE_VERSION, SUPPORTED_BEE_VERSION_EXACT } from './modules/debug/status' export * from './types' export * from './utils/error' export * as Utils from './utils/expose' -export { Bee, BeeDebug } +export { Bee } // for require-like imports declare global { @@ -13,7 +12,6 @@ declare global { // binded as 'BeeJs' via Webpack BeeJs: { Bee: typeof import('./bee').Bee - BeeDebug: typeof import('./bee-debug').BeeDebug Utils: typeof import('./utils/expose') BeeError: typeof import('./utils/error').BeeError BeeArgumentError: typeof import('./utils/error').BeeArgumentError diff --git a/src/modules/bytes.ts b/src/modules/bytes.ts index 50ef0b40..04ec5585 100644 --- a/src/modules/bytes.ts +++ b/src/modules/bytes.ts @@ -19,7 +19,7 @@ const endpoint = 'bytes' /** * Upload data to a Bee node * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param data Data to be uploaded * @param postageBatchId Postage BatchId that will be assigned to uploaded data * @param options Additional options like tag, encryption, pinning @@ -50,7 +50,7 @@ export async function upload( /** * Download data as a byte array * - * @param ky + * @param requestOptions Options for making requests * @param hash Bee content reference */ export async function download( @@ -70,7 +70,7 @@ export async function download( /** * Download data as a readable stream * - * @param ky + * @param requestOptions Options for making requests * @param hash Bee content reference */ export async function downloadReadable( diff --git a/src/modules/bzz.ts b/src/modules/bzz.ts index 2cccffaa..c2d9453a 100644 --- a/src/modules/bzz.ts +++ b/src/modules/bzz.ts @@ -1,3 +1,4 @@ +import { Readable } from 'stream' import { BatchId, BeeRequestOptions, @@ -7,7 +8,6 @@ import { DownloadRedundancyOptions, FileData, FileUploadOptions, - Readable, Reference, ReferenceOrEns, UploadHeaders, @@ -18,9 +18,8 @@ import { wrapBytesWithHelpers } from '../utils/bytes' import { assertCollection } from '../utils/collection' import { extractDownloadHeaders, extractRedundantUploadHeaders, readFileHeaders } from '../utils/headers' import { http } from '../utils/http' -import { isReadable } from '../utils/stream' -import { makeTar } from '../utils/tar' -import { makeTagUid } from '../utils/type' +import { uploadTar } from '../utils/tar-uploader' +import { isReadable, makeTagUid } from '../utils/type' const bzzEndpoint = 'bzz' @@ -45,7 +44,7 @@ function extractFileUploadHeaders( /** * Upload single file * - * @param ky + * @param requestOptions Options for making requests * @param data Files data * @param postageBatchId Postage BatchId that will be assigned to uploaded data * @param name Name that will be attached to the uploaded file. Wraps the data into manifest with set index document. @@ -85,7 +84,7 @@ export async function uploadFile( /** * Download single file as a buffer * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param hash Bee file or collection hash * @param path If hash is collection then this defines path to a single file in the collection */ @@ -112,7 +111,7 @@ export async function downloadFile( /** * Download single file as a readable stream * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param hash Bee file or collection hash * @param path If hash is collection then this defines path to a single file in the collection */ @@ -140,12 +139,12 @@ export async function downloadFileReadable( // Collections -interface CollectionUploadHeaders extends UploadHeaders { +export interface CollectionUploadHeaders extends UploadHeaders { 'swarm-index-document'?: string 'swarm-error-document'?: string } -function extractCollectionUploadHeaders( +export function extractCollectionUploadHeaders( postageBatchId: BatchId, options?: CollectionUploadOptions & UploadRedundancyOptions, ): CollectionUploadHeaders & UploadRedundancyOptions { @@ -164,31 +163,19 @@ function extractCollectionUploadHeaders( /** * Upload collection - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param collection Collection of Uint8Array buffers to upload * @param postageBatchId Postage BatchId that will be assigned to uploaded data * @param options */ export async function uploadCollection( requestOptions: BeeRequestOptions, - collection: Collection, + collection: Collection, postageBatchId: BatchId, options?: CollectionUploadOptions & UploadRedundancyOptions, ): Promise { assertCollection(collection) - const tarData = makeTar(collection) - - const response = await http<{ reference: Reference }>(requestOptions, { - method: 'post', - url: bzzEndpoint, - data: tarData, - responseType: 'json', - headers: { - 'content-type': 'application/x-tar', - 'swarm-collection': 'true', - ...extractCollectionUploadHeaders(postageBatchId, options), - }, - }) + const response = await uploadTar(requestOptions, collection, postageBatchId, options) return { reference: response.data.reference, diff --git a/src/modules/chunk.ts b/src/modules/chunk.ts index 4662bb6c..cdcfeaf0 100644 --- a/src/modules/chunk.ts +++ b/src/modules/chunk.ts @@ -20,7 +20,7 @@ const endpoint = 'chunks' * The span stores the length of the payload in uint64 little endian encoding. * Upload expects the chuck data to be set accordingly. * - * @param ky Ky instance + * @param requestOptions Options for making requests * @param data Chunk data to be uploaded * @param postageBatchId Postage BatchId that will be assigned to uploaded data * @param options Additional options like tag, encryption, pinning @@ -48,7 +48,7 @@ export async function upload( /** * Download chunk data as a byte array * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param hash Bee content reference * */ diff --git a/src/modules/debug/balance.ts b/src/modules/debug/balance.ts index 552ea298..97cd5263 100644 --- a/src/modules/debug/balance.ts +++ b/src/modules/debug/balance.ts @@ -7,7 +7,7 @@ const consumedEndpoint = 'consumed' /** * Get the balances with all known peers including prepaid services * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getAllBalances(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -21,7 +21,7 @@ export async function getAllBalances(requestOptions: BeeRequestOptions): Promise /** * Get the balances with a specific peer including prepaid services * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param address Swarm address of peer */ export async function getPeerBalance(requestOptions: BeeRequestOptions, address: string): Promise { @@ -36,7 +36,7 @@ export async function getPeerBalance(requestOptions: BeeRequestOptions, address: /** * Get the past due consumption balances with all known peers * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getPastDueConsumptionBalances(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -50,7 +50,7 @@ export async function getPastDueConsumptionBalances(requestOptions: BeeRequestOp /** * Get the past due consumption balance with a specific peer * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param address Swarm address of peer */ export async function getPastDueConsumptionPeerBalance( diff --git a/src/modules/debug/chequebook.ts b/src/modules/debug/chequebook.ts index bc966b6e..4111f67e 100644 --- a/src/modules/debug/chequebook.ts +++ b/src/modules/debug/chequebook.ts @@ -17,7 +17,7 @@ const chequebookEndpoint = 'chequebook' /** * Get the address of the chequebook contract used * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getChequebookAddress(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -31,7 +31,7 @@ export async function getChequebookAddress(requestOptions: BeeRequestOptions): P /** * Get the balance of the chequebook * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getChequebookBalance(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -45,7 +45,7 @@ export async function getChequebookBalance(requestOptions: BeeRequestOptions): P /** * Get last cashout action for the peer * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param peer Swarm address of peer */ export async function getLastCashoutAction( @@ -63,7 +63,7 @@ export async function getLastCashoutAction( /** * Cashout the last cheque for the peer * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param peer Swarm address of peer * @param options */ @@ -95,7 +95,7 @@ export async function cashoutLastCheque( /** * Get last cheques for the peer * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param peer Swarm address of peer */ export async function getLastChequesForPeer( @@ -113,7 +113,7 @@ export async function getLastChequesForPeer( /** * Get last cheques for all peers * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getLastCheques(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -127,7 +127,7 @@ export async function getLastCheques(requestOptions: BeeRequestOptions): Promise /** * Deposit tokens from overlay address into chequebook * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param amount Amount of tokens to deposit * @param gasPrice Gas Price in WEI for the transaction call * @return string Hash of the transaction @@ -157,7 +157,7 @@ export async function depositTokens( /** * Withdraw tokens from the chequebook to the overlay address * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param amount Amount of tokens to withdraw * @param gasPrice Gas Price in WEI for the transaction call * @return string Hash of the transaction diff --git a/src/modules/debug/chunk.ts b/src/modules/debug/chunk.ts index 75a00659..25f58450 100644 --- a/src/modules/debug/chunk.ts +++ b/src/modules/debug/chunk.ts @@ -6,7 +6,7 @@ const endpoint = 'chunks' /** * Check if chunk at address exists locally * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param address Swarm address of chunk * * @returns BeeGenericResponse if chunk is found or throws an exception @@ -22,24 +22,3 @@ export async function checkIfChunkExistsLocally( return response.data } - -/** - * Delete a chunk from local storage - * - * @param kyOptions Ky Options for making requests - * @param address Swarm address of chunk - * - * @returns BeeGenericResponse if chunk was deleted or throws an exception - */ -export async function deleteChunkFromLocalStorage( - requestOptions: BeeRequestOptions, - address: string, -): Promise { - const response = await http(requestOptions, { - method: 'delete', - url: `${endpoint}/${address}`, - responseType: 'json', - }) - - return response.data -} diff --git a/src/modules/debug/connectivity.ts b/src/modules/debug/connectivity.ts index 55472554..10482871 100644 --- a/src/modules/debug/connectivity.ts +++ b/src/modules/debug/connectivity.ts @@ -9,6 +9,7 @@ export async function getNodeAddresses(requestOptions: BeeRequestOptions): Promi return response.data } + interface Peers { peers: Peer[] } diff --git a/src/modules/debug/settlements.ts b/src/modules/debug/settlements.ts index da489ce0..78469a5d 100644 --- a/src/modules/debug/settlements.ts +++ b/src/modules/debug/settlements.ts @@ -6,7 +6,7 @@ const settlementsEndpoint = 'settlements' /** * Get amount of sent and received from settlements with a peer * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param peer Swarm address of peer */ export async function getSettlements(requestOptions: BeeRequestOptions, peer: string): Promise { @@ -21,7 +21,7 @@ export async function getSettlements(requestOptions: BeeRequestOptions, peer: st /** * Get settlements with all known peers and total amount sent or received * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getAllSettlements(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { diff --git a/src/modules/debug/stake.ts b/src/modules/debug/stake.ts index 6929023f..7d694c05 100644 --- a/src/modules/debug/stake.ts +++ b/src/modules/debug/stake.ts @@ -17,7 +17,7 @@ interface GetStake { /** * Gets the staked amount * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getStake(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -32,7 +32,7 @@ export async function getStake(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { diff --git a/src/modules/debug/states.ts b/src/modules/debug/states.ts index 4b8fb0bc..7b813ed9 100644 --- a/src/modules/debug/states.ts +++ b/src/modules/debug/states.ts @@ -8,7 +8,7 @@ const CHAIN_STATE_ENDPOINT = 'chainstate' /** * Get state of reserve * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getReserveState(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -23,7 +23,7 @@ export async function getReserveState(requestOptions: BeeRequestOptions): Promis /** * Get state of reserve * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getChainState(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -38,7 +38,7 @@ export async function getChainState(requestOptions: BeeRequestOptions): Promise< /** * Get wallet balances for xDai and BZZ of the node * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getWalletBalance(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -47,21 +47,5 @@ export async function getWalletBalance(requestOptions: BeeRequestOptions): Promi responseType: 'json', }) - return mapWalletProperties(response.data) -} - -/** - * TODO: Remove on next break - * @param data - */ -function mapWalletProperties(data: WalletBalance): WalletBalance { - return { - // @ts-ignore: Needed for backward compatibility mapping - bzz: data.bzzBalance, - // @ts-ignore: Needed for backward compatibility mapping - xDai: data.nativeTokenBalance, - // @ts-ignore: Needed for backward compatibility mapping - contractAddress: data.chequebookContractAddress, - ...data, - } + return response.data } diff --git a/src/modules/debug/status.ts b/src/modules/debug/status.ts index 02ef0e04..01572ebc 100644 --- a/src/modules/debug/status.ts +++ b/src/modules/debug/status.ts @@ -10,7 +10,7 @@ export const SUPPORTED_BEE_VERSION_EXACT = '1.18.2-759f56f' export const SUPPORTED_API_VERSION = '4.0.0' export const SUPPORTED_DEBUG_API_VERSION = '4.0.0' -export const SUPPORTED_BEE_VERSION = SUPPORTED_BEE_VERSION_EXACT.substring(0, SUPPORTED_BEE_VERSION_EXACT.indexOf('-')) +export const SUPPORTED_BEE_VERSION = SUPPORTED_BEE_VERSION_EXACT.split('-')[0] const NODE_INFO_URL = 'node' const STATUS_URL = 'status' @@ -30,7 +30,7 @@ export async function getDebugStatus(requestOptions: BeeRequestOptions): Promise /** * Get health of node * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests */ export async function getHealth(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -45,7 +45,7 @@ export async function getHealth(requestOptions: BeeRequestOptions): Promise { try { @@ -63,7 +63,7 @@ export async function getReadiness(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -78,8 +78,7 @@ export async function getNodeInfo(requestOptions: BeeRequestOptions): Promise { const { version } = await getHealth(requestOptions) @@ -107,10 +106,10 @@ export async function isSupportedExactVersion(requestOptions: BeeRequestOptions) /** * Connects to a node and checks if its main's API version matches with the one that bee-js supports. * - * This is useful if you are not using `BeeDebug` class (for anything else then this check) + * This is useful if you are not using `Bee` class (for anything else then this check) * and want to make sure about compatibility. * - * @param ky + * @param requestOptions Options for making requests */ export async function isSupportedMainApiVersion(requestOptions: BeeRequestOptions): Promise { const { apiVersion } = await getHealth(requestOptions) @@ -119,50 +118,31 @@ export async function isSupportedMainApiVersion(requestOptions: BeeRequestOption } /** - * Connects to a node and checks if its Debug API version matches with the one that bee-js supports. - * - * This is useful if you are not using `Bee` class in your application and want to make sure - * about compatibility. - * - * @param ky - */ -export async function isSupportedDebugApiVersion(requestOptions: BeeRequestOptions): Promise { - const { debugApiVersion } = await getHealth(requestOptions) - - return getMajorSemver(debugApiVersion) === getMajorSemver(SUPPORTED_DEBUG_API_VERSION) -} - -/** - * Connects to a node and checks if its Main and Debug API versions matches with the one that bee-js supports. + * Connects to a node and checks if its Main API versions matches with the one that bee-js supports. * * This should be the main way how to check compatibility for your app and Bee node. * - * @param ky + * @param requestOptions Options for making requests */ export async function isSupportedApiVersion(requestOptions: BeeRequestOptions): Promise { - const { apiVersion, debugApiVersion } = await getHealth(requestOptions) + const { apiVersion } = await getHealth(requestOptions) - return ( - getMajorSemver(apiVersion) === getMajorSemver(SUPPORTED_API_VERSION) && - getMajorSemver(debugApiVersion) === getMajorSemver(SUPPORTED_DEBUG_API_VERSION) - ) + return getMajorSemver(apiVersion) === getMajorSemver(SUPPORTED_API_VERSION) } /** * Returns object with all versions specified by the connected Bee node (properties prefixed with `bee*`) * and versions that bee-js supports (properties prefixed with `supported*`). * - * @param ky + * @param requestOptions Options for making requests */ export async function getVersions(requestOptions: BeeRequestOptions): Promise { - const { version, apiVersion, debugApiVersion } = await getHealth(requestOptions) + const { version, apiVersion } = await getHealth(requestOptions) return { supportedBeeVersion: SUPPORTED_BEE_VERSION_EXACT, supportedBeeApiVersion: SUPPORTED_API_VERSION, - supportedBeeDebugApiVersion: SUPPORTED_DEBUG_API_VERSION, beeVersion: version, beeApiVersion: apiVersion, - beeDebugApiVersion: debugApiVersion, } } diff --git a/src/modules/debug/tag.ts b/src/modules/debug/tag.ts index 71cd0ff7..2279451f 100644 --- a/src/modules/debug/tag.ts +++ b/src/modules/debug/tag.ts @@ -6,7 +6,7 @@ const endpoint = 'tags' /** * Retrieve tag with extended information from Bee node * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param uid UID of tag to be retrieved */ export async function retrieveExtendedTag(requestOptions: BeeRequestOptions, uid: number): Promise { diff --git a/src/modules/debug/transactions.ts b/src/modules/debug/transactions.ts index 78843c02..1fd0a5c1 100644 --- a/src/modules/debug/transactions.ts +++ b/src/modules/debug/transactions.ts @@ -14,7 +14,7 @@ interface TransactionResponse { /** * Get list of all pending transactions * - * @param ky Debug Ky instance + * @param requestOptions Options for making requests */ export async function getAllTransactions(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { @@ -28,7 +28,7 @@ export async function getAllTransactions(requestOptions: BeeRequestOptions): Pro /** * Get information for specific pending transactions * - * @param ky Debug Ky instance + * @param requestOptions Options for making requests * @param transactionHash Hash of the transaction */ export async function getTransaction( @@ -46,7 +46,7 @@ export async function getTransaction( /** * Rebroadcast existing transaction * - * @param ky Debug Ky instance + * @param requestOptions Options for making requests * @param transactionHash Hash of the transaction */ export async function rebroadcastTransaction( @@ -65,7 +65,7 @@ export async function rebroadcastTransaction( /** * Cancel existing transaction * - * @param ky Debug Ky instance + * @param requestOptions Options for making requests * @param transactionHash Hash of the transaction * @param gasPrice Optional gas price */ diff --git a/src/modules/feed.ts b/src/modules/feed.ts index 6ecc52b9..1e3de280 100644 --- a/src/modules/feed.ts +++ b/src/modules/feed.ts @@ -18,9 +18,6 @@ export interface FeedUpdateOptions { */ at?: number - /** - * Can be 'epoch' or 'sequence' (default: 'sequence') - */ type?: FeedType /** @@ -46,7 +43,7 @@ export interface FetchFeedUpdateResponse extends ReferenceResponse, FeedUpdateHe /** * Create an initial feed root manifest * - * @param ky Ky instance + * @param requestOptions Options for making requests * @param owner Owner's ethereum address in hex * @param topic Topic in hex * @param postageBatchId Postage BatchId to be used to create the Feed Manifest @@ -57,13 +54,11 @@ export async function createFeedManifest( owner: HexEthAddress, topic: Topic, postageBatchId: BatchId, - options?: CreateFeedOptions, ): Promise { const response = await http(requestOptions, { method: 'post', responseType: 'json', url: `${feedEndpoint}/${owner}/${topic}`, - params: options, headers: extractUploadHeaders(postageBatchId), }) @@ -96,10 +91,10 @@ function readFeedUpdateHeaders(headers: Record): FeedUpdateHeade * the reference it contains along with its index and the * index of the subsequent update. * - * @param ky Ky instance - * @param owner Owner's ethereum address in hex - * @param topic Topic in hex - * @param options Additional options, like index, at, type + * @param requestOptions Options for making requests + * @param owner Owner's ethereum address in hex + * @param topic Topic in hex + * @param options Additional options, like index, at, type */ export async function fetchLatestFeedUpdate( requestOptions: BeeRequestOptions, @@ -110,7 +105,7 @@ export async function fetchLatestFeedUpdate( const response = await http(requestOptions, { responseType: 'json', url: `${feedEndpoint}/${owner}/${topic}`, - params: options, + params: options as any, }) return { diff --git a/src/modules/pinning.ts b/src/modules/pinning.ts index 25ae68f8..c0ab5795 100644 --- a/src/modules/pinning.ts +++ b/src/modules/pinning.ts @@ -10,7 +10,7 @@ export interface GetAllPinResponse { /** * Pin data with given reference * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param reference Bee data reference */ export async function pin(requestOptions: BeeRequestOptions, reference: Reference): Promise { @@ -24,7 +24,7 @@ export async function pin(requestOptions: BeeRequestOptions, reference: Referenc /** * Unpin data with given reference * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param reference Bee data reference */ export async function unpin(requestOptions: BeeRequestOptions, reference: Reference): Promise { @@ -38,7 +38,7 @@ export async function unpin(requestOptions: BeeRequestOptions, reference: Refere /** * Get pin status for specific address. * - * @param ky Ky instance + * @param requestOptions Options for making requests * @param reference * @throws Error if given address is not pinned */ @@ -55,7 +55,7 @@ export async function getPin(requestOptions: BeeRequestOptions, reference: Refer /** * Get list of all pins * - * @param ky Ky instance + * @param requestOptions Options for making requests */ export async function getAllPins(requestOptions: BeeRequestOptions): Promise { const response = await http(requestOptions, { diff --git a/src/modules/pss.ts b/src/modules/pss.ts index dc1f945c..5ef67c2f 100644 --- a/src/modules/pss.ts +++ b/src/modules/pss.ts @@ -8,7 +8,7 @@ const endpoint = 'pss' /** * Send to recipient or target with Postal Service for Swarm * - * @param kyOptions Ky Options for making requests + * @param requestOptions Options for making requests * @param topic Topic name * @param target Target message address prefix * @param data diff --git a/src/modules/soc.ts b/src/modules/soc.ts index 975cde08..6024c10c 100644 --- a/src/modules/soc.ts +++ b/src/modules/soc.ts @@ -7,7 +7,7 @@ const socEndpoint = 'soc' /** * Upload single owner chunk (SOC) to a Bee node * - * @param ky Ky instance + * @param requestOptions Options for making requests * @param owner Owner's ethereum address in hex * @param identifier Arbitrary identifier in hex * @param signature Signature in hex diff --git a/src/modules/status.ts b/src/modules/status.ts index 0cbdfef6..b4e0418b 100644 --- a/src/modules/status.ts +++ b/src/modules/status.ts @@ -4,7 +4,7 @@ import { http } from '../utils/http' /** * Ping the base bee URL. If connection was not successful throw error * - * @param kyOptions Ky instance for given Bee class instance + * @param requestOptions Options for making requests */ export async function checkConnection(requestOptions: BeeRequestOptions): Promise | never { await http(requestOptions, { diff --git a/src/modules/stewardship.ts b/src/modules/stewardship.ts index a1c94f89..75139acd 100644 --- a/src/modules/stewardship.ts +++ b/src/modules/stewardship.ts @@ -5,7 +5,7 @@ const stewardshipEndpoint = 'stewardship' /** * Reupload locally pinned data - * @param ky Ky instance + * @param requestOptions Options for making requests * @param reference * @param options * @throws BeeResponseError if not locally pinned or invalid data diff --git a/src/types/debug.ts b/src/types/debug.ts index 22a5b7ba..d5f18ed4 100644 --- a/src/types/debug.ts +++ b/src/types/debug.ts @@ -160,16 +160,13 @@ export interface Health { status: 'ok' version: string apiVersion: string - debugApiVersion: string } export interface BeeVersions { supportedBeeVersion: string supportedBeeApiVersion: string - supportedBeeDebugApiVersion: string beeVersion: string beeApiVersion: string - beeDebugApiVersion: string } export enum BeeModes { diff --git a/src/types/index.ts b/src/types/index.ts index ecb04c1b..55eaf12f 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,4 +1,3 @@ -import { AxiosAdapter } from 'axios' import type { Identifier, SingleOwnerChunk } from '../chunk/soc' import type { FeedUploadOptions } from '../feed' import type { FeedType } from '../feed/type' @@ -8,10 +7,6 @@ import type { BeeError } from '../utils/error' import type { EthAddress, HexEthAddress } from '../utils/eth' import type { HexString } from '../utils/hex' -import type { Readable as CompatibilityReadable } from 'readable-stream' -import type { Readable as NativeReadable } from 'stream' -import type { ReadableStream as ReadableStreamPonyfill } from 'web-streams-polyfill' - export * from './debug' export interface Dictionary { @@ -37,6 +32,11 @@ export const ENCRYPTED_REFERENCE_BYTES_LENGTH = 64 */ export const STAMPS_DEPTH_MIN = 17 +/** + * Minimal amount that can be used for creation of postage batch + */ +export const STAMPS_AMOUNT_MIN = 24000 * 24 * 60 * 12 + /** * Maximal depth that can be used for creation of postage batch */ @@ -75,12 +75,6 @@ export type PublicKey = HexString export type Address = HexString -/** - * Type representing Readable stream that abstracts away implementation especially the difference between - * browser and NodeJS versions as both are supported. - */ -export type Readable = NativeReadable | CompatibilityReadable | ReadableStream | ReadableStreamPonyfill - /** * BatchId is result of keccak256 hash so 64 hex string without prefix. */ @@ -97,7 +91,6 @@ export type BeeRequestOptions = { timeout?: number | false retry?: number | false headers?: Record - adapter?: AxiosAdapter onRequest?: (request: BeeRequest) => void } @@ -357,19 +350,17 @@ export interface Data extends Uint8Array { /** * Object represents a file and some of its metadata in [[Directory]] object. */ -export interface CollectionEntry { - data: T - - /** - * - */ +export interface CollectionEntry { path: string + size: number + file?: File + fsPath?: string } /** * Represents Collections */ -export type Collection = Array> +export type Collection = Array export interface PssSubscription { readonly topic: string diff --git a/src/types/tar-js.d.ts b/src/types/tar-js.d.ts deleted file mode 100644 index 15478748..00000000 --- a/src/types/tar-js.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'tar-js' diff --git a/src/types/webpack-bundle-analyzer/index.d.ts b/src/types/webpack-bundle-analyzer/index.d.ts deleted file mode 100644 index 40f5afde..00000000 --- a/src/types/webpack-bundle-analyzer/index.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * We declare this module manually instead of using the @types/webpack-bundle-analyzer - * because it relies on the old @types/webpack for v4 that cause incompatibilities with v5 - * because v5 ships its own definitions. - */ -declare module 'webpack-bundle-analyzer' { - import { Compiler, WebpackPluginInstance } from 'webpack' - - export class BundleAnalyzerPlugin implements WebpackPluginInstance { - constructor(options?: unknown) - apply(compiler: Compiler): void - } -} diff --git a/src/utils/collection.browser.ts b/src/utils/collection.browser.ts index 6d298561..4fcd695e 100644 --- a/src/utils/collection.browser.ts +++ b/src/utils/collection.browser.ts @@ -6,7 +6,7 @@ import { Collection } from '../types' * * @param dir path to the directory */ -export async function makeCollectionFromFS(dir: string): Promise> { +export async function makeCollectionFromFS(dir: string): Promise { throw new Error('Creating Collection from File System is not supported in browsers!') } diff --git a/src/utils/collection.node.ts b/src/utils/collection.node.ts index 0ac02414..f04dacf8 100644 --- a/src/utils/collection.node.ts +++ b/src/utils/collection.node.ts @@ -8,7 +8,7 @@ import { Collection } from '../types' * * @param dir path to the directory */ -export async function makeCollectionFromFS(dir: string): Promise> { +export async function makeCollectionFromFS(dir: string): Promise { if (typeof dir !== 'string') { throw new TypeError('dir has to be string!') } @@ -20,11 +20,11 @@ export async function makeCollectionFromFS(dir: string): Promise> { +async function buildCollectionRelative(dir: string, relativePath: string): Promise { // Handles case when the dir is not existing or it is a file ==> throws an error const dirname = path.join(dir, relativePath) const entries = await fs.promises.opendir(dirname) - let collection: Collection = [] + let collection: Collection = [] for await (const entry of entries) { const fullPath = path.join(dir, relativePath, entry.name) @@ -33,7 +33,8 @@ async function buildCollectionRelative(dir: string, relativePath: string): Promi if (entry.isFile()) { collection.push({ path: entryPath, - data: new Uint8Array(await fs.promises.readFile(fullPath)), + size: (await fs.promises.stat(fullPath)).size, + fsPath: fullPath, }) } else if (entry.isDirectory()) { collection = [...(await buildCollectionRelative(dir, entryPath)), ...collection] diff --git a/src/utils/collection.ts b/src/utils/collection.ts index 03fda392..f8d397d7 100644 --- a/src/utils/collection.ts +++ b/src/utils/collection.ts @@ -1,17 +1,15 @@ import { Collection } from '../types' import { BeeArgumentError } from './error' -import { fileArrayBuffer } from './file' -import { isUint8Array } from './type' -export function isCollection(data: unknown): data is Collection { +export function isCollection(data: unknown): data is Collection { if (!Array.isArray(data)) { return false } - return data.every(entry => typeof entry === 'object' && entry.data && entry.path && isUint8Array(entry.data)) + return data.every(entry => typeof entry === 'object' && entry.path && entry.size) } -export function assertCollection(data: unknown): asserts data is Collection { +export function assertCollection(data: unknown): asserts data is Collection { if (!isCollection(data)) { throw new BeeArgumentError('invalid collection', data) } @@ -29,21 +27,12 @@ function makeFilePath(file: File) { throw new TypeError('file is not valid File object') } -export async function makeCollectionFromFileList(fileList: FileList | File[]): Promise> { - const collection: Collection = [] - - for (let i = 0; i < fileList.length; i++) { - const file = fileList[i] - - if (file) { - collection.push({ - path: makeFilePath(file), - data: new Uint8Array(await fileArrayBuffer(file)), - }) - } - } - - return collection +export async function makeCollectionFromFileList(fileList: FileList | File[]): Promise { + return Array.from(fileList).map(file => ({ + path: makeFilePath(file), + size: file.size, + file, + })) } /** @@ -53,15 +42,5 @@ export async function makeCollectionFromFileList(fileList: FileList | File[]): P * @returns size in bytes */ export function getCollectionSize(fileList: FileList | File[]): number { - let sum = 0 - - for (let i = 0; i < fileList.length; i++) { - const file = fileList[i] - - if (file) { - sum += file.size - } - } - - return sum + return Array.from(fileList).reduce((sum, file) => sum + file.size, 0) } diff --git a/src/utils/data.browser.ts b/src/utils/data.browser.ts index aab13038..fd45418c 100644 --- a/src/utils/data.browser.ts +++ b/src/utils/data.browser.ts @@ -1,61 +1,3 @@ -import { isNodeReadable, isReadableStream } from './stream' -import { Readable } from '../types' - -/** - * Validates input and converts to Uint8Array - * - * @param data any string, ArrayBuffer or Uint8Array - */ -export async function prepareData( - data: string | Blob | ArrayBuffer | Uint8Array | Readable, -): Promise | never> { - if (typeof data === 'string') return new Blob([data], { type: 'text/plain' }) - - if (data instanceof Uint8Array || data instanceof ArrayBuffer) { - return new Blob([data], { type: 'application/octet-stream' }) - } - - if (data instanceof Blob) { - return data - } - - // Currently it is not possible to stream requests from browsers - // there are already first experiments on this field (Chromium) - // but till it is fully implemented across browsers-land we have to - // buffer the data before sending the requests. - if (isNodeReadable(data)) { - return new Promise(resolve => { - const buffers: Array = [] - data.on('data', d => { - buffers.push(d) - }) - data.on('end', () => { - resolve(new Blob(buffers, { type: 'application/octet-stream' })) - }) - }) - } - - if (isReadableStream(data)) { - return new Promise(async resolve => { - const reader = data.getReader() - const buffers: Array = [] - - let done, value - do { - ;({ done, value } = await reader.read()) - - if (!done) { - buffers.push(value) - } - } while (!done) - - resolve(new Blob(buffers, { type: 'application/octet-stream' })) - }) - } - - throw new TypeError('unknown data type') -} - export async function prepareWebsocketData(data: string | ArrayBuffer | Blob): Promise | never { if (typeof data === 'string') return new TextEncoder().encode(data) diff --git a/src/utils/data.ts b/src/utils/data.ts index 1e214813..228d7d93 100644 --- a/src/utils/data.ts +++ b/src/utils/data.ts @@ -1,11 +1,10 @@ -import BlobPolyfill from 'fetch-blob' import type { Data } from 'ws' function isBufferArray(buffer: unknown): buffer is Buffer[] { return Array.isArray(buffer) && buffer.length > 0 && buffer.every(data => data instanceof Buffer) } -export async function prepareWebsocketData(data: Data | BlobPolyfill): Promise | never { +export async function prepareWebsocketData(data: Data | Blob): Promise | never { if (typeof data === 'string') return new TextEncoder().encode(data) if (data instanceof Buffer) return new Uint8Array(data) diff --git a/src/utils/error.ts b/src/utils/error.ts index cd05aa41..0676308a 100644 --- a/src/utils/error.ts +++ b/src/utils/error.ts @@ -1,5 +1,3 @@ -import { AxiosRequestConfig, AxiosResponse } from 'axios' - export class BeeError extends Error { public constructor(message: string) { super(message) @@ -13,15 +11,7 @@ export class BeeArgumentError extends BeeError { } export class BeeResponseError extends BeeError { - public constructor( - message: string, - public code?: string, - public axiosStatus?: number, - public status?: number, - public config?: AxiosRequestConfig, - public request?: any, - public response?: AxiosResponse, - ) { + public constructor(message: string, public status?: number, public statusText?: string) { super(message) } } diff --git a/src/utils/eth.ts b/src/utils/eth.ts index 5e7248b5..6534ce99 100644 --- a/src/utils/eth.ts +++ b/src/utils/eth.ts @@ -3,8 +3,8 @@ import pkg from 'js-sha3' const { keccak256, sha3_256 } = pkg import { BrandedString, Data, Signer } from '../types' -import { HexString, hexToBytes, intToHex, makeHexString, assertHexString } from './hex' import { Bytes, assertBytes } from './bytes' +import { HexString, assertHexString, hexToBytes, intToHex, makeHexString } from './hex' export type OverlayAddress = BrandedString<'OverlayAddress'> export type EthAddress = Bytes<20> diff --git a/src/utils/expose.ts b/src/utils/expose.ts index 3d6b65cd..fb34551f 100644 --- a/src/utils/expose.ts +++ b/src/utils/expose.ts @@ -36,15 +36,6 @@ export { toLittleEndian, } from './eth' -export { - isNodeReadable, - isReadable, - isReadableStream, - normalizeToReadableStream, - readableNodeToWeb, - readableWebToNode, -} from './stream' - export { keccak256Hash } from './hash' export { makeMaxTarget } from './pss' diff --git a/src/utils/file.ts b/src/utils/file.ts index bdd061fd..40f20672 100644 --- a/src/utils/file.ts +++ b/src/utils/file.ts @@ -3,7 +3,6 @@ * * https://developer.mozilla.org/en-US/docs/Web/API/File */ - export function isFile(file: unknown): file is File { // browser if (typeof File === 'function') { diff --git a/src/utils/http.ts b/src/utils/http.ts index 1e148633..b8863690 100644 --- a/src/utils/http.ts +++ b/src/utils/http.ts @@ -1,7 +1,9 @@ -import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios' +import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' import { Objects, Strings } from 'cafe-utility' import { BeeRequestOptions, BeeResponseError } from '../index' +const { AxiosError } = axios + export const DEFAULT_HTTP_CONFIG: AxiosRequestConfig = { headers: { accept: 'application/json, text/plain, */*', @@ -25,7 +27,7 @@ export async function http(options: BeeRequestOptions, config: AxiosRequestCo return response as AxiosResponse } catch (e: unknown) { if (e instanceof AxiosError) { - throw new BeeResponseError(e.message, e.code, e.status, e.response?.status, e.config, e.request, e.response) + throw new BeeResponseError(e.message, e.status, e.code) } throw e } diff --git a/src/utils/redundancy.ts b/src/utils/redundancy.ts index 586ce4ec..5d96f667 100644 --- a/src/utils/redundancy.ts +++ b/src/utils/redundancy.ts @@ -63,6 +63,7 @@ export function approximateOverheadForRedundancyLevel(chunks: number, level: Red : tables[RedundancyLevel.PARANOID] const table = encrypted ? tableType[1] : tableType[0] const [supportedChunks, parities] = table + for (let i = 0; i < supportedChunks.length; i++) { if (chunks >= supportedChunks[i]) { return parities[i] / supportedChunks[i] diff --git a/src/utils/stream.ts b/src/utils/stream.ts deleted file mode 100644 index 2037c88f..00000000 --- a/src/utils/stream.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { Readable as NodeReadableNative, ReadableOptions as NodeReadableOptions } from 'stream' -import { ReadableStream } from 'web-streams-polyfill' -import { Readable } from '../types' -import { isStrictlyObject } from './type' - -const NodeReadable = NodeReadableNative || class {} - -/** - * Validates if passed object is either browser's ReadableStream - * or Node's Readable. - * - * @param entry - */ -export function isReadable(entry: unknown): entry is Readable { - return isReadableStream(entry) || isNodeReadable(entry) -} - -export function isReadableStream(entry: unknown): entry is ReadableStream { - if (!isStrictlyObject(entry)) { - return false - } - - const browserReadable = entry as unknown as ReadableStream - - if ( - typeof browserReadable.getReader === 'function' && - browserReadable.locked !== undefined && - typeof browserReadable.cancel === 'function' && - typeof browserReadable.pipeTo === 'function' && - typeof browserReadable.pipeThrough === 'function' - ) { - return true - } - - return false -} - -export function isNodeReadable(entry: unknown): entry is NodeReadableNative { - if (!isStrictlyObject(entry)) { - return false - } - - const nodeReadable = entry as unknown as NodeReadableNative - - if (typeof nodeReadable.pipe === 'function' && nodeReadable.readable && typeof nodeReadable._read === 'function') { - return true - } - - return false -} - -/** - * Function that converts Node's Readable into WHATWG ReadableStream - * - * Taken over from https://github.com/gwicke/node-web-streams/blob/master/lib/conversions.js - * Because it uses forked web-streams-polyfill that are outdated. - * - * @author https://github.com/gwicke - * @licence Apache License 2.0 https://github.com/gwicke/node-web-streams/blob/master/LICENSE - * @param nodeStream - */ -export function readableNodeToWeb(nodeStream: NodeReadableNative): ReadableStream { - return new ReadableStream({ - start(controller) { - nodeStream.pause() - nodeStream.on('data', chunk => { - if (Buffer.isBuffer(chunk)) { - controller.enqueue(new Uint8Array(chunk.buffer)) - } else { - controller.enqueue(chunk) - } - nodeStream.pause() - }) - nodeStream.on('end', () => controller.close()) - nodeStream.on('error', e => controller.error(e)) - }, - pull() { - nodeStream.resume() - }, - cancel() { - nodeStream.pause() - }, - }) -} - -/** - * Taken over from https://github.com/gwicke/node-web-streams/blob/master/lib/conversions.js - * Because it uses forked web-streams-polyfill that are outdated. - * - * @author https://github.com/gwicke - * @licence Apache License 2.0 https://github.com/gwicke/node-web-streams/blob/master/LICENSE - */ -class NodeReadableWrapper extends NodeReadable { - private _webStream: ReadableStream - private _reader: ReadableStreamDefaultReader - private _reading: boolean - constructor(webStream: ReadableStream, options?: NodeReadableOptions) { - super(options) - this._webStream = webStream - this._reader = webStream.getReader() - this._reading = false - } - - _read() { - if (this._reading) { - return - } - this._reading = true - const doRead = () => { - this._reader.read().then(res => { - if (res.done) { - this.push(null) - - return - } - - if (this.push(res.value)) { - return doRead() - } else { - this._reading = false - } - }) - } - doRead() - } -} - -/** - * Function that converts WHATWG ReadableStream into Node's Readable - * - * Taken over from https://github.com/gwicke/node-web-streams/blob/master/lib/conversions.js - * Because it uses forked web-streams-polyfill that is outdated. - * - * **Warning!** - * If you want to use this function in browser you have to polyfill `stream` package with your bundler. - * - * @author https://github.com/gwicke - * @licence Apache License 2.0 https://github.com/gwicke/node-web-streams/blob/master/LICENSE - * @param webStream - * @param options - */ -export function readableWebToNode( - webStream: ReadableStream, - options?: NodeReadableOptions, -): NodeReadableNative { - if (!NodeReadableNative) { - throw new Error( - "The Node's Readable is not available! If you are running this in browser you have to polyfill 'stream' package!", - ) - } - - return new NodeReadableWrapper(webStream, options) as unknown as NodeReadableNative -} - -export function normalizeToReadableStream(stream: Readable): ReadableStream { - if (isNodeReadable(stream)) { - return readableNodeToWeb(stream) - } else if (isReadableStream(stream)) { - return stream - } - - throw new TypeError('Passed stream is not Node Readable nor ReadableStream!') -} diff --git a/src/utils/tar-uploader.browser.ts b/src/utils/tar-uploader.browser.ts new file mode 100644 index 00000000..08e27f95 --- /dev/null +++ b/src/utils/tar-uploader.browser.ts @@ -0,0 +1,31 @@ +import { BatchId, BeeRequestOptions, Collection, CollectionUploadOptions, Reference, UploadRedundancyOptions } from '..' +import { extractCollectionUploadHeaders } from '../modules/bzz' +import { http } from './http' +import { TarStream } from './tar' +import { writeTar } from './tar-writer' + +const bzzEndpoint = 'bzz' + +export async function uploadTar( + requestOptions: BeeRequestOptions, + collection: Collection, + postageBatchId: BatchId, + options?: CollectionUploadOptions & UploadRedundancyOptions, +) { + const tarStream = new TarStream() + await writeTar(collection, tarStream) + await tarStream.end() + const response = await http<{ reference: Reference }>(requestOptions, { + method: 'post', + url: bzzEndpoint, + data: tarStream.output, + responseType: 'json', + headers: { + 'content-type': 'application/x-tar', + 'swarm-collection': 'true', + ...extractCollectionUploadHeaders(postageBatchId, options), + }, + }) + + return response +} diff --git a/src/utils/tar-uploader.ts b/src/utils/tar-uploader.ts new file mode 100644 index 00000000..6e3f3b61 --- /dev/null +++ b/src/utils/tar-uploader.ts @@ -0,0 +1,33 @@ +import { BatchId, BeeRequestOptions, Collection, CollectionUploadOptions, Reference, UploadRedundancyOptions } from '..' +import { extractCollectionUploadHeaders } from '../modules/bzz' +import { http } from './http' +import { TarStream } from './tar' +import { writeTar } from './tar-writer' + +const bzzEndpoint = 'bzz' + +export async function uploadTar( + requestOptions: BeeRequestOptions, + collection: Collection, + postageBatchId: BatchId, + options?: CollectionUploadOptions & UploadRedundancyOptions, +) { + const tarStream = new TarStream() + const responsePromise = http<{ reference: Reference }>(requestOptions, { + method: 'post', + url: bzzEndpoint, + data: tarStream.output, + responseType: 'json', + headers: { + 'content-type': 'application/x-tar', + 'swarm-collection': 'true', + ...extractCollectionUploadHeaders(postageBatchId, options), + }, + }) + + await writeTar(collection, tarStream) + await tarStream.end() + const response = await responsePromise + + return response +} diff --git a/src/utils/tar-writer.browser.ts b/src/utils/tar-writer.browser.ts new file mode 100644 index 00000000..64b73f51 --- /dev/null +++ b/src/utils/tar-writer.browser.ts @@ -0,0 +1,15 @@ +import { Collection } from '..' +import { fileArrayBuffer } from './file' +import { TarStream } from './tar' + +export async function writeTar(collection: Collection, tarStream: TarStream) { + for (const item of collection) { + if (item.file) { + await tarStream.beginFile(item.path, item.file.size) + await tarStream.appendFile(new Uint8Array(await fileArrayBuffer(item.file))) + await tarStream.endFile() + } else { + throw new Error('Invalid collection item') + } + } +} diff --git a/src/utils/tar-writer.ts b/src/utils/tar-writer.ts new file mode 100644 index 00000000..b674c675 --- /dev/null +++ b/src/utils/tar-writer.ts @@ -0,0 +1,21 @@ +import { createReadStream } from 'fs' +import { Collection } from '..' +import { TarStream } from './tar' + +export async function writeTar(collection: Collection, tarStream: TarStream) { + for (const item of collection) { + await tarStream.beginFile(item.path, item.size) + + if (item.fsPath) { + const stream = createReadStream(item.fsPath) + + for await (const chunk of stream) { + await tarStream.appendFile(chunk) + } + await tarStream.endFile() + stream.close() + } else { + throw new Error('Invalid collection item') + } + } +} diff --git a/src/utils/tar.browser.ts b/src/utils/tar.browser.ts new file mode 100644 index 00000000..f1005017 --- /dev/null +++ b/src/utils/tar.browser.ts @@ -0,0 +1,68 @@ +export class TarStream { + pieces = [] as Uint8Array[] + currentFileSize = 0 + get output() { + return this.pieces.reduce((acc, piece) => { + const newAcc = new Uint8Array(acc.length + piece.length) + newAcc.set(acc) + newAcc.set(piece, acc.length) + + return newAcc + }) + } + async beginFile(path: string, size: number) { + const header = createHeader(path, size) + this.pieces.push(header) + this.currentFileSize = 0 + } + async appendFile(data: Uint8Array) { + this.pieces.push(data) + this.currentFileSize += data.length + } + async endFile() { + const padding = 512 - (this.currentFileSize % 512) + this.pieces.push(new Uint8Array(padding)) + } + async end() { + this.pieces.push(createEndOfArchive()) + } +} + +function createHeader(path: string, size: number): Uint8Array { + const header = new Uint8Array(512) // Initialize header with zeros + const encoder = new TextEncoder() + + function writeToBuffer(str: string, offset: number, length: number) { + const bytes = encoder.encode(str) + header.set(bytes.slice(0, length), offset) + } + + writeToBuffer(path, 0, 100) // File name + writeToBuffer('0000777', 100, 8) // File mode + writeToBuffer('0001750', 108, 8) // UID + writeToBuffer('0001750', 116, 8) // GID + writeToBuffer(size.toString(8).padStart(11, '0') + ' ', 124, 12) // File size + writeToBuffer(Math.floor(Date.now() / 1000).toString(8) + ' ', 136, 12) // Mod time + writeToBuffer(' ', 148, 8) // Checksum placeholder + writeToBuffer('0', 156, 1) // Typeflag + writeToBuffer('ustar ', 257, 8) // Magic and version + + for (let i = 345; i < 512; i++) { + header[i] = 0 // Fill remaining with zeros + } + + // Calculate checksum + let checksum = 0 + for (let i = 0; i < 512; i++) { + checksum += header[i] + } + + // Write checksum + writeToBuffer(checksum.toString(8).padStart(6, '0') + '\0 ', 148, 8) + + return header +} + +function createEndOfArchive(): Uint8Array { + return new Uint8Array(1024) +} diff --git a/src/utils/tar.ts b/src/utils/tar.ts index 06e3efe8..e77d91ac 100644 --- a/src/utils/tar.ts +++ b/src/utils/tar.ts @@ -1,30 +1,49 @@ -import Tar from 'tar-js' -import { Collection } from '../types' +import { PassThrough } from 'stream' -// this is a workaround type so that we are able to pass in Uint8Arrays -// as string to `tar.append` -interface StringLike { - readonly length: number - charCodeAt: (index: number) => number +export class TarStream { + output = new PassThrough() + currentFileSize = 0 + async beginFile(path: string, size: number) { + const header = createHeader(path, size) + this.output.write(header) + this.currentFileSize = 0 + } + async appendFile(data: Uint8Array) { + return new Promise(resolve => { + this.output.write(data, () => { + resolve() + }) + this.currentFileSize += data.length + }) + } + async endFile() { + const padding = 512 - (this.currentFileSize % 512) + this.output.write(Buffer.alloc(padding, 0)) + } + async end() { + this.output.write(createEndOfArchive()) + this.output.end() + } } -// converts a string to utf8 Uint8Array and returns it as a string-like -// object that `tar.append` accepts as path -function fixUnicodePath(path: string): StringLike { - const codes = new TextEncoder().encode(path) +function createHeader(path: string, size: number): Uint8Array { + const header = Buffer.alloc(512, 0) // Initialize header with zeros + header.write(path, 0, 100) // File name + header.write('0000777', 100, 8) // File mode + header.write('0001750', 108, 8) // UID + header.write('0001750', 116, 8) // GID + header.write(size.toString(8).padStart(11, '0') + ' ', 124, 12) // File size + header.write(Math.floor(new Date().getTime() / 1000).toString(8) + ' ', 136, 12) // Mod time + header.write(' ', 148, 8) // Checksum placeholder + header.write('0', 156, 1) // Typeflag + header.write('ustar ', 257, 8) // Magic and version + header.write('0'.repeat(8 * 12), 345, 8 * 12) // Fill remaining with zeros + const checksum = header.reduce((sum, elem) => sum + elem, 0) + header.write(checksum.toString(8).padStart(6, '0') + '\0 ', 148, 8) // Write checksum - return { - length: codes.length, - charCodeAt: index => codes[index], - } + return header } -export function makeTar(data: Collection): Uint8Array { - const tar = new Tar(1) - for (const entry of data) { - const path = fixUnicodePath(entry.path) - tar.append(path, entry.data) - } - - return tar.out +function createEndOfArchive(): Uint8Array { + return Buffer.alloc(1024, 0) } diff --git a/src/utils/type.ts b/src/utils/type.ts index 15461d58..1b85694f 100644 --- a/src/utils/type.ts +++ b/src/utils/type.ts @@ -1,4 +1,5 @@ import { decodeCid, encodeReference, ReferenceType } from '@ethersphere/swarm-cid' +import { Readable } from 'stream' import { Address, ADDRESS_HEX_LENGTH, @@ -17,7 +18,6 @@ import { PssMessageHandler, PUBKEY_HEX_LENGTH, PublicKey, - Readable, Reference, REFERENCE_HEX_LENGTH, ReferenceOrEns, @@ -31,7 +31,10 @@ import { import { BeeArgumentError, BeeError } from './error' import { isFile } from './file' import { assertHexString, assertPrefixedHexString, isHexString } from './hex' -import { isReadable } from './stream' + +export function isReadable(obj: unknown): obj is Readable { + return typeof Readable !== 'undefined' && obj instanceof Readable +} export function isUint8Array(obj: unknown): obj is Uint8Array { return obj instanceof Uint8Array diff --git a/src/utils/uint64.ts b/src/utils/uint64.ts deleted file mode 100644 index 3436e868..00000000 --- a/src/utils/uint64.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Bytes, makeBytes } from './bytes' - -// TODO handle bigger values than 32 bit -// For now it's good enough because we only use these functions -// sequential feed indexes. -export function writeUint64LittleEndian(value: number, bytes: Bytes<8> = makeBytes(8)): Bytes<8> { - const dataView = new DataView(bytes.buffer) - const valueLower32 = value & 0xffffffff - const littleEndian = true - - dataView.setUint32(0, valueLower32, littleEndian) - dataView.setUint32(4, 0, littleEndian) - - return bytes -} - -export function writeUint64BigEndian(value: number, bytes: Bytes<8> = makeBytes(8)): Bytes<8> { - const dataView = new DataView(bytes.buffer) - const valueLower32 = value & 0xffffffff - - dataView.setUint32(0, 0) - dataView.setUint32(4, valueLower32) - - return bytes -} - -export function readUint64BigEndian(bytes: Bytes<8>): number { - const dataView = new DataView(bytes.buffer) - - return dataView.getUint32(4) -} diff --git a/src/utils/url.ts b/src/utils/url.ts index 18179515..ef9cd072 100644 --- a/src/utils/url.ts +++ b/src/utils/url.ts @@ -26,13 +26,7 @@ export function isValidBeeUrl(url: unknown): url is URL { // There can be wide range of protocols passed. return urlObject.protocol === 'http:' || urlObject.protocol === 'https:' } catch (e) { - // URL constructor throws TypeError if not valid URL - // TODO: Drop the `.code` hack for NodeJS environment: https://github.com/ethersphere/bee-js/issues/204 - if (e instanceof TypeError || (isNodeJsError(e) && e.code === 'ERR_INVALID_URL')) { - return false - } - - throw e + return false } } diff --git a/test/integration/bee-class.spec.ts b/test/integration/bee-class.spec.ts index bbc36862..f2f2fd98 100644 --- a/test/integration/bee-class.spec.ts +++ b/test/integration/bee-class.spec.ts @@ -1,27 +1,21 @@ import { System } from 'cafe-utility' import { expect } from 'chai' import { expect as jestExpect } from 'expect' -import { Readable } from 'stream' -import { Bee, BeeDebug, BytesReference, Collection, PssSubscription } from '../../src' +import { Bee, BytesReference, Collection, PssSubscription } from '../../src' import { makeSigner } from '../../src/chunk/signer' -import { makeSOCAddress, uploadSingleOwnerChunkData } from '../../src/chunk/soc' +import { uploadSingleOwnerChunkData } from '../../src/chunk/soc' import * as bzz from '../../src/modules/bzz' import { REFERENCE_HEX_LENGTH } from '../../src/types' import { makeBytes } from '../../src/utils/bytes' -import { makeEthAddress } from '../../src/utils/eth' import { HexString, bytesToHex } from '../../src/utils/hex' import { ERR_TIMEOUT, FEED_TIMEOUT, PSS_TIMEOUT, - beeDebugUrl, beeKyOptions, - beePeerDebugUrl, beePeerUrl, beeUrl, commonMatchers, - createRandomNodeReadable, - createReadableStream, getPostageBatch, makeTestTarget, randomByteArray, @@ -29,7 +23,6 @@ import { testIdentity, testJsonHash, testJsonPayload, - tryDeleteChunkFromLocalStorage, } from '../utils' commonMatchers() @@ -38,7 +31,6 @@ describe('Bee class', () => { const BEE_URL = beeUrl() const BEE_KY_OPTIONS = beeKyOptions() const BEE_PEER_URL = beePeerUrl() - const BEE_DEBUG_PEER_URL = beePeerDebugUrl() const bee = new Bee(BEE_URL) const beePeer = new Bee(BEE_PEER_URL) @@ -171,58 +163,6 @@ describe('Bee class', () => { expect(downloadedFile.data).to.eql(content) expect(downloadedFile.contentType).to.eql(contentTypeOverride) }) - - // TODO: https://github.com/ethersphere/bee-js/issues/816 - it.skip('should work with NodeJS readable', async function () { - const readable = Readable.from([new TextEncoder().encode('hello '), new TextEncoder().encode('world')], { - objectMode: false, - }) - const name = 'hello.txt' - const contentType = 'text/plain' - - const result = await bee.uploadFile(getPostageBatch(), readable, name, { contentType }) - const file = await bee.downloadFile(result.reference) - - expect(file.name).to.eql(name) - expect(file.data.text()).to.eql('hello world') - }) - - // TODO: https://github.com/ethersphere/bee-js/issues/816 - it.skip('should work with WHATWG readable-stream', async function () { - this.timeout(1000000) - - const readable = createReadableStream([new TextEncoder().encode('hello '), new TextEncoder().encode('world')]) - const name = 'hello.txt' - const contentType = 'text/plain' - - const result = await bee.uploadFile(getPostageBatch(), readable, name, { contentType }) - const file = await bee.downloadFile(result.reference) - - expect(file.name).to.eql(name) - expect(file.data.text()).to.eql('hello world') - }) - - // TODO: https://github.com/ethersphere/bee-js/issues/816 - it.skip('should work with readable and tags', async function () { - const tag = await bee.createTag() - - const readable = createRandomNodeReadable(13000) - const name = 'hello.txt' - const contentType = 'text/plain' - - const result = await bee.uploadFile(getPostageBatch(), readable, name, { - contentType, - tag: tag.uid, - }) - - const file = await bee.downloadFile(result.reference) - - expect(file.name).to.eql(name) - expect(file.data.length).to.eql(13000) - - const retrievedTag = await bee.retrieveTag(tag) - expect(retrievedTag.split).to.eql(8) - }) }) describe('collections', () => { @@ -239,7 +179,7 @@ describe('Bee class', () => { }) it('should upload collection', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: new TextEncoder().encode('hello-world'), @@ -254,7 +194,7 @@ describe('Bee class', () => { }) it('should upload collection with CIDs support', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: new TextEncoder().encode('hello-CID-world'), @@ -386,15 +326,15 @@ describe('Bee class', () => { ;(async () => { const topic = 'bee-class-topic' const message = new Uint8Array([1, 2, 3]) - const beeDebug = new BeeDebug(beeDebugUrl()) + const bee = new Bee(beeUrl()) bee.pssReceive(topic).then(receivedMessage => { expect(receivedMessage).to.eql(message) resolve() }) - const { overlay } = await beeDebug.getNodeAddresses() - await beePeer.pssSend(getPostageBatch(BEE_DEBUG_PEER_URL), topic, makeTestTarget(overlay), message) + const { overlay } = await bee.getNodeAddresses() + await beePeer.pssSend(getPostageBatch(BEE_PEER_URL), topic, makeTestTarget(overlay), message) })().catch(reject) }) }) @@ -407,21 +347,15 @@ describe('Bee class', () => { ;(async () => { const topic = 'bee-class-topic-publickey' const message = new Uint8Array([1, 2, 3]) - const beeDebug = new BeeDebug(beeDebugUrl()) + const bee = new Bee(beeUrl()) bee.pssReceive(topic).then(receivedMessage => { expect(receivedMessage).to.eql(message) resolve() }) - const { overlay, pssPublicKey } = await beeDebug.getNodeAddresses() - await beePeer.pssSend( - getPostageBatch(BEE_DEBUG_PEER_URL), - topic, - makeTestTarget(overlay), - message, - pssPublicKey, - ) + const { overlay, pssPublicKey } = await bee.getNodeAddresses() + await beePeer.pssSend(getPostageBatch(BEE_PEER_URL), topic, makeTestTarget(overlay), message, pssPublicKey) })().catch(reject) }) }) @@ -434,7 +368,7 @@ describe('Bee class', () => { ;(async () => { const topic = 'bee-class-subscribe-topic' const message = new Uint8Array([1, 2, 3]) - const beeDebug = new BeeDebug(beeDebugUrl()) + const bee = new Bee(beeUrl()) subscription = bee.pssSubscribe(topic, { onMessage: receivedMessage => { @@ -449,8 +383,8 @@ describe('Bee class', () => { }, }) - const { overlay } = await beeDebug.getNodeAddresses() - await beePeer.pssSend(getPostageBatch(BEE_DEBUG_PEER_URL), topic, makeTestTarget(overlay), message) + const { overlay } = await bee.getNodeAddresses() + await beePeer.pssSend(getPostageBatch(BEE_PEER_URL), topic, makeTestTarget(overlay), message) })().catch(e => { // without cancel jest complains for leaking handles and may hang subscription?.cancel() @@ -558,7 +492,7 @@ describe('Bee class', () => { const topic = randomByteArray(32, Date.now()) - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: 'index.html', data: new TextEncoder().encode('some data'), @@ -649,8 +583,6 @@ describe('Bee class', () => { describe('writer', () => { it('should read and write', async function () { const identifier = makeBytes(32) // all zeroes - const socAddress = makeSOCAddress(identifier, makeEthAddress(testIdentity.address)) - await tryDeleteChunkFromLocalStorage(socAddress) const socWriter = bee.makeSOCWriter(testIdentity.privateKey) @@ -667,8 +599,6 @@ describe('Bee class', () => { it('should read', async function () { const signer = makeSigner(testIdentity.privateKey) const identifier = makeBytes(32) // all zeroes - const socAddress = makeSOCAddress(identifier, makeEthAddress(testIdentity.address)) - await tryDeleteChunkFromLocalStorage(socAddress) await uploadSingleOwnerChunkData(BEE_KY_OPTIONS, signer, getPostageBatch(), identifier, testChunkPayload) const socReader = bee.makeSOCReader(testIdentity.address) @@ -684,9 +614,6 @@ describe('Bee class', () => { const identifier = makeBytes(32) identifier[31] = 1 - const socAddress = makeSOCAddress(identifier, makeEthAddress(testIdentity.address)) - await tryDeleteChunkFromLocalStorage(socAddress) - const bee = new Bee(BEE_URL, { signer: testIdentity.privateKey }) const socWriter = bee.makeSOCWriter() @@ -698,9 +625,6 @@ describe('Bee class', () => { const identifier = makeBytes(32) identifier[31] = 2 - const socAddress = makeSOCAddress(identifier, makeEthAddress(testIdentity.address)) - await tryDeleteChunkFromLocalStorage(socAddress) - // We pass different private key to the instance const bee = new Bee(BEE_URL, { signer: '634fb5a872396d9611e5c9f9d7233cfa93f395c093371017ff44aa9ae6564cdd', diff --git a/test/integration/bee-debug-class.spec.ts b/test/integration/bee-debug-class.spec.ts index a7d629ac..a7a03821 100644 --- a/test/integration/bee-debug-class.spec.ts +++ b/test/integration/bee-debug-class.spec.ts @@ -1,33 +1,28 @@ import { System } from 'cafe-utility' import { expect } from 'chai' import { expect as jestExpect } from 'expect' -import { BeeArgumentError, BeeDebug } from '../../src' -import { - beeDebugUrl, - BLOCKCHAIN_TRANSACTION_TIMEOUT, - getOrCreatePostageBatch, - WAITING_USABLE_STAMP_TIMEOUT, -} from '../utils' - -describe('Bee Debug class', () => { - const BEE_DEBUG_URL = beeDebugUrl() - const beeDebug = new BeeDebug(BEE_DEBUG_URL) +import { Bee, BeeArgumentError } from '../../src' +import { BLOCKCHAIN_TRANSACTION_TIMEOUT, WAITING_USABLE_STAMP_TIMEOUT, beeUrl, getOrCreatePostageBatch } from '../utils' + +describe('Bee class debug modules', () => { + const BEE_URL = beeUrl() + const bee = new Bee(BEE_URL) describe('PostageBatch', () => { it('should create a new postage batch with zero amount and be usable', async function () { this.timeout(WAITING_USABLE_STAMP_TIMEOUT + BLOCKCHAIN_TRANSACTION_TIMEOUT) - const batchId = await beeDebug.createPostageBatch('10', 17) - const stamp = await beeDebug.getPostageBatch(batchId) + const batchId = await bee.createPostageBatch('10', 17) + const stamp = await bee.getPostageBatch(batchId) expect(stamp.usable).to.eql(true) - const allBatches = await beeDebug.getAllPostageBatch() + const allBatches = await bee.getAllPostageBatch() expect(allBatches.find(batch => batch.batchID === batchId)).to.be.ok() }) it('should not wait for the stamp to be usable if specified', async function () { this.timeout(BLOCKCHAIN_TRANSACTION_TIMEOUT) - const batchId = await beeDebug.createPostageBatch('1000', 17, { waitForUsable: false }) - const stamp = await beeDebug.getPostageBatch(batchId) + const batchId = await bee.createPostageBatch('1000', 17, { waitForUsable: false }) + const stamp = await bee.getPostageBatch(batchId) expect(stamp.usable).to.eql(false) }) @@ -36,10 +31,10 @@ describe('Bee Debug class', () => { this.timeout(BLOCKCHAIN_TRANSACTION_TIMEOUT * 3) const batch = await getOrCreatePostageBatch(undefined, undefined, false) - await beeDebug.topUpBatch(batch.batchID, '10') + await bee.topUpBatch(batch.batchID, '10') await System.sleepMillis(4000) - const batchDetails = await beeDebug.getPostageBatch(batch.batchID) + const batchDetails = await bee.getPostageBatch(batch.batchID) const newAmount = (parseInt(batch.amount) + 10).toString() expect(batchDetails.amount).to.eql(newAmount) }) @@ -48,24 +43,24 @@ describe('Bee Debug class', () => { it.skip('should dilute postage batch', async function () { this.timeout(BLOCKCHAIN_TRANSACTION_TIMEOUT * 2) const batch = await getOrCreatePostageBatch(undefined, 17, false) - await beeDebug.diluteBatch(batch.batchID, batch.depth + 2) + await bee.diluteBatch(batch.batchID, batch.depth + 2) - const batchDetails = await beeDebug.getPostageBatch(batch.batchID) + const batchDetails = await bee.getPostageBatch(batch.batchID) expect(batchDetails.depth).to.eql(batch.depth + 2) }) it('should have both immutable true and false', async function () { this.timeout(WAITING_USABLE_STAMP_TIMEOUT * 2 + BLOCKCHAIN_TRANSACTION_TIMEOUT * 4) - await beeDebug.createPostageBatch('1', 17, { immutableFlag: true, waitForUsable: true }) - await beeDebug.createPostageBatch('1', 17, { immutableFlag: false, waitForUsable: true }) - const allBatches = await beeDebug.getAllPostageBatch() + await bee.createPostageBatch('1', 17, { immutableFlag: true, waitForUsable: true }) + await bee.createPostageBatch('1', 17, { immutableFlag: false, waitForUsable: true }) + const allBatches = await bee.getAllPostageBatch() expect(allBatches.find(batch => batch.immutableFlag === true)).to.be.ok() expect(allBatches.find(batch => batch.immutableFlag === false)).to.be.ok() }) it('should have all properties', async function () { - const allBatches = await beeDebug.getAllPostageBatch() + const allBatches = await bee.getAllPostageBatch() expect(allBatches.length).above(0) @@ -89,11 +84,11 @@ describe('Bee Debug class', () => { }) it('buckets should have all properties', async function () { - const allBatches = await beeDebug.getAllPostageBatch() + const allBatches = await bee.getAllPostageBatch() expect(allBatches.length).above(0) const batchId = allBatches[0].batchID - const buckets = await beeDebug.getPostageBatchBuckets(batchId) + const buckets = await bee.getPostageBatchBuckets(batchId) jestExpect(buckets).toEqual( jestExpect.objectContaining({ @@ -111,13 +106,13 @@ describe('Bee Debug class', () => { }) it('should error with negative amount', async function () { - await expect(beeDebug.createPostageBatch('-1', 17)).rejectedWith(BeeArgumentError) + await expect(bee.createPostageBatch('-1', 17)).rejectedWith(BeeArgumentError) }) }) describe('modes', () => { it('should return modes', async function () { - jestExpect(await beeDebug.getNodeInfo()).toEqual( + jestExpect(await bee.getNodeInfo()).toEqual( jestExpect.objectContaining({ beeMode: jestExpect.stringMatching(/^(dev|light|full)$/), chequebookEnabled: jestExpect.any(Boolean), @@ -129,16 +124,16 @@ describe('Bee Debug class', () => { describe('staking', () => { it('should return amount staked', async function () { - expect(await beeDebug.getStake()).to.match(/^[0-9]+$/) + expect(await bee.getStake()).to.match(/^[0-9]+$/) }) it('should deposit stake', async function () { this.timeout(BLOCKCHAIN_TRANSACTION_TIMEOUT) - const originalStake = BigInt(await beeDebug.getStake()) + const originalStake = BigInt(await bee.getStake()) - await beeDebug.depositStake('100000000000000000') + await bee.depositStake('100000000000000000') - const increasedStake = BigInt(await beeDebug.getStake()) + const increasedStake = BigInt(await bee.getStake()) expect(increasedStake - originalStake).to.eql(BigInt(10e16)) }) @@ -146,7 +141,7 @@ describe('Bee Debug class', () => { describe('Wallet', () => { it('should return the nodes balances and other data', async function () { - jestExpect(await beeDebug.getWalletBalance()).toEqual( + jestExpect(await bee.getWalletBalance()).toEqual( jestExpect.objectContaining({ bzzBalance: jestExpect.stringMatching(/^[0-9]+$/), nativeTokenBalance: jestExpect.stringMatching(/^[0-9]+$/), diff --git a/test/integration/chunk/soc.spec.ts b/test/integration/chunk/soc.spec.ts index 7c9cd3c5..362030b8 100644 --- a/test/integration/chunk/soc.spec.ts +++ b/test/integration/chunk/soc.spec.ts @@ -3,9 +3,9 @@ import { makeContentAddressedChunk } from '../../../src/chunk/cac' import { makePrivateKeySigner } from '../../../src/chunk/signer' import { makeSingleOwnerChunk, makeSingleOwnerChunkFromData, uploadSingleOwnerChunk } from '../../../src/chunk/soc' import * as chunkAPI from '../../../src/modules/chunk' -import { assertBytes, Bytes } from '../../../src/utils/bytes' -import { bytesToHex, HexString, hexToBytes } from '../../../src/utils/hex' -import { beeKyOptions, getPostageBatch, testIdentity, tryDeleteChunkFromLocalStorage } from '../../utils' +import { Bytes, assertBytes } from '../../../src/utils/bytes' +import { HexString, bytesToHex, hexToBytes } from '../../../src/utils/hex' +import { beeKyOptions, getPostageBatch, testIdentity } from '../../utils' describe('soc', () => { const privateKey = hexToBytes(testIdentity.privateKey) @@ -20,8 +20,6 @@ describe('soc', () => { const soc = await makeSingleOwnerChunk(cac, identifier, signer) const socAddress = bytesToHex(soc.address()) - await tryDeleteChunkFromLocalStorage(socHash) - const response = await uploadSingleOwnerChunk(beeKyOptions(), soc, getPostageBatch()) expect(response).to.eql(socAddress) diff --git a/test/integration/modules/bzz.spec.ts b/test/integration/modules/bzz.spec.ts index 5f8f96db..3c62aabf 100644 --- a/test/integration/modules/bzz.spec.ts +++ b/test/integration/modules/bzz.spec.ts @@ -12,7 +12,7 @@ const BEE_KY_OPTIONS = beeKyOptions() describe('modules/bzz', () => { describe('collections', () => { it('should store and retrieve collection with single file', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: Uint8Array.from([0]), @@ -29,7 +29,7 @@ describe('modules/bzz', () => { it('should retrieve the filename but not the complete path', async function () { const path = 'a/b/c/d/' const name = '0' - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: `${path}${name}`, data: Uint8Array.from([0]), @@ -44,7 +44,7 @@ describe('modules/bzz', () => { }) it('should work with pinning', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: Uint8Array.from([0]), @@ -59,7 +59,7 @@ describe('modules/bzz', () => { }) it('should work with encryption', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: Uint8Array.from([0]), @@ -78,7 +78,7 @@ describe('modules/bzz', () => { it('should upload bigger file', async function () { this.timeout(BIG_FILE_TIMEOUT) - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: new Uint8Array(32 * 1024 * 1024), @@ -96,7 +96,7 @@ describe('modules/bzz', () => { }) it('should store and retrieve collection', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: Uint8Array.from([0]), @@ -119,7 +119,7 @@ describe('modules/bzz', () => { }) it('should store and retrieve collection with index document', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: Uint8Array.from([0]), @@ -140,7 +140,7 @@ describe('modules/bzz', () => { }) it('should store and retrieve collection with error document', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: Uint8Array.from([0]), diff --git a/test/integration/modules/debug/balance.spec.ts b/test/integration/modules/debug/balance.spec.ts index aab80a96..20a17c24 100644 --- a/test/integration/modules/debug/balance.spec.ts +++ b/test/integration/modules/debug/balance.spec.ts @@ -2,11 +2,11 @@ import { expect } from 'chai' import { expect as jestExpect } from 'expect' import * as balance from '../../../../src/modules/debug/balance' import * as connectivity from '../../../../src/modules/debug/connectivity' -import { beeDebugKyOptions, beePeerDebugKyOptions, commonMatchers } from '../../../utils' +import { beeKyOptions, beePeerKyOptions, commonMatchers } from '../../../utils' // helper function to get the peer overlay address async function getPeerOverlay() { - const nodeAddresses = await connectivity.getNodeAddresses(beePeerDebugKyOptions()) + const nodeAddresses = await connectivity.getNodeAddresses(beePeerKyOptions()) return nodeAddresses.overlay } @@ -17,7 +17,7 @@ describe('balance', () => { describe('balances', () => { it('Get the balances with all known peers including prepaid services', async function () { const peerOverlay = await getPeerOverlay() - const response = await balance.getAllBalances(beeDebugKyOptions()) + const response = await balance.getAllBalances(beeKyOptions()) jestExpect(response.balances).toEqual( jestExpect.arrayContaining([ @@ -35,7 +35,7 @@ describe('balance', () => { it('Get the balances with all known peers including prepaid services', async function () { const peerOverlay = await getPeerOverlay() - const peerBalance = await balance.getPeerBalance(beeDebugKyOptions(), peerOverlay) + const peerBalance = await balance.getPeerBalance(beeKyOptions(), peerOverlay) expect(peerBalance.peer).to.eql(peerOverlay) expect(peerBalance.balance).to.be.numberString() @@ -45,7 +45,7 @@ describe('balance', () => { describe('consumed', () => { it('Get the past due consumption balances with all known peers', async function () { const peerOverlay = await getPeerOverlay() - const response = await balance.getPastDueConsumptionBalances(beeDebugKyOptions()) + const response = await balance.getPastDueConsumptionBalances(beeKyOptions()) jestExpect(response.balances).toEqual( jestExpect.arrayContaining([ @@ -63,7 +63,7 @@ describe('balance', () => { it('Get the past due consumption balance with a specific peer', async function () { const peerOverlay = await getPeerOverlay() - const peerBalance = await balance.getPastDueConsumptionPeerBalance(beeDebugKyOptions(), peerOverlay) + const peerBalance = await balance.getPastDueConsumptionPeerBalance(beeKyOptions(), peerOverlay) expect(peerBalance.peer).to.eql(peerOverlay) expect(peerBalance.balance).to.be.numberString() diff --git a/test/integration/modules/debug/chequebook.spec.ts b/test/integration/modules/debug/chequebook.spec.ts index c67f0648..70065ca7 100644 --- a/test/integration/modules/debug/chequebook.spec.ts +++ b/test/integration/modules/debug/chequebook.spec.ts @@ -9,20 +9,20 @@ import { } from '../../../../src/modules/debug/chequebook' import { NumberString } from '../../../../src/types' import { isPrefixedHexString } from '../../../../src/utils/hex' -import { beeDebugKyOptions, commonMatchers } from '../../../utils' +import { beeKyOptions, commonMatchers } from '../../../utils' if (process.env.BEE_TEST_CHEQUEBOOK) { commonMatchers() describe('swap enabled chequebook', () => { it('address', async function () { - const response = await getChequebookAddress(beeDebugKyOptions()) + const response = await getChequebookAddress(beeKyOptions()) expect(isPrefixedHexString(response.chequebookAddress)).to.be.ok() }) it('balance', async function () { - const response = await getChequebookBalance(beeDebugKyOptions()) + const response = await getChequebookBalance(beeKyOptions()) expect(response.availableBalance).to.be.numberString() expect(response.totalBalance).to.be.numberString() @@ -31,14 +31,14 @@ if (process.env.BEE_TEST_CHEQUEBOOK) { const TRANSACTION_TIMEOUT = 20 * 1000 const withDrawDepositTest = (amount: number | NumberString) => async () => { - const withdrawResponse = await withdrawTokens(beeDebugKyOptions(), amount) + const withdrawResponse = await withdrawTokens(beeKyOptions(), amount) expect(withdrawResponse).a('string') // TODO avoid sleep in tests // See https://github.com/ethersphere/bee/issues/1191 await System.sleepMillis(TRANSACTION_TIMEOUT) - const depositResponse = await depositTokens(beeDebugKyOptions(), amount) + const depositResponse = await depositTokens(beeKyOptions(), amount) expect(depositResponse).a('string') @@ -58,7 +58,7 @@ if (process.env.BEE_TEST_CHEQUEBOOK) { }) it('get last cheques for all peers', async function () { - const response = await getLastCheques(beeDebugKyOptions()) + const response = await getLastCheques(beeKyOptions()) expect(Array.isArray(response.lastcheques)).to.be.ok() }) diff --git a/test/integration/modules/debug/connectivity.spec.ts b/test/integration/modules/debug/connectivity.spec.ts index a841671f..87a41d45 100644 --- a/test/integration/modules/debug/connectivity.spec.ts +++ b/test/integration/modules/debug/connectivity.spec.ts @@ -6,11 +6,11 @@ import { getTopology, pingPeer, } from '../../../../src/modules/debug/connectivity' -import { beeDebugKyOptions } from '../../../utils' +import { beeKyOptions } from '../../../utils' describe('modules/debug/connectivity', () => { it('getPeers', async function () { - const peers = await getPeers(beeDebugKyOptions()) + const peers = await getPeers(beeKyOptions()) expect(Array.isArray(peers)).to.be.ok() expect(peers.length).above(0) @@ -22,7 +22,7 @@ describe('modules/debug/connectivity', () => { }) it('getBlocklist', async function () { - const peers = await getBlocklist(beeDebugKyOptions()) + const peers = await getBlocklist(beeKyOptions()) expect(Array.isArray(peers)).to.be.ok() @@ -33,7 +33,7 @@ describe('modules/debug/connectivity', () => { }) it('getTopology', async function () { - const topology = await getTopology(beeDebugKyOptions()) + const topology = await getTopology(beeKyOptions()) expect(topology.baseAddr).to.match(/^[0-9a-f]{64}$/i) expect(topology.population).to.be.least(0) @@ -52,7 +52,7 @@ describe('modules/debug/connectivity', () => { }) it('getNodeAddresses', async function () { - const addresses = await getNodeAddresses(beeDebugKyOptions()) + const addresses = await getNodeAddresses(beeKyOptions()) expect(addresses.overlay).to.match(/^[0-9a-f]{64}$/) expect(Array.isArray(addresses.underlay)).to.be.ok() @@ -62,8 +62,8 @@ describe('modules/debug/connectivity', () => { }) it('pingPeer', async function () { - const peers = await getPeers(beeDebugKyOptions()) - const res = await pingPeer(beeDebugKyOptions(), peers[0].address) + const peers = await getPeers(beeKyOptions()) + const res = await pingPeer(beeKyOptions(), peers[0].address) expect(res.rtt).to.match(/^\d+(\.\d+)?[mnpµ]?s$/) }) diff --git a/test/integration/modules/debug/settlements.spec.ts b/test/integration/modules/debug/settlements.spec.ts index c395da6a..4db0f1ba 100644 --- a/test/integration/modules/debug/settlements.spec.ts +++ b/test/integration/modules/debug/settlements.spec.ts @@ -1,13 +1,13 @@ import { expect } from 'chai' import { expect as jestExpect } from 'expect' import * as settlements from '../../../../src/modules/debug/settlements' -import { beeDebugKyOptions, commonMatchers } from '../../../utils' +import { beeKyOptions, commonMatchers } from '../../../utils' commonMatchers() describe('settlements', () => { it('all settlements', async function () { - const response = await settlements.getAllSettlements(beeDebugKyOptions()) + const response = await settlements.getAllSettlements(beeKyOptions()) expect(response.totalReceived).to.be.numberString() expect(response.totalSent).to.be.numberString() @@ -26,7 +26,7 @@ describe('settlements', () => { const peerSettlement = response.settlements[0] - const peerSettlementResponse = await settlements.getSettlements(beeDebugKyOptions(), peerSettlement.peer) + const peerSettlementResponse = await settlements.getSettlements(beeKyOptions(), peerSettlement.peer) expect(peerSettlementResponse.peer).to.eql(peerSettlement.peer) expect(peerSettlementResponse.received).to.be.numberString() diff --git a/test/integration/modules/debug/states.spec.ts b/test/integration/modules/debug/states.spec.ts index 5ec6e9de..32085174 100644 --- a/test/integration/modules/debug/states.spec.ts +++ b/test/integration/modules/debug/states.spec.ts @@ -1,14 +1,14 @@ import { expect } from 'chai' import * as states from '../../../../src/modules/debug/states' -import { beeDebugKyOptions, commonMatchers } from '../../../utils' +import { beeKyOptions, commonMatchers } from '../../../utils' -const BEE_DEBUG_URL = beeDebugKyOptions() +const BEE_URL = beeKyOptions() commonMatchers() describe('modules/states', () => { describe('chainstate', () => { it('should fetch the chainstate', async function () { - const state = await states.getChainState(BEE_DEBUG_URL) + const state = await states.getChainState(BEE_URL) expect(state).to.have.property('block') expect(state).to.have.property('totalAmount') @@ -20,7 +20,7 @@ describe('modules/states', () => { }) describe('ReserveState', () => { it('should fetch the reserve state', async function () { - const state = await states.getReserveState(BEE_DEBUG_URL) + const state = await states.getReserveState(BEE_URL) expect(state).to.have.property('commitment') expect(state).to.have.property('radius') expect(state).to.have.property('storageRadius') diff --git a/test/integration/modules/debug/status.spec.ts b/test/integration/modules/debug/status.spec.ts index 6c7b6928..ec8c3e1a 100644 --- a/test/integration/modules/debug/status.spec.ts +++ b/test/integration/modules/debug/status.spec.ts @@ -9,21 +9,19 @@ import { getReadiness, getVersions, isSupportedApiVersion, - isSupportedDebugApiVersion, isSupportedExactVersion, isSupportedMainApiVersion, isSupportedVersion, SUPPORTED_API_VERSION, SUPPORTED_BEE_VERSION_EXACT, - SUPPORTED_DEBUG_API_VERSION, } from '../../../../src/modules/debug/status' -import { beeDebugKyOptions } from '../../../utils' +import { beeKyOptions } from '../../../utils' -const BEE_DEBUG_URL = beeDebugKyOptions() +const BEE_URL = beeKyOptions() describe('modules/status', () => { it('getHealth', async function () { - const health = await getHealth(BEE_DEBUG_URL) + const health = await getHealth(BEE_URL) expect(health.status).to.eql('ok') // Matches both versions like 0.5.3-c423a39c, 0.5.3-c423a39c-dirty and 0.5.3 @@ -31,61 +29,51 @@ describe('modules/status', () => { }) it('getReadiness', async function () { - const isReady = await getReadiness(BEE_DEBUG_URL) + const isReady = await getReadiness(BEE_URL) expect(isReady).to.eql(true) }) it('isSupportedVersion', async function () { - const isSupported = await isSupportedVersion(BEE_DEBUG_URL) + const isSupported = await isSupportedVersion(BEE_URL) expect(isSupported).to.eql(true) }) it('isSupportedExactVersion', async function () { - const isSupported = await isSupportedExactVersion(BEE_DEBUG_URL) + const isSupported = await isSupportedExactVersion(BEE_URL) expect(isSupported).to.eql(true) }) it('isSupportedMainApiVersion', async function () { - const isSupported = await isSupportedMainApiVersion(BEE_DEBUG_URL) - - expect(isSupported).to.eql(true) - }) - - it('isSupportedDebugApiVersion', async function () { - const isSupported = await isSupportedDebugApiVersion(BEE_DEBUG_URL) + const isSupported = await isSupportedMainApiVersion(BEE_URL) expect(isSupported).to.eql(true) }) it('isSupportedApiVersion', async function () { - const isSupported = await isSupportedApiVersion(BEE_DEBUG_URL) + const isSupported = await isSupportedApiVersion(BEE_URL) expect(isSupported).to.eql(true) }) it('getVersions', async function () { - const versions = await getVersions(BEE_DEBUG_URL) + const versions = await getVersions(BEE_URL) jestExpect(versions).toEqual( jestExpect.objectContaining({ supportedBeeVersion: jestExpect.any(String), supportedBeeApiVersion: jestExpect.any(String), - supportedBeeDebugApiVersion: jestExpect.any(String), beeVersion: jestExpect.any(String), beeApiVersion: jestExpect.any(String), - beeDebugApiVersion: jestExpect.any(String), }), ) expect(semver.valid(versions.beeVersion)).to.not.be.null() expect(semver.valid(versions.beeApiVersion)).to.not.be.null() - expect(semver.valid(versions.beeDebugApiVersion)).to.not.be.null() expect(semver.valid(versions.supportedBeeApiVersion)).to.not.be.null() expect(semver.valid(versions.supportedBeeVersion)).to.not.be.null() - expect(semver.valid(versions.supportedBeeDebugApiVersion)).to.not.be.null() }) it('SUPPORTED_BEE_* should be same as in package.json', async function () { @@ -94,6 +82,5 @@ describe('modules/status', () => { expect(SUPPORTED_BEE_VERSION_EXACT).to.eql(packageJson.engines.bee) expect(SUPPORTED_API_VERSION).to.eql(packageJson.engines.beeApiVersion) - expect(SUPPORTED_DEBUG_API_VERSION).to.eql(packageJson.engines.beeDebugApiVersion) }) }) diff --git a/test/integration/modules/debug/tag.spec.ts b/test/integration/modules/debug/tag.spec.ts deleted file mode 100644 index 23b1aea8..00000000 --- a/test/integration/modules/debug/tag.spec.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { expect as jestExpect } from 'expect' -import * as beeDebugTag from '../../../../src/modules/debug/tag' -import * as beeTag from '../../../../src/modules/tag' -import { beeDebugKyOptions, beeKyOptions } from '../../../utils' - -const BEE_URL = beeKyOptions() -const BEE_DEBUG_KY = beeDebugKyOptions() - -describe('modules/tag', () => { - it('should retrieve extended tag', async function () { - const tag1 = await beeTag.createTag(BEE_URL) - const tag2 = await beeDebugTag.retrieveExtendedTag(BEE_DEBUG_KY, tag1.uid) - - jestExpect(tag2).toEqual( - jestExpect.objectContaining({ - total: jestExpect.any(Number), - split: jestExpect.any(Number), - seen: jestExpect.any(Number), - stored: jestExpect.any(Number), - sent: jestExpect.any(Number), - synced: jestExpect.any(Number), - uid: jestExpect.any(Number), - startedAt: jestExpect.any(String), - address: jestExpect.any(String), - }), - ) - }) -}) diff --git a/test/integration/modules/debug/transactions.spec.ts b/test/integration/modules/debug/transactions.spec.ts index 0d5257f1..cb233a35 100644 --- a/test/integration/modules/debug/transactions.spec.ts +++ b/test/integration/modules/debug/transactions.spec.ts @@ -1,11 +1,11 @@ import { expect } from 'chai' import * as transactions from '../../../../src/modules/debug/transactions' -import { beeDebugKyOptions, commonMatchers } from '../../../utils' +import { beeKyOptions, commonMatchers } from '../../../utils' commonMatchers() describe('transactions', () => { it('should get at least empty array for listing', async function () { - await expect(transactions.getAllTransactions(beeDebugKyOptions())).eventually.a('array') + await expect(transactions.getAllTransactions(beeKyOptions())).eventually.a('array') }) }) diff --git a/test/integration/modules/feed.spec.ts b/test/integration/modules/feed.spec.ts index ae2ccc63..b348a85e 100644 --- a/test/integration/modules/feed.spec.ts +++ b/test/integration/modules/feed.spec.ts @@ -3,14 +3,7 @@ import { createFeedManifest, fetchLatestFeedUpdate } from '../../../src/modules/ import { upload as uploadSOC } from '../../../src/modules/soc' import type { Topic } from '../../../src/types' import { HexString, hexToBytes, makeHexString } from '../../../src/utils/hex' -import { - ERR_TIMEOUT, - beeKyOptions, - commonMatchers, - getPostageBatch, - testIdentity, - tryDeleteChunkFromLocalStorage, -} from '../../utils' +import { ERR_TIMEOUT, beeKyOptions, commonMatchers, getPostageBatch, testIdentity } from '../../utils' commonMatchers() @@ -46,11 +39,6 @@ describe('modules/feed', () => { '280000000000000000000000602a57df0000000000000000000000000000000000000000000000000000000000000000' as HexString, ) - // delete the chunk from local storage if already exists - // this makes the test repeatable - const cacAddress = '03e8eef6d72dbca9dfb7d2e15a5a305a152a3807ac7fd5ea52721a16972f3813' - await tryDeleteChunkFromLocalStorage(cacAddress) - const socResponse = await uploadSOC(BEE_KY_OPTIONS, owner, identifier, signature, socData, getPostageBatch()) expect(socResponse).a('string') diff --git a/test/integration/modules/pinning.spec.ts b/test/integration/modules/pinning.spec.ts index 4a7ed92f..530ad792 100644 --- a/test/integration/modules/pinning.spec.ts +++ b/test/integration/modules/pinning.spec.ts @@ -44,7 +44,7 @@ describe('modules/pin', () => { }) describe('should work with collections', () => { - const testCollection: Collection = [ + const testCollection: Collection = [ { path: '0', data: Uint8Array.from([0]), diff --git a/test/integration/modules/pss.spec.ts b/test/integration/modules/pss.spec.ts index dc137354..ecb0f122 100644 --- a/test/integration/modules/pss.spec.ts +++ b/test/integration/modules/pss.spec.ts @@ -2,21 +2,19 @@ import { expect } from 'chai' import * as connectivity from '../../../src/modules/debug/connectivity' import * as pss from '../../../src/modules/pss' import { - beeDebugKyOptions, beeKyOptions, - beePeerDebugUrl, beePeerKyOptions, + beePeerUrl, beeUrl, getPostageBatch, makeTestTarget, PSS_TIMEOUT, } from '../../utils' -const BEE_KY_OPTIONS = beeKyOptions() +const BEE_KY = beeKyOptions() const BEE_URL = beeUrl() const BEE_PEER_KY = beePeerKyOptions() -const BEE_DEBUG_KY = beeDebugKyOptions() -const BEE_DEBUG_PEER_URL = beePeerDebugUrl() +const BEE_PEER_URL = beePeerUrl() // these tests only work when there is at least one peer connected describe('modules/pss', () => { @@ -26,11 +24,11 @@ describe('modules/pss', () => { const topic = 'send-pss-message' const message = 'hello' - const peers = await connectivity.getPeers(BEE_DEBUG_KY) + const peers = await connectivity.getPeers(BEE_KY) expect(peers.length).above(0) const target = peers[0].address - await pss.send(BEE_KY_OPTIONS, topic, makeTestTarget(target), message, getPostageBatch()) // Nothing is asserted as nothing is returned, will throw error if something is wrong + await pss.send(BEE_KY, topic, makeTestTarget(target), message, getPostageBatch()) // Nothing is asserted as nothing is returned, will throw error if something is wrong }) it('should send and receive PSS message', async function () { @@ -54,9 +52,9 @@ describe('modules/pss', () => { resolve() } - const addresses = await connectivity.getNodeAddresses(BEE_DEBUG_KY) + const addresses = await connectivity.getNodeAddresses(BEE_KY) const target = addresses.overlay - await pss.send(BEE_PEER_KY, topic, makeTestTarget(target), message, getPostageBatch(BEE_DEBUG_PEER_URL)) + await pss.send(BEE_PEER_KY, topic, makeTestTarget(target), message, getPostageBatch(BEE_PEER_URL)) })().catch(reject) }) }) @@ -83,17 +81,10 @@ describe('modules/pss', () => { resolve() } - const addresses = await connectivity.getNodeAddresses(BEE_DEBUG_KY) + const addresses = await connectivity.getNodeAddresses(BEE_KY) const target = addresses.overlay const recipient = addresses.pssPublicKey - await pss.send( - BEE_PEER_KY, - topic, - makeTestTarget(target), - message, - getPostageBatch(BEE_DEBUG_PEER_URL), - recipient, - ) + await pss.send(BEE_PEER_KY, topic, makeTestTarget(target), message, getPostageBatch(BEE_PEER_URL), recipient) })().catch(reject) }) }) diff --git a/test/integration/modules/stewardship.spec.ts b/test/integration/modules/stewardship.spec.ts index 5ae8f089..bc3fc63d 100644 --- a/test/integration/modules/stewardship.spec.ts +++ b/test/integration/modules/stewardship.spec.ts @@ -8,7 +8,7 @@ const BEE_KY_OPTIONS = beeKyOptions() describe('modules/stewardship', () => { describe('collections', () => { it('should reupload directory', async function () { - const directoryStructure: Collection = [ + const directoryStructure: Collection = [ { path: '0', data: Uint8Array.from([0]), diff --git a/test/shape/get-addresses.ts b/test/shape/get-addresses.ts new file mode 100644 index 00000000..02954c82 --- /dev/null +++ b/test/shape/get-addresses.ts @@ -0,0 +1,12 @@ +import { Types } from 'cafe-utility' + +export const getAddressesShape = { + overlay: Types.isHexString, + underlay: (x: any) => + Types.asArray(x) + .map(Types.isString) + .every((y: boolean) => y === true), + ethereum: Types.isHexString, + publicKey: Types.isHexString, + pssPublicKey: Types.isHexString, +} diff --git a/test/shape/get-balances.ts b/test/shape/get-balances.ts new file mode 100644 index 00000000..a9e6093d --- /dev/null +++ b/test/shape/get-balances.ts @@ -0,0 +1,6 @@ +import { Types } from 'cafe-utility' +import { peerWithBalanceShape } from './peer-with-balance' + +export const getBalancesShape = { + balances: (x: any) => Types.enforceArrayShape(x, peerWithBalanceShape), +} diff --git a/test/shape/get-batches.ts b/test/shape/get-batches.ts new file mode 100644 index 00000000..ce63da3a --- /dev/null +++ b/test/shape/get-batches.ts @@ -0,0 +1,6 @@ +import { Types } from 'cafe-utility' +import { globalStampShape } from './global-stamp' + +export const getBatchesShape = { + batches: (x: any) => Types.enforceArrayShape(x, globalStampShape), +} diff --git a/test/shape/get-chainstate.ts b/test/shape/get-chainstate.ts new file mode 100644 index 00000000..3c9fd0a1 --- /dev/null +++ b/test/shape/get-chainstate.ts @@ -0,0 +1,8 @@ +import { Types } from 'cafe-utility' + +export const getChainstateShape = { + chainTip: Types.isNumber, + block: Types.isNumber, + totalAmount: Types.isIntegerString, + currentPrice: Types.isIntegerString, +} diff --git a/test/shape/get-chequebook-address.ts b/test/shape/get-chequebook-address.ts new file mode 100644 index 00000000..142d3118 --- /dev/null +++ b/test/shape/get-chequebook-address.ts @@ -0,0 +1,5 @@ +import { Types } from 'cafe-utility' + +export const getChequebookAddressShape = { + chequebookAddress: Types.isHexString, +} diff --git a/test/shape/get-chequebook-balance.ts b/test/shape/get-chequebook-balance.ts new file mode 100644 index 00000000..8fc6d036 --- /dev/null +++ b/test/shape/get-chequebook-balance.ts @@ -0,0 +1,6 @@ +import { Types } from 'cafe-utility' + +export const getChequebookBalanceShape = { + totalBalance: Types.isIntegerString, + availableBalance: Types.isIntegerString, +} diff --git a/test/shape/get-chequebook-cheque.ts b/test/shape/get-chequebook-cheque.ts new file mode 100644 index 00000000..b770272c --- /dev/null +++ b/test/shape/get-chequebook-cheque.ts @@ -0,0 +1,6 @@ +import { Types } from 'cafe-utility' +import { peerChequesShape } from './peer-cheques' + +export const getChequebookChequeShape = { + lastcheques: (x: any) => Types.enforceArrayShape(x, peerChequesShape), +} diff --git a/test/shape/get-health.ts b/test/shape/get-health.ts new file mode 100644 index 00000000..5ed30d79 --- /dev/null +++ b/test/shape/get-health.ts @@ -0,0 +1,7 @@ +import { Types } from 'cafe-utility' + +export const getHealthShape = { + status: Types.isString, + version: Types.isString, + apiVersion: Types.isString, +} diff --git a/test/shape/get-node.ts b/test/shape/get-node.ts new file mode 100644 index 00000000..864e9eac --- /dev/null +++ b/test/shape/get-node.ts @@ -0,0 +1,7 @@ +import { Types } from 'cafe-utility' + +export const getNodeShape = { + beeMode: Types.isString, + chequebookEnabled: Types.isBoolean, + swapEnabled: Types.isBoolean, +} diff --git a/test/shape/get-peers.ts b/test/shape/get-peers.ts new file mode 100644 index 00000000..6b599a72 --- /dev/null +++ b/test/shape/get-peers.ts @@ -0,0 +1,6 @@ +import { Types } from 'cafe-utility' +import { peerShape } from './peer' + +export const getPeersShape = { + peers: (x: any) => Types.enforceArrayShape(x, peerShape), +} diff --git a/test/shape/get-readiness.ts b/test/shape/get-readiness.ts new file mode 100644 index 00000000..ef6b747b --- /dev/null +++ b/test/shape/get-readiness.ts @@ -0,0 +1,10 @@ +import { Types } from 'cafe-utility' + +export const getReadinessShape = { + code: Types.isNumber, + message: Types.isString, + reasons: (x: any) => + Types.asArray(x) + .map(Types.isString) + .every((y: boolean) => y === true), +} diff --git a/test/shape/get-redistributionstate.ts b/test/shape/get-redistributionstate.ts new file mode 100644 index 00000000..3e2b50d4 --- /dev/null +++ b/test/shape/get-redistributionstate.ts @@ -0,0 +1,19 @@ +import { Types } from 'cafe-utility' + +export const getRedistributionstateShape = { + minimumGasFunds: Types.isIntegerString, + hasSufficientFunds: Types.isBoolean, + isFrozen: Types.isBoolean, + isFullySynced: Types.isBoolean, + isHealthy: Types.isBoolean, + phase: Types.isString, + round: Types.isNumber, + lastWonRound: Types.isNumber, + lastPlayedRound: Types.isNumber, + lastFrozenRound: Types.isNumber, + lastSelectedRound: Types.isNumber, + lastSampleDuration: Types.isString, + block: Types.isNumber, + reward: Types.isIntegerString, + fees: Types.isIntegerString, +} diff --git a/test/shape/get-reservestate.ts b/test/shape/get-reservestate.ts new file mode 100644 index 00000000..9d177071 --- /dev/null +++ b/test/shape/get-reservestate.ts @@ -0,0 +1,7 @@ +import { Types } from 'cafe-utility' + +export const getReservestateShape = { + radius: Types.isNumber, + storageRadius: Types.isNumber, + commitment: Types.isNumber, +} diff --git a/test/shape/get-settlements.ts b/test/shape/get-settlements.ts new file mode 100644 index 00000000..16f0c960 --- /dev/null +++ b/test/shape/get-settlements.ts @@ -0,0 +1,8 @@ +import { Types } from 'cafe-utility' +import { settlementShape } from './settlement' + +export const getSettlementsShape = { + totalReceived: Types.isIntegerString, + totalSent: Types.isIntegerString, + settlements: (x: any) => Types.enforceArrayShape(x, settlementShape), +} diff --git a/test/shape/get-stake.ts b/test/shape/get-stake.ts new file mode 100644 index 00000000..b4f3aa00 --- /dev/null +++ b/test/shape/get-stake.ts @@ -0,0 +1,5 @@ +import { Types } from 'cafe-utility' + +export const getStakeShape = { + stakedAmount: Types.isIntegerString, +} diff --git a/test/shape/get-stamps.ts b/test/shape/get-stamps.ts new file mode 100644 index 00000000..6752ebd7 --- /dev/null +++ b/test/shape/get-stamps.ts @@ -0,0 +1,6 @@ +import { Types } from 'cafe-utility' +import { stampShape } from './stamp' + +export const getStampsShape = { + stamps: (x: any) => Types.enforceArrayShape(x, stampShape), +} diff --git a/test/shape/get-status.ts b/test/shape/get-status.ts new file mode 100644 index 00000000..9fd30c2d --- /dev/null +++ b/test/shape/get-status.ts @@ -0,0 +1,15 @@ +import { Types } from 'cafe-utility' + +export const getStatusShape = { + peer: Types.isHexString, + beeMode: Types.isString, + proximity: Types.isNumber, + reserveSize: Types.isNumber, + reserveSizeWithinRadius: Types.isNumber, + pullsyncRate: Types.isNumber, + storageRadius: Types.isNumber, + connectedPeers: Types.isNumber, + neighborhoodSize: Types.isNumber, + batchCommitment: Types.isNumber, + isReachable: Types.isBoolean, +} diff --git a/test/shape/get-timesettlements.ts b/test/shape/get-timesettlements.ts new file mode 100644 index 00000000..20261a65 --- /dev/null +++ b/test/shape/get-timesettlements.ts @@ -0,0 +1,8 @@ +import { Types } from 'cafe-utility' +import { settlementShape } from './settlement' + +export const getTimesettlementsShape = { + totalReceived: Types.isIntegerString, + totalSent: Types.isIntegerString, + settlements: (x: any) => Types.enforceArrayShape(x, settlementShape), +} diff --git a/test/shape/get-topology.ts b/test/shape/get-topology.ts new file mode 100644 index 00000000..99322450 --- /dev/null +++ b/test/shape/get-topology.ts @@ -0,0 +1,16 @@ +import { Types } from 'cafe-utility' +import { topologyBinPropertyShape } from './topology-bin-property' +import { topologyBinsShape } from './topology-bins' + +export const getTopologyShape = { + baseAddr: Types.isHexString, + population: Types.isNumber, + connected: Types.isNumber, + timestamp: Types.isString, + nnLowWatermark: Types.isNumber, + depth: Types.isNumber, + reachability: Types.isString, + networkAvailability: Types.isString, + bins: (x: any) => Types.enforceObjectShape(x, topologyBinsShape), + lightNodes: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), +} diff --git a/test/shape/get-wallet.ts b/test/shape/get-wallet.ts new file mode 100644 index 00000000..f0ce342f --- /dev/null +++ b/test/shape/get-wallet.ts @@ -0,0 +1,9 @@ +import { Types } from 'cafe-utility' + +export const getWalletShape = { + bzzBalance: Types.isIntegerString, + nativeTokenBalance: Types.isIntegerString, + chainID: Types.isNumber, + chequebookContractAddress: Types.isHexString, + walletAddress: Types.isHexString, +} diff --git a/test/shape/get-welcome-message.ts b/test/shape/get-welcome-message.ts new file mode 100644 index 00000000..f5c9336c --- /dev/null +++ b/test/shape/get-welcome-message.ts @@ -0,0 +1,5 @@ +import { Types } from 'cafe-utility' + +export const getWelcomeMessageShape = { + welcomeMessage: Types.isString, +} diff --git a/test/shape/global-stamp.ts b/test/shape/global-stamp.ts new file mode 100644 index 00000000..1f78519d --- /dev/null +++ b/test/shape/global-stamp.ts @@ -0,0 +1,12 @@ +import { Types } from 'cafe-utility' + +export const globalStampShape = { + batchID: Types.isHexString, + value: Types.isIntegerString, + start: Types.isNumber, + depth: Types.isNumber, + bucketDepth: Types.isNumber, + immutable: Types.isBoolean, + batchTTL: Types.isNumber, + owner: Types.isHexString, +} diff --git a/test/shape/payment.ts b/test/shape/payment.ts new file mode 100644 index 00000000..73533fba --- /dev/null +++ b/test/shape/payment.ts @@ -0,0 +1,7 @@ +import { Types } from 'cafe-utility' + +export const paymentShape = { + beneficiary: Types.isHexString, + chequebook: Types.isHexString, + payout: Types.isIntegerString, +} diff --git a/test/shape/peer-accounting.ts b/test/shape/peer-accounting.ts new file mode 100644 index 00000000..a975dd57 --- /dev/null +++ b/test/shape/peer-accounting.ts @@ -0,0 +1,11 @@ +import { Types } from 'cafe-utility' + +export const peerAccountingShape = { + balance: Types.isIntegerString, + thresholdReceived: Types.isIntegerString, + thresholdGiven: Types.isIntegerString, + surplusBalance: Types.isIntegerString, + reservedBalance: Types.isIntegerString, + shadowReservedBalance: Types.isIntegerString, + ghostBalance: Types.isIntegerString, +} diff --git a/test/shape/peer-cheques.ts b/test/shape/peer-cheques.ts new file mode 100644 index 00000000..7f3c90bb --- /dev/null +++ b/test/shape/peer-cheques.ts @@ -0,0 +1,9 @@ +import { Types } from 'cafe-utility' +import { paymentShape } from './payment' + +export const peerChequesShape = { + peer: Types.isHexString, + lastreceived: (someObject: any) => + Types.isNullable((x: any) => Types.enforceObjectShape(x, paymentShape), someObject), + lastsent: (someObject: any) => Types.isNullable((x: any) => Types.enforceObjectShape(x, paymentShape), someObject), +} diff --git a/test/shape/peer-metrics.ts b/test/shape/peer-metrics.ts new file mode 100644 index 00000000..2d8deb57 --- /dev/null +++ b/test/shape/peer-metrics.ts @@ -0,0 +1,12 @@ +import { Types } from 'cafe-utility' + +export const peerMetricsShape = { + lastSeenTimestamp: Types.isNumber, + sessionConnectionRetry: Types.isNumber, + connectionTotalDuration: Types.isNumber, + sessionConnectionDuration: Types.isNumber, + sessionConnectionDirection: Types.isString, + latencyEWMA: Types.isNumber, + reachability: Types.isString, + healthy: Types.isBoolean, +} diff --git a/test/shape/peer-with-balance.ts b/test/shape/peer-with-balance.ts new file mode 100644 index 00000000..76ca1d68 --- /dev/null +++ b/test/shape/peer-with-balance.ts @@ -0,0 +1,8 @@ +import { Types } from 'cafe-utility' + +export const peerWithBalanceShape = { + peer: Types.isHexString, + balance: Types.isIntegerString, + thresholdreceived: (x: any) => Types.isNullable(Types.isIntegerString, x), + thresholdgiven: (x: any) => Types.isNullable(Types.isIntegerString, x), +} diff --git a/test/shape/peer-with-metrics.ts b/test/shape/peer-with-metrics.ts new file mode 100644 index 00000000..f7403a9c --- /dev/null +++ b/test/shape/peer-with-metrics.ts @@ -0,0 +1,7 @@ +import { Types } from 'cafe-utility' +import { peerMetricsShape } from './peer-metrics' + +export const peerWithMetricsShape = { + address: Types.isHexString, + metrics: (someObject: any) => Types.isNullable((x: any) => Types.enforceObjectShape(x, peerMetricsShape), someObject), +} diff --git a/test/shape/peer.ts b/test/shape/peer.ts new file mode 100644 index 00000000..2566b38b --- /dev/null +++ b/test/shape/peer.ts @@ -0,0 +1,6 @@ +import { Types } from 'cafe-utility' + +export const peerShape = { + address: Types.isHexString, + fullNode: Types.isBoolean, +} diff --git a/test/shape/settlement.ts b/test/shape/settlement.ts new file mode 100644 index 00000000..c6fcf17f --- /dev/null +++ b/test/shape/settlement.ts @@ -0,0 +1,7 @@ +import { Types } from 'cafe-utility' + +export const settlementShape = { + peer: Types.isHexString, + received: Types.isIntegerString, + sent: Types.isIntegerString, +} diff --git a/test/shape/shape.spec.ts b/test/shape/shape.spec.ts new file mode 100644 index 00000000..8d62042c --- /dev/null +++ b/test/shape/shape.spec.ts @@ -0,0 +1,57 @@ +import axios from 'axios' +import { Types } from 'cafe-utility' +import { getAddressesShape } from './get-addresses' +import { getBalancesShape } from './get-balances' +import { getBatchesShape } from './get-batches' +import { getChainstateShape } from './get-chainstate' +import { getChequebookAddressShape } from './get-chequebook-address' +import { getChequebookBalanceShape } from './get-chequebook-balance' +import { getChequebookChequeShape } from './get-chequebook-cheque' +import { getHealthShape } from './get-health' +import { getNodeShape } from './get-node' +import { getPeersShape } from './get-peers' +import { getReadinessShape } from './get-readiness' +import { getRedistributionstateShape } from './get-redistributionstate' +import { getReservestateShape } from './get-reservestate' +import { getSettlementsShape } from './get-settlements' +import { getStakeShape } from './get-stake' +import { getStampsShape } from './get-stamps' +import { getStatusShape } from './get-status' +import { getTimesettlementsShape } from './get-timesettlements' +import { getTopologyShape } from './get-topology' +import { getWalletShape } from './get-wallet' +import { getWelcomeMessageShape } from './get-welcome-message' + +test('GET /addresses', async () => { + await testGet('http://localhost:1635/addresses', getAddressesShape) + await testGet('http://localhost:1635/peers', getPeersShape) + await testGet('http://localhost:1635/topology', getTopologyShape) + await testGet('http://localhost:1635/welcome-message', getWelcomeMessageShape) + await testGet('http://localhost:1635/balances', getBalancesShape) + await testGet('http://localhost:1635/consumed', getBalancesShape) + await testGet('http://localhost:1635/chequebook/address', getChequebookAddressShape) + await testGet('http://localhost:1635/chequebook/balance', getChequebookBalanceShape) + await testGet('http://localhost:1635/chequebook/cheque', getChequebookChequeShape) + await testGet('http://localhost:1635/reservestate', getReservestateShape) + await testGet('http://localhost:1635/chainstate', getChainstateShape) + await testGet('http://localhost:1635/node', getNodeShape) + await testGet('http://localhost:1635/health', getHealthShape) + 0 && (await testGet('http://localhost:1635/readiness', getReadinessShape)) + await testGet('http://localhost:1635/settlements', getSettlementsShape) + await testGet('http://localhost:1635/timesettlements', getTimesettlementsShape) + 0 && (await testGet('http://localhost:1635/redistributionstate', getRedistributionstateShape)) + await testGet('http://localhost:1635/wallet', getWalletShape) + await testGet('http://localhost:1635/stamps', getStampsShape) + await testGet('http://localhost:1635/batches', getBatchesShape) + await testGet('http://localhost:1635/stake', getStakeShape) + await testGet('http://localhost:1635/status', getStatusShape) +}) + +async function testGet(url: string, shape: any) { + const response = await axios.get(url) + if (Array.isArray(response.data)) { + Types.enforceArrayShape(response.data, shape) + } else { + Types.enforceObjectShape(response.data, shape) + } +} diff --git a/test/shape/stamp.ts b/test/shape/stamp.ts new file mode 100644 index 00000000..824085b9 --- /dev/null +++ b/test/shape/stamp.ts @@ -0,0 +1,15 @@ +import { Types } from 'cafe-utility' + +export const stampShape = { + batchID: Types.isHexString, + utilization: Types.isNumber, + usable: Types.isBoolean, + label: Types.isString, + depth: Types.isNumber, + amount: Types.isIntegerString, + bucketDepth: Types.isNumber, + blockNumber: Types.isNumber, + immutableFlag: Types.isBoolean, + exists: Types.isBoolean, + batchTTL: Types.isNumber, +} diff --git a/test/shape/topology-bin-property.ts b/test/shape/topology-bin-property.ts new file mode 100644 index 00000000..75183298 --- /dev/null +++ b/test/shape/topology-bin-property.ts @@ -0,0 +1,11 @@ +import { Types } from 'cafe-utility' +import { peerWithMetricsShape } from './peer-with-metrics' + +export const topologyBinPropertyShape = { + population: Types.isNumber, + connected: Types.isNumber, + disconnectedPeers: (someArray: any) => + Types.isNullable((x: any) => Types.enforceArrayShape(x, peerWithMetricsShape), someArray), + connectedPeers: (someArray: any) => + Types.isNullable((x: any) => Types.enforceArrayShape(x, peerWithMetricsShape), someArray), +} diff --git a/test/shape/topology-bins.ts b/test/shape/topology-bins.ts new file mode 100644 index 00000000..6a6dba4f --- /dev/null +++ b/test/shape/topology-bins.ts @@ -0,0 +1,37 @@ +import { Types } from 'cafe-utility' +import { topologyBinPropertyShape } from './topology-bin-property' + +export const topologyBinsShape = { + bin_0: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_1: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_2: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_3: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_4: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_5: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_6: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_7: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_8: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_9: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_10: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_11: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_12: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_13: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_14: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_15: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_16: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_17: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_18: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_19: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_20: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_21: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_22: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_23: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_24: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_25: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_26: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_27: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_28: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_29: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_30: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), + bin_31: (x: any) => Types.enforceObjectShape(x, topologyBinPropertyShape), +} diff --git a/test/shape/types.ts b/test/shape/types.ts new file mode 100644 index 00000000..cac0a04a --- /dev/null +++ b/test/shape/types.ts @@ -0,0 +1,267 @@ +export interface GetChequebookAddress { + chequebookAddress: string +} + +export interface Payment { + beneficiary: string + chequebook: string + payout: string +} + +export interface PeerCheques { + peer: string + lastreceived?: Payment | null + lastsent?: Payment | null +} + +export interface GetStamps { + stamps: Stamp[] +} + +export interface Peer { + address: string + fullNode: boolean +} + +export interface GetStatus { + peer: string + beeMode: string + proximity: number + reserveSize: number + reserveSizeWithinRadius: number + pullsyncRate: number + storageRadius: number + connectedPeers: number + neighborhoodSize: number + batchCommitment: number + isReachable: boolean +} + +export interface GetSettlements { + totalReceived: string + totalSent: string + settlements: Settlement[] +} + +export interface TopologyBinProperty { + population: number + connected: number + disconnectedPeers: PeerWithMetrics[] + connectedPeers: PeerWithMetrics[] +} + +export interface GetChequebookBalance { + totalBalance: string + availableBalance: string +} + +export interface PeerAccounting { + balance: string + thresholdReceived: string + thresholdGiven: string + surplusBalance: string + reservedBalance: string + shadowReservedBalance: string + ghostBalance: string +} + +export interface GetChainstate { + chainTip: number + block: number + totalAmount: string + currentPrice: string +} + +export interface PeerWithMetrics { + address: string + metrics?: PeerMetrics | null +} + +export interface GetStake { + stakedAmount: string +} + +export interface GetWallet { + bzzBalance: string + nativeTokenBalance: string + chainID: number + chequebookContractAddress: string + walletAddress: string +} + +export interface GetBatches { + batches: GlobalStamp[] +} + +export interface Settlement { + peer: string + received: string + sent: string +} + +export interface GetHealth { + status: string + version: string + apiVersion: string +} + +export interface GlobalStamp { + batchID: string + value: string + start: number + depth: number + bucketDepth: number + immutable: boolean + batchTTL: number + owner: string +} + +export interface Stamp { + batchID: string + utilization: number + usable: boolean + label: string + depth: number + amount: string + bucketDepth: number + blockNumber: number + immutableFlag: boolean + exists: boolean + batchTTL: number +} + +export interface GetReservestate { + radius: number + storageRadius: number + commitment: number +} + +export interface GetPeers { + peers: Peer[] +} + +export interface GetTopology { + baseAddr: string + population: number + connected: number + timestamp: string + nnLowWatermark: number + depth: number + reachability: string + networkAvailability: string + bins: TopologyBins + lightNodes: TopologyBinProperty +} + +export interface GetReadiness { + code: number + message: string + reasons: string[] +} + +export interface GetChequebookCheque { + lastcheques: PeerCheques[] +} + +export interface PeerWithBalance { + peer: string + balance: string + thresholdreceived?: string | null + thresholdgiven?: string | null +} + +export interface WrappedAddress { + address: string +} + +export interface GetBalances { + balances: PeerWithBalance[] +} + +export interface GetRedistributionstate { + minimumGasFunds: string + hasSufficientFunds: boolean + isFrozen: boolean + isFullySynced: boolean + isHealthy: boolean + phase: string + round: number + lastWonRound: number + lastPlayedRound: number + lastFrozenRound: number + lastSelectedRound: number + lastSampleDuration: string + block: number + reward: string + fees: string +} + +export interface GetTimesettlements { + totalReceived: string + totalSent: string + settlements: Settlement[] +} + +export interface GetNode { + beeMode: string + chequebookEnabled: boolean + swapEnabled: boolean +} + +export interface PeerMetrics { + lastSeenTimestamp: number + sessionConnectionRetry: number + connectionTotalDuration: number + sessionConnectionDuration: number + sessionConnectionDirection: string + latencyEWMA: number + reachability: string + healthy: boolean +} + +export interface TopologyBins { + bin_0: TopologyBinProperty + bin_1: TopologyBinProperty + bin_2: TopologyBinProperty + bin_3: TopologyBinProperty + bin_4: TopologyBinProperty + bin_5: TopologyBinProperty + bin_6: TopologyBinProperty + bin_7: TopologyBinProperty + bin_8: TopologyBinProperty + bin_9: TopologyBinProperty + bin_10: TopologyBinProperty + bin_11: TopologyBinProperty + bin_12: TopologyBinProperty + bin_13: TopologyBinProperty + bin_14: TopologyBinProperty + bin_15: TopologyBinProperty + bin_16: TopologyBinProperty + bin_17: TopologyBinProperty + bin_18: TopologyBinProperty + bin_19: TopologyBinProperty + bin_20: TopologyBinProperty + bin_21: TopologyBinProperty + bin_22: TopologyBinProperty + bin_23: TopologyBinProperty + bin_24: TopologyBinProperty + bin_25: TopologyBinProperty + bin_26: TopologyBinProperty + bin_27: TopologyBinProperty + bin_28: TopologyBinProperty + bin_29: TopologyBinProperty + bin_30: TopologyBinProperty + bin_31: TopologyBinProperty +} + +export interface GetAddresses { + overlay: string + underlay: string[] + ethereum: string + publicKey: string + pssPublicKey: string +} + +export interface GetWelcomeMessage { + welcomeMessage: string +} diff --git a/test/shape/wrapped-address.ts b/test/shape/wrapped-address.ts new file mode 100644 index 00000000..899070b4 --- /dev/null +++ b/test/shape/wrapped-address.ts @@ -0,0 +1,5 @@ +import { Types } from 'cafe-utility' + +export const wrappedAddressShape = { + address: Types.isString, +} diff --git a/test/tests-setup.ts b/test/tests-setup.ts index bca50887..c7c86c61 100644 --- a/test/tests-setup.ts +++ b/test/tests-setup.ts @@ -30,18 +30,18 @@ export async function mochaGlobalSetup(): Promise { }) try { - const beeDebugRequestOptions: BeeRequestOptions = { - baseURL: process.env.BEE_DEBUG_API_URL || 'http://127.0.0.1:1635/', + const beeRequestOptions: BeeRequestOptions = { + baseURL: process.env.BEE_API_URL || 'http://127.0.0.1:1633/', timeout: false, } - const beeDebugPeerRequestOptions: BeeRequestOptions = { - baseURL: process.env.BEE_PEER_DEBUG_API_URL || 'http://127.0.0.1:11635/', + const beePeerRequestOptions: BeeRequestOptions = { + baseURL: process.env.BEE_PEER_API_URL || 'http://127.0.0.1:11633/', timeout: false, } if (process.env.BEE_POSTAGE) { try { - if (!(await getPostageBatch(beeDebugRequestOptions, process.env.BEE_POSTAGE as BatchId)).usable) { + if (!(await getPostageBatch(beeRequestOptions, process.env.BEE_POSTAGE as BatchId)).usable) { delete process.env.BEE_POSTAGE console.log('BEE_POSTAGE stamp was found but is not usable') } else { @@ -55,7 +55,7 @@ export async function mochaGlobalSetup(): Promise { if (process.env.BEE_PEER_POSTAGE) { try { - if (!(await getPostageBatch(beeDebugPeerRequestOptions, process.env.BEE_PEER_POSTAGE as BatchId)).usable) { + if (!(await getPostageBatch(beePeerRequestOptions, process.env.BEE_PEER_POSTAGE as BatchId)).usable) { delete process.env.BEE_PEER_POSTAGE console.log('BEE_PEER_POSTAGE stamp was found but is not usable') } else { @@ -73,11 +73,11 @@ export async function mochaGlobalSetup(): Promise { const stampsOrder: { requestOptions: BeeRequestOptions; env: string }[] = [] if (!process.env.BEE_POSTAGE) { - stampsOrder.push({ requestOptions: beeDebugRequestOptions, env: 'BEE_POSTAGE' }) + stampsOrder.push({ requestOptions: beeRequestOptions, env: 'BEE_POSTAGE' }) } if (!process.env.BEE_PEER_POSTAGE) { - stampsOrder.push({ requestOptions: beeDebugPeerRequestOptions, env: 'BEE_PEER_POSTAGE' }) + stampsOrder.push({ requestOptions: beePeerRequestOptions, env: 'BEE_PEER_POSTAGE' }) } const stamps = await Promise.all( diff --git a/test/unit/bee-debug-class.spec.ts b/test/unit/bee-debug-class.spec.ts index 92afc547..07e2291d 100644 --- a/test/unit/bee-debug-class.spec.ts +++ b/test/unit/bee-debug-class.spec.ts @@ -1,6 +1,6 @@ import { fail } from 'assert' import { expect } from 'chai' -import { BatchId, BeeArgumentError, BeeDebug, BeeRequestOptions, CashoutOptions, PostageBatchOptions } from '../../src' +import { BatchId, Bee, BeeArgumentError, BeeRequestOptions, CashoutOptions, PostageBatchOptions } from '../../src' import { testAddress, testBatchId } from '../utils' import { testAddressAssertions, @@ -10,11 +10,11 @@ import { testTransactionOptionsAssertions, } from './assertions' import { + MOCK_SERVER_URL, assertAllIsDone, cashoutLastChequeMock, createPostageBatchMock, depositTokensMock, - MOCK_SERVER_URL, withdrawTokensMock, } from './nock' @@ -23,12 +23,12 @@ const CASHOUT_RESPONSE = { transactionHash: TRANSACTION_HASH, } -describe('BeeDebug class', () => { +describe('Bee class debug modules', () => { function testUrl(url: unknown): void { it(`should not accept invalid url '${url}'`, () => { try { - new BeeDebug(url as string) - fail('BeeDebug constructor should have thrown error.') + new Bee(url as string) + fail('Bee constructor should have thrown error.') } catch (e) { if (e instanceof BeeArgumentError) { expect(e.value).to.eql(url) @@ -54,7 +54,7 @@ describe('BeeDebug class', () => { it('should set default headers and use them if specified', async function () { depositTokensMock('10', undefined, { 'X-Awesome-Header': '123' }).reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL, { headers: { 'X-Awesome-Header': '123' } }) + const bee = new Bee(MOCK_SERVER_URL, { headers: { 'X-Awesome-Header': '123' } }) await expect(bee.depositTokens('10')).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() @@ -62,13 +62,13 @@ describe('BeeDebug class', () => { describe('removePeer', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.removePeer(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.removePeer(input as string) }) @@ -76,13 +76,13 @@ describe('BeeDebug class', () => { describe('pingPeer', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.pingPeer(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.pingPeer(input as string) }) @@ -90,13 +90,13 @@ describe('BeeDebug class', () => { describe('getPeerBalance', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.getPeerBalance(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.getPeerBalance(input as string) }) @@ -104,13 +104,13 @@ describe('BeeDebug class', () => { describe('getPastDueConsumptionPeerBalance', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.getPastDueConsumptionPeerBalance(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.getPastDueConsumptionPeerBalance(input as string) }) @@ -118,13 +118,13 @@ describe('BeeDebug class', () => { describe('getLastChequesForPeer', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.getLastChequesForPeer(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.getLastChequesForPeer(input as string) }) @@ -132,13 +132,13 @@ describe('BeeDebug class', () => { describe('getLastCashoutAction', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.getLastCashoutAction(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.getLastCashoutAction(input as string) }) @@ -146,13 +146,13 @@ describe('BeeDebug class', () => { describe('getSettlements', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.getSettlements(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.getSettlements(input as string) }) @@ -160,13 +160,13 @@ describe('BeeDebug class', () => { describe('cashoutLastCheque', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.cashoutLastCheque(testAddress, undefined, input as BeeRequestOptions) }) testTransactionOptionsAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.cashoutLastCheque('', input as CashoutOptions) }) @@ -174,7 +174,7 @@ describe('BeeDebug class', () => { it('should not pass headers if no gas price is specified', async function () { cashoutLastChequeMock(testAddress).reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.cashoutLastCheque(testAddress)).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() }) @@ -182,7 +182,7 @@ describe('BeeDebug class', () => { it('should pass headers if gas price is specified', async function () { cashoutLastChequeMock(testAddress, '100000000000').reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.cashoutLastCheque(testAddress, { gasPrice: '100000000000' })).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() }) @@ -190,13 +190,13 @@ describe('BeeDebug class', () => { it('should pass headers if gas limit is specified', async function () { cashoutLastChequeMock(testAddress, undefined, '100000000000').reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.cashoutLastCheque(testAddress, { gasLimit: '100000000000' })).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() }) testAddressAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.cashoutLastCheque(input as string) }) @@ -209,7 +209,7 @@ describe('BeeDebug class', () => { } testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.withdrawTokens('1', '0', input as BeeRequestOptions) }) @@ -217,7 +217,7 @@ describe('BeeDebug class', () => { it('should not pass headers if no gas price is specified', async function () { withdrawTokensMock('10').reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.withdrawTokens('10')).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() }) @@ -225,13 +225,13 @@ describe('BeeDebug class', () => { it('should pass headers if gas price is specified', async function () { withdrawTokensMock('10', '100000000000').reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.withdrawTokens('10', '100000000000')).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() }) it('should throw error if passed wrong amount', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) // @ts-ignore: Input testing await expect(bee.withdrawTokens(true)).rejectedWith(TypeError) @@ -247,7 +247,7 @@ describe('BeeDebug class', () => { }) it('should throw error if passed wrong gas price input', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) // @ts-ignore: Input testing await expect(bee.withdrawTokens('1', true)).rejectedWith(TypeError) @@ -264,7 +264,7 @@ describe('BeeDebug class', () => { } testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.depositTokens('1', '0', input as BeeRequestOptions) }) @@ -272,7 +272,7 @@ describe('BeeDebug class', () => { it('should not pass headers if no gas price is specified', async function () { depositTokensMock('10').reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.depositTokens('10')).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() }) @@ -280,13 +280,13 @@ describe('BeeDebug class', () => { it('should pass headers if gas price is specified', async function () { depositTokensMock('10', '100000000000').reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.depositTokens('10', '100000000000')).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() }) it('should throw error if passed wrong amount', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) // @ts-ignore: Input testing await expect(bee.depositTokens(true)).rejectedWith(TypeError) @@ -302,7 +302,7 @@ describe('BeeDebug class', () => { }) it('should throw error if passed wrong gas price input', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) // @ts-ignore: Input testing await expect(bee.depositTokens('1', true)).rejectedWith(TypeError) @@ -314,13 +314,13 @@ describe('BeeDebug class', () => { describe('retrieveExtendedTag', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.retrieveExtendedTag(0, input as BeeRequestOptions) }) it('should throw exception for bad Tag', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) // @ts-ignore: Type testing await expect(bee.retrieveExtendedTag('')).rejectedWith(TypeError) @@ -348,7 +348,7 @@ describe('BeeDebug class', () => { describe('getStake', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.getStake(input as BeeRequestOptions) }) @@ -357,13 +357,13 @@ describe('BeeDebug class', () => { describe('depositStake', () => { const testStakingAmount = '100000000000000000' testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.depositStake(testStakingAmount, undefined, input as BeeRequestOptions) }) testTransactionOptionsAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.depositStake(testStakingAmount, undefined, input as BeeRequestOptions) }) @@ -376,13 +376,13 @@ describe('BeeDebug class', () => { } testPostageBatchOptionsAssertions(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.createPostageBatch('10', 17, input as PostageBatchOptions) }) testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.createPostageBatch('10', 17, undefined, input as BeeRequestOptions) }) @@ -390,7 +390,7 @@ describe('BeeDebug class', () => { it('should not pass headers if no gas price is specified', async function () { createPostageBatchMock('10', '17').reply(201, BATCH_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.createPostageBatch('10', 17, { waitForUsable: false })).eventually.to.eql(BATCH_ID) assertAllIsDone() }) @@ -398,7 +398,7 @@ describe('BeeDebug class', () => { it('should pass headers if gas price is specified', async function () { createPostageBatchMock('10', '17', '100').reply(201, BATCH_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.createPostageBatch('10', 17, { waitForUsable: false, gasPrice: '100' })).eventually.to.eql( BATCH_ID, ) @@ -406,7 +406,7 @@ describe('BeeDebug class', () => { }) it('should throw error if passed wrong immutable input', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) // @ts-ignore: Input testing await expect(bee.createPostageBatch('10', 17, { immutableFlag: 'asd' })).rejectedWith(TypeError) @@ -419,21 +419,21 @@ describe('BeeDebug class', () => { }) it('should throw error if too small depth', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.createPostageBatch('10', -1)).rejectedWith(BeeArgumentError) await expect(bee.createPostageBatch('10', 15)).rejectedWith(BeeArgumentError) }) it('should throw error if too small amount', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.createPostageBatch('-10', 17)).rejectedWith(BeeArgumentError) await expect(bee.createPostageBatch('0', 17)).rejectedWith(BeeArgumentError) }) it('should throw error if too big depth', async function () { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) await expect(bee.createPostageBatch('10', 256)).rejectedWith(BeeArgumentError) }) @@ -441,13 +441,13 @@ describe('BeeDebug class', () => { describe('getPostageBatch', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.getPostageBatch(testBatchId, input as BeeRequestOptions) }) testBatchIdAssertion(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.getPostageBatch(input as BatchId) }) @@ -455,13 +455,13 @@ describe('BeeDebug class', () => { describe('getPostageBatchBuckets', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { - const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) + const bee = new Bee(MOCK_SERVER_URL, beeOptions) return bee.getPostageBatchBuckets(testBatchId, input as BeeRequestOptions) }) testBatchIdAssertion(async (input: unknown) => { - const bee = new BeeDebug(MOCK_SERVER_URL) + const bee = new Bee(MOCK_SERVER_URL) return bee.getPostageBatchBuckets(input as BatchId) }) diff --git a/test/unit/chunk/cac.spec.ts b/test/unit/chunk/cac.spec.ts index 57589813..aee3f66b 100644 --- a/test/unit/chunk/cac.spec.ts +++ b/test/unit/chunk/cac.spec.ts @@ -1,9 +1,9 @@ -import { assertBytes } from '../../../src/utils/bytes' -import { makeContentAddressedChunk, assertValidChunkData } from '../../../src/chunk/cac' -import { serializeBytes } from '../../../src/chunk/serialize' -import { makeSpan } from '../../../src/chunk/span' -import { hexToBytes, bytesToHex } from '../../../src/utils/hex' +import { Binary } from 'cafe-utility' import { expect } from 'chai' +import { assertValidChunkData, makeContentAddressedChunk } from '../../../src/chunk/cac' +import { makeSpan } from '../../../src/chunk/span' +import { assertBytes } from '../../../src/utils/bytes' +import { bytesToHex, hexToBytes } from '../../../src/utils/hex' describe('cac', () => { const payload = new Uint8Array([1, 2, 3]) @@ -22,7 +22,7 @@ describe('cac', () => { const invalidAddress = hexToBytes('ca6357a08e317d15ec560fef34e4c45f8f19f01c372aa70f1da72bfa7f1a4335') assertBytes(invalidAddress, 32) - const data = serializeBytes(makeSpan(payload.length), payload) + const data = Binary.concatBytes(makeSpan(payload.length), payload) expect(() => assertValidChunkData(data, validAddress)).not.to.throw() expect(() => assertValidChunkData(data, invalidAddress)).to.throw() diff --git a/test/unit/chunk/serialize.spec.ts b/test/unit/chunk/serialize.spec.ts deleted file mode 100644 index 2cae2a56..00000000 --- a/test/unit/chunk/serialize.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { serializeBytes } from '../../../src/chunk/serialize' -import { expect } from 'chai' - -describe('serializeBytes', () => { - it('serializes', () => { - const a1 = new Uint8Array([1]) - const a2 = new Uint8Array([2]) - const a3 = new Uint8Array([3]) - const expectedResult = new Uint8Array([1, 2, 3]) - - const result = serializeBytes(a1, a2, a3) - - expect(result).to.eql(expectedResult) - }) - - it('serializes chunk data with span', () => { - const span = new Uint8Array(8) - const payload = new Uint8Array(4096) - const expectedResult = new Uint8Array(span.length + payload.length) - - const result = serializeBytes(span, payload) - - expect(result).to.eql(expectedResult) - }) -}) diff --git a/test/unit/utils/stream.spec.ts b/test/unit/utils/stream.spec.ts deleted file mode 100644 index 6947d739..00000000 --- a/test/unit/utils/stream.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Readable } from 'stream' -import { readableNodeToWeb, readableWebToNode } from '../../../src/utils/stream' -import { bytesEqual } from '../../../src/utils/bytes' -import { expect } from 'chai' - -async function getAllReadable(read: Readable): Promise { - const arr = [] - - for await (const readElement of read) { - arr.push(readElement) - } - - return arr -} - -describe('stream', () => { - it('should convert from nodejs readable to whatwg readablestream and back', async function () { - const input = [new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), new Uint8Array([7, 8, 9])] - const nodeJsReadable = Readable.from(input) - - const readableStream = readableNodeToWeb(nodeJsReadable) - const nodeJsRevertedReadable = readableWebToNode(readableStream, { highWaterMark: 1 }) - - const result = await getAllReadable(nodeJsRevertedReadable) - expect(result.length).to.eql(input.length) - - for (let i = 0; i < input.length; i++) { - expect(bytesEqual(result[i], input[i])).to.be.ok() - } - }) -}) diff --git a/test/unit/utils/uint64.spec.ts b/test/unit/utils/uint64.spec.ts deleted file mode 100644 index 723eb70b..00000000 --- a/test/unit/utils/uint64.spec.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { Bytes, makeBytes } from '../../../src/utils/bytes' -import { HexString, hexToBytes } from '../../../src/utils/hex' -import { readUint64BigEndian, writeUint64BigEndian, writeUint64LittleEndian } from '../../../src/utils/uint64' -import { expect } from 'chai' - -describe('uint64', () => { - describe('little endian', () => { - it('zero', () => { - const uint64 = writeUint64LittleEndian(0) - const zero = makeBytes(8) - - expect(uint64).to.eql(zero) - }) - - it('one', () => { - const uint64 = writeUint64LittleEndian(1) - const one = hexToBytes('0100000000000000' as HexString) - - expect(uint64).to.eql(one) - }) - - it('deadbeef', () => { - const uint64 = writeUint64LittleEndian(0xdeadbeef) - const deadbeef = hexToBytes('efbeadde00000000' as HexString) - - expect(uint64).to.eql(deadbeef) - }) - }) - - describe('big endian', () => { - describe('write', () => { - it('zero', () => { - const uint64 = writeUint64BigEndian(0) - const zero = makeBytes(8) - - expect(uint64).to.eql(zero) - }) - - it('one', () => { - const uint64 = writeUint64BigEndian(1) - const one = hexToBytes('0000000000000001' as HexString) - - expect(uint64).to.eql(one) - }) - - it('deadbeef', () => { - const uint64 = writeUint64BigEndian(0xdeadbeef) - const deadbeef = hexToBytes('00000000deadbeef' as HexString) - - expect(uint64).to.eql(deadbeef) - }) - }) - - describe('read', () => { - it('zero', () => { - const zero = makeBytes(8) - const value = readUint64BigEndian(zero) - - expect(value).to.eql(0) - }) - - it('one', () => { - const one = hexToBytes('0000000000000001' as HexString) as Bytes<8> - const value = readUint64BigEndian(one) - - expect(value).to.eql(1) - }) - - it('deadbeef', () => { - const deadbeef = hexToBytes('00000000deadbeef' as HexString) as Bytes<8> - const value = readUint64BigEndian(deadbeef) - - expect(value).to.eql(0xdeadbeef) - }) - }) - - describe('read and write', () => { - it('zero', () => { - const zero = makeBytes(8) - const num = readUint64BigEndian(zero) - const value = writeUint64BigEndian(num) - - expect(value).to.eql(zero) - }) - - it('one', () => { - const one = hexToBytes('0000000000000001' as HexString) as Bytes<8> - const num = readUint64BigEndian(one) - const value = writeUint64BigEndian(num) - - expect(value).to.eql(one) - }) - - it('deadbeef', () => { - const deadbeef = hexToBytes('00000000deadbeef' as HexString) as Bytes<8> - const num = readUint64BigEndian(deadbeef) - const value = writeUint64BigEndian(num) - - expect(value).to.eql(deadbeef) - }) - }) - }) -}) diff --git a/test/utils.ts b/test/utils.ts index c59dd85c..8000c3ca 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -1,20 +1,9 @@ import { System } from 'cafe-utility' import { Readable } from 'stream' -import { ReadableStream as ReadableStreamPolyfill } from 'web-streams-polyfill' -import { deleteChunkFromLocalStorage } from '../src/modules/debug/chunk' import * as stamps from '../src/modules/debug/stamps' -import type { - Address, - BatchId, - BeeGenericResponse, - BeeRequestOptions, - PlainBytesReference, - PostageBatch, - Reference, -} from '../src/types' -import { assertBytes } from '../src/utils/bytes' -import { bytesToHex, HexString } from '../src/utils/hex' +import type { Address, BatchId, BeeGenericResponse, BeeRequestOptions, PostageBatch, Reference } from '../src/types' +import { HexString } from '../src/utils/hex' declare global { // eslint-disable-next-line @typescript-eslint/no-namespace @@ -128,24 +117,6 @@ export function createRandomNodeReadable(totalSize: number, chunkSize = 1000): R return stream } -export function createReadableStream(iterable: Iterable): ReadableStream { - const iter = iterable[Symbol.iterator]() - - return new ReadableStreamPolyfill({ - async pull(controller) { - const result = iter.next() - - if (result.done) { - controller.close() - - return - } - - controller.enqueue(result.value) - }, - }) as ReadableStream -} - /** * Lehmer random number generator with seed (minstd_rand in C++11) * !!! Very fast but not well distributed pseudo-random function !!! @@ -202,14 +173,14 @@ export function beePeerKyOptions(): BeeRequestOptions { * There is semaphore mechanism that allows only creation of one batch across all the * parallel running tests that have to wait until it is created. */ -export function getPostageBatch(url = beeDebugUrl()): BatchId { +export function getPostageBatch(url = beeUrl()): BatchId { let stamp: BatchId switch (url) { - case beeDebugUrl(): + case beeUrl(): stamp = process.env.BEE_POSTAGE as BatchId break - case beePeerDebugUrl(): + case beePeerUrl(): stamp = process.env.BEE_PEER_POSTAGE as BatchId break default: @@ -223,50 +194,6 @@ export function getPostageBatch(url = beeDebugUrl()): BatchId { return stamp } -/** - * Returns a url for testing the Bee Debug API - */ -export function beeDebugUrl(): string { - return process.env.BEE_DEBUG_API_URL || 'http://127.0.0.1:1635' -} - -export function beeDebugKyOptions(): BeeRequestOptions { - return { baseURL: beeDebugUrl(), timeout: false } -} - -/** - * Returns a url for testing the Bee Debug API - */ -export function beePeerDebugUrl(): string { - return process.env.BEE_PEER_DEBUG_API_URL || 'http://127.0.0.1:11635' -} - -export function beePeerDebugKyOptions(): BeeRequestOptions { - return { baseURL: beePeerDebugUrl(), timeout: false } -} - -/** - * Try to delete a chunk from local storage, ignoring all errors - * - * @param address Swarm address of chunk - */ -export async function tryDeleteChunkFromLocalStorage(address: string | PlainBytesReference): Promise { - if (typeof address !== 'string') { - assertBytes(address, 32) - address = bytesToHex(address) - } - - try { - await deleteChunkFromLocalStorage(beeDebugKyOptions(), address) - } catch (e: any) { - // ignore not found errors - if (e?.response?.status === 404) { - return - } - throw e - } -} - /** * Formatting utility for displaying long strings like hexstrings. * @@ -296,7 +223,7 @@ export async function waitForBatchToBeUsable(batchId: string, pollingInterval = do { await System.sleepMillis(pollingInterval) - stamp = await stamps.getPostageBatch(beeDebugKyOptions(), batchId as BatchId) + stamp = await stamps.getPostageBatch(beeKyOptions(), batchId as BatchId) } while (!stamp.usable) }, ]) @@ -320,18 +247,18 @@ export async function getOrCreatePostageBatch( immutable?: boolean, ): Promise { // Non-usable stamps are ignored by Bee - const allUsableStamps = (await stamps.getAllPostageBatches(beeDebugKyOptions())).filter(stamp => stamp.usable) + const allUsableStamps = (await stamps.getAllPostageBatches(beeKyOptions())).filter(stamp => stamp.usable) if (allUsableStamps.length === 0) { const batchId = await stamps.createPostageBatch( - beeDebugKyOptions(), + beeKyOptions(), amount ?? DEFAULT_BATCH_AMOUNT, depth ?? DEFAULT_BATCH_DEPTH, ) await waitForBatchToBeUsable(batchId) - return stamps.getPostageBatch(beeDebugKyOptions(), batchId) + return stamps.getPostageBatch(beeKyOptions(), batchId) } // User does not want any specific batch, lets give him the first one @@ -364,14 +291,14 @@ export async function getOrCreatePostageBatch( // No stamp meeting the criteria was found ==> we need to create a new one const batchId = await stamps.createPostageBatch( - beeDebugKyOptions(), + beeKyOptions(), amount ?? DEFAULT_BATCH_AMOUNT, depth ?? DEFAULT_BATCH_DEPTH, ) await waitForBatchToBeUsable(batchId) - return stamps.getPostageBatch(beeDebugKyOptions(), batchId) + return stamps.getPostageBatch(beeKyOptions(), batchId) } export function makeTestTarget(target: string): string { diff --git a/webpack.config.ts b/webpack.config.ts index f49b0bdc..0afbd781 100644 --- a/webpack.config.ts +++ b/webpack.config.ts @@ -2,7 +2,6 @@ import Path from 'path' import TerserPlugin from 'terser-webpack-plugin' import { Configuration, DefinePlugin, WebpackPluginInstance } from 'webpack' -import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer' interface WebpackEnvParams { debug: boolean @@ -94,7 +93,7 @@ export default async (env?: Partial): Promise = if (nodeEnv == 'debug') { const config = { ...(await base(env)), - plugins: [new BundleAnalyzerPlugin()], + plugins: [], profile: true, }