@solana/web3.js 2.0.0-experimental.fe07532 → 2.0.0-experimental.ffeddf6

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/README.md CHANGED
@@ -12,88 +12,1156 @@
12
12
  [semantic-release-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
13
13
  [semantic-release-url]: https://github.com/semantic-release/semantic-release
14
14
 
15
- # Experimental Solana JavaScript SDK
15
+ # Solana JavaScript SDK Technology Preview
16
16
 
17
- Use this to interact with accounts and programs on the Solana network through the Solana [JSON-RPC API](https://docs.solana.com/apps/jsonrpc-api).
17
+ If you build JavaScript applications on Solana, it’s likely you’ve worked with `@solana/web3.js` or a library powered by it. With 400K+ weekly downloads on npm, it’s the most-used library in the ecosystem for building program clients, web applications, block explorers, and more.
18
+
19
+ Here’s an example of a common code snippet from `@solana/web3.js`:
20
+
21
+ ```tsx
22
+ const connection = new Connection('https://api.mainnet-beta.solana.com');
23
+ const instruction = SystemProgram.transfer({ fromPubkey, toPubkey, lamports });
24
+ const transaction = new Transaction().add(instruction);
25
+ await sendAndConfirmTransaction(connection, transaction, [payer]);
26
+ ```
27
+
28
+ In response to your feedback, we began a process of modernizing the library to prepare for the next generation of Solana applications. A Technology Preview of the new web3.js is now available for you to evaluate.
18
29
 
19
30
  **This library is experimental**. It is unsuitable for production use, because the API is unstable and may change without warning. If you want to build a production Solana application, use the [1.x branch](https://www.npmjs.com/package/@solana/web3.js).
20
31
 
21
32
  ## Installation
22
33
 
23
- ### For use in Node.js, React Native, or a web application
34
+ ### For use in Node.js or a web application
24
35
 
25
36
  ```shell
26
- npm install --save @solana/web3.js@experimental
37
+ npm install --save @solana/web3.js@ts
27
38
  ```
28
39
 
29
40
  ### For use in a browser, without a build system
30
41
 
31
42
  ```html
32
43
  <!-- Development (debug mode, unminified) -->
33
- <script src="https://unpkg.com/@solana/web3.js@experimental/dist/index.development.js"></script>
44
+ <script src="https://unpkg.com/@solana/web3.js@ts/dist/index.development.js"></script>
34
45
 
35
46
  <!-- Production (minified) -->
36
- <script src="https://unpkg.com/@solana/web3.js@experimental/dist/index.production.min.js"></script>
47
+ <script src="https://unpkg.com/@solana/web3.js@ts/dist/index.production.min.js"></script>
48
+ ```
49
+
50
+ What follows is an overview of *why* the library was re-engineered, what changes have been introduced, and how the JavaScript landscape might look across Solana in the near future.
51
+
52
+ # Community feedback in action
53
+
54
+ We’re grateful to all of you for communicating the pain points you’ve experienced when developing Solana applications with web3.js. We’ve heard you loud and clear.
55
+
56
+ ## Tree-shaking
57
+
58
+ The object-oriented design of the web3.js (1.x) API prevents optimizing compilers from being able to “tree-shake” unused code from your production builds. No matter how much of the web3.js API you use in your application, you have to package all of it.
59
+
60
+ Read more about tree-shaking here:
61
+
62
+ - [Mozilla Developer Docs: Tree Shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking)
63
+ - [WebPack Docs: Tree Shaking](https://webpack.js.org/guides/tree-shaking/)
64
+ - [Web.Dev Blog Article: Reduce JavaScript Payloads with Tree Shaking](https://web.dev/articles/reduce-javascript-payloads-with-tree-shaking)
65
+
66
+ One example of an API that can’t be tree-shaken is the `Connection` class. It has dozens of methods, but because it’s a *class* you have no choice but to include every method in your application’s final bundle, no matter how many you *actually* use.
67
+
68
+ Needlessly large JavaScript bundles can cause issues with deployments to cloud compute providers like Cloudflare or AWS Lambda. They also impact webapp startup performance because of longer download and JavaScript parse times.
69
+
70
+ ## Opinionated
71
+
72
+ Depending on your use case and your tolerance for certain application behaviours, you may be willing to configure your application to make a different set of tradeoffs than another developer. The default tradeoffs that we codify into the web3.js API on the other hand have to work for as large a population as possible, in the common case.
73
+
74
+ The inability to customize web3.js has been a source of frustration for some:
75
+
76
+ - The Mango team wanted to customize the transaction confirmation strategy, but all of that functionality is hidden away behind `confirmTransaction` – a static method of `Connection`. [Here’s the code for `confirmTransaction` on GitHub](https://github.com/solana-labs/solana-web3.js/blob/69a8ad25ef09f9e6d5bff1ffa8428d9be0bd32ac/packages/library-legacy/src/connection.ts#L3734).
77
+ - Solana developer ‘mPaella’ [wanted us to add a feature in the RPC](https://github.com/solana-labs/solana-web3.js/issues/1143#issuecomment-1435927152) that would failover to a set of backup URLs in case the primary one failed.
78
+ - Solana developer ‘epicfaace’ wanted first-class support for automatic time-windowed batching in the RPC transport. [Here’s their pull request](https://github.com/solana-labs/solana/pull/23628).
79
+ - Multiple folks have expressed the need for custom retry logic for failed requests or transactions. [Here’s a pull request from ‘dafyddd’](https://github.com/solana-labs/solana/pull/11811) and [another from ‘abrkn’](https://github.com/solana-labs/solana-web3.js/issues/1041) attempting to modify retry logic to suit their individual use cases.
80
+
81
+ ## Lagging Behind Modern JavaScript
82
+
83
+ The advance of modern JavaScript features presents an opportunity to developers of crypto applcations, such as the ability to use native Ed25519 keys and to express large values as native `bigint`.
84
+
85
+ The Web Incubator Community Group has advocated for the addition of Ed25519 support to the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API), and support has already landed in *most* modern JavaScript runtimes.
86
+
87
+ Support for `bigint` values has also become commonplace. The older `number` primitive in JavaScript has a maximum value of 2^53 - 1, whereas Rust’s `u64` can represent values up to 2^64.
88
+
89
+ ## Class-Based Architecture
90
+
91
+ The object oriented, class-based architecture of the legacy library causes unnecessary bundle bloat. Your application has no choice but to bundle *all* of the functionality and dependencies of a class no matter how many methods you actually use at runtime.
92
+
93
+ Class-based architecture also presents unique risks to developers who trigger the dual-package hazard. This describes a situation you can find yourself in if you build for both CommonJS and ES modules. The situation arises when two “copies” of the same class are present in the dependency tree, causing checks like `instanceof` to fail, which introduces aggravating and difficult to debug problems.
94
+
95
+ Read more about dual-package hazard:
96
+
97
+ - [NodeJS: Dual Package Hazard](https://nodejs.org/api/packages.html#dual-package-hazard)
98
+
99
+ # The New web3.js
100
+
101
+ Enter web3.js 2.0. The new API aims to deliver a re-imagined experience of building Solana applications, a high level of performance by default, and all with a minimum of code. From the ability to customize the behaviour of the library through composition, to the joy of being able to catch common errors during build time before they make it to production, we hope that you enjoy building with it as much as we’ve enjoyed creating it.
102
+
103
+ ## Features
104
+
105
+ The new (2.0) version of `@solana/web3.js` aims to address shortcomings in the legacy library first, then goes even further .
106
+
107
+ ### Tree-Shaking
108
+
109
+ The 2.0 library is tree-shakable, and that tree-shakeability is enforced in the CI. Anything you don’t use from web3.js 2.0 can now be discarded from your bundle by an optimizing compiler.
110
+
111
+ The new library itself is comprised of several smaller, modular packages under the `@solana` organization, including:
112
+
113
+ - `@solana/rpc-transport`: For building and managing RPC transports
114
+ - `@solana/rpc-core`: The type-spec of the Solana JSON RPC
115
+ - `@solana/transactions`: For building and transforming Solana transaction objects
116
+ - `@solana/codecs-*`: For building data (de)serializers
117
+
118
+ Developers can use the default configurations within the library itself (`@solana/web3.js:2.0`) or import any number of the modular packages for additional customization.
119
+
120
+ ### Minimally Opinionated
121
+
122
+ The individual modules that make up web3.js are assembled in a **default** configuration reminiscent of the legacy library as part of the npm package `@solana/web3.js`, but those who wish to assemble them in different configurations may do so.
123
+
124
+ Each package uses types and generics liberally, allowing you to inject new functionality, to make extensions to each API via composition and supertypes, and to encourage you to create higher-level opinionated abstractions of your own.
125
+
126
+ In fact, we expect you to do so, and to open source some of those for use by others with similar needs.
127
+
128
+ ### Modern JavaScript
129
+
130
+ The new API is built for compatibility with platform APIs to reduce our dependencies on userspace implementations that introduce supply chain risk and bundle bloat to your applications.
131
+
132
+ One such example is the integration of Ed25519 `CryptoKeys` – native platform primitives for managing cryptographic keys and signatures.
133
+
134
+ Read more about the Web Crypto API here:
135
+
136
+ - [Mozilla Developer Docs: Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)
137
+ - [Node JS Documentation: Web Crypto API](https://nodejs.org/api/webcrypto.html)
138
+ - [Nieky Allen (Blog): The Web Crypto API in Action](https://medium.com/slalom-build/the-web-cryptography-api-in-action-89b2f68c602c)
139
+
140
+ web3.js 2.0 also further eliminates dependencies such as `BN.js` by implementing large integers with `bigint`.
141
+
142
+ ### Interface-Based Architecture
143
+
144
+ The new library employs interfaces and types for just about *everything*, expressing most objects as data. The dual-package hazard is no longer a threat to your development; any objects compatible with an interface are usable with functions that specify that interface.
145
+
146
+ This interface-based approach also allows for easy customization; for extending the library’s functionality or building on top of it.
147
+
148
+ ## Statistics
149
+
150
+ Consider these statistical comparisons between web3.js 2.0 and the legacy 1.x.
151
+
152
+ | | 1.x (Legacy) | 2.0 | +/- % |
153
+ | --- | --- | --- | --- |
154
+ | Total minified size of library | 90 KB | 33 KB | -63% |
155
+ | Total minified size of library (when runtime supports Ed25519) | 90 KB | 17 KB | -81% |
156
+ | Bundled size of a web application that only executes a transfer of lamports | 67 KB | 4.5 KB | -93% |
157
+ | Bundled size of a web application that only executes a transfer of lamports (when runtime supports Ed25519) | 67 KB | 4.5 KB | -93% |
158
+ | Bundled size of a worker that signs and sends a transaction | 5.4 MB | 1.7 MB | -68% |
159
+ | Performance of key generation, signing, and verifying signatures (Brave with Experimental API flag) | 700 ops/s | 7000 ops/s | +900% |
160
+ | First-load size for Solana Explorer | 311 KB | 228 KB | -26% |
161
+
162
+ The re-engineered library achieves these speedups and reductions in bundle size in large part through use of modern JavaScript APIs.
163
+
164
+ To validate our work, we replaced the legacy 1.x library with the new 2.0 library on the homepage of the Solana Explorer. Total first-load bundle size dropped by 26% without removing a single feature. [Here’s an X thread](https://twitter.com/callum_codes/status/1679124485218226176) by Callum McIntyre if you would like to dig deeper.
165
+
166
+ # A tour of the web3.js 2.0 API
167
+
168
+ Here’s an overview of how to use the new library to interact with the RPC, configure network transports, work with Ed25519 keys, and to serialize data.
169
+
170
+ ## RPC
171
+
172
+ web3.js 2.0 ships with an implementation of the [JSON RPC specification](https://www.jsonrpc.org/specification) and a type spec for the [Solana JSON RPC](https://docs.solana.com/api).
173
+
174
+ ### Initializing a Default RPC API
175
+
176
+ Here’s an example of creating the default API for interacting with the Solana JSON RPC:
177
+
178
+ ```tsx
179
+ import { createSolanaRpc, createDefaultRpcTransport } from '@solana/web3.js';
180
+
181
+ // Create an HTTP transport
182
+ const transport = createDefaultRpcTransport({ url: 'http://127.0.0.1:8899' });
183
+
184
+ // Create an RPC client
185
+ const rpc = createSolanaRpc({ transport });
186
+ // ^ RpcMethods<SolanaRpcMethods>
187
+
188
+ // Send a request
189
+ const slot = await rpc.getSlot().send();
190
+ ```
191
+
192
+ The function `createSolanaRpc(..)` accepts a transport to some endpoint that implements JSON RPC and provides all of the capabilities specified by the [Solana JSON RPC HTTP Methods](https://docs.solana.com/api/http).
193
+
194
+ ### Aborting Requests
195
+
196
+ RPC requests are now abortable with modern `AbortControllers`. The `send(..)` method on any `PendingRpcRequest<..>` allows an optional `abortSignal?: AbortSignal` argument.
197
+
198
+ Here’s an example of a custom `AbortController` used to abort a subscription:
199
+
200
+ ```tsx
201
+ import { createSolanaRpcSubscriptions, createDefaultRpcSubscriptionsTransport } from '@solana/web3.js';
202
+
203
+ const transport = createDefaultRpcSubscriptionsTransport({ url: 'ws://127.0.0.1:8900' });
204
+ const rpcSubscriptions = createSolanaRpcSubscriptions({ transport });
205
+
206
+ // Create a new AbortController
207
+ const abortController = new AbortController();
208
+
209
+ // Subscribe for slot notifications
210
+ const slotNotifications = await rpcSubscriptions
211
+ .slotNotifications()
212
+ .subscribe({ abortSignal: abortController.signal });
213
+
214
+ // Set a timer for 5 seconds, then abort the controller
215
+ setTimeout(() => { abortController.abort(); }, 5000);
216
+
217
+ // Log slot notifications
218
+ for await (const notif of slotNotifications) {
219
+ console.log('Slot notification', notif);
220
+ }
221
+
222
+ console.log('Done.');
223
+ ```
224
+
225
+ Read more about `AbortController` at the following links:
226
+
227
+ - [Mozilla Developer Docs: `AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)
228
+ - [Mozilla Developer Docs: `AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
229
+ - [JavaScript.info: Fetch: Abort](https://javascript.info/fetch-abort)
230
+
231
+ ### Scoping the RPC API
232
+
233
+ The new library is comprised of many smaller modular libraries. The packages responsible for managing communication with an RPC are `@solana/rpc-transport` and `@solana/rpc-core`.
234
+
235
+ The `@solana/rpc-transport` library is responsible for creating transports to an RPC using some specified API – such as the Solana [JSON RPC HTTP API](https://docs.solana.com/api/http), while `@solana/rpc-core` provides the actual Solana JSON RPC API (a specification of each of its supported methods).
236
+
237
+ Here’s an example of using `@solana/rpc-transport` and `@solana/rpc-core` to create an RPC transport with the Solana API (note: this is the manual implementation of the code snippet above):
238
+
239
+ ```tsx
240
+ import { createSolanaRpcApi, SolanaRpcMethods } from '@solana/rpc-core';
241
+ import { createHttpTransport, createJsonRpc } from '@solana/rpc-transport';
242
+
243
+ const api = createSolanaRpcApi();
244
+
245
+ const transport = createHttpTransport({ url: 'http://127.0.0.1:8899' });
246
+
247
+ const rpc = createJsonRpc<SolanaRpcMethods>({ api, transport });
248
+ // ^ RpcMethods<SolanaRpcMethods>
249
+ ```
250
+
251
+ If you want to, you can also reduce the scope of the API’s type-spec so you are left only with the types you need. Keep in mind types don’t affect bundle size, but you may choose to scope the type-spec for a variety of reasons, including reducing TypeScript noise.
252
+
253
+ ```tsx
254
+ import { createSolanaRpcApi } from '@solana/rpc-core';
255
+ import type { GetAccountInfoApi } from '@solana/rpc-core/dist/types/rpc-methods/getAccountInfo';
256
+ import { createHttpTransport, createJsonRpc } from '@solana/rpc-transport';
257
+
258
+ const api = createSolanaRpcApi();
259
+
260
+ const transport = createHttpTransport({ url: 'http://127.0.0.1:8899' });
261
+
262
+ const getAccountInfoRpc = createJsonRpc<GetAccountInfoApi>({ api, transport });
263
+ // ^ RpcMethods<GetAccountInfoApi>
264
+ ```
265
+
266
+ ### Creating a Custom RPC API
267
+
268
+ The new library’s RPC specification supports an *infinite* number of JSON-RPC methods with **zero increase** in bundle size.
269
+
270
+ This means the library can support future additions to the official [Solana JSON RPC](https://docs.solana.com/api), or [custom RPC methods](https://www.quicknode.com/docs/ethereum/qn_fetchNFTCollectionDetails_v2) defined by some development team – for example QuickNode or Helius.
271
+
272
+ Here’s an example of how a developer at QuickNode might build a custom RPC type-spec for their in-house RPC methods:
273
+
274
+ ```tsx
275
+ // Define the method's response payload
276
+ type NftCollectionDetailsApiResponse = Readonly<{
277
+ address: string;
278
+ circulatingSupply: number;
279
+ description: string;
280
+ erc721: boolean;
281
+ erc1155: boolean;
282
+ genesisBlock: string;
283
+ genesisTransaction: string;
284
+ name: string;
285
+ totalSupply: number;
286
+ }>;
287
+
288
+ // Set up an interface for the request method
289
+ interface NftCollectionDetailsApi {
290
+ // Define the method's name, parameters and response type
291
+ qn_fetchNFTCollectionDetails(args: {
292
+ contracts: string[],
293
+ }): NftCollectionDetailsApiResponse;
294
+ }
295
+
296
+ // Export the type spec for downstream users
297
+ export type QuickNodeRpcMethods = NftCollectionDetailsApi;
37
298
  ```
38
299
 
39
- ## Usage
300
+ Here’s how a developer might use it:
301
+
302
+ ```tsx
303
+ import { createHttpTransport, createJsonRpc, createJsonRpcApi } from '@solana/rpc-transport';
304
+
305
+ // Create the custom API
306
+ const api = createJsonRpcApi<QuickNodeRpcMethods>();
40
307
 
41
- There are 3 main applications of this library.
308
+ // Set up an HTTP transport
309
+ const transport = createHttpTransport({ url: 'http://127.0.0.1:8899' });
310
+
311
+ // Create the RPC client
312
+ const quickNodeRpc = createJsonRpc<QuickNodeRpcMethods>({ api, transport });
313
+ // ^ RpcMethods<QuickNodeRpcMethods>
314
+ ```
42
315
 
43
- 1. **RPC**. Solana apps interact with the network by calling methods on the Solana JSON-RPC.
44
- 2. **Transactions**. Solana apps interact with Solana program by building and sending transactions.
45
- 3. **Keys**. People use cryptographic keys to verify the provenance of messages and to attest to the ownership of their accounts.
316
+ As long as a particular JSON RPC method adheres to the [official JSON RPC specification](https://www.jsonrpc.org/specification), it will be supported by web3.js 2.0.
46
317
 
47
- ### RPC
318
+ ## Transports
48
319
 
49
- First, configure your connection to an RPC server. This might be a server that you host, one that you lease, or one of the limited-use [public RPC servers](https://docs.solana.com/cluster/rpc-endpoints).
320
+ Using the `@solana/rpc-transport` package, developers can create custom RPC transports. With this library, one can implement highly specialized functionality for leveraging multiple transports, attempting/handling retries, and more.
50
321
 
51
- ```ts
322
+ ### Round Robin
323
+
324
+ Here’s an example of how someone might implement a “round robin” approach to leveraging multiple RPC transports within their application:
325
+
326
+ ```tsx
327
+ import { createSolanaRpcApi } from '@solana/rpc-core';
328
+ import { createJsonRpc } from '@solana/rpc-transport';
329
+ import { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';
52
330
  import { createDefaultRpcTransport } from '@solana/web3.js';
53
- const devnetTransport = createDefaultRpcTransport({ url: 'https://api.devnet.solana.com' });
331
+
332
+ // Create a transport for each RPC server
333
+ const transports = [
334
+ createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-1.com' }),
335
+ createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-2.com' }),
336
+ createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-3.com' }),
337
+ ];
338
+
339
+ // Set up the round robin factory
340
+ let nextTransport = 0;
341
+ async function roundRobinTransport<TResponse>(...args: Parameters<IRpcTransport>): Promise<TResponse> {
342
+ const transport = transports[nextTransport];
343
+ nextTransport = (nextTransport + 1) % transports.length;
344
+ return await transport(...args);
345
+ }
346
+
347
+ // Create the RPC client
348
+ const rpc = createJsonRpc({
349
+ api: createSolanaRpcApi(),
350
+ transport: roundRobinTransport,
351
+ });
54
352
  ```
55
353
 
56
- Second, construct an RPC instance that uses that transport.
354
+ ### Sharding
57
355
 
58
- ```ts
59
- const devnetRpc = createSolanaRpc({ transport: devnetTransport });
356
+ Another example of a possible customization for RPC transports is sharding. Here’s an example:
357
+
358
+ ```tsx
359
+ // TODO: Your turn; send us a pull request with an example.
60
360
  ```
61
361
 
62
- Now, you can use it to call methods on your RPC server. For instance, here is how you would fetch an account's balance.
362
+ ### Retry Logic
363
+
364
+ The transport library can also be used to implement custom retry logic on any request:
63
365
 
64
- ```ts
65
- const systemProgramAddress = '11111111111111111111111111111111' as Base58EncodedAddress;
66
- const balanceInLamports = await devnetRpc.getBalance(systemProgramAddress).send();
67
- console.log('Balance of System Program account in Lamports', balanceInLamports);
366
+ ```tsx
367
+ // TODO: Your turn; send us a pull request with an example.
68
368
  ```
69
369
 
70
- ### Transactions
370
+ ### Failover
71
371
 
72
- Unimplemented.
372
+ Support for handling failover can be implemented as a first-class citizen in your application using the new transport library. Here’s an example of some failover logic integrated into a transport:
73
373
 
74
- ### Keys
374
+ ```tsx
375
+ // TODO: Your turn; send us a pull request with an example.
376
+ ```
75
377
 
76
- #### Addresses and public keys
378
+ ### Fanning Out
77
379
 
78
- Client applications primarily deal with addresses and public keys in the form of base58-encoded strings. Addresses and public keys returned from the RPC API conform to the type `Base58EncodedAddress`. You can use a value of that type wherever a base58-encoded address or key is expected.
380
+ Perhaps your application needs to make a large number of requests, or needs to fan request for different methods out to different servers. Here’s an example of an implementation that does the latter:
79
381
 
80
- From time to time you might acquire a string, that you expect to validate as an address, from an untrusted network API or user input. To assert that such an arbitrary string is a base58-encoded address, use the `assertIsAddress` function.
382
+ ```tsx
383
+ import { createSolanaRpcApi } from '@solana/rpc-core';
384
+ import { createJsonRpc } from '@solana/rpc-transport';
385
+ import { IRpcTransport } from '@solana/rpc-transport/dist/types/transports/transport-types';
386
+ import { createDefaultRpcTransport } from '@solana/web3.js';
81
387
 
82
- ```ts
83
- import { assertIsAddress } from '@solana/web3.js';
388
+ // Create multiple transports
389
+ const transportA = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-1.com' }));
390
+ const transportB = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-2.com' }));
391
+ const transportC = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-3.com' }));
392
+ const transportD = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-4.com' }));
84
393
 
85
- // Imagine a function that fetches an account's balance when a user submits a form.
86
- async function handleSubmit() {
87
- // We know only that what the user typed conforms to the `string` type.
88
- const address: string = accountAddressInput.value;
89
- try {
90
- // If this type assertion function doesn't throw, then
91
- // Typescript will upcast `address` to `Base58EncodedAddress`.
92
- assertIsAddress(address);
93
- // At this point, `address` is a `Base58EncodedAddress` that can be used with the RPC.
94
- const balanceInLamports = await rpc.getBalance(address).send();
95
- } catch (e) {
96
- // `address` turned out not to be a base58-encoded address
394
+ // Function to determine which shard to use based on the request method
395
+ function selectShard(method: string): IRpcTransport {
396
+ switch (method) {
397
+ case 'getAccountInfo':
398
+ case 'getBalance':
399
+ return transportA;
400
+ case 'getTransaction':
401
+ case 'getRecentBlockhash':
402
+ return transportB;
403
+ case 'sendTransaction':
404
+ return transportC;
405
+ default:
406
+ return transportD;
97
407
  }
98
408
  }
409
+
410
+ const rpc = createJsonRpc({
411
+ api: createSolanaRpcApi(),
412
+ transport: async (...args: Parameters<IRpcTransport>): Promise<any> => {
413
+ const payload = args[0].payload as { method: string };
414
+ const selectedTransport = selectShard(payload.method);
415
+ return await selectedTransport(...args);
416
+ },
417
+ });
418
+ ```
419
+
420
+ ## Subscriptions
421
+
422
+ Subscriptions in the legacy library do not allow custom retry logic, and do not give you the opportunity to recover from having potentially missed messages. The new version does away with silent retries, surfaces transport errors to your application, and gives you the opportunity to recover from gap events.
423
+
424
+ ### Async Iterator
425
+
426
+ The new subscriptions API vends subscription notifications as an `AsyncIterator`. The `AsyncIterator` conforms to the [async iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), which allows developers to consume messages using a `for await...of` loop.
427
+
428
+ Here’s an example of working with a subscription in the new library:
429
+
430
+ ```tsx
431
+ import { address, createSolanaRpcSubscriptions, createDefaultRpcSubscriptionsTransport } from '@solana/web3.js';
432
+
433
+ // Create the subscriptions transport
434
+ const transport = createDefaultRpcSubscriptionsTransport({ url: 'ws://127.0.0.1:8900' });
435
+
436
+ // Create the RPC client
437
+ const rpc = createSolanaRpcSubscriptions({ transport });
438
+
439
+ // Set up an abort controller
440
+ const abortController = new AbortController();
441
+
442
+ // Subscribe to account notifications
443
+ const accountNotifications = await rpc
444
+ .accountNotifications(address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3'), { commitment: 'confirmed' })
445
+ .subscribe({ abortSignal: abortController.signal });
446
+
447
+ // Consume messages
448
+ try {
449
+ for await (const notification of accountNotifications) {
450
+ console.log('New balance', notification.value.lamports);
451
+ }
452
+ // Reaching this line means the subscription was aborted (ie. unsubscribed).
453
+ } catch (e) {
454
+ // The subscription went down.
455
+ // Retry it and then recover from potentially having missed
456
+ // a balance update, here (eg. by making a `getBalance()` call)
457
+ } finally {
458
+ // Whether the subscription failed or was aborted, you can run cleanup code here.
459
+ }
460
+ ```
461
+
462
+ The new subscriptions API also offers a separate rpc creator if you would like to use Solana’s [unstable subscription methods](https://docs.solana.com/api/websocket#blocksubscribe).
463
+
464
+ ```tsx
465
+ import { createSolanaRpcSubscriptions_UNSTABLE, createDefaultRpcSubscriptionsTransport } from '@solana/web3.js';
466
+
467
+ const transport = createDefaultRpcSubscriptionsTransport({ url: 'ws://127.0.0.1:8900' });
468
+
469
+ // For unstable methods, explicitly request them in the type spec
470
+ const unstableRpc = createSolanaRpcSubscriptions_UNSTABLE({ transport });
471
+ // ^ RpcSubscriptionMethods<SolanaRpcSubscriptions & SolanaRpcSubscriptionsUnstable>
472
+ ```
473
+
474
+ You can read more about `AsyncIterator` at the following links:
475
+
476
+ - [Mozilla Developer Docs: `AsyncIterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator)
477
+ - [Luciano Mammino (Blog): JavaScript Async Iterators](https://www.nodejsdesignpatterns.com/blog/javascript-async-iterators/)
478
+
479
+ ### Cancelling Subscriptions
480
+
481
+ Similar to the `AbortSignal` logic in the HTTP methods provided by `@solana/rpc-core`, applications can terminate active subscriptions using an `AbortController`. In fact, this parameter is *required* for subscriptions to encourage you to cleanup subscriptions that your application no longer needs.
482
+
483
+ Consider this example of cancelling a subscription using an `AbortController`:
484
+
485
+ ```tsx
486
+ // Subscribe to account notifications
487
+ const accountNotifications = await rpc
488
+ .accountNotifications(address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3'), { commitment: 'confirmed' })
489
+ .subscribe({ abortSignal });
490
+
491
+ // Consume messages
492
+ let previousOwner = null;
493
+ for await (const notification of accountNotifications) {
494
+ const { value: { owner } } = notification;
495
+ // Check the owner to see if it has changed
496
+ if (previousOwner && owner !== previousOwner) {
497
+ // If so, abort the subscription
498
+ abortController.abort();
499
+ } else {
500
+ console.log(notification);
501
+ }
502
+ previousOwner = owner;
503
+ }
504
+ ```
505
+
506
+ ### Message Gap Recovery
507
+
508
+ One of the most crucial aspects of any subscription API is managing potential missed messages. Missing messages, such as account state updates, could be catastrophic for an application. That’s why the new library provides native support for recovering missed messages using the `AsyncIterator`.
509
+
510
+ When a connection fails unexpectedly, any messages you miss while disconnected can result in your UI falling behind or becoming corrupt. Because subscription failure is now made explicit in the new API, you can implement ‘catch up’ logic after re-estabilshing the subscription.
511
+
512
+ Here’s an example of such logic:
513
+
514
+ ```tsx
515
+ try {
516
+ for await (const notif of accountNotifications) {
517
+ updateAccountBalance(notif.lamports);
518
+ }
519
+ } catch(e) {
520
+ // The subscription failed.
521
+ // First, reestablish the subscription.
522
+ await setupAccountBalanceSubscription(address);
523
+ // Then make a one-shot request to 'catch up' on any missed balance changes.
524
+ const { value: lamports } = await rpc.getBalance(address).send();
525
+ updateAccountBalance(lamports);
526
+ }
527
+ ```
528
+
529
+ ## Keys
530
+
531
+ The new library takes a brand-new approach to Solana key pairs and addresses, which will feel quite different from the classes `PublicKey` and `Keypair` from version 1.x.
532
+
533
+ ### Web Crypto API
534
+
535
+ All key operations now use the native Ed25519 implementation in JavaScript’s Web Crypto API.
536
+
537
+ The API itself is designed to be a more reliably secure way to manage highly sensitive secret key information, but **********************************************************************************************************************************developers should still use extreme caution when dealing with secret key bytes in their applications**********************************************************************************************************************************.
538
+
539
+ One thing to note is that many operations from Web Crypto – such as importing, generating, signing, and verifying are now ************************asynchronous************************.
540
+
541
+ Here’s an example of generating a `CryptoKeyPair` using the Web Crypto API and signing a message:
542
+
543
+ ```tsx
544
+ import { generateKeyPair, signBytes, verifySignature } from '@solana/web3.js';
545
+
546
+ const keyPair: CryptoKeyPair = await generateKeyPair();
547
+
548
+ const message = new Uint8Array(8).fill(0);
549
+
550
+ const signedMessage = await signBytes(keyPair.privateKey, message);
551
+ // ^ Ed25519Signature
552
+
553
+ const verified = await verifySignature(keyPair.publicKey, signedMessage, message);
554
+ ```
555
+
556
+ ### Web Crypto Polyfill
557
+
558
+ Wherever Ed25519 is not supported, we offer a polyfill for Web Crypto’s Ed25519 API.
559
+
560
+ This polyfill can be found at `@solana/webcrypto-ed25519-polyfill` and mimics the functionality of the Web Crypto API for Ed25519 key pairs using the same userspace implementation we used in web3.js 1.x. It does not polyfill other algorithms.
561
+
562
+ Determine if your target runtime supports Ed25519, and install the polyfill if it does not:
563
+
564
+ ```tsx
565
+ import '@solana/webcrypto-ed25519-polyfill';
566
+ import { generateKeyPair, signBytes, verifySignature } from '@solana/web3.js';
567
+
568
+ const keyPair: CryptoKeyPair = await generateKeyPair();
569
+
570
+ /* Remaining logic */
571
+ ```
572
+
573
+ You can see where Ed25519 is currently supported in [this GitHub issue](https://github.com/WICG/webcrypto-secure-curves/issues/20) on the Web Crypto repository. Consider sniffing the user-agent when deciding whether or not to deliver the polyfill to browsers.
574
+
575
+ Operations on `CryptoKey` objects using the Web Crypto API *or* the polyfill are mostly handled by the `@solana/keys` package.
576
+
577
+ ### String Addresses
578
+
579
+ All addresses are now JavaScript strings. They are represented by the opaque type `Base58EncodedAddress`, which describes exactly what a Solana address actually is.
580
+
581
+ Consequently, that means no more `PublicKey`.
582
+
583
+ Here’s what they look like in development:
584
+
585
+ ```tsx
586
+ import { address, getAddressFromPublicKey, generateKeyPair, Base58EncodedAddress } from '@solana/web3.js';
587
+
588
+ // Coerce a string to a `Base58EncodedAddress`
589
+ const myOtherAddress = address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3');
590
+
591
+ // Typecast it instead
592
+ const myAddress =
593
+ 'AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3' as Base58EncodedAddress<'AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3'>;
594
+
595
+ // From CryptoKey
596
+ const keyPair = await generateKeyPair();
597
+ const myPublicKeyAsAddress = await getAddressFromPublicKey(keyPair.publicKey);
598
+ ```
599
+
600
+ Some tooling for working with base58-encoded addresses can be found in the `@solana/addresses` package.
601
+
602
+ ## Transactions
603
+
604
+ Just like many other familiar aspects of the 1.0 library, transactions have received a makeover as well.
605
+
606
+ For starters, all transactions are now version-aware, so there’s no longer a need to juggle two different types of transactions (`Transaction` vs. `VersionedTransaction`).
607
+
608
+ Address lookups are now completely described inside transaction instructions, so you don’t have to materialize `addressTableLookups` from the transaction object anymore.
609
+
610
+ Here’s a simple example of creating a transaction – notice how the type of the transaction is refined at each step of the process:
611
+
612
+ ```tsx
613
+ import {
614
+ address,
615
+ createTransaction,
616
+ setTransactionFeePayer,
617
+ setTransactionLifetimeUsingBlockhash,
618
+ Blockhash,
619
+ } from '@solana/web3.js';
620
+
621
+ const recentBlockhash = {
622
+ blockhash: '4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY' as Blockhash,
623
+ lastValidBlockHeight: 196055492n,
624
+ };
625
+ const feePayer = address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3');
626
+
627
+ // Create a new transaction (legacy)
628
+ const transactionLegacy = createTransaction({ version: 'legacy' });
629
+ // ^ LegacyTransaction
630
+
631
+ const transactionWithFeePayerLegacy = setTransactionFeePayer(feePayer, transactionLegacy);
632
+ // ^ LegacyTransaction & ITransactionWithFeePayer
633
+
634
+ const transactionWithFeePayerAndLifetimeLegacy = setTransactionLifetimeUsingBlockhash(
635
+ recentBlockhash,
636
+ transactionWithFeePayerLegacy
637
+ );
638
+ // ^ LegacyTransaction & ITransactionWithFeePayer & ITransactionWithBlockhash
639
+
640
+ // Create a new transaction (v0)
641
+ const transactionV0 = createTransaction({ version: 0 });
642
+ // ^ V0Transaction
643
+
644
+ // Set the fee payer
645
+ const transactionWithFeePayerV0 = setTransactionFeePayer(feePayer, transactionV0);
646
+ // ^ V0Transaction & ITransactionWithFeePayer
647
+
648
+ const transactionWithFeePayerAndLifetimeV0 = setTransactionLifetimeUsingBlockhash(
649
+ recentBlockhash,
650
+ transactionWithFeePayerV0
651
+ );
652
+ // ^ V0Transaction & ITransactionWithFeePayer & ITransactionWithBlockhash
653
+ ```
654
+
655
+ As you can see, each time a transaction is modified, the type reflects the current state. If you add a fee payer, you’ll get a type representing a transaction with a fee payer, and so on.
656
+
657
+ Additionally, transaction-modifying methods such as `setTransactionFeePayer(..)` and `setTransactionLifetimeUsingBlockhash(..)` will strip a transaction of its signatures, since those signatures would no longer match the modified transaction message.
658
+
659
+ ```tsx
660
+ import {
661
+ address,
662
+ createTransaction,
663
+ generateKeyPair,
664
+ setTransactionFeePayer,
665
+ setTransactionLifetimeUsingBlockhash,
666
+ signTransaction,
667
+ Blockhash,
668
+ } from '@solana/web3.js';
669
+
670
+ const recentBlockhash = {
671
+ blockhash: '4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY' as Blockhash,
672
+ lastValidBlockHeight: 196055492n,
673
+ };
674
+ const feePayer = address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3');
675
+ const signer = await generateKeyPair();
676
+
677
+ const transaction = createTransaction({ version: 'legacy' });
678
+ const transactionWithFeePayer = setTransactionFeePayer(feePayer, transaction);
679
+ const transactionWithFeePayerAndLifetime = setTransactionLifetimeUsingBlockhash(
680
+ recentBlockhash,
681
+ transactionWithFeePayer
682
+ );
683
+ const transactionSignedWithFeePayerAndLifetime = await signTransaction(
684
+ [signer],
685
+ transactionWithFeePayerAndLifetime
686
+ );
687
+ // ^ LegacyTransaction & ITransactionWithFeePayer & ITransactionWithBlockhash & ITransactionWithSignatures
688
+
689
+ // Setting the lifetime again will remove the signatures from the object
690
+ const transactionSignaturesStripped = setTransactionLifetimeUsingBlockhash(
691
+ recentBlockhash,
692
+ transactionSignedWithFeePayerAndLifetime,
693
+ );
694
+ // ^ LegacyTransaction & ITransactionWithFeePayer & ITransactionWithBlockhash
695
+ ```
696
+
697
+ The `signTransaction(..)` function will raise a type error if your unsigned transaction is not already equipped with a fee payer and a lifetime.
698
+
699
+ ```tsx
700
+ const feePayer = address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3');
701
+ const signer = await generateKeyPair();
702
+
703
+ const transaction = createTransaction({ version: 'legacy' });
704
+ const transactionWithFeePayer = setTransactionFeePayer(feePayer, transaction);
705
+
706
+ // Attempting to sign the transaction without a lifetime will throw a type error
707
+ const transactionSignedWithFeePayer = await signTransaction([signer], transactionWithFeePayer);
708
+ // => "Property 'lifetimeConstraint' is missing in type"
709
+ ```
710
+
711
+ Transaction objects are also ********frozen by these functions******** to prevent transactions from being mutated in place by functions you pass them to.
712
+
713
+ Building transactions in this manner might feel different to what you’re used to. Also, we certainly wouldn’t want you to have to bind transformed transactions to a new variable at each step, so we have released a functional programming library dubbed `@solana/functional` that lets you build transactions in **********************************pipelines**********************************. Here’s how it can be used:
714
+
715
+ ```tsx
716
+ import { pipe } from '@solana/functional';
717
+ import {
718
+ address,
719
+ Blockhash,
720
+ createTransaction,
721
+ setTransactionFeePayer,
722
+ setTransactionLifetimeUsingBlockhash,
723
+ } from '@solana/web3.js';
724
+
725
+ // Use `pipe(..)` to create a pipeline of transaction transform operations
726
+ const transaction = pipe(
727
+ createTransaction({ version: 0 }),
728
+ tx => setTransactionFeePayer(feePayer, tx),
729
+ tx => setTransactionLifetimeUsingBlockhash(recentBlockhash, tx)
730
+ );
731
+ ```
732
+
733
+ Note that `pipe(..)` is completely decoupled from transactions, so it can be used to pipeline any compatible transforms.
734
+
735
+ ## Codecs
736
+
737
+ We have taken steps to make it easier to write data (de)serializers, especially as they pertain to Rust datatypes and byte buffers.
738
+
739
+ Solana’s codecs libraries are broken up into modular components so you only need to import the ones you need. They are:
740
+
741
+ - `@solana/codecs-core`: The core codecs library for working with codecs serializers and creating custom ones
742
+ - `@solana/codecs-numbers`: Used for serialization of numbers (little-endian and big-endian bytes, etc.)
743
+ - `@solana/codecs-strings`: Used for serialization of strings
744
+ - `@solana/codecs-data-structures`: Codecs and serializers for structs
745
+ - `@solana/options`: Designed to build codecs and serializers for types that mimic Rust’s enums, which can include embedded data within their variants such as values, tuples, and structs
746
+
747
+ Here’s an example of encoding and decoding a custom struct with some strings and numbers:
748
+
749
+ ```tsx
750
+ import { getStructCodec } from "@solana/codecs-data-structures";
751
+ import { getU64Codec, getU8Codec } from "@solana/codecs-numbers";
752
+ import { getStringCodec } from "@solana/codecs-strings";
753
+
754
+ // Equivalent in Rust:
755
+ // struct {
756
+ // amount: u64,
757
+ // decimals: u8,
758
+ // name: String,
759
+ // }
760
+ const structCodec = getStructCodec([
761
+ ["amount", getU64Codec()],
762
+ ["decimals", getU8Codec()],
763
+ ["name", getStringCodec()],
764
+ ]);
765
+
766
+ const myToken = {
767
+ amount: 1000000000000000n, // `bigint` or `number` is supported
768
+ decimals: 2,
769
+ name: "My Token",
770
+ };
771
+
772
+ const myEncodedToken: Uint8Array = structCodec.encode(myToken);
773
+ const myDecodedToken = structCodec.decode(myEncodedToken)[0];
774
+
775
+ myDecodedToken satisfies {
776
+ amount: bigint;
777
+ decimals: number;
778
+ name: string;
779
+ }
780
+ ```
781
+
782
+ You may only need to encode or decode data, but not both. Importing one or the other allows your optimizing compiler to tree-shake the other implementation away:
783
+
784
+ ```tsx
785
+ import { Codec, combineCodec, Decoder, Encoder } from "@solana/codecs-core";
786
+ import { getStructDecoder, getStructEncoder } from "@solana/codecs-data-structures";
787
+ import { getU8Decoder, getU8Encoder, getU64Decoder, getU64Encoder } from "@solana/codecs-numbers";
788
+ import { getStringDecoder, getStringEncoder } from "@solana/codecs-strings";
789
+
790
+ export type MyToken = {
791
+ amount: bigint,
792
+ decimals: number,
793
+ name: string,
794
+ }
795
+
796
+ export type MyTokenArgs = {
797
+ amount: number | bigint,
798
+ decimals: number,
799
+ name: string,
800
+ }
801
+
802
+ export const getMyTokenEncoder = (): Encoder<MyTokenArgs> => getStructEncoder([
803
+ ["amount", getU64Encoder()],
804
+ ["decimals", getU8Encoder()],
805
+ ["name", getStringEncoder()],
806
+ ]);
807
+
808
+ export const getMyTokenDecoder = (): Decoder<MyToken> => getStructDecoder([
809
+ ["amount", getU64Decoder()],
810
+ ["decimals", getU8Decoder()],
811
+ ["name", getStringDecoder()],
812
+ ]);
813
+
814
+ export const getMyTokenCodec = (): Codec<MyTokenArgs, MyToken> => combineCodec(
815
+ getMyTokenEncoder(),
816
+ getMyTokenDecoder()
817
+ );
818
+ ```
819
+
820
+ See more in the different packages’ [README files on GitHub](https://github.com/solana-labs/solana-web3.js/blob/master/packages/codecs-data-structures/README.md).
821
+
822
+ ## Type-Safety
823
+
824
+ The new library makes use of some advanced TypeScript features, including generic types, conditional types, `Parameters<..>`, `ReturnType<..>` and more.
825
+
826
+ We’ve described the RPC API in detail so that TypeScript can determine the *exact* type of the result you will receive from the server given a particular input. Change the type of the input, and you will see the return type reflect that change.
827
+
828
+ ### RPC Types
829
+
830
+ The RPC methods – both HTTP and subscriptions – are built with multiple overloads and conditional types. The expected HTTP response payload or subscription message format will be reflected in the return type of the function you’re working with when you provide the inputs in your code.
831
+
832
+ Here’s an example of this in action:
833
+
834
+ ```tsx
835
+ // Provide one set of parameters, get a certain type
836
+ // These parameters resolve to return type:
837
+ // {
838
+ // blockhash: Blockhash;
839
+ // blockHeight: bigint;
840
+ // blockTime: UnixTimestamp;
841
+ // parentSlot: bigint;
842
+ // previousBlockhash: Blockhash;
843
+ // }
844
+ const blockResponse = await rpc.getBlock(0n, {
845
+ rewards: false,
846
+ transactionDetails: 'none'
847
+ }).send();
848
+
849
+ // Switch `rewards` to `true`, get `rewards` in the return type
850
+ // {
851
+ // /* ... Previous response */
852
+ // rewards: Reward[];
853
+ // }
854
+ const blockWithRewardsResponse = await rpc.getBlock(0n, {
855
+ rewards: true,
856
+ transactionDetails: 'none'
857
+ }).send();
858
+
859
+ // Switch `transactionDetails` to `full`, get `transactions` in the return type
860
+ // {
861
+ // /* ... Previous response */
862
+ // transactions: TransactionResponse[];
863
+ // }
864
+ const blockWithRewardsAndTransactionsResponse = await rpc.getBlock(0n, {
865
+ rewards: true,
866
+ transactionDetails: 'full'
867
+ }).send();
868
+ ```
869
+
870
+ ### Catching Compile-Time Bugs with TypeScript
871
+
872
+ As previously mentioned, the type coverage in web3.js 2.0 allow developers to catch common bugs at compile time, rather than runtime.
873
+
874
+ In the example below, a transaction is created and then attempted to be compiled without setting the fee payer. This would result in a runtime error from the RPC, but instead you will see a type error from TypeScript as you type:
875
+
876
+ ```tsx
877
+ const encodedTx = pipe(
878
+ createTransaction({ version: 0 }),
879
+ tx => setTransactionLifetimeUsingBlockhash(recentBlockhash, tx),
880
+ tx => getBase64EncodedWireTransaction(tx), // Property 'feePayer' is missing in type
881
+ );
882
+ ```
883
+
884
+ Consider another example where a developer is attempting to send a transaction that has not been fully signed. Again, the TypeScript compiler will throw a type error:
885
+
886
+ ```tsx
887
+ const unsignedTransaction = pipe(
888
+ createTransaction({ version: 0 }),
889
+ tx => setTransactionFeePayer(feePayerAddress, tx),
890
+ tx => setTransactionLifetimeUsingBlockhash(recentBlockhash, tx),
891
+ );
892
+
893
+ const signature = sendAndConfirmTransaction({
894
+ confirmRecentTransaction: createDefaultRecentTransactionConfirmer({ rpc, rpcSubscriptions }),
895
+ rpc,
896
+ transaction: unsignedTransaction, // Transaction has not been signed: Type error
897
+ });
898
+
899
+ const transaction = await signTransaction([], unsignedTransaction);
900
+
901
+ // Asserts the transaction as a `IFullySignedTransaction`
902
+ // Throws an error if any signatures are missing!
903
+ assertTransactionIsFullySigned(transaction);
904
+ ```
905
+
906
+ Are you working with a nonce transaction and forgot to make `AdvanceNonce` the first instruction? That’s a type error:
907
+
908
+ ```tsx
909
+ const feePayer = await generateKeyPair();
910
+ const feePayerAddress = await getAddressFromPublicKey(feePayer.publicKey);
911
+
912
+ const notNonceTransaction = pipe(
913
+ createTransaction({ version: 0 }),
914
+ tx => setTransactionFeePayer(feePayerAddress, tx),
915
+ );
916
+
917
+ notNonceTransaction satisfies IDurableNonceTransaction;
918
+ // => Property 'lifetimeConstraint' is missing in type
919
+
920
+ const nonceConfig = {
921
+ nonce: 'nonce' as Nonce,
922
+ nonceAccountAddress: address('5tLU66bxQ35so2bReGcyf3GfMMAAauZdNA1N4uRnKQu4'),
923
+ nonceAuthorityAddress: address('GDhj8paPg8woUzp9n8fj7eAMocN5P7Ej3A7T9F5gotTX'),
924
+ };
925
+
926
+ const stillNotNonceTransaction = {
927
+ lifetimeConstraint: nonceConfig,
928
+ ...notNonceTransaction,
929
+ };
930
+
931
+ stillNotNonceTransaction satisfies IDurableNonceTransaction;
932
+ // => 'readonly IInstruction<string>[]' is not assignable to type 'readonly [AdvanceNonceAccountInstruction<string, string>, ...IInstruction<string>[]]'
933
+
934
+ const validNonceTransaction = pipe(
935
+ createTransaction({ version: 0 }),
936
+ tx => setTransactionFeePayer(feePayerAddress, tx),
937
+ tx => setTransactionLifetimeUsingDurableNonce(nonceConfig, tx), // Adds the instruction!
938
+ );
939
+
940
+ validNonceTransaction satisfies IDurableNonceTransaction; // OK
941
+ ```
942
+
943
+ The library’s type-checking can even catch you using lamports instead of SOL for a value:
944
+
945
+ ```tsx
946
+ const airdropAmount = 1n; // SOL
947
+ const signature = rpc.requestAirdrop(myAddress, airdropAmount).send();
99
948
  ```
949
+
950
+ It will force you to cast the numerical value for your airdrop (or transfer, etc.) amount using `lamports()`, which should be a good reminder!
951
+
952
+ ```tsx
953
+ const airdropAmount = lamports(1000000000n);
954
+ const signature = rpc.requestAirdrop(myAddress, airdropAmount).send();With the new library, it’s possible to specify the nature of a transaction instruction completely, just using TypeScrip
955
+ ```
956
+
957
+ ## Compatibility Layer
958
+
959
+ You will have noticed by now that web3.js is a complete and total breaking change from the 1.x line. We want to provide you with a strategy for interacting with 1.x APIs while building your application using 2.0. You need a tool for commuting between 1.x and 2.0 data types.
960
+
961
+ The `@solana/compat` library allows for interoperability between functions and class objects from the legacy library - such as `VersionedTransaction`, `PublicKey`, and `Keypair` - and functions and types of the new library - such as `Transaction`, `Base58EncodedAddress`, and `CryptoKeyPair`.
962
+
963
+ Here’s how you can use `@solana/compat` to convert from a legacy `PublicKey` to a `Base58EncodedAddress`:
964
+
965
+ ```tsx
966
+ import { fromLegacyPublicKey } from '@solana/compat';
967
+
968
+ const publicKey = new PublicKey('B3piXWBQLLRuk56XG5VihxR4oe2PSsDM8nTF6s1DeVF5');
969
+ const base58Address: Base58EncodedAddress = fromLegacyPublicKey(publicKey);
970
+ ```
971
+
972
+ Here’s how to convert from a legacy `Keypair` to a `CryptoKeyPair`:
973
+
974
+ ```tsx
975
+ import { fromLegacyKeypair } from '@solana/compat';
976
+
977
+ const keypairLegacy = Keypair.generate();
978
+ const cryptoKeyPair: CryptoKeyPair = fromLegacyKeypair(keypair);
979
+ ```
980
+
981
+ Here’s how to convert legacy transaction objects to the new library’s transaction types:
982
+
983
+ ```tsx
984
+ // For a transaction using a blockhash lifetime
985
+ const tx = fromVersionedTransactionWithBlockhash(legacyTransactionV0);
986
+ // You can also optionally provide a `lastValidBlockheight` parameter to manage retries
987
+ const tx = fromVersionedTransactionWithBlockhash(legacyTransactionV0, lastValidBlockheight);
988
+
989
+ // For a transaction using a durable nonce lifetime
990
+ const tx = fromVersionedTransactionWithDurableNonce(transaction);
991
+ // Again you can also optionally provide a `lastValidBlockheight`
992
+ const tx = fromVersionedTransactionWithDurableNonce(transaction, lastValidBlockheight);
993
+ ```
994
+
995
+ To see more conversions supported by `@solana/compat`, you can check out the package’s [README on GitHub](https://github.com/solana-labs/solana-web3.js/blob/master/packages/compat/README.md).
996
+
997
+ # Going Forward
998
+
999
+ This Technology Preview is just that, and development on the new web3.js is ongoing. We are working on tooling to accompany the new library to make building web applications on Solana easier, safer, and more scalable.
1000
+
1001
+ Although this new approach to JavaScript tooling is drastically different than the tooling you are used to, we are confident that the customizability, performance, bundle size, and safety characteristics of the new library will make it worth the migration. We’re here to help you every step of the way, via Github issues when you find problems with the library, and on the [Solana Stack Exchange](https://sola.na/sse) when you have questions on how something is supposed to work.
1002
+
1003
+ ## Program Clients
1004
+
1005
+ Writing JavaScript clients for on-chain programs has been done manually up until now. Without an IDL for some of the native programs, this process has been necessarily manual and has resulted in clients that lag behind the actual capabilities of the programs themselves.
1006
+
1007
+ We think that program clients should be *generated* rather than written. Developers should be able to write Rust programs, compile the program code, and generate all of the JavaScript client-side code to interact with the program.
1008
+
1009
+ Developers familiar with Shank and Solita may recognize this idea. We want to take it even further.
1010
+
1011
+ Here’s what the code could look like for a program client that includes Solana’s core programs like the System program or the Compute Budget program.
1012
+
1013
+ ```tsx
1014
+ import { createTransaction, pipe } from '@solana/web3.js';
1015
+ import { addMemo, setComputeUnitLimit, transferSol } from '@solana/spl-core';
1016
+
1017
+ const instructions = await Promise.all([
1018
+ setComputeUnitLimit({ units: 600_000 }),
1019
+ transferSol({ source, destination, amount: 1_000_000_000 }),
1020
+ addMemo({ memo: "I'm transferring some SOL!" })
1021
+ ]);
1022
+
1023
+ // Creates a V0 transaction with 3 instructions inside.
1024
+ const transaction = pipe(
1025
+ createTransaction({ version: 0 }),
1026
+ tx => appendTransactionInstructions(instructions, tx),
1027
+ );
1028
+ ```
1029
+
1030
+ ## GraphQL
1031
+
1032
+ Though not directly related to web3.js, we wanted to hijack your attention to show you something else that we’re working on, of particular interest to frontend developers. It’s a new API for interacting with the RPC: a GraphQL API.
1033
+
1034
+ The `@solana/rpc-graphql` package can be used to make GraphQL queries to Solana RPC endpoints, using the same transports described above (including any customizations).
1035
+
1036
+ Here’s an example of retrieving account data with GraphQL:
1037
+
1038
+ ```tsx
1039
+ const source = `
1040
+ query myQuery($address: String!) {
1041
+ account(address: $address) {
1042
+ lamports
1043
+ }
1044
+ }
1045
+ `;
1046
+
1047
+ const variableValues = {
1048
+ address: 'AyGCwnwxQMCqaU4ixReHt8h5W4dwmxU7eM3BEQBdWVca',
1049
+ };
1050
+
1051
+ const result = await rpcGraphQL.query(source, variableValues);
1052
+
1053
+ expect(result).toMatchObject({
1054
+ data: {
1055
+ account: {
1056
+ lamports: 10290815n,
1057
+ },
1058
+ },
1059
+ });
1060
+ ```
1061
+
1062
+ Using GraphQL allows developers to only specify which fields they *actually* need, and do away with the rest of the response.
1063
+
1064
+ However, GraphQL is also extremely powerful for **nesting queries**, which can be particularly useful if you want to, say, get the **sum** of every lamports balance of every **owner of the owner** of each token account, while discarding any mint accounts.
1065
+
1066
+ ```tsx
1067
+ const source = `
1068
+ query getLamportsOfOwnersOfOwnersOfTokenAccounts {
1069
+ programAccounts(programAddress: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA") {
1070
+ ... on TokenAccount {
1071
+ data {
1072
+ parsed {
1073
+ info {
1074
+ owner {
1075
+ owner {
1076
+ lamports
1077
+ }
1078
+ }
1079
+ }
1080
+ }
1081
+ }
1082
+ }
1083
+ }
1084
+ }
1085
+ `;
1086
+
1087
+ const result = await rpcGraphQL.query(source);
1088
+
1089
+ const sumOfAllLamportsOfOwnersOfOwnersOfTokenAccounts = result
1090
+ .map(o => o.account.data.parsed.info.owner.owner.lamports)
1091
+ .reduce((acc, lamports) => acc + lamports, 0);
1092
+ ```
1093
+
1094
+ The new GraphQL package supports this same style of nested querying on transactions and blocks.
1095
+
1096
+ ```tsx
1097
+ const source = `
1098
+ query myQuery($signature: String!, $commitment: Commitment) {
1099
+ transaction(signature: $signature, commitment: $commitment) {
1100
+ ... on TransactionJsonParsed {
1101
+ transaction {
1102
+ message {
1103
+ ... on TransactionMessageParsed {
1104
+ instructions {
1105
+ ... on CreateAccountInstruction {
1106
+ parsed {
1107
+ info {
1108
+ lamports
1109
+ space
1110
+ }
1111
+ program
1112
+ }
1113
+ }
1114
+ }
1115
+ }
1116
+ }
1117
+ }
1118
+ }
1119
+ }
1120
+ }
1121
+ `;
1122
+
1123
+ const variableValues = {
1124
+ signature: '63zkpxATgAwXRGFQZPDESTw2m4uZQ99sX338ibgKtTcgG6v34E3MSS3zckCwJHrimS71cvei6h1Bn1K1De53BNWC',
1125
+ commitment: 'confirmed',
1126
+ };
1127
+
1128
+ const result = await rpcGraphQL.query(source, variableValues);
1129
+
1130
+ expect(result).toMatchObject({
1131
+ data: {
1132
+ transaction: {
1133
+ transaction: {
1134
+ message: {
1135
+ instructions: expect.arrayContaining([{
1136
+ parsed: {
1137
+ info: {
1138
+ lamports: expect.any(BigInt),
1139
+ space: expect.any(BigInt),
1140
+ },
1141
+ program: 'system',
1142
+ },
1143
+ }])
1144
+ },
1145
+ },
1146
+ },
1147
+ },
1148
+ });
1149
+ ```
1150
+
1151
+ See more in the package’s [README on GitHub](https://github.com/solana-labs/solana-web3.js/tree/master/packages/rpc-graphql).
1152
+
1153
+ ## Development
1154
+
1155
+ You can see all development of the new library and any associated tooling – such as program clients and GraphQL support – in the web3.js repository on GitHub.
1156
+
1157
+ https://github.com/solana-labs/solana-web3.js
1158
+
1159
+ Solana Labs develops these tools in public, with open source. We encourage any and all developers who would like to work on these tools to contribute to the codebase.
1160
+
1161
+ In fact, we welcome anyone who experiments with the new library to submit feedback via GitHub issues (or pull requests). A steady stream of feedback on the library from you will give us the confidence to propose a release candidate sooner.
1162
+
1163
+ You can find issues to tackle in the repository’s “issues” section, just make sure to follow the contributor guidelines!
1164
+
1165
+ ## Thank you
1166
+
1167
+ We’re grateful that you have read this far. If you are interested in migrating an existing application to the new web3.js to take advantage of some of the benefits we’ve demonstrated, we want to give you some direct support. Reach out to [@steveluscher](https://twitter.com/steveluscher/) on Twitter to start a conversation.