Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/kit-plugin-litesvm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist/
4 changes: 4 additions & 0 deletions packages/kit-plugin-litesvm/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dist/
test-ledger/
target/
CHANGELOG.md
22 changes: 22 additions & 0 deletions packages/kit-plugin-litesvm/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2025 Anza

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
48 changes: 48 additions & 0 deletions packages/kit-plugin-litesvm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Kit Plugins ➤ LiteSVM

[![npm][npm-image]][npm-url]
[![npm-downloads][npm-downloads-image]][npm-url]

[npm-downloads-image]: https://img.shields.io/npm/dm/@solana/kit-plugin-litesvm.svg?style=flat
[npm-image]: https://img.shields.io/npm/v/@solana/kit-plugin-litesvm.svg?style=flat&label=%40solana%2Fkit-plugin-litesvm
[npm-url]: https://www.npmjs.com/package/@solana/kit-plugin-litesvm

This package provides a plugin that adds LiteSVM functionality to your Kit clients.

## Installation

```sh
pnpm install @solana/kit-plugin-litesvm
```

> [!NOTE]
> This package is included in the main [`@solana/kit-plugins`](../kit-plugins) package.
>
> ```sh
> pnpm install @solana/kit-plugins
> ```

## `litesvm` plugin

The LiteSVM plugin starts a new LiteSVM instance within your Kit client, allowing you to simulate Solana programs and accounts locally. Additionally, it derives a small RPC subset that interacts with the LiteSVM instance instead of making network requests.

### Installation

```ts
import { createEmptyClient } from '@solana/kit';
import { litesvm } from '@solana/kit-plugins';

const client = createEmptyClient().use(litesvm());
```

### Features

- `svm`: Access the underlying LiteSVM instance.
```ts
client.svm.setAccount(myAccount);
client.svm.addProgramFromFile(myProgramAddress, 'my_program.so');
```
- `rpc`: Call a subset of Solana RPC methods against the LiteSVM instance. Currently supported methods are: `getAccountInfo`, `getMultipleAccounts`, and `getLatestBlockhash`.
```ts
const { value: latestBlockhash } = await client.rpc.getLatestBlockhash().send();
```
69 changes: 69 additions & 0 deletions packages/kit-plugin-litesvm/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"name": "@solana/kit-plugin-litesvm",
"version": "0.1.0",
"description": "LiteSVM support for Kit clients",
"exports": {
"types": "./dist/types/index.d.ts",
"react-native": "./dist/index.react-native.mjs",
"browser": {
"import": "./dist/index.browser.mjs",
"require": "./dist/index.browser.cjs"
},
"node": {
"import": "./dist/index.node.mjs",
"require": "./dist/index.node.cjs"
}
},
"browser": {
"./dist/index.node.cjs": "./dist/index.browser.cjs",
"./dist/index.node.mjs": "./dist/index.browser.mjs"
},
"main": "./dist/index.node.cjs",
"module": "./dist/index.node.mjs",
"react-native": "./dist/index.react-native.mjs",
"types": "./dist/types/index.d.ts",
"type": "commonjs",
"files": [
"./dist/types",
"./dist/index.*"
],
"sideEffects": false,
"keywords": [
"solana",
"kit",
"plugin",
"LiteSVM"
],
"scripts": {
"build": "rimraf dist && tsup && tsc -p ./tsconfig.declarations.json",
"dev": "vitest --project node",
"lint": "eslint . && prettier --check .",
"lint:fix": "eslint --fix . && prettier --write .",
"test": "pnpm test:types && pnpm test:treeshakability && pnpm test:unit",
"test:treeshakability": "for file in dist/index.*.mjs; do agadoo $file; done",
"test:types": "tsc --noEmit",
"test:unit": "vitest run"
},
"peerDependencies": {
"@solana/kit": "^5.1.0"
},
"dependencies": {
"@loris-sandbox/litesvm-kit": "^0.5.0"
},
"devDependencies": {
"@solana/kit": "^5.1.0",
"@solana/plugin-core": "workspace:*"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/anza-xyz/kit-plugins"
},
"bugs": {
"url": "https://github.com/anza-xyz/kit-plugins/issues"
},
"browserslist": [
"supports bigint and not dead",
"maintained node versions"
]
}
102 changes: 102 additions & 0 deletions packages/kit-plugin-litesvm/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { LiteSVM } from '@loris-sandbox/litesvm-kit';
import {
AccountInfoBase,
AccountInfoWithBase64EncodedData,
Address,
Base64EncodedBytes,
GetAccountInfoApi,
getBase64Decoder,
GetLatestBlockhashApi,
GetMultipleAccountsApi,
MaybeEncodedAccount,
PendingRpcRequest,
Rpc,
SolanaRpcResponse,
} from '@solana/kit';

