πŸš€ Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more β†’
Socket
DemoInstallSign in
Socket

@ethersphere/bee-js

Package Overview
Dependencies
Maintainers
2
Versions
95
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ethersphere/bee-js

Javascript client for Bee

9.3.0
latest
Source
npm
Version published
Weekly downloads
908
-18.86%
Maintainers
2
Weekly downloads
Β 
Created
Source

Bee-JS

FOSSA Status standard-readme compliant js-standard-style

JavaScript SDK for the Swarm decentralised storage.

Supports Node.js 18+, Vite and Webpack.

Write your code in CJS, MJS or TypeScript.

Intended to be used with Bee version 2.5.0.

Quick start

Start a Swarm project using TypeScript:

npm init swarm-app@latest my-dapp node-ts

or using Vite and TypeScript:

npm init swarm-app@latest my-dapp vite-tsx

Supported types are node, node-esm, node-ts and vite-tsx. Replace my-dapp with your project name.

Install

npm install @ethersphere/bee-js

Import

CJS

const { Bee } = require('@ethersphere/bee-js')

MJS and TypeScript

import { Bee } from '@ethersphere/bee-js'

Script tag

Loading this module through a script tag will make the BeeJs object available in the global namespace.

<script src="https://unpkg.com/@ethersphere/bee-js/dist/index.browser.min.js"></script>

Overview

Type interfaces

NumberString is a branded type for marking strings that represent numbers. It interops with string and bigint types. Where NumberString is present, number is disallowed in order to avoid pitfalls with unsafe large values.

Byte primitives

All the classes below extend Bytes, therefor the following methods are available on all of them: toUint8Array, toHex, toBase64, toBase32, toUtf8, toJSON, static keccak256, static fromUtf8.

The toString method uses toHex.

Bytes and its subclasses may be constructed with new from Uint8Array or hex string.

Elliptic

NameDescriptionMethods
PrivateKey32 bytes private keypublicKey, sign
PublicKey64 bytes public keyaddress, toCompressedUint8Array, toCompressedHex
EthAddress20 bytes Ethereum addresstoChecksum
Signature65 bytes signaturerecoverPublicKey

Swarm

NameDescriptionMethods
Reference32/64 bytes reference (chunk, feed)toCid
Identifier32 bytes identifier (SOC, Feed)-
TransactionId32 bytes transaction ID-
FeedIndex8 bytes feed index (BE)static fromBigInt, toBigInt
Topic32 bytes topicstatic fromString
PeerAddress32 bytes peer address-
BatchId32 bytes batch ID-
Span8 bytes span (LE)static fromBigInt, toBigInt

Tokens

NameDescriptionMethods
DAIERC20 DAI token (18 digits)static fromDecimalString, static fromWei, toWeiString, toWeiBigInt, toDecimalString
BZZERC20 BZZ token (16 digits)static fromDecimalString, static fromPLUR, toPLURString, toPLURBigInt, toDecimalString

Swarm chunks

NameDescriptionCreation
ChunkSpan, max. 4096 bytes payload; address dervied from contentmakeContentAddressedChunk
SingleOwnerChunkIdentifier, signature, span, max. 4096 bytes payload; address derived from identifier and ownermakeSingleOwnerChunk

Swarm primitives

NameDescriptionMethods
MantarayNodeCompact trie with reference values and JSON metadataaddFork, removeFork, calculateSelfAddress, find, findClosest, collect, marshal, unmarshal, saveRecursively, loadRecursively
MerkleTreeStreaming BMT of chunksappend, finalize, static root

Swarm objects

NameDescriptionCreation
SOCWriterSingleOwnerChunk writerbee.makeSOCWriter
SOCReaderSingleOwnerChunk readerbee.makeSOCReader
FeedWriterFeed writerbee.makeFeedWriter
FeedReaderFeed readerbee.makeFeedReader

Bee API

  • βŒβŒβœ… - Full node only
  • βŒβœ…βœ… - Light node and full node
  • βœ…βœ…βœ… - Ultra-light node, light node and full node
