Skip to content

Latest commit

Β 

History

701 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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.8.1.

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, therefore 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

Name Description Methods
PrivateKey 32 bytes private key publicKey, sign
PublicKey 64 bytes public key address, toCompressedUint8Array, toCompressedHex
EthAddress 20 bytes Ethereum address toChecksum
Signature 65 bytes signature recoverPublicKey

Swarm

Name Description Methods
Reference 32/64 bytes reference (chunk, feed) toCid
Identifier 32 bytes identifier (SOC, Feed) -
TransactionId 32 bytes transaction ID -
FeedIndex 8 bytes feed index (BE) static fromBigInt, toBigInt
Topic 32 bytes topic static fromString
PeerAddress 32 bytes peer address -
BatchId 32 bytes batch ID -
Span 8 bytes span (LE) static fromBigInt, toBigInt

Tokens

Name Description Methods
DAI ERC20 DAI token (18 digits) static fromDecimalString, static fromWei, toWeiString, toWeiBigInt, toDecimalString
BZZ ERC20 BZZ token (16 digits) static fromDecimalString, static fromPLUR, toPLURString, toPLURBigInt, toDecimalString

Swarm chunks

Name Description Creation
Chunk Span, max. 4096 bytes payload; address derived from content makeContentAddressedChunk
SingleOwnerChunk Identifier, signature, span, max. 4096 bytes payload; address derived from identifier and owner makeSingleOwnerChunk

Swarm primitives

Name Description Methods
MantarayNode Compact trie with reference values and JSON metadata addFork, removeFork, calculateSelfAddress, find, findClosest, collect, marshal, unmarshal, saveRecursively, loadRecursively
ChunkSplitter Streaming BMT chunk-tree builder append, finalize, static root
ChunkJoiner Reconstructs data from a chunk tree join, static collect

Swarm objects

Name Description Creation
SOCWriter SingleOwnerChunk writer bee.soc.makeWriter
SOCReader SingleOwnerChunk reader bee.soc.makeReader
FeedWriter Feed writer bee.feed.makeWriter
FeedReader Feed reader bee.feed.makeReader

Bee API

  • βŒβŒβœ… - Full node only
  • βŒβœ…βœ… - Light node and full node
  • βœ…βœ…βœ… - Ultra-light node, light node and full node
