Skip to Content
API Reference@parity/product-sdk-cloud-storageOverview

@parity/product-sdk-cloud-storage

Upload and retrieve content from the cloud (currently through the Polkadot Bulletin Chain).

Wraps @parity/bulletin-sdk (chunking, DAG-PB manifests, CID calculation, progress events) and adds:

  • Network presets via CloudStorageNetworks
  • Read helpers (CloudStorageClient.fetchBytes / CloudStorageClient.fetchJson)
  • Authorization pre-flight via checkAuthorization
npm install @parity/product-sdk-cloud-storage

Exports

Classes

NameSummary
AsyncBulletinClientAsync Bulletin client that submits transactions to the chain
AuthCallBuilderBuilder for authorization calls that may require sudo
BulletinErrorSDK error class
BulletinPreparerOffline data preparer for Bulletin Chain
CallBuilderBuilder for calls with CallOptions (waitFor + callback)
CID
CloudStorageAuthorizationErrorFailed to check authorization status for an account.
CloudStorageCidErrorInvalid CID format or version.
CloudStorageClientErgonomic entry point for Cloud Storage operations.
CloudStorageHostUnavailableErrorThe host preimage API is unavailable.
CloudStorageLookupInterruptedErrorThe host interrupted the preimage lookup.
CloudStorageLookupTimeoutErrorThe host preimage lookup timed out.
MockBulletinClientMock Bulletin client for testing
ProductCloudStorageErrorBase class for read-side errors raised by @parity/product-sdk-cloud-storage.
StoreBuilderBuilder for store operations with fluent API

Functions

NameSummary
authorizeAccount()Grant an account authorization to store data in Cloud Storage.
calculateCid()Create a CID for data with specified codec and hashing algorithm
checkAuthorization()Check whether an account is authorized to store data in Cloud Storage.
cidFromBytes()Parse CID from bytes
cidToBytes()Convert CID to bytes
cidToPreimageKey()Extract the 32-byte content hash digest from a CIDv1 and return it as a
convertCid()Convert CID to different codec while keeping the same hash
createLazySigner()Build a PolkadotSigner whose underlying signer is resolved on every call.
estimateAuthorization()Estimate authorization needed for storing data
executeQuery()Execute a query using a pre-resolved strategy.
getContentHash()Calculate content hash using the specified algorithm
hashToCid()Reconstruct a CIDv1 from a 0x-prefixed 32-byte hex hash.
parseCid()Parse CID from string
queryBytes()Fetch raw bytes for a CID via the host’s preimage lookup.
queryJson()Fetch and parse JSON for a CID via the host’s preimage lookup.
reassembleChunks()Reassemble chunks back into the original data
resolveClientConfig()Merge caller-supplied config with defaults, ignoring undefined values.
resolveQueryStrategy()Determine the query strategy for Cloud Storage retrieval.
validateChunkSize()
verifyStored()Verify that a CID is recorded in the cloud storage (bulletin chain’s Transactions storage)

Interfaces

NameSummary
AuthorizationStatus//TODO: Come back to this (code docs might need update)
AuthorizeAccountOptionsOptions for authorizeAccount.
BulletinClientInterfaceShared interface for Bulletin clients (real and mock).
BulletinTypedApiMinimal interface for the PAPI typed API.
ChainStoredEntryA single matched entry from TransactionStorage.Transactions.
ChunkA single chunk of data
ChunkDetailsDetails about chunks in a chunked upload
ChunkedStoreResultResult of a chunked storage operation
ChunkerConfigConfiguration for chunking large data
ClientConfigClient configuration
CloudStorageNetwork
DagManifestDAG-PB manifest representing a file composed of multiple chunks
MockClientConfigConfiguration for the mock Bulletin client
QueryOptionsOptions for CloudStorageClient.fetchBytes / CloudStorageClient.fetchJson.
QueryStrategyQuery strategy for Cloud Storage retrieval.
StoreOptionsOptions for storing data
StoreResultResult of a storage operation
TransactionReceiptTransaction receipt from a successful submission
VerifyStoredOptionsVerification options for verifyStored.

Type Aliases

NameSummary
ChunkProgressEventProgress event types for chunked uploads
CidCodecCID codecs supported by Cloud Storage.
CloudStorageApiTyped API for the Cloud Storage (re-export from upstream BulletinTypedApi).
CloudStorageEnvironmentNetwork keys with built-in presets in CloudStorageNetworks.
CreateCloudStorageClientOptionsOptions for CloudStorageClient.create.
HashAlgorithmHash algorithms supported by Cloud Storage.
MockOperationRecord of a mock operation performed
ProgressCallbackProgress callback type
ProgressEventCombined progress event types
SubmitFnFunction type for submitting raw transactions to the chain.
TransactionStatusEventTransaction status event types (mirrors PAPI’s signSubmitAndWatch events)
WaitForTransaction confirmation level

Enums

NameSummary
AuthorizationScopeAuthorization scope types (mirrors the pallet’s AuthorizationScope enum)
ChunkStatusChunk progress event types
ErrorCodeError codes for the Bulletin SDK.
TxStatusTransaction status event types

Variables

NameSummary
CidCodecCID codecs supported by Cloud Storage.
CloudStorageNetworksCloud Storage network presets.
DEFAULT_CHUNKER_CONFIGDefault chunker configuration
DEFAULT_CLIENT_CONFIGDefault client configuration values.
DEFAULT_STORE_OPTIONSDefault store options
HashAlgorithmHash algorithms supported by Cloud Storage.
MAX_CHUNK_SIZEMaximum chunk size allowed (2 MiB, Bitswap compatibility limit)
MAX_FILE_SIZEMaximum file size the SDK will chunk in a single operation (64 MiB).
WaitFor

Re-exports

Convenience re-exports from leaf packages. Click through for the canonical documentation.

NameKindSource package
Environmenttype@parity/product-sdk-chain-client

Classes

class AsyncBulletinClient

Async Bulletin client that submits transactions to the chain

This client is tightly coupled to PAPI (Polkadot API) for blockchain interaction. Users must provide a configured PAPI client with appropriate chain metadata.

Implements: BulletinClientInterface

Examples

import { createClient } from 'polkadot-api'; import { getWsProvider } from 'polkadot-api/ws'; import { AsyncBulletinClient } from '@parity/bulletin-sdk'; // User sets up PAPI client const wsProvider = getWsProvider('wss://bulletin-rpc.polkadot.io'); const client = createClient(wsProvider); const api = client.getTypedApi(bulletinDescriptor); // Create SDK client const bulletinClient = new AsyncBulletinClient(api, signer, papiClient.submit); // Store data const result = await bulletinClient.store(data).send();

Constructors

constructor

Create a new async client with PAPI client and signer

The PAPI client must be configured with the correct chain metadata for your Bulletin Chain node.