JS CallBee EndpointBee Mode
uploadFilePOST /bzz πŸ”—βŒβœ…βœ…
uploadFilesFromDirectory Node.jsPOST /bzz πŸ”—βŒβœ…βœ…
uploadFilesPOST /bzz πŸ”—βŒβœ…βœ…
uploadCollectionPOST /bzz πŸ”—βŒβœ…βœ…
uploadDataPOST /bytes πŸ”—βŒβœ…βœ…
uploadChunkPOST /chunks πŸ”—βŒβœ…βœ…
streamDirectory Node.jsPOST /chunks πŸ”—βŒβœ…βœ…
streamFiles BrowserPOST /chunks πŸ”—βŒβœ…βœ…
SOCWriter.uploadPOST /soc/:owner/:identifier πŸ”—βŒβœ…βœ…
FeedReader.downloadGET /feeds/:owner/:topic πŸ”—βœ…βœ…βœ…
FeedWriter.updateFeedPOST /soc/:owner/:identifier πŸ”—βŒβœ…βœ…
downloadFileGET /bzz/:reference πŸ”—βœ…βœ…βœ…
downloadFileGET /bzz/:reference/:path πŸ”—βœ…βœ…βœ…
downloadReadableFileGET /bzz/:reference πŸ”—βœ…βœ…βœ…
downloadDataGET /bytes/:reference πŸ”—βœ…βœ…βœ…
downloadReadableDataGET /bytes/:reference πŸ”—βœ…βœ…βœ…
downloadChunkGET /chunks/:reference πŸ”—βœ…βœ…βœ…
createFeedManifestPOST /feeds/:owner/:topic πŸ”—βŒβœ…βœ…
isConnectedGET /βœ…βœ…βœ…
getHealthGET /health πŸ”—βœ…βœ…βœ…
getReadinessGET /readiness πŸ”—βœ…βœ…βœ…
getNodeInfoGET /node πŸ”—βœ…βœ…βœ…
getChainStateGET /chainstate πŸ”—βŒβœ…βœ…
getRedistributionStateGET /redistributionstate πŸ”—βŒβŒβœ…
getReserveStateGET /reservestate πŸ”—βŒβŒβœ…
getStatusGET /status πŸ”—βœ…βœ…βœ…
getWalletGET /wallet πŸ”—βŒβœ…βœ…
getTopologyGET /topology πŸ”—βœ…βœ…βœ…
getAddressesGET /addresses πŸ”—βœ…βœ…βœ…
getPeersGET /peers πŸ”—βœ…βœ…βœ…
getAllBalancesGET /balances πŸ”—βŒβœ…βœ…
getPeerBalanceGET /balances/:peer πŸ”—βŒβœ…βœ…
getPastDueConsumptionBalancesGET /consumed πŸ”—βŒβœ…βœ…
getPastDueConsumptionPeerBalanceGET /consumed/:peer πŸ”—βŒβœ…βœ…
getAllSettlementsGET /settlements πŸ”—βŒβœ…βœ…
getSettlementsGET /settlements/:peer πŸ”—βŒβœ…βœ…
getChequebookAddressGET /chequebook/address πŸ”—βŒβœ…βœ…
getChequebookBalanceGET /chequebook/balance πŸ”—βŒβœ…βœ…
getLastChequesGET /chequebook/cheque πŸ”—βŒβœ…βœ…
getLastChequesForPeerGET /chequebook/cheque/:peer πŸ”—βŒβœ…βœ…
getLastCashoutActionGET /chequebook/cashout/:peer πŸ”—βŒβœ…βœ…
cashoutLastChequePOST /chequebook/cashout/:peer πŸ”—βŒβœ…βœ…
depositTokensPOST /chequebook/deposit πŸ”—βŒβœ…βœ…
withdrawTokensPOST /chequebook/withdraw πŸ”—βŒβœ…βœ…
getAllPendingTransactionsGET /transactions πŸ”—βŒβœ…βœ…
getPendingTransactionGET /transactions/:id πŸ”—βŒβœ…βœ…
rebroadcastTransactionPOST /transactions/:id πŸ”—βŒβœ…βœ…
cancelTransactionDELETE /transactions/:id πŸ”—βŒβœ…βœ…
createTagPOST /tags πŸ”—βŒβœ…βœ…
retrieveTagGET /tags/:id πŸ”—βŒβœ…βœ…
getAllTagsGET /tags πŸ”—βŒβœ…βœ…
deleteTagDELETE /tags/:id πŸ”—βŒβœ…βœ…
updateTagPATCH /tags/:id πŸ”—βŒβœ…βœ…
pinPOST /pins/:reference πŸ”—βœ…βœ…βœ…
getAllPinsGET /pins πŸ”—βœ…βœ…βœ…
getPinGET /pins/:reference πŸ”—βœ…βœ…βœ…
isReferenceRetrievableGET /stewardship/:reference πŸ”—βœ…βœ…βœ…
reuploadPinnedDataPUT /stewardship/:reference πŸ”—βŒβœ…βœ…
unpinDELETE /pins/:reference πŸ”—βœ…βœ…βœ…
getGranteesGET /grantee/:reference πŸ”—βŒβœ…βœ…
createGranteesPOST /grantee πŸ”—βŒβœ…βœ…
patchGranteesPATCH /grantee/:reference πŸ”—βŒβœ…βœ…
pssSendPOST /pss/send/:topic/:target πŸ”—βŒβœ…βœ…
pssSubscribe WebsocketGET /pss/subscribe/:topic πŸ”—βŒβŒβœ…
pssReceiveGET /pss/subscribe/:topic πŸ”—βŒβŒβœ…
getAllPostageBatchGET /stamps πŸ”—βŒβœ…βœ…
getGlobalPostageBatchesGET /batches πŸ”—βŒβœ…βœ…
getPostageBatchGET /stamps/:batchId πŸ”—βŒβœ…βœ…
getPostageBatchBucketsGET /stamps/:batchId/buckets πŸ”—βŒβœ…βœ…
createPostageBatchPOST /stamps/:amount/:depth πŸ”—βŒβœ…βœ…
topUpBatchPATCH /stamps/topup/:batchId/:amount πŸ”—βŒβœ…βœ…
diluteBatchPATCH /stamps/dilute/:batchId/:depth πŸ”—βŒβœ…βœ…
createEnvelopePOST /envelope/:reference πŸ”—βŒβœ…βœ…
getStakeGET /stake πŸ”—βŒβŒβœ…
depositStakePOST /stake πŸ”—βŒβŒβœ…