// Re-export the LiteSVM type to make the `litesvm` type-portable.
export type { LiteSVM } from '@loris-sandbox/litesvm-kit';

/** The RPC subset provided by the LiteSVM plugin. */
export type RpcFromLiteSVM = Rpc<GetAccountInfoApi & GetLatestBlockhashApi & GetMultipleAccountsApi>;

/**
* A Kit plugin that adds LiteSVM functionality to your client.
*
* This plugin starts a new LiteSVM instance within your Kit client,
* allowing you to simulate Solana programs and accounts locally.
* Additionally, it derives a small RPC subset that interacts with the
* LiteSVM instance instead of making network requests.
*
* @example
* ```ts
* import { createEmptyClient } from '@solana/kit';
* import { litesvm } from '@solana/kit-plugins';
*
* // Install the LiteSVM plugin.
* const client = createEmptyClient().use(litesvm());
*
* // Use LiteSVM to set up accounts and programs.
* client.svm.setAccount(myAccount);
* client.svm.addProgramFromFile(myProgramAddress, 'my_program.so');
*
* // Make some RPC calls.
* const { value: latestBlockhash } = await client.rpc.getLatestBlockhash().send();
* ```
*/
export function litesvm() {
return <T extends object>(client: T) => {
const svm = new LiteSVM();
const rpc = createRpcFromSvm(svm);
return { ...client, rpc, svm };
};
}

type Encoding = 'base58' | 'base64' | 'base64+zstd' | 'jsonParsed';

function createRpcFromSvm(svm: LiteSVM): RpcFromLiteSVM {
const base64Decoder = getBase64Decoder();
const convertMaybeEncodedAccount = (
account: MaybeEncodedAccount,
): (AccountInfoBase & AccountInfoWithBase64EncodedData) | null => {
if (!account.exists) return null;
return {
data: [base64Decoder.decode(account.data) as Base64EncodedBytes, 'base64'] as const,
executable: account.executable,
lamports: account.lamports,
owner: account.programAddress,
space: account.space,
};
};

return {
getAccountInfo: (address: Address, config?: { encoding?: Encoding }) => {
assertEncodingIsBase64(config?.encoding);
const response = convertMaybeEncodedAccount(svm.getAccount(address));
return wrapInPendingRpcRequest(wrapInSolanaRpcResponse(response));
},
getLatestBlockhash: () => {
const response = { blockhash: svm.latestBlockhash(), lastValidBlockHeight: 0n };
return wrapInPendingRpcRequest(wrapInSolanaRpcResponse(response));
},
getMultipleAccounts: (addresses: readonly Address[], config?: { encoding?: Encoding }) => {
assertEncodingIsBase64(config?.encoding);
const response = addresses.map(address => convertMaybeEncodedAccount(svm.getAccount(address)));
return wrapInPendingRpcRequest(wrapInSolanaRpcResponse(response));
},
} as RpcFromLiteSVM;
}

function wrapInPendingRpcRequest<T>(response: T): PendingRpcRequest<T> {
return { send: () => Promise.resolve(response) };
}

function wrapInSolanaRpcResponse<T>(value: T): SolanaRpcResponse<T> {
return { context: { slot: 0n }, value };
}

function assertEncodingIsBase64(encoding: Encoding | undefined) {
if (encoding && encoding !== 'base64') {
throw new Error(`Please use 'base64' encoding when using LiteSVM RPC. Requested encoding: ${encoding}`);
}
}
121 changes: 121 additions & 0 deletions packages/kit-plugin-litesvm/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { LiteSVM } from '@loris-sandbox/litesvm-kit';
import {
address,
generateKeyPairSigner,
GetAccountInfoApi,
GetLatestBlockhashApi,
GetMultipleAccountsApi,
lamports,
Rpc,
} from '@solana/kit';
import { createEmptyClient } from '@solana/plugin-core';
import { describe, expect, expectTypeOf, it } from 'vitest';