new AsyncBulletinClient(api: BulletinTypedApi, signer: PolkadotSigner, submit: SubmitFn, config?: Partial<ClientConfig>, onDestroy?: () => void | Promise<void>): AsyncBulletinClient
Parameters
  • api: Configured PAPI TypedApi instance
  • signer: Polkadot signer for transaction signing
  • submit: Raw transaction submit function (pass papiClient.submit)
  • config: Optional client configuration
  • onDestroy: Optional teardown callback. When provided, destroy() awaits it so callers (e.g. wrappers that own the underlying PolkadotClient) can route cleanup through this client.

Properties

api
propertyBulletinTypedApi

PAPI client for blockchain interaction

config
propertyRequired<ClientConfig>

Client configuration

signer
propertyPolkadotSigner

Signer for transaction signing

submit
propertySubmitFn

Submit function for broadcasting raw transactions (from PolkadotClient.submit)

Methods

authorizeAccount

Authorize an account to store data

authorizeAccount(who: string, transactions: number, bytes: bigint): AuthCallBuilder
Parameters
  • who: Account address to authorize
  • transactions: Number of transactions to authorize
  • bytes: Maximum bytes to authorize
authorizePreimage

Authorize a preimage (by content hash) to be stored

authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuilder
Parameters
  • contentHash: Blake2b-256 hash of the content to authorize
  • maxSize: Maximum size in bytes for the content
destroy

Release resources held on behalf of this client.

Invokes the optional onDestroy callback supplied at construction time. Without one, this is a no-op — the SDK itself holds no long-lived resources, so callers that own the underlying PolkadotClient (or other connection) can either tear it down themselves or pass onDestroy to route teardown through here.

destroy(): Promise<void>
estimateAuthorization

Estimate authorization needed for storing data

estimateAuthorization(dataSize: number): { bytes: number; transactions: number }
refreshAccountAuthorization

Refresh an account authorization (extends expiry)

Requires Authorizer origin on-chain.

refreshAccountAuthorization(who: string): AuthCallBuilder
Parameters
  • who: Account address to refresh authorization for
refreshPreimageAuthorization

Refresh a preimage authorization (extends expiry)

Requires Authorizer origin on-chain.

refreshPreimageAuthorization(contentHash: Uint8Array): AuthCallBuilder
Parameters
  • contentHash: Blake2b-256 hash of the authorized content
removeExpiredAccountAuthorization

Remove an expired account authorization

Can be called by anyone (no special origin required).

removeExpiredAccountAuthorization(who: string): CallBuilder
Parameters
  • who: Account address with expired authorization
removeExpiredPreimageAuthorization

Remove an expired preimage authorization

Can be called by anyone (no special origin required).

removeExpiredPreimageAuthorization(contentHash: Uint8Array): CallBuilder
Parameters
  • contentHash: Blake2b-256 hash of the expired authorization
renew

Renew/extend retention period for stored data

renew(block: number, index: number): CallBuilder
Parameters
  • block: Block number where the original storage transaction was included
  • index: Extrinsic index within the block
store

Store data on Bulletin Chain using builder pattern

Returns a builder that allows fluent configuration of store options.

store(data: Uint8Array): StoreBuilder
Parameters
  • data: Data to store as Uint8Array
Examples
const result = await client .store(new TextEncoder().encode('Hello, Bulletin!')) .withCodec(CidCodec.DagPb) .withHashAlgorithm('blake2b-256') .withCallback((event) => console.log('Progress:', event)) .send();
storeWithOptions

Store data with custom options (internal, used by builder)

Note: This method is public for use by the builder but users should prefer the builder pattern via store().

Automatically chunks data if it exceeds the configured threshold.

storeWithOptions(data: Uint8Array, options?: StoreOptions, progressCallback?: ProgressCallback, chunkerConfig?: Partial<ChunkerConfig>): Promise<StoreResult>
storeWithPreimageAuth

Store preimage-authorized content as an unsigned (bare) transaction.

Use this for content that has been pre-authorized via authorizePreimage(). The transaction is encoded as a bare (unsigned) extrinsic and submitted via the client’s submit function (from PolkadotClient.submit).

storeWithPreimageAuth(data: Uint8Array, options?: StoreOptions): Promise<StoreResult>
Parameters
  • data: The preauthorized content to store
  • options: Store options (codec, hashing algorithm, etc.)
Examples
import { blake2b256 } from '@polkadot-labs/hdkd-helpers'; // First, authorize the content hash (requires sudo) const data = new TextEncoder().encode('Hello, Bulletin!'); const hash = blake2b256(data); await sudoClient.authorizePreimage(hash, BigInt(data.length)); // Anyone can now submit without fees const result = await client.store(data).sendUnsigned();

class AuthCallBuilder

Builder for authorization calls that may require sudo

Used by: authorizeAccount, authorizePreimage, refreshAccountAuthorization, refreshPreimageAuthorization

Examples

const receipt = await client .authorizeAccount(who, transactions, bytes) .withSudo() .withCallback((event) => console.log(event)) .send();

Constructors

constructor
new AuthCallBuilder(executor: (options: AuthCallOptions) => Promise<TransactionReceipt>): AuthCallBuilder

Methods

send

Submit the transaction

send(): Promise<TransactionReceipt>
withCallback

Set progress callback

withCallback(callback: ProgressCallback): this
withSudo

Wrap the call in Sudo

withSudo(): this
withWaitFor

Set what to wait for before returning

withWaitFor(waitFor: WaitFor): this

class BulletinError

SDK error class

Extends: Error

Constructors

constructor
new BulletinError(message: string, code: ErrorCode, cause?: unknown): BulletinError

Properties

cause
propertyreadonlyoptionalunknown
code
propertyreadonlyErrorCode

Accessors

recoveryHint
accessorstring

An actionable recovery suggestion for this error.

retryable
accessorboolean

Whether this error is likely transient and retrying may succeed.

class BulletinPreparer

Offline data preparer for Bulletin Chain

Handles CID calculation, chunking, DAG-PB manifest creation, and authorization estimation without any chain interaction. Used internally by AsyncBulletinClient and MockBulletinClient.

Constructors

constructor
new BulletinPreparer(config?: ClientConfig): BulletinPreparer

Methods

estimateAuthorization

Estimate authorization needed for storing data

Returns (num_transactions, total_bytes) needed for authorization

estimateAuthorization(dataSize: number): { bytes: number; transactions: number }
prepareStore

Prepare a simple store operation (data < 2 MiB)

Returns the data and its CID. Use PAPI to submit to TransactionStorage.store

prepareStore(data: Uint8Array, options?: StoreOptions): Promise<{ cid: CID; data: Uint8Array }>
prepareStoreChunked

Prepare a chunked store operation for large files

This chunks the data, calculates CIDs, and optionally creates a DAG-PB manifest. Returns chunk data and manifest that can be submitted via PAPI.

prepareStoreChunked(data: Uint8Array, config?: Partial<ChunkerConfig>, options?: StoreOptions): Promise<{ chunks: Chunk[]; manifest?: { cid: CID; data: Uint8Array } }>

class CallBuilder

Builder for calls with CallOptions (waitFor + callback)

Used by: renew, removeExpiredAccountAuthorization, removeExpiredPreimageAuthorization

Examples

