SDK
Every call the TypeScript SDK exports.
The SDK is the part of Hush that runs where your key is. It derives the key from a wallet signature, decrypts balances and amounts, and builds the transactions that carry proofs: set up, apply, send, and the encrypted step of a withdraw. It is TypeScript, it runs in a browser and in Node, and the app and the CLI are both written on it.
It works beside @hush/contract, the typed client of the API. The API supplies public data and builds a deposit and a withdraw's release.
| Import from | Holds | Runs in |
|---|---|---|
@hush/sdk | Keys, decryption and the four builders | Browser and Node |
@hush/sdk/chain | Addresses, the program's instructions, and sending | Browser and Node |
@hush/sdk/node | A keypair file as the wallet | Node |
The proof code is WebAssembly. The SDK loads it on the first call that needs it and not at import.
Unlock
The wallet signs KEY_MESSAGE and deriveKeys turns the signature into the keys. Keep them in memory.
import { createClient } from "@hush/contract";
import { KEY_MESSAGE, deriveKeys } from "@hush/sdk";
const api = createClient(apiUrl);
const config = await api.config();
const keys = await deriveKeys(await signMessage(KEY_MESSAGE));signMessage here is your wallet adapter's: it takes the message bytes and returns the 64 signature bytes.
Read balances and amounts
The API returns ciphertexts and the SDK opens them. Every amount is a bigint of base units.
import { decryptAvailable, decryptPending, decryptAmount } from "@hush/sdk";
const account = await api.account(wallet);
const usdc = account.assets.find((a) => a.asset === "usdc")!;
if (usdc.state === "ready") {
const available = await decryptAvailable(keys, usdc.decryptableAvailable!);
const pending = await decryptPending(keys, usdc.pendingLo!, usdc.pendingHi!);
console.log({ available, pending });
}
const { items } = await api.activity(wallet, { asset: "usdc" });
for (const item of items) {
if (item.encryptedAmount) console.log(item.kind, await decryptAmount(keys, item.encryptedAmount));
}Run against a server of sample data, with the sample wallet's keys, this prints:
{ available: 1590500000n, pending: 0n }
send 250000000n
receive 1840500000n
Run a build
Each builder returns a HushBuild: the action's transactions in order, unsigned, and a complete function. Running one goes the same way every time.
import type { HushBuild } from "@hush/sdk";
async function run(build: HushBuild): Promise<string[]> {
const signed = await signAllTransactions(build.steps.map((step) => step.transaction));
const complete = await build.complete(signed);
const signatures: string[] = [];
for (const transaction of complete) {
const { signature } = await api.submit({ transaction });
for (;;) {
const { status, error } = await api.transaction(signature);
if (status === "failed") throw new Error(error ?? "The transaction failed.");
if (status === "confirmed" || status === "finalized") break;
await new Promise((resolve) => setTimeout(resolve, 500));
}
signatures.push(signature);
}
return signatures;
}The wallet signs every step
Pass all the transactions to the wallet in one request. It signs as fee payer.
complete adds the other signatures
A proof step creates accounts with fresh keypairs, and those keypairs sign too. They sign after the wallet, because a wallet may add instructions of its own before signing.
completetakes the wallet's output in the same order and returns transactions ready to send.Submit in order
Send each one and wait until it is confirmed before sending the next. A later step reads accounts an earlier one created.
The actions
import { buildSetup, buildApply, buildSend, buildWithdraw } from "@hush/sdk";
const input = { api, config, wallet, asset: "usdc" as const, keys };
// Set up, once for each asset.
await run(await buildSetup(input));
// Deposit 500 USDC: the API builds it, then apply.
const deposit = await api.buildDeposit({ wallet, asset: "usdc", amount: "500000000" });
await run({ steps: [{ label: "Deposit", transaction: deposit.transaction }], complete: async (signed) => signed });
await run(await buildApply(input));
// Send 120 USDC.
await run(await buildSend({ ...input, to: recipient, amount: 120_000_000n }));
// Withdraw 100 USDC: out of the encrypted balance, then the release.
await run(await buildWithdraw({ ...input, amount: 100_000_000n }));
const release = await api.buildWithdraw({ wallet, asset: "usdc", amount: "100000000" });
await run({ steps: [{ label: "Release", transaction: release.transaction }], complete: async (signed) => signed });A withdraw is two builds. buildWithdraw from the SDK proves the balance covers the amount and moves it out of the encrypted balance. api.buildWithdraw then burns it and releases the asset from the vault. Pass the same amount to both.
In Node
@hush/sdk/node uses a keypair file as the wallet, and executeBuild does what run does above, sending straight to an RPC. With rpcUrl in the input, the builders read the chain through that RPC and the API is not called.
import { address, createSolanaRpc } from "@solana/kit";
import { createClient } from "@hush/contract";
import { KEY_MESSAGE, deriveKeys, buildSend } from "@hush/sdk";
import { configFromChain } from "@hush/sdk/chain";
import { executeBuild, loadKeypair } from "@hush/sdk/node";
const rpc = createSolanaRpc(rpcUrl);
const wallet = await loadKeypair(keypairPath);
const config = await configFromChain(rpc, address(programId), "mainnet");
if (!config) throw new Error("Hush is not initialized on this cluster.");
const [signed] = await wallet.signMessages([{ content: KEY_MESSAGE, signatures: {} }]);
const keys = await deriveKeys(signed![wallet.address]!);
const build = await buildSend({
api: createClient("http://unused.invalid"), // not called when rpcUrl is given
config, wallet: wallet.address, asset: "usdc", keys, rpcUrl,
to: recipient, amount: 120_000_000n,
});
const signatures = await executeBuild(rpc, build, wallet, (label, signature) => console.log(label, signature));Reference: @hush/sdk
| Export | Type | Description |
|---|---|---|
KEY_MESSAGE | Uint8Array | The bytes a wallet signs to unlock. |
deriveKeys | (signature: Uint8Array) => Promise<HushKeys> | Derives your key from the wallet's signature over KEY_MESSAGE. |
decryptAvailable | (keys: HushKeys, base64: string) => Promise<bigint> | Reads an available balance from its owner copy, the account's decryptableAvailable. Throws when the ciphertext doesn't open with these keys. |
decryptPending | (keys: HushKeys, lo: string, hi: string) => Promise<bigint> | Reads a pending balance from the account's pendingLo and pendingHi. |
decryptAmount | (keys: HushKeys, enc: EncryptedAmount) => Promise<bigint> | Reads the amount of a send or a receive from an activity item's encryptedAmount. |
buildSetup | (input: BuildInput) => Promise<HushBuild> | Creates the wallet's Hush account for the asset and registers its encryption public key. |
buildApply | (input: BuildInput) => Promise<HushBuild> | Folds pending into available. |
buildSend | (input: BuildInput & { to: string; amount: bigint }) => Promise<HushBuild> | Sends amount to the Hush account of the wallet to. |
buildWithdraw | (input: BuildInput & { amount: bigint }) => Promise<HushBuild> | Moves amount out of the encrypted balance, ready for the release step that the API builds. |
Types
| Type | Type | Description |
|---|---|---|
HushKeys | { elgamal: ElGamalKeypair; ae: AeKey; elgamalPubkey: string } | Your key. elgamalPubkey is base58 of the 32-byte public key, as the Hush account stores it. |
BuildInput | object | What every builder takes. Fields below. |
HushBuild | { steps: Step[]; complete(signedByWallet: string[]): Promise<string[]> } | One action as its transactions, in order. |
Step | { label: string; transaction: string } | One unsigned v0 transaction, base64, and a label saying what it does. |
BuildInput
| Field | Type | Description |
|---|---|---|
api required | HushApi | The client from createClient in @hush/contract. In a browser the SDK reads the chain through its JSON-RPC relay. |
config required | Config | The answer of api.config(). |
wallet required | string | The wallet's address. It pays the fees and signs every step. |
asset required | "sol" | "usdc" | Which Hush account to act on. |
keys required | HushKeys | From deriveKeys. |
onProgress | (label: string) => void | Called as the build starts its slow part, with a label such as Generating proofs. |
rpcUrl | string | A Solana RPC URL to read the chain through directly. Leave out in a browser. |
Step labels
Each Step has a label naming what its transaction does, for showing progress.
| Label | The transaction |
|---|---|
| Set up account | Creates and configures the Hush account. |
| Key validity proof | Verifies that you hold the key being registered. |
| Apply pending | Folds pending into available. |
| Equality proof | Verifies the equality proof into a context-state account. |
| Ciphertext validity proof | Verifies the validity proof into a context-state account. |
| Stage range proof | Writes the range proof's bytes to a record account, since the proof is too large to ride in the transaction that verifies it. |
| Range proof | Verifies the staged range proof into a context-state account. |
| Send | The transfer, reading the verified proofs. |
| Withdraw to public balance | Moves the amount out of the encrypted balance. |
| Deposit to pending | Moves a deposit into the pending balance. |
| Close proof accounts | Closes the context-state accounts and returns their rent. |
| Close staged proof | Closes the record account and returns its rent. |
Errors
| Thrown by | When | How to tell |
|---|---|---|
buildApply, buildSend, buildWithdraw | The wallet has no Hush account for the asset | error.code is ACCOUNT_NOT_SET_UP |
buildSend | The recipient has no Hush account for the asset | error.code is RECIPIENT_NOT_SET_UP |
decryptAvailable | The ciphertext doesn't open with these keys | Message: This balance does not open with these keys. |
decryptAmount, decryptPending | The value isn't an ElGamal ciphertext | Message: Not an ElGamal ciphertext. |
complete | The number of signed transactions differs from the number of steps | Message names both counts |
| Any call to the API | The API answered with an error | An ApiClientError, with code from the error codes |
Reference: @hush/sdk/chain
The pieces the builders are made of, for a client that builds its own transactions or runs without the API. Addresses and signers are the types of @solana/kit.
| Export | Type | Description |
|---|---|---|
hushAddresses | (programId: Address, usdcMint?: Address) => Promise<HushAddresses> | Derives the program's addresses: config, authority, both vaults and both mints. |
ata | (owner: Address, mint: Address, tokenProgram?: Address) => Promise<Address> | The associated token account of owner for mint. With an hSOL or hUSDC mint this is the wallet's Hush account. |
readVaultConfig | (rpc: HushRpc, programId: Address) => Promise<VaultConfig | null> | Reads the program's Config account. null before the program is initialized. |
configFromChain | (rpc: HushRpc, programId: Address, cluster: Config["cluster"], usdcMint?: Address) => Promise<Config | null> | Builds the API's Config from chain data, for a client that runs without the API. |
confidentialExtension | (token: Token) => ConfidentialTransferAccount | null | The confidential extension of a decoded token account, or null when the account has none. |
feeOf | (amount: bigint, feeBps: number) => bigint | The withdraw fee on amount, rounded down. |
depositInstructions | (a: HushAddresses, owner: TransactionSigner, asset: Asset, amount: bigint) => Promise<Instruction[]> | The program's deposit, then the token program's deposit into pending. |
withdrawReleaseInstructions | (a: HushAddresses, owner: TransactionSigner, asset: Asset, amount: bigint, feeRecipient: Address) => Promise<Instruction[]> | The program's withdraw. For USDC it is preceded by creating the owner's USDC account when missing. |
initializeInstruction | (a: HushAddresses, admin: TransactionSigner, feeBps: number, feeRecipient: Address) => Instruction | The program's initialize. |
setFeeInstruction | (a: HushAddresses, admin: TransactionSigner, feeBps: number, feeRecipient: Address) => Instruction | The program's set_fee. |
buildDepositTransaction | (rpc: HushRpc, a: HushAddresses, wallet: Address, asset: Asset, amount: bigint) => Promise<string> | A deposit as one unsigned transaction, base64. The API's buildDeposit returns the same. |
buildWithdrawReleaseTransaction | (rpc: HushRpc, a: HushAddresses, wallet: Address, asset: Asset, amount: bigint, feeRecipient: Address) => Promise<string> | A withdraw's release step as one unsigned transaction, base64. The API's buildWithdraw returns the same. |
toBuild | (rpc: HushRpc, wallet: Address, plan: InstructionPlan) => Promise<HushBuild> | Packs an instruction plan into v0 transactions with the wallet as fee payer. |
sendAndConfirm | (rpc: HushRpc, signedBase64: string, timeoutMs?: number) => Promise<string> | Sends one signed transaction and waits until it is confirmed. Returns the signature. Throws when it fails or isn't confirmed within timeoutMs, 60,000 by default. |
buildSetup | (input: BuildInput) => Promise<HushBuild> | As in the main entry, which loads this module on the first build. |
buildApply | (input: BuildInput) => Promise<HushBuild> | As in the main entry. |
buildSend | (input: BuildInput & { to: string; amount: bigint }) => Promise<HushBuild> | As in the main entry. |
buildWithdraw | (input: BuildInput & { amount: bigint }) => Promise<HushBuild> | As in the main entry. |
TOKEN_PROGRAM | Address | The SPL Token program, which owns USDC. |
SYSTEM_PROGRAM | Address | The System program. |
ZK_PROOF_PROGRAM | Address | The ZK ElGamal Proof program. |
RECORD_PROGRAM | Address | The SPL Record program, which holds a staged range proof. |
ATA_PROGRAM | Address | The Associated Token Account program. |
MAINNET_USDC_MINT | Address | USDC's mint on mainnet. |
CONFIG_DISCRIMINATOR | number[] | The first 8 bytes of the program's Config account. |
Types
| Type | Type | Description |
|---|---|---|
HushRpc | Rpc<SolanaRpcApi> | A Solana RPC client from @solana/kit. |
HushAddresses | { programId; config; authority; solVault; usdcVault; hsolMint; husdcMint; usdcMint } | Every address the program uses, each an Address. |
VaultConfig | { admin; feeRecipient; feeBps; usdcMint; hsolMint; husdcMint } | The program's Config account, decoded. |
Step | { label; transaction } | As in the main entry. |
HushBuild | { steps; complete } | As in the main entry. |
BuildInput | object | As in the main entry. |
Reference: @hush/sdk/node
| Export | Type | Description |
|---|---|---|
loadKeypair | (path: string) => Promise<KeyPairSigner> | Reads a Solana keypair JSON file as a signer. |
executeBuild | (rpc: HushRpc, build: HushBuild, wallet: KeyPairSigner, onStep?: (label: string, signature: string) => void) => Promise<string[]> | Signs every step with the keypair, completes the build, and sends the transactions in order, waiting for each to confirm. Returns the signatures. |
singleStep | (label: string, transaction: string) => HushBuild | Wraps one unsigned transaction, such as the API's deposit, as a HushBuild so executeBuild can run it. |