@mysten/walrus 1.1.5 → 1.1.6

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @mysten/walrus
2
2
 
3
+ ## 1.1.6
4
+
5
+ ### Patch Changes
6
+
7
+ - f7de3e5: Restore docs in published tarballs.
8
+ - Updated dependencies [f7de3e5]
9
+ - @mysten/bcs@2.0.5
10
+ - @mysten/sui@2.16.2
11
+ - @mysten/utils@0.3.3
12
+ - @mysten/walrus-wasm@0.2.2
13
+
3
14
  ## 1.1.5
4
15
 
5
16
  ### Patch Changes
package/docs/index.md ADDED
@@ -0,0 +1,572 @@
1
+ # Walrus SDK
2
+
3
+ > Store and retrieve blobs on Walrus decentralized storage using the TypeScript SDK.
4
+
5
+ The Walrus TypeScript SDK works directly with Walrus storage nodes or with the Walrus upload relay.
6
+ When you use the Walrus SDK without an upload relay, reading and writing Walrus blobs requires many
7
+ requests (approximately 2200 to write a blob and approximately 335 to read a blob). The upload relay
8
+ reduces the number of requests needed to write a blob, but reads through the Walrus SDK still
9
+ require many requests. For many applications, using publishers and aggregators is recommended, but
10
+ the TypeScript SDK is useful when building applications where the application needs to directly
11
+ interact with Walrus, or when users need to pay for their own storage directly.
12
+
13
+ The Walrus SDK exposes high-level methods for reading and writing blobs, as well as lower-level
14
+ methods for the individual steps in the process. You can use the lower-level methods to implement
15
+ more complex flows when you want more control over optimization.
16
+
17
+ ## Installation
18
+
19
+ ```bash npm2yarn
20
+ npm install --save @mysten/walrus @mysten/sui
21
+ ```
22
+
23
+ ## Setup
24
+
25
+ To use the Walrus SDK, you need to create a client from the TypeScript SDK and extend it with the
26
+ Walrus SDK.
27
+
28
+ ```ts
29
+
30
+ const client = new SuiGrpcClient({
31
+ network: 'testnet',
32
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
33
+ }).$extend(walrus());
34
+ ```
35
+
36
+ The Walrus SDK includes all the relevant package and object IDs needed for connecting to Testnet.
37
+ You can also manually configure the Walrus SDK to use a different set of IDs, allowing you to
38
+ connect to a different network or updated deployment of the Walrus contracts.
39
+
40
+ ```ts
41
+
42
+ const client = new SuiGrpcClient({
43
+ network: 'testnet',
44
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
45
+ }).$extend(
46
+ walrus({
47
+ packageConfig: {
48
+ systemObjectId: '0x98ebc47370603fe81d9e15491b2f1443d619d1dab720d586e429ed233e1255c1',
49
+ stakingPoolId: '0x20266a17b4f1a216727f3eef5772f8d486a9e3b5e319af80a5b75809c035561d',
50
+ },
51
+ }),
52
+ );
53
+ ```
54
+
55
+ Some environments require you to customize how data is fetched:
56
+
57
+ ```ts
58
+
59
+ const client = new SuiGrpcClient({
60
+ network: 'testnet',
61
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
62
+ }).$extend(
63
+ walrus({
64
+ storageNodeClientOptions: {
65
+ fetch: (url, options) => {
66
+ console.log('fetching', url);
67
+ return fetch(url, options);
68
+ },
69
+ timeout: 60_000,
70
+ },
71
+ }),
72
+ );
73
+ ```
74
+
75
+ You can use this approach to implement a fetch function with custom timeouts, rate limits, retry
76
+ logic, or any other desired behavior.
77
+
78
+ ## `WalrusFile` API
79
+
80
+ The `WalrusFile` API provides a higher-level abstraction so that applications do not need to worry
81
+ about how data is stored in Walrus. It handles data stored directly in blobs and data stored in
82
+ quilts, but might expand to cover other storage patterns in the future.
83
+
84
+ ### Reading files
85
+
86
+ To read files, use the `getFiles` method. This method accepts both blob IDs and quilt IDs, and
87
+ returns a `WalrusFile`.
88
+
89
+ Read files in batches when possible, which allows the client to be more efficient when loading
90
+ multiple files from the same quilt.
91
+
92
+ ```ts
93
+ const [file1, file2] = await client.walrus.getFiles({ ids: [anyBlobId, orQuiltId] });
94
+ ```
95
+
96
+ A `WalrusFile` works like a `Response` object from the `fetch` API:
97
+
98
+ ```ts
99
+ // get contents as a Uint8Array
100
+ const bytes = await file1.bytes();
101
+ // Parse the contents as a `utf-8` string
102
+ const text = await file1.text();
103
+ // Parse the contents as JSON
104
+ const json = await file2.json();
105
+ ```
106
+
107
+ A `WalrusFile` might also have `identifier` and `tags` properties if the file was stored in a quilt.
108
+
109
+ ```ts
110
+ const identifier: string | null = await file1.getIdentifier();
111
+ const tags: Record<string, string> = await file1.getTags();
112
+ ```
113
+
114
+ #### `WalrusBlob`
115
+
116
+ You can also get a `WalrusBlob` instead of a `WalrusFile` if you have the `blobId`:
117
+
118
+ ```ts
119
+ const blob = await client.walrus.getBlob({ blobId });
120
+ ```
121
+
122
+ If the blob is a quilt, you can read the files in the quilt:
123
+
124
+ ```ts
125
+ // Get all files:
126
+ const files = await blob.files();
127
+ // Get files by identifier
128
+ const [readme] = await blob.files({ identifiers: ['README.md'] });
129
+ // Get files by tag
130
+ const textFiles = await blob.files({ tags: [{ 'content-type': 'text/plain' }] });
131
+ // Get files by quilt id
132
+ const filesById = await blob.files({ ids: [quiltID] });
133
+ ```
134
+
135
+ ### Writing files
136
+
137
+ You can also construct a `WalrusFile` from a `Uint8Array`, `Blob`, or a `string`, which you can then
138
+ store on Walrus:
139
+
140
+ ```ts
141
+ const file1 = WalrusFile.from({
142
+ contents: new Uint8Array([1, 2, 3]),
143
+ identifier: 'file1.bin',
144
+ });
145
+ const file2 = WalrusFile.from({
146
+ contents: new Blob([new Uint8Array([1, 2, 3])]),
147
+ identifier: 'file2.bin',
148
+ });
149
+ const file3 = WalrusFile.from({
150
+ contents: new TextEncoder().encode('Hello from the TS SDK!!!\n'),
151
+ identifier: 'README.md',
152
+ tags: {
153
+ 'content-type': 'text/plain',
154
+ },
155
+ });
156
+ ```
157
+
158
+ After you have your files, use the `writeFiles` method to write them to Walrus.
159
+
160
+ Along with the files, you also need to provide a `Signer` instance that signs and pays for the
161
+ transaction and storage fees. The signer's address needs sufficient SUI to cover the transactions
162
+ that register the blob and certify its availability after upload. The signer must own sufficient WAL
163
+ to pay to store the blob for the specified number of epochs, as well as the write fee for writing
164
+ the blob.
165
+
166
+ The exact costs depend on the size of the blobs, as well as the current gas and storage prices.
167
+
168
+ ```ts
169
+ const results: {
170
+ id: string;
171
+ blobId: string;
172
+ blobObject: Blob.$inferType;
173
+ }[] = await client.walrus.writeFiles({
174
+ files: [file1, file2, file3],
175
+ epochs: 3,
176
+ deletable: true,
177
+ signer: keypair,
178
+ });
179
+ ```
180
+
181
+ The provided files are all written into a single quilt. Future versions of the SDK might optimize
182
+ how files are stored to be more efficient by splitting files into multiple quilts.
183
+
184
+ The current quilt encoding is less efficient for single files, so writing multiple files together is
185
+ recommended when possible. Writing raw blobs directly is also possible using the `writeBlob` API
186
+ described below.
187
+
188
+ #### Writing files in browser environments
189
+
190
+ When the transactions to upload a blob are signed by a wallet in a browser, some wallets use popups
191
+ to prompt you for a signature. If the popups are not opened in direct response to a user
192
+ interaction, the browser might block them.
193
+
194
+ To avoid this, execute the transactions that register and certify the blob in separate event
195
+ handlers by creating separate buttons for each step.
196
+
197
+ The `client.writeFilesFlow` method returns an object with a set of methods that break the write flow
198
+ into several smaller steps:
199
+
200
+ 1. `encode`: Encodes the files and generates a `blobId`.
201
+ 2. `register`: Returns a transaction that registers the blob onchain.
202
+ 3. `upload`: Uploads the data to storage nodes.
203
+ 4. `certify`: Returns a transaction that certifies the blob onchain.
204
+ 5. `listFiles`: Returns a list of the created files.
205
+
206
+ The following simplified example shows the core API usage with separate user interactions:
207
+
208
+ ```tsx
209
+ // Step 1: Create and encode the flow (can be done immediately when file is selected)
210
+ const flow = client.walrus.writeFilesFlow({
211
+ files: [
212
+ WalrusFile.from({
213
+ contents: new Uint8Array(fileData),
214
+ identifier: 'my-file.txt',
215
+ }),
216
+ ],
217
+ });
218
+
219
+ await flow.encode();
220
+
221
+ // Step 2: Register the blob (triggered by user clicking a register button after the encode step)
222
+ async function handleRegister() {
223
+ const registerTx = flow.register({
224
+ epochs: 3,
225
+ owner: currentAccount.address,
226
+ deletable: true,
227
+ });
228
+ const result = await signAndExecuteTransaction({ transaction: registerTx });
229
+
230
+ // Check transaction status
231
+ if (result.$kind === 'FailedTransaction') {
232
+ throw new Error(`Registration failed: ${result.FailedTransaction.status.error?.message}`);
233
+ }
234
+
235
+ // Step 3: Upload the data to storage nodes
236
+ // This can be done immediately after the register step, or as a separate step the user initiates
237
+ await flow.upload({ digest: result.Transaction.digest });
238
+ }
239
+
240
+ // Step 4: Certify the blob (triggered by user clicking a certify button after the blob is uploaded)
241
+ async function handleCertify() {
242
+ const certifyTx = flow.certify();
243
+
244
+ const result = await signAndExecuteTransaction({ transaction: certifyTx });
245
+
246
+ // Check transaction status
247
+ if (result.$kind === 'FailedTransaction') {
248
+ throw new Error(`Certification failed: ${result.FailedTransaction.status.error?.message}`);
249
+ }
250
+
251
+ // Step 5: Get the new files
252
+ const files = await flow.listFiles();
253
+ console.log('Uploaded files', files);
254
+ }
255
+ ```
256
+
257
+ This approach ensures that each transaction signing step is separated into different user
258
+ interactions, allowing wallet popups to work properly without being blocked by the browser.
259
+
260
+ ### Running the full flow
261
+
262
+ If you do not need separate user interactions for each step, use `run()` to execute the full
263
+ pipeline as an async iterator.
264
+
265
+ ```ts
266
+ const flow = client.walrus.writeBlobFlow({ blob });
267
+
268
+ for await (const step of flow.run({ signer, epochs: 3, deletable: true })) {
269
+ await db.save(fileId, step); // persist for crash recovery
270
+ }
271
+ ```
272
+
273
+ The flow also provides `executeRegister` and `executeCertify` methods that handle signing and return
274
+ typed step results:
275
+
276
+ ```ts
277
+ const flow = client.walrus.writeBlobFlow({ blob });
278
+ const enc = await flow.encode();
279
+ const reg = await flow.executeRegister({ signer, epochs: 3, deletable: true, owner: address });
280
+ const up = await flow.upload({ digest: reg.txDigest });
281
+ const cert = await flow.executeCertify({ signer });
282
+ ```
283
+
284
+ #### Resuming uploads
285
+
286
+ Each step executed by `run()` produces a `WriteBlobStep` that you can persist for crash recovery. To
287
+ resume an upload after a crash, pass a saved `WriteBlobStep` as `resume`. The flow skips completed
288
+ steps, validates the `blobId`, and only uploads slivers that are not already stored:
289
+
290
+ ```ts
291
+ const saved = await db.load(fileId);
292
+ const flow = client.walrus.writeBlobFlow({ blob, resume: saved });
293
+
294
+ for await (const step of flow.run({ signer, epochs: 3, deletable: true })) {
295
+ await db.save(fileId, step);
296
+ }
297
+ ```
298
+
299
+ ## Using an upload relay
300
+
301
+ Writing blobs directly from a client requires many requests to write data to all the storage nodes.
302
+ An upload relay offloads the work of these writes to a server, reducing complexity for the client.
303
+
304
+ To use an upload relay, add the `uploadRelay` option when adding the Walrus extension:
305
+
306
+ ```ts
307
+ const client = new SuiGrpcClient({
308
+ network: 'testnet',
309
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
310
+ }).$extend(
311
+ walrus({
312
+ uploadRelay: {
313
+ host: 'https://upload-relay.testnet.walrus.space',
314
+ sendTip: {
315
+ max: 1_000,
316
+ },
317
+ },
318
+ }),
319
+ );
320
+ ```
321
+
322
+ The `host` option is required and indicates the URL for your upload relay. Upload relays might
323
+ require a tip to cover the cost of writing the blob. You can configure a maximum tip (paid in MIST)
324
+ and the `WalrusClient` automatically determines the required tip for your upload relay. You can also
325
+ manually configure the tip as shown below.
326
+
327
+ Find the tip required by an upload relay using the `tip-config` endpoint (for example,
328
+ `https://upload-relay.testnet.walrus.space/v1/tip-config`). The tip is either a `const` or a
329
+ `linear` type.
330
+
331
+ ### `const` tip
332
+
333
+ A `const` tip sends a fixed amount for each blob written to the upload relay.
334
+
335
+ ```ts
336
+ const client = new SuiGrpcClient({
337
+ network: 'testnet',
338
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
339
+ }).$extend(
340
+ walrus({
341
+ uploadRelay: {
342
+ host: 'https://upload-relay.testnet.walrus.space',
343
+ sendTip: {
344
+ address: '0x123...',
345
+ kind: {
346
+ const: 105,
347
+ },
348
+ },
349
+ },
350
+ }),
351
+ );
352
+ ```
353
+
354
+ ### `linear` tip
355
+
356
+ A `linear` tip sends a fixed amount for each blob written to the upload relay, plus a multiplier
357
+ based on the size of the blob.
358
+
359
+ ```ts
360
+ const client = new SuiGrpcClient({
361
+ network: 'testnet',
362
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
363
+ }).$extend(
364
+ walrus({
365
+ uploadRelay: {
366
+ host: 'https://upload-relay.testnet.walrus.space',
367
+ sendTip: {
368
+ address: '0x123...',
369
+ kind: {
370
+ linear: {
371
+ base: 105,
372
+ perEncodedKib: 10,
373
+ },
374
+ },
375
+ },
376
+ },
377
+ }),
378
+ );
379
+ ```
380
+
381
+ ## Interacting with blobs directly
382
+
383
+ If you do not want to use the `WalrusFile` abstractions, use the `readBlob` and `writeBlob` APIs
384
+ directly.
385
+
386
+ ### Reading blobs
387
+
388
+ The `readBlob` method reads a blob given the `blobId` and returns a `Uint8Array` containing the blob
389
+ content:
390
+
391
+ ```ts
392
+ const blob = await client.walrus.readBlob({ blobId });
393
+ ```
394
+
395
+ ### Writing blobs
396
+
397
+ The `writeBlob` method writes a blob (as a `Uint8Array`) to Walrus. You need to specify how long the
398
+ blob should be stored for and whether the blob should be deletable.
399
+
400
+ ```ts
401
+ const file = new TextEncoder().encode('Hello from the TS SDK!!!\n');
402
+
403
+ const { blobId } = await client.walrus.writeBlob({
404
+ blob: file,
405
+ deletable: false,
406
+ epochs: 3,
407
+ signer: keypair,
408
+ });
409
+ ```
410
+
411
+ `writeBlob` and `writeFiles` also support `onStep` and `resume` for crash-recoverable uploads:
412
+
413
+ ```ts
414
+ const { blobId } = await client.walrus.writeBlob({
415
+ blob: file,
416
+ deletable: true,
417
+ epochs: 3,
418
+ signer: keypair,
419
+ onStep: (step) => db.save(fileId, step),
420
+ resume: await db.load(fileId), // pass a previously saved step to resume
421
+ });
422
+ ```
423
+
424
+ ## Error handling
425
+
426
+ The SDK exports all the error classes for different types of errors that can be thrown. Walrus is a
427
+ fault-tolerant distributed system where many types of errors can be recovered from. During epoch
428
+ changes, the data cached in the `WalrusClient` can become invalid. Errors that result from this
429
+ situation extend the `RetryableWalrusClientError` class.
430
+
431
+ You can check for these errors and reset the client before retrying:
432
+
433
+ ```ts
434
+
435
+ if (error instanceof RetryableWalrusClientError) {
436
+ client.walrus.reset();
437
+
438
+ /* retry your operation */
439
+ }
440
+ ```
441
+
442
+ `RetryableWalrusClientError` errors are not guaranteed to succeed after resetting the client and
443
+ retrying, but this pattern handles some edge cases.
444
+
445
+ High-level methods like `readBlob` already handle various error cases and automatically retry when
446
+ encountering these errors, as well as handling cases where only a subset of nodes need to respond
447
+ successfully to read or publish a blob.
448
+
449
+ When using the lower-level methods to build your own read or publish flows, understand the number of
450
+ shards and slivers that need to be successfully written or read for your operation to succeed.
451
+ Gracefully handle cases where some nodes might be in a bad state.
452
+
453
+ ### Network errors
454
+
455
+ Walrus handles some nodes being down, and the SDK only throws errors when it cannot read from or
456
+ write to enough storage nodes. When troubleshooting problems, figuring out what went wrong can be
457
+ challenging because you do not see all the individual network errors.
458
+
459
+ Pass an `onError` option in the `storageNodeClientOptions` to get the individual errors from failed
460
+ requests:
461
+
462
+ ```ts
463
+ const client = new SuiGrpcClient({
464
+ network: 'testnet',
465
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
466
+ }).$extend(
467
+ walrus({
468
+ storageNodeClientOptions: {
469
+ onError: (error) => console.log(error),
470
+ },
471
+ }),
472
+ );
473
+ ```
474
+
475
+ ## Configuring network requests
476
+
477
+ Reading and writing blobs directly from storage nodes requires many requests. The Walrus SDK issues
478
+ all requests needed to complete these operations, but does not handle all the complexities a robust
479
+ aggregator or publisher might encounter.
480
+
481
+ By default, all requests use the global `fetch` for whatever runtime the SDK runs in.
482
+
483
+ This does not impose any limitations on concurrency, and is subject to default timeouts and behavior
484
+ defined by your runtime. To customize how requests are made, provide a custom `fetch` method:
485
+
486
+ ```ts
487
+
488
+ const client = new SuiGrpcClient({
489
+ network: 'testnet',
490
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
491
+ }).$extend(
492
+ walrus({
493
+ storageNodeClientOptions: {
494
+ timeout: 60_000,
495
+ fetch: (url, init) => {
496
+ // Some casting may be required because undici types may not exactly match the @node/types types
497
+ return fetch(url as RequestInfo, {
498
+ ...(init as RequestInit),
499
+ dispatcher: new Agent({
500
+ connectTimeout: 60_000,
501
+ }),
502
+ }) as unknown as Promise<Response>;
503
+ },
504
+ },
505
+ }),
506
+ );
507
+ ```
508
+
509
+ ## Loading the WASM module in Vite or client-side apps
510
+
511
+ The Walrus SDK requires WASM bindings to encode and decode blobs. When running in Node.js or Bun,
512
+ and with some bundlers, this works without any additional configuration.
513
+
514
+ In some cases, you might need to manually specify where the SDK loads the WASM bindings from.
515
+
516
+ In Vite, get the URL for the WASM bindings by importing the WASM file with a `?url` suffix, then
517
+ pass it into the Walrus client:
518
+
519
+ ```ts
520
+
521
+ const client = new SuiGrpcClient({
522
+ network: 'testnet',
523
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
524
+ }).$extend(
525
+ walrus({
526
+ wasmUrl: walrusWasmUrl,
527
+ }),
528
+ );
529
+ ```
530
+
531
+ If you are unable to get a URL for the WASM file in your bundler or build system, you can self-host
532
+ the WASM bindings or load them from a CDN:
533
+
534
+ ```ts
535
+ const client = new SuiGrpcClient({
536
+ network: 'testnet',
537
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
538
+ }).$extend(
539
+ walrus({
540
+ wasmUrl: 'https://unpkg.com/@mysten/walrus-wasm@latest/web/walrus_wasm_bg.wasm',
541
+ }),
542
+ );
543
+ ```
544
+
545
+ In Next.js, when using Walrus in API routes, you might need to tell Next.js to skip bundling for the
546
+ Walrus packages:
547
+
548
+ ```ts
549
+ // next.config.ts
550
+ const nextConfig: NextConfig = {
551
+ serverExternalPackages: ['@mysten/walrus', '@mysten/walrus-wasm'],
552
+ };
553
+ ```
554
+
555
+ ## Known fetch limitations
556
+
557
+ - Some nodes can be slow to respond. When running in Node.js, the default `connectTimeout` is 10
558
+ seconds and can cause request timeouts.
559
+ - In Bun, the `abort` signal stops requests from responding, but the requests still wait for
560
+ completion before their promises reject.
561
+
562
+ ## Full API
563
+
564
+ For a complete overview of the available methods on the `WalrusClient`, reference the
565
+ [TypeDocs](/typedoc/classes/_mysten_walrus.WalrusClient.html).
566
+
567
+ ## Examples
568
+
569
+ There are a number of
570
+ [examples you can reference](https://github.com/MystenLabs/ts-sdks/tree/main/packages/walrus/examples)
571
+ in the `ts-sdks` repository that show things like building aggregators and publishers with the
572
+ Walrus SDK.
@@ -0,0 +1,4 @@
1
+ # Walrus
2
+ > Publish and Read blobs directly from walrus storage nodes
3
+
4
+ - [Walrus SDK](..md): Store and retrieve blobs on Walrus decentralized storage using the TypeScript SDK.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten/walrus",
3
- "version": "1.1.5",
3
+ "version": "1.1.6",
4
4
  "private": false,
5
5
  "description": "Walrus SDK",
6
6
  "license": "Apache-2.0",
@@ -46,12 +46,12 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "dataloader": "^2.2.3",
49
- "@mysten/utils": "^0.3.2",
50
- "@mysten/bcs": "^2.0.4",
51
- "@mysten/walrus-wasm": "^0.2.1"
49
+ "@mysten/bcs": "^2.0.5",
50
+ "@mysten/utils": "^0.3.3",
51
+ "@mysten/walrus-wasm": "^0.2.2"
52
52
  },
53
53
  "peerDependencies": {
54
- "@mysten/sui": "^2.16.1"
54
+ "@mysten/sui": "^2.16.2"
55
55
  },
56
56
  "scripts": {
57
57
  "clean": "rm -rf tsconfig.tsbuildinfo ./dist",