Skip to main content

JavaScript client (StorageClient)

StorageClient is the reference client of the network, written in JavaScript. It is what the app, the command line and the publisher use. It encodes blobs, pays in IOTA, uploads the slivers to the storage nodes, certifies the blobs on IOTA and reads them back, checking every piece.

Not public yet

The client lives in the project repository, which is not public yet. This page documents it for reference. The same operations are available from the app with a wallet, and reads from the public aggregator.

It runs in Node.js 22 and in browsers: it imports nothing from Node.js, so a bundler can ship it to a page where a wallet signs. Its dependencies are the IOTA SDK (@iota/iota-sdk 1.16.0) and the encoding library of the network, compiled to WebAssembly.

Setup​

The client needs an IOTA client for the RPC and the IDs of the network's objects, which are in Contracts and IDs:

import { getFullnodeUrl, IotaClient } from '@iota/iota-sdk/client';
import { Ed25519Keypair } from '@iota/iota-sdk/keypairs/ed25519';
import { StorageChain } from './chain.mjs';
import { StorageClient } from './client.mjs';

const iota = new IotaClient({ url: 'https://api.testnet.iota.cafe' });
const network = new StorageChain(iota, {
packageId: '0x4d2c…55c3', // package iota_storage (the original one; upgrades are followed on their own)
system: '0x765f…241d',
staking: '0x6001…c743',
treasury: '0x476c…9d10',
});
const client = new StorageClient({ network });

const signer = Ed25519Keypair.fromSecretKey('iotaprivkey1…'); // the account that pays

The command line reads the same IDs from a JSON file (--network), and the app from its config.json.

The signer​

Every operation that writes takes a signer: the account that signs and pays the gas. It is any object with:

  • toIotaAddress(), the address; and either
  • signTransaction(bytes), as the key pairs of the IOTA SDK have, or
  • signTransactionBytes(bytes), which returns { bytes, signature }: what the app's wallet adapter does, so that a browser wallet signs. The client checks that the bytes signed are the ones it sent.

Before signing, the client simulates the transaction and checks that the balance covers the payment and the gas; if not, it fails with insufficientBalance without sending anything.

Store​

const stored = await client.store(bytes, { signer, epochs: 5, deletable: true });
console.log(stored.text, stored.objectId, stored.endEpoch, stored.cost);

store(bytes, options) encodes bytes (a Uint8Array), registers and pays for the blob in one transaction, uploads the metadata and the slivers to the storage nodes, collects their confirmations and certifies the blob in a second transaction.

OptionDefaultMeaning
signerThe account that pays and receives the Blob.
epochs1Epochs to store the blob, 1 to 53.
deletablefalseWhether the owner can delete it before it expires.
ownerthe signerAddress that receives the Blob object.
reuseStoragetrueUse a paid Storage of the wallet instead of buying space, when it is cheaper (see Concepts).
onStep(step, data)Called as it goes (below).

It returns:

FieldMeaning
blobId, textThe blob ID as a number and as text (the one the aggregator takes).
objectIdThe ID of the Blob object.
sizeSize of the data, in bytes.
epoch, certifiedEpoch, endEpochThe epoch when it was stored, the one in the certificate and the last paid epoch.
costWhat the contract charged for storage, in nanos of IOTA (gas not included).
reusedtrue if an unfinished registration of the same blob was reused instead of paying a new one.
reusedStorageThe ID of the Storage of the wallet it was stored on, or null.
addedEpochsEpochs bought to extend a reused registration or Storage.

Several blobs at once. storeMany([bytes, …], options) stores a list with the same two transactions for all of them: one registers and pays for all, the other certifies all. It returns { stored, result, gas, transactions }: a result per blob, the response of the last transaction, the gas spent and the number of transactions. With a wallet, that is two signatures however many blobs there are; the app publishes sites this way. Its finish option adds the commands of the caller (for example, writing a Site) to the last transaction.

What is reused. If the signer already has a Blob with the same blob ID that was registered but not certified (an earlier store that did not finish), it is reused and only the missing epochs are paid. If the signer has a paid Storage large enough, the blob is stored on it. The result and the steps say so.

Steps​

onStep(step, data) reports the progress; the app shows these steps on screen:

Stepdata
encoded{ blobId }
reused{ objectId, cost, endEpoch }: an unfinished registration is reused.
storage-reused{ storage, size, endEpoch, addedEpochs, cost }: stored on a paid Storage.
registered{ objectId, cost }: the first transaction went through.
node-failure{ node, error }: a node did not confirm (the store goes on with the others).
epoch-change{ epoch }: the epoch changed; confirmations are requested again.
confirmed{ weight, shards }: nodes holding weight shards confirmed.
certified{ objectId }: the second transaction went through.

With storeMany, data.index says which blob of the list the step is about.

Read​

const bytes = await client.read(stored.text); // Uint8Array
const size = await client.size(stored.text); // without downloading the slivers

read(blobId, { maxSize, onStep }) fetches the metadata of the blob from the storage nodes, checks it against the blob ID, downloads primary slivers until it has enough (34 of 100), checks each one against the metadata and decodes the blob. A sliver that does not match is discarded (onStep('invalid-sliver', { node, pair, error })) and another one is requested. With maxSize, a larger blob fails before downloading anything.