Utils

General

  • getCollectionSize
  • getFolderSize

PSS

  • makeMaxTarget

Erasure Coding

  • approximateOverheadForRedundancyLevel
  • getRedundancyStat
  • getRedundancyStats

Stamps

  • getAmountForTtl
  • getDepthForCapacity
  • getStampCost
  • getStampEffectiveBytes
  • getStampMaximumCapacityBytes
  • getStampTtlSeconds
  • getStampUsage

Usage

Upload via Swarm Gateway

import { Bee, NULL_STAMP, SWARM_GATEWAY_URL } from '@ethersphere/bee-js'

main()

async function main() {
  const bee = new Bee(SWARM_GATEWAY_URL)
  const { reference } = await bee.uploadData(NULL_STAMP, 'Hello, World!')
  console.log(reference.toHex())
}

Create or select an existing postage batch

Swarm incentivizes nodes in the network to store content, therefor all uploads require a paid postage batch.

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.buyStorage(Size.fromGigabytes(1), Duration.fromDays(7))
  }
}

The following examples all assume an existing batchId.

Upload simple data (Browser + Node.js)

import { Bee } from '@ethersphere/bee-js'

const bee = new Bee('http://localhost:1633')

const uploadResult = await bee.uploadData(batchId, 'Bee is awesome!')
const data = await bee.downloadData(uploadResult.reference)

console.log(data.toUtf8()) // prints 'Bee is awesome!'

Upload data from a file input (React)

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)

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)

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)

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/')

Customize http/https agent and headers

const bee = new Bee('http://localhost:1633', {
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
  headers: {
    Authorization: 'Basic ' + Buffer.from('username:password').toString('base64'),
  },
})

Contribute

Stay up to date by joining the official Discord and by keeping an eye on the releases tab.

We are using Conventional Commits for our commit messages and pull requests, following the Semantic Versioning rules.

There are some ways you can make this module better:

  • Consult our open issues and take on one of them
  • Help our tests reach 100% coverage!
  • Join us in our Discord chat in the #develop-on-swarm channel if you have questions or want to give feedback

Setup

Install project dependencies:

npm install

Build the project:

npm run build

After making changes, link the package to your project by running npm link in the Bee-JS project root, and npm link @ethersphere/bee-js in your project root.

Test

Code coverage

Tests are currently run against a mainnet Bee nodes. This is temporary and this section will be revised in the future.

License

BSD-3-Clause

FOSSA Status

Keywords

bee

FAQs

Package last updated on 12 May 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts