# Transactions Source: https://sava.software/guides/transactions Build, simulate, sign, and submit Solana transactions. ## Transaction Formats | Format | Construction | Address lookup tables | | ------ | ----------------------------------------------------------- | --------------------- | | Legacy | `Transaction.createTx(feePayer, instruction)` | No | | v0 | `Transaction.createTx(feePayer, instructions, lookupTable)` | Yes | | v1 | `TxBuilder.createBuilder()` | No | `TxBuilder` builds v1 transactions. Use it with a cluster that has activated v1; legacy and v0 factories remain available. ## Build, Simulate, Sign, and Submit ```java theme={null} final var tx = TxBuilder.createBuilder() .feePayer(signer.publicKey()) .addInstruction(instruction) .priorityFeeLamports(priorityFeeLamports) .createTransaction(); final var simulation = rpcClient.simulateTransaction(Commitment.CONFIRMED, tx, true).join(); if (simulation.error() != null) { throw new IllegalStateException("Simulation failed: " + simulation.error()); } // If dealing with transactions that have dynamic onchain paths or accounts, // increase the returned simulation values. tx.setComputeUnitLimit(simulation.unitsConsumed().getAsInt()); tx.setAccountDataSizeLimit(simulation.loadedAccountsDataSize()); tx.setRecentBlockHash(simulation.replacementBlockHash().blockhash()); tx.sign(signer); final var signature = rpcClient.sendTransaction(Commitment.CONFIRMED, tx.base64EncodeToString()).join(); ``` Simulation supplies the blockhash and both budgets. Usage can vary between runs, so add a margin if your program needs one. Submission returns a signature; confirmation is a separate step. ## Budgets and Priority Fees The builder defaults to 1,400,000 compute units and 64 MiB of loaded account data. Zero omits either field and leaves a zero budget, so do not use zero to request defaults. V1 transaction setters update fields already present; rebuild to add an omitted field. V1 priority fees are **total lamports**. To convert a legacy/v0 price in **micro-lamports per compute unit**: ```java theme={null} final var builder = TxBuilder.createBuilder() .computeUnitLimit(200_000) .priorityFeeLamportsFromComputeUnitPrice(5_000); // Priority fee: 1,000 lamports. ``` The conversion uses the current compute limit once. Changing that limit later does not change the fee; convert again if needed. ## Read and Rebuild `TransactionSkeleton.deserializeSkeleton` reads all three formats. For legacy or v1: ```java theme={null} final var skeleton = TransactionSkeleton.deserializeSkeleton(serializedTransaction); final var accounts = skeleton.parseAccounts(); final var instructions = skeleton.parseInstructions(accounts); ``` For v0 with lookup-table accounts, use `skeleton.parseAccounts(lookupTables)` with a `Map` before parsing instructions. `skeleton.prototypeTransaction(instructions)` creates a v1 builder from the resolved instructions and budgets. Set a fresh blockhash and sign the rebuilt transaction. # Core Source: https://sava.software/libraries/core Common Solana Cryptography & Serialization Utilities. ## [Dependencies](https://github.com/sava-software/sava/blob/main/sava-core/src/main/java/module-info.java) * [org.bouncycastle.provider](https://www.bouncycastle.org/download/bouncy-castle-java/#latest) ## Features * [Transaction construction and signing](/guides/transactions), plus [legacy, v0, and v1 deserialization](#transaction-deserialization) * [Account Types:](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/accounts) * Token, Mint, [Token-2022 and all of its extensions](#token-2022-extensions) * Address Lookup Tables * [Common collection of main-net addresses](#solana-accounts) * Ed25519 [public](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/accounts/PublicKey.java) and [private](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/accounts/Signer.java) keys * [Program derived addresses](#program-derived-addresses) * [Encoding:](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/encoding) * [Base58](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/encoding/Base58.java) * [Hex](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/encoding/Jex.java) * [Little Endian Numbers](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/encoding/ByteUtil.java) * [Compact u16](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/encoding/CompactU16Encoding.java) ## Solana Accounts [SolanaAccounts](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/accounts/SolanaAccounts.java) provides the native/builtin program IDs, common SPL program IDs, and sysvar addresses, each with pre-constructed read/invoked `AccountMeta` variants. ```java theme={null} var accounts = SolanaAccounts.MAIN_NET; var tokenProgram = accounts.invokedTokenProgram(); var clock = accounts.readClockSysVar(); ``` For a fork or custom deployment, use [SolanaAccountsBuilder](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/accounts/SolanaAccountsBuilder.java) and override only the addresses which differ; every field defaults to its main-net value. ```java theme={null} var accounts = SolanaAccountsBuilder.builder() .tokenProgram("") .create(); ``` ## Token-2022 Extensions [Token2022](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/accounts/token/Token2022.java) and [Token2022Account](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/accounts/token/Token2022Account.java) parse known [Token-2022 extensions](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/accounts/token/extensions) into a sealed type hierarchy. Unrecognized type IDs in well-formed TLV data are retained as `UnknownTokenExtension` with their on-chain type value and raw data. Truncated TLV values, mismatched fixed-size extension lengths, and duplicate extension IDs are rejected. `tokenExtensions()` returns the parsed extensions. Match their concrete types when handling them; `ordinal()` exposes each extension's stable on-chain type ID. ```java theme={null} var token2022 = Token2022.read(mintAddress, accountData); for (var extension : token2022.tokenExtensions()) { switch (extension) { case TransferFeeConfig(_, _, _, _, TransferFee(_, long maxFee, int feeBasisPoints)) -> System.out.format("Transfer fee: %d bps, max %d%n", feeBasisPoints, maxFee); case TokenMetadata metadata -> System.out.println(metadata.name()); case UnknownTokenExtension(int type, byte[] data) -> System.out.println("Unknown extension type " + type); default -> { } } } ``` ## Program Derived Addresses ```java theme={null} var programId = PublicKey.fromBase58Encoded(""); var seeds = List.of("state".getBytes(US_ASCII), owner.toByteArray()); ProgramDerivedAddress pda = PublicKey.findProgramAddress(seeds, programId); ``` ## Private Key Parsing `PrivateKeyEncoding` is provided by `sava-rpc`. `JsonIterator` comes from its transitive [json-iterator](https://github.com/comodal/json-iterator) dependency. ### Usage ```java theme={null} var jsonConfig = ""; var ji = JsonIterator.parse(jsonConfig); var signer = PrivateKeyEncoding.fromJsonPrivateKey(ji); ``` ### JSON Configuration A JSON object requires `encoding` and `secret`; fields may appear in any order. Unknown fields are skipped, including nested objects and arrays. If the base58 encoded public key is supplied as `pubKey`, it is checked against the public key derived from the private key. #### Solana CLI Key Pair JSON Array By default, if only an array is configured, the assumption is that it is a key pair generated by the Solana CLI. ``` [1,2,3, ... ,42] ``` #### JSON Array ```json theme={null} { "pubKey": "", "encoding": "jsonKeyPairArray", "secret": [] } ``` #### Key Pair Encoded 64 byte private/public key pair. Derived public key will be validated. * base64KeyPair * base58KeyPair ```json theme={null} { "pubKey": "", "encoding": "base64KeyPair", "secret": "asdf==" } ``` #### Private Key Only Encoded 32 byte private key. * base64PrivateKey * base58PrivateKey ```json theme={null} { "pubKey": "", "encoding": "base64PrivateKey", "secret": "asdf==" } ``` ## Transaction Deserialization The [TransactionSkeleton](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/tx/TransactionSkeleton.java) interface provides a lightweight view over transaction data. Allowing for partial introspection or complete reconstruction of a [Transaction](https://github.com/sava-software/sava/tree/main/sava-core/src/main/java/software/sava/core/tx/Transaction.java). ### Legacy ```java theme={null} byte[] legacyTransactionData = ...; var skeleton = TransactionSkeleton.deserializeSkeleton(legacyTransactionData); AccountMeta[] accounts = skeleton.parseAccounts(); Instruction[] instructions = skeleton.parseLegacyInstructions(); Transaction transaction = skeleton.createTransaction(); ``` ### v0 ```java theme={null} byte[] v0TransactionData = ...; var skeleton = TransactionSkeleton.deserializeSkeleton(v0TransactionData); var instructionsWithoutTableAccounts = skeleton.parseInstructionsWithoutTableAccounts(); PublicKey[] tableAccounts = skeleton.lookupTableAccounts(); // ... Fetch table accounts (See RPC) ... AddressLookupTable lookupTable = ...; AccountMeta[] accounts = skeleton.parseAccounts(lookupTable); Instruction[] instructions = skeleton.parseInstructions(accounts); Transaction transaction = skeleton.createTransaction(instructions, lookupTable); ``` ### v1 The same deserializer recognizes v1. All v1 accounts are carried directly in the message, so no address lookup tables need to be fetched. ```java theme={null} byte[] v1TransactionData = ...; var skeleton = TransactionSkeleton.deserializeSkeleton(v1TransactionData); int version = skeleton.version(); // 1 AccountMeta[] accounts = skeleton.parseAccounts(); Instruction[] instructions = skeleton.parseInstructions(accounts); long priorityFeeLamports = skeleton.priorityFeeLamports(); int computeUnitLimit = skeleton.computeUnitLimit(); ``` Deserialization reads the wire structure; it does not establish signature validity or whether a transaction would execute successfully on a cluster. ## Creating Transactions The [transaction guide](/guides/transactions) covers choosing a format, building v1 transactions with `TxBuilder`, simulating, signing, and submitting. It also covers creating a v1 builder from a parsed `TransactionSkeleton` with `prototypeTransaction()`. The [IDL client examples](/libraries/idl-clients#typical-transaction-flow) show a supported legacy flow using generated program instructions. # IDL Clients Source: https://sava.software/libraries/idl-clients Generated source and convenient clients to (de)serialize instructions and accounts for common Solana programs. ## Dependencies Each module's `module-info.java` is the list of record. * [`idl-clients-spl`](https://github.com/sava-software/idl-clients/blob/main/idl-clients-spl/src/main/java/module-info.java): `java.net.http`, `software.sava.core`, `software.sava.rpc` * [`idl-clients-bundle`](https://github.com/sava-software/idl-clients/blob/main/idl-clients-bundle/src/main/java/module-info.java): the above, `software.sava.idl.clients.spl` and `systems.comodal.json_iterator` ## Supported Programs Clients are generated from each program's IDL, providing typed instruction builders and account (de)serialization, plus hand-written convenience clients where useful. | Module | Programs | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `idl-clients-spl` | Token, Token-2022, Associated Token Account, System, Stake, Stake Pool, Address Lookup Table, Memo, Compute Budget, signature verification precompiles, Attestation Service | | `idl-clients-bundle` | Jupiter, Kamino, Marginfi, Marinade, Metaplex, Meteora, Orca, Phoenix, Squads, CCTP, Exponent, Loopscale, Neutral Trade, Pyth, Switchboard, Wormhole | ## Build Configuration ```kotlin build.gradle.kts theme={null} dependencies { implementation("software.sava:idl-clients-spl:$VERSION") implementation("software.sava:idl-clients-bundle:$VERSION") } ``` These modules are published to GitHub Packages only; the [quickstart](/quickstart#github-packages) shows the repository configuration. ## Usage Examples ### Create a Program Client The [idl-clients-spl](https://github.com/sava-software/idl-clients/tree/main/idl-clients-spl) module, used throughout the examples below, provides `SPLClient` and `SPLAccountClient` for working with tokens, associated token accounts, stake accounts, etc. ```java theme={null} var solanaAccounts = SolanaAccounts.MAIN_NET; var splClient = SPLClient.createClient(solanaAccounts); // Create an account-specific client bound to an owner and fee payer var owner = PublicKey.fromBase58Encoded(/* your public key */); var feePayer = AccountMeta.createFeePayer(/* fee payer public key */); var splAccountClient = splClient.createAccountClient(owner, feePayer); ``` ### Typical Legacy Transaction Flow ```java theme={null} Signer signer = ...; // load private key var feePayer = AccountMeta.createFeePayer(signer.publicKey()); var solanaAccounts = SolanaAccounts.MAIN_NET; try (var httpClient = HttpClient.newHttpClient()) { var rpcClient = SolanaRpcClient.build() .endpoint(SolanaNetwork.MAIN_NET.getEndpoint()) .httpClient(httpClient) .createClient(); List instructions = List.of( ComputeBudgetUtil.MAX_COMPUTE_BUDGET_IX, ComputeBudgetProgram.setComputeUnitPrice( solanaAccounts.invokedComputeBudgetProgram(), 0 ) // TODO: Create and add relevant instructions ); var simulationTransaction = Transaction.createTx(feePayer, instructions); var simulationFuture = rpcClient.simulateTransaction(simulationTransaction); // Apply a user-provided fee or fetch an estimate from a service such as Helius' Fee API. var cuPriceIx = ComputeBudgetProgram.setComputeUnitPrice( solanaAccounts.invokedComputeBudgetProgram(), 42 ); var simulationResult = simulationFuture.join(); var transaction = simulationTransaction .replaceInstruction(0, ComputeBudgetProgram.setComputeUnitLimit( solanaAccounts.invokedComputeBudgetProgram(), // CU usage can be dynamic and may need to be increased. simulationResult.unitsConsumed().getAsInt() ) ) .replaceInstruction(1, cuPriceIx); transaction.setRecentBlockHash(simulationResult.replacementBlockHash().blockhash()); transaction.sign(signer); var base64Encoded = transaction.base64EncodeToString(); var sig = rpcClient.sendTransaction(base64Encoded).join(); System.out.println(sig); } ``` v1 transactions are supported on mainnet, and `TxBuilder` builds them from the same generated `Instruction` objects; see the [transaction guide](/guides/transactions) for construction and signing. The example above uses the legacy transaction factories, which remain supported. ### Transfer SOL ```java theme={null} // splAccountClient, owner & feePayer from "Create a Program Client" above. var transferTo = PublicKey.fromBase58Encoded(/* recipient */); var transferIx = splAccountClient.transferSolLamports(transferTo, 42); ``` ### Associated Token Accounts ```java theme={null} var mint = PublicKey.fromBase58Encoded(/* token mint */); // Find the ATA for the standard Token Program ProgramDerivedAddress ata = splClient.findATA(owner, mint); // Create the ATA (idempotent - won't fail if it already exists) var tokenProgram = solanaAccounts.tokenProgram(); Instruction createAtaIx = splAccountClient.createATAForOwnerFundedByFeePayer( true, // idempotent ata.publicKey(), mint, tokenProgram ); ``` ### Token Transfers ```java theme={null} var fromTokenAccount = PublicKey.fromBase58Encoded(/* source token account */); var toTokenAccount = PublicKey.fromBase58Encoded(/* destination token account */); var tokenMint = PublicKey.fromBase58Encoded(/* mint */); var invokedTokenProgram = solanaAccounts.invokedTokenProgram(); long amount = 1_000_000; int decimals = 6; Instruction transferIx = splAccountClient.transferTokenChecked( invokedTokenProgram, fromTokenAccount, toTokenAccount, amount, decimals, tokenMint ); ``` ### Stake Accounts ```java theme={null} Signer signer = ...; var stakeAuthority = signer.publicKey(); var feePayer = AccountMeta.createFeePayer(stakeAuthority); var validatorVoteAccount = PublicKey.fromBase58Encoded(/* vote account */); long stakeLamports = LamportDecimal.fromBigDecimal(BigDecimal.ONE).longValue(); var solanaAccounts = SolanaAccounts.MAIN_NET; try (var httpClient = HttpClient.newHttpClient()) { var rpcClient = SolanaRpcClient.build() .endpoint(SolanaNetwork.MAIN_NET.getEndpoint()) .httpClient(httpClient) .createClient(); long minRent = rpcClient.getMinimumBalanceForRentExemption(StakeAccount.BYTES).join(); var seed = ZonedDateTime.now(ZoneOffset.UTC).toString(); var stakeAccountPubKey = PublicKey.createOffCurveAccountWithAsciiSeed( stakeAuthority, seed, solanaAccounts.stakeProgram() ).publicKey(); var createStakeAccountIx = SystemProgram.createAccountWithSeed( solanaAccounts.invokedSystemProgram(), stakeAuthority, // payer stakeAccountPubKey, // new account stakeAuthority, // base account, must sign stakeAuthority, // base key the seed derives from seed, minRent + stakeLamports, StakeAccount.BYTES, solanaAccounts.stakeProgram() ); var authorized = new Authorized(stakeAuthority, stakeAuthority); var lockup = new Lockup(new UnixTimestamp(0), new Epoch(0), PublicKey.NONE); var initializeIx = StakeProgram.initialize( solanaAccounts.invokedStakeProgram(), stakeAccountPubKey, authorized, lockup ); var delegateStakeIx = StakeProgram.delegateStake( solanaAccounts.invokedStakeProgram(), stakeAccountPubKey, validatorVoteAccount, stakeAuthority ); var instructions = List.of(createStakeAccountIx, initializeIx, delegateStakeIx); } ``` ### Durable Nonce Transactions See the [official Solana documentation](https://solana.com/developers/courses/offline-transactions/durable-nonces) for context on durable nonce transactions. #### Create & Initialize Nonce Account ```java theme={null} Signer signer = ...; var rpcEndpoint = SolanaNetwork.MAIN_NET.getEndpoint(); try (var httpClient = HttpClient.newHttpClient()) { var rpcClient = SolanaRpcClient.build() .endpoint(rpcEndpoint) .httpClient(httpClient) .createClient(); var blockHashFuture = rpcClient.getLatestBlockHash(); var minRentFuture = rpcClient.getMinimumBalanceForRentExemption(NonceAccount.BYTES); var solanaAccounts = SolanaAccounts.MAIN_NET; var seed = "nonce"; var nonceAccountWithSeed = PublicKey.createOffCurveAccountWithAsciiSeed( signer.publicKey(), seed, solanaAccounts.systemProgram() ); var initializeNonceAccountIx = SystemProgram.initializeNonceAccount( solanaAccounts.invokedSystemProgram(), solanaAccounts, nonceAccountWithSeed.publicKey(), signer.publicKey() ); long minRent = minRentFuture.join(); var createNonceAccountIx = SystemProgram.createAccountWithSeed( solanaAccounts.invokedSystemProgram(), signer.publicKey(), // payer nonceAccountWithSeed.publicKey(), // new account signer.publicKey(), // base account (signer) signer.publicKey(), // base seed, minRent, NonceAccount.BYTES, solanaAccounts.systemProgram() ); var instructions = List.of(createNonceAccountIx, initializeNonceAccountIx); var transaction = Transaction.createTx(signer.publicKey(), instructions); var blockHash = blockHashFuture.join().blockHash(); transaction.setRecentBlockHash(blockHash); transaction.sign(signer); var base64Encoded = transaction.base64EncodeToString(); var sig = rpcClient.sendTransaction(base64Encoded).join(); System.out.println("https://explorer.solana.com/tx/" + sig); var nonceAccountInfo = rpcClient.getAccountInfo(nonceAccountWithSeed.publicKey()).join(); var nonceAccount = NonceAccount.read(nonceAccountInfo); System.out.println(nonceAccount); } ``` #### Create & Send Durable Nonce Transaction ```java theme={null} Signer signer = ...; var nonceAccountKey = PublicKey.fromBase58Encoded(""); var sendToKey = PublicKey.fromBase58Encoded(""); var transferSOL = new BigDecimal("0.0"); var solanaAccounts = SolanaAccounts.MAIN_NET; var rpcEndpoint = SolanaNetwork.MAIN_NET.getEndpoint(); try (var httpClient = HttpClient.newHttpClient()) { var rpcClient = SolanaRpcClient.build() .endpoint(rpcEndpoint) .httpClient(httpClient) .createClient(); var nonceAccountInfo = rpcClient.getAccountInfo(nonceAccountKey).join(); var nonceAccount = NonceAccount.read(nonceAccountInfo); System.out.println(nonceAccount); var advanceNonceIx = nonceAccount.advanceNonceAccount(solanaAccounts); var transferIx = SystemProgram.transferSol( solanaAccounts.invokedSystemProgram(), signer.publicKey(), sendToKey, LamportDecimal.fromBigDecimal(transferSOL).longValue() ); var instructions = List.of(advanceNonceIx, transferIx); var transaction = Transaction.createTx(signer.publicKey(), instructions); nonceAccount.setNonce(transaction); transaction.sign(signer); var base64Encoded = transaction.base64EncodeToString(); var sig = rpcClient.sendTransaction(base64Encoded).join(); System.out.println("https://explorer.solana.com/tx/" + sig); } ``` # RPC Source: https://sava.software/libraries/rpc HTTP and WebSocket JSON RPC Clients. ## [Dependencies](https://github.com/sava-software/sava/blob/main/sava-rpc/src/main/java/module-info.java) * java.net.http * systems.comodal.json\_iterator * software.sava.core ## Features * Every active [HTTP RPC method](https://solana.com/docs/rpc/http) with typed response records. * [WebSocket subscriptions](https://solana.com/docs/rpc/websocket) which automatically re-subscribe on re-connection, including a [generic passthrough](#provider-specific-subscriptions) for provider-specific methods. * Typed, sealed error hierarchies: known [TransactionError](https://github.com/sava-software/sava/blob/main/sava-rpc/src/main/java/software/sava/rpc/json/http/response/TransactionError.java) and [InstructionError](https://github.com/sava-software/sava/blob/main/sava-rpc/src/main/java/software/sava/rpc/json/http/response/IxError.java) variants and supported [custom JSON-RPC error codes](https://github.com/sava-software/sava/blob/main/sava-rpc/src/main/java/software/sava/rpc/json/http/response/RpcCustomError.java) parse to their own types, with `Unknown` fallbacks for unrecognized variants or codes. * Asynchronous by default, every request returns a `CompletableFuture`. ## HTTP See the official Solana docs for context on each [HTTP RPC method.](https://solana.com/docs/rpc/http) ### Create Client ```java theme={null} try (var httpClient = HttpClient.newHttpClient()) { var rpcClient = SolanaRpcClient.build() .endpoint(SolanaNetwork.MAIN_NET.getEndpoint()) .httpClient(httpClient) .createClient(); // The examples below assume an rpcClient within this scope. } ``` ### Fetch & Parse Accounts ```java theme={null} var accountInfo = rpcClient.getAccountInfo( PublicKey.fromBase58Encoded("6T6vqb3VykNToz4sqY5C29Psb8iNUuVZPAqJXbAgorVF") ).join(); byte[] tableData = accountInfo.data(); var table = AddressLookupTable.read(accountInfo.pubKey(), tableData); System.out.println(table); ``` ```java theme={null} var accountInfo = rpcClient.getAccountInfo( PublicKey.fromBase58Encoded("6T6vqb3VykNToz4sqY5C29Psb8iNUuVZPAqJXbAgorVF"), AddressLookupTable.FACTORY ).join(); AddressLookupTable table = accountInfo.data(); System.out.println(table); ``` ### Query Program Accounts with [Filters](https://solana.com/docs/rpc#filter-criteria) **Note**: You will need access to an RPC node which has getProgramAccounts enabled, such as [Helius](https://www.helius.dev/). Retrieve all lookup tables which are active and frozen. ```java theme={null} byte[] stillActive = new byte[Long.BYTES]; ByteUtil.putInt64LE(stillActive, 0, Clock.MAX_SLOT); var activeFilter = Filter.createMemCompFilter(DEACTIVATION_SLOT_OFFSET, stillActive); var noAuthorityFilter = Filter.createMemCompFilter(AUTHORITY_OPTION_OFFSET, new byte[]{0}); var accountInfoFuture = rpcClient.getProgramAccounts( SolanaAccounts.MAIN_NET.addressLookupTableProgram(), List.of( activeFilter, noAuthorityFilter ), AddressLookupTable.FACTORY ); var accountInfoList = accountInfoFuture.join(); accountInfoList.stream().map(AccountInfo::data).forEach(System.out::println); System.out.format("Retrieved %d tables which are active and frozen.%n", accountInfoList.size()); ``` ### Fetch Transactions & Blocks The built-in client automatically requests `maxSupportedTransactionVersion: 1` for `getTransaction` and for `getBlock` with `BlockTxDetails.full`. Both requests use Base64 transaction bytes. Other block-detail modes omit the version ceiling; request `full` to retrieve serialized transactions. The destination node and cluster still determine which transaction versions are available. Given a transaction `signature`, inspect its wire version and v1 configuration: ```java theme={null} var tx = rpcClient.getTransaction(signature).join(); if (tx != null) { var skeleton = tx.skeleton(); if (skeleton != null) { System.out.println("Version: " + skeleton.version()); if (skeleton.version() == 1) { System.out.println("Priority fee (lamports): " + skeleton.priorityFeeLamports()); System.out.println("Compute-unit limit: " + skeleton.computeUnitLimit()); System.out.println("Account-data limit (bytes): " + skeleton.accountDataSizeLimit()); System.out.println("Heap request (bytes): " + skeleton.heapSize()); } } } ``` For a block `slot`, each `BlockTx` also exposes `skeleton()`: ```java theme={null} var block = rpcClient.getBlock(slot, BlockTxDetails.full).join(); if (block != null) { for (var entry : block.transactions()) { var skeleton = entry.skeleton(); if (skeleton != null) { System.out.println(skeleton.id() + ": version " + skeleton.version()); } } } ``` `version()` is `1` for v1, `0` for v0, and negative for legacy. Both skeleton helpers deserialize on each call and return `null` when transaction bytes are absent or empty. `BlockTx` reads the version from those bytes through its skeleton. Execution results, such as the fee and consumed compute units, are available through `meta()` when present. ### Version Errors & Submission Results These failures describe different stages of a request: | Situation | Typed result | | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | A fetched transaction exceeds the requesting client's version ceiling | `JsonRpcException` with code `-32015` and `RpcCustomError.UnsupportedTransactionVersion` | | Simulation rejects a version unsupported by the destination runtime | `TxSimulation.error()` is `TransactionError.UnsupportedVersion` | | Submission preflight rejects the transaction | `JsonRpcException` with code `-32002` and `RpcCustomError.SendTransactionPreflightFailure`; inspect its `simulation().error()` | For a JSON-RPC error, `join()` throws a `CompletionException` whose cause is a `JsonRpcException`. Preserve an `Unknown` case when handling error variants. A successful `sendTransaction` response supplies a transaction signature. Check its confirmation status and execution error afterward; skipping preflight can return a signature even when the runtime will reject the transaction. See the [transaction lifecycle guide](/guides/transactions) for building, simulation, signing, and submission, including how to adjust v1 limits after simulation. ### Request Encodings Use `RpcEncoding.base64`, or `RpcEncoding.base64_zstd` (`base64+zstd`) for account requests that support compression. Transaction fetch, simulation, and submission use Base64. Account parsing remains client-side through the typed account factories; `jsonParsed` is intentionally absent. ## WebSocket See the official Solana docs for context on each [WebSocket RPC method.](https://solana.com/docs/rpc/websocket) ### Create Client ```java theme={null} try (var httpClient = HttpClient.newHttpClient()) { var webSocket = SolanaRpcWebsocket.build() .webSocketBuilder(httpClient.newWebSocketBuilder()) .uri(SolanaNetwork.MAIN_NET.getWebSocketEndpoint()) .solanaAccounts(SolanaAccounts.MAIN_NET) .commitment(Commitment.CONFIRMED) .onOpen(ws -> System.out.println("Websocket connected to " + ws.endpoint())) .onClose((_, statusCode, reason) -> System.out.format("%d: %s%n", statusCode, reason)) .onError((_, throwable) -> throwable.printStackTrace()) .create(); webSocket.connect(); } ``` ### Stream Program Accounts #### Token Accounts ```java theme={null} var solanaAccounts = SolanaAccounts.MAIN_NET; var tokenProgram = solanaAccounts.tokenProgram(); var tokenOwner = PublicKey.fromBase58Encoded(""); webSocket.programSubscribe( tokenProgram, List.of( Filter.createDataSizeFilter(TokenAccount.BYTES), Filter.createMemCompFilter(TokenAccount.OWNER_OFFSET, tokenOwner) ), accountInfo -> { var tokenAccount = TokenAccount.read(accountInfo.pubKey(), accountInfo.data()); System.out.println(tokenAccount); } ); ``` #### Address Lookup Tables ```java theme={null} var solanaAccounts = SolanaAccounts.MAIN_NET; var addressLookupTableProgram = solanaAccounts.addressLookupTableProgram(); webSocket.programSubscribe(addressLookupTableProgram, accountInfo -> { var table = AddressLookupTable.read(accountInfo.pubKey(), accountInfo.data()); System.out.println(table); }); ``` ### Provider Specific Subscriptions Subscription methods which are not part of the standard Solana API, or not supported by public RPC infrastructure, are reachable via the generic `subscribe` passthrough. You provide the method names, request parameters JSON, and a response parser; subscriptions are replayed if the connection is re-established. See [HeliusRpcWebsocket](https://github.com/sava-software/helius-sdk) for a complete example wrapping Helius' `transactionSubscribe`. ```java theme={null} webSocket.subscribe( "transactionSubscribe", "transactionUnsubscribe", "transactionNotification", subscriptionKey, paramsJson, TransactionNotification::parse, notification -> System.out.println(notification) ); ``` # Source: https://sava.software/project/contact Sava is maintained by [Sava Engineering, Inc](https://sava.engineering/). Join the conversation @sava\_software [hello@sava.software](mailto:hello@sava.software) # Spotlight Source: https://sava.software/project/spotlight See who's building with Sava GLAM is an onchain asset management and tokenization platform
to launch and manage investment products on Solana. *** [Claim your spotlight](https://tally.so/r/nrJR82) # Quickstart Source: https://sava.software/quickstart Add Sava to your Gradle or Maven build. ## Build Configuration Sava targets Java 25. Ensure you have a compatible JDK installed before adding Sava to your build. Use the same Sava version for `sava-core` and `sava-rpc`; replace `VERSION` below with the published version you are using. ```kotlin build.gradle.kts theme={null} dependencies { implementation("software.sava:sava-core:$VERSION") implementation("software.sava:sava-rpc:$VERSION") } ``` ```groovy build.gradle theme={null} dependencies { implementation "software.sava:sava-core:$VERSION" implementation "software.sava:sava-rpc:$VERSION" } ``` ```xml pom.xml theme={null} software.sava sava-core VERSION software.sava sava-rpc VERSION ``` A Gradle Version Catalog and Platform (BOM) is provided for each target version of Java. Signed libraries are published to both Maven Central and the GitHub Package Repository. ### GitHub Packages Every release is also published to the GitHub Package Repository, and [idl-clients](/libraries/idl-clients) is published there only. Resolving from it needs a GitHub token with the `read:packages` scope. ```kotlin settings.gradle.kts theme={null} dependencyResolutionManagement { repositories { mavenCentral() maven { url = uri("https://maven.pkg.github.com/sava-software/idl-clients") credentials { username = providers.gradleProperty("gpr.user").get() password = providers.gradleProperty("gpr.token").get() } } } } ``` Keep `gpr.user` and `gpr.token` in `~/.gradle/gradle.properties`, out of the project. ```xml pom.xml theme={null} sava-github https://maven.pkg.github.com/sava-software/idl-clients ``` ```xml settings.xml theme={null} sava-github GITHUB_USERNAME GITHUB_TOKEN ``` *** # 25.11.0 Source: https://sava.software/releases/25.11.0 Transaction v1 support, explicit signing APIs, and migration from 25.10.0. ## What changes * Build transaction format v1 with `TxBuilder`, including transactions up to 4,096 bytes and configuration for priority fees, compute units, loaded account data, and heap size. * Choose signer matching explicitly with `signByKey` and `signInOrder`. * Read v1 transactions through `getTransaction` and full `getBlock` responses. The client advertises support through version 1; `BlockTx.skeleton()` exposes each block entry's format and configuration from its wire data. * Import JSON keys with fields in any order, skip unrelated fields, and receive errors that identify missing required fields. * Use equal instructions interchangeably in hash-based collections, even when their data comes from different arrays or offsets. Start with the [transaction guide](/guides/transactions) for a complete v1 flow. V1 submission requires a cluster that has activated the format. Upgrading Sava does not change cluster support or automatically convert existing transactions to v1. ## Upgrading from 25.10.0 25.11.0 introduces transaction format v1 and removes APIs that were already deprecated in 25.10.0. These removals are intentional breaking changes. Applications using them need source changes and recompilation. Legacy and v0 transaction factories remain available; their deprecation is deferred until v1 is activated on mainnet, with removal to follow later. The deprecated RecentBlockhashes sysvar accessors also remain. | Removed API | Replacement | | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `PublicKey.verifySignature` overloads taking a `String` signature | Pass the decoded signature as `byte[]`. | | `Hmac.hmacSHA512(byte[], byte[])` | Obtain a `Mac` from `Hmac.hmacSHA512()`, initialize it with the key, and authenticate the message. | | `Token2022.extensions()` and `Token2022Account.extensions()` | Use `tokenExtensions()`, which returns a `Set`. | | `ExtensionType` and `TokenExtension.extensionType()` | Use concrete extension types for dispatch and `ordinal()` for the on-chain type ID. | | `RpcEncoding.base58` | Request `RpcEncoding.base64`, or `base64_zstd` where supported. | | `Transaction.MAX_SERIALIZED_LENGTH` | Use the transaction's `exceedsSizeLimit()` method. | ## JSON key import `PrivateKeyEncoding.fromJsonPrivateKey` accepts `encoding`, `secret`, and the optional `pubKey` in any order. Unknown fields are skipped, including nested objects and arrays; fields inside them cannot supply or override the imported key. A supplied public key is still checked against the derived key. Missing `encoding` or `secret` fields now raise `IllegalStateException` naming the missing field. ## Instructions in hash-based collections For valid data spans, factory-created instructions now hash their data by content, consistently with `equals`. Equal instructions can be used interchangeably as `HashMap` keys and `HashSet` entries even when backed by different arrays or offsets. Hash values change; do not persist them as identifiers. Keep the retained account list, public keys, and data unchanged while an instruction is stored in a hash-based collection, or copy mutable inputs before construction. ## Signature verification A signature is binary data. Decode a textual signature using its actual encoding before passing it to the existing byte-array overload. For example, for a base58 signature: ```java theme={null} boolean valid = publicKey.verifySignature(message, Base58.decode(signatureBase58)); ``` The removed overload encoded the signature string as UTF-8. That cannot generally preserve an Ed25519 signature. The overloads accepting a `String` message remain. ## Token-2022 extensions The map keyed by `ExtensionType` is removed. Iterate `tokenExtensions()` and match the concrete type, for example: ```java theme={null} for (var extension : token2022.tokenExtensions()) { if (extension instanceof TransferFeeConfig transferFees) { // Use transferFees here. } } ``` `ordinal()` is the stable on-chain numeric type ID, not an index into a Java enum. Known extensions retain their existing IDs and serialized layouts. Unknown type IDs remain represented by `UnknownTokenExtension`, including their raw bytes, so consumers should preserve them when reading and writing accounts. ## RPC encodings and transaction limits Base58 account data in RPC responses remains readable. Removing the request enum member does not remove the response decoder. `RpcEncoding.parseEncoding` now returns `null` for `"base58"`, just as it does for other unsupported request names. The single transaction-size constant could not describe every transaction format. It carried plain `@Deprecated` in 25.10.0, without `forRemoval = true`, so builds that checked only removal warnings did not receive advance notice of this removal. `exceedsSizeLimit()` applies the built-in transaction's limit: 1,232 bytes for legacy/v0 and 4,096 bytes for v1. Its interface default retains the 1,232-byte compatibility limit for third-party implementations. A transaction fitting its format's size limit does not imply that the destination cluster accepts that format. ## Newly deprecated transaction signing APIs These methods remain available with their existing behavior for this release, but are now marked `@Deprecated(forRemoval = true)`. The `SequencedCollection` overloads of `sign` and `signAndBase64Encode` sign positionally. A `List` selects these overloads even when the caller expects the by-key behavior of `sign(Collection)`. Use the explicit names to choose the behavior: ```java theme={null} tx.signInOrder(signers); // Preserves positional signing; supply message signer order. tx.signByKey(signers); // Matches required signer keys, regardless of list order. ``` Both families include blockhash and Base64 conveniences, such as `signInOrderAndBase64Encode(recentBlockHash, signers)` and `signByKeyAndBase64Encode(recentBlockHash, signers)`. The static raw-buffer helpers use `Transaction.signInOrder(...)` and `Transaction.signInOrderAndBase64Encode(...)`. Transaction-aware positional overloads retain count validation without checking each signer's key against its signature position; the explicit-offset helper trusts the supplied spans. By-key signing validates the complete assignment before writing signatures. The existing single-signer, explicit-index, and `Collection` overloads remain undeprecated. Named instance positional aliases delegate to the corresponding existing overload, including custom convenience overrides. New instance methods have defaults, so existing `Transaction` implementations do not need additional method overrides. # Vanity Address Generator Source: https://sava.software/utilities/vanity Generate addresses with a defined prefix and/or suffix. ## Configuration **GitHub Access Token**: [Generate a classic token](https://github.com/settings/tokens) with the `read:packages` scope to access dependencies hosted on GitHub Package Repository. ```properties .gradle/gradle.properties theme={null} savaGithubPackagesUsername=GITHUB_USERNAME savaGithubPackagesPassword=GITHUB_TOKEN ``` ## Compile ```shell theme={null} ./sava-vanity/compile.sh ``` ## Run ```shell theme={null} ./sava-vanity/genKeys.sh --prefix="abc" --outDir=".keys" ``` ### Docker Instead of running the local jlink binary, you can run a Docker image by passing the `docker` flag with the image name and tag. Build the image: ```shell theme={null} docker build --build-arg PROJECT=sava-vanity -t sava-vanity:local -f sava-vanity/Dockerfile . ``` Run it: ```shell theme={null} ./sava-vanity/genKeys.sh --docker="sava-vanity:local" --prefix="abc" --outDir=".keys" ``` By default, the image is built only when it is not found locally. Pass the `build` flag to force a rebuild even if the image already exists: ```shell theme={null} ./sava-vanity/genKeys.sh --docker="sava-vanity:local" --build --prefix="abc" --outDir=".keys" ``` When not using Docker, the local jlink binary image (`./gradlew :sava-vanity:image`) is built automatically when it has not been built yet. Pass the `build` flag to force a rebuild of the local binary image even if it already exists: ```shell theme={null} ./sava-vanity/genKeys.sh --build --prefix="abc" --outDir=".keys" ``` An `outDir` is required so the generated keys are saved to disk; the host directory is created if necessary and bind-mounted into the container with write permissions so that generated keys are persisted on the host: ```shell theme={null} ./sava-vanity/genKeys.sh --docker="sava-vanity:local" --prefix="abc" --outDir=".keys" ``` ### Args * A `prefix` and/or `suffix` must be provided. * `outDir` is required so the generated keys are saved to disk. * `numThreads` defaults to half of the systems CPU's. * `keyFileFormat` controls the on-disk key file format and may be `properties` (default) or `json`. * Each thread will check every `checkFound` iterations if `numKeys` have been found. * `p1337Letters` allows alphabetic characters to be replaced by visually similar numbers. * `1337Numbers` allows numbers to be replaced by visually similar alphabetic characters. * `screen` may be enabled to manage the session so that it can be re-attached if a remote session is disconnected. * `ctrl+a -> d` to detach * `screen -r` to re-attach ### Run Control * jvmArgs="-server -Xms64M -Xmx128M" * \[d | docker | dockerImage]= * \[b | build]=false * screen=0 * \[nt | numThreads]= * \[nk | numKeys]=1 * \[kf | keyFormat]="base64KeyPair" * \[kff | keyFileFormat]="properties" * \[cf | checkFound]=131072 * \[ld | logDelay]="5S" * \[o | outDir] (required; no default; example: '.keys') * \[sv | sigVerify]=false ### Encryption The generated secret key can be encrypted at rest by enabling the `encrypt` flag. The password is never passed on the command line or as a JVM system property (both of which are visible in process listings); it is supplied to the Java runtime only via the `SAVA_VANITY_ENCRYPT_PASSWORD` environment variable. * \[e | encrypt]=false * \[pw | password] — securely prompts for the password (with confirmation) and forwards it to the Java runtime via the environment variable. Implies `encrypt=true`. * \[pe | passwordEnv]=ENV\_VAR\_NAME — reads the password from an already-exported environment variable for fully non-interactive runs. Implies `encrypt=true`. If `encrypt=true` is set without `password`/`passwordEnv`, and the `SAVA_VANITY_ENCRYPT_PASSWORD` environment variable is not present, the application falls back to reading the password from the interactive Java Console. ```shell theme={null} # Securely prompt for the encryption password. ./sava-vanity/genKeys.sh --prefix="abc" --outDir=".keys" --password # Non-interactive: read the password from an existing environment variable. export MY_VANITY_PASSWORD="..." ./sava-vanity/genKeys.sh --prefix="abc" --outDir=".keys" --passwordEnv=MY_VANITY_PASSWORD ``` #### Key Derivation (KDF) The password is run through a key derivation function before it is used to encrypt the secret. The `kdf` flag selects the function and the secret is always encrypted with AES-256/GCM. The KDF parameters can be customized; when they are omitted, hardened defaults are used. * \[kdf]=argon2id — `argon2id` (memory-hard, the default) or `pbkdf2` (`PBKDF2WithHmacSHA512`). * \[kit | kdfIterations] — number of iterations. Applies to both `pbkdf2` and `argon2id`. * \[kmem | kdfMemoryKB] — Argon2id memory cost in KiB. Only valid with `kdf=argon2id`. * \[kpar | kdfParallelism] — Argon2id parallelism (lanes). Only valid with `kdf=argon2id`. Argon2id parameter tuning is all-or-nothing: either provide none of `kdfMemoryKB`, `kdfParallelism` and `kdfIterations` (to use the defaults) or provide all three. Because Argon2id is memory-hard, each concurrent derivation allocates `kdfMemoryKB` of heap (default 262144 KB / 256 MiB). When `kdf=argon2id` is selected, `genKeys.sh` automatically sizes the JVM heap to `(kdfMemoryKB × numThreads) + 128 MiB` so concurrent derivations do not exhaust the default heap. Passing your own `--jvm` args disables this auto-sizing. ```shell theme={null} # Use Argon2id (the default) with the hardened defaults. ./sava-vanity/genKeys.sh --prefix="abc" --outDir=".keys" --password # Use Argon2id with fully customized parameters (all three are required). ./sava-vanity/genKeys.sh --prefix="abc" --outDir=".keys" --password --kdf=argon2id \ --kdfMemoryKB=262144 --kdfParallelism=4 --kdfIterations=3 # Opt out of Argon2id and customize only the PBKDF2 iteration count. ./sava-vanity/genKeys.sh --prefix="abc" --outDir=".keys" --password --kdf=pbkdf2 --kdfIterations=600000 ``` ### Prefix * \[p | prefix]="" * \[pc | pCaseSensitive]=false * \[pn | p1337Numbers]=true * \[pl | p1337Letters]=true ### Suffix * \[s | suffix]="" * \[sc | sCaseSensitive]=false * \[sn | s1337Numbers]=true * \[sl | s1337Letters]=true # Welcome Source: https://sava.software/welcome Sava is a minimal dependency Java SDK for building on Solana.
Hero Light
*** Crypto and data structure primitives. HTTP and WebSocket JSON RPC clients. Generated source and clients for interacting with onchain programs. ***