@parity/product-sdk-cloud-storage 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,600 @@
1
+ import { BulletinTypedApi, AsyncBulletinClient, ClientConfig, StoreBuilder, AuthCallBuilder, CallBuilder } from '@parity/bulletin-sdk';
2
+ export { AsyncBulletinClient, AuthCallBuilder, AuthorizationScope, BulletinClientInterface, BulletinError, BulletinPreparer, BulletinTypedApi, CID, CallBuilder, Chunk, ChunkDetails, ChunkProgressEvent, ChunkStatus, ChunkedStoreResult, ChunkerConfig, ClientConfig, DEFAULT_CHUNKER_CONFIG, DEFAULT_CLIENT_CONFIG, DEFAULT_STORE_OPTIONS, DagManifest, ErrorCode, MAX_CHUNK_SIZE, MAX_FILE_SIZE, MockBulletinClient, MockClientConfig, MockOperation, ProgressCallback, ProgressEvent, StoreBuilder, StoreOptions, StoreResult, SubmitFn, TransactionReceipt, TransactionStatusEvent, TxStatus, WaitFor, calculateCid, cidFromBytes, cidToBytes, convertCid, estimateAuthorization, getContentHash, parseCid, reassembleChunks, resolveClientConfig, validateChunkSize } from '@parity/bulletin-sdk';
3
+ import { PolkadotSigner } from 'polkadot-api';
4
+ import { paseo_bulletin } from '@parity/product-sdk-descriptors/paseo-bulletin';
5
+ import { WaitFor, TxStatus } from '@parity/product-sdk-tx';
6
+ export { Environment } from '@parity/product-sdk-chain-client';
7
+
8
+ /**
9
+ * Known Cloud Storage networks.
10
+ *
11
+ * Each environment pairs its genesis hash with a per-environment PAPI descriptor.
12
+ */
13
+
14
+ interface CloudStorageNetwork {
15
+ /** Genesis hash of the underlying chain on this environment. */
16
+ genesisHash: `0x${string}`;
17
+ /** PAPI descriptor for typed API access. */
18
+ descriptor: typeof paseo_bulletin;
19
+ }
20
+ /**
21
+ * Cloud Storage network presets.
22
+ *
23
+ * Use these with {@link CloudStorageClient.create} when you want to be explicit
24
+ * about the network rather than passing an environment string. Reads go
25
+ * through the host's preimage subscription (container-only); no gateway
26
+ * URL is configured per network.
27
+ */
28
+ declare const CloudStorageNetworks: {
29
+ readonly paseo: {
30
+ readonly genesisHash: "0x8cfe6717dc4becfda2e13c488a1e2061ff2dfee96e7d031157f72d36716c0a22";
31
+ readonly descriptor: any;
32
+ };
33
+ };
34
+ /** Network keys with built-in presets in {@link CloudStorageNetworks}. */
35
+ type CloudStorageEnvironment = keyof typeof CloudStorageNetworks;
36
+
37
+ /** Typed API for the Cloud Storage (re-export from upstream BulletinTypedApi). */
38
+ type CloudStorageApi = BulletinTypedApi;
39
+
40
+ /** //TODO: Come back to this (code docs might need update)
41
+ * Authorization status for a Cloud Storage account.
42
+ *
43
+ * Returned by {@link checkAuthorization} as a pre-flight check before storing
44
+ * data. Consumers can use this to show "not authorized" or "insufficient quota"
45
+ * messages instead of letting the transaction fail mid-execution.
46
+ */
47
+ interface AuthorizationStatus {
48
+ /** Whether an authorization entry exists for this account. */
49
+ authorized: boolean;
50
+ /** Remaining transactions allowed. 0 if not authorized. */
51
+ remainingTransactions: number;
52
+ /** Remaining bytes allowed. 0n if not authorized. */
53
+ remainingBytes: bigint;
54
+ /** Block number when the authorization expires. 0 if not authorized. */
55
+ expiration: number;
56
+ }
57
+ /**
58
+ * Options for {@link CloudStorageClient.fetchBytes} / {@link CloudStorageClient.fetchJson}.
59
+ */
60
+ interface QueryOptions {
61
+ /**
62
+ * Timeout for the host preimage lookup subscription, in ms.
63
+ * Default: 30_000. Applied per lookup — for chunked content (DAG-PB
64
+ * manifest CIDs), the manifest fetch and each child chunk fetch
65
+ * each get this budget.
66
+ */
67
+ lookupTimeoutMs?: number;
68
+ /**
69
+ * When `true`, return the raw bytes for the requested CID without
70
+ * parsing or recursing into a DAG-PB manifest. Default: `false` — the
71
+ * client transparently reassembles chunked content so callers don't
72
+ * need to know whether a CID points at a single chunk or a manifest.
73
+ *
74
+ * Set this if you want to inspect the manifest itself, e.g., to read
75
+ * `unixfs.fileSize()` ahead of fetching, or to drive your own chunk
76
+ * pipeline.
77
+ */
78
+ noReassemble?: boolean;
79
+ }
80
+
81
+ /** A single matched entry from `TransactionStorage.Transactions`. */
82
+ interface ChainStoredEntry {
83
+ /** Block number where the transaction was included. */
84
+ block: number;
85
+ /** Index of the entry within the block's transactions array. */
86
+ index: number;
87
+ /** Size of the stored data in bytes (from chain metadata). */
88
+ size: number;
89
+ /** Number of chunks (1 for unchunked data, >1 for chunked + manifest). */
90
+ blockChunks: number;
91
+ }
92
+ /**
93
+ * Verification options for {@link verifyStored}.
94
+ */
95
+ interface VerifyStoredOptions {
96
+ /**
97
+ * Block number to look up. Pass the `blockNumber` returned from a prior
98
+ * `store(...).send()` for an O(1) lookup.
99
+ *
100
+ * If omitted, throws — full-chain scans are not supported because
101
+ * `RetentionPeriod` can be many days of blocks. Use `getEntries()` on
102
+ * `api.query.TransactionStorage.Transactions` directly if you need that.
103
+ */
104
+ block: number;
105
+ /**
106
+ * Optional: index within the block. When provided, narrows verification
107
+ * to that exact slot. Useful when re-checking a known `(block, index)`
108
+ * tuple from an earlier receipt.
109
+ */
110
+ index?: number;
111
+ }
112
+ /**
113
+ * Verify that a CID is recorded in the cloud storage (bulletin chain's `Transactions` storage)
114
+ * at the given block.
115
+ *
116
+ * Returns the matched entry (with block + index) when the CID's content
117
+ * hash and hashing algorithm both match a `Transactions[block]` entry.
118
+ * Returns `null` when no match is found at that block.
119
+ *
120
+ * @param api - Typed Cloud Storage API instance.
121
+ * @param cid - CIDv1 string to look up.
122
+ * @param options - Verification target (block number, optional index).
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * const receipt = await client.store(data).send();
127
+ * if (receipt.blockNumber !== undefined) {
128
+ * const entry = await verifyStored(client.api, receipt.cid!.toString(), {
129
+ * block: receipt.blockNumber,
130
+ * index: receipt.extrinsicIndex,
131
+ * });
132
+ * if (!entry) console.warn("CID not found in expected block — chain reorg?");
133
+ * }
134
+ * ```
135
+ */
136
+ declare function verifyStored(api: CloudStorageApi, cid: string, options: VerifyStoredOptions): Promise<ChainStoredEntry | null>;
137
+
138
+ /**
139
+ * Options for {@link CloudStorageClient.create}.
140
+ *
141
+ * One of two construction shapes is supported:
142
+ *
143
+ * - **Environment shorthand** — pass an `environment` string keyed by
144
+ * {@link CloudStorageNetworks}. Wires up the chain-client automatically.
145
+ * - **Explicit network** — pass `genesisHash` and `descriptor` directly
146
+ * (e.g., spread from a {@link CloudStorageNetworks} entry, or supply custom
147
+ * values for a private chain).
148
+ */
149
+ type CreateCloudStorageClientOptions = (CreateCloudStorageClientCommon & {
150
+ environment: CloudStorageEnvironment;
151
+ }) | (CreateCloudStorageClientCommon & {
152
+ genesisHash: `0x${string}`;
153
+ descriptor: (typeof CloudStorageNetworks)[CloudStorageEnvironment]["descriptor"];
154
+ });
155
+ interface CreateCloudStorageClientCommon {
156
+ /** Signer for transaction submission. Required — every store needs a signer. */
157
+ signer: PolkadotSigner;
158
+ /** Optional config forwarded to the upstream client. */
159
+ config?: Partial<ClientConfig>;
160
+ }
161
+ /**
162
+ * Ergonomic entry point for Cloud Storage operations.
163
+ *
164
+ * Wraps the upstream `@parity/bulletin-sdk` client (which handles
165
+ * chunking, DAG-PB manifests, CID calculation, and progress events) and adds:
166
+ *
167
+ * - **Network presets** via {@link CloudStorageClient.create} and {@link CloudStorageNetworks}.
168
+ * - **Read helpers** ({@link fetchBytes}, {@link fetchJson}) routed through
169
+ * the host's preimage subscription — upstream is upload-only and the SDK
170
+ * is container-only by design (no public-gateway fetches).
171
+ * - **Pre-flight authorization check** ({@link checkAuthorization}) for
172
+ * friendlier UX before submitting a store.
173
+ *
174
+ * For uploads, mirror upstream's fluent builders:
175
+ *
176
+ * ```ts
177
+ * const client = await CloudStorageClient.create({ environment: "paseo", signer });
178
+ * const result = await client.store(data).send();
179
+ * ```
180
+ *
181
+ * For chunked uploads with progress:
182
+ *
183
+ * ```ts
184
+ * const result = await client
185
+ * .store(largeFile)
186
+ * .withChunkSize(1 << 20)
187
+ * .withCallback((evt) => console.log(evt))
188
+ * .send();
189
+ * ```
190
+ */
191
+ declare class CloudStorageClient {
192
+ /** Underlying upstream client — exposed for power users. */
193
+ readonly inner: AsyncBulletinClient;
194
+ /** Typed CloudStorage API. */
195
+ readonly api: CloudStorageApi;
196
+ /** Lazy-resolved host-preimage query strategy, cached for the client lifetime. */
197
+ private queryStrategyPromise;
198
+ /** Constructed via {@link create} or {@link from}. */
199
+ private constructor();
200
+ /** Resolve and cache the host query strategy on first use. */
201
+ private resolveQuery;
202
+ /**
203
+ * Create a client from an environment shorthand or an explicit network.
204
+ *
205
+ * Environment form uses our `getChainAPI(env)` to resolve the typed API.
206
+ * Explicit form skips the environment lookup and lets you pass any
207
+ * genesis/descriptor combo.
208
+ *
209
+ * @example
210
+ * ```ts
211
+ * // Shorthand
212
+ * const client = await CloudStorageClient.create({ environment: "paseo", signer });
213
+ *
214
+ * // Explicit (custom network)
215
+ * const client = await CloudStorageClient.create({
216
+ * ...CloudStorageNetworks.paseo,
217
+ * signer,
218
+ * config: { defaultChunkSize: 1 << 20 },
219
+ * });
220
+ * ```
221
+ */
222
+ static create(options: CreateCloudStorageClientOptions): Promise<CloudStorageClient>;
223
+ /**
224
+ * Construct from a pre-built `AsyncBulletinClient` and PAPI typed API.
225
+ *
226
+ * Use this when you already own the connection lifecycle (BYOD setups,
227
+ * tests). The caller is responsible for calling `papiClient.destroy()`
228
+ * — this client's {@link destroy} only tears down the upstream's
229
+ * `onDestroy` hook.
230
+ */
231
+ static from(inner: AsyncBulletinClient, api: CloudStorageApi): CloudStorageClient;
232
+ /** Build a store transaction. See upstream `StoreBuilder` for chained options. */
233
+ store(data: Uint8Array): StoreBuilder;
234
+ /** Authorize an account to store data on the chain (sudo required on most networks). */
235
+ authorizeAccount(who: string, transactions: number, bytes: bigint): AuthCallBuilder;
236
+ /** Authorize content storage by hash (anyone can store; no fees). */
237
+ authorizePreimage(contentHash: Uint8Array, maxSize: bigint): AuthCallBuilder;
238
+ /** Renew a stored transaction by block + index. */
239
+ renew(block: number, index: number): CallBuilder;
240
+ /** Estimate the authorization (transactions + bytes) needed for `dataSize`. */
241
+ estimateAuthorization(dataSize: number): {
242
+ transactions: number;
243
+ bytes: number;
244
+ };
245
+ /**
246
+ * Fetch raw bytes for a CID via the host's preimage lookup.
247
+ *
248
+ * Container-only — outside a Polkadot Browser / Desktop host this
249
+ * throws {@link CloudStorageHostUnavailableError}. The chain stores
250
+ * content metadata (`content_hash`, size, codec) but the bytes
251
+ * themselves are surfaced through the host's preimage subscription.
252
+ *
253
+ * Use {@link verifyStored} if you only need to confirm a CID was
254
+ * recorded on-chain (no byte fetch).
255
+ */
256
+ fetchBytes(cid: string, options?: QueryOptions): Promise<Uint8Array>;
257
+ /** Fetch and parse JSON for a CID. */
258
+ fetchJson<T>(cid: string, options?: QueryOptions): Promise<T>;
259
+ /** Pre-flight: check whether `address` can store via Cloud Storage. */
260
+ checkAuthorization(address: string): Promise<AuthorizationStatus>;
261
+ /**
262
+ * Verify that a CID was recorded on-chain at the given block.
263
+ *
264
+ * Common pattern: pass `blockNumber` (and optionally `extrinsicIndex`)
265
+ * from a `store(...).send()` receipt to confirm the upload landed.
266
+ * See {@link verifyStored} for details.
267
+ */
268
+ verifyStored(cid: string, options: VerifyStoredOptions): Promise<ChainStoredEntry | null>;
269
+ /** Tear down the underlying connection. */
270
+ destroy(): Promise<void>;
271
+ }
272
+
273
+ /**
274
+ * Check whether an account is authorized to store data in Cloud Storage.
275
+ *
276
+ * Queries `TransactionStorage.Authorizations` for the given address and returns
277
+ * the raw authorization quota. Use this as a pre-flight check before calling
278
+ * {@link CloudStorageClient.store} to provide clear UX ("not authorized" / "insufficient quota")
279
+ * instead of letting the transaction fail mid-execution.
280
+ *
281
+ * The expiration block number is returned as-is — the chain enforces expiration
282
+ * at submission time, so callers can optionally compare against the current
283
+ * block for display purposes.
284
+ *
285
+ * @param api - Typed Cloud Storage API instance.
286
+ * @param address - SS58-encoded account address to check.
287
+ * @returns Authorization status with remaining quota.
288
+ *
289
+ * @example
290
+ * ```ts
291
+ * import { checkAuthorization } from "@parity/product-sdk-cloud-storage";
292
+ *
293
+ * const auth = await checkAuthorization(api, address);
294
+ * if (!auth.authorized) {
295
+ * console.error("Account is not authorized for cloud storage");
296
+ * } else if (auth.remainingBytes < BigInt(fileBytes.length)) {
297
+ * console.error(`Insufficient quota: ${auth.remainingBytes} bytes remaining`);
298
+ * }
299
+ * ```
300
+ *
301
+ * @see {@link CloudStorageClient.checkAuthorization} for the client method equivalent.
302
+ */
303
+ declare function checkAuthorization(api: CloudStorageApi, address: string): Promise<AuthorizationStatus>;
304
+ /**
305
+ * Options for {@link authorizeAccount}.
306
+ */
307
+ interface AuthorizeAccountOptions {
308
+ /**
309
+ * Wrap the extrinsic in `Sudo.sudo(...)` before submission. Default: `false`.
310
+ *
311
+ * Use `true` on networks where granting cloud storage authorization
312
+ * requires sudo permissions (most production / managed test networks).
313
+ * Use `false` (default) when the account self-authorizes — typical for
314
+ * local development chains.
315
+ */
316
+ viaSudo?: boolean;
317
+ /** When to resolve: `"best-block"` (default) or `"finalized"`. */
318
+ waitFor?: WaitFor;
319
+ /** Timeout in ms. Default: 300_000 (5 min). */
320
+ timeoutMs?: number;
321
+ /** Lifecycle status callback for UI progress. */
322
+ onStatus?: (status: TxStatus) => void;
323
+ }
324
+ /**
325
+ * Grant an account authorization to store data in Cloud Storage.
326
+ *
327
+ * Submits a `TransactionStorage.authorize_account` extrinsic, optionally
328
+ * wrapped in `Sudo.sudo(...)` for networks that require sudo to grant
329
+ * authorization. Mirrors the call shape of {@link CloudStorageClient.store} — top-level
330
+ * function, takes an explicit signer, returns a block hash on success.
331
+ *
332
+ * Pair with {@link checkAuthorization} for a typical "check, grant if
333
+ * insufficient, then upload" flow.
334
+ *
335
+ * ## Additive semantics — call once per authorization need
336
+ *
337
+ * `authorize_account` is **additive** within an unexpired authorization window
338
+ * for `AuthorizationScope::Account` (see `pallet-bulletin-transaction-storage`,
339
+ * `fn authorize`). Each successful call **adds** to the existing
340
+ * `transactions_allowance` and `bytes_allowance` rather than overwriting them.
341
+ *
342
+ * Implications for callers:
343
+ *
344
+ * - Calling this function twice with `(100, 1MB)` while the previous
345
+ * authorization is still active leaves the account with quota for `200`
346
+ * transactions and `2MB` — likely unintended.
347
+ * - **This function does NOT use `withRetry`.** Retrying a successful-but-
348
+ * acknowledgment-lost submission would double-grant the quota. Callers
349
+ * needing retry should wrap this function and use {@link checkAuthorization}
350
+ * to verify the post-state before retrying.
351
+ * - To "reset" a quota, let the existing authorization expire
352
+ * (`AuthorizationPeriod` blocks). The next call after expiry creates a fresh
353
+ * authorization rather than adding.
354
+ *
355
+ * Note: `AuthorizationScope::Preimage` uses `set` semantics in the same
356
+ * pallet. This helper is for account-scope authorization only.
357
+ *
358
+ * @param api - Typed Cloud Storage API instance.
359
+ * @param who - SS58-encoded account to authorize.
360
+ * @param transactions - Number of transactions to **add** to the account's allowance.
361
+ * @param bytes - Byte budget to **add** to the account's allowance.
362
+ * @param signer - Signer for the extrinsic. On `viaSudo: true` this must be the sudo key.
363
+ * @param options - Optional `viaSudo` flag plus standard submission controls.
364
+ * @returns Block hash where the extrinsic was included.
365
+ * @throws {ProductCloudStorageError} If `viaSudo: true` is requested but the chain has no `Sudo` pallet.
366
+ *
367
+ * @example Direct (account self-authorizes — local dev)
368
+ * ```ts
369
+ * import { authorizeAccount } from "@parity/product-sdk-cloud-storage";
370
+ *
371
+ * await authorizeAccount(api, address, 100, 100n * 1024n * 1024n, signer);
372
+ * ```
373
+ *
374
+ * @example Sudo-wrapped (managed test network)
375
+ * ```ts
376
+ * await authorizeAccount(api, userAddress, 100, 1_000_000n, sudoSigner, {
377
+ * viaSudo: true,
378
+ * });
379
+ * ```
380
+ *
381
+ * @see {@link checkAuthorization} for the read counterpart.
382
+ * @see {@link CloudStorageClient.authorizeAccount} for the client method equivalent.
383
+ */
384
+ declare function authorizeAccount(api: CloudStorageApi, who: string, transactions: number, bytes: bigint, signer: PolkadotSigner, options?: AuthorizeAccountOptions): Promise<{
385
+ blockHash: string;
386
+ }>;
387
+
388
+ /**
389
+ * Build a `PolkadotSigner` whose underlying signer is resolved on every call.
390
+ *
391
+ * `AsyncBulletinClient` takes a fixed `PolkadotSigner` at construction, but
392
+ * apps often build the Cloud Storage client before any account is selected. This
393
+ * wrapper defers signer resolution: each call to `signTx` / `signBytes`
394
+ * invokes `getSigner()` and forwards to the result. If the getter returns
395
+ * `null`, calls throw with a clear message.
396
+ *
397
+ * The `publicKey` field is *also* resolved lazily — accessing it before a
398
+ * signer is available throws. This means callers that read `publicKey`
399
+ * eagerly will fail fast with the same error rather than seeing a stale
400
+ * key from a previously-selected account.
401
+ *
402
+ * Account changes between calls are picked up automatically: each sign
403
+ * resolves the current signer.
404
+ */
405
+ declare function createLazySigner(getSigner: () => PolkadotSigner | null, onMissing?: string): PolkadotSigner;
406
+
407
+ /**
408
+ * Query strategy for Cloud Storage retrieval.
409
+ *
410
+ * The host manages the lookup via its preimage subscription API,
411
+ * which includes local caching and managed IPFS polling.
412
+ */
413
+ interface QueryStrategy {
414
+ kind: "host-lookup";
415
+ lookup: (cid: string, timeoutMs?: number) => Promise<Uint8Array>;
416
+ }
417
+ /**
418
+ * Determine the query strategy for Cloud Storage retrieval.
419
+ *
420
+ * Uses the host preimage lookup API which caches results and manages
421
+ * IPFS polling automatically.
422
+ *
423
+ * @returns The resolved query strategy.
424
+ * @throws {CloudStorageHostUnavailableError} If the host preimage manager is unavailable.
425
+ */
426
+ declare function resolveQueryStrategy(): Promise<QueryStrategy>;
427
+
428
+ /**
429
+ * Fetch raw bytes for a CID via the host's preimage lookup.
430
+ *
431
+ * Container-only by design: the Cloud Storage SDK does not retrieve content
432
+ * through public IPFS gateways. Inside a Polkadot Browser / Desktop
433
+ * container, the host's `preimageManager` provides a cached, polling-
434
+ * managed lookup that returns bytes when the underlying IPFS network
435
+ * makes them available. Outside a container, this throws
436
+ * {@link CloudStorageHostUnavailableError}.
437
+ *
438
+ * The underlying chain stores transaction *metadata* on-chain
439
+ * (`chunk_root`, `content_hash`, `size`, `cid_codec`, `hashing`) — the
440
+ * content bytes themselves live in IPFS and are surfaced through the
441
+ * host's preimage subscription, never via direct gateway fetch.
442
+ *
443
+ * To prove that a CID was stored on-chain (without fetching the bytes),
444
+ * use `verifyStored` from `verify.ts`.
445
+ *
446
+ * @param cid - CIDv1 string to fetch.
447
+ * @param options - Query options (`lookupTimeoutMs` for host).
448
+ * @throws {CloudStorageHostUnavailableError} If running outside a container.
449
+ */
450
+ declare function queryBytes(cid: string, options?: QueryOptions): Promise<Uint8Array>;
451
+ /**
452
+ * Fetch and parse JSON for a CID via the host's preimage lookup.
453
+ *
454
+ * Convenience wrapper over {@link queryBytes}.
455
+ */
456
+ declare function queryJson<T>(cid: string, options?: QueryOptions): Promise<T>;
457
+ /**
458
+ * Execute a query using a pre-resolved strategy.
459
+ *
460
+ * Exposed so `CloudStorageClient` can resolve the strategy once at
461
+ * construction time and reuse it across calls without re-detecting
462
+ * the host environment on every fetch.
463
+ *
464
+ * **Reassembly is automatic.** If `cid` carries the DAG-PB codec
465
+ * (`0x70`) — meaning the upload was chunked and a UnixFS manifest was
466
+ * created — this function recursively fetches each chunk via `strategy
467
+ * .lookup` and returns the concatenated bytes. Pass `noReassemble: true`
468
+ * to get the raw manifest bytes instead.
469
+ *
470
+ * For raw-codec CIDs (`0x55`, single-chunk content), the bytes returned
471
+ * by the host are returned directly — no parsing overhead.
472
+ */
473
+ declare function executeQuery(strategy: QueryStrategy, cid: string, options?: QueryOptions): Promise<Uint8Array>;
474
+
475
+ /**
476
+ * Hash algorithms supported by Cloud Storage.
477
+ *
478
+ * Values are multihash codes from the multicodec table.
479
+ */
480
+ declare const HashAlgorithm: {
481
+ /** BLAKE2b-256 — chain default. */
482
+ readonly Blake2b256: 45600;
483
+ /** SHA2-256. */
484
+ readonly Sha2_256: 18;
485
+ /** Keccak-256 — Ethereum compatibility. */
486
+ readonly Keccak256: 27;
487
+ };
488
+ type HashAlgorithm = (typeof HashAlgorithm)[keyof typeof HashAlgorithm];
489
+ /**
490
+ * CID codecs supported by Cloud Storage.
491
+ */
492
+ declare const CidCodec: {
493
+ /** Raw binary — default for single-chunk data. */
494
+ readonly Raw: 85;
495
+ /** DAG-PB — used for multi-chunk manifests / IPFS UnixFS. */
496
+ readonly DagPb: 112;
497
+ /** DAG-CBOR — alternative DAG encoding. */
498
+ readonly DagCbor: 113;
499
+ };
500
+ type CidCodec = (typeof CidCodec)[keyof typeof CidCodec];
501
+ /**
502
+ * Reconstruct a CIDv1 from a `0x`-prefixed 32-byte hex hash.
503
+ *
504
+ * Useful when reading on-chain `TransactionInfo.content_hash` and you need
505
+ * the CID to look up content via an IPFS gateway.
506
+ *
507
+ * @param hexHash - 66-char `0x`-prefixed hex of a 32-byte digest.
508
+ * @param hashCode - Multihash code (default: blake2b-256).
509
+ * @param codec - Multicodec code (default: raw).
510
+ */
511
+ declare function hashToCid(hexHash: `0x${string}`, hashCode?: HashAlgorithm, codec?: CidCodec): string;
512
+ /**
513
+ * Extract the 32-byte content hash digest from a CIDv1 and return it as a
514
+ * `0x`-prefixed hex string.
515
+ *
516
+ * Useful for matching a CID against on-chain `TransactionInfo.content_hash`.
517
+ */
518
+ declare function cidToPreimageKey(cid: string): `0x${string}`;
519
+
520
+ /**
521
+ * Cloud Storage error types.
522
+ *
523
+ * Two error families coexist:
524
+ *
525
+ * 1. **Upstream SDK errors** — `BulletinError` and `ErrorCode` from
526
+ * `@parity/bulletin-sdk` cover upload/store/authorization failures
527
+ * surfaced by `AsyncBulletinClient`. Each carries `code`, `retryable`,
528
+ * and `recoveryHint`.
529
+ * 2. **Read-side errors** declared here — host preimage availability /
530
+ * lookup timeouts / interrupts, plus CID format problems, surfaced by
531
+ * our retrieval helpers (`fetchBytes`, `fetchJson`, `verifyStored`).
532
+ *
533
+ * Catch upstream errors with `instanceof BulletinError`. Catch our read-side
534
+ * errors with `instanceof ProductCloudStorageError` (or the specific subclass).
535
+ */
536
+
537
+ /**
538
+ * Base class for read-side errors raised by `@parity/product-sdk-cloud-storage`.
539
+ *
540
+ * Distinct from upstream `BulletinError` which covers upload/store failures.
541
+ */
542
+ declare class ProductCloudStorageError extends Error {
543
+ constructor(message: string, options?: ErrorOptions);
544
+ }
545
+ /**
546
+ * The host preimage API is unavailable.
547
+ *
548
+ * Thrown when cloud storage operations require the host container but it's not
549
+ * available. This typically means the SDK is running outside Polkadot
550
+ * Browser / Desktop. The Cloud Storage SDK is container-only by design — see
551
+ * the README for the rationale.
552
+ */
553
+ declare class CloudStorageHostUnavailableError extends ProductCloudStorageError {
554
+ constructor(operation: "upload" | "query");
555
+ }
556
+ /**
557
+ * The host preimage lookup timed out.
558
+ *
559
+ * The host was unable to retrieve the requested content within the timeout
560
+ * period. The content may still become available later.
561
+ */
562
+ declare class CloudStorageLookupTimeoutError extends ProductCloudStorageError {
563
+ /** The CID that was being looked up. */
564
+ readonly cid: string;
565
+ /** The timeout duration in milliseconds. */
566
+ readonly timeoutMs: number;
567
+ constructor(cid: string, timeoutMs: number);
568
+ }
569
+ /**
570
+ * The host interrupted the preimage lookup.
571
+ *
572
+ * The host terminated the lookup subscription, typically after repeated
573
+ * failures or when the host determines the content is unavailable.
574
+ */
575
+ declare class CloudStorageLookupInterruptedError extends ProductCloudStorageError {
576
+ /** The CID that was being looked up. */
577
+ readonly cid: string;
578
+ constructor(cid: string);
579
+ }
580
+ /**
581
+ * Invalid CID format or version.
582
+ */
583
+ declare class CloudStorageCidError extends ProductCloudStorageError {
584
+ /** The invalid CID string, if available. */
585
+ readonly cid?: string;
586
+ constructor(message: string, cid?: string);
587
+ }
588
+ /**
589
+ * Failed to check authorization status for an account.
590
+ *
591
+ * Wraps RPC or query errors that occur when checking if an account
592
+ * is authorized to store data in Cloud Storage.
593
+ */
594
+ declare class CloudStorageAuthorizationError extends ProductCloudStorageError {
595
+ /** The address that was being checked. */
596
+ readonly address: string;
597
+ constructor(address: string, cause?: unknown);
598
+ }
599
+
600
+ export { type AuthorizationStatus, type AuthorizeAccountOptions, type ChainStoredEntry, CidCodec, type CloudStorageApi, CloudStorageAuthorizationError, CloudStorageCidError, CloudStorageClient, type CloudStorageEnvironment, CloudStorageHostUnavailableError, CloudStorageLookupInterruptedError, CloudStorageLookupTimeoutError, type CloudStorageNetwork, CloudStorageNetworks, type CreateCloudStorageClientOptions, HashAlgorithm, ProductCloudStorageError, type QueryOptions, type QueryStrategy, type VerifyStoredOptions, authorizeAccount, checkAuthorization, cidToPreimageKey, createLazySigner, executeQuery, hashToCid, queryBytes, queryJson, resolveQueryStrategy, verifyStored };