@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-storageExports
Classes
| Name | Summary |
|---|---|
AsyncBulletinClient | Async Bulletin client that submits transactions to the chain |
AuthCallBuilder | Builder for authorization calls that may require sudo |
BulletinError | SDK error class |
BulletinPreparer | Offline data preparer for Bulletin Chain |
CallBuilder | Builder for calls with CallOptions (waitFor + callback) |
CID | — |
CloudStorageAuthorizationError | Failed to check authorization status for an account. |
CloudStorageCidError | Invalid CID format or version. |
CloudStorageClient | Ergonomic entry point for Cloud Storage operations. |
CloudStorageHostUnavailableError | The host preimage API is unavailable. |
CloudStorageLookupInterruptedError | The host interrupted the preimage lookup. |
CloudStorageLookupTimeoutError | The host preimage lookup timed out. |
MockBulletinClient | Mock Bulletin client for testing |
ProductCloudStorageError | Base class for read-side errors raised by @parity/product-sdk-cloud-storage. |
StoreBuilder | Builder for store operations with fluent API |
Functions
| Name | Summary |
|---|---|
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
| Name | Summary |
|---|---|
AuthorizationStatus | //TODO: Come back to this (code docs might need update) |
AuthorizeAccountOptions | Options for authorizeAccount. |
BulletinClientInterface | Shared interface for Bulletin clients (real and mock). |
BulletinTypedApi | Minimal interface for the PAPI typed API. |
ChainStoredEntry | A single matched entry from TransactionStorage.Transactions. |
Chunk | A single chunk of data |
ChunkDetails | Details about chunks in a chunked upload |
ChunkedStoreResult | Result of a chunked storage operation |
ChunkerConfig | Configuration for chunking large data |
ClientConfig | Client configuration |
CloudStorageNetwork | — |
DagManifest | DAG-PB manifest representing a file composed of multiple chunks |
MockClientConfig | Configuration for the mock Bulletin client |
QueryOptions | Options for CloudStorageClient.fetchBytes / CloudStorageClient.fetchJson. |
QueryStrategy | Query strategy for Cloud Storage retrieval. |
StoreOptions | Options for storing data |
StoreResult | Result of a storage operation |
TransactionReceipt | Transaction receipt from a successful submission |
VerifyStoredOptions | Verification options for verifyStored. |
Type Aliases
| Name | Summary |
|---|---|
ChunkProgressEvent | Progress event types for chunked uploads |
CidCodec | CID codecs supported by Cloud Storage. |
CloudStorageApi | Typed API for the Cloud Storage (re-export from upstream BulletinTypedApi). |
CloudStorageEnvironment | Network keys with built-in presets in CloudStorageNetworks. |
CreateCloudStorageClientOptions | Options for CloudStorageClient.create. |
HashAlgorithm | Hash algorithms supported by Cloud Storage. |
MockOperation | Record of a mock operation performed |
ProgressCallback | Progress callback type |
ProgressEvent | Combined progress event types |
SubmitFn | Function type for submitting raw transactions to the chain. |
TransactionStatusEvent | Transaction status event types (mirrors PAPI’s signSubmitAndWatch events) |
WaitFor | Transaction confirmation level |
Enums
| Name | Summary |
|---|---|
AuthorizationScope | Authorization scope types (mirrors the pallet’s AuthorizationScope enum) |
ChunkStatus | Chunk progress event types |
ErrorCode | Error codes for the Bulletin SDK. |
TxStatus | Transaction status event types |
Variables
| Name | Summary |
|---|---|
CidCodec | CID codecs supported by Cloud Storage. |
CloudStorageNetworks | Cloud Storage network presets. |
DEFAULT_CHUNKER_CONFIG | Default chunker configuration |
DEFAULT_CLIENT_CONFIG | Default client configuration values. |
DEFAULT_STORE_OPTIONS | Default store options |
HashAlgorithm | Hash algorithms supported by Cloud Storage. |
MAX_CHUNK_SIZE | Maximum chunk size allowed (2 MiB, Bitswap compatibility limit) |
MAX_FILE_SIZE | Maximum 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.
| Name | Kind | Source package |
|---|---|---|
Environment | type | @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>): AsyncBulletinClientParameters
api: Configured PAPI TypedApi instancesigner: Polkadot signer for transaction signingsubmit: Raw transaction submit function (passpapiClient.submit)config: Optional client configurationonDestroy: Optional teardown callback. When provided,destroy()awaits it so callers (e.g. wrappers that own the underlyingPolkadotClient) can route cleanup through this client.
Properties
api
BulletinTypedApiPAPI client for blockchain interaction
config
Required<ClientConfig>Client configuration
signer
PolkadotSignerSigner for transaction signing
submit
SubmitFnSubmit function for broadcasting raw transactions (from PolkadotClient.submit)
Methods
authorizeAccount
Authorize an account to store data
authorizeAccount(who: string, transactions: number, bytes: bigint): AuthCallBuilderParameters
who: Account address to authorizetransactions: Number of transactions to authorizebytes: Maximum bytes to authorize
authorizePreimage
Authorize a preimage (by content hash) to be stored
authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuilderParameters
contentHash: Blake2b-256 hash of the content to authorizemaxSize: 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): AuthCallBuilderParameters
who: Account address to refresh authorization for
refreshPreimageAuthorization
Refresh a preimage authorization (extends expiry)
Requires Authorizer origin on-chain.
refreshPreimageAuthorization(contentHash: Uint8Array): AuthCallBuilderParameters
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): CallBuilderParameters
who: Account address with expired authorization
removeExpiredPreimageAuthorization
Remove an expired preimage authorization
Can be called by anyone (no special origin required).
removeExpiredPreimageAuthorization(contentHash: Uint8Array): CallBuilderParameters
contentHash: Blake2b-256 hash of the expired authorization
renew
Renew/extend retention period for stored data
renew(block: number, index: number): CallBuilderParameters
block: Block number where the original storage transaction was includedindex: 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): StoreBuilderParameters
data: Data to store asUint8Array
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 storeoptions: 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>): AuthCallBuilderMethods
send
Submit the transaction
send(): Promise<TransactionReceipt>withCallback
Set progress callback
withCallback(callback: ProgressCallback): thiswithSudo
Wrap the call in Sudo
withSudo(): thiswithWaitFor
Set what to wait for before returning
withWaitFor(waitFor: WaitFor): thisclass BulletinError
SDK error class
Extends: Error
Constructors
constructor
new BulletinError(message: string, code: ErrorCode, cause?: unknown): BulletinErrorProperties
cause
unknowncode
ErrorCodeAccessors
recoveryHint
stringAn actionable recovery suggestion for this error.
retryable
booleanWhether 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): BulletinPreparerMethods
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>): CallBuilderMethods
send
Submit the transaction
send(): Promise<TransactionReceipt>withCallback
Set progress callback
withCallback(callback: ProgressCallback): thiswithWaitFor
Set what to wait for before returning
withWaitFor(waitFor: WaitFor): thisclass 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
version: Version of the CIDcode: Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csvmultihash: (Multi)hash of the of the content.
Properties
[toStringTag]
"CID"/
Uint8Arraybytes
Uint8Arraycode
Formatmultihash
MultihashDigest<Alg>version
VersionAccessors
asCID
thisSignalling cid.asCID === cid has been replaced with cid['/'] === cid.bytes
please either use CID.asCID(cid) or switch to new signalling mechanism
byteLength
numberbyteOffset
numberMethods
equals
equals(other: unknown): other is CID<Data, Format, Alg, Version>link
link(): thistoJSON
toJSON(): LinkJSON<CID<Data, Format, Alg, Version>>toString
toString(base?: MultibaseEncoder<string>): stringtoV0
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> | nullcreate
create(version: Version, code: Format, digest: MultihashDigest<Alg>): CID<Data, Format, Alg, Version>Parameters
version: Version of the CIDcode: Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csvdigest: (Multi)hash of the of the content.
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): CloudStorageAuthorizationErrorProperties
address
stringThe address that was being checked.
class CloudStorageCidError
Invalid CID format or version.
Extends: ProductCloudStorageError
Constructors
constructor
new CloudStorageCidError(message: string, cid?: string): CloudStorageCidErrorProperties
cid
stringThe 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.createandCloudStorageNetworks. - 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
BulletinTypedApiTyped CloudStorage API.
inner
AsyncBulletinClientUnderlying 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): AuthCallBuilderauthorizePreimage
Authorize content storage by hash (anyone can store; no fees).
authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuildercheckAuthorization
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): CallBuilderstore
Build a store transaction. See upstream StoreBuilder for chained options.
store(data: Uint8Array): StoreBuilderverifyStored
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): CloudStorageClientclass 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"): CloudStorageHostUnavailableErrorclass 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): CloudStorageLookupInterruptedErrorProperties
cid
stringThe 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): CloudStorageLookupTimeoutErrorProperties
cid
stringThe CID that was being looked up.
timeoutMs
numberThe 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>): MockBulletinClientProperties
config
Required<ClientConfig> & { simulateAuthFailure: boolean; simulateInsufficientAuth: boolean; simulateStorageFailure: boolean }Client configuration
Methods
authorizeAccount
authorizeAccount(who: string, transactions: number, bytes: bigint): AuthCallBuilderauthorizePreimage
authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuilderclearOperations
Clear recorded operations
clearOperations(): voiddestroy
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): AuthCallBuilderrefreshPreimageAuthorization
refreshPreimageAuthorization(contentHash: Uint8Array): AuthCallBuilderremoveExpiredAccountAuthorization
removeExpiredAccountAuthorization(who: string): CallBuilderremoveExpiredPreimageAuthorization
removeExpiredPreimageAuthorization(contentHash: Uint8Array): CallBuilderrenew
renew(block: number, index: number): CallBuilderstore
Store data using builder pattern
store(data: Uint8Array): StoreBuilderParameters
data: Data to store asUint8Array
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): ProductCloudStorageErrorclass 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): StoreBuilderMethods
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): thiswithChunkSize
Set chunk size (forces chunked upload path)
withChunkSize(chunkSize: number): thiswithCodec
Set the CID codec. Accepts a CidCodec or a custom numeric multicodec code.
withCodec(codec: number): thiswithHashAlgorithm
Set the hash algorithm
withHashAlgorithm(algorithm: HashAlgorithm): thiswithManifest
Enable or disable DAG-PB manifest creation for chunked uploads (default: true)
withManifest(enabled: boolean): thiswithWaitFor
Set what to wait for before returning
withWaitFor(waitFor: WaitFor): thisFunctions
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 for200transactions and2MB— 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 usecheckAuthorizationto verify the post-state before retrying. - To “reset” a quota, let the existing authorization expire
(
AuthorizationPeriodblocks). 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. OnviaSudo: truethis must be the sudo key.options: OptionalviaSudoflag plus standard submission controls.
Returns
Block hash where the extrinsic was included.
Throws
- If
viaSudo: trueis requested but the chain has noSudopallet.
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
-
checkAuthorizationfor the read counterpart.
CloudStorageClient.authorizeAccountfor 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.checkAuthorizationfor the client method equivalent.
cidFromBytes()
Parse CID from bytes
cidFromBytes(bytes: Uint8Array): CIDcidToBytes()
Convert CID to bytes
cidToBytes(cid: CID): Uint8ArraycidToPreimageKey()
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): CIDcreateLazySigner()
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."): PolkadotSignerestimateAuthorization()
Estimate authorization needed for storing data
estimateAuthorization(dataSize: number, chunkSize: number, createManifest: boolean): { bytes: number; transactions: number }Parameters
dataSize: Total data size in byteschunkSize: Size of each chunk in bytescreateManifest: 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): stringParameters
hexHash: 66-char0x-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): CIDqueryBytes()
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 (lookupTimeoutMsfor 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[]): Uint8ArrayParameters
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): voidverifyStored()
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
booleanWhether an authorization entry exists for this account.
expiration
numberBlock number when the authorization expires. 0 if not authorized.
remainingBytes
bigintRemaining bytes allowed. 0n if not authorized.
remainingTransactions
numberRemaining transactions allowed. 0 if not authorized.
interface AuthorizeAccountOptions
Options for authorizeAccount.
Properties
onStatus
(status: TxStatus) => voidLifecycle status callback for UI progress.
timeoutMs
numberTimeout in ms. Default: 300_000 (5 min).
viaSudo
booleanWrap 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
WaitForWhen 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): AuthCallBuilderauthorizePreimage
authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuilderdestroy
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): AuthCallBuilderrefreshPreimageAuthorization
refreshPreimageAuthorization(contentHash: Uint8Array): AuthCallBuilderremoveExpiredAccountAuthorization
removeExpiredAccountAuthorization(who: string): CallBuilderremoveExpiredPreimageAuthorization
removeExpiredPreimageAuthorization(contentHash: Uint8Array): CallBuilderrenew
renew(block: number, index: number): CallBuilderstore
store(data: Uint8Array): StoreBuilderstoreWithOptions
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
{ TransactionStorage: { Authorizations: { getValue: unknown } } }Optional query interface for on-chain storage reads (e.g., authorization checks)
tx
{ 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
numberBlock number where the transaction was included.
blockChunks
numberNumber of chunks (1 for unchunked data, >1 for chunked + manifest).
index
numberIndex of the entry within the block’s transactions array.
size
numberSize of the stored data in bytes (from chain metadata).
interface Chunk
A single chunk of data
Properties
cid
CID<unknown, number, number, Version>The CID of this chunk (calculated after encoding)
data
Uint8ArrayThe chunk data
index
numberIndex of this chunk in the sequence
totalChunks
numberTotal number of chunks
interface ChunkDetails
Details about chunks in a chunked upload
Properties
chunkCids
CID<unknown, number, number, Version>[]CIDs of all stored chunks
numChunks
numberNumber of chunks
interface ChunkedStoreResult
Result of a chunked storage operation
Properties
chunkCids
CID<unknown, number, number, Version>[]CIDs of all stored chunks
manifestCid
CID<unknown, number, number, Version>The manifest CID (if manifest was created)
numChunks
numberNumber of chunks
totalSize
numberTotal size of all chunks in bytes
interface ChunkerConfig
Configuration for chunking large data
Properties
chunkSize
numberSize of each chunk in bytes (default: 1 MiB)
createManifest
booleanWhether to create a DAG-PB manifest (default: true)
interface ClientConfig
Client configuration
Properties
chunkingThreshold
numberThreshold for automatic chunking (default: 2 MiB).
Data larger than this will be automatically chunked by store().
createManifest
booleanWhether to create manifests for chunked uploads (default: true)
defaultChunkSize
numberDefault chunk size for large files (default: 1 MiB)
txTimeout
numberDefensive 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
anyPAPI descriptor for typed API access.
genesisHash
`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
CID<unknown, number, number, Version>[]CIDs of all chunks in order
dagBytes
Uint8ArrayEncoded DAG-PB bytes
rootCid
CIDThe root CID of the manifest
totalSize
numberTotal size of the file in bytes
interface MockClientConfig
Configuration for the mock Bulletin client
Extends: ClientConfig
Properties
simulateAuthFailure
booleanSimulate authorization failures (for testing error paths)
simulateInsufficientAuth
booleanSimulate insufficient authorization (for testing pre-check error path)
simulateStorageFailure
booleanSimulate storage failures (for testing error paths)
interface QueryOptions
Options for CloudStorageClient.fetchBytes / CloudStorageClient.fetchJson.
Properties
lookupTimeoutMs
numberTimeout 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
booleanWhen 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
"host-lookup"lookup
(cid: string, timeoutMs?: number) => Promise<Uint8Array<ArrayBufferLike>>interface StoreOptions
Options for storing data
Properties
cidCodec
numberCID codec to use (default: raw). Accepts a CidCodec or a custom numeric multicodec code.
hashingAlgorithm
HashAlgorithmHashing algorithm to use (default: blake2b-256)
waitFor
WaitForWhat 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
numberBlock number where data was stored (if known)
chunks
ChunkDetailsChunk details (only present for chunked uploads)
cid
CID<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
numberExtrinsic index within the block (required for renew operations)
This value comes from the Stored event’s index field
size
numberSize of the stored data in bytes
interface TransactionReceipt
Transaction receipt from a successful submission
Properties
blockHash
stringBlock hash containing the transaction
blockNumber
numberBlock number (if known)
txHash
stringTransaction hash
interface VerifyStoredOptions
Verification options for verifyStored.
Properties
block
numberBlock 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
numberOptional: 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 = BulletinTypedApitype CloudStorageEnvironment
Network keys with built-in presets in CloudStorageNetworks.
type CloudStorageEnvironment = keyof typeof CloudStorageNetworkstype CreateCloudStorageClientOptions
Options for CloudStorageClient.create.
One of two construction shapes is supported:
- Environment shorthand — pass an
environmentstring keyed byCloudStorageNetworks. Wires up the chain-client automatically. - Explicit network — pass
genesisHashanddescriptordirectly (e.g., spread from aCloudStorageNetworksentry, 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) => voidtype ProgressEvent
Combined progress event types
type ProgressEvent = ChunkProgressEvent | TransactionStatusEventtype 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
| Name | Value | Description |
|---|---|---|
Account | "Account" | Account-based authorization |
Preimage | "Preimage" | Preimage-based authorization (content-addressed) |
enum ChunkStatus
Chunk progress event types
Members
| Name | Value | Description |
|---|---|---|
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
| Name | Value | Description |
|---|---|---|
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
| Name | Value | Description |
|---|---|---|
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: ChunkerConfigDEFAULT_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: StoreOptionsHashAlgorithm
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: numberMAX_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: numberWaitFor
let WaitFor: { Finalized: "finalized"; InBlock: "in_block" }