JS Call Bee Endpoint Bee Mode
file.upload POST /bzz πŸ”— βŒβœ…βœ…
collection.uploadFromDirectory Node.js POST /bzz πŸ”— βŒβœ…βœ…
collection.uploadFromFileList POST /bzz πŸ”— βŒβœ…βœ…
collection.upload POST /bzz πŸ”— βŒβœ…βœ…
data.upload POST /bytes πŸ”— βŒβœ…βœ…
chunk.upload POST /chunks πŸ”— βŒβœ…βœ…
collection.streamFromDirectory Node.js POST /chunks πŸ”— βŒβœ…βœ…
collection.stream Browser POST /chunks πŸ”— βŒβœ…βœ…
SOCWriter.upload POST /soc/:owner/:identifier πŸ”— βŒβœ…βœ…
FeedReader.download GET /feeds/:owner/:topic πŸ”— βœ…βœ…βœ…
FeedWriter.uploadReference POST /soc/:owner/:identifier πŸ”— βŒβœ…βœ…
file.download GET /bzz/:reference πŸ”— βœ…βœ…βœ…
file.download GET /bzz/:reference/:path πŸ”— βœ…βœ…βœ…
file.downloadReadable GET /bzz/:reference πŸ”— βœ…βœ…βœ…
data.download GET /bytes/:reference πŸ”— βœ…βœ…βœ…
data.downloadReadable GET /bytes/:reference πŸ”— βœ…βœ…βœ…
chunk.download GET /chunks/:reference πŸ”— βœ…βœ…βœ…
feed.createManifest POST /feeds/:owner/:topic πŸ”— βŒβœ…βœ…
connectivity.isConnected GET / βœ…βœ…βœ…
status.getHealth GET /health πŸ”— βœ…βœ…βœ…
status.getReadiness GET /readiness πŸ”— βœ…βœ…βœ…
status.getNodeInfo GET /node πŸ”— βœ…βœ…βœ…
status.getChainState GET /chainstate πŸ”— βŒβœ…βœ…
stake.getRedistributionState GET /redistributionstate πŸ”— βŒβŒβœ…
status.getReserveState GET /reservestate πŸ”— βŒβŒβœ…
status.get GET /status πŸ”— βœ…βœ…βœ…
wallet.getBalance GET /wallet πŸ”— βŒβœ…βœ…
connectivity.getTopology GET /topology πŸ”— βœ…βœ…βœ…
connectivity.getNodeAddresses GET /addresses πŸ”— βœ…βœ…βœ…
connectivity.getPeers GET /peers πŸ”— βœ…βœ…βœ…
balance.getAll GET /balances πŸ”— βŒβœ…βœ…
balance.getPeer GET /balances/:peer πŸ”— βŒβœ…βœ…
balance.getAllPastDueConsumption GET /consumed πŸ”— βŒβœ…βœ…
balance.getAllPastDueConsumptionForPeer GET /consumed/:peer πŸ”— βŒβœ…βœ…
settlement.getAll GET /settlements πŸ”— βŒβœ…βœ…
settlement.get GET /settlements/:peer πŸ”— βŒβœ…βœ…
chequebook.getAddress GET /chequebook/address πŸ”— βŒβœ…βœ…
chequebook.getBalance GET /chequebook/balance πŸ”— βŒβœ…βœ…
cheque.getAllLatest GET /chequebook/cheque πŸ”— βŒβœ…βœ…
cheque.getAllLatestForPeer GET /chequebook/cheque/:peer πŸ”— βŒβœ…βœ…
cheque.getLastCashoutAction GET /chequebook/cashout/:peer πŸ”— βŒβœ…βœ…
cheque.cashoutLast POST /chequebook/cashout/:peer πŸ”— βŒβœ…βœ…
chequebook.deposit POST /chequebook/deposit πŸ”— βŒβœ…βœ…
chequebook.withdraw POST /chequebook/withdraw πŸ”— βŒβœ…βœ…
transaction.getAll GET /transactions πŸ”— βŒβœ…βœ…
transaction.get GET /transactions/:id πŸ”— βŒβœ…βœ…
transaction.rebroadcast POST /transactions/:id πŸ”— βŒβœ…βœ…
transaction.cancel DELETE /transactions/:id πŸ”— βŒβœ…βœ…
tag.create POST /tags πŸ”— βŒβœ…βœ…
tag.get GET /tags/:id πŸ”— βŒβœ…βœ…
tag.getAll GET /tags πŸ”— βŒβœ…βœ…
tag.delete DELETE /tags/:id πŸ”— βŒβœ…βœ…
tag.update PATCH /tags/:id πŸ”— βŒβœ…βœ…
pin.add POST /pins/:reference πŸ”— βœ…βœ…βœ…
pin.getAll GET /pins πŸ”— βœ…βœ…βœ…
pin.get GET /pins/:reference πŸ”— βœ…βœ…βœ…
data.isRetrievable GET /stewardship/:reference πŸ”— βœ…βœ…βœ…
pin.reuploadData PUT /stewardship/:reference πŸ”— βŒβœ…βœ…
pin.remove DELETE /pins/:reference πŸ”— βœ…βœ…βœ…
grantee.get GET /grantee/:reference πŸ”— βŒβœ…βœ…
grantee.create POST /grantee πŸ”— βŒβœ…βœ…
grantee.patch PATCH /grantee/:reference πŸ”— βŒβœ…βœ…
messaging.pssSend POST /pss/send/:topic/:target πŸ”— βŒβœ…βœ…
messaging.pssSubscribe Websocket GET /pss/subscribe/:topic πŸ”— βŒβŒβœ…
messaging.pssReceive GET /pss/subscribe/:topic πŸ”— βŒβŒβœ…
stamp.getAll GET /stamps πŸ”— βŒβœ…βœ…
stamp.getAllGlobal GET /batches πŸ”— βŒβœ…βœ…
stamp.get GET /stamps/:batchId πŸ”— βŒβœ…βœ…
stamp.getBuckets GET /stamps/:batchId/buckets πŸ”— βŒβœ…βœ…
stamp.create POST /stamps/:amount/:depth πŸ”— βŒβœ…βœ…
stamp.topUp PATCH /stamps/topup/:batchId/:amount πŸ”— βŒβœ…βœ…
stamp.dilute PATCH /stamps/dilute/:batchId/:depth πŸ”— βŒβœ…βœ…
createEnvelope POST /envelope/:reference πŸ”— βŒβœ…βœ…
stake.get GET /stake πŸ”— βŒβŒβœ…
stake.deposit POST /stake πŸ”— βŒβŒβœ…

Utils

General

  • getCollectionSize
  • getFolderSize

PSS

  • makeMaxTarget

Erasure Coding

  • approximateOverheadForRedundancyLevel
  • getRedundancyStat
  • getRedundancyStats

Stamps

  • getAmountForDuration
  • getDepthForSize
  • getStampCost
  • getStampEffectiveBytes
  • getStampTheoreticalBytes
  • getStampDuration
  • 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.data.upload(NULL_STAMP, 'Hello, World!')
  console.log(reference.toHex())
}

Create or select an existing postage batch

Swarm incentivizes nodes in the network to store content, therefore 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.stamp.getAll()
  const usable = batches.find(x => x.usable)

  if (usable) {
    batchId = usable.batchID
  } else {
    batchId = await bee.storage.buy(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.data.upload(batchId, 'Bee is awesome!')
const data = await bee.data.download(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.file.upload(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.collection.uploadFromFileList(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.file.upload(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.collection.uploadFromDirectory(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 node. This is temporary and this section will be revised in the future.

License

BSD-3-Clause

FOSSA Status

About

Javascript client library for connecting to Bee decentralised storage

Topics

Resources

Code of conduct

Stars

67 stars

Watchers

16 watching

Forks

Releases

Packages

Used by

Contributors

Languages