import { litesvm } from '../src';

describe('litesvm', () => {
it('instantiates and attaches a new LiteSVM client', () => {
const client = createEmptyClient().use(litesvm());
expect(client).toHaveProperty('svm');
expect(client.svm).toBeInstanceOf(LiteSVM);
});

it('derives a small RPC from the LiteSVM client', () => {
const client = createEmptyClient().use(litesvm());
expect(client).toHaveProperty('rpc');
expect(client.rpc).toBeTypeOf('object');
expect(client.rpc.getAccountInfo).toBeTypeOf('function');
expect(client.rpc.getLatestBlockhash).toBeTypeOf('function');
expect(client.rpc.getMultipleAccounts).toBeTypeOf('function');
expectTypeOf(client.rpc).toEqualTypeOf<
Rpc<GetAccountInfoApi & GetLatestBlockhashApi & GetMultipleAccountsApi>
>();
});

it('can fetch an account set on the svm', async () => {
const client = createEmptyClient().use(litesvm());
const accountAddress = await generateKeyPairSigner().then(signer => signer.address);

client.svm.setAccount({
address: accountAddress,
data: new Uint8Array([1, 1]),
executable: false,
lamports: lamports(1_000_000n),
programAddress: address('11111111111111111111111111111111'),
space: 2n,
});

const { value } = await client.rpc.getAccountInfo(accountAddress).send();
expect(value).toEqual({
data: ['AQE=', 'base64'],
executable: false,
lamports: lamports(1_000_000n),
owner: address('11111111111111111111111111111111'),
space: 2n,
});
});

it('can fetch a missing account on the svm', async () => {
const client = createEmptyClient().use(litesvm());
const missingAddress = await generateKeyPairSigner().then(signer => signer.address);

const { value } = await client.rpc.getAccountInfo(missingAddress).send();
expect(value).toBeNull();
});

it('can fetch multiple accounts set on the svm', async () => {
const client = createEmptyClient().use(litesvm());

const [addressA, addressB, missingAddressC] = await Promise.all([
generateKeyPairSigner().then(signer => signer.address),
generateKeyPairSigner().then(signer => signer.address),
generateKeyPairSigner().then(signer => signer.address),
]);

client.svm.setAccount({
address: addressA,
data: new Uint8Array([1, 1]),
executable: false,
lamports: lamports(1_000_000n),
programAddress: address('11111111111111111111111111111111'),
space: 2n,
});
client.svm.setAccount({
address: addressB,
data: new Uint8Array([2, 2, 2, 2]),
executable: false,
lamports: lamports(2_000_000n),
programAddress: address('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'),
space: 4n,
});

const { value } = await client.rpc.getMultipleAccounts([addressA, addressB, missingAddressC]).send();

expect(value).toHaveLength(3);
expect(value[0]).toEqual({
data: ['AQE=', 'base64'],
executable: false,
lamports: lamports(1_000_000n),
owner: address('11111111111111111111111111111111'),
space: 2n,
});
expect(value[1]).toEqual({
data: ['AgICAg==', 'base64'],
executable: false,
lamports: lamports(2_000_000n),
owner: address('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'),
space: 4n,
});
expect(value[2]).toBeNull();
});

it('can fetch a the latest blockhash', async () => {
const client = createEmptyClient().use(litesvm());

const { value } = await client.rpc.getLatestBlockhash({ commitment: 'finalized' }).send();
expect(value).toStrictEqual({
blockhash: client.svm.latestBlockhash(),
lastValidBlockHeight: 0n,
});
});
});
10 changes: 10 additions & 0 deletions packages/kit-plugin-litesvm/tsconfig.declarations.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true,
"outDir": "./dist/types"
},
"extends": "./tsconfig.json",
"include": ["src/index.ts", "src/types"]
}
7 changes: 7 additions & 0 deletions packages/kit-plugin-litesvm/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": { "lib": [] },
"display": "@solana/kit-plugin-litesvm",
"extends": "../../tsconfig.json",
"include": ["src", "test"]
}
5 changes: 5 additions & 0 deletions packages/kit-plugin-litesvm/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { defineConfig } from 'tsup';

import { getPackageBuildConfigs } from '../../tsup.config.base';

export default defineConfig(getPackageBuildConfigs());
Loading