const receipt = await client .renew(blockNumber, index) .withWaitFor('finalized') .withCallback((event) => console.log(event)) .send();

Constructors

constructor
new CallBuilder(executor: (options: CallOptions) => Promise<TransactionReceipt>): CallBuilder

Methods

send

Submit the transaction

send(): Promise<TransactionReceipt>
withCallback

Set progress callback

withCallback(callback: ProgressCallback): this
withWaitFor

Set what to wait for before returning

withWaitFor(waitFor: WaitFor): this

class CID

Implements: Link<Data, Format, Alg, Version>

Constructors

constructor
new CID(version: Version, code: Format, multihash: MultihashDigest<Alg>, bytes: Uint8Array): CID<Data, Format, Alg, Version>
Parameters

Properties

[toStringTag]
propertyreadonly"CID"
/
propertyreadonlyUint8Array
bytes
propertyreadonlyUint8Array
code
propertyreadonlyFormat
multihash
propertyreadonlyMultihashDigest<Alg>
version
propertyreadonlyVersion

Accessors

asCID
accessorthis

Signalling cid.asCID === cid has been replaced with cid['/'] === cid.bytes please either use CID.asCID(cid) or switch to new signalling mechanism

byteLength
accessornumber
byteOffset
accessornumber

Methods

equals
equals(other: unknown): other is CID<Data, Format, Alg, Version>
link(): this
toJSON
toJSON(): LinkJSON<CID<Data, Format, Alg, Version>>
toString
toString(base?: MultibaseEncoder<string>): string
toV0
toV0(): CID<Data, 112, 18, 0>
toV1
toV1(): CID<Data, Format, Alg, 1>
asCID

Takes any input value and returns a CID instance if it was a CID otherwise returns null. If value is instanceof CID it will return value back. If value is not instance of this CID class, but is compatible CID it will return new instance of this CID class. Otherwise returns null.

This allows two different incompatible versions of CID library to co-exist and interop as long as binary interface is compatible.

asCID(input: U | Link<Data, Format, Alg, Version>): CID<Data, Format, Alg, Version> | null
create
create(version: Version, code: Format, digest: MultihashDigest<Alg>): CID<Data, Format, Alg, Version>
Parameters
createV0

Simplified version of create for CIDv0.

createV0(digest: MultihashDigest<18>): CID<T, 112, 18, 0>
createV1

Simplified version of create for CIDv1.

createV1(code: Code, digest: MultihashDigest<Alg>): CID<Data, Code, Alg, 1>
Parameters
  • code: Content encoding format code.
  • digest: Multihash of the content.
decode

Decoded a CID from its binary representation. The byte array must contain only the CID with no additional bytes.

An error will be thrown if the bytes provided do not contain a valid binary representation of a CID.

