SDK

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 fromHoldsRuns in
@hush/sdkKeys, decryption and the four buildersBrowser and Node
@hush/sdk/chainAddresses, the program's instructions, and sendingBrowser and Node
@hush/sdk/nodeA keypair file as the walletNode

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.

ts
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.

ts
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:

text
{ 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.

ts
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;
}
  1. The wallet signs every step

    Pass all the transactions to the wallet in one request. It signs as fee payer.

  2. 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. complete takes the wallet's output in the same order and returns transactions ready to send.

  3. 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

ts
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.

ts
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

ExportTypeDescription
KEY_MESSAGEUint8ArrayThe 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

TypeTypeDescription
HushKeys{ elgamal: ElGamalKeypair; ae: AeKey; elgamalPubkey: string }Your key. elgamalPubkey is base58 of the 32-byte public key, as the Hush account stores it.
BuildInputobjectWhat 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

FieldTypeDescription
api requiredHushApiThe client from createClient in @hush/contract. In a browser the SDK reads the chain through its JSON-RPC relay.
config requiredConfigThe answer of api.config().
wallet requiredstringThe wallet's address. It pays the fees and signs every step.
asset required"sol" | "usdc"Which Hush account to act on.
keys requiredHushKeysFrom deriveKeys.
onProgress(label: string) => voidCalled as the build starts its slow part, with a label such as Generating proofs.
rpcUrlstringA 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.

LabelThe transaction
Set up accountCreates and configures the Hush account.
Key validity proofVerifies that you hold the key being registered.
Apply pendingFolds pending into available.
Equality proofVerifies the equality proof into a context-state account.
Ciphertext validity proofVerifies the validity proof into a context-state account.
Stage range proofWrites the range proof's bytes to a record account, since the proof is too large to ride in the transaction that verifies it.
Range proofVerifies the staged range proof into a context-state account.
SendThe transfer, reading the verified proofs.
Withdraw to public balanceMoves the amount out of the encrypted balance.
Deposit to pendingMoves a deposit into the pending balance.
Close proof accountsCloses the context-state accounts and returns their rent.
Close staged proofCloses the record account and returns its rent.

Errors

Thrown byWhenHow to tell
buildApply, buildSend, buildWithdrawThe wallet has no Hush account for the asseterror.code is ACCOUNT_NOT_SET_UP
buildSendThe recipient has no Hush account for the asseterror.code is RECIPIENT_NOT_SET_UP
decryptAvailableThe ciphertext doesn't open with these keysMessage: This balance does not open with these keys.
decryptAmount, decryptPendingThe value isn't an ElGamal ciphertextMessage: Not an ElGamal ciphertext.
completeThe number of signed transactions differs from the number of stepsMessage names both counts
Any call to the APIThe API answered with an errorAn 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.

ExportTypeDescription
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 | nullThe confidential extension of a decoded token account, or null when the account has none.
feeOf(amount: bigint, feeBps: number) => bigintThe 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) => InstructionThe program's initialize.
setFeeInstruction(a: HushAddresses, admin: TransactionSigner, feeBps: number, feeRecipient: Address) => InstructionThe 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_PROGRAMAddressThe SPL Token program, which owns USDC.
SYSTEM_PROGRAMAddressThe System program.
ZK_PROOF_PROGRAMAddressThe ZK ElGamal Proof program.
RECORD_PROGRAMAddressThe SPL Record program, which holds a staged range proof.
ATA_PROGRAMAddressThe Associated Token Account program.
MAINNET_USDC_MINTAddressUSDC's mint on mainnet.
CONFIG_DISCRIMINATORnumber[]The first 8 bytes of the program's Config account.

Types

TypeTypeDescription
HushRpcRpc<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.
BuildInputobjectAs in the main entry.

Reference: @hush/sdk/node

ExportTypeDescription
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) => HushBuildWraps one unsigned transaction, such as the API's deposit, as a HushBuild so executeBuild can run it.