It throws a ReadError with an HTTP-like code: 404 when nodes holding a quorum of shards say they do not have the blob (expired, deleted or never stored), 413 when it is larger than maxSize, 503 when too many nodes did not answer.

readColumns(blobId, columns) reads only some columns of a blob (the secondary slivers that hold them). The aggregator uses it to serve one file of a quilt without reading the whole quilt.

Manage a Blob​

All of these take the signer that owns the object, sign one transaction and return when it is in a checkpoint.

MethodReturnsWhat it does
renew(objectId, epochs, { signer }){ objectId, endEpoch, cost }Pays epochs more. The blob must be certified and not expired, and cannot end more than 53 epochs after the current one.
transfer(objectId, address, { signer }){ objectId, owner }The Blob now belongs to address.
deleteBlob(objectId, { signer }){ objectId, storage }Deletes a deletable blob. storage is the ID of the Storage object left in the wallet, already paid.
burn(objectId, { signer }){ objectId }Destroys the object of an expired blob and recovers its storage deposit.
certify(objectId, { signer, bytes }){ objectId, epoch, … }Finishes a store that was registered but not certified. If the nodes already have the data, it only asks for their confirmations; with bytes, the data of the blob, it uploads what is missing first.
share([objectId, …], { signer })Map blob ID → SharedBlob IDWraps Blob objects in SharedBlob objects: anyone can renew them by paying, nobody can delete them.
renewShared(sharedId, epochs, { signer }){ objectId, endEpoch, cost }Renews a SharedBlob; the signer does not need to own anything.
execute(tx, { signer })effects, objects and eventsSigns and sends any Transaction, with the same checks and retries as the client's own.

blobs(owner) lists the Blob objects of an address, each as { id, owner, blobId, size, registeredEpoch, certifiedEpoch, deletable, endEpoch, storage } (certifiedEpoch is null while not certified). network.storagesOf(owner) lists its paid Storage objects.

Errors​

Errors meant for a user are UserErrors: an English message, plus a key and its values (amounts in nanos, sizes in bytes, IDs) so that an interface can write them in its own language, as the app does. The main keys:

keyWhen
insufficientBalance, noIotaThe balance does not cover the payment and the gas. Nothing is sent.
networkPausedThe network is paused until values.until.
wouldFail, transactionFailedThe simulation, or the chain, rejected the transaction.
transactionUnknownThe transaction was sent but its response did not arrive within a minute. values.digest lets you look it up before retrying.
noQuorumNot enough nodes confirmed (values.weight of values.shards shards). What was paid is reused next time.
nodeTimeout, nodeUnreachable, nodeResponseA node failed; values.node and, for a response, values.status and values.reason.
nodeNotWaitedA node had not confirmed when nodes holding a quorum of shards already had, and the store went on without it (see below). It is not an error of the store.
blobNotFound, blobNotOwned, blobCertified, blobExpired, blobNotCertified, blobAtMaxEpochs, invalidEpochs, otherDataChecks before signing: the object does not exist, is someone else's, is already certified, expired, is not certified yet, already lasts the maximum, the epochs are not 1 to 53, or bytes are not the data of that blob.
connectionThe RPC could not be reached.

Anything else is an internal error, with only its message.

Robustness​

  • Retries. A request that gets no answer is repeated a couple of times; a node that answers 503 with Retry-After, or 429, is asked again after waiting (never more than 5 seconds, whatever the node asks for; a read asks again at most twice); a node that does not see the registration yet (NOT_REGISTERED) is asked again for a while. Any other error is final for that node, and the store goes on with the others.
  • Deadlines. Each request has 10 seconds plus 1 second per 50 KB of what it sends or expects, and never accepts more bytes than the answer can have. read, readColumns and size take a signal (an AbortSignal) to give the whole read a deadline.
  • Slow nodes. A single node cannot hold a store or a read up. The metadata is asked of three nodes at a time, and of one more whenever one is slow. A sliver that is slow to arrive is asked for from another node meanwhile; a node that sends one that does not match is left out of the read. Once the nodes that confirmed a store hold a quorum of shards, the client waits for the others only half the time that took, plus half a second, and certifies: the nodes left out rebuild their part from the others. Each signature is checked with the key the node has in the committee of the epoch, the one IOTA checks the certificate with.
  • Epoch changes. If the epoch changes between registering and certifying, the client reads the new committee and asks for fresh confirmations. If the response of a transaction is lost, it looks the transaction up by its digest for a minute before failing.
  • TLS. In Node.js, the client only talks to a storage node whose TLS connection is made with the network key registered for that node on IOTA, whoever signed the certificate. In a browser it relies on the usual certificate checks. See TLS and the network key.
  • Memory. Slivers are streamed; a large upload is bounded by the uploadsAtOnce and keepEncoded options.

Sites from code​

The library sites.mjs (no Node.js dependencies either) publishes and manages sites on top of StorageClient: publishSite, renewSite, destroySite and SiteReader, which reads a Site and its resources. Before its first transaction, publishSite checks that the account can pay the whole publication: the storage and renewals (publishCost) plus an estimate of the gas of all its transactions (publishGas, which is most of the cost of an update with many files); if not, it fails with insufficientBalance without sending anything, so a site is never left half updated. names.mjs reads IOTA Names and builds the transactions that point a name to a site. The command line is a thin layer over them, and documents what they do.