{"id":25841239,"url":"https://github.com/anza-xyz/kit","last_synced_at":"2026-01-27T21:24:06.972Z","repository":{"id":267885119,"uuid":"902639929","full_name":"anza-xyz/kit","owner":"anza-xyz","description":"Solana JavaScript SDK","archived":false,"fork":false,"pushed_at":"2025-05-08T17:44:04.000Z","size":61942,"stargazers_count":401,"open_issues_count":54,"forks_count":59,"subscribers_count":9,"default_branch":"main","last_synced_at":"2025-05-08T19:08:16.840Z","etag":null,"topics":["blockchain","sdk-js","solana","web3"],"latest_commit_sha":null,"homepage":"https://solana-kit-docs.vercel.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/anza-xyz.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-12-13T01:09:53.000Z","updated_at":"2025-05-08T17:30:31.000Z","dependencies_parsed_at":null,"dependency_job_id":"45ea9072-d770-4c0c-b3b7-320bd378a8b2","html_url":"https://github.com/anza-xyz/kit","commit_stats":null,"previous_names":["anza-xyz/solana-web3.js","anza-xyz/kit"],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anza-xyz%2Fkit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anza-xyz%2Fkit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anza-xyz%2Fkit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anza-xyz%2Fkit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/anza-xyz","download_url":"https://codeload.github.com/anza-xyz/kit/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253837247,"owners_count":21971979,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["blockchain","sdk-js","solana","web3"],"created_at":"2025-03-01T05:14:38.039Z","updated_at":"2026-01-27T21:24:06.955Z","avatar_url":"https://github.com/anza-xyz.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","Developer Resources","Solana Agent Infrastructure","Web Tooling","Libraries \u0026 Frameworks"],"sub_categories":["Crates and SDKs","Benchmark Reality Check (real-world tool use)","Liquid Staking \u0026 Restaking"],"readme":"[![npm][npm-image]][npm-url]\n[![npm-downloads][npm-downloads-image]][npm-url]\n\u003cbr /\u003e\n[![code-style-prettier][code-style-prettier-image]][code-style-prettier-url]\n\n[code-style-prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square\n[code-style-prettier-url]: https://github.com/prettier/prettier\n[npm-downloads-image]: https://img.shields.io/npm/dm/@solana/kit?style=flat\n[npm-image]: https://img.shields.io/npm/v/@solana/kit?style=flat\n[npm-url]: https://www.npmjs.com/package/@solana/kit\n\n# Kit\n\nThis is the JavaScript SDK for building Solana apps for Node, web, and React Native.\n\n\u003e [!NOTE]\n\u003e Did you expect to find `@solana/web3.js` here? You're in the right place! We have renamed the 2.x line of `@solana/web3.js` to `@solana/kit`.\n\u003e\n\u003e The code for the 1.x line of `@solana/web3.js` can be found [here](https://github.com/solana-labs/solana-web3.js/tree/maintenance/v1.x) and the documentation [here](https://solana-foundation.github.io/solana-web3.js/).\n\n# Installation\n\nFor use in a Node.js or web application:\n\n```shell\nnpm install --save @solana/kit\n```\n\nFor use in a browser, without a build system:\n\n```html\n\u003c!-- Development (debug mode, unminified) --\u003e\n\u003cscript src=\"https://unpkg.com/@solana/kit/dist/index.development.js\"\u003e\u003c/script\u003e\n\n\u003c!-- Production (minified) --\u003e\n\u003cscript src=\"https://unpkg.com/@solana/kit/dist/index.production.min.js\"\u003e\u003c/script\u003e\n```\n\n# Quick Start\n\nTo get a feel for the API, run and modify the live examples in the `examples/` directory. There, you will find a series of single-purpose Node scripts that demonstrate a specific feature or use case. You will also find a React application that you can run in a browser, that demonstrates being able to create, sign, and send transactions using browser wallets.\n\nFor a fully baked intro, see: [Getting started with Solana kit](https://www.solanakit.com/docs/getting-started)\n\n# What's New in Kit\n\nKit is a response to many of the pain points you have communicated to us when developing Solana applications with web3.js.\n\n## Tree-Shakability\n\nThe 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 until now been forced to package all of it.\n\nRead more about tree-shaking here:\n\n- [Mozilla Developer Docs: Tree Shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking)\n- [WebPack Docs: Tree Shaking](https://webpack.js.org/guides/tree-shaking/)\n- [Web.Dev Blog Article: Reduce JavaScript Payloads with Tree Shaking](https://web.dev/articles/reduce-javascript-payloads-with-tree-shaking)\n\nOne 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.\n\nNeedlessly 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.\n\nKit is fully tree-shakable and will remain so, enforced by build-time checks. Optimizing compilers can now eliminate those parts of the library that your application does not use.\n\nKit is comprised of several smaller, modular packages under the `@solana` organization, including:\n\n- `@solana/accounts`: For fetching and decoding accounts\n- `@solana/codecs`: For composing data (de)serializers from a set of primitives or building custom ones\n- `@solana/errors`: For identifying and refining coded errors thrown in the `@solana` namespace\n- `@solana/rpc`: For sending RPC requests\n- `@solana/rpc-subscriptions`: For subscribing to RPC notifications\n- `@solana/signers`: For building message and/or transaction signer objects\n- `@solana/sysvars`: For fetching and decoding sysvar accounts\n- `@solana/transaction-messages`: For building and transforming Solana transaction message objects\n- `@solana/transactions`: For compiling and signing transactions for submission to the network\n- And many more!\n\nSome of these packages are themselves composed of smaller packages. For instance, `@solana/rpc` is composed of `@solana/rpc-spec` (for core JSON RPC specification types), `@solana/rpc-api` (for the Solana-specific RPC methods), `@solana/rpc-transport-http` (for the default HTTP transport) and so on.\n\nDevelopers can use the default configurations within the main library (`@solana/kit`) or import any of its subpackages where customization-through-composition is desired.\n\n## Composable Internals\n\nDepending on your use case and your tolerance for certain application behaviours, you may wish to configure your application to make a different set of tradeoffs than another developer. The web3.js (1.x) API imposed a rigid set of common-case defaults on _all_ developers, some of which were impossible to change.\n\nThe inability to customize web3.js up until now has been a source of frustration:\n\n- 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).\n- 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.\n- 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).\n- 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.\n\nKit exposes far more of its internals, particularly where communication with an RPC is concerned, and allows willing developers the ability to compose new implementations from the default ones that manifest a nearly limitless array of customizations.\n\nThe individual modules that make up Kit are assembled in a **default** configuration reminiscent of the legacy library as part of the npm package `@solana/kit`, but those who wish to assemble them in different configurations may do so.\n\nGeneric types are offered in numerous places, allowing you to specify 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.\n\nIn fact, we expect you to do so, and to open source some of those for use by others with similar needs.\n\n## Modern JavaScript; Zero-Dependency\n\nThe advance of modern JavaScript features presents an opportunity to developers of crypto applications, such as the ability to use native Ed25519 keys and to express large values as native `bigint`.\n\nThe 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.\n\nEngine 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.\n\nKit eliminates userspace implementations of Ed25519 cryptography, large number polyfills, and more, in favour of custom implementations or the use of native JavaScript features, reducing the size of the library. It has no third-party dependencies.\n\n## Functional Architecture\n\nThe object oriented, class-based architecture of web3.js (1.x) 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.\n\nClass-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. It arises when two copies of the same class are present in the dependency tree, causing checks like `instanceof` to fail. This introduces aggravating and difficult to debug problems.\n\nRead more about dual-package hazard:\n\n- [NodeJS: Dual Package Hazard](https://nodejs.org/api/packages.html#dual-package-hazard)\n\nKit implements no classes (with the notable exception of the `SolanaError` class) and implements the thinnest possible interfaces at function boundaries.\n\n## Statistics\n\nConsider these statistical comparisons between Kit and the legacy web3.js 1.x.\n\n|                                                                                                        | 1.x (Legacy) | Kit        | +/- % |\n| ------------------------------------------------------------------------------------------------------ | ------------ | ---------- | ----- |\n| Total minified size of library                                                                         | 81 KB        | 57.5 KB    | -29%  |\n| Total minified size of library (when runtime supports Ed25519)                                         | 81 KB        | 53 KB      | -33%  |\n| Bundled size of a web application that executes a transfer of lamports                                 | 111 KB       | 23.9 KB    | -78%  |\n| Bundled size of a web application that executes a transfer of lamports (when runtime supports Ed25519) | 111 KB       | 18.2 KB    | -83%  |\n| Performance of key generation, signing, and verifying signatures (Brave with Experimental API flag)    | 700 ops/s    | 7000 ops/s | +900% |\n| First-load size for Solana Explorer                                                                    | 311 KB       | 228 KB     | -26%  |\n\nThe re-engineered library achieves these speedups and reductions in bundle size in large part through use of modern JavaScript APIs.\n\nTo validate our work, we replaced the legacy 1.x library with Kit 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.\n\n# A Tour of the Kit API\n\nHere’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.\n\n## RPC\n\nKit 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).\n\nThe main package responsible for managing communication with an RPC is `@solana/rpc`. However, this package makes use of more granular packages to break down the RPC logic into smaller pieces. Namely, these packages are:\n\n- `@solana/rpc`: Contains all logic related to sending Solana RPC calls.\n- `@solana/rpc-api`: Describes all Solana RPC methods using types.\n- `@solana/rpc-transport-http`: Provides a concrete implementation of an RPC transport using HTTP requests.\n- `@solana/rpc-spec`: Defines the JSON RPC spec for sending RPC requests.\n- `@solana/rpc-spec-types`: Shared JSON RPC specifications types and helpers that are used by both `@solana/rpc` and `@solana/rpc-subscriptions` (described in the next section).\n- `@solana/rpc-types`: Shared Solana RPC types and helpers that are used by both `@solana/rpc` and `@solana/rpc-subscriptions`.\n\nThe main `@solana/kit` package re-exports the `@solana/rpc` package so, going forward, we will import RPC types and functions from the library directly.\n\n### RPC Calls\n\nYou can use the `createSolanaRpc` function by providing the URL of a Solana JSON RPC server. This will create a default client for interacting with the Solana JSON RPC API.\n\n```ts\nimport { createSolanaRpc } from '@solana/kit';\n\n// Create an RPC client.\nconst rpc = createSolanaRpc('http://127.0.0.1:8899');\n//    ^? Rpc\u003cSolanaRpcApi\u003e\n\n// Send a request.\nconst slot = await rpc.getSlot().send();\n```\n\n### Custom RPC Transports\n\nThe `createSolanaRpc` function communicates with the RPC server using a default HTTP transport that should satisfy most use cases. You can provide your own transport or wrap an existing one to communicate with RPC servers in any way you see fit. In the example below, we explicitly create a transport and use it to create a new RPC client via the `createSolanaRpcFromTransport` function.\n\n```ts\nimport { createSolanaRpcFromTransport, createDefaultRpcTransport } from '@solana/kit';\n\n// Create an HTTP transport or any custom transport of your choice.\nconst transport = createDefaultRpcTransport({ url: 'https://api.devnet.solana.com' });\n\n// Create an RPC client using that transport.\nconst rpc = createSolanaRpcFromTransport(transport);\n//    ^? Rpc\u003cSolanaRpcApi\u003e\n\n// Send a request.\nconst slot = await rpc.getSlot().send();\n```\n\nA custom transport can implement specialized functionality such as coordinating multiple transports, implementing retries, and more. Let's take a look at some concrete examples.\n\n#### Round Robin\n\nA ‘round robin’ transport is one that distributes requests to a list of endpoints in sequence.\n\n```ts\nimport { createDefaultRpcTransport, createSolanaRpcFromTransport, type RpcTransport } from '@solana/kit';\n\n// Create an HTTP transport for each RPC server.\nconst transports = [\n    createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-1.com' }),\n    createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-2.com' }),\n    createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-3.com' }),\n];\n\n// Set up the round-robin transport.\nlet nextTransport = 0;\nasync function roundRobinTransport\u003cTResponse\u003e(...args: Parameters\u003cRpcTransport\u003e): Promise\u003cTResponse\u003e {\n    const transport = transports[nextTransport];\n    nextTransport = (nextTransport + 1) % transports.length;\n    return await transport(...args);\n}\n\n// Create an RPC client using the round-robin transport.\nconst rpc = createSolanaRpcFromTransport(roundRobinTransport);\n```\n\n#### Sharding\n\nA sharding transport is a kind of distributing transport that sends requests to a particular server based on something about the request itself. Here’s an example that sends requests to different servers depending on the name of the method:\n\n```ts\nimport { createDefaultRpcTransport, createSolanaRpcFromTransport, type RpcTransport } from '@solana/kit';\n\n// Create multiple transports.\nconst transportA = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-1.com' });\nconst transportB = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-2.com' });\nconst transportC = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-3.com' });\nconst transportD = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-4.com' });\n\n// Function to determine which shard to use based on the request method.\nfunction selectShard(method: string): RpcTransport {\n    switch (method) {\n        case 'getAccountInfo':\n        case 'getBalance':\n            return transportA;\n        case 'getLatestBlockhash':\n        case 'getTransaction':\n            return transportB;\n        case 'sendTransaction':\n            return transportC;\n        default:\n            return transportD;\n    }\n}\n\n// Create a transport that selects the correct transport given the request method name.\nasync function shardingTransport\u003cTResponse\u003e(...args: Parameters\u003cRpcTransport\u003e): Promise\u003cTResponse\u003e {\n    const payload = args[0].payload as { method: string };\n    const selectedTransport = selectShard(payload.method);\n    return (await selectedTransport(...args)) as TResponse;\n}\n\n// Create an RPC client using the sharding transport.\nconst rpc = createSolanaRpcFromTransport(shardingTransport);\n```\n\n#### Retry\n\nA custom transport is a good place to implement global retry logic for every request:\n\n```ts\nimport { createDefaultRpcTransport, createSolanaRpcFromTransport, type RpcTransport } from '@solana/kit';\n\n// Set the maximum number of attempts to retry a request.\nconst MAX_ATTEMPTS = 4;\n\n// Create the default transport.\nconst defaultTransport = createDefaultRpcTransport({ url: 'https://mainnet-beta.my-server-1.com' });\n\n// Sleep function to wait for a given number of milliseconds.\nfunction sleep(ms: number): Promise\u003cvoid\u003e {\n    return new Promise(resolve =\u003e setTimeout(resolve, ms));\n}\n\n// Calculate the delay for a given attempt.\nfunction calculateRetryDelay(attempt: number): number {\n    // Exponential backoff with a maximum of 1.5 seconds.\n    return Math.min(100 * Math.pow(2, attempt), 1500);\n}\n\n// A retrying transport that will retry up to MAX_ATTEMPTS times before failing.\nasync function retryingTransport\u003cTResponse\u003e(...args: Parameters\u003cRpcTransport\u003e): Promise\u003cTResponse\u003e {\n    let requestError;\n    for (let attempts = 0; attempts \u003c MAX_ATTEMPTS; attempts++) {\n        try {\n            return await defaultTransport(...args);\n        } catch (err) {\n            requestError = err;\n            // Only sleep if we have more attempts remaining.\n            if (attempts \u003c MAX_ATTEMPTS - 1) {\n                const retryDelay = calculateRetryDelay(attempts);\n                await sleep(retryDelay);\n            }\n        }\n    }\n    throw requestError;\n}\n\n// Create the RPC client using the retrying transport.\nconst rpc = createSolanaRpcFromTransport(retryingTransport);\n```\n\n#### Failover\n\nSupport for handling network failures can be implemented in the transport itself. Here’s an example of some failover logic integrated into a transport:\n\n```ts\nimport { createDefaultRpcTransport, createSolanaRpcFromTransport, type RpcTransport } from '@solana/kit';\n\n// List of RPC endpoints for failover.\nconst rpcEndpoints = [\n    'https://mainnet-beta.my-server-1.com',\n    'https://mainnet-beta.my-server-2.com',\n    'https://mainnet-beta.my-server-3.com',\n    'https://mainnet-beta.my-server-3.com',\n];\n\n// Create an array of transports from the endpoints.\nconst transports = rpcEndpoints.map(url =\u003e createDefaultRpcTransport({ url }));\n\n// A failover transport that switches to the next transport on failure.\nasync function failoverTransport\u003cTResponse\u003e(...args: Parameters\u003cRpcTransport\u003e): Promise\u003cTResponse\u003e {\n    let lastError;\n    for (const transport of transports) {\n        try {\n            return await transport(...args);\n        } catch (err) {\n            lastError = err;\n            console.warn(`Transport failed: ${err}. Trying next transport...`);\n        }\n    }\n    // If all transports fail, throw the last error.\n    throw lastError;\n}\n\n// Create the RPC client using the failover transport.\nconst rpc = createSolanaRpcFromTransport(failoverTransport);\n```\n\n### Augmenting/Constraining the RPC API\n\nUsing the `createSolanaRpc` or `createSolanaRpcFromTransport` methods, we always get the same API that includes the Solana RPC API methods. Since the RPC API is described using types only, it is possible to augment those types to add your own methods.\n\nWhen constraining the API scope, keep in mind that types don’t affect bundle size. You may still like to constrain the type-spec for a variety of reasons, including reducing TypeScript noise.\n\n#### Constraining by Cluster\n\nIf you're using a specific cluster, you may wrap your RPC URL inside a helper function like `mainnet` or `devnet` to inject that information into the RPC type system.\n\n```ts\nimport { createSolanaRpc, mainnet, devnet } from '@solana/kit';\n\nconst mainnetRpc = createSolanaRpc(mainnet('https://api.mainnet-beta.solana.com'));\n//    ^? RpcMainnet\u003cSolanaRpcApiMainnet\u003e\n\nconst devnetRpc = createSolanaRpc(devnet('https://api.devnet.solana.com'));\n//    ^? RpcDevnet\u003cSolanaRpcApiDevnet\u003e\n```\n\nIn the example above, `devnetRpc.requestAirdrop(..)` will work, but `mainnetRpc.requestAirdrop(..)` will raise a TypeScript error since `requestAirdrop` is not a valid method of the mainnet cluster.\n\n#### Cherry-Picking API Methods\n\nYou can constrain the API’s type-spec even further so you are left only with the methods you need. The simplest way to do this is to cast the created RPC client to a type that only includes the required methods.\n\n```ts\nimport { createSolanaRpc, type Rpc, type GetAccountInfoApi, type GetMultipleAccountsApi } from '@solana/kit';\n\nconst rpc = createSolanaRpc('http://127.0.0.1:8899') as Rpc\u003cGetAccountInfoApi \u0026 GetMultipleAccountsApi\u003e;\n```\n\nAlternatively, you can explicitly create the RPC API using the `createSolanaRpcApi` function. You will need to create your own transport and bind the two together using the `createRpc` function.\n\n```ts\nimport {\n    createDefaultRpcTransport,\n    createRpc,\n    createSolanaRpcApi,\n    DEFAULT_RPC_CONFIG,\n    type GetAccountInfoApi,\n    type GetMultipleAccountsApi,\n} from '@solana/kit';\n\nconst api = createSolanaRpcApi\u003cGetAccountInfoApi \u0026 GetMultipleAccountsApi\u003e(DEFAULT_RPC_CONFIG);\nconst transport = createDefaultRpcTransport({ url: 'http://127.0.0.1:8899' });\n\nconst rpc = createRpc({ api, transport });\n```\n\nNote that the `createSolanaRpcApi` function is a wrapper on top of the `createJsonRpcApi` function which adds some Solana-specific transformers such as setting a default commitment on all methods or throwing an error when an integer overflow is detected.\n\n#### Creating Your Own API Methods\n\nThe new library’s RPC specification supports an _infinite_ number of JSON-RPC methods with **zero increase** in bundle size.\n\nThis means the library can support future additions to the official [Solana JSON RPC](https://docs.solana.com/api), or [custom RPC methods](https://docs.helius.dev/compression-and-das-api/digital-asset-standard-das-api/get-asset) defined by some RPC provider.\n\nHere’s an example of how a developer at might build a custom RPC type-spec for an RPC provider's implementation of the Metaplex Digital Asset Standard's `getAsset` method:\n\n```ts\n// Define the method's response payload.\ntype GetAssetApiResponse = Readonly\u003c{\n    interface: DasApiAssetInterface;\n    id: Address;\n    content: Readonly\u003c{\n        files?: readonly {\n            mime?: string;\n            uri?: string;\n            [key: string]: unknown;\n        }[];\n        json_uri: string;\n        links?: readonly {\n            [key: string]: unknown;\n        }[];\n        metadata: DasApiMetadata;\n    }\u003e;\n    /* ...etc... */\n}\u003e;\n\n// Set up a type spec for the request method.\ntype GetAssetApi = {\n    // Define the method's name, parameters and response type\n    getAsset(args: { id: Address }): GetAssetApiResponse;\n};\n\n// Export the type spec for downstream users.\nexport type MetaplexDASApi = GetAssetApi;\n```\n\nHere’s how a developer might use it:\n\n```ts\nimport { createDefaultRpcTransport, createRpc, createJsonRpcApi } from '@solana/kit';\n\n// Create the custom API.\nconst api = createJsonRpcApi\u003cMetaplexDASApi\u003e();\n\n// Set up an HTTP transport to a server that supports the custom API.\nconst transport = createDefaultRpcTransport({\n    url: 'https://mainnet.helius-rpc.com/?api-key=\u003capi_key\u003e',\n});\n\n// Create the RPC client.\nconst metaplexDASRpc = createRpc({ api, transport });\n//    ^? Rpc\u003cMetaplexDASApi\u003e\n```\n\nAs long as a particular JSON RPC method adheres to the [official JSON RPC specification](https://www.jsonrpc.org/specification), it will be supported by Kit.\n\n### Aborting RPC Requests\n\nRPC requests are now abortable with modern `AbortControllers`. When calling an RPC method such as `getSlot`, it will return a `PendingRpcRequest` proxy object that contains a `send` method to send the request to the server.\n\n```ts\nconst pendingRequest: PendingRpcRequest\u003cSlot\u003e = rpc.getSlot();\n\nconst slot: Slot = await pendingRequest.send();\n```\n\nThe arguments of the `getSlot` method are reserved for the request payload, but the `send` method is where additional arguments such as an `AbortSignal` can be accepted in the context of the request.\n\nAborting RPC requests can be useful for a variety of things such as setting a timeout on a request or cancelling a request when a user navigates away from a page.\n\n```ts\nimport { createSolanaRpc } from '@solana/kit';\n\nconst rpc = createSolanaRpc('http://127.0.0.1:8900');\n\n// Create a new AbortController.\nconst abortController = new AbortController();\n\n// Abort the request when the user navigates away from the current page.\nfunction onUserNavigateAway() {\n    abortController.abort();\n}\n\n// The request will be aborted if and only if the user navigates away from the page.\nconst slot = await rpc.getSlot().send({ abortSignal: abortController.signal });\n```\n\nRead more about `AbortController` here:\n\n- [Mozilla Developer Docs: `AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)\n- [Mozilla Developer Docs: `AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)\n- [JavaScript.info: Fetch: Abort](https://javascript.info/fetch-abort)\n\n## RPC Subscriptions\n\nSubscriptions in the legacy library do not allow custom retry logic and do not allow you to recover from 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.\n\nThe main package responsible for managing communication with RPC subscriptions is `@solana/rpc-subscriptions`. However, similarly to `@solana/rpc`, this package also makes use of more granular packages. These packages are:\n\n- `@solana/rpc-subscriptions`: Contains all logic related to subscribing to Solana RPC notifications.\n- `@solana/rpc-subscriptions-api`: Describes all Solana RPC subscriptions using types.\n- `@solana/rpc-subscriptions-channel-websocket`: Provides a concrete implementation of an RPC Subscriptions channel using WebSockets.\n- `@solana/rpc-subscriptions-spec`: Defines the JSON RPC spec for subscribing to RPC notifications.\n- `@solana/rpc-spec-types`: Shared JSON RPC specifications types and helpers that are used by both `@solana/rpc` and `@solana/rpc-subscriptions`.\n- `@solana/rpc-types`: Shared Solana RPC types and helpers that are used by both `@solana/rpc` and `@solana/rpc-subscriptions`.\n\nSince the main `@solana/kit` library also re-exports the `@solana/rpc-subscriptions` package we will import RPC Subscriptions types and functions directly from the main library going forward.\n\n### Getting Started with RPC Subscriptions\n\nTo get started with RPC Subscriptions, you may use the `createSolanaRpcSubscriptions` function by providing the WebSocket URL of a Solana JSON RPC server. This will create a default client for interacting with Solana RPC Subscriptions.\n\n```ts\nimport { createSolanaRpcSubscriptions } from '@solana/kit';\n\n// Create an RPC Subscriptions client.\nconst rpcSubscriptions = createSolanaRpcSubscriptions('ws://127.0.0.1:8900');\n//    ^? RpcSubscriptions\u003cSolanaRpcSubscriptionsApi\u003e\n```\n\n### Subscriptions as `AsyncIterators`\n\nThe 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.\n\nHere’s an example of working with a subscription in the new library:\n\n```ts\nimport { address, createSolanaRpcSubscriptions, createDefaultRpcSubscriptionsTransport } from '@solana/kit';\n\n// Create the RPC Subscriptions client.\nconst rpcSubscriptions = createSolanaRpcSubscriptions('ws://127.0.0.1:8900');\n\n// Set up an abort controller.\nconst abortController = new AbortController();\n\n// Subscribe to account notifications.\nconst accountNotifications = await rpcSubscriptions\n    .accountNotifications(address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3'), { commitment: 'confirmed' })\n    .subscribe({ abortSignal: abortController.signal });\n\ntry {\n    // Consume messages.\n    for await (const notification of accountNotifications) {\n        console.log('New balance', notification.value.lamports);\n    }\n} catch (e) {\n    // The subscription went down.\n    // Retry it and then recover from potentially having missed\n    // a balance update, here (eg. by making a `getBalance()` call).\n}\n```\n\nYou can read more about `AsyncIterator` at the following links:\n\n- [Mozilla Developer Docs: `AsyncIterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator)\n- [Luciano Mammino (Blog): JavaScript Async Iterators](https://www.nodejsdesignpatterns.com/blog/javascript-async-iterators/)\n\n### Aborting RPC Subscriptions\n\nSimilarly to RPC calls, applications can terminate active subscriptions using an `AbortController` attribute on the `subscribe` method. In fact, this parameter is _required_ for subscriptions to encourage you to clean up subscriptions that your application no longer needs.\n\nLet's take a look at some concrete examples that demonstrate how to abort subscriptions.\n\n#### Subscription Timeout\n\nHere's an example of an `AbortController` used to abort a subscription after a 5-second timeout:\n\n```ts\nimport { createSolanaRpcSubscriptions } from '@solana/kit';\n\nconst rpcSubscriptions = createSolanaRpcSubscriptions('ws://127.0.0.1:8900');\n\n// Subscribe for slot notifications using an AbortSignal that times out after 5 seconds.\nconst slotNotifications = await rpcSubscriptions\n    .slotNotifications()\n    .subscribe({ abortSignal: AbortSignal.timeout(5000) });\n\n// Log slot notifications.\nfor await (const notification of slotNotifications) {\n    console.log('Slot notification', notification);\n}\n\nconsole.log('Done.');\n```\n\nRead more about `AbortController` at the following links:\n\n- [Mozilla Developer Docs: `AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)\n- [Mozilla Developer Docs: `AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)\n- [JavaScript.info: Fetch: Abort](https://javascript.info/fetch-abort)\n\n#### Cancelling Subscriptions\n\nIt is also possible to abort a subscription inside the `for await...of` loop. This enables us to cancel a subscription based on some condition, such as a change in the state of an account. For instance, the following example cancels a subscription when the owner of an account changes:\n\n```ts\n// Subscribe to account notifications.\nconst accountNotifications = await rpc\n    .accountNotifications(address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3'), { commitment: 'confirmed' })\n    .subscribe({ abortSignal });\n\n// Consume messages.\nlet previousOwner = null;\nfor await (const notification of accountNotifications) {\n    const {\n        value: { owner },\n    } = notification;\n    // Check the owner to see if it has changed\n    if (previousOwner \u0026\u0026 owner !== previousOwner) {\n        // If so, abort the subscription\n        abortController.abort();\n    } else {\n        console.log(notification);\n    }\n    previousOwner = owner;\n}\n```\n\n### Failed vs. Aborted Subscriptions\n\nIt is important to note that a subscription failure behaves differently from a subscription abort. A subscription failure occurs when the subscription goes down and will throw an error that can be intercepted in a `try/catch`. However, an aborted subscription will not throw an error, but will instead exit the `for await...of` loop.\n\n```ts\ntry {\n    for await (const notification of notifications) {\n        // Consume messages.\n    }\n    // [ABORTED] Reaching this line means the subscription was aborted — i.e. unsubscribed.\n} catch (e) {\n    // [FAILED] Reaching this line means the subscription went down.\n    // Retry it, then recover from potential missed messages.\n} finally {\n    // [ABORTED or FAILED] Whether the subscription failed or was aborted, you can run cleanup code here.\n}\n```\n\n### Message Gap Recovery\n\nOne 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`.\n\nWhen 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-establishing the subscription.\n\nHere’s an example of such logic:\n\n```ts\ntry {\n    for await (const notif of accountNotifications) {\n        updateAccountBalance(notif.lamports);\n    }\n} catch (e) {\n    // The subscription failed.\n    // First, re-establish the subscription.\n    await setupAccountBalanceSubscription(address);\n    // Then make a one-shot request to 'catch up' on any missed balance changes.\n    const { value: lamports } = await rpc.getBalance(address).send();\n    updateAccountBalance(lamports);\n}\n```\n\n### Using Custom RPC Subscriptions Transports\n\nThe `createSolanaRpcSubscriptions` function communicates with the RPC server using a default `WebSocket` channel that should satisfy most use cases. However, you may here as well provide your own channel creator or decorate existing ones to communicate with RPC servers in any way you see fit. In the example below, we supply a custom `WebSocket` channel creator and use it to create a new RPC Subscriptions client via the `createSolanaRpcSubscriptionsFromTransport` function.\n\n```ts\nimport { createDefaultRpcSubscriptionsTransport, createSolanaRpcSubscriptionsFromTransport } from '@solana/kit';\n\n// Create a transport with a custom channel creator of your choice.\nconst transport = createDefaultRpcSubscriptionsTransport({\n    createChannel({ abortSignal }) {\n        return createWebSocketChannel({\n            maxSubscriptionsPerChannel: 100,\n            minChannels: 25,\n            sendBufferHighWatermark: 32_768,\n            signal: abortSignal,\n            url: 'ws://127.0.0.1:8900',\n        });\n    },\n});\n\n// Create an RPC client using that transport.\nconst rpcSubscriptions = createSolanaRpcSubscriptionsFromTransport(transport);\n//    ^? RpcSubscriptions\u003cSolanaRpcSubscriptionsApi\u003e\n```\n\n### Augmenting/Constraining the RPC Subscriptions API\n\nUsing the `createSolanaRpcSubscriptions` or `createSolanaRpcSubscriptionsFromTransport` functions, we always get the same RPC Subscriptions API, including all Solana RPC stable subscriptions. However, since the RPC Subscriptions API is described using types only, it is possible to constrain the API to a specific set of subscriptions or even add your own custom subscriptions.\n\n#### Constraining by Cluster\n\nIf you're using a specific cluster, you may wrap your RPC URL inside a helper function like `mainnet` or `devnet` to inject that information into the RPC type system.\n\n```ts\nimport { createSolanaRpcSubscriptions, mainnet, devnet } from '@solana/kit';\n\nconst mainnetRpc = createSolanaRpcSubscriptions(mainnet('https://api.mainnet-beta.solana.com'));\n//    ^? RpcSubscriptionsMainnet\u003cSolanaRpcSubscriptionsApi\u003e\n\nconst devnetRpc = createSolanaRpcSubscriptions(devnet('https://api.devnet.solana.com'));\n//    ^? RpcSubscriptionsDevnet\u003cSolanaRpcSubscriptionsApi\u003e\n```\n\n#### Including Unstable Subscriptions\n\nIf your app needs access to [unstable RPC Subscriptions](https://docs.solana.com/api/websocket#blocksubscribe) — e.g. `BlockNotificationsApi` or `SlotsUpdatesNotificationsApi` — and your RPC server supports them, you may use the `createSolanaRpcSubscriptions_UNSTABLE` and `createSolanaRpcSubscriptionsFromTransport_UNSTABLE` functions to create an RPC Subscriptions client that includes those subscriptions.\n\n```ts\nimport {\n    createDefaultSolanaRpcSubscriptionsChannelCreator,\n    createDefaultRpcSubscriptionsTransport,\n    createSolanaRpcSubscriptions_UNSTABLE,\n    createSolanaRpcSubscriptionsFromTransport_UNSTABLE,\n} from '@solana/kit';\n\n// Using the default WebSocket channel.\nconst rpcSubscriptions = createSolanaRpcSubscriptions_UNSTABLE('ws://127.0.0.1:8900');\n//    ^? RpcSubscriptions\u003cSolanaRpcSubscriptionsApi \u0026 SolanaRpcSubscriptionsApiUnstable\u003e\n\n// Using a custom transport.\nconst transport = createDefaultRpcSubscriptionsTransport({\n    createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({\n        url: 'ws://127.0.0.1:8900',\n    }),\n});\nconst rpcSubscriptions = createSolanaRpcSubscriptionsFromTransport_UNSTABLE(transport);\n//    ^? RpcSubscriptions\u003cSolanaRpcSubscriptionsApi \u0026 SolanaRpcSubscriptionsApiUnstable\u003e\n```\n\n#### Cherry-Picking API Methods\n\nYou may constrain the scope of the Subscription API even further so you are left only with the subscriptions you need. The simplest way to do this is to cast the created RPC client to a type that only includes the methods you need.\n\n```ts\nimport {\n    createSolanaRpcSubscriptions,\n    type RpcSubscriptions,\n    type AccountNotificationsApi,\n    type SlotNotificationsApi,\n} from '@solana/kit';\n\nconst rpc = createSolanaRpcSubscriptions('ws://127.0.0.1:8900') as RpcSubscriptions\u003c\n    AccountNotificationsApi \u0026 SlotNotificationsApi\n\u003e;\n```\n\nAlternatively, you may explicitly create the RPC Subscriptions API using the `createSolanaRpcSubscriptionsApi` function. You will then need to create your own transport explicitly and bind the two together using the `createSubscriptionRpc` function.\n\n```ts\nimport {\n    createDefaultSolanaRpcSubscriptionsChannelCreator,\n    createDefaultRpcSubscriptionsTransport,\n    createSubscriptionRpc,\n    createSolanaRpcSubscriptionsApi,\n    DEFAULT_RPC_CONFIG,\n    type AccountNotificationsApi,\n    type SlotNotificationsApi,\n} from '@solana/kit';\n\nconst api = createSolanaRpcSubscriptionsApi\u003cAccountNotificationsApi \u0026 SlotNotificationsApi\u003e(DEFAULT_RPC_CONFIG);\nconst transport = createDefaultRpcSubscriptionsTransport({\n    createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({\n        url: 'ws://127.0.0.1:8900',\n    }),\n});\nconst rpcSubscriptions = createSubscriptionRpc({ api, transport });\n```\n\nNote that the `createSolanaRpcSubscriptionsApi` function is a wrapper on top of the `createRpcSubscriptionsApi` function which adds some Solana-specific transformers such as setting a default commitment on all methods or throwing an error when an integer overflow is detected.\n\n## Keys\n\nThe 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.\n\n### Web Crypto API\n\nAll key operations now use the native Ed25519 implementation in JavaScript’s Web Crypto API.\n\nThe 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**.\n\nOne thing to note is that many operations from Web Crypto – such as importing, generating, signing, and verifying are now **asynchronous**.\n\nHere’s an example of generating a `CryptoKeyPair` using the Web Crypto API and signing a message:\n\n```ts\nimport { generateKeyPair, signBytes, verifySignature } from '@solana/kit';\n\nconst keyPair: CryptoKeyPair = await generateKeyPair();\n\nconst message = new Uint8Array(8).fill(0);\n\nconst signedMessage = await signBytes(keyPair.privateKey, message);\n//    ^? Signature\n\nconst verified = await verifySignature(keyPair.publicKey, signedMessage, message);\n```\n\n### Web Crypto Polyfill\n\nWherever Ed25519 is not supported, we offer a polyfill for Web Crypto’s Ed25519 API.\n\nThis 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.\n\nDetermine if your target runtime supports Ed25519, and install the polyfill if it does not:\n\n```ts\nimport { install } from '@solana/webcrypto-ed25519-polyfill';\nimport { generateKeyPair, signBytes, verifySignature } from '@solana/kit';\n\ninstall();\nconst keyPair: CryptoKeyPair = await generateKeyPair();\n\n/* Remaining logic */\n```\n\nYou 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.\n\nOperations on `CryptoKey` objects using the Web Crypto API _or_ the polyfill are mostly handled by the `@solana/keys` package.\n\n### String Addresses\n\nAll addresses are now JavaScript strings. They are represented by the opaque type `Address`, which describes exactly what a Solana address actually is.\n\nConsequently, that means no more `PublicKey`.\n\nHere’s what they look like in development:\n\n```ts\nimport { Address, address, getAddressFromPublicKey, generateKeyPair } from '@solana/kit';\n\n// Coerce a string to an `Address`\nconst myOtherAddress = address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3');\n\n// Typecast it instead\nconst myAddress =\n    'AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3' as Address\u003c'AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3'\u003e;\n\n// From CryptoKey\nconst keyPair = await generateKeyPair();\nconst myPublicKeyAsAddress = await getAddressFromPublicKey(keyPair.publicKey);\n```\n\nSome tooling for working with base58-encoded addresses can be found in the `@solana/addresses` package.\n\n## Transactions\n\n### Creating Transaction Messages\n\nLike many other familiar aspects of the 1.0 library, transactions have received a makeover.\n\nFor starters, all transaction messages are now version-aware, so there’s no longer a need to juggle two different types (eg. `Transaction` vs. `VersionedTransaction`).\n\nAddress lookups are now completely described inside transaction message instructions, so you don’t have to materialize `addressTableLookups` anymore.\n\nHere’s a simple example of creating a transaction message \u0026ndash; notice how its type is refined at each step of the process:\n\n```ts\nimport {\n    address,\n    createTransactionMessage,\n    setTransactionMessageFeePayer,\n    setTransactionMessageLifetimeUsingBlockhash,\n    Blockhash,\n} from '@solana/kit';\n\nconst recentBlockhash = {\n    blockhash: '4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY' as Blockhash,\n    lastValidBlockHeight: 196055492n,\n};\nconst feePayer = address('AxZfZWeqztBCL37Mkjkd4b8Hf6J13WCcfozrBY6vZzv3');\n\n// Create a new transaction message\nconst transactionMessage = createTransactionMessage({ version: 0 });\n//    ^? V0TransactionMessage\n\n// Set the fee payer\nconst transactionMessageWithFeePayer = setTransactionMessageFeePayer(feePayer, transactionMessage);\n//    ^? V0TransactionMessage \u0026 TransactionMessageWithFeePayer\n\nconst transactionMessageWithFeePayerAndLifetime = setTransactionMessageLifetimeUsingBlockhash(\n    // ^? V0TransactionMessage \u0026 TransactionMessageWithFeePayer \u0026 TransactionMessageWithBlockhashLifetime\n    recentBlockhash,\n    transactionMessageWithFeePayer,\n);\n```\n\nAs you can see, each time a transaction message is modified, the type reflects its new shape. If you add a fee payer, you’ll get a type representing a transaction message with a fee payer, and so on.\n\nTransaction message objects are also **frozen by these functions** to prevent them from being mutated in place.\n\n### Signing Transaction Messages\n\nThe `signTransaction(..)` function will raise a type error if your transaction message is not already equipped with a fee payer and a lifetime. This helps you catch errors at author-time instead of runtime.\n\n```ts\nconst feePayer = await generateKeyPair();\nconst feePayerAddress = await getAddressFromPublicKey(feePayer.publicKey);\n\nconst transactionMessage = createTransactionMessage({ version: 'legacy' });\nconst transactionMessageWithFeePayer = setTransactionMessageFeePayer(feePayerAddress, transactionMessage);\n\n// Attempting to sign the transaction message without a lifetime will throw a type error\nconst signedTransaction = await signTransaction([signer], transactionMessageWithFeePayer);\n// =\u003e \"Property 'lifetimeConstraint' is missing in type\"\n```\n\n### Calibrating a Transaction Message's Compute Unit Budget\n\nCorrectly budgeting a compute unit limit for your transaction message can increase the probability that your transaction will be accepted for processing. If you don't declare a compute unit limit on your transaction, validators will assume an upper limit of 200K compute units (CU) per instruction.\n\nSince validators have an incentive to pack as many transactions into each block as possible, they may choose to include transactions that they know will fit into the remaining compute budget for the current block over transactions that might not. For this reason, you should set a compute unit limit on each of your transaction messages, whenever possible.\n\nUse this utility to estimate the actual compute unit cost of a given transaction message.\n\n```ts\nimport { getSetComputeUnitLimitInstruction } from '@solana-program/compute-budget';\nimport { createSolanaRpc, getComputeUnitEstimateForTransactionMessageFactory, pipe } from '@solana/kit';\n\n// Create an estimator function.\nconst rpc = createSolanaRpc('http://127.0.0.1:8899');\nconst getComputeUnitEstimateForTransactionMessage = getComputeUnitEstimateForTransactionMessageFactory({\n    rpc,\n});\n\n// Create your transaction message.\nconst transactionMessage = pipe(\n    createTransactionMessage({ version: 'legacy' }),\n    /* ... */\n);\n\n// Request an estimate of the actual compute units this message will consume.\nconst computeUnitsEstimate = await getComputeUnitEstimateForTransactionMessage(transactionMessage);\n\n// Set the transaction message's compute unit budget.\nconst transactionMessageWithComputeUnitLimit = prependTransactionMessageInstruction(\n    getSetComputeUnitLimitInstruction({ units: computeUnitsEstimate }),\n    transactionMessage,\n);\n```\n\n\u003e [!WARNING]\n\u003e The compute unit estimate is just that \u0026ndash; an estimate. The compute unit consumption of the actual transaction might be higher or lower than what was observed in simulation. Unless you are confident that your particular transaction message will consume the same or fewer compute units as was estimated, you might like to augment the estimate by either a fixed number of CUs or a multiplier.\n\n\u003e [!NOTE]\n\u003e If you are preparing an _unsigned_ transaction, destined to be signed and submitted to the network by a wallet, you might like to leave it up to the wallet to determine the compute unit limit. Consider that the wallet might have a more global view of how many compute units certain types of transactions consume, and might be able to make better estimates of an appropriate compute unit budget.\n\n### Helpers For Building Transaction Messages\n\nBuilding transaction messages in this manner might feel different from what you’re used to. Also, we certainly wouldn’t want you to have to bind transformed transaction messages to a new variable at each step, so we have released a functional programming library dubbed `@solana/functional` that lets you build transaction messages in **pipelines**. Here’s how it can be used:\n\n```ts\nimport { pipe } from '@solana/functional';\nimport {\n    address,\n    createTransactionMessage,\n    setTransactionMessageFeePayer,\n    setTransactionMessageLifetimeUsingBlockhash,\n    Blockhash,\n} from '@solana/kit';\n\n// Use `pipe(..)` to create a pipeline of transaction message transformation operations\nconst transactionMessage = pipe(\n    createTransactionMessage({ version: 0 }),\n    tx =\u003e setTransactionMessageFeePayer(feePayer, tx),\n    tx =\u003e setTransactionMessageLifetimeUsingBlockhash(recentBlockhash, tx),\n);\n```\n\nNote that `pipe(..)` is general-purpose, so it can be used to pipeline any functional transforms.\n\n## Codecs\n\nWe have taken steps to make it easier to write data (de)serializers, especially as they pertain to Rust datatypes and byte buffers.\n\nSolana’s codecs libraries are broken up into modular components so you only need to import the ones you need. They are:\n\n- `@solana/codecs-core`: The core codecs library for working with codecs serializers and creating custom ones\n- `@solana/codecs-numbers`: Used for serialization of numbers (little-endian and big-endian bytes, etc.)\n- `@solana/codecs-strings`: Used for serialization of strings\n- `@solana/codecs-data-structures`: Codecs and serializers for structs\n- `@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\n\nThese packages are included in the main `@solana/kit` library but you may also import them from `@solana/codecs` if you only need the codecs.\n\nHere’s an example of encoding and decoding a custom struct with some strings and numbers:\n\n```ts\nimport { addCodecSizePrefix } from '@solana/codecs-core';\nimport { getStructCodec } from '@solana/codecs-data-structures';\nimport { getU32Codec, getU64Codec, getU8Codec } from '@solana/codecs-numbers';\nimport { getUtf8Codec } from '@solana/codecs-strings';\n\n// Equivalent in Rust:\n// struct {\n//     amount: u64,\n//     decimals: u8,\n//     name: String,\n// }\nconst structCodec = getStructCodec([\n    ['amount', getU64Codec()],\n    ['decimals', getU8Codec()],\n    ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n]);\n\nconst myToken = {\n    amount: 1000000000000000n, // `bigint` or `number` is supported\n    decimals: 2,\n    name: 'My Token',\n};\n\nconst myEncodedToken: Uint8Array = structCodec.encode(myToken);\nconst myDecodedToken = structCodec.decode(myEncodedToken);\n\nmyDecodedToken satisfies {\n    amount: bigint;\n    decimals: number;\n    name: string;\n};\n```\n\nYou 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:\n\n```ts\nimport { Codec, combineCodec, Decoder, Encoder, addDecoderSizePrefix, addEncoderSizePrefix } from '@solana/codecs-core';\nimport { getStructDecoder, getStructEncoder } from '@solana/codecs-data-structures';\nimport {\n    getU8Decoder,\n    getU8Encoder,\n    getU32Decoder,\n    getU32Encoder,\n    getU64Decoder,\n    getU64Encoder,\n} from '@solana/codecs-numbers';\nimport { getUtf8Decoder, getUtf8Encoder } from '@solana/codecs-strings';\n\nexport type MyToken = {\n    amount: bigint;\n    decimals: number;\n    name: string;\n};\n\nexport type MyTokenArgs = {\n    amount: number | bigint;\n    decimals: number;\n    name: string;\n};\n\nexport const getMyTokenEncoder = (): Encoder\u003cMyTokenArgs\u003e =\u003e\n    getStructEncoder([\n        ['amount', getU64Encoder()],\n        ['decimals', getU8Encoder()],\n        ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n    ]);\n\nexport const getMyTokenDecoder = (): Decoder\u003cMyToken\u003e =\u003e\n    getStructDecoder([\n        ['amount', getU64Decoder()],\n        ['decimals', getU8Decoder()],\n        ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n    ]);\n\nexport const getMyTokenCodec = (): Codec\u003cMyTokenArgs, MyToken\u003e =\u003e\n    combineCodec(getMyTokenEncoder(), getMyTokenDecoder());\n```\n\nYou can read more about codecs in [the official Codec documentation](https://github.com/anza-xyz/kit/blob/main/packages/codecs/README.md).\n\n## Type-Safety\n\nThe new library makes use of some advanced TypeScript features, including generic types, conditional types, `Parameters\u003c..\u003e`, `ReturnType\u003c..\u003e` and more.\n\nWe’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.\n\n### RPC Types\n\nThe 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.\n\nHere’s an example of this in action:\n\n```ts\n// Provide one set of parameters, get a certain type\n// These parameters resolve to return type:\n// {\n//     blockhash: Blockhash;\n//     blockHeight: bigint;\n//     blockTime: UnixTimestamp;\n//     parentSlot: bigint;\n//     previousBlockhash: Blockhash;\n// }\nconst blockResponse = await rpc\n    .getBlock(0n, {\n        rewards: false,\n        transactionDetails: 'none',\n    })\n    .send();\n\n// Switch `rewards` to `true`, get `rewards` in the return type\n// {\n//     /* ... Previous response */\n//     rewards: Reward[];\n// }\nconst blockWithRewardsResponse = await rpc\n    .getBlock(0n, {\n        rewards: true,\n        transactionDetails: 'none',\n    })\n    .send();\n\n// Switch `transactionDetails` to `full`, get `transactions` in the return type\n// {\n//     /* ... Previous response */\n//     transactions: TransactionResponse[];\n// }\nconst blockWithRewardsAndTransactionsResponse = await rpc\n    .getBlock(0n, {\n        rewards: true,\n        transactionDetails: 'full',\n    })\n    .send();\n```\n\n### Catching Compile-Time Bugs with TypeScript\n\nAs previously mentioned, the type coverage in Kit allows developers to catch common bugs at compile time, rather than runtime.\n\nIn the example below, a transaction message is created and then attempted to be signed 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:\n\n```ts\nconst transactionMessage = pipe(createTransactionMessage({ version: 0 }), tx =\u003e\n    setTransactionMessageLifetimeUsingBlockhash(recentBlockhash, tx),\n);\nconst signedTransaction = await signTransaction([keyPair], transactionMessage); // ERROR: Property 'feePayer' is missing in type\n```\n\nConsider 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:\n\n```ts\nconst transactionMessage = pipe(\n    createTransactionMessage({ version: 0 }),\n    tx =\u003e setTransactionMessageFeePayer(feePayerAddress, tx),\n    tx =\u003e setTransactionMessageLifetimeUsingBlockhash(recentBlockhash, tx),\n);\n\nconst signedTransaction = await signTransaction([], transactionMessage);\n\n// Asserts the transaction is a `FullySignedTransaction`\n// Throws an error if any signatures are missing!\nassertIsFullySignedTransaction(signedTransaction);\n\nawait sendAndConfirmTransaction(signedTransaction);\n```\n\nAre you building a nonce transaction and forgot to make `AdvanceNonce` the first instruction? That’s a type error:\n\n```ts\nconst feePayer = await generateKeyPair();\nconst feePayerAddress = await getAddressFromPublicKey(feePayer.publicKey);\n\nconst notNonceTransactionMessage = pipe(createTransactionMessage({ version: 0 }), tx =\u003e\n    setTransactionMessageFeePayer(feePayerAddress, tx),\n);\n\nnotNonceTransactionMessage satisfies TransactionMessageWithDurableNonceLifetime;\n// =\u003e Property 'lifetimeConstraint' is missing in type\n\nconst nonceConfig = {\n    nonce: 'nonce' as Nonce,\n    nonceAccountAddress: address('5tLU66bxQ35so2bReGcyf3GfMMAAauZdNA1N4uRnKQu4'),\n    nonceAuthorityAddress: address('GDhj8paPg8woUzp9n8fj7eAMocN5P7Ej3A7T9F5gotTX'),\n};\n\nconst stillNotNonceTransactionMessage = {\n    lifetimeConstraint: nonceConfig,\n    ...notNonceTransactionMessage,\n};\n\nstillNotNonceTransactionMessage satisfies TransactionMessageWithDurableNonceLifetime;\n// =\u003e 'readonly Instruction\u003cstring\u003e[]' is not assignable to type 'readonly [AdvanceNonceAccountInstruction\u003cstring, string\u003e, ...Instruction\u003cstring\u003e[]]'\n\nconst validNonceTransactionMessage = pipe(\n    createTransactionMessage({ version: 0 }),\n    tx =\u003e setTransactionMessageFeePayer(feePayerAddress, tx),\n    tx =\u003e setTransactionMessageLifetimeUsingDurableNonce(nonceConfig, tx), // Adds the instruction!\n);\n\nvalidNonceTransactionMessage satisfies TransactionMessageWithDurableNonceLifetime; // OK\n```\n\nThe library’s type-checking can even catch you using lamports instead of SOL for a value:\n\n```ts\nconst airdropAmount = 1n; // SOL\nconst signature = rpc.requestAirdrop(myAddress, airdropAmount).send();\n```\n\nIt will force you to cast the numerical value for your airdrop (or transfer, etc.) amount using `lamports()`, which should be a good reminder!\n\n```ts\nconst airdropAmount = lamports(1000000000n);\nconst signature = rpc.requestAirdrop(myAddress, airdropAmount).send();\n```\n\n## Compatibility Layer\n\nYou will have noticed by now that Kit is a complete and total breaking change from the web3.js 1.x line. We want to provide you with a strategy for interacting with web3.js 1.x APIs while building your application using Kit. You need a tool for converting between web3.js 1.x and Kit data types.\n\nThe `@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 `Address`, `Transaction`, and `CryptoKeyPair`.\n\nHere’s how you can use `@solana/compat` to convert from a legacy `PublicKey` to an `Address`:\n\n```ts\nimport { fromLegacyPublicKey } from '@solana/compat';\n\nconst publicKey = new PublicKey('B3piXWBQLLRuk56XG5VihxR4oe2PSsDM8nTF6s1DeVF5');\nconst address: Address = fromLegacyPublicKey(publicKey);\n```\n\nHere’s how to convert from a legacy `Keypair` to a `CryptoKeyPair`:\n\n```ts\nimport { fromLegacyKeypair } from '@solana/compat';\n\nconst keypairLegacy = Keypair.generate();\nconst cryptoKeyPair: CryptoKeyPair = fromLegacyKeypair(keypair);\n```\n\nHere’s how to convert legacy transaction objects to the new library’s transaction types:\n\n```ts\n// Note that you can only convert `VersionedTransaction` objects\nconst modernTransaction = fromVersionedTransaction(classicTransaction);\n```\n\nTo see more conversions supported by `@solana/compat`, you can check out the package’s [README on GitHub](https://github.com/anza-xyz/kit/blob/main/packages/compat/README.md).\n\n## Program Clients\n\nWriting 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.\n\nWe 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.\n\nWe use [Codama](https://github.com/codama-idl/codama) to represent Solana programs and generate clients for them. This includes a JavaScript client compatible with this library. For instance, here is how you’d construct a transaction message composed of instructions from three different core programs.\n\n```ts\nimport { appendTransactionMessageInstructions, createTransactionMessage, pipe } from '@solana/kit';\nimport { getAddMemoInstruction } from '@solana-program/memo';\nimport { getSetComputeUnitLimitInstruction } from '@solana-program/compute-budget';\nimport { getTransferSolInstruction } from '@solana-program/system';\n\nconst instructions = [\n    getSetComputeUnitLimitInstruction({ units: 600_000 }),\n    getTransferSolInstruction({ source, destination, amount: 1_000_000_000 }),\n    getAddMemoInstruction({ memo: \"I'm transferring some SOL!\" }),\n];\n\n// Creates a V0 transaction message with 3 instructions inside.\nconst transactionMessage = pipe(createTransactionMessage({ version: 0 }), tx =\u003e\n    appendTransactionMessageInstructions(instructions, tx),\n);\n```\n\nAs you can see, each program now generates its own library allowing you to cherry-pick your dependencies.\n\nNote that asynchronous versions may be available for some instructions which allows them to resolve more inputs on your behalf — such as PDA derivation. For instance, the `CreateLookupTable` instruction offers an asynchronous builder that derives the `address` account and the `bump` argument for us.\n\n```ts\nconst rpc = createSolanaRpc('http://127.0.0.1:8899');\nconst [authority, recentSlot] = await Promise.all([\n    generateKeyPairSigner(),\n    rpc.getSlot({ commitment: 'finalized' }).send(),\n]);\n\nconst instruction = await getCreateLookupTableInstructionAsync({\n    authority,\n    recentSlot,\n});\n```\n\nAlternatively, you may use the synchronous builder if you already have all the required inputs at hand.\n\n```ts\nconst [address, bump] = await findAddressLookupTablePda({\n    authority: authority.address,\n    recentSlot,\n});\n\nconst instruction = getCreateLookupTableInstruction({\n    address,\n    authority,\n    bump,\n    recentSlot,\n});\n```\n\nOn top of instruction builders, these clients offer a variety of utilities such as:\n\n- Instruction codecs — e.g. `getTransferSolInstructionDataCodec`.\n- Account types — e.g. `AddressLookupTable`.\n- Account codecs — e.g. `getAddressLookupTableAccountDataCodec`.\n- Account helpers — e.g. `fetchAddressLookupTable`.\n- PDA helpers — e.g. `findAddressLookupTablePda`, `fetchAddressLookupTableFromSeeds`.\n- Defined types and their codecs — e.g. `NonceState`, `getNonceStateCodec`.\n- Program helpers — e.g. `SYSTEM_PROGRAM_ADDRESS`, `SystemAccount` enum, `identifySystemInstruction`.\n- And much more!\n\nHere’s another example that fetches an `AddressLookupTable` PDA from its seeds.\n\n```ts\nconst account = await fetchAddressLookupTableFromSeeds(rpc, {\n    authority: authority.address,\n    recentSlot,\n});\n\naccount.address; // Address\naccount.lamports; // Lamports\naccount.data.addresses; // Address[]\naccount.data.authority; // Some\u003cAddress\u003e\naccount.data.deactivationSlot; // Slot\naccount.data.lastExtendedSlot; // Slot\naccount.data.lastExtendedSlotStartIndex; // number\n```\n\n### How Does This Work?\n\nAll of this code is 100% auto-generated by Codama from a tree of standardized nodes that represent our programs. It contains obvious nodes such as `AccountNode` but also more specified nodes such as `ConditionalValueNode` that allows us to resolve account or argument default values conditionally.\n\nCodama allows us to hydrate our tree of nodes from IDLs which are typically generated by program frameworks such as [Anchor](https://github.com/coral-xyz/anchor) or [Shank](https://github.com/metaplex-foundation/shank). Additionally, visitors can be used on our nodes to expand the knowledge of our programs since the IDL itself doesn’t yet contain that level of information. Finally, special visitors called ‘renderers’ visit our tree to generate clients such as this JavaScript client.\n\nCurrently, there is one other renderer that generates Rust clients but this is only the beginning. In the future, you can expect renderers for auto-generated Python clients, documentation, CLIs, etc.\n\n## Create Solana Program\n\nWe believe the whole ecosystem could benefit from generated program clients. That’s why we introduced a new NPM binary that allows you to create your Solana program — and generate clients for it — in no time. Simply run the following and follow the prompts to get started.\n\n```sh\npnpm create solana-program\n```\n\nThis [`create-solana-program`](https://github.com/solana-program/create-solana-program) installer will create a new repository including:\n\n- An example program using the framework of your choice (Anchor coming soon).\n- Generated clients for any of the selected clients.\n- A set of scripts that allows you to:\n    - Start a local validator including all programs and accounts you depend on.\n    - Build, lint and test your programs.\n    - Generate IDLs from your programs.\n    - Generate clients from the generated IDLs.\n    - Build and test each of your clients.\n- GitHub Actions pipelines to test your program, test your clients, and even manually publish new packages or crates for your clients. (Coming soon).\n\nWhen selecting the JavaScript client, you will get a fully generated library compatible with Kit much like the `@solana-program` packages showcased above.\n\n## GraphQL\n\nThough 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.\n\nThe `@solana/rpc-graphql` package can be used to make GraphQL queries to Solana RPC endpoints, using the same transports described above (including any customizations).\n\nHere’s an example of retrieving account data with GraphQL:\n\n```ts\nconst source = `\n    query myQuery($address: String!) {\n        account(address: $address) {\n            dataBase58: data(encoding: BASE_58)\n            dataBase64: data(encoding: BASE_64)\n            lamports\n        }\n    }\n`;\n\nconst variableValues = {\n    address: 'AyGCwnwxQMCqaU4ixReHt8h5W4dwmxU7eM3BEQBdWVca',\n};\n\nconst result = await rpcGraphQL.query(source, variableValues);\n\nexpect(result).toMatchObject({\n    data: {\n        account: {\n            dataBase58: '2Uw1bpnsXxu3e',\n            dataBase64: 'dGVzdCBkYXRh',\n            lamports: 10290815n,\n        },\n    },\n});\n```\n\nUsing GraphQL allows developers to only specify which fields they _actually_ need, and do away with the rest of the response.\n\nHowever, 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.\n\n```ts\nconst source = `\n    query getLamportsOfOwnersOfOwnersOfTokenAccounts {\n        programAccounts(programAddress: \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\") {\n            ... on TokenAccount {\n                owner {\n                    ownerProgram {\n                        lamports\n                    }\n                }\n            }\n        }\n    }\n`;\n\nconst result = await rpcGraphQL.query(source);\n\nconst sumOfAllLamportsOfOwnersOfOwnersOfTokenAccounts = result\n    .map(o =\u003e o.account.owner.ownerProgram.lamports)\n    .reduce((acc, lamports) =\u003e acc + lamports, 0);\n```\n\nThe new GraphQL package supports this same style of nested querying on transactions and blocks.\n\n```ts\nconst source = `\n    query myQuery($signature: String!, $commitment: Commitment) {\n        transaction(signature: $signature, commitment: $commitment) {\n            message {\n                instructions {\n                    ... on CreateAccountInstruction {\n                        lamports\n                        programId\n                        space\n                    }\n                }\n            }\n        }\n    }\n`;\n\nconst variableValues = {\n    signature: '63zkpxATgAwXRGFQZPDESTw2m4uZQ99sX338ibgKtTcgG6v34E3MSS3zckCwJHrimS71cvei6h1Bn1K1De53BNWC',\n    commitment: 'confirmed',\n};\n\nconst result = await rpcGraphQL.query(source, variableValues);\n\nexpect(result).toMatchObject({\n    data: {\n        transaction: {\n            message: {\n                instructions: expect.arrayContaining([\n                    {\n                        lamports: expect.any(BigInt),\n                        programId: '11111111111111111111111111111111',\n                        space: expect.any(BigInt),\n                    },\n                ]),\n            },\n        },\n    },\n});\n```\n\nSee more in the package’s [README on GitHub](https://github.com/anza-xyz/kit/tree/main/packages/rpc-graphql).\n\n## Development\n\nYou can see all development of this library and associated GraphQL tooling in the Kit repository on GitHub.\n\n- https://github.com/anza-xyz/kit\n\nYou can follow along with program client generator development in the `@solana-program` org and the `@codama-idl/codama` repository.\n\n- https://github.com/solana-program/\n- https://github.com/codama-idl/codama\n\nSolana Labs develops these tools in public, as open source. We encourage any and all developers who would like to work on these tools to contribute to the codebase.\n\n## Thank you\n\nWe’re grateful that you have read this far. If you are interested in migrating an existing application to Kit to take advantage of some of the benefits we’ve demonstrated, we want to give you some direct support. Reach out to [@steveluscher](https://t.me/steveluscher/) on Telegram to start a conversation.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanza-xyz%2Fkit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fanza-xyz%2Fkit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanza-xyz%2Fkit/lists"}