decode(bytes: ByteView<Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version>
decodeFirst

Decoded a CID from its binary representation at the beginning of a byte array.

Returns an array with the first element containing the CID and the second element containing the remainder of the original byte array. The remainder will be a zero-length byte array if the provided bytes only contained a binary CID representation.

decodeFirst(bytes: ByteView<Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array<ArrayBufferLike>]
equals
equals(self: Link<Data, Format, Alg, Version>, other: unknown): other is CID<unknown, number, number, Version>
inspectBytes

Inspect the initial bytes of a CID to determine its properties.

Involves decoding up to 4 varints. Typically this will require only 4 to 6 bytes but for larger multicodec code values and larger multihash digest lengths these varints can be quite large. It is recommended that at least 10 bytes be made available in the initialBytes argument for a complete inspection.

inspectBytes(initialBytes: ByteView<Link<T, C, A, V>>): { codec: C; digestSize: number; multihashCode: A; multihashSize: number; size: number; version: V }
parse

Takes cid in a string representation and creates an instance. If base decoder is not provided will use a default from the configuration. It will throw an error if encoding of the CID is not compatible with supplied (or a default decoder).

parse(source: ToString<Link<Data, Code, Alg, Version>, Prefix>, base?: MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version>

class CloudStorageAuthorizationError

Failed to check authorization status for an account.

Wraps RPC or query errors that occur when checking if an account is authorized to store data in Cloud Storage.

Extends: ProductCloudStorageError

Constructors

constructor
new CloudStorageAuthorizationError(address: string, cause?: unknown): CloudStorageAuthorizationError

Properties

address
propertyreadonlystring

The address that was being checked.

class CloudStorageCidError

Invalid CID format or version.

Extends: ProductCloudStorageError

Constructors

constructor
new CloudStorageCidError(message: string, cid?: string): CloudStorageCidError

Properties

cid
propertyreadonlyoptionalstring

The invalid CID string, if available.

class CloudStorageClient

Ergonomic entry point for Cloud Storage operations.

Wraps the upstream @parity/bulletin-sdk client (which handles chunking, DAG-PB manifests, CID calculation, and progress events) and adds:

  • Network presets via CloudStorageClient.create and CloudStorageNetworks.
  • Read helpers (fetchBytes, fetchJson) routed through the host’s preimage subscription — upstream is upload-only and the SDK is container-only by design (no public-gateway fetches).
  • Pre-flight authorization check (checkAuthorization) for friendlier UX before submitting a store.

For uploads, mirror upstream’s fluent builders:

const client = await CloudStorageClient.create({ environment: "paseo", signer }); const result = await client.store(data).send();

For chunked uploads with progress:

const result = await client .store(largeFile) .withChunkSize(1 << 20) .withCallback((evt) => console.log(evt)) .send();

Properties

api
propertyreadonlyBulletinTypedApi

Typed CloudStorage API.

inner
propertyreadonlyAsyncBulletinClient

Underlying upstream client — exposed for power users.

Methods

authorizeAccount

Authorize an account to store data on the chain (sudo required on most networks).

authorizeAccount(who: string, transactions: number, bytes: bigint): AuthCallBuilder
authorizePreimage

Authorize content storage by hash (anyone can store; no fees).

authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuilder
checkAuthorization

Pre-flight: check whether address can store via Cloud Storage.

checkAuthorization(address: string): Promise<AuthorizationStatus>
destroy

Tear down the underlying connection.

destroy(): Promise<void>
estimateAuthorization

Estimate the authorization (transactions + bytes) needed for dataSize.

estimateAuthorization(dataSize: number): { bytes: number; transactions: number }
fetchBytes

Fetch raw bytes for a CID via the host’s preimage lookup.

Container-only — outside a Polkadot Browser / Desktop host this throws CloudStorageHostUnavailableError. The chain stores content metadata (content_hash, size, codec) but the bytes themselves are surfaced through the host’s preimage subscription.

Use verifyStored if you only need to confirm a CID was recorded on-chain (no byte fetch).

fetchBytes(cid: string, options?: QueryOptions): Promise<Uint8Array<ArrayBufferLike>>
fetchJson

Fetch and parse JSON for a CID.

fetchJson(cid: string, options?: QueryOptions): Promise<T>
renew

Renew a stored transaction by block + index.

renew(block: number, index: number): CallBuilder
store

Build a store transaction. See upstream StoreBuilder for chained options.

store(data: Uint8Array): StoreBuilder
verifyStored

Verify that a CID was recorded on-chain at the given block.

Common pattern: pass blockNumber (and optionally extrinsicIndex) from a store(...).send() receipt to confirm the upload landed. See verifyStored for details.

verifyStored(cid: string, options: VerifyStoredOptions): Promise<ChainStoredEntry | null>
create

Create a client from an environment shorthand or an explicit network.

Environment form uses our getChainAPI(env) to resolve the typed API. Explicit form skips the environment lookup and lets you pass any genesis/descriptor combo.

create(options: CreateCloudStorageClientOptions): Promise<CloudStorageClient>
Examples
// Shorthand const client = await CloudStorageClient.create({ environment: "paseo", signer }); // Explicit (custom network) const client = await CloudStorageClient.create({ ...CloudStorageNetworks.paseo, signer, config: { defaultChunkSize: 1 << 20 }, });
from

Construct from a pre-built AsyncBulletinClient and PAPI typed API.

Use this when you already own the connection lifecycle (BYOD setups, tests). The caller is responsible for calling papiClient.destroy() — this client’s destroy only tears down the upstream’s onDestroy hook.

from(inner: AsyncBulletinClient, api: BulletinTypedApi): CloudStorageClient

class CloudStorageHostUnavailableError

The host preimage API is unavailable.

Thrown when cloud storage operations require the host container but it’s not available. This typically means the SDK is running outside Polkadot Browser / Desktop. The Cloud Storage SDK is container-only by design — see the README for the rationale.

Extends: ProductCloudStorageError

Constructors

constructor
new CloudStorageHostUnavailableError(operation: "upload" | "query"): CloudStorageHostUnavailableError

class CloudStorageLookupInterruptedError

The host interrupted the preimage lookup.

The host terminated the lookup subscription, typically after repeated failures or when the host determines the content is unavailable.

Extends: ProductCloudStorageError

Constructors

constructor
new CloudStorageLookupInterruptedError(cid: string): CloudStorageLookupInterruptedError

Properties

cid
propertyreadonlystring

The CID that was being looked up.

class CloudStorageLookupTimeoutError

The host preimage lookup timed out.

The host was unable to retrieve the requested content within the timeout period. The content may still become available later.

Extends: ProductCloudStorageError

Constructors

constructor
new CloudStorageLookupTimeoutError(cid: string, timeoutMs: number): CloudStorageLookupTimeoutError

Properties

cid
propertyreadonlystring

The CID that was being looked up.

timeoutMs
propertyreadonlynumber

The timeout duration in milliseconds.

class MockBulletinClient

Mock Bulletin client for testing

This client simulates blockchain operations without requiring a running node. It calculates CIDs correctly and tracks operations but doesn’t actually submit transactions to a chain.

Implements: BulletinClientInterface

Examples

import { MockBulletinClient } from '@parity/bulletin-sdk'; // Create mock client const client = new MockBulletinClient(); // Store data (no blockchain required) const result = await client.store(data).send(); console.log('Mock CID:', result.cid.toString()); // Check what operations were performed const ops = client.getOperations(); expect(ops).toHaveLength(1);

Constructors

constructor

Create a new mock client with optional configuration

new MockBulletinClient(config?: Partial<MockClientConfig>): MockBulletinClient

Properties

config
propertyRequired<ClientConfig> & { simulateAuthFailure: boolean; simulateInsufficientAuth: boolean; simulateStorageFailure: boolean }

Client configuration

Methods

authorizeAccount
authorizeAccount(who: string, transactions: number, bytes: bigint): AuthCallBuilder
authorizePreimage
authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuilder
clearOperations

Clear recorded operations

clearOperations(): void
destroy

No-op for the mock client — present to satisfy BulletinClientInterface.

destroy(): Promise<void>
estimateAuthorization

Estimate authorization needed for storing data

estimateAuthorization(dataSize: number): { bytes: number; transactions: number }
getOperations

Get all operations performed by this client

getOperations(): MockOperation[]
refreshAccountAuthorization
refreshAccountAuthorization(who: string): AuthCallBuilder
refreshPreimageAuthorization
refreshPreimageAuthorization(contentHash: Uint8Array): AuthCallBuilder
removeExpiredAccountAuthorization
removeExpiredAccountAuthorization(who: string): CallBuilder
removeExpiredPreimageAuthorization
removeExpiredPreimageAuthorization(contentHash: Uint8Array): CallBuilder
renew
renew(block: number, index: number): CallBuilder
store

Store data using builder pattern

store(data: Uint8Array): StoreBuilder
Parameters
  • data: Data to store as Uint8Array
storeWithOptions

Store data with custom options (internal, used by builder)

storeWithOptions(data: Uint8Array, options?: StoreOptions, _progressCallback?: ProgressCallback, chunkerConfig?: Partial<ChunkerConfig>): Promise<StoreResult>
storeWithPreimageAuth

Store preimage-authorized content (mock)

storeWithPreimageAuth(data: Uint8Array, options?: StoreOptions): Promise<StoreResult>

class ProductCloudStorageError

Base class for read-side errors raised by @parity/product-sdk-cloud-storage.

Distinct from upstream BulletinError which covers upload/store failures.

Extends: Error

Constructors

constructor
new ProductCloudStorageError(message: string, options?: ErrorOptions): ProductCloudStorageError

class StoreBuilder

Builder for store operations with fluent API

Examples

const result = await client .store(new TextEncoder().encode('Hello')) .withCodec(CidCodec.DagPb) .withHashAlgorithm('blake2b-256') .withCallback((event) => console.log('Progress:', event)) .send();

Constructors

constructor
new StoreBuilder(executor: BulletinClientInterface, data: Uint8Array): StoreBuilder

Methods

send

Execute the store operation (signed transaction, uses account authorization)

send(): Promise<StoreResult>
sendUnsigned

Execute store operation as unsigned transaction (for preimage-authorized content)

Use this when the content has been pre-authorized via authorizePreimage(). Unsigned transactions don’t require fees and can be submitted by anyone.

sendUnsigned(): Promise<StoreResult>
Examples
// First authorize the content hash const hash = blake2b256(data); await client.authorizePreimage(hash, BigInt(data.length)); // Anyone can now store this content without fees const result = await client.store(data).sendUnsigned();
withCallback

Set progress callback for chunked uploads

withCallback(callback: ProgressCallback): this
withChunkSize

Set chunk size (forces chunked upload path)

withChunkSize(chunkSize: number): this
withCodec

Set the CID codec. Accepts a CidCodec or a custom numeric multicodec code.

withCodec(codec: number): this
withHashAlgorithm

Set the hash algorithm

withHashAlgorithm(algorithm: HashAlgorithm): this
withManifest

Enable or disable DAG-PB manifest creation for chunked uploads (default: true)

withManifest(enabled: boolean): this
withWaitFor

Set what to wait for before returning

withWaitFor(waitFor: WaitFor): this

Functions

authorizeAccount()

Grant an account authorization to store data in Cloud Storage.

Submits a TransactionStorage.authorize_account extrinsic, optionally wrapped in Sudo.sudo(...) for networks that require sudo to grant authorization. Mirrors the call shape of CloudStorageClient.store — top-level function, takes an explicit signer, returns a block hash on success.

Pair with checkAuthorization for a typical “check, grant if insufficient, then upload” flow.

Additive semantics — call once per authorization need

authorize_account is additive within an unexpired authorization window for AuthorizationScope::Account (see pallet-bulletin-transaction-storage, fn authorize). Each successful call adds to the existing transactions_allowance and bytes_allowance rather than overwriting them.

Implications for callers:

  • Calling this function twice with (100, 1MB) while the previous authorization is still active leaves the account with quota for 200 transactions and 2MB — likely unintended.
  • This function does NOT use withRetry. Retrying a successful-but- acknowledgment-lost submission would double-grant the quota. Callers needing retry should wrap this function and use checkAuthorization to verify the post-state before retrying.
  • To “reset” a quota, let the existing authorization expire (AuthorizationPeriod blocks). The next call after expiry creates a fresh authorization rather than adding.

Note: AuthorizationScope::Preimage uses set semantics in the same pallet. This helper is for account-scope authorization only.

authorizeAccount(api: BulletinTypedApi, who: string, transactions: number, bytes: bigint, signer: PolkadotSigner, options: AuthorizeAccountOptions = {}): Promise<{ blockHash: string }>

Parameters

  • api: Typed Cloud Storage API instance.
  • who: SS58-encoded account to authorize.
  • transactions: Number of transactions to add to the account’s allowance.
  • bytes: Byte budget to add to the account’s allowance.
  • signer: Signer for the extrinsic. On viaSudo: true this must be the sudo key.
  • options: Optional viaSudo flag plus standard submission controls.

Returns

Block hash where the extrinsic was included.

Throws

  • If viaSudo: true is requested but the chain has no Sudo pallet.

Examples

import { authorizeAccount } from "@parity/product-sdk-cloud-storage"; await authorizeAccount(api, address, 100, 100n * 1024n * 1024n, signer);
await authorizeAccount(api, userAddress, 100, 1_000_000n, sudoSigner, { viaSudo: true, });

See also

    • checkAuthorization for the read counterpart.
  • CloudStorageClient.authorizeAccount for the client method equivalent.

calculateCid()

Create a CID for data with specified codec and hashing algorithm

Default to raw codec (0x55) with blake2b-256 hash (0xb220)

calculateCid(data: Uint8Array, cidCodec?: number, hashAlgorithm?: HashAlgorithm): Promise<CID<unknown, number, number, Version>>

checkAuthorization()

Check whether an account is authorized to store data in Cloud Storage.

Queries TransactionStorage.Authorizations for the given address and returns the raw authorization quota. Use this as a pre-flight check before calling CloudStorageClient.store to provide clear UX (“not authorized” / “insufficient quota”) instead of letting the transaction fail mid-execution.

The expiration block number is returned as-is — the chain enforces expiration at submission time, so callers can optionally compare against the current block for display purposes.

checkAuthorization(api: BulletinTypedApi, address: string): Promise<AuthorizationStatus>

Parameters

  • api: Typed Cloud Storage API instance.
  • address: SS58-encoded account address to check.

Returns

Authorization status with remaining quota.

Examples

import { checkAuthorization } from "@parity/product-sdk-cloud-storage"; const auth = await checkAuthorization(api, address); if (!auth.authorized) { console.error("Account is not authorized for cloud storage"); } else if (auth.remainingBytes < BigInt(fileBytes.length)) { console.error(`Insufficient quota: ${auth.remainingBytes} bytes remaining`); }

See also

  • CloudStorageClient.checkAuthorization for the client method equivalent.

cidFromBytes()

Parse CID from bytes

cidFromBytes(bytes: Uint8Array): CID

cidToBytes()

Convert CID to bytes

cidToBytes(cid: CID): Uint8Array

cidToPreimageKey()

Extract the 32-byte content hash digest from a CIDv1 and return it as a 0x-prefixed hex string.

Useful for matching a CID against on-chain TransactionInfo.content_hash.

cidToPreimageKey(cid: string): `0x${string}`

convertCid()

Convert CID to different codec while keeping the same hash

convertCid(cid: CID, newCodec: number): CID

createLazySigner()

Build a PolkadotSigner whose underlying signer is resolved on every call.

AsyncBulletinClient takes a fixed PolkadotSigner at construction, but apps often build the Cloud Storage client before any account is selected. This wrapper defers signer resolution: each call to signTx / signBytes invokes getSigner() and forwards to the result. If the getter returns null, calls throw with a clear message.

The publicKey field is also resolved lazily — accessing it before a signer is available throws. This means callers that read publicKey eagerly will fail fast with the same error rather than seeing a stale key from a previously-selected account.

Account changes between calls are picked up automatically: each sign resolves the current signer.

createLazySigner(getSigner: () => PolkadotSigner | null, onMissing: string = "No signer available — connect a wallet and select an account first."): PolkadotSigner

estimateAuthorization()

Estimate authorization needed for storing data

estimateAuthorization(dataSize: number, chunkSize: number, createManifest: boolean): { bytes: number; transactions: number }

Parameters

  • dataSize: Total data size in bytes
  • chunkSize: Size of each chunk in bytes
  • createManifest: Whether a DAG-PB manifest will be created

executeQuery()

Execute a query using a pre-resolved strategy.

Exposed so CloudStorageClient can resolve the strategy once at construction time and reuse it across calls without re-detecting the host environment on every fetch.

Reassembly is automatic. If cid carries the DAG-PB codec (0x70) — meaning the upload was chunked and a UnixFS manifest was created — this function recursively fetches each chunk via strategy .lookup and returns the concatenated bytes. Pass noReassemble: true to get the raw manifest bytes instead.

For raw-codec CIDs (0x55, single-chunk content), the bytes returned by the host are returned directly — no parsing overhead.

executeQuery(strategy: QueryStrategy, cid: string, options?: QueryOptions): Promise<Uint8Array<ArrayBufferLike>>

getContentHash()

Calculate content hash using the specified algorithm

Note: For production use, integrate with the pallet’s hashing functions via PAPI to ensure exact compatibility.

getContentHash(data: Uint8Array, hashAlgorithm: HashAlgorithm): Promise<Uint8Array<ArrayBufferLike>>

hashToCid()

Reconstruct a CIDv1 from a 0x-prefixed 32-byte hex hash.

Useful when reading on-chain TransactionInfo.content_hash and you need the CID to look up content via an IPFS gateway.

hashToCid(hexHash: `0x${string}`, hashCode: HashAlgorithm = HashAlgorithm.Blake2b256, codec: CidCodec = CidCodec.Raw): string

Parameters

  • hexHash: 66-char 0x-prefixed hex of a 32-byte digest.
  • hashCode: Multihash code (default: blake2b-256).
  • codec: Multicodec code (default: raw).

parseCid()

Parse CID from string

parseCid(cidString: string): CID

queryBytes()

Fetch raw bytes for a CID via the host’s preimage lookup.

Container-only by design: the Cloud Storage SDK does not retrieve content through public IPFS gateways. Inside a Polkadot Browser / Desktop container, the host’s preimageManager provides a cached, polling- managed lookup that returns bytes when the underlying IPFS network makes them available. Outside a container, this throws CloudStorageHostUnavailableError.

The underlying chain stores transaction metadata on-chain (chunk_root, content_hash, size, cid_codec, hashing) — the content bytes themselves live in IPFS and are surfaced through the host’s preimage subscription, never via direct gateway fetch.

To prove that a CID was stored on-chain (without fetching the bytes), use verifyStored from verify.ts.

queryBytes(cid: string, options?: QueryOptions): Promise<Uint8Array<ArrayBufferLike>>

Parameters

  • cid: CIDv1 string to fetch.
  • options: Query options (lookupTimeoutMs for host).

Throws

  • If running outside a container.

queryJson()

Fetch and parse JSON for a CID via the host’s preimage lookup.

Convenience wrapper over queryBytes.

queryJson(cid: string, options?: QueryOptions): Promise<T>

reassembleChunks()

Reassemble chunks back into the original data

Chunks are sorted by index before concatenation to handle out-of-order input.

reassembleChunks(chunks: Chunk[]): Uint8Array

Parameters

  • chunks: Array of chunks to reassemble

Returns

The original data as a single Uint8Array

resolveClientConfig()

Merge caller-supplied config with defaults, ignoring undefined values.

resolveClientConfig(config?: Partial<ClientConfig>): Required<ClientConfig>

resolveQueryStrategy()

Determine the query strategy for Cloud Storage retrieval.

Uses the host preimage lookup API which caches results and manages IPFS polling automatically.

resolveQueryStrategy(): Promise<QueryStrategy>

Returns

The resolved query strategy.

Throws

  • If the host preimage manager is unavailable.

validateChunkSize()

validateChunkSize(size: number): void

verifyStored()

Verify that a CID is recorded in the cloud storage (bulletin chain’s Transactions storage) at the given block.

Returns the matched entry (with block + index) when the CID’s content hash and hashing algorithm both match a Transactions[block] entry. Returns null when no match is found at that block.

verifyStored(api: BulletinTypedApi, cid: string, options: VerifyStoredOptions): Promise<ChainStoredEntry | null>

Parameters

  • api: Typed Cloud Storage API instance.
  • cid: CIDv1 string to look up.
  • options: Verification target (block number, optional index).

Examples

const receipt = await client.store(data).send(); if (receipt.blockNumber !== undefined) { const entry = await verifyStored(client.api, receipt.cid!.toString(), { block: receipt.blockNumber, index: receipt.extrinsicIndex, }); if (!entry) console.warn("CID not found in expected block — chain reorg?"); }

Interfaces

interface AuthorizationStatus

//TODO: Come back to this (code docs might need update) Authorization status for a Cloud Storage account.

Returned by checkAuthorization as a pre-flight check before storing data. Consumers can use this to show “not authorized” or “insufficient quota” messages instead of letting the transaction fail mid-execution.

Properties

authorized
propertyboolean

Whether an authorization entry exists for this account.

expiration
propertynumber

Block number when the authorization expires. 0 if not authorized.

remainingBytes
propertybigint

Remaining bytes allowed. 0n if not authorized.

remainingTransactions
propertynumber

Remaining transactions allowed. 0 if not authorized.

interface AuthorizeAccountOptions

Options for authorizeAccount.

Properties

onStatus
propertyoptional(status: TxStatus) => void

Lifecycle status callback for UI progress.

timeoutMs
propertyoptionalnumber

Timeout in ms. Default: 300_000 (5 min).

viaSudo
propertyoptionalboolean

Wrap the extrinsic in Sudo.sudo(...) before submission. Default: false.

Use true on networks where granting cloud storage authorization requires sudo permissions (most production / managed test networks). Use false (default) when the account self-authorizes — typical for local development chains.

waitFor
propertyoptionalWaitFor

When to resolve: "best-block" (default) or "finalized".

interface BulletinClientInterface

Shared interface for Bulletin clients (real and mock).

Both AsyncBulletinClient and MockBulletinClient implement this interface.

Methods

authorizeAccount
authorizeAccount(who: string, transactions: number, bytes: bigint): AuthCallBuilder
authorizePreimage
authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuilder
destroy

Release resources held on behalf of this client (e.g. underlying PAPI client).

destroy(): Promise<void>
estimateAuthorization
estimateAuthorization(dataSize: number): { bytes: number; transactions: number }
refreshAccountAuthorization
refreshAccountAuthorization(who: string): AuthCallBuilder
refreshPreimageAuthorization
refreshPreimageAuthorization(contentHash: Uint8Array): AuthCallBuilder
removeExpiredAccountAuthorization
removeExpiredAccountAuthorization(who: string): CallBuilder
removeExpiredPreimageAuthorization
removeExpiredPreimageAuthorization(contentHash: Uint8Array): CallBuilder
renew
renew(block: number, index: number): CallBuilder
store
store(data: Uint8Array): StoreBuilder
storeWithOptions

Store data with options (used internally by StoreBuilder)

storeWithOptions(data: Uint8Array, options?: StoreOptions, progressCallback?: ProgressCallback, chunkerConfig?: Partial<ChunkerConfig>): Promise<StoreResult>
storeWithPreimageAuth

Store preimage-authorized content as unsigned transaction

storeWithPreimageAuth(data: Uint8Array, options?: StoreOptions): Promise<StoreResult>

interface BulletinTypedApi

Minimal interface for the PAPI typed API.

Describes the pallets and extrinsics the SDK interacts with. Users pass their actual TypedApi<ChainDescriptor> which satisfies this interface structurally.

Properties

query
propertyoptional{ TransactionStorage: { Authorizations: { getValue: unknown } } }

Optional query interface for on-chain storage reads (e.g., authorization checks)

tx
property{ Sudo?: { sudo: unknown }; TransactionStorage: { authorize_account: unknown; authorize_preimage: unknown; refresh_account_authorization: unknown; refresh_preimage_authorization: unknown; remove_expired_account_authorization: unknown; remove_expired_preimage_authorization: unknown; renew: unknown; store: unknown; store_with_cid_config: unknown } }

interface ChainStoredEntry

A single matched entry from TransactionStorage.Transactions.

Properties

block
propertynumber

Block number where the transaction was included.

blockChunks
propertynumber

Number of chunks (1 for unchunked data, >1 for chunked + manifest).

index
propertynumber

Index of the entry within the block’s transactions array.

size
propertynumber

Size of the stored data in bytes (from chain metadata).

interface Chunk

A single chunk of data

Properties

cid
propertyoptionalCID<unknown, number, number, Version>

The CID of this chunk (calculated after encoding)

data
propertyUint8Array

The chunk data

index
propertynumber

Index of this chunk in the sequence

totalChunks
propertynumber

Total number of chunks

interface ChunkDetails

Details about chunks in a chunked upload

Properties

chunkCids
propertyCID<unknown, number, number, Version>[]

CIDs of all stored chunks

numChunks
propertynumber

Number of chunks

interface ChunkedStoreResult

Result of a chunked storage operation

Properties

chunkCids
propertyCID<unknown, number, number, Version>[]

CIDs of all stored chunks

manifestCid
propertyoptionalCID<unknown, number, number, Version>

The manifest CID (if manifest was created)

numChunks
propertynumber

Number of chunks

totalSize
propertynumber

Total size of all chunks in bytes

interface ChunkerConfig

Configuration for chunking large data

Properties

chunkSize
propertynumber

Size of each chunk in bytes (default: 1 MiB)

createManifest
propertyboolean

Whether to create a DAG-PB manifest (default: true)

interface ClientConfig

Client configuration

Properties

chunkingThreshold
propertyoptionalnumber

Threshold for automatic chunking (default: 2 MiB). Data larger than this will be automatically chunked by store().

createManifest
propertyoptionalboolean

Whether to create manifests for chunked uploads (default: true)

defaultChunkSize
propertyoptionalnumber

Default chunk size for large files (default: 1 MiB)

txTimeout
propertyoptionalnumber

Defensive timeout in milliseconds per transaction (default: 420_000). PAPI handles reconnects and mortality, so this should rarely fire. Set above PAPI’s default mortality window (64 blocks ~ 6.4 min at 6s blocks).

interface CloudStorageNetwork

Properties

descriptor
propertyany

PAPI descriptor for typed API access.

genesisHash
property`0x${string}`

Genesis hash of the underlying chain on this environment.

interface DagManifest

DAG-PB manifest representing a file composed of multiple chunks

Properties

chunkCids
propertyCID<unknown, number, number, Version>[]

CIDs of all chunks in order

dagBytes
propertyUint8Array

Encoded DAG-PB bytes

rootCid
propertyCID

The root CID of the manifest

totalSize
propertynumber

Total size of the file in bytes

interface MockClientConfig

Configuration for the mock Bulletin client

Extends: ClientConfig

Properties

simulateAuthFailure
propertyoptionalboolean

Simulate authorization failures (for testing error paths)

simulateInsufficientAuth
propertyoptionalboolean

Simulate insufficient authorization (for testing pre-check error path)

simulateStorageFailure
propertyoptionalboolean

Simulate storage failures (for testing error paths)

interface QueryOptions

Options for CloudStorageClient.fetchBytes / CloudStorageClient.fetchJson.

Properties

lookupTimeoutMs
propertyoptionalnumber

Timeout for the host preimage lookup subscription, in ms. Default: 30_000. Applied per lookup — for chunked content (DAG-PB manifest CIDs), the manifest fetch and each child chunk fetch each get this budget.

noReassemble
propertyoptionalboolean

When true, return the raw bytes for the requested CID without parsing or recursing into a DAG-PB manifest. Default: false — the client transparently reassembles chunked content so callers don’t need to know whether a CID points at a single chunk or a manifest.

Set this if you want to inspect the manifest itself, e.g., to read unixfs.fileSize() ahead of fetching, or to drive your own chunk pipeline.

interface QueryStrategy

Query strategy for Cloud Storage retrieval.

The host manages the lookup via its preimage subscription API, which includes local caching and managed IPFS polling.

Properties

kind
property"host-lookup"
lookup
property(cid: string, timeoutMs?: number) => Promise<Uint8Array<ArrayBufferLike>>

interface StoreOptions

Options for storing data

Properties

cidCodec
propertyoptionalnumber

CID codec to use (default: raw). Accepts a CidCodec or a custom numeric multicodec code.

hashingAlgorithm
propertyoptionalHashAlgorithm

Hashing algorithm to use (default: blake2b-256)

waitFor
propertyoptionalWaitFor

What to wait for before returning (default: “in_block”)

  • “in_block”: Return when tx is in a best block (faster, may reorg)
  • “finalized”: Return when tx is finalized (safer, slower)

interface StoreResult

Result of a storage operation

This result type works for both single-transaction uploads and chunked uploads. For chunked uploads, the cid field contains the manifest CID, and chunks contains details about the individual chunks.

When chunked without a manifest (withManifest(false)), cid is undefined and the individual chunk CIDs are in chunks.chunkCids.

Properties

blockNumber
propertyoptionalnumber

Block number where data was stored (if known)

chunks
propertyoptionalChunkDetails

Chunk details (only present for chunked uploads)

cid
propertyoptionalCID<unknown, number, number, Version>

The primary CID of the stored data

  • For single uploads: CID of the data
  • For chunked uploads with manifest: CID of the manifest
  • For chunked uploads without manifest: undefined
extrinsicIndex
propertyoptionalnumber

Extrinsic index within the block (required for renew operations) This value comes from the Stored event’s index field

size
propertynumber

Size of the stored data in bytes

interface TransactionReceipt

Transaction receipt from a successful submission

Properties

blockHash
propertystring

Block hash containing the transaction

blockNumber
propertyoptionalnumber

Block number (if known)

txHash
propertystring

Transaction hash

interface VerifyStoredOptions

Verification options for verifyStored.

Properties

block
propertynumber

Block number to look up. Pass the blockNumber returned from a prior store(...).send() for an O(1) lookup.

If omitted, throws — full-chain scans are not supported because RetentionPeriod can be many days of blocks. Use getEntries() on api.query.TransactionStorage.Transactions directly if you need that.

index
propertyoptionalnumber

Optional: index within the block. When provided, narrows verification to that exact slot. Useful when re-checking a known (block, index) tuple from an earlier receipt.

Type Aliases

type ChunkProgressEvent

Progress event types for chunked uploads

type ChunkProgressEvent = { index: number; total: number; type: ChunkStatus.ChunkStarted } | { cid: CID; index: number; total: number; type: ChunkStatus.ChunkCompleted } | { error: Error; index: number; total: number; type: ChunkStatus.ChunkFailed } | { type: ChunkStatus.ManifestStarted } | { cid: CID; type: ChunkStatus.ManifestCreated } | { manifestCid?: CID; type: ChunkStatus.Completed }

type CidCodec

CID codecs supported by Cloud Storage.

type CidCodec = typeof CidCodec[keyof typeof CidCodec]

type CloudStorageApi

Typed API for the Cloud Storage (re-export from upstream BulletinTypedApi).

type CloudStorageApi = BulletinTypedApi

type CloudStorageEnvironment

Network keys with built-in presets in CloudStorageNetworks.

type CloudStorageEnvironment = keyof typeof CloudStorageNetworks

type CreateCloudStorageClientOptions

Options for CloudStorageClient.create.

One of two construction shapes is supported:

  • Environment shorthand — pass an environment string keyed by CloudStorageNetworks. Wires up the chain-client automatically.
  • Explicit network — pass genesisHash and descriptor directly (e.g., spread from a CloudStorageNetworks entry, or supply custom values for a private chain).
type CreateCloudStorageClientOptions = CreateCloudStorageClientCommon & { environment: CloudStorageEnvironment } | CreateCloudStorageClientCommon & { descriptor: typeof CloudStorageNetworks[CloudStorageEnvironment]["descriptor"]; genesisHash: `0x${string}` }

type HashAlgorithm

Hash algorithms supported by Cloud Storage.

Values are multihash codes from the multicodec table.

type HashAlgorithm = typeof HashAlgorithm[keyof typeof HashAlgorithm]

type MockOperation

Record of a mock operation performed

type MockOperation = { cid: string; dataSize: number; type: "store" } | { bytes: bigint; transactions: number; type: "authorize_account"; who: string } | { contentHash: Uint8Array; maxSize: bigint; type: "authorize_preimage" } | { type: "refresh_account_authorization"; who: string } | { contentHash: Uint8Array; type: "refresh_preimage_authorization" } | { block: number; index: number; type: "renew" } | { cid: string; dataSize: number; type: "store_preimage_auth" } | { type: "remove_expired_account_authorization"; who: string } | { contentHash: Uint8Array; type: "remove_expired_preimage_authorization" }

type ProgressCallback

Progress callback type

type ProgressCallback = (event: ProgressEvent) => void

type ProgressEvent

Combined progress event types

type ProgressEvent = ChunkProgressEvent | TransactionStatusEvent

type SubmitFn

Function type for submitting raw transactions to the chain.

Matches the signature of PolkadotClient.submit from polkadot-api. Pass papiClient.submit directly when constructing the client.

type SubmitFn = (transaction: Uint8Array, at?: string) => Promise<{ block: { hash: string; index: number; number: number }; dispatchError?: { type: string; value: unknown }; events: { type: string; value?: { type?: string; value?: unknown } }[]; ok: boolean; txHash: string }>

type TransactionStatusEvent

Transaction status event types (mirrors PAPI’s signSubmitAndWatch events)

type TransactionStatusEvent = { chunkIndex?: number; txHash: string; type: TxStatus.Signed } | { chunkIndex?: number; type: TxStatus.Validated } | { chunkIndex?: number; type: TxStatus.Broadcasted } | { blockHash: string; blockNumber: number; chunkIndex?: number; txIndex?: number; type: TxStatus.InBlock } | { blockHash: string; blockNumber: number; chunkIndex?: number; txIndex?: number; type: TxStatus.Finalized } | { chunkIndex?: number; type: TxStatus.NoLongerInBlock } | { chunkIndex?: number; error: string; type: TxStatus.Invalid } | { chunkIndex?: number; error: string; type: TxStatus.Dropped }

type WaitFor

Transaction confirmation level

Can be used as a value (WaitFor.InBlock) or as a type (WaitFor).

type WaitFor = "in_block" | "finalized"

Enums

enum AuthorizationScope

Authorization scope types (mirrors the pallet’s AuthorizationScope enum)

Members

NameValueDescription
Account"Account"Account-based authorization
Preimage"Preimage"Preimage-based authorization (content-addressed)

enum ChunkStatus

Chunk progress event types

Members

NameValueDescription
ChunkCompleted"chunk_completed"
ChunkFailed"chunk_failed"
ChunkStarted"chunk_started"
Completed"completed"
ManifestCreated"manifest_created"
ManifestStarted"manifest_started"

enum ErrorCode

Error codes for the Bulletin SDK.

These codes are consistent with the Rust SDK’s Error::code() method.

Members

NameValueDescription
AUTHORIZATION_FAILED"AUTHORIZATION_FAILED"
CHUNK_FAILED"CHUNK_FAILED"
CHUNK_TOO_LARGE"CHUNK_TOO_LARGE"
CID_CALCULATION_FAILED"CID_CALCULATION_FAILED"
DAG_ENCODING_FAILED"DAG_ENCODING_FAILED"
DATA_TOO_LARGE"DATA_TOO_LARGE"
EMPTY_DATA"EMPTY_DATA"
INSUFFICIENT_AUTHORIZATION"INSUFFICIENT_AUTHORIZATION"
INVALID_CHUNK_SIZE"INVALID_CHUNK_SIZE"
INVALID_CID"INVALID_CID"
INVALID_CONFIG"INVALID_CONFIG"
INVALID_HASH_ALGORITHM"INVALID_HASH_ALGORITHM"
MISSING_CHUNK"MISSING_CHUNK"
TIMEOUT"TIMEOUT"
TRANSACTION_FAILED"TRANSACTION_FAILED"
UNSUPPORTED_OPERATION"UNSUPPORTED_OPERATION"

enum TxStatus

Transaction status event types

Members

NameValueDescription
Broadcasted"broadcasted"
Dropped"dropped"
Finalized"finalized"
InBlock"in_block"
Invalid"invalid"
NoLongerInBlock"no_longer_in_block"
Signed"signed"
Validated"validated"

Variables

CidCodec

CID codecs supported by Cloud Storage.

let CidCodec: { readonly DagCbor: 113; readonly DagPb: 112; readonly Raw: 85 } = ...

CloudStorageNetworks

Cloud Storage network presets.

Use these with CloudStorageClient.create when you want to be explicit about the network rather than passing an environment string. Reads go through the host’s preimage subscription (container-only); no gateway URL is configured per network.

let CloudStorageNetworks: { readonly paseo: { readonly descriptor: any; readonly genesisHash: "0x8cfe6717dc4becfda2e13c488a1e2061ff2dfee96e7d031157f72d36716c0a22" }; readonly summit: { readonly descriptor: any; readonly genesisHash: "0x147aae0d60625af72300d4d5ebd5dcb869f7ac4c6c1a326be1cbb14a4a65ae77" } } = ...

DEFAULT_CHUNKER_CONFIG

Default chunker configuration

Uses 1 MiB chunk size by default (safe and efficient for most use cases). Maximum allowed is 2 MiB (MAX_CHUNK_SIZE, Bitswap limit for IPFS compatibility).

let DEFAULT_CHUNKER_CONFIG: ChunkerConfig

DEFAULT_CLIENT_CONFIG

Default client configuration values.

Used by AsyncBulletinClient, MockBulletinClient, and BulletinPreparer so that defaults are defined in one place.

let DEFAULT_CLIENT_CONFIG: Required<ClientConfig>

DEFAULT_STORE_OPTIONS

Default store options

let DEFAULT_STORE_OPTIONS: StoreOptions

HashAlgorithm

Hash algorithms supported by Cloud Storage.

Values are multihash codes from the multicodec table.

let HashAlgorithm: { readonly Blake2b256: 45600; readonly Keccak256: 27; readonly Sha2_256: 18 } = ...

MAX_CHUNK_SIZE

Maximum chunk size allowed (2 MiB, Bitswap compatibility limit)

let MAX_CHUNK_SIZE: number

MAX_FILE_SIZE

Maximum file size the SDK will chunk in a single operation (64 MiB). For larger files, split into segments of at most 64 MiB and chunk each independently.

let MAX_FILE_SIZE: number

WaitFor

let WaitFor: { Finalized: "finalized"; InBlock: "in_block" }
Last updated on