dWallet Developer Guide for Solana
A dWallet is a signing key that a Solana account controls. It can sign for any chain: Bitcoin, Ethereum, Solana and others. The owner of a dWallet decides which messages get signed, and the ika network produces the signatures. When the owner is your Solana program, your program’s rules decide what the dWallet signs.
The devnet pre-alpha is a mock network
Read this before you build anything. The Solana devnet pre-alpha does not run the real ika network. One backend, the mock, stands in for all the validators.
- There is no MPC. The mock holds an ordinary private key for every dWallet, and signs with it alone.
- It is not secure. The mock can sign any message with any dWallet. Put no real funds on a pre-alpha dWallet.
- No private key is ever sent to the mock. The mock makes every dWallet’s key itself. In the pre-alpha, importing a key does not send that key anywhere: the mock makes a new key, so the imported dWallet has a different public key and address than the key you passed.
- Everything is wiped. The program and all its accounts are reset from time to time, and everything is deleted when ika moves to Alpha 1.
- Nothing is final. Request formats, account layouts, derived addresses and the SDK’s API can change without notice.
This software is provided “as is”, without warranty of any kind. You use it entirely at your own risk, and dWallet Labs assumes no liability for any damages arising from its use.
The pre-alpha is still useful because everything around the signing is real:
- The Solana program on devnet is the one the real network uses.
- The transactions your app and your program send are the real ones.
- The SDK’s calls are the real ones, and the SDK still checks every answer the mock signs and every record on Solana.
The SDK runs in mock mode for the pre-alpha. An app moves to the real network by creating its client without mock mode and naming the real network. Nothing else in the app changes.
How it works
- Create a dWallet. Your app asks the network for a new dWallet. The network writes a
DWalletaccount on Solana that holds its public key. The user accepts their share of the key on Solana, which makes the dWallet usable. - Give it to your program. The dWallet’s owner transfers it to your program’s CPI authority, an address only your program can sign for.
- Approve a message. When your program’s conditions hold, it calls
issue_signature_voucherthrough a CPI. That creates aSignatureVoucheraccount, which allows exactly one signature of one message. - Ask for the signature. Your app sends a sign request that names the voucher. The network reads the voucher on Solana for itself and refuses a request the voucher does not allow.
- Read the signature. The network writes the signature into the voucher account. The app gets it back from the request too, and anyone can read it from the account.
On the real network, the key is split between the user and the validators, and neither side can sign alone. The validators sign together through the 2PC-MPC protocol. In the pre-alpha, the mock does all of this with one key.
#![allow(unused)]
fn main() {
// Your program decides when to sign, and with which dWallet. The CPI authority
// is one address per program, shared by every dWallet you hand it, so bind each
// voucher to the dWallet the request was approved for.
fn cast_vote(ctx: &DWalletContext, proposal: &Proposal, dwallet: &AccountView) -> ProgramResult {
if dwallet.address().as_array() != &proposal.dwallet {
return Err(VotingError::DWalletMismatch.into());
}
if proposal.yes_votes >= proposal.quorum {
ctx.issue_signature_voucher(
coordinator, signature_voucher, dwallet, payer, system_program,
proposal.message_digest, [0u8; 32], proposal.signature_scheme,
None, Some(proposal.user_pubkey), Some(&voucher_seeds),
)?;
}
Ok(())
}
}
What this guide covers
- Getting started. What to install, the devnet pre-alpha’s addresses, a first dWallet and signature from an app, and the concepts the rest of the guide uses.
- SDK. The TypeScript SDK, which an app uses to create dWallets and ask for signatures.
- Tutorial. A voting program, built step by step, where a quorum of votes makes a dWallet sign.
- On-chain integration. The dWallet and voucher accounts, the CPI crates, the rules your program must follow, and gas deposits.
- gRPC API. The requests the network serves, for a client that does not use an SDK.
- Testing. Mollusk, LiteSVM and end-to-end tests.
- Frameworks. The CPI crates for Pinocchio, native Solana programs and Anchor.
- Examples. A voting dWallet and a multisig dWallet, each with a program in three frameworks and an end-to-end demo in TypeScript.
- Reference. Every instruction, account and event of the program.
Installation
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
What you install depends on what you build. An app that creates dWallets and asks for signatures needs an SDK. A Solana program that controls dWallets needs a CPI crate. Most projects have both.
Tools
- Rust, edition 2024:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - Solana CLI 4.2 or later:
sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)". The network sends its transactions in format v1, which Agave 4.2 and later can read and send. - Node.js 22.12 or later and pnpm, for the TypeScript SDK. Bun runs the examples.
- Anchor CLI 1.x, only for Anchor programs. See the Anchor guide.
An app in TypeScript
The SDK is two packages, @ika.xyz/pre-alpha-core and @ika.xyz/pre-alpha-solana. The package names say they are
the pre-alpha, so they install like any other package:
npm install @ika.xyz/pre-alpha-core @ika.xyz/pre-alpha-solana @solana/web3.js
They bring in @ika.xyz/pre-alpha-wasm, the compiled crypto package. To build the
SDK from source instead, clone this repository and run pnpm install && pnpm build at its root.
@ika.xyz/pre-alpha-solana has two entry points. @ika.xyz/pre-alpha-solana/web3 works with @solana/web3.js,
and @ika.xyz/pre-alpha-solana/kit works with @solana/kit. The kit entry point also needs
@solana/web3.js installed, because the SDK builds its instructions with it.
@ika.xyz/pre-alpha-core is listed on its own because the pre-alpha’s mock mode comes from it, as
@ika.xyz/pre-alpha-core/mock. See the TypeScript SDK.
A Solana program
Pick the crate for your framework. All three call the same instructions of the ika program, so the programs they build work the same way.
Pinocchio, for the lowest compute cost, no_std:
[dependencies]
ika-dwallet-pinocchio = { git = "https://github.com/dwallet-labs/ika-pre-alpha" }
pinocchio = { version = "0.11", features = ["cpi"] }
pinocchio-system = "0.6"
Anchor 1.x, declarative:
[dependencies]
ika-dwallet-anchor = { git = "https://github.com/dwallet-labs/ika-pre-alpha" }
anchor-lang = "1.2"
Native, plain solana-program with no framework:
[dependencies]
ika-dwallet-native = { git = "https://github.com/dwallet-labs/ika-pre-alpha" }
solana-program = "2.2"
Each program also needs:
[lib]
crate-type = ["cdylib", "lib"]
Build for SBPF v3, and name the ika network your program will run on:
cargo build-sbf --tools-version v1.54 --arch v3 -- --features devnet-pre-alpha
-
SBPF v3, because Solana refuses to deploy a program built for an earlier version.
-
The network feature, because each CPI crate holds the ika program’s address for each network. Forward a
devnet-pre-alphafeature of your own program to the crate’s feature of the same name:[features] devnet-pre-alpha = ["ika-dwallet-pinocchio/devnet-pre-alpha"]The crate’s
DWalletContextrefuses to call any other program as the ika program. Without that check, a caller could pass a fake ika program and borrow your program’s CPI authority to get a voucher on another dWallet your program controls. Build without a network feature only for tests.
A program built for one network refuses the dWallets of every other. If a pre-alpha wipe moves the ika program to a new address, update the crate, rebuild with the feature, and upgrade your program.
Next
- The devnet pre-alpha: the addresses and values to connect with.
- Quick start: a first dWallet and signature.
For AI coding agents
This repository has a skill for coding agents, ika-solana-pre-alpha, in skills/. It holds the
pre-alpha’s addresses, the rules that prevent the common failures, and the SDK and program
references in a compact form. Install it with the skills CLI, which works with most coding agents:
npx skills add dwallet-labs/ika-pre-alpha --skill ika-solana-pre-alpha
Add -g to install it for every project, or -a <agent> to pick the agents.
The Devnet Pre-Alpha
Pre-alpha. This network is a mock with no MPC. It can sign anything with any dWallet, and it is wiped from time to time. Read the warning in the introduction first.
This page lists the addresses and values an app needs to reach the pre-alpha, and what is different about it.
Addresses
| What | Value |
|---|---|
| Solana cluster | devnet |
| Solana RPC | https://api.devnet.solana.com, or your own devnet RPC provider |
| ika program | 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv |
| ika network, gRPC-Web | https://solana-alpha-dev-1.ika-network.net |
| Network key | fe8a6482521cc4bae052c55cd5b3c92d05c8749bcc2c584046de3efb077d65ed |
| Chain number | 1 |
| Network value | 3 |
| IKA mint | 9NxjShUBEGVzHePwseToSjuH7MXKVphcmVd7XzHj2K22 |
| Treasury vault | 8wFLkRY3MnmxdNKvUtDH1pfvYyjZNDtpWPhYnm2w5ZW5 |
The SDK needs the network key, the chain number and the network value when you create the client. A gas deposit’s top-up names the IKA mint and the treasury vault. The chain number and the network value are recorded in the program’s dWallet coordinator account. The SDK checks every answer against the network key, and the user signs the chain number and the network value into their gas deposit. So copy these values from this page or from the coordinator account. Never take them from an answer of the ika network.
The program and its accounts are wiped from time to time. A wipe can change the program id and the network key. When it does, this page changes with it.
Connecting
The pre-alpha serves the ika network’s API over gRPC-Web, with a public TLS certificate. Use the
SDK’s gRPC-Web client, DWalletGrpcClient from @ika.xyz/pre-alpha-core/web. It works in a browser and
in Node, because it sends its calls through fetch. A plain gRPC client gets HTTP status 400 from
this address.
import { DWalletGrpcClient } from '@ika.xyz/pre-alpha-core/web';
const grpc = new DWalletGrpcClient('https://solana-alpha-dev-1.ika-network.net');
Mock mode
The pre-alpha’s network key is a mock value. A client created without mock mode refuses it with the error “mock values need the SDK’s mock feature”. A client in mock mode refuses any real network key. So the SDK’s mock mode is only for the pre-alpha, and it cannot be turned on by accident against the real network.
In mock mode the SDK skips the user’s half of the 2PC-MPC computations, because the mock has no MPC to answer them. Every other check stays: the network’s signatures on its answers, the records on Solana, the holder’s acceptance of a share, and each signature against the dWallet’s public key.
See mock mode in the TypeScript SDK.
Paying for requests
Each request to the ika network is charged to a gas deposit on Solana. A gas deposit pays for one request key, and the SDK derives the request key from the user’s root seed. The wallet that creates the deposit owns it, and only that wallet can withdraw from it. So a user needs one gas deposit for each root seed, whatever curves their dWallets use. A request signed by a key with no deposit is refused with “this transport key has no gas deposit on the chain the request names”.
The mock charges nothing. An empty gas deposit is enough in the pre-alpha, but it must exist.
Getting devnet SOL
Every Solana transaction costs SOL: the encryption key’s registration, the gas deposit, the acceptance of a share and each voucher. The devnet RPC faucet is closed, so the SDK’s examples cannot ask for an airdrop. Get devnet SOL from https://faucet.solana.com. One SOL covers many dWallets and signatures.
Things that differ from what you might expect
- ECDSA signatures are 65 bytes. On secp256k1 and P-256, the first byte is the recovery byte,
then come
rands. A verifier that takes 64 bytes needssignature.slice(1). Ed25519 signatures are the usual 64 bytes. - The public Solana RPC limits its rate. A full flow reads many accounts, and
https://api.devnet.solana.comanswers some of those reads with HTTP 429. Use your own devnet RPC provider, or retry reads that get 429. - Imported keys get a new key. As the introduction says, the mock makes a new key for an imported dWallet. Your imported key never leaves your device, and the dWallet does not sign as it.
Quick Start
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
This page takes a TypeScript app from nothing to a signature on the devnet pre-alpha. The app creates an Ed25519 dWallet, approves one message, has the network sign it, and checks the signature. Then it shows where a Solana program takes over the approval.
You need Node.js 22.12 or later, the packages from Installation, and a devnet keypair with about 0.1 SOL. Get the SOL from https://faucet.solana.com.
1. Create the client
The client needs two connections: one to Solana, to send transactions and read accounts, and one to the ika network, to send requests. The values come from the devnet pre-alpha.
import { DWalletGrpcClient } from '@ika.xyz/pre-alpha-core/web';
import { withMockCryptography } from '@ika.xyz/pre-alpha-core/mock';
import {
Curve,
Hash,
IkaClient,
IkaTransaction,
SignatureAlgorithm,
UserShareEncryptionKeys,
} from '@ika.xyz/pre-alpha-solana/web3';
import { Connection, Keypair, PublicKey, Transaction } from '@solana/web3.js';
import { ed25519 } from '@noble/curves/ed25519.js';
const connection = new Connection('https://api.devnet.solana.com', 'confirmed');
const programId = new PublicKey('8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv');
const networkKey = Uint8Array.from(
Buffer.from('fe8a6482521cc4bae052c55cd5b3c92d05c8749bcc2c584046de3efb077d65ed', 'hex'),
);
const ikaClient = new IkaClient(
withMockCryptography({
connection,
grpc: new DWalletGrpcClient('https://solana-alpha-dev-1.ika-network.net'),
config: {
network: { custom: { networkPublicKeys: [networkKey] } },
programId,
chainNumber: 1,
networkValue: 3,
},
}),
);
withMockCryptography puts the client in mock mode, which the pre-alpha needs. Drop it, and name the
real network, to move the same app to the real network.
2. Make the user’s keys
Every key of a user comes from one root seed of 32 random bytes. Keep the seed as a secret: a user who loses it loses the shares of their dWallets.
const wallet = Keypair.fromSecretKey(/* your devnet keypair */);
const rootSeed = crypto.getRandomValues(new Uint8Array(32));
const keys = await UserShareEncryptionKeys.fromRootSeedKey(rootSeed, Curve.ED25519);
wallet is the user’s Solana wallet. It pays for transactions and owns the new dWallet. keys holds
the user’s encryption key, which the user’s share is encrypted to, and the request key, which signs
every request to the network.
3. Register the encryption key and open a gas deposit
Both are Solana transactions the wallet signs, once per root seed. The registration goes in a transaction of its own, because it carries the whole encryption key.
async function send(build: (ikaTx: IkaTransaction) => unknown): Promise<void> {
const transaction = new Transaction();
const ikaTx = new IkaTransaction({
ikaClient,
transaction,
owner: wallet.publicKey,
userShareEncryptionKeys: keys,
});
await build(ikaTx);
transaction.feePayer = wallet.publicKey;
transaction.recentBlockhash = (await connection.getLatestBlockhash('finalized')).blockhash;
transaction.sign(wallet, ...ikaTx.signers);
const signature = await connection.sendRawTransaction(transaction.serialize());
// The network reads Solana at finalized commitment, so wait for it.
await connection.confirmTransaction(signature, 'finalized');
}
await send((ikaTx) => ikaTx.registerEncryptionKey({ curve: Curve.ED25519 }));
await send((ikaTx) => ikaTx.createGasDeposit());
Every request is charged to the gas deposit of the key that signs it. The mock charges nothing, so an
empty deposit is enough. On the real network, fund it with topUpGasDeposit.
4. Create the dWallet
const { dWallet } = await ikaClient.requestDWalletDKG({
curve: Curve.ED25519,
userShareEncryptionKeys: keys,
owner: wallet.publicKey,
});
await send((ikaTx) => ikaTx.acceptEncryptedUserShare({ dWallet }));
const address = await ikaClient.waitForDWallet(dWallet);
requestDWalletDKG asks the network for a new dWallet and checks the network’s answer. The network
writes the DWallet account on Solana and leaves the user’s share waiting there. The user accepts
the share in a Solana transaction, and only then can the dWallet sign. waitForDWallet returns the
dWallet account’s address once Solana shows the acceptance.
5. Approve a message and sign it
const message = new TextEncoder().encode('hello from the pre-alpha');
const scheme = { signatureAlgorithm: SignatureAlgorithm.EdDSA, hashScheme: Hash.SHA512 };
let signatureVoucher!: PublicKey;
await send(async (ikaTx) => {
signatureVoucher = await ikaTx.approveMessage({ dWallet, message, ...scheme });
});
const signature = await ikaClient.requestSign({
dWallet,
signatureVoucherId: signatureVoucher,
message,
...scheme,
userShareEncryptionKeys: keys,
});
console.log('verifies:', ed25519.verify(signature, message, dWallet.publicKey));
approveMessage adds an instruction that creates a signature voucher: an account that allows one
signature of this message, with this dWallet. The voucher lives at a fresh address that signs its own
creation, which is why send signs with ikaTx.signers too.
requestSign reads the voucher first, and refuses before sending anything if the voucher is for
another dWallet, message or scheme. It takes a presign from the network’s pool, sends the sign
request, and checks the signature against the dWallet’s public key. The network also writes the
signature into the voucher account.
6. Hand the approval to a program
Above, the user’s wallet owns the dWallet, so the wallet approves messages. To let a program decide
instead, transfer the dWallet to the program’s CPI authority. That is the address derived from the
seed __ika_cpi_authority under your program’s id. Only your program can sign for it.
const [cpiAuthority] = PublicKey.findProgramAddressSync(
[Buffer.from('__ika_cpi_authority')],
yourProgramId,
);
await send((ikaTx) => ikaTx.transferDWallet({ dWallet, newOwner: cpiAuthority }));
Set up your program’s own record of who may use the dWallet before this transfer, while the wallet still owns it. After the transfer, only your program can act on the dWallet.
From then on, your program creates the voucher through a CPI when its conditions hold:
#![allow(unused)]
fn main() {
ctx.issue_signature_voucher(
coordinator, // the ika program's DWalletCoordinator account
signature_voucher, // a fresh writable address that signs its own creation
dwallet, // the dWallet account
payer, // pays the voucher's rent
system_program,
message_digest, // keccak256 of the message
message_metadata_digest, // keccak256 of the metadata, or all zeros if there is none
signature_scheme, // a DWalletSignatureScheme value, for example 5 for EdDSA with SHA-512
None, // the voucher's owner: None makes it your program's CPI authority
Some(user_pubkey), // the request key allowed to send the sign request
Some(&voucher_seeds), // the voucher's seeds, when it is your program's PDA
)?;
}
The app then calls requestSign with that voucher’s address, as in step 5.
The ika program checks only that your program owns the dWallet. Which dWallet gets a voucher, and who may ask for one, is your program’s decision. Read Integrator Invariants before you ship, and follow the voting tutorial for a whole program.
Core Concepts
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
This page explains the terms the rest of the guide uses. Each section starts with what the thing is, then says where it lives and who changes it. The byte layouts are in the account reference.
dWallet
A dWallet is a signing key that a Solana account controls. Its DWallet account on Solana holds the
public key, the curve and the owner.
On the real network, the private key never exists in one place. It is split into two shares. The user holds one share, and the validators hold the other between them. Neither side can sign alone: a signature needs both, through the 2PC-MPC protocol. In the devnet pre-alpha, the mock holds the whole key instead.
A dWallet can sign for any chain whose signature scheme it supports. The curve decides which schemes those are. See Curves and signature schemes below.
A new dWallet goes through these states, and only forward:
- Awaiting the key holder’s signature. The network has written the dWallet and left the user’s share waiting on Solana, encrypted to the user’s encryption key.
- Active. The user accepted the share in a Solana transaction (
AcceptEncryptedUserShare), or the user’s share was made public. Only an active dWallet can get a voucher or be transferred.
Owner
The owner of a dWallet decides which messages it signs, because only the owner can issue a voucher for it. The owner is one of two things:
- A wallet. The user signs the voucher’s transaction directly. This is how a dWallet starts: its creator owns it.
- A program’s CPI authority. A program owns the dWallet and issues vouchers through a CPI.
The owner transfers a dWallet with the TransferDWallet instruction.
CPI authority
A program’s CPI authority is the address derived from the seed __ika_cpi_authority under the
program’s id. Only that program can sign for it.
When a dWallet’s owner is a program’s CPI authority, only that program can issue vouchers for it. The ika program checks the CPI caller to make sure.
A program has one CPI authority, and every dWallet handed to the program shares it. So the ika program cannot tell which of your dWallets a request is meant for. Your program must bind each voucher to the right dWallet itself. See Integrator Invariants.
Signature voucher
A signature voucher is an account that allows the network to sign one message with one dWallet,
once. Its owner creates it with IssueSignatureVoucher. It records:
- the dWallet;
- the digest of the message, and of its metadata if it has any;
- the signature scheme;
- the signing key: the request key that may send the sign request;
- its status, and the signature once the network writes it.
A voucher lives at a fresh address that signs its own creation. No seeds derive it. A sign request names the voucher by its address.
The network signs for a voucher only when the voucher is pending and has a signing key, and the request matches the voucher’s dWallet, digests, scheme and signing key. Two signatures of the same message need two vouchers.
A voucher’s status is one of these:
| Status | Meaning |
|---|---|
| Pending | Waiting for its signature. |
| Signed | Holds its signature. |
| Settled without delivery | The network charged for the sign, and no signature will be written. |
| Revoked | The owner revoked it. A sign agreed before the revoke still writes its signature. |
A future signature voucher works the same way, in two steps. The user’s half of the signature is written first, and the signature is finished later, from any key the voucher names.
Request key and gas deposit
Requests to the ika network do not go through Solana. The app sends them to the network directly. Each request is signed by a request key and charged to that key’s gas deposit on Solana.
The SDK derives the request key from the user’s root seed, the same seed every other key of the user comes from. The request key does not depend on the curve. So one gas deposit serves all the user’s dWallets, on every curve.
A gas deposit holds two balances:
- IKA, for the network’s fees for each request;
- SOL, for the network’s cost of writing results to Solana.
The devnet pre-alpha charges nothing, but a request still needs a deposit to exist. See Gas Deposits.
Encryption key
The user’s encryption key is the key the user’s share is encrypted to. The user registers it on
Solana once per curve (RegisterEncryptionKey), before their first dWallet on that curve. The
network writes each new share encrypted to it, so only the user can read their share.
The network’s address
The network acts on Solana through its own Ed25519 key. It writes every result: new dWallets, shares, signatures and the first step of future signs. The program accepts these writes only when that key signed them. On the real network the key is a threshold key: the validators make each of its signatures together, and no single validator holds it.
Presign
A presign is a part of a signature that the network computes before the message is known. A sign uses up one presign, which makes the sign faster.
- Global presigns come from the network’s pool, one pool per signature algorithm. Any dWallet made by the network can use them.
- Presigns for one dWallet are made for one imported-key dWallet. Its ECDSA signs need them.
A presign belongs to the epoch it was made in, and expires with it. The SDK takes a new one when that happens.
Epoch
The ika network works in epochs. Every request names the epoch the chain shows, and the network refuses a request for another epoch. On Solana, the SDK reads the epoch from the program’s dWallet coordinator account. The devnet pre-alpha moves its epoch rarely.
Key generation (DKG)
A new dWallet comes from a distributed key generation. On the real network, the user and the network compute the key together, so that each ends up with its own share and neither knows the other’s.
The flow on Solana:
- The app sends a DKG request to the network.
- The network computes its side, writes the
DWalletaccount and the user’s encrypted share (CommitDWallet), and answers the app with a signed record of the result. - The SDK checks that record against the network key.
- The user accepts the share on Solana. The dWallet is then active, and its creator owns it.
Curves and signature schemes
| Curve | Value | Used by |
|---|---|---|
| Secp256k1 | 0 | Bitcoin, Ethereum |
| Secp256r1 (P-256) | 1 | WebAuthn, secure enclaves |
| Curve25519 | 2 | Ed25519: Solana, Sui |
| Ristretto | 3 | sr25519: Substrate, Polkadot |
A voucher names a signature scheme: the signature algorithm and the hash together.
| Scheme | Value | Curve | Used by |
|---|---|---|---|
EcdsaKeccak256 | 0 | Secp256k1 | Ethereum |
EcdsaSha256 | 1 | Secp256k1, Secp256r1 | Bitcoin legacy, WebAuthn |
EcdsaDoubleSha256 | 2 | Secp256k1 | Bitcoin BIP143 |
TaprootSha256 | 3 | Secp256k1 | Bitcoin Taproot |
EcdsaBlake2b256 | 4 | Secp256k1 | Zcash |
EddsaSha512 | 5 | Curve25519 | Ed25519 |
SchnorrkelMerlin | 6 | Ristretto | sr25519 |
In the SDKs, a sign takes the signature algorithm and the hash separately, for example
SignatureAlgorithm.EdDSA with Hash.SHA512. Presigns are kept per signature algorithm, not per
scheme.
An ECDSA signature comes back as 65 bytes: the recovery byte, then r and s.
TypeScript SDK
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The TypeScript SDK creates dWallets, asks the ika network for signatures, and builds the Solana instructions that go with them. It runs in Node and in a browser.
It comes as two packages:
@ika.xyz/pre-alpha-coreis the part every chain shares: the requests to the network, the user’s keys, the checks of the network’s answers, and the user’s half of each protocol step.@ika.xyz/pre-alpha-solanais the Solana part: the program’s addresses and instructions, the readers for its accounts, and theIkaClientandIkaTransactionclasses an app uses.
@ika.xyz/pre-alpha-solana has two entry points with the same classes. Import
@ika.xyz/pre-alpha-solana/web3 if your app uses @solana/web3.js, or @ika.xyz/pre-alpha-solana/kit if it
uses @solana/kit. The examples below use web3.js.
The three classes
UserShareEncryptionKeysholds every key of one user, derived from one root seed.IkaTransactionadds the ika program’s instructions to a Solana transaction that the user’s wallet signs.IkaClientsends requests to the ika network and reads the program’s accounts on Solana.
Requests to the network do not go through Solana. The SDK sends them to the network directly, signed by the user’s request key, which comes from the root seed. So the wallet never signs request bytes. It signs only Solana transactions: the encryption key’s registration, the gas deposit, the share’s acceptance and the vouchers that approve messages.
Creating the client
import { DWalletGrpcClient } from '@ika.xyz/pre-alpha-core/web';
import { IkaClient } from '@ika.xyz/pre-alpha-solana/web3';
const ikaClient = new IkaClient({
connection, // a @solana/web3.js Connection
grpc, // the ika network: a URL, or a DWalletGrpcClient
config: { network, programId },
});
config.network names the ika network. It is 'mainnet', 'testnet', or for any other network
{ custom: { networkPublicKeys } }. A custom network also needs chainNumber and networkValue on
config. Take these values from the network’s operator or from the program’s coordinator account,
never from an answer of the ika network. The SDK checks every answer against the network keys, and
the user signs the chain number and the network value into their gas deposit.
grpc is how the client reaches the network:
- For the devnet pre-alpha, in a browser or in Node, pass a
DWalletGrpcClientfrom@ika.xyz/pre-alpha-core/web, made with thehttps://URL of the network’s gRPC-Web endpoint. This client sends its calls throughfetch, so it works in Node too. In a browser bundle, a plainhttps://URL string works as well. - In Node against validators, pass a validator’s
host:portstring. The client then pins TLS to the network key of a member of the committee the network signed, and checks that committee against Solana. - For a local node that serves plaintext, pass
{ url, insecure: true }.
Reads of Solana go through connection. To read through something else, pass
getAccount(address), a function that returns an account’s owner and data, or null.
Mock mode for the pre-alpha
The devnet pre-alpha needs the client in mock mode. Wrap the client’s options in
withMockCryptography, from the separate entry @ika.xyz/pre-alpha-core/mock:
import { withMockCryptography } from '@ika.xyz/pre-alpha-core/mock';
const ikaClient = new IkaClient(
withMockCryptography({
connection,
grpc: new DWalletGrpcClient('https://solana-alpha-dev-1.ika-network.net'),
config: {
network: { custom: { networkPublicKeys: [networkKey] } },
programId,
chainNumber: 1,
networkValue: 3,
},
}),
);
The values are on the devnet pre-alpha page.
In mock mode the SDK skips its 2PC-MPC computations: the user’s half of the key generation, the encryption and decryption of the share, and the user’s half of each signature. Every other check stays: the network’s signatures on its answers, the records on Solana, the holder’s acceptance of a share, and each signature against the dWallet’s public key.
Mock mode is safe to leave in the code by mistake, for three reasons:
- Mock mode needs a custom network.
- A client in mock mode refuses a network that serves a real network key.
- Mock mode belongs to one client. Every other client, in the same process too, refuses the mock’s values with the error “mock values need the SDK’s mock feature”.
The main entry of @ika.xyz/pre-alpha-core never imports /mock, so an app that does not import it ships
no mock code.
In mock mode, importing a key does not read the key you pass. The mock makes a new key for the dWallet, so your key never leaves your device, and the imported dWallet has a different public key.
The flow
Each step below that changes Solana is a transaction the user’s wallet signs. A helper keeps the examples short:
import { IkaTransaction, UserShareEncryptionKeys, Curve } from '@ika.xyz/pre-alpha-solana/web3';
import { Transaction } from '@solana/web3.js';
const keys = await UserShareEncryptionKeys.fromRootSeedKey(rootSeed, Curve.ED25519);
async function send(build: (ikaTx: IkaTransaction) => unknown): Promise<void> {
const transaction = new Transaction();
const ikaTx = new IkaTransaction({
ikaClient,
transaction,
owner: wallet.publicKey,
userShareEncryptionKeys: keys,
});
await build(ikaTx);
transaction.feePayer = wallet.publicKey;
transaction.recentBlockhash = (await connection.getLatestBlockhash('finalized')).blockhash;
transaction.sign(wallet, ...ikaTx.signers);
const signature = await connection.sendRawTransaction(transaction.serialize());
await connection.confirmTransaction(signature, 'finalized');
}
The network reads Solana at finalized commitment. So wait for each transaction to be finalized before the request that depends on it.
ikaTx.signers holds the keypairs of the vouchers the transaction creates. A voucher lives at a
fresh address that signs its own creation, so the transaction needs those signatures too.
Once per root seed: register the encryption key and open the gas deposit.
await send((ikaTx) => ikaTx.registerEncryptionKey({ curve: Curve.ED25519 }));
await send((ikaTx) => ikaTx.createFundedGasDeposit({ ikaTokenAccount, ikaAmount, solAmount }));
The registration goes in a transaction of its own. It takes 876 of the 1,232 bytes a Solana
transaction holds. The gas deposit pays for every request the user’s request key signs.
createFundedGasDeposit reads the network’s minimum first deposit and deposit fee: ikaAmount and
solAmount are what the deposit is credited, and the payer also pays the fee in SOL. The devnet
pre-alpha charges nothing, so there createGasDeposit() alone is enough. A payout that pays
everything closes the deposit, and createFundedGasDeposit then reopens it as its next life.
A user registers an encryption key once for each curve they use. The gas deposit is one for all curves, because the request key does not depend on the curve.
Create a dWallet:
const { dWallet } = await ikaClient.requestDWalletDKG({
curve: Curve.ED25519,
userShareEncryptionKeys: keys,
owner: wallet.publicKey,
});
await send((ikaTx) => ikaTx.acceptEncryptedUserShare({ dWallet }));
const address = await ikaClient.waitForDWallet(dWallet);
The network writes the dWallet on Solana and leaves the user’s share waiting there. The user’s
acceptance makes the dWallet usable. The holder’s signature is what the program checks, so anyone
may send the acceptance. waitForDWallet returns once Solana shows the dWallet active.
Sign a message:
let signatureVoucher!: PublicKey;
await send(async (ikaTx) => {
signatureVoucher = await ikaTx.approveMessage({ dWallet, message, signatureAlgorithm, hashScheme });
});
const signature = await ikaClient.requestSign({
dWallet,
signatureVoucherId: signatureVoucher,
message,
signatureAlgorithm,
hashScheme,
userShareEncryptionKeys: keys,
});
requestSign reads the voucher on Solana first. It throws before computing anything when the
voucher is for another dWallet, message or scheme. signatureAlgorithm and hashScheme may be left
out, and the sign then uses the voucher’s scheme. Given no presign, the sign takes one from the
network’s pool. The SDK checks the signature against the dWallet’s public key before it returns it.
An ECDSA signature is 65 bytes: the recovery byte, then r and s. Pass signature.slice(1) to a
verifier that takes 64 bytes.
Hand the dWallet to a program:
await send((ikaTx) => ikaTx.transferDWallet({ dWallet, newOwner: programCpiAuthority }));
After this, only the program can issue vouchers for the dWallet. The app still sends the sign request, naming the voucher the program issued.
Every request
IkaClient has the same calls on every chain:
| Call | What it does |
|---|---|
requestDWalletDKG | Create a dWallet. With signDuringDKGRequest, also sign one message. |
requestDWalletDKGWithPublicUserShare | Create a dWallet whose user share is public. |
requestImportedKeyDWalletVerification | Create a dWallet from a key the user holds. |
requestGlobalPresign, requestGlobalPresigns | Take presigns from the network’s pool. |
requestPresign | Take a presign made for one imported-key dWallet, for its ECDSA signs. |
requestSign | Sign under a signature voucher. Takes its own presign when given none. |
requestFutureSign, futureSign | Sign in two steps: the user’s half now, the rest later. |
makeDWalletUserSecretKeySharesPublic | Make a dWallet’s user share public. This cannot be undone. |
requestReEncryptUserShareFor, receiveEncryptedUserShare | Give a dWallet’s share to another user, who then accepts it. |
getDWallet | Read a dWallet on Solana, checked for the keys’ holder. |
A future sign has three steps after requestFutureSign:
- Wait for the partial signature on Solana with
waitForPartialUserSignature. - Set the voucher’s signing key again with
IkaTransaction.setFutureSignatureVoucherSigningKey, because step 1 clears it. - Call
futureSign.
Errors an app handles
PresignExpiredWithTheEpoch. You passed a presign, and the chain is already past the presign’s epoch. Nothing was sent. Take a new presign and sign again.EpochClosedBeforeAnswer. The request’s epoch closed before the network answered. The request may still have run in that epoch, so the SDK does not send it again: a new request would open a new session and could be charged a second time. The error carries the request’s epoch and its session identifier, so the app can decide.TransactionTooLargeError. AnIkaTransactionmethod would push the transaction over 1,232 bytes. The method takes its instructions out again. Send what the transaction holds and put the rest in a new one.
Several steps in one transaction
Each IkaTransaction method adds instructions to the same transaction. So several approvals, voucher
changes and your own instructions can go out and land together. Add your own instructions with
ikaTx.add(...), so they count towards the size check too.
For a versioned transaction, which can use address lookup tables to fit more, pass version: 0 in
place of transaction, and build it when you send:
const ikaTx = new IkaTransaction({
ikaClient,
version: 0,
addressLookupTableAccounts,
owner,
userShareEncryptionKeys: keys,
});
await ikaTx.approveMessage({ dWallet, message, signatureAlgorithm, hashScheme });
const tx = ikaTx.buildVersionedTransaction({ recentBlockhash }); // already signed by the vouchers
tx.sign([wallet]);
With @solana/kit
@ika.xyz/pre-alpha-solana/kit is the same SDK with kit types. Every address is a kit Address.
IkaClient reads through a kit Rpc. IkaTransaction returns kit instructions to append to your
transaction message. The voucher’s keypair signer is attached to its account, and so are the owner
and the payer when you pass them as signers. So signTransactionMessageWithSigners signs the whole
transaction.
import { IkaClient, IkaTransaction } from '@ika.xyz/pre-alpha-solana/kit';
import {
appendTransactionMessageInstructions,
createSolanaRpc,
createTransactionMessage,
pipe,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
signTransactionMessageWithSigners,
} from '@solana/kit';
const ikaClient = new IkaClient({ rpc: createSolanaRpc(rpcUrl), grpc, config });
const ikaTx = new IkaTransaction({ ikaClient, owner: walletSigner, userShareEncryptionKeys: keys });
await ikaTx.approveMessage({ dWallet, message, signatureAlgorithm, hashScheme });
const transaction = await signTransactionMessageWithSigners(
pipe(
createTransactionMessage({ version: 0 }),
(m) => setTransactionMessageFeePayerSigner(walletSigner, m),
(m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
(m) => appendTransactionMessageInstructions(ikaTx.instructions, m),
),
);
Mock mode works the same way on kit: wrap the options in withMockCryptography. The kit entry point
still needs @solana/web3.js installed, because the SDK builds its instructions with it.
In a browser
-
Use the gRPC-Web client from
@ika.xyz/pre-alpha-core/web. The network’s gRPC-Web endpoint serves a public TLS certificate, and the SDK’s checks of each answer verify what the network signed. -
The user’s device computes its half of every protocol step. On the real network, creating a dWallet takes about 10 seconds of computation and a secp256k1 sign about 8. On a page’s main thread that freezes the page, so call
useWasmWorker()once at startup, or passcomputeInWorker: truetoIkaClient. In mock mode there is almost nothing to compute. -
The instruction builders import
Bufferfrom the npmbufferpackage. Point your bundler’sbufferat it. With Vite:// vite.config.ts export default defineConfig({ resolve: { alias: { buffer: 'buffer/' } }, define: { global: 'globalThis' }, optimizeDeps: { include: ['buffer'] }, });// the page's entry module, before anything else import { Buffer } from 'buffer'; globalThis.Buffer = Buffer;
The multisig example has a React app that does all of this.
An app paying for its users
Users need no IKA and no SOL when the app pays every cost. There are three costs:
- Solana fees and rent. Pass the app’s wallet as
payertoIkaTransaction. It pays the fees and every account’s rent, and the user’s wallet signs only as the dWallet’s owner. - The network’s fees, with one app key. The app’s backend holds one
RequestKeywith one gas deposit, and signs every user’s requests. The client passes arequestSignerthat sends each request’s bytes to the backend. The backend checks them withdecodeSignedRequestagainst its own rules, then signs them withRequestKey.signRequest. The user’s device still computes its half of each signature, so the backend never sees a share and cannot sign anything an owner did not approve. - The network’s fees, with a deposit per user. Each user keeps their own request key. The user’s
device signs its consent with
IkaClient.signGasDepositConsent({ requestKey: keys, depositOwner: app }). The app creates the deposit with it (createGasDeposit(consent)), owns it, and refills it withtopUpGasDeposit({ requestPublicKey }).
// The app's backend
const appKey = RequestKey.fromSecretKey(secret);
app.post('/ika/sign-request', async (req) => {
const request = decodeSignedRequest(req.body.bytes); // kind, chain, owner, fields
await checkPolicy(req.user, request); // the app's own rules: who, what, how often
return appKey.signRequest(req.body.bytes);
});
// The app's client
const ikaClient = new IkaClient({
...options,
requestSigner: {
publicKey: appRequestPublicKey,
signRequest: (bytes) => callBackend('/ika/sign-request', bytes),
},
});
The lower-level parts
IkaClient and IkaTransaction are built on the root entry of @ika.xyz/pre-alpha-solana, which an app
can use to build its own flow:
- Addresses.
dwalletPda,gasDepositPda,encryptionKeyPda,dwalletCoordinatorPdaand the others derive each account’s address.approvalMessageDigestscomputes the two digests a voucher stores from a message and its metadata. - Account readers.
readDWallet,readDWalletCoordinator,readSignatureVoucherVerifiedand the others decode the program’s accounts. Each returnsnullfor data that is not an account of its type.readSignatureVoucherVerifiedthrows when the voucher is not for the dWallet, message, metadata and scheme you expect, and returns the signature only after your verifier accepts it. - Instruction builders, on
@ika.xyz/pre-alpha-solana/instructions:createDepositInstructions,transferOwnershipInstruction,issueSignatureVoucherInstruction,topUpInstructionand others. This entry is the only one that needs@solana/web3.js. - Instruction bytes and account tags.
instructionByte(name)andaccountDiscriminator(name)look the numbers up by name in a copy of the program’swire-tables.json. An unknown name throws and lists the names it knows, instead of returning a byte that means something else.
The package’s README has the details of each.
Tutorial: A Voting dWallet
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
This tutorial walks through a Solana program that puts a dWallet under the control of a council. The council is a fixed list of members and a quorum. A member proposes a message. When enough members vote yes, the program issues a signature voucher for the message, and the ika network signs it with the dWallet.
The program is examples/voting/pinocchio/src/lib.rs. The tutorial quotes it as it
is, so you can read the two side by side. The same program exists for solana-program and for
Anchor, in examples/voting/native and examples/voting/anchor.
What the program does
| Number | Instruction | Who sends it | What it does |
|---|---|---|---|
| 2 | create_council | the dWallet’s owner | Fixes the members and the quorum for one dWallet |
| 0 | create_proposal | a council member | Creates a proposal: a message to sign with the council’s dWallet |
| 1 | cast_vote | a council member | Records a vote. The vote that reaches the quorum issues the voucher |
The life of one dWallet in this program:
- A user creates a dWallet. The user’s wallet is its owner.
- The user creates the council for the dWallet, at the address
["council", dwallet]. - The user transfers the dWallet to the program’s CPI authority. From now on only the program can issue vouchers for it.
- A member creates a proposal with the message’s digest. The proposal takes the council’s quorum.
- Members vote. Each vote creates a vote record,
["vote", proposal_id, voter]. - The vote that reaches the quorum makes the program call
issue_signature_voucher. The voucher is at the program’s own address["signature_voucher", proposal_id]. - The proposal’s signer sends a sign request that names the voucher. The network signs and writes the signature into the voucher.
Why the council exists
The ika program knows a program by one address: its CPI authority. Every dWallet owned by that address belongs to the program as a whole. So the program must decide, for each dWallet it holds, who may ask for a signature. Without that decision, anybody could create a proposal of their own, with their own quorum, for a dWallet someone else gave the program, and get any message signed.
The program closes that with two rules:
- The rules are fixed per dWallet, by the dWallet’s owner, before the transfer. The council’s address is derived from the dWallet’s, so there is one per dWallet. Only the dWallet’s current owner can create it.
- Everything after is bound to that council. Only its members propose and vote. The quorum comes from the council. The vote that issues the voucher must pass the proposal’s own dWallet.
Copy both rules when you build your own program. The full list is in Integrator Invariants.
The chapters
- Create the program: the accounts, the errors and the dispatch.
- Create the council and the proposal.
- Cast votes and issue the voucher.
- Read and verify the signature.
- Test the program.
Source layout
examples/voting/
pinocchio/src/lib.rs the program
pinocchio/tests/mollusk.rs one instruction at a time
pinocchio/tests/litesvm.rs the CPI into the real ika program
native/, anchor/ the same program in the other frameworks
e2e/ a TypeScript demo against the devnet pre-alpha
Before you start
- Complete the installation.
- Know Solana programs: accounts, PDAs and CPIs. This tutorial explains only what is specific to dWallets.
Create the Program
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
This chapter sets up the program: its dependencies, its three account types, its errors, and the function that reads a dWallet’s owner.
Cargo.toml
[package]
name = "my-voting-program"
version = "0.1.0"
edition = "2024"
[dependencies]
ika-dwallet-pinocchio = { git = "https://github.com/dwallet-labs/ika-pre-alpha" }
pinocchio = { version = "0.11", features = ["cpi"] }
pinocchio-system = "0.6"
solana-address = { version = "2.6", features = ["curve25519"] }
[dev-dependencies]
mollusk-svm = "0.15"
solana-account = "4.3"
solana-instruction = "3.4"
solana-program-error = "3"
solana-pubkey = "4.1"
[features]
devnet-pre-alpha = ["ika-dwallet-pinocchio/devnet-pre-alpha"]
[lib]
crate-type = ["cdylib", "lib"]
ika-dwallet-pinocchiogivesDWalletContext, which makes the CPI into the ika program, andID, the ika program’s address on the network you build for.- The features pick that network. Build for the devnet pre-alpha with
cargo build-sbf --tools-version v1.54 --arch v3 -- --features devnet-pre-alpha. The tests build with no feature. See Build for one network. pinocchio-systemcreates the program’s own accounts.solana-addresswithcurve25519derives PDAs when the program runs in host tests. On chain, the program uses the runtime’s own call for it.
The skeleton
#![allow(unused)]
#![no_std]
fn main() {
extern crate alloc;
use pinocchio::{
AccountView, Address, ProgramResult,
cpi::{Seed, Signer},
entrypoint,
error::ProgramError,
};
use pinocchio_system::instructions::CreateAccount;
use ika_dwallet_pinocchio::{DWalletContext, ID as IKA_PROGRAM_ID};
entrypoint!(process_instruction);
pinocchio::nostd_panic_handler!();
// Replace with your program's id before you deploy.
pub const ID: Address = Address::new_from_array([5u8; 32]);
}
Errors
Each check gets its own error code, so a test can assert the exact one.
#![allow(unused)]
fn main() {
#[repr(u32)]
pub enum VotingError {
DWalletMismatch = 0, // the dWallet passed is not the proposal's
NotAMember = 1, // the signer is not on the council
NotDWalletOwner = 2, // the council's creator is not the dWallet's owner
InvalidCouncil = 3, // the council account is not the dWallet's council
InvalidDWalletAccount = 4, // the account is not a DWallet of the ika program
InvalidQuorum = 5, // the quorum is 0 or above the member count
DuplicateMember = 6,
ProposalClosed = 7,
ProposalMismatch = 8, // the proposal id does not match the account
InvalidVoucherBump = 9, // the voucher bump is not the canonical one
VoucherMismatch = 10, // the voucher account is not the proposal's voucher PDA
InvalidBump = 11, // a bump the client chose is not the canonical one
}
impl From<VotingError> for ProgramError {
fn from(error: VotingError) -> Self {
ProgramError::Custom(error as u32)
}
}
}
The accounts
Every account starts with a two-byte header, a tag and a version, like the ika program’s own.
Council, at ["council", dwallet], 361 bytes, tag 3:
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | dwallet | 32 | The dWallet this council governs |
| 34 | quorum | 4 | Yes votes needed |
| 38 | member_count | 2 | 1 to 10 |
| 40 | bump | 1 | The council’s canonical bump |
| 41 | members | 320 | Ten 32-byte keys. The first member_count are used |
Proposal, at ["proposal", proposal_id], 196 bytes, tag 1:
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | proposal_id | 32 | The proposal’s id |
| 34 | dwallet | 32 | The council’s dWallet |
| 66 | message_digest | 32 | The Keccak-256 of the message to sign |
| 98 | user_pubkey | 32 | The request key that will send the sign request. It becomes the voucher’s signing key |
| 130 | signature_scheme | 2 | The scheme, such as 5 for EdDSA |
| 132 | creator | 32 | The member who proposed |
| 164 | yes_votes | 4 | |
| 168 | no_votes | 4 | |
| 172 | quorum | 4 | Copied from the council |
| 176 | status | 1 | 0 open, 1 approved |
| 177 | signature_voucher_bump | 1 | The bump of ["signature_voucher", proposal_id] |
| 178 | bump | 1 | The proposal’s bump |
| 179 | _reserved | 16 |
VoteRecord, at ["vote", proposal_id, voter], 69 bytes, tag 2:
| Offset | Field | Size |
|---|---|---|
| 2 | voter | 32 |
| 34 | proposal_id | 32 |
| 66 | vote | 1 |
| 67 | bump | 1 |
Dispatch
The first byte of the instruction data names the instruction:
#![allow(unused)]
fn main() {
pub fn process_instruction(
program_id: &Address,
accounts: &mut [AccountView],
data: &[u8],
) -> ProgramResult {
let (discriminator, rest) = data
.split_first()
.ok_or(ProgramError::InvalidInstructionData)?;
match *discriminator {
0 => create_proposal(program_id, accounts, rest),
1 => cast_vote(program_id, accounts, rest),
2 => create_council(program_id, accounts, rest),
_ => Err(ProgramError::InvalidInstructionData),
}
}
}
Reading a dWallet’s owner
create_council must prove that its signer owns the dWallet now. It reads the DWallet account
of the ika program: tag 97 at byte 0, then owner at offset 2. First it proves the account is
really the ika program’s.
#![allow(unused)]
fn main() {
const DWALLET_ACCOUNT_DISCRIMINATOR: u8 = 97;
const DWALLET_OWNER_OFFSET: usize = 2;
fn dwallet_owner(
dwallet: &AccountView,
dwallet_program: &AccountView,
) -> Result<[u8; 32], ProgramError> {
// The dWallet program must be ika's own, the address this program was
// built for: a dWallet account of any other program is anyone's word.
if dwallet_program.address() != &IKA_PROGRAM_ID
|| !dwallet_program.executable()
|| !dwallet.owned_by(&IKA_PROGRAM_ID)
{
return Err(VotingError::InvalidDWalletAccount.into());
}
let data = dwallet.try_borrow()?;
if data.first() != Some(&DWALLET_ACCOUNT_DISCRIMINATOR) {
return Err(VotingError::InvalidDWalletAccount.into());
}
read_key(&data, DWALLET_OWNER_OFFSET).map_err(|_| VotingError::InvalidDWalletAccount.into())
}
}
The owner is compared with IKA_PROGRAM_ID, never with the program account the caller passed. A
caller could otherwise pass a program of its own, with a look-alike account that names the caller
as owner. Your own program can also check the account’s length, 185 bytes.
Rent
The example pays rent with a fixed formula:
#![allow(unused)]
fn main() {
fn minimum_balance(data_len: usize) -> u64 {
(data_len as u64).saturating_add(128).saturating_mul(6960)
}
}
It equals Solana’s rent-exempt minimum at the current rent rate. Reading the Rent sysvar is the
choice that stays right if the rate changes.
Next
Create the council and the proposal.
Create the Council and the Proposal
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
This chapter covers the two instructions that come before any vote. create_council fixes who
governs a dWallet. create_proposal names a message to sign, and the address its voucher will
have.
create_council (2)
The dWallet’s current owner sends it, before giving the dWallet to the program. After the transfer the owner is the program’s CPI authority, which no user can sign for. So the council can never be replaced once the dWallet is handed over.
Data: quorum (u32), member_count (u16, 1 to 10), then member_count keys of 32 bytes.
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | council, ["council", dwallet] | yes | no |
| 1 | dwallet | no | no |
| 2 | dwallet_program, the ika program | no | no |
| 3 | owner, the dWallet’s owner | no | yes |
| 4 | payer | yes | yes |
| 5 | system_program | no | no |
The checks, in the order the program makes them:
#![allow(unused)]
fn main() {
if quorum == 0 || quorum > member_count as u32 {
return Err(VotingError::InvalidQuorum.into());
}
let has_duplicate = members.chunks(32).enumerate().any(|(index, member)| {
members.chunks(32).skip(index).skip(1).any(|other| other == member)
});
if has_duplicate {
return Err(VotingError::DuplicateMember.into());
}
// Only the dWallet's current owner may fix its governance.
if dwallet_owner(dwallet, dwallet_program)? != *owner.address().as_array() {
return Err(VotingError::NotDWalletOwner.into());
}
// The council lives at the canonical bump, so there is exactly one per dWallet.
let dwallet_key = dwallet.address().as_array();
let (expected, bump) =
Address::find_program_address(&[b"council", dwallet_key.as_ref()], program_id);
if council_account.address() != &expected {
return Err(VotingError::InvalidCouncil.into());
}
}
The program then creates the council with CreateAccount, signed with the council’s seeds, and
writes its fields.
Two choices here make the council unique. The address is derived from the dWallet. The bump is the canonical one, found by the program itself, not taken from the caller. With a bump from the caller, a second council could exist at another valid bump.
Checking a council later
Every later instruction takes a council account and must prove it is the right one:
#![allow(unused)]
fn main() {
fn verify_council_member(
program_id: &Address,
council: &AccountView,
dwallet: &[u8; 32],
member: &[u8; 32],
) -> Result<u32, ProgramError> {
if !council.owned_by(program_id) {
return Err(VotingError::InvalidCouncil.into());
}
let data = council.try_borrow()?;
if data.len() < COUNCIL_LEN || data[0] != COUNCIL_DISCRIMINATOR {
return Err(VotingError::InvalidCouncil.into());
}
if data[CN_DWALLET..CN_DWALLET + 32] != *dwallet {
return Err(VotingError::InvalidCouncil.into());
}
let bump = [data[CN_BUMP]];
let expected =
Address::create_program_address(&[b"council", dwallet.as_ref(), &bump], program_id)
.map_err(|_| VotingError::InvalidCouncil)?;
if council.address() != &expected {
return Err(VotingError::InvalidCouncil.into());
}
let member_count = read_u16(&data, CN_MEMBER_COUNT)? as usize;
let is_member = data[CN_MEMBERS..]
.chunks(32)
.take(member_count)
.any(|candidate| candidate == member);
if !is_member {
return Err(VotingError::NotAMember.into());
}
read_u32(&data, CN_QUORUM)
}
}
It checks four things: the program owns the account, the tag is the council’s, the council names this dWallet, and the address is the council PDA of this dWallet. An account with council-like data at any other address fails. Then it checks membership, and returns the quorum.
create_proposal (0)
A council member sends it.
Data, 100 bytes:
| Field | Size | Meaning |
|---|---|---|
proposal_id | 32 | The proposal’s id, chosen by the client |
message_digest | 32 | The Keccak-256 of the message to sign |
user_pubkey | 32 | The request key that will send the sign request |
signature_scheme | 2 | The scheme the sign request will use |
signature_voucher_bump | 1 | The canonical bump of ["signature_voucher", proposal_id] |
bump | 1 | The proposal’s canonical bump |
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | proposal, ["proposal", proposal_id] | yes | no |
| 1 | council | no | no |
| 2 | dwallet, the council’s dWallet | no | no |
| 3 | creator, a council member | no | yes |
| 4 | payer | yes | yes |
| 5 | system_program | no | no |
The proposal takes its quorum from the council, never from the caller:
#![allow(unused)]
fn main() {
let dwallet_key = dwallet.address().as_array();
let quorum = verify_council_member(program_id, council, dwallet_key, creator.address().as_array())?;
}
It accepts only the canonical voucher bump:
#![allow(unused)]
fn main() {
let (_, canonical_voucher_bump) =
Address::find_program_address(&[b"signature_voucher", proposal_id.as_ref()], program_id);
if signature_voucher_bump != canonical_voucher_bump {
return Err(VotingError::InvalidVoucherBump.into());
}
}
Another valid bump would put the voucher at an address no client computes. The proposal would pass and issue its voucher where nobody looks for it, and no signature would ever be asked for.
It accepts only the canonical proposal bump too, so one proposal id has one proposal account:
#![allow(unused)]
fn main() {
let bump = data[99];
require_canonical_bump(&[b"proposal", proposal_id.as_ref()], bump, program_id)?;
}
require_canonical_bump refuses any other bump with InvalidBump. The next chapter shows it.
The program then creates the proposal and writes its fields, with status 0, open.
Where the voucher will be
The voucher’s address is known as soon as the proposal exists: the program’s PDA
["signature_voucher", proposal_id]. The ika program does not choose it. It accepts any new
address that signs the voucher’s creation, and the voting program signs for its own PDA. So a
client can name the voucher in a sign request without searching for it.
user_pubkey becomes the voucher’s signing key. The network serves a sign request for the
voucher only when it is signed by that key. That key needs its own
gas deposit.
Next
Cast votes and issue the voucher.
Cast Votes and Issue the Voucher
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
cast_vote records one member’s vote. The vote that brings the yes votes to the quorum also issues
the signature voucher, through a CPI into the ika program.
cast_vote (1)
Data, 35 bytes: proposal_id (32), vote (1: 1 yes, 0 no), vote_record_bump (1),
cpi_authority_bump (1).
Every vote takes six accounts:
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | proposal | yes | no |
| 1 | vote_record, ["vote", proposal_id, voter] | yes | no |
| 2 | council, of the proposal’s dWallet | no | no |
| 3 | voter, a council member | no | yes |
| 4 | payer | yes | yes |
| 5 | system_program | no | no |
The vote that reaches the quorum takes six more, for the CPI:
| # | Account | Writable | Signer |
|---|---|---|---|
| 6 | coordinator, the ika program’s DWalletCoordinator | no | no |
| 7 | signature_voucher, ["signature_voucher", proposal_id] | yes | no |
| 8 | dwallet, the proposal’s dWallet | no | no |
| 9 | caller_program, this program | no | no |
| 10 | cpi_authority, this program’s CPI authority | no | no |
| 11 | dwallet_program, the ika program | no | no |
The client decides whether to add them. It reads the proposal first: when yes_votes + 1 reaches
quorum and the vote is yes, it adds the six.
Recording the vote
The program checks that the proposal is open and is the one named, then checks the voter against the proposal’s council:
#![allow(unused)]
fn main() {
let proposal_dwallet = {
let prop_data = proposal_account.try_borrow()?;
if prop_data.len() < PROPOSAL_LEN || prop_data[0] != PROPOSAL_DISCRIMINATOR {
return Err(ProgramError::InvalidAccountData);
}
if prop_data[PROP_STATUS] != STATUS_OPEN {
return Err(VotingError::ProposalClosed.into());
}
if prop_data[PROP_PROPOSAL_ID..PROP_PROPOSAL_ID + 32] != proposal_id {
return Err(VotingError::ProposalMismatch.into());
}
read_key(&prop_data, PROP_DWALLET)?
};
verify_council_member(program_id, council, &proposal_dwallet, voter.address().as_array())?;
}
It then creates the vote record with CreateAccount, signed with the seeds
["vote", proposal_id, voter, vote_record_bump], and adds one to the yes or the no count.
Make the vote record unique
The vote record is what stops a member voting twice: creating it a second time fails, because the
account exists. That holds only if the record has one possible address. A seed list has many valid
bumps, and each bump gives another address. So the program must accept only the canonical bump, the
one find_program_address returns. Otherwise a member who passes a second valid bump creates a
second record, and votes twice.
The example checks the bump the client passes before it creates the record:
#![allow(unused)]
fn main() {
fn require_canonical_bump(
seeds: &[&[u8]],
bump: u8,
program_id: &Address,
) -> Result<(), ProgramError> {
let (_, canonical) = Address::find_program_address(seeds, program_id);
if bump != canonical {
return Err(VotingError::InvalidBump.into());
}
Ok(())
}
require_canonical_bump(
&[b"vote", proposal_id.as_ref(), voter.address().as_array().as_ref()],
vote_record_bump,
program_id,
)?;
}
The proposal gets the same check, with its seeds ["proposal", proposal_id]. The Anchor version
needs no such code: seeds with bump makes Anchor derive the canonical bump and refuse any other.
The rule holds for any account whose existence means “done once”. See
invariant 6.
Issuing the voucher
When the yes votes reach the quorum, the program reads the six extra accounts and checks two of them itself, before the CPI:
#![allow(unused)]
fn main() {
if yes_votes >= quorum {
let [coordinator, signature_voucher, dwallet, caller_program, cpi_authority, dwallet_program, ..] =
&*tail
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
// The CPI must target the dWallet this proposal was created for.
if dwallet.address().as_array() != &proposal_dwallet {
return Err(VotingError::DWalletMismatch.into());
}
// The voucher must be this program's PDA for the proposal.
let expected_voucher = Address::create_program_address(
&[b"signature_voucher", proposal_id.as_ref(), &[signature_voucher_bump]],
program_id,
)
.map_err(|_| VotingError::VoucherMismatch)?;
if signature_voucher.address() != &expected_voucher {
return Err(VotingError::VoucherMismatch.into());
}
}
The dWallet check is the one the whole design rests on. The ika program accepts a voucher for any dWallet this program owns. Only this check makes it the proposal’s dWallet.
The voucher check is needed because the ika program accepts any new address that signed. A keypair that signed the outer transaction is still a signer inside the CPI. Without the check, the caller could pass such a keypair, and the voucher would be created where no client looks for it.
Then the CPI:
#![allow(unused)]
fn main() {
let ctx = DWalletContext { dwallet_program, cpi_authority, caller_program, cpi_authority_bump };
let voucher_bump_byte = [signature_voucher_bump];
let voucher_seeds = [
Seed::from(b"signature_voucher" as &[u8]),
Seed::from(proposal_id.as_ref()),
Seed::from(voucher_bump_byte.as_ref()),
];
ctx.issue_signature_voucher(
coordinator,
signature_voucher,
dwallet,
payer,
system_program,
message_digest,
[0u8; 32], // no message metadata
signature_scheme,
None, // the voucher's owner: this program's CPI authority
Some(user_pubkey), // the voucher's signing key
Some(&voucher_seeds),
)?;
let mut prop_data = proposal_account.try_borrow_mut()?;
prop_data[PROP_STATUS] = STATUS_APPROVED;
}
}
The helper first checks that dwallet_program is the ika program, ID of the crate. Any other
account is refused with IncorrectProgramId, so the CPI authority’s signature never reaches a
program that only claims to be ika’s. It then signs for two addresses with invoke_signed: the CPI authority, with
["__ika_cpi_authority", bump], and the voucher, with the seeds passed. The ika program then
checks:
- this program’s account is executable;
- the CPI authority is this program’s, and it signed;
- the CPI authority is the dWallet’s owner;
- the dWallet is Active and the coordinator is not paused;
- the voucher’s address signed, holds nothing, and belongs to the system program.
It creates the voucher, pending, with the proposal’s digest and scheme, owned by this program’s CPI
authority, with user_pubkey as its signing key.
If any check fails, the whole transaction fails. The vote record and the count are undone with it, so the deciding vote can be sent again later, for example after a pause.
Next
Read and verify the signature.
Read and Verify the Signature
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
Once the voucher exists, the proposal’s signer asks the network to sign. The network answers with the signature, and also writes it into the voucher. Anyone can then read it from Solana.
Asking for the signature
The signer is the key named as the proposal’s user_pubkey. It must have a
gas deposit. It takes a presign, then sends a sign request that
names the voucher’s address. In TypeScript, with the SDK in mock mode for the pre-alpha:
const presign = await ikaClient.requestGlobalPresign({
curve,
signatureAlgorithm: SignatureAlgorithm.EdDSA,
userShareEncryptionKeys,
});
const signature = await ikaClient.requestSign({
dWallet,
presign,
signatureVoucherId: signatureVoucher, // ["signature_voucher", proposal_id] of the voting program
message,
signatureAlgorithm: SignatureAlgorithm.EdDSA,
hashScheme: Hash.SHA512,
userShareEncryptionKeys,
});
requestSign returns the signature once it verifies under the dWallet’s public key. See the SDK
pages for the client’s setup.
Reading it from the voucher
A reader that did not send the request reads the voucher. In TypeScript, waitForSignature reads
it until the signature is there, and returns it only once it verifies:
const signature = await ikaClient.waitForSignature({
signatureVoucher,
dWallet,
message,
signatureAlgorithm: SignatureAlgorithm.EdDSA,
hashScheme: Hash.SHA512,
});
It throws when the voucher ends without a signature, at status 2.
From Rust, read the account and the fields yourself:
#![allow(unused)]
fn main() {
const STATUS: usize = 173;
const SIGNATURE_LEN: usize = 174;
const SIGNATURE: usize = 176;
fn signature_of(data: &[u8]) -> Option<Vec<u8>> {
if data.len() != 304 || data[0] != 108 {
return None; // not a SignatureVoucher
}
match data[STATUS] {
1 => {
let len = u16::from_le_bytes([data[SIGNATURE_LEN], data[SIGNATURE_LEN + 1]]) as usize;
Some(data[SIGNATURE..SIGNATURE + len].to_vec())
}
_ => None,
}
}
}
Read again while the status is 0, pending, or 3, revoked: a sign agreed before a revoke can still be written. Stop at status 2, which means no signature will come. Check the account’s owner is the ika program before you trust its bytes.
Verifying it
The bytes in the voucher are not checked by the ika program. Verify them under the dWallet’s public key before you use them.
An EdDSA signature, for a Curve25519 dWallet, is 64 bytes:
#![allow(unused)]
fn main() {
use ed25519_dalek::{Signature, VerifyingKey};
let key = VerifyingKey::from_bytes(&dwallet_public_key)?;
key.verify_strict(&message, &Signature::from_bytes(&signature.try_into()?))?;
}
An ECDSA signature is 65 bytes: a recovery byte, then r and s. Drop the first byte for a library
that takes 64. For secp256k1 with SHA-256:
#![allow(unused)]
fn main() {
use k256::ecdsa::{Signature, VerifyingKey, signature::hazmat::PrehashVerifier};
use sha2::{Digest, Sha256};
let key = VerifyingKey::from_sec1_bytes(&dwallet_public_key)?;
let digest = Sha256::digest(&message);
key.verify_prehash(&digest, &Signature::from_slice(&signature[1..])?)?;
}
The hash is the one the scheme names, not the Keccak-256 the voucher stores. The voucher’s digest only names the message.
The whole run
1. Create a dWallet the user's wallet owns it
2. create_council (quorum 3) council at ["council", dwallet]
3. TransferOwnership to the CPI authority dWallet.owner = the program's CPI authority
4. create_proposal proposal open, quorum 3
5. cast_vote, member 1, yes yes_votes = 1
6. cast_vote, member 2, yes yes_votes = 2
7. cast_vote, member 3, yes the voucher is created, pending; the proposal is approved
8. presign and sign request the network signs
9. the network's CommitSignature the voucher is signed, status 1
Next
Test the Program
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The voting example is tested at three levels. Each catches what the one before cannot.
| Level | Tool | What runs | What it proves |
|---|---|---|---|
| One instruction | Mollusk | your program alone | Every check and every error code |
| The CPI | LiteSVM | your program and the real ika program | The vote at the quorum creates the right voucher |
| The whole run | the SDK, against the pre-alpha or a local mock | Solana and an ika network | The network signs, and the signature is written into the voucher |
Mollusk: one instruction at a time
examples/voting/pinocchio/tests/mollusk.rs builds each account by hand, runs one instruction,
and checks the result. A negative test asserts the exact error code:
#![allow(unused)]
fn main() {
#[test]
fn test_create_proposal_rejects_non_member() {
// A council around a dWallet, and a creator who is not on it.
// ...
let result = mollusk.process_instruction(&ix, &accounts);
assert_custom_error(&result, ERR_NOT_A_MEMBER);
}
}
A test that only asserts failure also passes when the instruction fails for another reason, such as a wrong system program. Then the membership check could be gone and the test would not notice.
The dWallet is an account the test writes: 185 bytes, tag 97, owner at offset 2, owned by
ika_dwallet_pinocchio::ID, which a test build sets to the development address. See Mollusk Tests for the
helpers and the full list of tests.
LiteSVM: the CPI into the real ika program
examples/voting/pinocchio/tests/litesvm.rs loads the built ika program and the voting program into
one runtime. DWalletTestContext writes a coordinator, a network key and a dWallet into it. The
test then runs the real instructions: the council, the real TransferOwnership, the proposal, and
three votes.
After the third vote it reads the voucher at ["signature_voucher", proposal_id]:
- it exists, with tag 108;
- it names the proposal’s dWallet and digest;
- its owner is the voting program’s CPI authority;
- its status is 0, pending.
These tests check the attacks the program exists to stop:
test_outsider_cannot_vote_or_recreate_council: a key that is not a member cannot vote, and cannot create a second council for the dWallet.test_quorum_cannot_be_redirected_to_another_councils_dwallet: a council that reaches its quorum cannot pass another council’s dWallet to the CPI.test_a_member_cannot_vote_twice_with_a_second_bump: a second vote record at another valid bump is refused withInvalidBump.test_create_proposal_refuses_a_non_canonical_proposal_bump: one proposal id has one proposal.test_dwallet_context_refuses_a_program_that_is_not_ika: a fake ika program passed for the CPI is refused withIncorrectProgramId, so it never receives the CPI authority’s signature.
See LiteSVM Tests.
Prove the tests matter
A test of a security check is worth something only if it fails when the check is gone. Try it once for each check that matters:
- Remove the check from the program, for example the
DWalletMismatchcomparison incast_vote. - Build and run the test that guards it.
- Confirm that the test fails, and that the attack now succeeds.
- Put the check back.
Running the tests
From the repository root, with no network feature, since the tests load the ika program from bin/
at its development address:
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/voting/pinocchio/Cargo.toml
cargo test -p ika-example-voting-pinocchio
The whole run
The end-to-end demo in examples/voting/e2e runs the full path against the devnet pre-alpha: the dWallet, the council, the votes, the voucher, the presign and the
signature. See End-to-End Tests and
Examples for how to run it.
dWallet Accounts
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
A dWallet is a signing key on some chain, held jointly by its user and the ika network. On
Solana each dWallet has one account in the ika program, of type DWallet. The account records
the dWallet’s public key, its curve, its state, and its owner. The owner is whoever may ask the
network to sign with the dWallet.
Nobody creates a DWallet account directly. A user asks the network for a new dWallet over
gRPC, and the network writes the account to Solana with its own transaction. On the devnet
pre-alpha the mock network writes it.
What the account holds
| Offset | Field | Meaning |
|---|---|---|
| 2 | owner | Who controls the dWallet: a wallet, or a program’s CPI authority |
| 34 | curve | The curve, as a u16 |
| 36 | state | 1 when Active. 3 while it waits for its holder to accept an encrypted share |
| 37 | public_key_len | The public key’s length |
| 38 | public_key | The public key, padded to 65 bytes |
| 103 | created_epoch | The epoch it was created in |
| 111 | noa_public_key | The network key that holds the network’s share |
| 143 | is_imported | 1 when the user imported an existing key |
| 153 | session_identifier | For an imported dWallet, the import request’s session |
The account is 185 bytes, tag 97. The full table is in the Account Reference.
The owner decides everything that matters. Only the owner can issue a voucher for the dWallet, and only the owner can give the dWallet to someone else. A program becomes a dWallet’s owner when the dWallet is given to the program’s CPI authority, an address derived from the program. See The CPI Framework.
Curves
| Curve | Number | Public key | Schemes it signs with |
|---|---|---|---|
| secp256k1 | 0 | 33 bytes, compressed | ECDSA with Keccak-256 (0), SHA-256 (1), double SHA-256 (2) or BLAKE2b-256 (4); Taproot (3) |
| secp256r1 | 1 | 33 bytes, compressed | ECDSA with SHA-256 (1) |
| Curve25519 | 2 | 32 bytes | EdDSA with SHA-512 (5) |
| Ristretto | 3 | 32 bytes | Schnorrkel (6) |
The numbers in brackets are signature scheme numbers. A voucher records one, and a sign request names the same one. A scheme that does not sign on the dWallet’s curve is refused by the network.
The address
The dWallet’s address is derived from its curve and its public key. Write the curve as two little-endian bytes, append the public key, and split the result into chunks of 32 bytes. These chunks are the root.
- A generated dWallet is at
["dwallet", "record", root...]. - An imported dWallet is at
["dwallet", "imported_record", root..., session_identifier].
So a client finds a generated dWallet from its public key alone. In TypeScript,
dwalletPda(programId, curve, publicKey) from @ika.xyz/pre-alpha-solana derives it, and
readDWallet(data) reads the account.
How a dWallet is created
A dWallet comes from a key generation between the user and the network. The user computes its half of the key, and the network computes the other half. The user keeps a secret share. The network keeps its own share, which no single party holds.
The user’s share is kept in one of two ways:
- Encrypted. The share is encrypted to an encryption key of the user’s, and the network stores only the encrypted copy. The network cannot sign without the user’s help. This is the zero-trust form.
- Public. The user reveals its share to the network. The network can then sign alone. This form trusts the network.
The steps for an encrypted share:
- The user registers its encryption key on chain for the curve, with
RegisterEncryptionKey. It does this once per curve. - The user sends a key generation request (
Dkg) over gRPC, with its half of the key and its encrypted share. - The network runs its half and answers with an attestation: a record of the new dWallet that the network signed.
- The network writes the dWallet to Solana with
CommitDWallet, and the encrypted share withCommitEncryptedUserSecretKeyShare, in one transaction. The dWallet’s state is 3: it waits for its holder. - The holder checks the share and accepts it on chain with
AcceptEncryptedUserShare. The dWallet becomes Active.
With a public share, step 1 and step 5 do not happen. The network writes the dWallet Active and then writes the public share.
The details of steps 1, 4 and 5 are in Encrypted Shares. The SDKs do all five steps in one call. On the devnet pre-alpha the SDK must run in mock mode, and the mock makes the dWallet’s key itself.
Who the owner is at creation
The network sets the owner to the request’s intended_chain_sender: the 32-byte Solana address
the user named in its signed request. The SDKs put the user’s wallet there. The program refuses
an all-zero owner, and the mock refuses a request that names one.
Changing the owner
TransferOwnership gives the dWallet to a new owner. The current owner signs it, either as a
wallet or as a program through its CPI authority. The dWallet must be Active. The new owner
must not be all zeros.
To give a dWallet to a program, transfer it to the program’s CPI authority:
#![allow(unused)]
fn main() {
let (cpi_authority, _bump) =
Pubkey::find_program_address(&[b"__ika_cpi_authority"], &your_program_id);
}
After the transfer, only that program can issue vouchers for the dWallet or move it again. Decide before the transfer who inside your program may ask for a signature. After the transfer the user no longer signs for the dWallet, so it cannot set that up any more. See Integrator Invariants.
A voucher issued before a transfer stays valid after it. It belongs to the voucher’s owner, not to the dWallet’s.
Reading a dWallet from a program
A program that reads a DWallet account must check that it is real before it reads owner:
- The account is owned by the ika program. Compare the account’s owner with
IDof the CPI crate, the ika program of the network you built for. Never compare it with a program account the caller passed. - Byte 0 is 97.
- The account is 185 bytes long.
Then read owner at offset 2 and state at offset 36.
Signature Vouchers
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
A signature voucher is the on-chain permission for one signature. It names a dWallet, the digest of one message, and a signature scheme. The network signs that message once with that dWallet, and only when a voucher allows it. It then writes the signature into the voucher, where anyone can read it.
A voucher is a SignatureVoucher account of the ika program. The dWallet’s owner creates it with
IssueSignatureVoucher, either directly or from a program through a CPI.
One voucher allows one signature. To sign the same message twice, issue two vouchers.
The flow
- The dWallet’s owner issues a voucher at a new address. The voucher is pending.
- The user sends a sign request over gRPC. The request names the voucher’s address, and it is signed by the voucher’s signing key.
- Each validator reads the voucher at that address on Solana and checks that it matches the request. The request runs once enough validators agree on what they read.
- The network answers the request with the signature.
- The network writes the same signature into the voucher with
CommitSignature. The voucher’s status becomes 1, signed.
The sign request carries no copy of the voucher. The validators trust only what they read from Solana themselves. On the devnet pre-alpha, the mock reads the voucher instead, and then signs.
What the voucher holds
| Offset | Field | Meaning |
|---|---|---|
| 2 | dwallet | The dWallet’s address |
| 34 | message_digest | The Keccak-256 of the message |
| 66 | message_metadata_digest | The Keccak-256 of the metadata, or 32 zeros for none |
| 98 | owner | Who controls the voucher |
| 130 | signature_scheme | The signature scheme, as a u16 |
| 132 | has_signing_key | 1 when signing_key is set |
| 133 | signing_key | The Ed25519 key a sign request must be signed by |
| 165 | issued_epoch | The epoch it was issued in |
| 173 | status | 0 pending, 1 signed, 2 closed by a charge, 3 revoked |
| 174 | signature_len | The signature’s length. 0 until signed |
| 176 | signature | The signature, padded to 128 bytes |
The account is 304 bytes, tag 108.
has_signing_key exists because no key value can mean “no key”. An all-zero Ed25519 key is
still a key.
The message digest
message_digest is the Keccak-256 of the message to sign. It is always Keccak-256, whatever
the signature scheme hashes the message with. The network computes the same digest from the
message in the sign request, and compares the two.
import { approvalMessageDigests } from '@ika.xyz/pre-alpha-solana';
const { messageDigest, messageMetadataDigest } = approvalMessageDigests(message);
#![allow(unused)]
fn main() {
let message_digest = solana_keccak_hasher::hash(message).to_bytes();
}
Most schemes have no metadata. Then message_metadata_digest is 32 zeros, not the hash of an
empty input. ECDSA with BLAKE2b-256 and Schnorrkel carry metadata.
Where a voucher lives
A voucher has no derived address. The issuer picks a new address, and that address must sign the transaction that creates the voucher. Two choices work:
- A wallet that owns its dWallet makes a new keypair. The keypair signs the transaction, and the voucher is created at its address.
- A program uses a PDA of its own, and signs for it with
invoke_signed. Derive the PDA from the record that asked for the signature, such as["signature_voucher", proposal_id]. Then the program and the client both know the address before the voucher exists.
The address must hold nothing when the voucher is created. Keep it: the sign request names it.
Issuing a voucher
The issuer must be the dWallet’s owner. The dWallet must be Active, and the coordinator must not be paused. See the full layout of IssueSignatureVoucher.
The issuer can set two things at issue time:
- The owner. Who controls the voucher afterwards. Without one, the owner is the issuer: the wallet, or the program’s CPI authority.
- The signing key. The Ed25519 key whose signed sign request the voucher accepts. Without one, the voucher waits until its owner sets a key.
The signing key is the user’s request key: the key that signs gRPC requests and pays for them from its gas deposit. A program that issues a voucher for a user names that user’s request key here.
From a Pinocchio program:
#![allow(unused)]
fn main() {
ctx.issue_signature_voucher(
coordinator, // the DWalletCoordinator
signature_voucher, // the new voucher's address
dwallet, // the dWallet
payer, // pays the voucher's rent
system_program,
message_digest, // Keccak-256 of the message
[0u8; 32], // no metadata
5, // EdDSA with SHA-512, for a Curve25519 dWallet
None, // owner: this program's CPI authority
Some(user_request_key), // the key the sign request must be signed by
Some(&voucher_seeds), // the voucher PDA's seeds, bump included
)?;
}
See The CPI Framework for the context ctx and the other frameworks.
The owner’s controls
After issue, only the voucher’s owner can change it. The dWallet’s owner has no say over a voucher it did not keep.
| Instruction | What it does | When |
|---|---|---|
SetVoucherSigningKey | Sets or replaces the signing key | While pending |
RevokeSignatureVoucher | Revokes the voucher for good | While pending |
TransferSignatureVoucher | Gives the voucher to a new owner | Always |
None of the three checks the pause.
The statuses
| Status | Name | What it means |
|---|---|---|
| 0 | Pending | Waiting for a sign request |
| 1 | Signed | The signature is stored |
| 2 | Closed by a charge | The network charged for the signature and gave up delivering it. No signature will come |
| 3 | Revoked | The owner revoked it. No new sign request is served |
A revoke stops new requests, not work already agreed. When enough validators agreed on a sign before the revoke was written, that sign still runs. The network then writes its signature into the revoked voucher, which becomes Signed.
A voucher that is already signed keeps its first signature. A second write is accepted and changes nothing.
What the network checks
On the real network, a sign request is served only when the voucher:
- exists, is owned by the ika program and is a
SignatureVoucher; - is pending;
- names the dWallet of the request;
- holds the digests of the request’s message and metadata;
- holds the request’s signature scheme;
- has a signing key, equal to the key that signed the request.
A request whose voucher is missing, or has no key yet, or has another key, waits. The voucher can still appear, or its key can still be set. A request whose voucher is signed, revoked, closed, or for another dWallet, message or scheme is refused.
The mock network checks the same values. It differs in one way: it signs for a voucher that has no signing key, where the real network waits for the key.
Reading the signature
Read the account and look at status:
#![allow(unused)]
fn main() {
let data = rpc.get_account_data(&signature_voucher)?;
match data[173] {
1 => {
let len = u16::from_le_bytes([data[174], data[175]]) as usize;
let signature = &data[176..176 + len];
// use the signature
}
0 | 3 => { /* not signed yet: read again later */ }
_ => { /* 2: no signature will come */ }
}
}
Keep reading a revoked voucher, because a sign agreed before the revoke can still be written. Stop at status 2.
The stored signature is the same bytes the gRPC answer carried. An ECDSA signature is 65 bytes:
a recovery byte, then r and s. Taproot, EdDSA and Schnorrkel signatures are 64 bytes.
Nothing in the account proves the signature is correct. Verify it under the dWallet’s public key
before you use it. In TypeScript, readSignatureVoucherVerified from @ika.xyz/pre-alpha-solana reads
the voucher and verifies its signature.
Checks for a program that reads a voucher
A program that acts on a voucher should check:
- the account is the ika program’s, with tag 108 and 304 bytes;
dwalletis the dWallet you expect;owneris the owner you expect, usually your own CPI authority;message_digestis the digest you expect.
A voucher with the right digest for another dWallet is not yours.
Future Signature Vouchers
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
A future sign splits one signature into two steps that can happen at different times. In step 1 the user does its half of the signature now, and the network checks it and keeps the result. In step 2 the network completes the signature, later, when the owner allows it. The user does not need to be online for step 2.
This suits a program that collects the user’s consent first and decides later. For example, a user signs an order now, and the program releases it when a price is reached.
A FutureSignatureVoucher is the on-chain permission for one future sign. It works like a
signature voucher, with one more state between pending and signed.
The flow
- The dWallet’s owner issues a future voucher with
IssueFutureSignatureVoucher. Its signing key is the key step 1 must be signed by. - The user sends step 1 over gRPC (
FutureSign). It names the voucher, a presign, the message, and the user’s half of the signature. - The network checks the user’s half. It writes the checked result into the voucher with
CommitPartialUserSignature, and answers with the same result. The write clears the voucher’s signing key. - The voucher’s owner sets the key for step 2 with
SetVoucherSigningKey. - Anyone holding that key sends step 2 over gRPC (
SignWithPartialUserSig, orImportedKeySignWithPartialUserSigfor an imported dWallet). It carries step 1’s result and the message. - The network completes the signature, answers with it, and writes it into the voucher with
CommitSignature.
Step 3 clears the key on purpose. The key that made step 1 cannot finish the signature unless the owner names it again. So the owner, often a program, decides when step 2 may happen and who sends it.
What the voucher holds
The fields up to offset 172 are those of a SignatureVoucher, at the same offsets. Then:
| Offset | Field | Meaning |
|---|---|---|
| 173 | status | 0 open, 1 partially signed, 2 signed, 3 closed by a charge, 4 revoked |
| 174 | attestation_proof | The network’s signature over step 1’s result |
| 272 | has_partial_signature | 1 once step 1 wrote its result |
| 273 | attestation_len | The length of step 1’s result |
| 275 | attestation | Step 1’s result, up to 1536 bytes |
| 1811 | signature_len | The signature’s length. 0 until signed |
| 1813 | signature | The signature, padded to 128 bytes |
The account is 1941 bytes, tag 109. The issuer pays rent for all of it at issue time, so step 1 adds no rent.
The statuses
| Status | Name | Next |
|---|---|---|
| 0 | Open | Step 1 makes it partially signed |
| 1 | Partially signed | Step 2 makes it signed |
| 2 | Signed | Final |
| 3 | Closed by a charge | Final. The network charged for work it gave up delivering |
| 4 | Revoked | Final for new requests |
The owner can set the signing key, or revoke the voucher, while it is open or partially signed. A revoke stops new requests. A step that enough validators agreed before the revoke is still written: a revoked voucher can still take step 1’s result, and then its signature. It stays revoked while it holds step 1’s result.
Step 1’s write never fails because of what the voucher holds. A voucher that already holds step
1’s result, or a signature, keeps it, and the second write changes nothing. Only a voucher closed
by a charge refuses the write (FutureVoucherNotOpenForStep, 4062).
The presign and the epoch
Step 1 uses a presign: the network’s half of a signature, made in advance. The presign must be one of the current epoch, served to the same request key, and not used before. A presign expires with its epoch.
Step 2 uses no presign. Step 1’s result already holds what the presign gave. So step 2 can run in any later epoch.
Issuing from a program
The CPI helper takes the same arguments as issue_signature_voucher:
#![allow(unused)]
fn main() {
ctx.issue_future_signature_voucher(
coordinator,
future_signature_voucher, // the new voucher's address
dwallet,
payer,
system_program,
message_digest,
[0u8; 32],
signature_scheme,
None, // owner: this program's CPI authority
Some(user_request_key), // the key step 1 must be signed by
Some(&voucher_seeds),
)?;
}
After step 1, the program sets the key for step 2 when its own condition is met:
#![allow(unused)]
fn main() {
ctx.set_voucher_signing_key(future_signature_voucher, completion_key)?;
}
The multisig example uses a future voucher. See examples/multisig/.
Encrypted Shares
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
A zero-trust dWallet keeps the user’s secret share encrypted on chain. Only the holder of the matching decryption key can read it. The network stores the encrypted copy and cannot use it. This page explains the three accounts involved and the two instructions a user sends.
The three accounts
EncryptionKey: a holder’s public encryption key for one curve, at["encryption_key", holder, curve_le]. The holder is an Ed25519 key, which signed the registration.EncryptedUserSecretKeyShare: one holder’s encrypted share of one dWallet, at["dwallet", "encrypted_user_share", root..., holder].DWalletAttestationof the share: the network’s signed record of the share, at["dwallet", "encrypted_share_attestation", root..., holder].
root is the dWallet’s root of 32-byte chunks. See
The dWallet’s address.
Step 1: register the encryption key
Before the network encrypts a share to a holder, the holder registers its encryption key on chain. The network serves a request only when the holder’s registered key is exactly the key the request names. A request for a holder with no registered key waits for about a minute, then is refused.
The holder signs the registration message with its Ed25519 key. The message names this chain’s
number, the deployment’s network, the curve and the encryption key, so a registration signed for
one chain or curve cannot be used for another. Anyone may then send the registration and pay for
it: an Ed25519 precompile instruction with the holder’s signature, followed by
RegisterEncryptionKey. The program reads the key from the signed message.
One key exists per holder and curve, and it never changes. To use another key, a holder registers it under another Ed25519 key, which is then another holder.
In TypeScript, registerEncryptionKeyInstructions from @ika.xyz/pre-alpha-solana/instructions builds
the two instructions. The SDKs register the key for you when they create a dWallet.
Step 2: the network stores the share
When the network creates a dWallet with an encrypted share, it writes the dWallet and the share in one transaction. The dWallet’s state is 3, waiting for its holder. The share is not accepted. Until a share is accepted, the dWallet cannot be used: the program issues it no voucher, and the network starts no sign on it.
The share account stores the digest the holder must sign to accept it
(acceptance_digest, offset 182):
- for a dWallet’s first share, the Keccak-256 of the dWallet attestation’s bytes;
- for a re-encrypted share, the Keccak-256 of the share attestation’s bytes.
Step 3: the holder accepts
The holder checks the share before it accepts:
- Read the share’s attestation account. Check that the network’s signature in it verifies under a network key you trust.
- Check that the stored encrypted share hashes to the share hash the attestation names.
Then the holder signs acceptance_digest with its Ed25519 key. Anyone sends an Ed25519
precompile instruction with that signature, followed by AcceptEncryptedUserShare. The program
checks that the signature is the holder’s, over the stored digest. It then marks the share
accepted, and moves the dWallet from waiting to Active.
acceptEncryptedUserShareInstructions from @ika.xyz/pre-alpha-solana/instructions builds the two
instructions. The SDKs do these checks and the accept for you.
The accept is refused while the coordinator is paused. The network charges no fee for it.
Re-encrypting a share to another holder
The holder of a share can give a copy to another holder. The second holder registers its own
encryption key first. Then the first holder asks the network to re-encrypt (ReEncryptShare).
The network writes the new share, with its own attestation, at the second holder’s address. The
second holder checks and accepts it the same way.
A re-encrypted share can be accepted only when the dWallet is already Active.
Making the share public
The holder can reveal its share to the network (MakeSharePublic). The network writes the public
share into the dWallet’s public-share attestation, ["dwallet", "public_user_share", root...].
From then on, the network can sign with the dWallet without the user’s help. This cannot be
undone. The network starts a reveal only for an Active dWallet.
On the devnet pre-alpha
The mock network holds an ordinary key for every dWallet. It does not use the encrypted share to sign. The accounts, the instructions and the accept work as on the real network, so the flow an app writes is the same.
The CPI Framework
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
A Solana program controls a dWallet by being its owner. It then calls the ika program through a cross-program invocation (CPI) to issue vouchers and to move the dWallet. Three crates build these calls, one for each common way to write a program:
| Crate | Framework | Account type it takes |
|---|---|---|
ika-dwallet-pinocchio | Pinocchio | &AccountView |
ika-dwallet-native | solana-program | &AccountInfo<'info> |
ika-dwallet-anchor | Anchor | AccountInfo<'info> |
The three send the same instruction bytes and the same accounts. Only the account types differ. The pages for each framework show the dependencies and a full example: Pinocchio, Native, Anchor.
The CPI authority
The ika program cannot see which program called it. It sees only which accounts signed. So each
program has one address that it alone can sign for: its CPI authority. It is the PDA of the seed
__ika_cpi_authority under the program’s id.
#![allow(unused)]
fn main() {
use ika_dwallet_pinocchio::CPI_AUTHORITY_SEED; // b"__ika_cpi_authority"
let (cpi_authority, bump) =
pinocchio::Address::find_program_address(&[CPI_AUTHORITY_SEED], program_id);
}
A dWallet whose owner is this address belongs to the program. When the program calls the ika
program, it signs for its CPI authority with invoke_signed. The ika program then checks three
things:
- The calling program’s account is executable.
- The CPI authority is the PDA of
__ika_cpi_authorityunder that program, and it signed. - The CPI authority equals the dWallet’s owner. For a voucher control, it must equal the voucher’s owner instead.
That is all the ika program checks. Your program has one CPI authority for every dWallet it holds. So the ika program cannot tell which of your users, proposals or vaults a call is for. Your program must make that check itself. See Integrator Invariants.
DWalletContext
Each crate provides a DWalletContext. It holds the four values every call needs:
#![allow(unused)]
fn main() {
use ika_dwallet_pinocchio::DWalletContext;
let ctx = DWalletContext {
dwallet_program, // the ika program's account
cpi_authority, // your program's CPI authority account
caller_program, // your program's own account. It must be executable
cpi_authority_bump, // the CPI authority's bump
};
}
Pass a bump that is wrong and the signature for the CPI authority fails, so the call fails.
The context calls only the real ika program
Each crate exports ID, the address of the ika program on the network the crate was built for.
Every call of DWalletContext first compares dwallet_program with ID. Any other account is
refused with ProgramError::IncorrectProgramId, and nothing is called.
The check exists because of how Solana passes signatures on. Every call the context makes is
signed by your program’s CPI authority. A program that receives a signed account can pass that
signature on in the calls it makes in turn. So suppose a caller passes a program of its own as
dwallet_program, and the context called it. That fake program would receive your CPI authority’s
signature. It could then call the real ika program with it, and issue a voucher for any dWallet
your program holds, or give one away. Refusing every program but ID means your CPI authority’s
signature only ever reaches the real ika program.
ID comes from a network feature of the crate: devnet-pre-alpha for the devnet pre-alpha,
and none for the test suites, which load the ika program at a
fixed development address. Build your program with the feature of the network you deploy it to.
A program built for one network calls only that network’s ika program, so it refuses the dWallets
of every other. See Pinocchio for the build
lines.
The calls
| Method | Instruction | What it does |
|---|---|---|
issue_signature_voucher | 156 | Creates a voucher for one signature |
issue_future_signature_voucher | 161 | Creates a voucher for one future sign |
set_voucher_signing_key | 157 | Sets the key a sign request must be signed by |
revoke_signature_voucher | 158 | Revokes a voucher |
transfer_signature_voucher | 159 | Gives a voucher to a new owner |
transfer_dwallet | 129 | Gives the dWallet to a new owner |
The three voucher controls act on either kind of voucher.
issue_signature_voucher
#![allow(unused)]
fn main() {
ctx.issue_signature_voucher(
coordinator, // the DWalletCoordinator, read only
signature_voucher, // the new voucher's address: writable, empty, a signer
dwallet, // the dWallet, read only
payer, // writable signer, pays the voucher's rent
system_program,
message_digest, // [u8; 32]: the Keccak-256 of the message
message_metadata_digest, // [u8; 32]: zeros for no metadata
signature_scheme, // u16: the scheme number
owner, // Option<[u8; 32]>: None makes your CPI authority the owner
signing_key, // Option<[u8; 32]>: the key a sign request must be signed by
voucher_seeds, // Option<&[Seed]>: the voucher PDA's seeds, bump included
)?;
}
The voucher’s address must sign its own creation. There are two ways:
- Pass your program’s PDA as the voucher, and its seeds as
voucher_seeds. The helper signs for it withinvoke_signed. - Pass
Noneforvoucher_seeds. The outer transaction must then carry the signature of a new keypair at the voucher’s address.
Prefer a PDA derived from your own record. A voucher at a keypair’s address can be put anywhere the transaction’s sender likes, so your program cannot know where it went.
The accounts the CPI sends:
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | coordinator | no | no |
| 1 | signature_voucher | yes | yes |
| 2 | dwallet | no | no |
| 3 | caller_program | no | no |
| 4 | cpi_authority | no | yes |
| 5 | payer | yes | yes |
| 6 | system_program | no | no |
Your instruction must receive all of these accounts, and the ika program’s account too, so it can pass them on.
issue_future_signature_voucher
The same arguments and accounts as issue_signature_voucher. The signing key is the key step 1
must be signed by. See Future Signature Vouchers.
The voucher controls
#![allow(unused)]
fn main() {
ctx.set_voucher_signing_key(signature_voucher, new_signing_key)?; // [u8; 32]
ctx.revoke_signature_voucher(signature_voucher)?;
ctx.transfer_signature_voucher(signature_voucher, new_owner)?; // [u8; 32]
}
Each sends three accounts: the voucher (writable), the calling program, and the CPI authority (signer). The voucher’s owner must be your CPI authority.
transfer_dwallet
#![allow(unused)]
fn main() {
ctx.transfer_dwallet(dwallet, new_owner)?;
}
It sends three accounts: the calling program, the CPI authority (signer), and the dWallet
(writable). The dWallet must be Active. In ika-dwallet-pinocchio the new owner is a
[u8; 32]. In the native and Anchor crates it is a &Pubkey.
When a call fails
A failed CPI fails the whole transaction, with the ika program’s error code. The codes a program meets most:
| Code | Cause |
|---|---|
IncorrectProgramId | dwallet_program is not the ika program the crate was built for. Refused before any call |
| 4005 | The dWallet is not Active |
| 4030 | The coordinator is paused |
MissingRequiredSignature | The CPI authority is not the dWallet’s or the voucher’s owner |
AccountAlreadyInitialized | The voucher address already holds an account |
| 4059 | The voucher is not pending any more |
All codes are in the Error Reference.
Integrator Invariants
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The ika program checks only which program asks for a voucher, never why. Every check between “a user gave a dWallet to my program” and “my program asked for a signature” is your program’s job. This page lists those checks. The voting and multisig examples make them, and each item names where.
The fact the rest follows from
Your program has one CPI authority, the PDA ["__ika_cpi_authority"] under your program’s id.
The ika program treats every dWallet owned by that address as controlled by your program as a
whole. It checks that the CPI authority signed and that it equals the dWallet’s owner. It cannot
know which of your users, proposals or vaults a call is for.
So suppose your program holds dWallet A for one user and dWallet B for another. Any path in your
program that ends in issue_signature_voucher can issue a voucher for A or for B, unless your
program itself checks which dWallet the path may use. The typical attack: an attacker creates a
proposal of their own in your program, with rules they control. They meet its condition, and pass
somebody else’s dWallet to the CPI.
The invariants
1. Bind every voucher to the dWallet it was approved for
The record that approves a signature, such as a proposal or a multisig transaction, must store its dWallet. When the record is carried out, the dWallet account passed to the CPI must be that one. Check it before the CPI, with an error of your own.
Examples: VotingError::DWalletMismatch in the voting programs’ cast_vote, Anchor’s
#[account(address = proposal.dwallet)], and MultisigError::DWalletMismatch in the multisig
programs’ approve.
2. Let the dWallet’s owner set its rules, once, before the transfer
Who may approve signatures for a dWallet must be fixed by the dWallet’s current owner, before it
gives the dWallet to your program. After that, nobody may create a second set of rules for the
same dWallet. Derive the rules’ account from the dWallet’s address, so there is one per dWallet.
Require its creator to be the dWallet’s stored owner.
To read that owner safely:
- Check that the account’s owner is the ika program:
IDof the CPI crate, the address of the network your program was built for. Never compare it with a program account the caller passed. A caller can pass a program of its own, with a look-alike account that names the caller as owner. - Check that byte 0 is 97 and the account is 185 bytes.
- Read
ownerat offset 2.
The CPI crates make the same check for every call they send: DWalletContext refuses a
dwallet_program that is not ID, with IncorrectProgramId. So your program’s CPI authority
never signs a call to a fake ika program. Your own reads of ika accounts are still yours to check
against ID. See The CPI Framework.
Order matters for the user: create the rules first, then transfer the dWallet. After the transfer, the owner is your program’s CPI authority, and the user cannot sign for the dWallet any more.
Examples: create_council at ["council", dwallet] and CreateMultisig at
["multisig", dwallet], with NotDWalletOwner and InvalidDWalletAccount. Their dwallet_owner
requires the ika program account to be ID and executable, and to own the dWallet. The Anchor
examples use owner = IKA_PROGRAM_ID.
3. Close the set of actors
If your program has members, voters or signers, only they may create approval records and act on them. Take the quorum or threshold from the rules’ account, never from the caller. Refuse a member listed twice, so one key cannot count twice. Refuse a threshold of zero or above the member count.
Examples: NotAMember on propose and vote, the quorum copied from the council into the
proposal, and InvalidQuorum, InvalidThreshold and DuplicateMember at creation.
4. Bind every account the CPI touches, not only the dWallet
The voucher controls act on whatever voucher account you pass, of either kind. If your record refers to a voucher, the account passed later must be that one.
A new voucher lives at an address the issuer picks. No account of the ika program names it.
Derive the address from your record, so your program and your clients can find it again. The
examples use ["signature_voucher", proposal_id] and ["signature_voucher", transaction], and
refuse any other address (VoucherMismatch).
5. Check your own accounts by address, not only by content
An account your program owns, with the right tag, can still be the wrong one: another user’s
council, or a transaction of another multisig. Check that its address is the PDA you expect.
create_program_address with the stored bump is cheap. Check the cross-references too, such as
transaction.multisig == multisig.
Examples: InvalidCouncil checks the address and the dwallet field. InvalidMultisig and
TransactionMismatch do the same for the multisig.
6. Use the canonical bump for every account whose existence enforces “once”
A seed list has up to 255 valid bumps, each giving another address. When the caller supplies the
bump, the caller can create a second account for the same seeds. So an account whose existence
means “this was done once” must be created at the canonical bump, the one
find_program_address returns. That covers the rules’ account per dWallet, and also a vote
record per voter: with a bump of the caller’s choosing, one voter could create two vote records
and vote twice.
The examples check every bump a client chooses: the proposal’s, the vote record’s, the multisig
transaction’s and the approval record’s. Their Pinocchio and native programs compare it with the
canonical one in require_canonical_bump, and refuse another with InvalidBump (11 in voting, 12
in multisig). Their Anchor programs derive every bump with seeds and bump, so Anchor uses the
canonical one. The LiteSVM tests test_a_member_cannot_vote_twice_with_a_second_bump and
test_a_member_cannot_approve_twice_with_a_second_bump show the check works.
The voucher’s bump matters for another reason. A non-canonical voucher bump puts the voucher at an
address clients do not compute. The proposal would pass and use up its voucher, and no client
would find it. The examples refuse it (InvalidVoucherBump).
7. Read the ika program’s accounts at the current offsets
SignatureVoucher, 304 bytes: dwallet at 2, message_digest at 34, message_metadata_digest
at 66, owner at 98, signature_scheme at 130, has_signing_key at 132, signing_key at 133,
issued_epoch at 165, status at 173, signature_len at 174, signature at 176.
DWallet, 185 bytes: owner at 2, curve at 34, state at 36, public_key_len at 37,
public_key at 38, created_epoch at 103, noa_public_key at 111, is_imported at 143,
bump at 144, session_identifier at 153.
Reading status at the offset of another field lets whoever controls that field make a voucher
look signed. Full tables: Account Reference.
8. Pass the coordinator, and the scheme the sign request will use
issue_signature_voucher takes the DWalletCoordinator as its first account, and a u16 signature
scheme. The network serves a sign request only when its scheme equals the voucher’s. So store the
scheme the later request will use, for example 5, EdDSA with SHA-512, for a Curve25519 dWallet.
9. Issue each voucher once
One voucher allows one signature. A second voucher for the same digest allows a second signature. Decide how many vouchers one record may issue. With the voucher at a PDA of the record, a second issue fails because the account exists, so the record must handle that. Store the digest the voucher was issued for, and the voucher’s address.
10. Check the owner and the dWallet when you read a voucher
Anything that acts on a SignatureVoucher, such as your client, an indexer or another program,
should check owner and dwallet. A voucher with the right digest for another dWallet is not
yours. A voucher stays valid after its dWallet changes owner, so the dWallet’s current owner does
not tell you who issued it.
11. Check that the dWallet is Active when it matters
The ika program issues vouchers only for Active dWallets. If an earlier step of your program
assumes the dWallet is usable, read state at offset 36 instead of assuming.
12. Give every check its own error code, and test it
Return ProgramError::Custom(n) with a different n for each condition. Write negative tests
that assert the exact code. A test that only asserts that the instruction failed also passes
when it fails for another reason, while the check you meant to test no longer runs. Then prove
the tests matter: remove a check, run the attack, and confirm the test fails.
Examples: every negative test in examples/*/*/tests/mollusk.rs, and
test_quorum_cannot_be_redirected_to_another_councils_dwallet in the voting example’s
tests/litesvm.rs.
13. Do not pass on signatures you did not mean to
Solana keeps an account’s signer and writable flags through a CPI. An account that signed your instruction is still a signer inside the program you call. Pass only what the callee needs. Never pass a user’s signer account into a CPI that could act for that user.
The voucher address is a case of this. A keypair that signed the outer transaction is a signer inside your CPI too. That is why the examples check the voucher’s address themselves, as in invariant 4.
14. Plan how a dWallet leaves your program
Once a dWallet’s owner is your CPI authority, only your program can move it, with
transfer_dwallet. Decide in advance how a user takes a dWallet back. Bind that path to the same
rules as signing. It is a change of owner, and it can be attacked the same way.
Checklist
- The rules’ account is derived from the dWallet’s address, created only by the dWallet’s stored owner, before the transfer.
- The owner check compares the dWallet account’s owner with the CPI crate’s
ID, and the program is built with its network’s feature. - Every approval record stores its dWallet, and carrying it out refuses any other dWallet before the CPI.
- Every other account the CPI touches, such as a voucher your record names, is checked the same way.
- The actor set is closed, the quorum comes from the rules, and duplicates are refused.
- Your own accounts are checked by address and cross-reference, not only by tag.
- Every account whose existence enforces “once” is created at its canonical bump.
- The coordinator is passed, with the scheme the later sign request uses.
- Each record issues its voucher once, at an address your program can find again.
- Clients read
statusat 173 andcurveas a u16 at 34. - Every check has its own error code and a test that asserts it.
- The way out for a dWallet is bound to the same rules.
Gas Deposits
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The network serves a gRPC request only when the key that signed it has a gas deposit on the
chain the request names. The deposit is a GasDeposit account of the ika program. It holds IKA,
which pays the network’s fees, and SOL, which pays for the transactions the network sends to
write results on Solana.
One deposit per request key
A user signs every gRPC request with an Ed25519 key, the request key. The deposit pays for that
key’s requests: it lives at ["gas_deposit", user_pubkey], where user_pubkey is the request
key.
The wallet that creates the deposit owns it (owner). Only the owner’s signature requests a
withdrawal, and the network then pays it. The request key only pays for requests and cannot
withdraw. The owner can be a program’s address that signs through invoke_signed.
So a user who makes a new request key needs a new deposit. A request signed by a key with no deposit is refused with:
this transport key has no gas deposit on the chain the request names
A voucher’s signing key is a request key too. The key a program names as a voucher’s signing key must have its own deposit, or its sign request is refused.
Creating a deposit
CreateDeposit creates the account. The request key must agree to it: it signs a message that
names this chain, this deployment’s network, and the wallet that creates the deposit. That
signature is checked by the Ed25519 precompile, in an instruction before CreateDeposit in the
same transaction. Anyone can pay the rent. The wallet that signs CreateDeposit becomes the
deposit’s owner.
CreateDeposit also funds the deposit, with IKA, SOL, or both. The deposit it creates must reach
the minimum first deposit (BelowMinimumDeposit, 4075). See
Deposit minimums.
A paused coordinator refuses CreateDeposit. See Pauses.
In TypeScript, createDepositInstructions from @ika.xyz/pre-alpha-solana/instructions builds both
instructions, and ikaTx.createGasDeposit() on an IkaTransaction adds them to a transaction.
Adding funds
TopUp adds IKA, SOL, or both. The IKA moves from a token account of the payer into the
coordinator’s treasury vault. The SOL moves from the payer into the deposit account. Anyone can
top up any deposit. A top-up that moves nothing is refused (EmptyTopUp, 4038). Each coin’s
amount must be zero, which adds nothing of that coin, or at least the minimum balance in that coin
(BelowMinimumTopUp, 4078). So a top-up of SOL alone checks only the SOL minimum. After a top-up,
the deposit’s balance net of debt must reach the minimum first deposit in each coin
(BelowMinimumDeposit, 4075).
What the network charges
The network charges a deposit for the work each request needs, and for the SOL its own
transactions spend. It charges in the same transaction that writes the result, with SettleGas.
It also charges for some work it delivered nothing for, such as a request it refused from its own
bytes, with SettleGasCharge.
A charge never makes the network’s transaction fail. When the balance is too small, the rest of
the charge becomes debt (ika_debt, sol_debt). The next charge takes the debt first, before its
own amount. Funds that cover debt cannot be withdrawn.
The mock network charges nothing. On the devnet pre-alpha a deposit with no funds serves, and its balance never changes.
Taking funds back
A withdrawal returns the whole deposit, less what the deposit owes and less the withdrawal’s charge. It takes two steps, and only the first is the owner’s:
- The owner sends
RequestWithdraw, naming the token account the IKA is paid to. The request carries no amount. The token account must be an open, unfrozen token account of the IKA mint (InvalidIkaDestination, 4077). - The network sends
SettleGasWithdrawalfrom its own address. There is no claim step.
The owner signs the request. Any other signer, the request key included, is refused with
AuthorityMismatch. A request is final: there is no cancel, and a second request while one is
pending is refused (WithdrawalAlreadyPending, 4076). The request names the deposit’s incarnation,
its current life; a request for another one is refused (GasDepositIncarnationMismatch, 4081), and
so is a request on a closed deposit (DepositClosed, 4080).
The payout takes the charge first, through the same collection every charge uses, and only then
pays what is left: the SOL to the owner, the IKA to the token account the request named. So no
payout happens without its charge. It creates a GasWithdrawalCharge record at
["gas_withdrawal_charge", user_pubkey, withdrawal_sequence_le], so one request is paid once.
A payout that pays everything ends the deposit’s life: the deposit is closed in place. It keeps its
account and its rent, holds nothing, owes nothing, and its owner is zeroed. A closed deposit
refuses a top-up, a request and a transfer (DepositClosed, 4080). The same request key opens it
again with CreateDeposit, the same instruction that created it: the signer becomes the owner,
the deposit’s incarnation goes up by one, and no rent is paid. The proof of possession names the
life it opens, the closed incarnation plus one, so the proof of a life that ended does not reopen
the deposit. A deposit that is open, or whose request is pending, is not reopened.
When the request is pending but the balance is below the debt plus the charge in one of the two
coins, the payout takes nothing and pays nothing, and creates no record. It emits
WithdrawalShortOfCharge. A coin whose debt exceeds its balance makes the payout short even when
that coin’s charge is 0, so no payout leaves a debt unpaid. The request stays pending, and a top-up
lets a later payout pay it.
When no request is pending at its counter, the payout is still charged. Only a payout ends a
request, so the network sends such a payout only by mistake. It creates the record, takes the charge, pays nothing, and emits
GasSettled then WithdrawalNotPaid. A shortfall becomes debt. Every withdrawal the network
sends is charged.
What a destination cannot take stays in the deposit, and GasWithdrawn names it as kept. SOL is
kept when the owner’s account is executable or would be left below its rent-exempt minimum. IKA is
kept when the destination is no longer an open token account of the IKA mint, or the vault is
frozen. The request still ends, the deposit stays open holding what was kept, and the owner can
request again.
A deposit whose request is pending still accepts a top-up, and the payout pays it out with the rest. A top-up names no incarnation: it lands on whatever life is open when it executes.
Every network charge names the incarnation it is for. A charge that names another one, or reaches a
closed deposit, takes nothing and emits GasChargeSkipped. It never fails for that reason: the
delivery it rides still lands, a charge without delivery still creates its record, and a given-up
signature’s voucher still closes. For now the network names the incarnation of the deposit state
its validators agreed when the charge is sent; it will name the incarnation the request was
admitted under.
The mock network sends no payout. On the devnet pre-alpha, funds put into a deposit stay there. Put nothing into a pre-alpha deposit.
Deposit minimums
The coordinator holds two minimums the network sets, each an (IKA, SOL) pair. Zero in a coin means no minimum in that coin. Each coin is compared with its balance minus its debt.
- The minimum first deposit (
SetMinFirstDeposit) is a minimum on the deposit’s total.CreateDepositand everyTopUpmust leave the balance net of debt at or above it. It is refundable: a withdrawal pays it back. - The minimum balance (
SetMinBalance) is the buffer for starting a new action. The network refuses a new request against a deposit below it. The program uses it for one check: each coin aTopUpadds must be zero or at least the minimum balance in that coin.CreateDepositdoes not check it.
Anyone can top up any deposit, and each top-up changes the balance the validators read. With the minimum balance on every top-up, each such change costs its sender at least that minimum, and the amount stays in the deposit, to its owner’s credit.
The deposit fee
Every CreateDeposit, a reopen included, and every TopUp also pays the coordinator’s deposit fee
in lamports. The fee pays for the network’s work of agreeing the deposit’s new state, and it is not
credited to the deposit. The network sets it with SetDepositFee, and the address that sent the
setting is the fee’s recipient.
The sol_amount the call moves includes the fee. The program sends exactly the fee to the
recipient and credits the rest to the deposit. So an IKA-only top-up still carries the fee as its
sol_amount. A sol_amount below the fee is refused (BelowDepositFee, 4082). A top-up whose
sol_amount is only the fee credits nothing, so it is empty (EmptyTopUp). The minimum first
deposit and the minimum balance apply to the credited amount.
The call names the recipient as its last account. Another account is refused while a fee is set
(InvalidDepositFeeRecipient, 4083). With no fee set nothing is paid, the whole sol_amount is
credited, and any writable account stands in the slot.
Deposit events
Every change of a deposit emits one event. Every one of them starts with the deposit’s state after
the change. A reader that keeps the state of the highest sequence it has seen follows every
deposit without reading the accounts. The Event Reference
lists each event’s fields.
Handing a deposit to a new owner
TransferGasDeposit names a new owner. The current owner signs it. A zero owner is refused with
InvalidAuthority, and any other signer with AuthorityMismatch. It is refused while a withdrawal
request is pending (TransferWhileWithdrawalPending, 4079): a request is final, and only the
network’s payout ends it. It advances sequence and emits GasDepositTransferred. A pause does
not stop it.
The account
The full layout is in the Account Reference. The fields a client reads most:
| Offset | Field | Meaning |
|---|---|---|
| 2 | user_pubkey | The request key |
| 34 | ika_balance | IKA available |
| 42 | sol_balance | Lamports available |
| 107 | ika_debt | IKA owed |
| 115 | sol_debt | Lamports owed |
| 131 | owner | The wallet that may withdraw: the signer of CreateDeposit, or the owner a TransferGasDeposit named since |
| 163 | withdrawal_pending | 1 while a withdrawal request waits for the network’s payout |
Pauses
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The dWallet part of the ika program can be paused. A pause stops users from starting new things on chain. It never stops the network from writing results. Your program needs to know this because a CPI it makes can fail while the program is paused.
The coordinator pause
The DWalletCoordinator holds a pause flag at offset 18. While it is 1, the program refuses five
instructions with Paused (4030):
CreateDepositRegisterEncryptionKeyAcceptEncryptedUserShareIssueSignatureVoucherIssueFutureSignatureVoucher
Every other instruction ignores the flag. These keep working while paused:
- every instruction the network signs, so results already started are still written;
TopUp,RequestWithdrawandTransferGasDeposit, so users can always fund, empty or hand over a deposit;TransferOwnershipand the voucher owner’s controls, so an owner can always move a dWallet or narrow a voucher.
A program whose instruction ends in an issue_signature_voucher CPI fails with 4030 while
paused. The whole transaction fails, so your program’s own writes in it are undone. A
proposal that reaches its quorum during a pause stays open, and the deciding vote can be sent
again after the unpause.
Two keys can pause and unpause: the coordinator’s pauser (offset 84), and the network. The flag
does not record who set it, so either can lift the other’s pause. Only the network can change
who the pauser is, with SetPauser. An all-zero pauser means the network alone can pause.
The program starts paused. Initialize sets the flag, and the deployment lifts it once the
network’s setup is done. The devnet pre-alpha is unpaused.
Paused signing parameters
The coordinator also lists curves, signature algorithms and hash schemes that the network refuses
requests for (offsets 165 to 559). The pauser and the network add and remove entries with
PauseSigningParameter and UnpauseSigningParameter.
The program itself refuses nothing for these lists. The validators read them and refuse a request that names a paused value. A voucher can still be issued for a paused scheme. It stays pending, and a sign request sent after the scheme is unpaused can use it.
The gRPC API
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
Users talk to the ika network over gRPC. Every dWallet operation, from key generation to
signing, is one call of SubmitTransaction. The operation is named inside the signed request,
not by the call. The SDKs build, sign and send these requests, and check the answers. This page
and the next two describe the wire format, for readers who build a client of their own or read
the traffic.
The service is the package ika.dwallet.v1alpha1. The SDK carries its definition in sdk/core/src/grpc/messages.ts. The API is
alpha: its messages and methods may change without notice.
Endpoints
| Network | Endpoint |
|---|---|
| Devnet pre-alpha, gRPC-Web | https://solana-alpha-dev-1.ika-network.net |
The devnet pre-alpha is served by the mock network. It serves gRPC-Web with a public TLS certificate. The SDK’s gRPC-Web client uses it, in a browser and in Node. A plain gRPC client on this address gets an HTTP 400 answer.
A validator of the real network serves plain gRPC over TLS. The TLS certificate is made from the validator’s network key, not from a public authority. The SDK’s Node client checks it against the committee the network signed, which it reads from Solana.
The calls
| Call | What it does |
|---|---|
SubmitTransaction | Sends one signed dWallet request and returns its answer |
GetPresigns | Lists the unused presigns served to one request key |
GetPresignsForDWallet | Lists the unused presigns bound to one imported dWallet |
GetNetworkKeyOutput | Returns a network key’s public outputs, which a client needs to compute its half of the cryptography |
GetNetworkKeysByAge | Lists the epoch’s active network keys, oldest first, and names the one new dWallets are made under |
GetCommittee | Returns the epoch’s committee, signed by the network |
Only SubmitTransaction is signed by the user. The other calls are reads. Their answers are
checked against what Solana records, never trusted on the server’s word.
The request
message UserSignedRequest {
bytes user_signature = 1; // BCS of UserSignature
bytes signed_request_data = 2; // BCS of SignedRequestData
}
signed_request_data is the request itself:
#![allow(unused)]
fn main() {
pub struct SignedRequestData {
pub session_identifier_preimage: [u8; 32],
pub epoch: u64,
pub chain_id: ChainId, // the chain the request is for: Solana here
pub network: u8, // 1 mainnet, 2 testnet, 3 a local network
pub deposit_incarnation: u64, // the life of the request key's gas deposit
pub intended_chain_sender: Vec<u8>,
pub request: DWalletRequest,
}
}
| Field | Meaning |
|---|---|
session_identifier_preimage | 32 random bytes. With the epoch and the request key, it names the request’s session |
epoch | The epoch the chain shows. On Solana, the DWalletCoordinator’s epoch |
chain_id | The chain the result is written to. Solana for this program |
network | The network the request is for: 1 mainnet, 2 testnet, 3 a local network. A validator refuses a request for another network, free of charge |
deposit_incarnation | The incarnation of the request key’s GasDeposit account, read just before signing, or 1 when the key has no deposit yet. Each reopen of a closed deposit adds one. A validator refuses, free of charge, a request that names an earlier life, and holds one that names a later life until it has read it. The deposit is always the request key’s own, even when someone else pays for it |
intended_chain_sender | The user’s 32-byte Solana address. A new dWallet’s owner is this address |
request | The operation. See Request Types |
user_signature signs those bytes with the request key:
#![allow(unused)]
fn main() {
pub enum UserSignature {
Ed25519 { signature: Vec<u8>, public_key: Vec<u8> }, // 64 and 32 bytes
Secp256k1 { signature: Vec<u8>, public_key: Vec<u8> }, // 64 and 33 bytes
Secp256r1 { signature: Vec<u8>, public_key: Vec<u8> }, // 64 and 33 bytes
}
}
On Solana the request key must be an Ed25519 key, because a gas deposit is kept per 32-byte Ed25519 key. The mock network accepts Ed25519 request keys only.
What the request key signs
The key does not sign signed_request_data alone. It signs a message with a prefix:
0xFF || "ika-request" || signed_request_data
The prefix is not sent. The validators add it, then verify. They refuse a signature over the bare
bytes. The first byte, 0xFF, cannot start a Solana transaction message, so a request key that is
also a Solana wallet never signs a request by mistake.
In TypeScript, signGrpcRequest from @ika.xyz/pre-alpha-core signs a request, and
requestSigningMessage builds the message.
What the network checks first
Before it runs a request, the network checks, in order:
- The bytes decode and the signature verifies.
- The chain is one the network writes to.
- The epoch is the current one. An earlier epoch is refused with
request epoch E does not match current epoch N. A later epoch is answeredUNAVAILABLE, so the client sends it again. - The session. The same signed bytes sent again get the same answer. Other bytes under the same preimage, key and epoch are refused.
- The request key has a gas deposit on the chain. Otherwise the request is refused with
this transport key has no gas deposit on the chain the request names.
The mock network makes the same checks in the same order.
The answer
message TransactionResponse {
bytes response_data = 1; // BCS of TransactionResponseData
RefusalCode refusal_code = 2; // which refusal an Error answer is, or UNSPECIFIED
}
#![allow(unused)]
fn main() {
pub enum TransactionResponseData {
Signature { signature: Vec<u8> },
Attestation(NetworkSignedAttestation),
Error { message: String },
}
}
A sign is answered with the signature. Every other served request is answered with an attestation: a record the network signed. A refused request is answered with an error message. See Response Types.
When the refusal is one a client acts on, such as an empty presign pool or a missing gas deposit,
refusal_code names it. The message is the same either way. A validator built before the field
existed leaves it REFUSAL_CODE_UNSPECIFIED, so a client that finds no code reads the message.
A refusal sent as a gRPC status carries the same code in the status’s details, as a
RefusalDetails message.
A gRPC status of UNAVAILABLE means “send the same bytes again later”. It is not a refusal. The
SDKs send the same signed bytes again; they never sign a new request for it.
Presigns
A presign is the network’s half of a signature, made in advance and not tied to a message. A
Presign request makes one. GetPresigns lists the unused ones served to a request key:
message PresignInfo {
bytes presign_id = 1; // pass it back in a Sign request
bytes dwallet_binding_id = 2; // empty for a presign of the global pool
uint32 signature_algorithm = 3;
uint64 assigned_epoch = 4; // the presign expires with this epoch
}
GetPresignsForDWallet takes the request key, an imported dWallet’s public key and the session
identifier of the import, and lists the presigns bound to that dWallet.
Request Types
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The request field of a signed request is a DWalletRequest. Its variant names the operation.
This page lists the variants, what each needs first, and what comes back. The SDK defines their BCS
encoding in sdk/core/src/grpc/bcs.ts.
The variants
The variant’s position is its BCS index, so the order is part of the wire format.
| # | Variant | What it does | Answer |
|---|---|---|---|
| 0 | Dkg | Creates a dWallet by key generation | dWallet attestation |
| 1 | Sign | Signs a message with a dWallet, under a voucher | signature |
| 2 | ImportedKeySign | Signs with an imported dWallet, under a voucher | signature |
| 3 | Presign | Makes a presign from the global pool | presign attestation |
| 4 | PresignForDWallet | Makes a presign bound to one imported dWallet. ECDSA only | presign attestation |
| 5 | ImportedKeyVerification | Creates a dWallet from an existing key | dWallet attestation |
| 6 | ReEncryptShare | Encrypts a copy of the user’s share to another holder | encrypted share attestation |
| 7 | MakeSharePublic | Reveals the user’s share to the network | public share attestation |
| 8 | FutureSign | Step 1 of a future sign | partial signature attestation |
| 9 | SignWithPartialUserSig | Step 2 of a future sign | signature |
| 10 | ImportedKeySignWithPartialUserSig | Step 2 for an imported dWallet | signature |
| 11 | RetiredReleaseGas | Removed. Refused from its bytes | |
| 12 | RetiredAcceptShare | Removed. Refused | |
| 13 | RetiredStorePresign | Removed. Refused | |
| 14 | AttachEncryptedShare | Not used on Solana | encrypted share attestation |
A holder accepts an encrypted share on chain, with its own transaction. That is why variant 12 is gone. See Encrypted Shares.
The network pays a gas withdrawal with its own transaction, once the deposit’s owner sends
RequestWithdraw on chain. No user asks the network for anything to withdraw, so variant 11 is
gone too. See Gas Deposits.
What the real network serves
The real network serves every variant except the three removed ones, with one more exception: an
ImportedKeyVerification with a public share. It refuses that one with
gRPC request type not yet supported for session conversion.
What the mock network serves
The devnet pre-alpha’s mock network serves variants 0 to 10. It refuses the three removed variants
as the real network does, and AttachEncryptedShare.
The mock makes every dWallet’s key itself, an imported one included. An import request on the pre-alpha names a curve and nothing else, and no private key is ever sent. So an imported pre-alpha dWallet does not hold the key you imported, and has a different address. Never import a real key on the pre-alpha.
Signature schemes
Every request that signs names a DWalletSignatureScheme, a u16:
| Number | Scheme | Curve |
|---|---|---|
| 0 | ECDSA with Keccak-256 | secp256k1 |
| 1 | ECDSA with SHA-256 | secp256k1 or secp256r1 |
| 2 | ECDSA with double SHA-256 | secp256k1 |
| 3 | Taproot, Schnorr with SHA-256 | secp256k1 |
| 4 | ECDSA with BLAKE2b-256 | secp256k1 |
| 5 | EdDSA with SHA-512 | Curve25519 |
| 6 | Schnorrkel | Ristretto |
A scheme on a curve not listed with it is refused from the request’s bytes.
Dkg
#![allow(unused)]
fn main() {
Dkg {
network_key_id: NetworkKeyId, // the network key's 32-byte public key
curve: DWalletCurve,
centralized_public_key_share_and_proof: Vec<u8>,
user_secret_key_share: UserSecretKeyShare,
user_public_output: Vec<u8>,
sign_during_dkg_request: Option<SignDuringDKGRequest>,
}
enum UserSecretKeyShare {
Encrypted {
encrypted_centralized_secret_share_and_proof: Vec<u8>,
encryption_key: Vec<u8>,
signer_public_key: Vec<u8>, // the holder's 32-byte Ed25519 key
},
Public { public_user_secret_key_share: Vec<u8> },
}
}
Needs first: for an encrypted share, the holder’s EncryptionKey on chain must hold exactly
encryption_key. A request for a holder with no registered key waits about a minute, then is
refused.
network_key_id must be the epoch’s newest usable network key: latest_usable_network_key_id of
GetNetworkKeysByAge. A new dWallet under any other key is refused.
sign_during_dkg_request asks the network to sign one message with the new dWallet in the same
session. It names a presign from the global pool served to the same request key. No voucher is
needed: the request that creates the dWallet asks for it. The signature comes back inside the
dWallet attestation, in sign_during_dkg_signature.
After it: the network writes the dWallet to Solana. With an encrypted share, the dWallet waits for its holder to accept the share.
Presign
#![allow(unused)]
fn main() {
Presign { network_key_id: NetworkKeyId, curve: DWalletCurve, signature_algorithm: DWalletSignatureAlgorithm }
}
Needs first: nothing. The presign belongs to the request key, and expires with the epoch it was made in.
Sign
#![allow(unused)]
fn main() {
Sign {
message: Vec<u8>,
message_metadata: Vec<u8>, // empty for most schemes
signature_scheme: DWalletSignatureScheme,
presign_session_identifier: Vec<u8>, // the presign to use
message_centralized_signature: Vec<u8>, // the user's half of the signature
dwallet_attestation: NetworkSignedAttestation,
signature_voucher: [u8; 32], // the voucher's address on Solana
}
}
Needs first:
- an Active dWallet, whose attestation the request carries;
- a presign of this epoch, served to the request key and not used before;
- a pending
SignatureVoucheratsignature_voucher, for this dWallet, message, metadata and scheme, whose signing key is the request key.
The network reads the voucher on Solana itself. A request whose voucher is missing, or has no signing key yet, waits for it. See Signature Vouchers.
message_metadata is BCS bytes of the scheme’s metadata. Most schemes have none, and a non-empty
value for such a scheme is refused.
ImportedKeyVerification, PresignForDWallet, ImportedKeySign
An imported dWallet holds a key the user already had. ImportedKeyVerification creates it. Its
fields are those of Dkg, with centralized_party_message in place of the public key share, and
no sign during creation.
For ECDSA, an imported dWallet signs only with a presign bound to it, which
PresignForDWallet makes. Schnorr-family presigns are always from the global pool.
ImportedKeySign has the fields of Sign.
ReEncryptShare
#![allow(unused)]
fn main() {
ReEncryptShare {
network_key_id: NetworkKeyId,
dwallet_public_key: Vec<u8>,
dwallet_attestation: NetworkSignedAttestation,
encrypted_centralized_secret_share_and_proof: Vec<u8>,
encryption_key: Vec<u8>,
holder: ShareHolder, // the new holder
source_holder: ShareHolder, // the holder of the share it is made from
}
}
Needs first: the dWallet Active on chain, and the new holder’s EncryptionKey registered.
The network writes the new share to Solana, and the new holder accepts it there.
MakeSharePublic
#![allow(unused)]
fn main() {
MakeSharePublic {
dwallet_public_key: Vec<u8>,
dwallet_attestation: NetworkSignedAttestation,
public_user_secret_key_share: Vec<u8>,
}
}
Needs first: the dWallet Active on chain. The network writes the public share to Solana. From then on the network can sign with the dWallet alone.
FutureSign and its completions
#![allow(unused)]
fn main() {
FutureSign {
dwallet_public_key: Vec<u8>,
dwallet_attestation: NetworkSignedAttestation,
presign_attestation: NetworkSignedAttestation,
message: Vec<u8>,
message_metadata: Vec<u8>,
message_centralized_signature: Vec<u8>,
signature_scheme: DWalletSignatureScheme,
future_signature_voucher: [u8; 32],
}
SignWithPartialUserSig {
partial_user_signature_attestation: NetworkSignedAttestation, // step 1's answer
dwallet_attestation: NetworkSignedAttestation,
message: Vec<u8>,
message_metadata: Vec<u8>,
future_signature_voucher: [u8; 32],
}
}
Step 1 needs: a presign of this epoch, served to the request key and not used before, and an
open FutureSignatureVoucher whose signing key is the request key.
Step 2 needs: the voucher holding step 1’s result, with its signing key set again by its owner to the request key. Step 2 uses no presign, so it can run in any later epoch.
ImportedKeySignWithPartialUserSig has the fields of SignWithPartialUserSig, for an imported
dWallet. See Future Signature Vouchers.
A dWallet that waits for its holder
A dWallet created with an encrypted share is unusable until its holder accepts the share. The network starts no sign, presign for the dWallet, future sign, re-encryption or reveal on it until then. Such a request is not refused at once. It waits, and runs once the network reads the dWallet as Active. It is refused only if its usual wait ends first.
Response Types
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
SubmitTransaction answers with the BCS bytes of a TransactionResponseData:
#![allow(unused)]
fn main() {
pub enum TransactionResponseData {
Signature { signature: Vec<u8> },
Attestation(NetworkSignedAttestation),
Error { message: String },
}
}
Check for Error first. An error message explains the refusal in plain text.
Signature
A sign request, of any of the three sign kinds, is answered with the signature. The bytes are the ones the network also writes into the voucher.
| Algorithm | Length | Bytes |
|---|---|---|
| ECDSA, secp256k1 or secp256r1 | 65 | a recovery byte, then r (32) and s (32) |
| Taproot | 64 | a BIP-340 signature |
| EdDSA | 64 | an Ed25519 signature |
| Schnorrkel | 64 | an sr25519 signature |
To verify an ECDSA signature with a library that takes 64 bytes, drop the first byte. The SDKs also check that the recovery byte recovers the dWallet’s public key.
Attestation
Every other served request is answered with an attestation: a record of the result, signed by the network.
#![allow(unused)]
fn main() {
pub struct NetworkSignedAttestation {
pub attestation_data: Vec<u8>, // BCS of the attestation
pub network_signature: Vec<u8>, // the network's Ed25519 signature
pub network_pubkey: Vec<u8>, // the network key the dWallet was made under
pub signer_noa_public_key: [u8; 32], // the network key that made the signature
}
}
network_pubkey and signer_noa_public_key can differ. A dWallet stays under the network key it
was made under, while each epoch signs with its own newest key. Verify the signature under
signer_noa_public_key, after you have checked that it is a network key you trust.
The network’s signature covers only attestation_data. The attestation names its own session and
sender inside those bytes, so nobody who passes it on can change them.
The same attestation, proof and fields are what the network writes to Solana. A client can check an answer it got over gRPC against the copy on chain, or the other way round.
What the network signs
The network does not sign attestation_data alone. It signs a message that names the kind:
0xFE || "ika-attestation" || kind tag (1) || attestation_data
| Attestation | Kind tag | Answer to |
|---|---|---|
VersionedDWalletDataAttestation | 0 | Dkg, ImportedKeyVerification |
VersionedPresignDataAttestation | 1 | Presign, PresignForDWallet |
VersionedPartialUserSignatureAttestation | 2 | FutureSign |
VersionedEncryptedUserKeyShareAttestation | 3 | ReEncryptShare, a dWallet’s first encrypted share |
VersionedPublicUserKeyShareAttestation | 4 | MakeSharePublic, a dWallet’s public share at creation |
Verify with the kind you expect. A check that ignores the kind can be fooled: the bytes of one kind can also decode as another.
A signature proves only that the key it names made it. The answer names its own signer, so a
faulty server can sign with a key of its own and name that key. Check the signer against the
network keys you trust. In TypeScript, use the checks that take your trusted keys, such as
verifyAttestation from @ika.xyz/pre-alpha-core. verifyAttestationSignature checks only the
signature, under the key the answer names. Use it only after you checked that key yourself.
The attestations
Each is a versioned enum with one version today, V1.
DWallet
#![allow(unused)]
fn main() {
pub struct DWalletDataAttestationV1 {
pub session_identifier: [u8; 32],
pub intended_chain_sender: Vec<u8>, // the dWallet's owner on Solana
pub curve: DWalletCurve,
pub public_key: Vec<u8>,
pub public_output: Vec<u8>,
pub is_imported_key: bool,
pub sign_during_dkg_signature: Option<Vec<u8>>,
pub holder: Option<ShareHolder>, // the encrypted share's holder
pub encryption_key_hash: Option<[u8; 32]>,
pub encrypted_share_hash: Option<[u8; 32]>,
pub epoch: u64, // the epoch it was made in
}
}
A later request on the dWallet carries this attestation back. An imported dWallet’s session
identifier is this session_identifier.
Presign
#![allow(unused)]
fn main() {
pub struct PresignDataAttestationV1 {
pub session_identifier: [u8; 32],
pub epoch: u64, // the presign expires with it
pub presign_session_identifier: Vec<u8>, // pass it in a sign request
pub presign_data: Vec<u8>,
pub curve: DWalletCurve,
pub signature_algorithm: DWalletSignatureAlgorithm,
pub dwallet_public_key: Option<Vec<u8>>, // None for the global pool
pub user_pubkey: Vec<u8>, // the request key it was served to
}
}
Partial user signature
The answer to step 1 of a future sign. Step 2 carries it back.
#![allow(unused)]
fn main() {
pub struct PartialUserSignatureAttestationV1 {
pub session_identifier: [u8; 32],
pub intended_chain_sender: Vec<u8>,
pub dwallet_public_key: Vec<u8>,
pub dwallet_attestation_hash: [u8; 32], // Keccak-256 of the dWallet attestation's bytes
pub future_signature_voucher: [u8; 32],
pub presign_session_identifier: Vec<u8>,
pub presign_attestation_hash: [u8; 32],
pub message_digest: [u8; 32],
pub message_metadata_digest: [u8; 32],
pub signature_scheme: DWalletSignatureScheme,
pub verified_sign_data: Vec<u8>,
}
}
It holds digests, not the message. Step 2 carries the message, and the network checks it against the digest.
Encrypted share
#![allow(unused)]
fn main() {
pub struct EncryptedUserKeyShareAttestationV1 {
pub session_identifier: [u8; 32],
pub intended_chain_sender: Vec<u8>,
pub dwallet_public_key: Vec<u8>,
pub encrypted_share_hash: [u8; 32],
pub encryption_key_hash: [u8; 32],
pub holder: ShareHolder,
pub dwallet_attestation_digest: [u8; 32], // Keccak-256 of the dWallet attestation's bytes
}
}
dwallet_attestation_digest names the one dWallet the share belongs to. Two imports of one key
have the same public key, so compare this digest with the digest of the dWallet attestation you
hold.
Public share
#![allow(unused)]
fn main() {
pub struct PublicUserKeyShareAttestationV1 {
pub session_identifier: [u8; 32],
pub intended_chain_sender: Vec<u8>,
pub dwallet_public_key: Vec<u8>,
pub public_user_secret_key_share: Vec<u8>,
pub dwallet_attestation_digest: [u8; 32],
}
}
ShareHolder is a signature scheme and a 32-byte signer key. Only Ed25519 holders are accepted.
On the devnet pre-alpha
The mock network answers in the same formats and signs with its one network key. The
cryptographic outputs it serves, such as the network key’s output and each dWallet’s public
output, are mock values: they start with the byte 0xFF and the text ika-mock. An SDK that is not in mock
mode refuses them with “mock values need the SDK’s mock feature”. This is what stops a real app
from trusting the pre-alpha by mistake.
Mollusk Tests
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
Mollusk runs one instruction of one program against accounts you build by hand. It starts no validator and takes milliseconds. Use it to test each of your program’s instructions alone: its data parsing, its account checks, and every error it returns.
Mollusk runs a single program, so it cannot run your CPI into the ika program. Test the CPI with LiteSVM.
Setup
[dev-dependencies]
mollusk-svm = "0.15"
solana-account = "4.3"
solana-instruction = "3.4"
solana-program-error = "3"
solana-pubkey = "4.1"
These are the versions the examples use. Build your program first with
cargo build-sbf --tools-version v1.54 --arch v3, with no network feature, then load it:
#![allow(unused)]
fn main() {
use mollusk_svm::Mollusk;
use solana_pubkey::Pubkey;
const PROGRAM_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/target/deploy/my_program");
fn setup() -> (Mollusk, Pubkey) {
let program_id = Pubkey::new_unique();
(Mollusk::new(&program_id, PROGRAM_PATH), program_id)
}
}
--arch v3 builds for SBPF version 3. A cluster with SIMD-0500 active refuses to deploy a build
for an older version. --tools-version v1.54 names platform tools that have the version 3 target.
Building a dWallet account by hand
Your program reads DWallet accounts of the ika program. In a Mollusk test you build one: 185
bytes, tag 97 at byte 0, version 1 at byte 1, the owner at offset 2. The account’s owner must be
ID of the CPI crate. A test build has no network feature, so ID is the development address,
and your program accepts only dWallets owned by it. Pass the same address as the ika program
account wherever your instruction takes one.
#![allow(unused)]
fn main() {
let ika_program = Pubkey::new_from_array(*ika_dwallet_pinocchio::ID.as_array());
}
#![allow(unused)]
fn main() {
fn dwallet_account(ika_program: &Pubkey, dwallet_owner: &Pubkey) -> Account {
let mut data = vec![0u8; 185];
data[0] = 97; // DWallet
data[1] = 1; // version
data[2..34].copy_from_slice(dwallet_owner.as_ref());
Account {
lamports: 1_000_000_000,
data,
owner: *ika_program,
executable: false,
rent_epoch: 0,
}
}
}
Set state at offset 36 to 1 when your program checks that the dWallet is Active. The full
layout is in the Account Reference.
Asserting the exact error
Assert the error code a test expects, never only that the instruction failed. A test that only checks for failure also passes when the instruction fails for another reason, and then the check you meant to test may no longer run at all.
#![allow(unused)]
fn main() {
use mollusk_svm::result::{InstructionResult, ProgramResult};
use solana_program_error::ProgramError;
fn assert_custom_error(result: &InstructionResult, code: u32) {
match &result.program_result {
ProgramResult::Failure(error) => assert_eq!(*error, ProgramError::Custom(code)),
other => panic!("expected Custom({code}), got {other:?}"),
}
}
}
What the voting example tests with Mollusk
examples/voting/pinocchio/tests/mollusk.rs tests each instruction, and each
binding the program relies on:
| Test | What it shows |
|---|---|
test_create_council_success | The council is created at its canonical address with its fields |
test_create_council_rejects_non_owner | Only the dWallet’s owner can create the council |
test_create_council_rejects_dwallet_not_owned_by_dwallet_program | A look-alike dWallet account is refused |
test_create_council_rejects_quorum_above_member_count | The quorum is checked |
test_create_council_rejects_duplicate_member | A member listed twice is refused |
test_create_council_rejects_non_canonical_address | The council must be at its canonical address |
test_create_proposal_success | The proposal takes its quorum from the council |
test_create_proposal_rejects_non_member | Only members propose |
test_create_proposal_rejects_council_of_another_dwallet | The council must be the dWallet’s own |
test_create_proposal_rejects_forged_council_account | Council-like data at another address is refused |
test_create_proposal_already_exists | A proposal id is used once |
test_cast_vote_yes_success, test_cast_vote_no_success | Votes are counted |
test_cast_vote_rejects_non_member, test_cast_vote_rejects_council_of_another_dwallet | Membership is checked on every vote |
test_cast_vote_at_quorum_rejects_wrong_dwallet | The vote that reaches the quorum refuses another dWallet |
test_cast_vote_double_vote_fails | A second vote at the same vote record fails |
test_cast_vote_closed_proposal_fails | A passed proposal takes no more votes |
Running the tests
From the repository root:
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/voting/pinocchio/Cargo.toml
cargo test -p ika-example-voting-pinocchio --test mollusk
LiteSVM Tests
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
LiteSVM runs a Solana runtime inside your test. It loads
several programs and runs whole transactions, so your program’s CPI into the real ika program
runs as it does on chain. Use it to test the path that ends in issue_signature_voucher.
LiteSVM runs no ika network. Nothing signs a voucher in a LiteSVM test. You check that the voucher was created with the right fields, and stop there. The full path with a signature is an end-to-end test.
What a test needs
-
The compiled ika program. This repository ships it in
bin/, with a build for the fixed development address the tests use. A program binary works only at the address it was built for, because it derives its own accounts’ addresses from that id. So load it at that id. -
The ika program’s state. No network runs in the test to create the coordinator, a network key or a dWallet. Write them into the runtime directly with
set_account: aDWalletCoordinatorthat is not paused, an activeNetworkEncryptionKey, and an ActiveDWalletowned by a key of the test. -
Your program, built with no network feature, and loaded at an id of your choosing. With no feature, the CPI crate’s
IDis the same development address the ika program is loaded at, so your program’s calls reach it. A program built withdevnet-pre-alpharefuses that address withIncorrectProgramId.
The harness in this repository
crates/ika-dwallet-litesvm-test (crate ika-dwallet-litesvm-test) does steps 1 and 2. It loads
the compiled ika program from bin/. Its DWalletTestContext loads the ika program, funds a payer, and writes an unpaused coordinator and
an active network key:
#![allow(unused)]
fn main() {
use ika_dwallet_litesvm_test::*;
let mut ctx = DWalletTestContext::new();
let my_program = ctx.deploy_program(MY_PROGRAM_SO);
let (cpi_authority, cpi_authority_bump) = ctx.cpi_authority_for(&my_program);
// An Active dWallet, owned by a test key.
let user = ctx.new_funded_keypair();
let public_key = [7u8; 32];
let dwallet = ctx.create_dwallet(&keypair_pubkey(&user), 2, 32, &public_key);
// Give it to the program, through the real TransferOwnership.
ctx.transfer_dwallet(&dwallet, &user, &cpi_authority);
}
It also offers send_tx, which panics on failure, try_send_tx, which returns the result, and
get_account_data. It depends on litesvm 0.16.
Checking the voucher
After the instruction that should issue a voucher, read the voucher’s address:
#![allow(unused)]
fn main() {
let voucher = ctx.get_account_data(&voucher_pda).expect("the voucher exists");
assert_eq!(voucher.len(), 304);
assert_eq!(voucher[0], 108); // SignatureVoucher
assert_eq!(&voucher[2..34], dwallet.as_ref()); // its dWallet
assert_eq!(&voucher[34..66], &message_digest); // its message
assert_eq!(&voucher[98..130], cpi_authority.as_ref()); // owned by the program
assert_eq!(voucher[173], 0); // pending
}
What the voting example tests with LiteSVM
examples/voting/pinocchio/tests/litesvm.rs:
| Test | What it shows |
|---|---|
test_voting_full_lifecycle | Council, transfer, proposal and three votes. The third vote issues the voucher |
test_voting_below_quorum_no_voucher | No voucher before the quorum |
test_no_votes_dont_trigger_quorum | No votes do not count toward the quorum |
test_outsider_cannot_vote_or_recreate_council | A stranger cannot vote, or replace the council |
test_quorum_cannot_be_redirected_to_another_councils_dwallet | A quorum cannot issue a voucher for another council’s dWallet |
test_create_proposal_refuses_a_non_canonical_voucher_bump | The voucher’s bump must be the canonical one |
test_quorum_vote_refuses_a_substituted_voucher_account | The voucher must be at the program’s PDA |
test_a_member_cannot_vote_twice_with_a_second_bump | A vote record at a second valid bump is refused (InvalidBump) |
test_create_proposal_refuses_a_non_canonical_proposal_bump | The proposal’s bump must be the canonical one |
test_dwallet_context_refuses_a_program_that_is_not_ika | A fake ika program is refused with IncorrectProgramId, before any call |
The native and Anchor versions, and the three multisig programs, have the same kind of tests. The
multisig programs also test test_a_member_cannot_approve_twice_with_a_second_bump,
test_a_member_cannot_reject_twice_with_a_second_bump and
test_create_transaction_refuses_a_non_canonical_transaction_bump.
Running the tests
From the repository root, build the example, then run its tests:
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/voting/pinocchio/Cargo.toml
cargo test -p ika-example-voting-pinocchio --test litesvm
Mollusk or LiteSVM
| Mollusk | LiteSVM | |
|---|---|---|
| Runs | one instruction | whole transactions |
| CPI into the ika program | no | yes |
| Several programs | no | yes |
| State kept between steps | no | yes |
| Speed | fastest | fast |
Test each instruction and each error with Mollusk. Test the CPI and multi-step flows with LiteSVM.
End-to-End Tests
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
An end-to-end test runs the whole path: a dWallet is created, your program issues a voucher, the network signs, and the signature lands in the voucher. It runs on the devnet pre-alpha, where the ika program and the mock network are already running. You deploy only your own program, and the SDK runs in mock mode, because the network is the mock.
On the devnet pre-alpha
| Solana cluster | devnet, https://api.devnet.solana.com |
| ika program | 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv |
| ika gRPC-Web | https://solana-alpha-dev-1.ika-network.net |
What you need:
-
A funded devnet wallet. The devnet RPC faucet is closed. Get devnet SOL from
https://faucet.solana.com. The mock charges no fees, but Solana transactions still cost SOL: your own program’s deployment, the accounts it creates, and each voucher’s rent. -
Your program, built for the pre-alpha and deployed to devnet. Build it with the
devnet-pre-alphafeature, so it calls the pre-alpha’s ika program:cargo build-sbf --tools-version v1.54 --arch v3 -- --features devnet-pre-alpha solana program deploy -u devnet target/deploy/my_program.soA program built without the feature refuses the pre-alpha’s dWallets.
-
The SDK in mock mode. Wrap the client’s options in
withMockCryptographyfrom@ika.xyz/pre-alpha-core/mock.
The public devnet RPC limits how fast you can read. A full run reads accounts often while it waits for the network, and can be refused with HTTP 429. Use your own RPC endpoint, or retry reads that are refused.
The steps of a run
A run of a program that controls a dWallet goes like this:
- Create a gas deposit for your request key. On the mock it needs no funds.
- Create a dWallet with the SDK, and accept its encrypted share. The SDK does both.
- While your wallet still owns the dWallet, create your program’s rules for it, such as a council.
- Transfer the dWallet to your program’s CPI authority.
- Run your program’s instructions until it issues a voucher.
- Take a presign, and send the sign request that names the voucher. The SDK does both.
- Wait for the voucher’s status to become 1, and check that its signature is the one the gRPC answer carried, and that it verifies under the dWallet’s public key.
The voting and multisig examples run these steps against the pre-alpha. See Examples for how to run them.
Pinocchio
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
ika-dwallet-pinocchio lets a Pinocchio program call
the ika program. Pinocchio programs are no_std and copy nothing they do not need to, so they
cost the fewest compute units. The ika program itself is written in Pinocchio.
Dependencies
[dependencies]
ika-dwallet-pinocchio = { git = "https://github.com/dwallet-labs/ika-pre-alpha" }
pinocchio = { version = "0.11", features = ["cpi"] }
pinocchio-system = "0.6"
[lib]
crate-type = ["cdylib", "lib"]
pinocchio-system creates your program’s own accounts. A program that derives PDAs in host
tests also needs solana-address with its curve25519 feature, as the examples do.
Build for one network
The crate names one ika program, the one deployed on the network you build for. It exports that
program’s address as ID. Pick the network with a feature of the crate:
| Feature | Network |
|---|---|
devnet-pre-alpha | the Solana devnet pre-alpha, ika program 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv |
localnet | a local validator running the localnet ika program, as the local mock does |
| none | the test suites only, which load the ika program at a fixed development address |
Other network features exist for networks not deployed yet. Only one feature can be on.
Forward the features from your own crate, as the examples do, so that tests build without one:
[features]
devnet-pre-alpha = ["ika-dwallet-pinocchio/devnet-pre-alpha"]
Then build with the network’s feature:
cargo build-sbf --tools-version v1.54 --arch v3 -- --features devnet-pre-alpha
A program built for one network refuses the dWallets of every other, because it calls only that network’s ika program. If a pre-alpha wipe moves the ika program to a new address, update the crate, rebuild with the feature, and redeploy or upgrade your program.
The context
#![allow(unused)]
fn main() {
use ika_dwallet_pinocchio::{CPI_AUTHORITY_SEED, DWalletContext, ID as IKA_PROGRAM_ID};
let ctx = DWalletContext {
dwallet_program, // &AccountView: the ika program
cpi_authority, // &AccountView: your program's CPI authority
caller_program, // &AccountView: your program's own account
cpi_authority_bump, // u8
};
}
Your program’s CPI authority is Address::find_program_address(&[CPI_AUTHORITY_SEED], program_id).
A client can compute the bump and pass it in your instruction’s data. A wrong bump makes the CPI
fail, so a caller cannot misuse it.
dwallet_program must be the account at IKA_PROGRAM_ID. Every call refuses any other account
with IncorrectProgramId, before it calls anything. The CPI Framework
explains why.
The calls
| Method | Arguments after the context |
|---|---|
issue_signature_voucher | coordinator, signature_voucher, dwallet, payer, system_program, message_digest, message_metadata_digest, signature_scheme, owner, signing_key, voucher_seeds |
issue_future_signature_voucher | the same |
set_voucher_signing_key | signature_voucher, signing_key: [u8; 32] |
revoke_signature_voucher | signature_voucher |
transfer_signature_voucher | signature_voucher, new_owner: [u8; 32] |
transfer_dwallet | dwallet, new_owner: [u8; 32] |
owner and signing_key are Option<[u8; 32]>. voucher_seeds is Option<&[Seed]>: the
seeds of the voucher’s PDA, bump included, or None when a keypair at the voucher’s address signs
the transaction. Each call returns a ProgramResult. See The CPI Framework
for what each call checks and sends.
Example: issue a voucher when a proposal passes
This is the core of examples/voting/pinocchio/src/lib.rs. When the yes votes reach
the quorum, the program checks the accounts the client passed, and issues a voucher at its own PDA
["signature_voucher", proposal_id]:
#![allow(unused)]
fn main() {
if yes_votes >= quorum {
let [coordinator, signature_voucher, dwallet, caller_program, cpi_authority, dwallet_program, ..] =
&*tail
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
// The dWallet must be the proposal's own, not one the caller chose.
if dwallet.address().as_array() != &proposal_dwallet {
return Err(VotingError::DWalletMismatch.into());
}
// The voucher must be this program's PDA for the proposal.
let expected_voucher = Address::create_program_address(
&[b"signature_voucher", proposal_id.as_ref(), &[signature_voucher_bump]],
program_id,
)
.map_err(|_| VotingError::VoucherMismatch)?;
if signature_voucher.address() != &expected_voucher {
return Err(VotingError::VoucherMismatch.into());
}
let ctx = DWalletContext { dwallet_program, cpi_authority, caller_program, cpi_authority_bump };
let voucher_bump_byte = [signature_voucher_bump];
let voucher_seeds = [
Seed::from(b"signature_voucher" as &[u8]),
Seed::from(proposal_id.as_ref()),
Seed::from(voucher_bump_byte.as_ref()),
];
ctx.issue_signature_voucher(
coordinator,
signature_voucher,
dwallet,
payer,
system_program,
message_digest,
[0u8; 32], // no metadata
signature_scheme,
None, // owner: this program's CPI authority
Some(user_pubkey), // the key the sign request must be signed by
Some(&voucher_seeds),
)?;
}
}
The whole program, with its council and its tests, is walked through in the voting tutorial.
Choosing a framework
| Pinocchio | Native | Anchor | |
|---|---|---|---|
| Compute cost | lowest | middle | highest |
| Program size | smallest | middle | largest |
no_std | yes | no | no |
| Account checks | by hand | by hand | declared on the accounts struct |
All three call the same ika instructions, so the choice does not change what the network sees.
Native
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
ika-dwallet-native lets a program written with plain solana-program, with no framework, call
the ika program.
Dependencies
[dependencies]
ika-dwallet-native = { git = "https://github.com/dwallet-labs/ika-pre-alpha" }
solana-program = "2.2"
[lib]
crate-type = ["cdylib", "lib"]
Build for one network
The crate names one ika program, the one deployed on the network you build for. It exports that
program’s address as ID. Pick the network with a feature of the crate:
| Feature | Network |
|---|---|
devnet-pre-alpha | the Solana devnet pre-alpha, ika program 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv |
localnet | a local validator running the localnet ika program, as the local mock does |
| none | the test suites only, which load the ika program at a fixed development address |
Other network features exist for networks not deployed yet. Only one feature can be on.
Forward the features from your own crate, as the examples do, so that tests build without one:
[features]
devnet-pre-alpha = ["ika-dwallet-native/devnet-pre-alpha"]
Then build with the network’s feature:
cargo build-sbf --tools-version v1.54 --arch v3 -- --features devnet-pre-alpha
A program built for one network refuses the dWallets of every other, because it calls only that network’s ika program. If a pre-alpha wipe moves the ika program to a new address, update the crate, rebuild with the feature, and redeploy or upgrade your program.
The context
#![allow(unused)]
fn main() {
use ika_dwallet_native::{CPI_AUTHORITY_SEED, DWalletContext, ID as IKA_PROGRAM_ID};
let ctx = DWalletContext {
dwallet_program, // &AccountInfo: the ika program
cpi_authority, // &AccountInfo: your program's CPI authority
caller_program, // &AccountInfo: your program's own account
cpi_authority_bump, // u8
};
}
Your program’s CPI authority is Pubkey::find_program_address(&[CPI_AUTHORITY_SEED], program_id).
IKA_PROGRAM_ID is a Pubkey. Every call refuses a dwallet_program at any other address with
IncorrectProgramId.
The calls
The methods and their order of arguments are those of the Pinocchio crate. Two types differ:
voucher_seedsisOption<&[&[u8]]>, the seeds assolana-programtakes them.transfer_dwallettakes the new owner as&Pubkey.
Each call returns Result<(), ProgramError>.
Example
From examples/voting/native/src/lib.rs, once the vote reaches the quorum and the
dWallet and voucher accounts are checked:
#![allow(unused)]
fn main() {
let ctx = DWalletContext { dwallet_program, cpi_authority, caller_program, cpi_authority_bump };
let voucher_seeds: &[&[u8]] = &[
b"signature_voucher",
proposal_id.as_ref(),
&[signature_voucher_bump],
];
ctx.issue_signature_voucher(
coordinator,
signature_voucher,
dwallet,
payer,
system_program,
message_digest,
[0u8; 32],
signature_scheme,
None,
Some(user_pubkey),
Some(voucher_seeds),
)?;
}
The native example creates its own accounts with solana_program::system_instruction, which
solana-program marks deprecated in favour of the solana-system-interface crate. It still works.
Anchor
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
ika-dwallet-anchor lets an Anchor 1.x program call the ika
program. Anchor checks accounts from constraints declared on the accounts struct, so most of the
checks a dWallet program needs fit in a few attributes.
Dependencies
[dependencies]
ika-dwallet-anchor = { git = "https://github.com/dwallet-labs/ika-pre-alpha" }
anchor-lang = "1.2"
[lib]
crate-type = ["cdylib", "lib"]
Build with the Anchor CLI 1.x, with the network’s feature, for example
anchor build -- --features devnet-pre-alpha, or with cargo build-sbf as below. The ika program has no Anchor IDL, so its accounts reach your
program as UncheckedAccount, and your program checks them.
Build for one network
The crate names one ika program, the one deployed on the network you build for. It exports that
program’s address as ID. Pick the network with a feature of the crate:
| Feature | Network |
|---|---|
devnet-pre-alpha | the Solana devnet pre-alpha, ika program 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv |
localnet | a local validator running the localnet ika program, as the local mock does |
| none | the test suites only, which load the ika program at a fixed development address |
Other network features exist for networks not deployed yet. Only one feature can be on.
Forward the features from your own crate, as the examples do, so that tests build without one:
[features]
devnet-pre-alpha = ["ika-dwallet-anchor/devnet-pre-alpha"]
Then build with the network’s feature:
cargo build-sbf --tools-version v1.54 --arch v3 -- --features devnet-pre-alpha
A program built for one network refuses the dWallets of every other, because it calls only that network’s ika program. If a pre-alpha wipe moves the ika program to a new address, update the crate, rebuild with the feature, and redeploy or upgrade your program.
The context
#![allow(unused)]
fn main() {
use ika_dwallet_anchor::{CPI_AUTHORITY_SEED, DWalletContext, ID as IKA_PROGRAM_ID};
let dwallet_ctx = DWalletContext {
dwallet_program: ctx.accounts.dwallet_program.to_account_info(),
cpi_authority: ctx.accounts.cpi_authority.to_account_info(),
caller_program: ctx.accounts.program.to_account_info(),
cpi_authority_bump,
};
}
The methods and their order of arguments are those of the
Pinocchio crate. The accounts are &AccountInfo<'info>,
voucher_seeds is Option<&[&[u8]]>, transfer_dwallet takes &Pubkey, and each call returns
Anchor’s Result<()>. Every call refuses a dwallet_program that is not at IKA_PROGRAM_ID with
IncorrectProgramId.
Example: the voting program in Anchor
examples/voting/anchor/src/lib.rs is the voting program written with Anchor. Its
accounts struct for a vote states most of the bindings from
Integrator Invariants as constraints:
#![allow(unused)]
fn main() {
#[derive(Accounts)]
#[instruction(proposal_id: [u8; 32], vote: bool, cpi_authority_bump: u8)]
pub struct CastVote<'info> {
#[account(mut, seeds = [b"proposal", proposal_id.as_ref()], bump)]
pub proposal: Account<'info, Proposal>,
// One vote record per voter, at the canonical bump.
#[account(
init,
payer = payer,
space = 8 + VoteRecord::INIT_SPACE,
seeds = [b"vote", proposal_id.as_ref(), voter.key().as_ref()],
bump,
)]
pub vote_record: Account<'info, VoteRecord>,
// The council of the proposal's dWallet. The voter must be a member.
#[account(
seeds = [b"council", proposal.dwallet.as_ref()],
bump = council.bump,
constraint = council.members.contains(&voter.key()) @ VotingError::NotAMember,
)]
pub council: Account<'info, Council>,
pub voter: Signer<'info>,
#[account(mut)]
pub payer: Signer<'info>,
pub system_program: Program<'info, System>,
/// CHECK: the DWalletCoordinator of the ika program.
pub coordinator: UncheckedAccount<'info>,
/// CHECK: the voucher to create, at this program's PDA for the proposal.
#[account(mut, seeds = [b"signature_voucher", proposal_id.as_ref()], bump = proposal.signature_voucher_bump)]
pub signature_voucher: UncheckedAccount<'info>,
/// CHECK: must be the proposal's dWallet.
#[account(address = proposal.dwallet @ VotingError::DWalletMismatch)]
pub dwallet: UncheckedAccount<'info>,
/// CHECK: this program's account.
pub program: UncheckedAccount<'info>,
/// CHECK: this program's CPI authority.
pub cpi_authority: UncheckedAccount<'info>,
/// CHECK: the ika program.
pub dwallet_program: UncheckedAccount<'info>,
}
}
When the quorum is reached, the handler issues the voucher:
#![allow(unused)]
fn main() {
let voucher_seeds: &[&[u8]] = &[
b"signature_voucher",
proposal_id.as_ref(),
&[proposal.signature_voucher_bump],
];
dwallet_ctx.issue_signature_voucher(
&ctx.accounts.coordinator.to_account_info(),
&ctx.accounts.signature_voucher.to_account_info(),
&ctx.accounts.dwallet.to_account_info(),
&ctx.accounts.payer.to_account_info(),
&ctx.accounts.system_program.to_account_info(),
proposal.message_digest,
[0u8; 32],
proposal.signature_scheme,
None,
Some(proposal.user_pubkey),
Some(voucher_seeds),
)?;
}
Anchor needs every account of an instruction on every call. So, unlike the Pinocchio version,
the Anchor cast_vote takes the six accounts of the CPI on every vote, not only on the vote that
reaches the quorum.
Reading the dWallet’s owner
The ika program’s accounts are not Anchor accounts: they have a two-byte header, not Anchor’s
eight-byte discriminator. Read them by hand. The example’s create_council checks the owner
like this:
#![allow(unused)]
fn main() {
#[account(owner = IKA_PROGRAM_ID @ VotingError::InvalidDWalletAccount)]
pub dwallet: UncheckedAccount<'info>,
}
#![allow(unused)]
fn main() {
let dwallet_data = ctx.accounts.dwallet.try_borrow_data()?;
require!(dwallet_data.first() == Some(&97), VotingError::InvalidDWalletAccount);
let stored_owner = dwallet_data
.get(2..)
.and_then(|tail| tail.first_chunk::<32>())
.ok_or(VotingError::InvalidDWalletAccount)?;
require!(*stored_owner == ctx.accounts.owner.key().to_bytes(), VotingError::NotDWalletOwner);
}
The constraint compares the account’s owner with IKA_PROGRAM_ID, the ika program of the network
the program was built for, never with a program account the caller passed. See
invariant 2.
Examples
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
Two complete examples show a Solana program that controls a dWallet:
| Example | What decides a signature |
|---|---|
| Voting | A council votes on a message. When yes votes reach the quorum, the program issues a voucher. |
| Multisig | Fixed members approve a message. When approvals reach the threshold, the program issues a voucher. |
Each example binds its governance to the one dWallet it controls. Integrator Invariants explains why that matters.
What each example contains
examples/<name>/
├── pinocchio/ the program, written with Pinocchio, with Mollusk and LiteSVM tests
├── native/ the same program with plain solana-program, with the same tests
├── anchor/ the same program with Anchor, with LiteSVM tests
└── e2e/ the end-to-end demo in TypeScript, run with Bun
The multisig example also has react/, a page that runs the multisig flow in a browser with a
connected wallet.
The demos share their common steps in examples/_shared/. Each demo’s own file is then only its
governance story.
How every demo runs
The demos use the SDK as an app does, in mock mode for the pre-alpha:
- Make a user. The demo makes new user keys, registers the encryption key on Solana, and opens a gas deposit for the user’s request key.
- Create a dWallet. The demo asks the network for a dWallet, accepts the user’s share on Solana, and waits until the dWallet is active. The payer’s wallet owns it.
- Create the governance. The council or the multisig is an account of the example program, keyed by the dWallet’s address. The dWallet’s owner signs its creation, so this happens before the transfer.
- Transfer the dWallet to the example program’s CPI authority.
- Propose a message. A member creates the proposal. It names the user’s request key as the key allowed to ask for the signature.
- Approve it. Members vote or approve. The approval that reaches the quorum or threshold makes the program issue the signature voucher through a CPI, in the same transaction.
- Sign. The demo takes a presign and sends the sign request, naming the voucher. The network reads the voucher on Solana for itself, returns the signature, and writes it into the voucher account.
- Check. The demo checks that the signature it got back equals the one written on Solana, and that it verifies under the dWallet’s public key.
Running them
The demos run against the devnet pre-alpha by default. You need:
- a devnet keypair with about 1 SOL, from https://faucet.solana.com. Deploying an example program needs most of it, and closing the program afterwards returns it;
- the example program built and deployed to devnet;
- Node.js 22.12 or later and pnpm, or Bun, with this repository installed (
pnpm install && pnpm buildat its root); - a Rust toolchain with
cargo build-sbf, to build the program.
Build and deploy the Pinocchio variant of an example:
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/voting/pinocchio/Cargo.toml \
-- --features devnet-pre-alpha
solana program deploy -u devnet --keypair <your-keypair.json> target/deploy/ika_example_voting_pinocchio.so
The devnet-pre-alpha feature builds the program for the devnet pre-alpha’s ika program. A
program built without it refuses every devnet dWallet. The deploy prints the program id. Each example’s end-to-end page shows how to run its demo with that
id. When you are done, solana program close <program id> -u devnet --keypair <your-keypair.json> --bypass-warning returns the program’s rent. A closed program’s address cannot be used again.
The program tests run in-process, with no network:
cargo test -p ika-example-voting-pinocchio --test litesvm
cargo test -p ika-example-multisig --test litesvm
Voting dWallet: Overview
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
Overview
A governance program where a dWallet is placed under a council — a fixed member list with a quorum, created by the dWallet’s owner before the dWallet is handed to the program. Council members create proposals referencing the council’s dWallet and cast yes/no votes; when the quorum of yes votes is reached, the program CPI-calls issue_signature_voucher on the dWallet program to authorize signing.
Use case: DAO governance, treasury management, group signing authorization.
The council is not decoration: the dWallet program authenticates a program by one CPI authority PDA per program, so every dWallet handed to this program is controlled by the program as a whole. The per-dWallet council (and the dWallet check at quorum) is what stops one group’s proposal from issuing a voucher on another group’s dWallet. See Integrator Invariants.
Program Design
Accounts
| Account | Seeds | Size | Description |
|---|---|---|---|
| Council | ["council", dwallet] | 361 bytes | Members and quorum for one dWallet — exactly one per dWallet |
| Proposal | ["proposal", proposal_id] | 196 bytes | Stores vote counts, quorum (from the council), message digest, dWallet reference |
| VoteRecord | ["vote", proposal_id, voter] | 69 bytes | Prevents double voting — one per voter per proposal |
Instructions
| Disc | Instruction | Description |
|---|---|---|
0 | CreateProposal | A council member creates a proposal (message digest, signer key) for the council’s dWallet |
1 | CastVote | A council member records a vote; when quorum reached, CPI-issues a signature voucher on the proposal’s dWallet |
2 | CreateCouncil | The dWallet’s current owner fixes members and quorum for that dWallet |
Council Layout (361 bytes)
disc(1) + version(1) + dwallet(32) + quorum(4) + member_count(2) + bump(1) + members(32*10)
Proposal Layout (196 bytes)
disc(1) + version(1) + proposal_id(32) + dwallet(32) + message_digest(32) +
user_pubkey(32) + signature_scheme(2) + creator(32) + yes_votes(4) +
no_votes(4) + quorum(4) + status(1) + signature_voucher_bump(1) +
bump(1) + _reserved(16)
Key Offsets
| Field | Offset | Size | Type |
|---|---|---|---|
| dwallet | 34 | 32 | pubkey |
| signature_scheme | 130 | 2 | u16 LE (5 = EdDSA/SHA-512) |
| yes_votes | 164 | 4 | u32 LE |
| no_votes | 168 | 4 | u32 LE |
| quorum | 172 | 4 | u32 LE |
| status | 176 | 1 | 0=Open, 1=Approved |
CPI Flow
When yes_votes >= quorum, the program:
- Reads message digest, user pubkey, and signature scheme from the Proposal account
- Checks that the dWallet account passed for the CPI is the proposal’s dWallet
- Constructs a
DWalletContextwith the CPI authority PDA - Calls
ctx.issue_signature_voucher(...), which creates aSignatureVoucherat the program’s PDA["signature_voucher", proposal_id]; the program signs for that PDA with its seeds. The voucher’s signing key is the proposal’suser_pubkey, and its owner is the program’s CPI authority - Sets proposal status to Approved
The caller then sends a gRPC Sign request to obtain the signature. That request names the voucher’s address: validators read this SignatureVoucher themselves and vote on what they see.
E2E Flow
1. Make a user → new keys, encryption key registered, gas deposit opened
2. gRPC DKG → dWallet created on-chain; the user accepts the share; owner = the payer
3. Create council → quorum=3, members Alice/Bob/Charlie (signed by the payer, still the owner)
4. Transfer ownership → the program's CPI authority owns the dWallet
5. Create proposal → Alice proposes the message; user_pubkey = the user's request key
6. Cast 3 YES votes → the last vote issues the signature voucher through a CPI
7. gRPC presign → take a presign
8. gRPC sign → the 64-byte Ed25519 signature, also written into the voucher
The proposal’s user_pubkey is the key allowed to send the sign request. With the SDK, that is the
user’s request key (ikaClient.getRequestPublicKey(keys)), not the user’s wallet.
Testing
# from the repository root
# Mollusk (instruction-level) + LiteSVM (CPI path against the real dWallet program)
cargo test -p ika-example-voting-pinocchio
cargo test -p ika-example-voting-native
cargo test -p ika-example-voting-anchor
# TypeScript E2E, against the devnet pre-alpha (see the E2E Demo page)
cd examples && bun install
PAYER_KEYPAIR=<your-keypair.json> bun voting/e2e/main.ts 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv <VOTING_ID>
Source Files
- Pinocchio:
examples/voting/pinocchio/src/lib.rs - Native:
examples/voting/native/src/lib.rs - Anchor:
examples/voting/anchor/src/lib.rs - TypeScript E2E:
examples/voting/e2e/main.ts
Building the Voting Program
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
What You’ll Learn
- How to define on-chain account layouts for councils, proposals and vote records
- How to implement the CPI authority pattern for dWallet control — and bind each dWallet to its own governance
- How quorum detection issues a signature voucher via CPI
- How to prevent double voting using PDA-based vote records
Architecture
dWallet owner ──► CreateCouncil (members, quorum) ──► Council PDA ["council", dwallet]
──► transfer ownership to CPI PDA
Member 1 ──► CastVote ──┐
Member 2 ──► CastVote ──┤
Member 3 ──► CastVote ──┼──► Quorum? ──► dwallet == proposal.dwallet? ──► issue_signature_voucher CPI ──► SignatureVoucher
│ │
└── VoteRecord PDAs (prevent double vote) ▼
gRPC Sign request
│
▼
64-byte signature
1. Account Layouts
Council PDA (["council", dwallet]) — 361 bytes
#![allow(unused)]
fn main() {
// Header
discriminator: u8, // offset 0, always 3
version: u8, // offset 1, always 1
// Fields
dwallet: [u8; 32], // offset 2 — the dWallet this council governs
quorum: u32, // offset 34 (LE)
member_count: u16, // offset 38 (LE), 1..=10
bump: u8, // offset 40 — canonical bump of this PDA
members: [[u8; 32]; 10], // offset 41 — first `member_count` entries valid
}
Proposal PDA (["proposal", proposal_id]) — 196 bytes
#![allow(unused)]
fn main() {
// Header
discriminator: u8, // offset 0, always 1
version: u8, // offset 1, always 1
// Fields
proposal_id: [u8; 32], // offset 2
dwallet: [u8; 32], // offset 34 — the council's dWallet
message_digest: [u8; 32], // offset 66 — keccak256 of the message to sign
user_pubkey: [u8; 32], // offset 98 — key allowed to call gRPC Sign
signature_scheme: u16, // offset 130 (LE) — DWalletSignatureScheme, 5 = EdDSA/SHA-512
creator: [u8; 32], // offset 132
yes_votes: u32, // offset 164 (LE)
no_votes: u32, // offset 168 (LE)
quorum: u32, // offset 172 (LE) — copied from the council
status: u8, // offset 176 — 0=Open, 1=Approved
signature_voucher_bump: u8, // offset 177
bump: u8, // offset 178
_reserved: [u8; 16], // offset 179
}
VoteRecord PDA (["vote", proposal_id, voter]) — 69 bytes
#![allow(unused)]
fn main() {
discriminator: u8, // offset 0, always 2
version: u8, // offset 1
voter: [u8; 32], // offset 2
proposal_id: [u8; 32], // offset 34
vote: u8, // offset 66 — 1=yes, 0=no
bump: u8, // offset 67
}
2. CreateCouncil Instruction (disc = 2)
Signed by the dWallet’s current owner, before the ownership is transferred to the CPI PDA. The program reads the DWallet account (owner = dWallet program, discriminator 97, owner at offset 2) and requires the signer to be that owner; the council is created at the canonical ["council", dwallet] PDA, so there is exactly one per dWallet.
Data: [quorum(4), member_count(2), members(32 * member_count)]
Accounts:
| # | Account | Flags | Description |
|---|---|---|---|
| 0 | Council PDA | writable | Created via invoke_signed |
| 1 | dWallet | readonly | The dWallet account on the dWallet program |
| 2 | dWallet Program | readonly | Must be the ika program (ID of the CPI crate), executable, and the dWallet account’s owner |
| 3 | Owner | signer | The dWallet’s current owner |
| 4 | Payer | writable, signer | Pays rent |
| 5 | System Program | readonly | For PDA creation |
Rejects: quorum outside 1..=member_count, more than 10 members, duplicate members, a signer that is not the owner, a dWallet program account that is not the ika program, a dWallet account the ika program does not own, a council address other than the canonical PDA.
3. CreateProposal Instruction (disc = 0)
Data: [proposal_id(32), message_digest(32), user_pubkey(32), signature_scheme(2), signature_voucher_bump(1), bump(1)] = 100 bytes
Accounts:
| # | Account | Flags | Description |
|---|---|---|---|
| 0 | Proposal PDA | writable | Created via invoke_signed |
| 1 | Council PDA | readonly | The council of the dWallet |
| 2 | dWallet | readonly | The dWallet account on the dWallet program |
| 3 | Creator | signer | Must be a council member |
| 4 | Payer | writable, signer | Pays rent |
| 5 | System Program | readonly | For PDA creation |
The council is verified (program-owned, council discriminator, dwallet field equals the passed dWallet, address equals ["council", dwallet, bump]) and the creator must be one of its members. The proposal’s quorum is the council’s.
4. CastVote Instruction (disc = 1)
Data: [proposal_id(32), vote(1), vote_record_bump(1), cpi_authority_bump(1)] = 35 bytes
Base accounts (always required):
| # | Account | Flags |
|---|---|---|
| 0 | Proposal PDA | writable |
| 1 | VoteRecord PDA | writable |
| 2 | Council PDA | readonly |
| 3 | Voter | signer (must be a council member) |
| 4 | Payer | writable, signer |
| 5 | System Program | readonly |
CPI accounts (when quorum will be reached):
| # | Account | Flags |
|---|---|---|
| 6 | DWalletCoordinator PDA | readonly |
| 7 | SignatureVoucher PDA (["signature_voucher", proposal_id], this program’s) | writable |
| 8 | dWallet | readonly — must be the proposal’s dWallet |
| 9 | Voting Program | readonly |
| 10 | CPI Authority PDA | readonly |
| 11 | dWallet Program | readonly |
5. The CPI Call
When yes_votes >= quorum, the program:
#![allow(unused)]
fn main() {
// The CPI authority PDA is shared by every dWallet this program controls:
// only the proposal's own dWallet may get a voucher.
if dwallet.address().as_array() != &proposal_dwallet {
return Err(VotingError::DWalletMismatch.into());
}
let ctx = DWalletContext {
dwallet_program,
cpi_authority,
caller_program,
cpi_authority_bump,
};
// The voucher is this program's PDA for the proposal, so the program signs
// its creation with the PDA's seeds.
let voucher_bump_byte = [signature_voucher_bump];
let voucher_seeds = [
Seed::from(b"signature_voucher" as &[u8]),
Seed::from(proposal_id.as_ref()),
Seed::from(voucher_bump_byte.as_ref()),
];
ctx.issue_signature_voucher(
coordinator, signature_voucher, dwallet, payer, system_program,
message_digest, [0u8; 32] /* no metadata */, signature_scheme,
None /* owner: this program's CPI authority */,
Some(user_pubkey) /* signing key */,
Some(&voucher_seeds),
)?;
prop_data[PROP_STATUS] = STATUS_APPROVED;
}
The DWalletContext signs via invoke_signed with seeds ["__ika_cpi_authority", &[bump]], proving the voting program authorized this signing request. The dWallet program checks that the program controls the dWallet; the program itself checks that it is the right dWallet.
Source Code
| Framework | Path |
|---|---|
| Pinocchio | examples/voting/pinocchio/src/lib.rs |
| Native | examples/voting/native/src/lib.rs |
| Anchor | examples/voting/anchor/src/lib.rs (address = proposal.dwallet and council seeds constraints do the binding; the voucher account is unchecked, and the program signs for ["signature_voucher", proposal_id] with the stored bump, so the dWallet program refuses any other account in that slot as unsigned) |
Testing the Voting Program
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
What You’ll Learn
- How to write Mollusk instruction-level tests for dWallet programs
- How to build and verify account data at specific byte offsets
- Testing error conditions with exact error codes (non-member, wrong council, wrong dWallet, double vote, closed proposal)
- Testing the CPI path — and the confused-deputy attack — with LiteSVM against the real dWallet program
Test Matrix (Mollusk)
| Test | Instruction | Expected Result |
|---|---|---|
test_create_council_success | CreateCouncil | PDA created at the canonical address with dwallet, quorum, members |
test_create_council_rejects_non_owner | CreateCouncil | Custom(2) NotDWalletOwner |
test_create_council_rejects_dwallet_not_owned_by_dwallet_program | CreateCouncil | Custom(4) InvalidDWalletAccount |
test_create_council_rejects_quorum_above_member_count | CreateCouncil | Custom(5) InvalidQuorum |
test_create_council_rejects_duplicate_member | CreateCouncil | Custom(6) DuplicateMember |
test_create_council_rejects_non_canonical_address | CreateCouncil | Custom(3) InvalidCouncil |
test_create_proposal_success | CreateProposal | PDA created; quorum copied from the council |
test_create_proposal_rejects_non_member | CreateProposal | Custom(1) NotAMember |
test_create_proposal_rejects_council_of_another_dwallet | CreateProposal | Custom(3) InvalidCouncil |
test_create_proposal_rejects_forged_council_account | CreateProposal | Custom(3) InvalidCouncil |
test_create_proposal_already_exists | CreateProposal | Fails (account in use) |
test_cast_vote_yes_success / _no_success | CastVote | counters incremented, status=Open |
test_cast_vote_rejects_non_member | CastVote | Custom(1) NotAMember |
test_cast_vote_rejects_council_of_another_dwallet | CastVote | Custom(3) InvalidCouncil |
test_cast_vote_at_quorum_rejects_wrong_dwallet | CastVote | Custom(0) DWalletMismatch, before any CPI |
test_cast_vote_double_vote_fails | CastVote | Fails (VoteRecord exists) |
test_cast_vote_closed_proposal_fails | CastVote | Custom(7) ProposalClosed |
The Anchor variant reports the same conditions as Anchor errors (6003 NotAMember, 6004 DWalletMismatch, 6005 NotDWalletOwner, …; a council at the wrong PDA fails Anchor’s ConstraintSeeds, 2006).
Test Matrix (LiteSVM)
| Test | Expected Result |
|---|---|
test_voting_full_lifecycle | council → transfer → proposal → 3 votes → SignatureVoucher created with the right fields |
test_voting_below_quorum_no_voucher | no SignatureVoucher before quorum |
test_no_votes_dont_trigger_quorum | “no” votes never issue a voucher |
test_outsider_cannot_vote_or_recreate_council | outsider vote / proposal NotAMember; council (re)creation NotDWalletOwner |
test_quorum_cannot_be_redirected_to_another_councils_dwallet | attacker’s own council reaching quorum with the victim’s dWallet as CPI target fails DWalletMismatch; no voucher for the victim |
test_create_proposal_refuses_a_non_canonical_voucher_bump | a proposal naming a voucher bump other than the canonical one is refused |
test_quorum_vote_refuses_a_substituted_voucher_account | the quorum vote refuses a voucher account other than the proposal’s PDA |
test_a_member_cannot_vote_twice_with_a_second_bump | a second vote with another valid vote-record bump fails InvalidBump (11); no second record, the count stays 1 |
test_create_proposal_refuses_a_non_canonical_proposal_bump | a proposal at a non-canonical bump fails InvalidBump; nothing is written there |
test_dwallet_context_refuses_a_program_that_is_not_ika | at quorum, a program other than the ika program in the dWallet-program slot fails IncorrectProgramId; no voucher |
Three tests guard attacks that would otherwise work:
- The redirect test: with the dWallet check removed from the program, the attacker’s transaction succeeds and issues a voucher on the victim’s dWallet.
- The second-bump test: with the canonical-bump check removed, the member’s second vote succeeds and counts twice.
- The ika-program test: with
DWalletContext’s program check removed, the call goes to whatever program the caller named.
Each of them was run against the program with its check removed, and failed there.
The Pinocchio and native variants run all ten. The Anchor variant runs five: the full lifecycle, below quorum, outsider, redirect and ika-program tests. It needs no bump tests, because Anchor derives every canonical bump itself.
Running Tests
# from the repository root
# SBF builds the tests load (the ika program itself is shipped in bin/)
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/voting/pinocchio/Cargo.toml
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/voting/native/Cargo.toml
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/voting/anchor/Cargo.toml
# Mollusk + LiteSVM
cargo test -p ika-example-voting-pinocchio
cargo test -p ika-example-voting-native
cargo test -p ika-example-voting-anchor
Key Patterns
Building Test Account Data
Tests pre-populate account data with exact byte layouts:
#![allow(unused)]
fn main() {
fn build_council_data(dwallet: &Pubkey, quorum: u32, members: &[Pubkey], bump: u8) -> Vec<u8> {
let mut data = vec![0u8; COUNCIL_LEN]; // 361 bytes
data[0] = COUNCIL_DISCRIMINATOR; // 3
data[1] = 1; // version
data[CN_DWALLET..CN_DWALLET + 32].copy_from_slice(dwallet.as_ref());
data[CN_QUORUM..CN_QUORUM + 4].copy_from_slice(&quorum.to_le_bytes());
// ... member_count, bump, members
data
}
}
A fixture() helper builds a dWallet address, a stand-in dWallet program, an owner and a 3-member council around them so each test states only what it changes.
Asserting Exact Error Codes
#![allow(unused)]
fn main() {
fn assert_custom_error(result: &InstructionResult, code: u32) {
match &result.program_result {
ProgramResult::Failure(err) => assert_eq!(*err, ProgramError::Custom(code)),
other => panic!("expected Custom({code}) failure, got {other:?}"),
}
}
}
assert!(result.program_result.is_err()) is not enough for a negative test: the instruction may fail for an unrelated reason (a fake token program, a wrong bump) while the check you meant to test no longer fires.
Testing Double Vote Prevention
The VoteRecord PDA prevents double voting. If the PDA already exists, CreateAccount fails:
#![allow(unused)]
fn main() {
// Pre-populate VoteRecord (voter already voted)
let existing_vr = build_vote_record_data(&voter, &proposal_id, 1, vr_bump);
let result = mollusk.process_instruction(&ix, &[
(proposal_pda, program_account(&program_id, proposal_data)),
(vote_record_pda, program_account(&program_id, existing_vr)), // exists!
// ...
]);
assert!(matches!(result.program_result, ProgramResult::Failure(_)));
}
Source
- Pinocchio tests:
examples/voting/pinocchio/tests/{mollusk,litesvm}.rs - Native tests:
examples/voting/native/tests/{mollusk,litesvm}.rs - Anchor tests:
examples/voting/anchor/tests/{mollusk,litesvm}.rs
E2E Demo
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The voting demo runs the whole story against a live network: a council of three votes on a message, and the network signs it with a dWallet the council controls. It uses the SDK as an app does, in mock mode for the pre-alpha.
The demo is examples/voting/e2e/main.ts, run with Bun.
Before you run it
-
Get a devnet keypair with about 1 SOL from https://faucet.solana.com.
-
Build the voting program and deploy it to devnet, as the examples overview shows. Note the program id the deploy prints.
-
Install and build the SDK and the examples once, from the repository root:
pnpm install pnpm build
Running the TypeScript demo
cd examples
PAYER_KEYPAIR=<your-keypair.json> \
bun voting/e2e/main.ts 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv <voting program id>
The first argument is the ika program, and the second is your voting program. The environment variables:
| Variable | Default | What it is |
|---|---|---|
PAYER_KEYPAIR | ~/.config/solana/id.json | The keypair that pays for every transaction and owns the dWallet. |
RPC_URL | https://api.devnet.solana.com | The Solana RPC. |
GRPC_URL | https://solana-alpha-dev-1.ika-network.net | The ika network. An https:// URL is gRPC-Web. http://host:port is plaintext gRPC, for a mock on your machine. |
What the demo does
1/9 Make the payer a user: new keys, the encryption key registered on Solana,
and a gas deposit for the request key
2/9 Run a key generation over gRPC
3/9 Accept the user's share on Solana and wait until the dWallet is active
4/9 Create the council (quorum 3: Alice, Bob, Charlie), signed by the payer
while it still owns the dWallet
5/9 Transfer the dWallet to the voting program's CPI authority
6/9 Alice proposes the message
7/9 Three yes votes. The third reaches the quorum, and the program issues the
signature voucher in the same transaction
8/9 Take a presign from the network
9/9 Ask the network to sign, naming the voucher. Check that the signature is the
one written into the voucher account, and that it verifies under the
dWallet's public key
The order matters twice:
- The council must exist before the transfer. The dWallet’s owner signs
CreateCouncil, and after the transfer the owner is the program’s CPI authority, which only the program can sign for. - The voucher must be on Solana, finalized, before the sign request. The request names the voucher, and the network reads it on Solana for itself.
Expected output
═══ dWallet Voting E2E Demo (TypeScript) ═══
[1/9] Registering new keys and a gas deposit for the payer...
✓ Encryption key registered, gas deposit created
[2/9] Running a distributed key generation over gRPC...
[3/9] Accepting the user's share and waiting for the dWallet...
✓ dWallet account: ...
[4/9] Creating the council (quorum 3)...
✓ Council: ...
[5/9] Handing the dWallet to the voting program...
✓ Owner is now the voting program's signing address: ...
[6/9] A council member proposes the message...
✓ Proposal: ...
[7/9] Vote 1/3: Alice votes yes...
✓ Alice voted yes
[7/9] Vote 2/3: Bob votes yes...
✓ Bob voted yes
[7/9] Vote 3/3: Charlie votes yes...
✓ Charlie voted yes
✓ Proposal approved (3/3 yes)
✓ Voucher issued on chain: ...
[8/9] Taking a presign from the network...
✓ Presign allocated
[9/9] Asking the network to sign...
✓ The network returned a signature
✓ The same signature is committed in the voucher account
✓ The signature verifies under the dWallet's public key
═══ The demo ran to the end ═══
How the shared code is split
The TypeScript demo imports its common steps from examples/_shared/:
network.tsis the SDK side.connectToIkacreates theIkaClientin mock mode.newUsermakes the keys, registers the encryption key and opens the gas deposit.createDWalletruns the key generation, accepts the share and waits for the dWallet.takePresignandsignWithVouchertake a presign and sign under a voucher.chain.tsis the program side the SDK does not cover: the CPI authority’s address, the message digest the program stores, and waiting for the voucher on Solana.helpers.tshas the logging and the transaction sending.
The voting instructions themselves are in voting/e2e/instructions.ts.
Multisig dWallet: Overview
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
Overview
An M-of-N multisig program controlling a dWallet. The multisig is created for one dWallet by that dWallet’s owner (before the dWallet is handed to the program) with a fixed member list and threshold. Any member can propose transactions with message data stored on-chain for other members to inspect. Members approve or reject. When threshold approvals are reached, the program CPI-calls issue_signature_voucher on the multisig’s dWallet. A transaction proposed as a future sign gets issue_future_signature_voucher instead. When enough rejections accumulate (making approval impossible), the transaction is marked rejected.
Use case: Multi-party custody, organizational signing policies, timelocked operations.
The per-dWallet binding is what makes this a multisig for a dWallet rather than a multisig for the program: the dWallet program authenticates a program by one CPI authority PDA per program, so without the binding any multisig instance could reach any dWallet the program controls. See Integrator Invariants.
Program Design
Accounts
| Account | Seeds | Size | Description |
|---|---|---|---|
| Multisig | ["multisig", dwallet] | 363 bytes | Members list, threshold, tx counter — exactly one per dWallet |
| Transaction | ["transaction", multisig, tx_index_le] | 402 bytes | Message data, approval/rejection counts, status, future-sign flag |
| ApprovalRecord | ["approval", transaction, member] | 68 bytes | Prevents double voting — one per member per transaction |
Instructions
| Disc | Instruction | Description |
|---|---|---|
0 | CreateMultisig | The dWallet’s owner creates the multisig for that dWallet with members (up to 10) and threshold |
1 | CreateTransaction | A member proposes a transaction with message data stored on-chain |
2 | Approve | Approve; when threshold reached, CPI issue_signature_voucher on the multisig’s dWallet, or issue_future_signature_voucher for a future-sign transaction |
3 | Reject | Reject; when enough rejections, mark transaction as rejected |
Multisig Layout (363 bytes)
disc(1) + version(1) + dwallet(32) + threshold(u16) + member_count(u16) +
tx_index(u32) + bump(1) + members(32 * 10)
Transaction Layout (402 bytes)
disc(1) + version(1) + multisig(32) + tx_index(u32) + proposer(32) +
message_hash(32) + user_pubkey(32) + signature_scheme(u16) +
approval_count(u16) + rejection_count(u16) + status(1) +
signature_voucher_bump(1) + future_sign(1) + bump(1) +
message_data_len(u16) + message_data(256)
Key Offsets
| Account | Field | Offset | Size | Type |
|---|---|---|---|---|
| Multisig | dwallet | 2 | 32 | pubkey |
| Multisig | threshold | 34 | 2 | u16 LE |
| Multisig | member_count | 36 | 2 | u16 LE |
| Multisig | tx_index | 38 | 4 | u32 LE |
| Multisig | bump | 42 | 1 | u8 |
| Multisig | members | 43 | 320 | 10 x pubkey |
| Transaction | signature_scheme | 134 | 2 | u16 LE (5 = EdDSA/SHA-512) |
| Transaction | approval_count | 136 | 2 | u16 LE |
| Transaction | rejection_count | 138 | 2 | u16 LE |
| Transaction | status | 140 | 1 | 0=Active, 1=Approved, 2=Rejected |
| Transaction | signature_voucher_bump | 141 | 1 | u8 |
| Transaction | future_sign | 142 | 1 | 0 = signature voucher, 1 = future signature voucher |
| Transaction | bump | 143 | 1 | u8 |
| Transaction | message_data_len | 144 | 2 | u16 LE |
| Transaction | message_data | 146 | 256 | raw bytes |
Rejection Logic
A transaction is rejected when enough members reject that approval becomes impossible:
rejection_threshold = member_count - threshold + 1
For a 2-of-3 multisig: 3 - 2 + 1 = 2 rejections needed to reject.
CPI Flow
When approval_count >= threshold, the program:
- Checks that the dWallet account passed for the CPI is the multisig’s dWallet, before any CPI
- If
future_signis 0, callsctx.issue_signature_voucher(...). This creates theSignatureVoucherat the program’s PDA["signature_voucher", transaction], and the program signs for it with those seeds. The voucher’s signing key is the transaction’suser_pubkey, and its owner is the program’s CPI authority - If
future_signis 1, callsctx.issue_future_signature_voucher(...)instead. This creates aFutureSignatureVoucherat the same PDA. Its signing key is the transaction’suser_pubkey, and its owner is the proposer. The proposer later sets the key that completes the future sign, with the dWallet program’sSetVoucherSigningKeyinstruction - Sets transaction status to Approved
E2E Flow
1. Make a user → new keys, encryption key registered, gas deposit opened
2. gRPC DKG → dWallet created; the user accepts the share; owner = the payer
3. Create multisig → 2-of-3 with 3 member pubkeys, for this dWallet (signed by the payer)
4. Transfer ownership → the program's CPI authority owns the dWallet
5. Propose transaction → message stored on-chain; user_pubkey = the user's request key
6. Member 1 approves → approval_count = 1
7. Member 2 approves → approval_count = 2 = threshold → the CPI issues the voucher
8. gRPC presign → take a presign
9. gRPC sign → the 64-byte Ed25519 signature, also written into the voucher
10. Rejection → propose a 2nd transaction, 2 rejections → status = Rejected
React Frontend
A React frontend at examples/multisig/react/ does the same
thing from a browser: the user’s half of the protocol runs in the tab, the
dWallet is owned by the connected wallet, and every approval is a wallet
signature.
The page talks gRPC-Web to the devnet pre-alpha directly, through fetch, so it needs no proxy.
The E2E Demo page shows how to run it.
The page holds two kinds of key. The connected wallet owns the dWallet, pays for every transaction, and signs the multisig’s instructions. The user’s keys, made from a root seed in the tab, sign the gRPC requests. Those requests are charged to the gas deposit of their request key. The connected wallet creates that deposit, so it owns it, and only it can withdraw from it.
Testing
# from the repository root
# Mollusk + LiteSVM (all 3 framework variants)
cargo test -p ika-example-multisig # pinocchio
cargo test -p ika-example-multisig-native # native
cargo test -p ika-example-multisig-anchor # anchor (LiteSVM)
# TypeScript E2E, against the devnet pre-alpha (see the E2E Demo page)
cd examples && bun install
PAYER_KEYPAIR=<your-keypair.json> bun multisig/e2e/main.ts 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv <MULTISIG_ID>
Source Files
- Pinocchio:
examples/multisig/pinocchio/src/lib.rs - Native:
examples/multisig/native/src/lib.rs - Anchor:
examples/multisig/anchor/src/lib.rs - TypeScript E2E:
examples/multisig/e2e/main.ts - React:
examples/multisig/react/
Building the Multisig Program
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
What You’ll Learn
- How to design a multisig with fixed members and threshold approval, bound to one dWallet
- How to store transaction data on-chain for other signers to inspect
- How to implement both approval and rejection flows
- How to issue a future signature voucher, owned by the proposer, for a transaction proposed as a future sign
Architecture
dWallet owner ──► CreateMultisig (members, threshold) ──► Multisig PDA ["multisig", dwallet]
──► transfer ownership to CPI PDA
│
Member 1 ──► CreateTransaction (message data stored on-chain)
│
Member 1 ──► Approve ──┐
Member 2 ──► Approve ──┼──► threshold reached? ──► dwallet == multisig.dwallet? ──► future_sign == 0? ──► issue_signature_voucher CPI
Member 3 ──► Reject ──┘ future_sign == 1? ──► issue_future_signature_voucher CPI
│
Transaction = Approved
1. Account Layouts
Multisig PDA (["multisig", dwallet]) — 363 bytes
| Field | Offset | Size | Type |
|---|---|---|---|
| disc | 0 | 1 | always 1 |
| version | 1 | 1 | always 1 |
| dwallet | 2 | 32 | pubkey — the dWallet this multisig governs |
| threshold | 34 | 2 | u16 LE |
| member_count | 36 | 2 | u16 LE |
| tx_index | 38 | 4 | u32 LE (auto-increment) |
| bump | 42 | 1 | canonical PDA bump |
| members | 43 | 320 | 10 × 32-byte pubkeys |
Transaction PDA (["transaction", multisig, tx_index_le]) — 402 bytes
| Field | Offset | Size | Type |
|---|---|---|---|
| disc | 0 | 1 | always 2 |
| version | 1 | 1 | always 1 |
| multisig | 2 | 32 | pubkey |
| tx_index | 34 | 4 | u32 LE |
| proposer | 38 | 32 | pubkey |
| message_hash | 70 | 32 | keccak256 |
| user_pubkey | 102 | 32 | key allowed to call gRPC Sign |
| signature_scheme | 134 | 2 | u16 LE (DWalletSignatureScheme) |
| approval_count | 136 | 2 | u16 LE |
| rejection_count | 138 | 2 | u16 LE |
| status | 140 | 1 | 0=Active, 1=Approved, 2=Rejected |
| signature_voucher_bump | 141 | 1 | u8 (bump of the voucher PDA ["signature_voucher", transaction]) |
| future_sign | 142 | 1 | 0 = issue a signature voucher, 1 = issue a future signature voucher |
| bump | 143 | 1 | PDA bump |
| message_data_len | 144 | 2 | u16 LE |
| message_data | 146 | 256 | raw bytes |
ApprovalRecord PDA (["approval", transaction, member]) — 68 bytes
Prevents double voting. One per member per transaction.
2. Instructions
| Disc | Name | Description |
|---|---|---|
| 0 | CreateMultisig | The dWallet’s current owner sets members (up to 10) and threshold for that dWallet |
| 1 | CreateTransaction | A member proposes with message data stored on-chain |
| 2 | Approve | Vote yes; triggers CPI at threshold |
| 3 | Reject | Vote no; marks rejected when impossible to approve |
CreateMultisig takes the dWallet account and the dWallet program: the dWallet program account must be the ika program (ID of the CPI crate) and executable, the dWallet account must be owned by it, carry the DWallet discriminator (97), and its stored owner (offset 2) must be the signer. The multisig is created at the canonical ["multisig", dwallet] PDA, so there is exactly one per dWallet and it can only be created while the dWallet is still controlled by its user — once the owner is the CPI PDA nobody can sign for it.
3. Rejection Threshold
A transaction is rejected when enough members reject that approval becomes impossible:
rejection_threshold = member_count - threshold + 1
Example: 2-of-3 multisig → 3 - 2 + 1 = 2 rejections needed.
4. CPI Flow on Approval
When approval_count >= threshold:
#![allow(unused)]
fn main() {
// 0. Bind the CPI target — before any CPI. The CPI authority PDA is shared by
// every dWallet this program controls, so only the multisig's own dWallet
// may get a voucher.
if dwallet.address().as_array() != &multisig_dwallet {
return Err(MultisigError::DWalletMismatch.into());
}
// 1. Issue the voucher. It is this program's PDA for the transaction, so the
// program signs its creation with the PDA's seeds.
let voucher_bump_byte = [signature_voucher_bump];
let voucher_seeds = [
Seed::from(b"signature_voucher" as &[u8]),
Seed::from(tx_account.address().as_array().as_ref()),
Seed::from(voucher_bump_byte.as_ref()),
];
if future_sign {
// A future signature voucher, owned by the proposer. The proposer later
// sets the key that completes the future sign.
ctx.issue_future_signature_voucher(
coordinator, signature_voucher, dwallet, payer, system_program,
message_hash, [0u8; 32] /* no metadata */, signature_scheme,
Some(proposer_key) /* owner */,
Some(user_pubkey) /* signing key */,
Some(&voucher_seeds),
)?;
} else {
ctx.issue_signature_voucher(
coordinator, signature_voucher, dwallet, payer, system_program,
message_hash, [0u8; 32] /* no metadata */, signature_scheme,
None /* owner: this program's CPI authority */,
Some(user_pubkey) /* signing key */,
Some(&voucher_seeds),
)?;
}
// 2. Mark transaction as approved
tx_data[TX_STATUS] = STATUS_APPROVED;
}
CreateTransaction takes the future_sign flag as one byte after signature_voucher_bump. Only 0 and 1 are accepted; any other value fails with InvalidInstructionData.
The Anchor variant expresses the same binding as a constraint: #[account(address = multisig.dwallet)] on dwallet. Its future_sign field is a bool.
Source Code
| Framework | Path |
|---|---|
| Pinocchio | examples/multisig/pinocchio/src/lib.rs |
| Native | examples/multisig/native/src/lib.rs |
| Anchor | examples/multisig/anchor/src/lib.rs |
Testing the Multisig Program
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
Test Matrix (Mollusk)
Every negative test asserts the exact MultisigError code.
| Test | Instruction | Expected Result |
|---|---|---|
test_create_multisig_success | CreateMultisig | 2-of-3 with correct fields at the canonical PDA |
test_create_multisig_rejects_non_owner | CreateMultisig | Custom(3) NotDWalletOwner |
test_create_multisig_rejects_dwallet_not_owned_by_dwallet_program | CreateMultisig | Custom(4) InvalidDWalletAccount |
test_create_multisig_zero_threshold_fails | CreateMultisig | Custom(5) InvalidThreshold |
test_create_multisig_threshold_exceeds_members_fails | CreateMultisig | Custom(5) InvalidThreshold |
test_create_multisig_rejects_duplicate_member | CreateMultisig | Custom(6) DuplicateMember |
test_create_multisig_rejects_non_canonical_address | CreateMultisig | Custom(9) InvalidMultisig |
test_create_transaction_success | CreateTransaction | Message data stored, tx_index incremented |
test_create_transaction_rejects_a_future_sign_flag_other_than_0_or_1 | CreateTransaction | InvalidInstructionData |
test_create_transaction_non_member_fails | CreateTransaction | Custom(0) NotAMember |
test_create_transaction_rejects_forged_multisig_account | CreateTransaction | Custom(9) InvalidMultisig |
test_approve_success | Approve | approval_count incremented, still Active |
test_approve_double_vote_fails | Approve | ApprovalRecord already exists |
test_approve_non_member_fails | Approve | Custom(0) NotAMember |
test_approve_rejects_transaction_of_another_multisig | Approve | Custom(8) TransactionMismatch |
test_approve_at_threshold_rejects_wrong_dwallet | Approve | Custom(1) DWalletMismatch, before any CPI |
test_reject_success | Reject | rejection_count incremented, still Active |
test_reject_threshold_marks_rejected | Reject | 2nd rejection → status=Rejected |
test_reject_non_member_fails | Reject | Custom(0) NotAMember |
test_vote_on_closed_transaction_fails | Approve | Custom(7) TransactionNotActive |
All 20 tests run for both Pinocchio and Native variants.
Test Matrix (LiteSVM, real dWallet program)
| Test | Expected Result |
|---|---|
test_multisig_full_lifecycle | multisig → transfer → propose → 2 approvals → SignatureVoucher created |
test_multisig_issues_a_future_signature_voucher_owned_by_the_proposer | a transaction proposed as a future sign gets a FutureSignatureVoucher at the voucher PDA; its owner is the proposer and its signing key is the transaction’s user_pubkey |
test_outsider_cannot_approve_or_recreate_multisig | outsider approval NotAMember; multisig (re)creation NotDWalletOwner |
test_threshold_cannot_be_redirected_to_another_multisigs_dwallet | attacker’s own 1-of-1 multisig reaching threshold with the victim’s dWallet as CPI target fails DWalletMismatch; no voucher for the victim |
test_a_member_cannot_approve_twice_with_a_second_bump | a second approval with another valid approval-record bump fails InvalidBump (12); the count stays 1 |
test_a_member_cannot_reject_twice_with_a_second_bump | the same for a rejection |
test_create_transaction_refuses_a_non_canonical_transaction_bump | a transaction at a non-canonical bump fails InvalidBump; nothing is written there |
The three bump tests failed against the program without the canonical-bump check, and pass with it. The Pinocchio and native variants run all seven. The Anchor variant runs the first four: Anchor derives every canonical bump itself.
Running Tests
# from the repository root
# SBF builds the tests load (the ika program itself is shipped in bin/)
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/multisig/pinocchio/Cargo.toml
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/multisig/native/Cargo.toml
cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/multisig/anchor/Cargo.toml
# Mollusk + LiteSVM
cargo test -p ika-example-multisig
cargo test -p ika-example-multisig-native
cargo test -p ika-example-multisig-anchor
Source
- Pinocchio:
examples/multisig/pinocchio/tests/{mollusk,litesvm}.rs - Native:
examples/multisig/native/tests/{mollusk,litesvm}.rs - Anchor:
examples/multisig/anchor/tests/litesvm.rs
E2E Demo
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The multisig demo runs a 2-of-3 multisig against a live network. Two members approve a message, and the network signs it with the dWallet the multisig controls. Then a second message is rejected, and never reaches the network. The demo uses the SDK as an app does, in mock mode for the pre-alpha.
| Language | File |
|---|---|
| TypeScript, run with Bun | examples/multisig/e2e/main.ts |
| Browser, React | examples/multisig/react/ |
Before you run it
-
Get a devnet keypair with about 1 SOL from https://faucet.solana.com.
-
Build the multisig program and deploy it to devnet. The Pinocchio variant builds to
target/deploy/ika_example_multisig.so:cargo build-sbf --tools-version v1.54 --arch v3 --manifest-path examples/multisig/pinocchio/Cargo.toml \ -- --features devnet-pre-alpha solana program deploy -u devnet --keypair <your-keypair.json> target/deploy/ika_example_multisig.so -
For the demo and the React page, install and build this repository once, as the voting demo shows.
Running the TypeScript demo
cd examples
PAYER_KEYPAIR=<your-keypair.json> \
bun multisig/e2e/main.ts 8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv <multisig program id>
It reads the same environment variables as the voting demo: PAYER_KEYPAIR, RPC_URL and
GRPC_URL, with the devnet pre-alpha as the default.
Running the React page
cd examples/multisig/react
VITE_DWALLET_PROGRAM_ID=8siGnE3tCZbu4LTuX8QoBPErvWeGBF4pRSJDnaGdHyQv \
VITE_MULTISIG_PROGRAM_ID=<multisig program id> \
pnpm dev
The page needs a browser wallet, such as Phantom, set to devnet and holding devnet SOL. It talks
gRPC-Web to the pre-alpha directly, so it needs no proxy. VITE_RPC_URL and VITE_GRPC_WEB_URL pick
another cluster or network.
The page keeps the user’s root seed in memory only. Reloading the page loses the keys, and with them the user’s share of the dWallet the page made. A real app keeps the root seed, encrypted, or derives it from something the user holds.
What the demo does
1/9 Make the payer a user: new keys, the encryption key registered on Solana,
and a gas deposit for the request key
2/9 Run a key generation over gRPC
3/9 Accept the user's share on Solana and wait until the dWallet is active
4/9 Create the 2-of-3 multisig, signed by the payer while it still owns the dWallet
5/9 Transfer the dWallet to the multisig program's CPI authority
6/9 A member proposes the message
7/9 Two members approve. The second approval reaches the threshold, and the
program issues the signature voucher in the same transaction
8/9 Take a presign and ask the network to sign, naming the voucher. Check that the
signature is the one written into the voucher account, and that it verifies
under the dWallet's public key
9/9 Propose a second message and reject it with two members. No voucher is
issued, so the network is never asked
Expected output
═══ dWallet Multisig E2E Demo (TypeScript) ═══
[1/9] Registering new keys and a gas deposit for the payer...
✓ Encryption key registered, gas deposit created
[2/9] Running a distributed key generation over gRPC...
[3/9] Accepting the user's share and waiting for the dWallet...
✓ dWallet account: ...
[4/9] Creating the 2-of-3 multisig...
✓ Multisig: ...
[5/9] Handing the dWallet to the multisig program...
✓ Owner is now the multisig program's signing address: ...
[6/9] A member proposes the message...
✓ Transaction: ...
[7/9] Approval 1/2: member 1 approves...
✓ Member 1 approved
[7/9] Approval 2/2: member 2 approves...
✓ Member 2 approved
✓ The multisig approved the transaction
✓ Voucher issued on chain: ...
[8/9] Taking a presign from the network, then asking it to sign...
✓ Presign allocated
✓ The network returned a signature
✓ The same signature is committed in the voucher account
✓ The signature verifies under the dWallet's public key
[9/9] Proposing a second message and rejecting it...
✓ The second message was rejected and never reached the network
═══ The demo ran to the end ═══
The shared code is split as in the voting demo.
Instruction Reference
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
This page lists the ika program’s dWallet instructions. The first byte of an instruction’s data
is the instruction’s number. The rest is the instruction’s own data, and it must be exactly the
length its layout gives. A shorter or longer instruction is refused with
InvalidInstructionData.
The SDKs build every instruction a user sends. The CPI crates build the ones a program sends. You need this page to build an instruction yourself, or to read one in a transaction.
Who sends what
Three kinds of signer send dWallet instructions.
- A user or a program. These are the instructions an integrator sends: vouchers, ownership, deposits, encryption keys and accepts. They are described in full below.
- The network. The network writes every result to the chain with its own transactions,
signed by a network key (
NetworkEncryptionKey.noa_public_key). They are listed in Network instructions. - The pauser. One key may pause and unpause. See Pauses.
| Number | Instruction | Sent by |
|---|---|---|
| 129 | TransferOwnership | the dWallet’s owner |
| 130 | CommitNetworkDkg | the network |
| 131 | CommitNetworkKeyReconfiguration | the network |
| 132 | CommitDWallet | the network |
| 134 | CommitEncryptedUserSecretKeyShare | the network |
| 135 | CommitPublicUserSecretKeyShare | the network |
| 136 | CreateDeposit | anyone, with a proof from the request key |
| 137 | TopUp | anyone |
| 138 | SettleGas | the network |
| 140 | CommitSignature | the network |
| 141 | RequestWithdraw | the deposit’s owner |
| 143 | Initialize | the program’s upgrade authority, once at deployment |
| 144 | AdvanceEpoch | the network |
| 145 | SettleGasWithoutDelivery | the network |
| 147 | Pause | the pauser or the network |
| 148 | Unpause | the pauser or the network |
| 149 | SetPauser | the network |
| 150 | SettleGasCharge | the network |
| 151 | PauseSigningParameter | the pauser or the network |
| 152 | UnpauseSigningParameter | the pauser or the network |
| 153 | RegisterEncryptionKey | anyone, with a signature from the holder |
| 156 | IssueSignatureVoucher | the dWallet’s owner |
| 157 | SetVoucherSigningKey | the voucher’s owner |
| 158 | RevokeSignatureVoucher | the voucher’s owner |
| 159 | TransferSignatureVoucher | the voucher’s owner |
| 161 | IssueFutureSignatureVoucher | the dWallet’s owner |
| 163 | CommitPartialUserSignature | the network |
| 164 | SetChainIdentifier | the network |
| 165 | AcceptEncryptedUserShare | anyone, with a signature from the holder |
| 166 | TransferGasDeposit | the deposit’s owner |
| 167 | SettleGasWithdrawal | the network |
| 168 | SetMinFirstDeposit | the network |
| 169 | SetMinBalance | the network |
| 170 | SetDepositFee | the network |
| 228 | EmitEvent | the program itself, to emit an event |
Numbers 128, 133, 139, 142, 146, 154, 155, 160 and 162 belonged to instructions that were removed. They are refused, and they are never given to another instruction.
Signer mode and program mode
The instructions that an owner sends work in two modes.
- Signer mode. The owner is a wallet, and it signs the transaction.
- Program mode. The owner is a program’s CPI authority. The program calls the ika program
through a CPI and signs for its CPI authority with
invoke_signed.
The ika program tells the two apart by one account: when the account in a fixed slot is an
executable program, the instruction is in program mode, and it takes one more account. In
program mode the program checks that the CPI authority signed, that it is the address
["__ika_cpi_authority"] derived under the calling program, and that it equals the owner. See
The CPI Framework.
Vouchers
IssueSignatureVoucher (156)
Creates a SignatureVoucher: the right to have the network sign one message once, with one
dWallet. See Signature Vouchers.
Data, 67 to 131 bytes after the instruction number:
| Field | Size | Meaning |
|---|---|---|
message_digest | 32 | The Keccak-256 of the message |
message_metadata_digest | 32 | The Keccak-256 of the message’s metadata, or 32 zeros for none |
signature_scheme | 2 | The signature scheme number, little-endian |
flags | 1 | Bit 1: an owner follows. Bit 2: a signing key follows. Any other bit is refused |
owner | 32 | Only when bit 1 is set. The voucher’s owner. Must not be all zeros |
signing_key | 32 | Only when bit 2 is set. The key a sign request must be signed by |
Without an owner, the voucher’s owner is the issuer. Without a signing key, the voucher has none until its owner sets one.
Accounts in signer mode:
| # | Account | Writable | Signer | Meaning |
|---|---|---|---|---|
| 0 | coordinator | no | no | The DWalletCoordinator |
| 1 | signature_voucher | yes | yes | The new voucher’s address. It must be empty and owned by the system program |
| 2 | dwallet | no | no | The dWallet |
| 3 | owner | no | yes | The dWallet’s owner |
| 4 | payer | yes | yes | Pays the voucher’s rent |
| 5 | system_program | no | no | The system program |
Accounts in program mode:
| # | Account | Writable | Signer | Meaning |
|---|---|---|---|---|
| 0 | coordinator | no | no | The DWalletCoordinator |
| 1 | signature_voucher | yes | yes | The new voucher’s address |
| 2 | dwallet | no | no | The dWallet |
| 3 | caller_program | no | no | The calling program. Executable |
| 4 | cpi_authority | no | yes | The calling program’s CPI authority |
| 5 | payer | yes | yes | Pays the voucher’s rent |
| 6 | system_program | no | no | The system program |
It is refused when the dWallet is not Active (InvalidDWalletState, 4005), when the
coordinator is paused (Paused, 4030), or when the signer is not the dWallet’s owner
(MissingRequiredSignature).
IssueFutureSignatureVoucher (161)
Creates a FutureSignatureVoucher. Its data, its accounts and its checks are those of
IssueSignatureVoucher. Its signing key is the key step 1 must be signed by. See
Future Signature Vouchers.
SetVoucherSigningKey (157), RevokeSignatureVoucher (158), TransferSignatureVoucher (159)
The voucher’s owner changes the voucher. Each acts on a SignatureVoucher or a
FutureSignatureVoucher, chosen by the account’s tag. None checks the pause, so an owner can
always narrow what a voucher allows.
| Instruction | Data | Effect |
|---|---|---|
SetVoucherSigningKey | the new signing key, 32 bytes | Sets or replaces the key a request must be signed by |
RevokeSignatureVoucher | none | Revokes the voucher for good |
TransferSignatureVoucher | the new owner, 32 bytes, not all zeros | Gives the voucher to a new owner, in any state |
Accounts in signer mode: signature_voucher (writable), then owner (signer).
Accounts in program mode: signature_voucher (writable), caller_program (executable), then
cpi_authority (signer).
A signature voucher takes a new key, or a revoke, only while pending. A future voucher takes
them while open or partially signed. Otherwise the instruction fails with VoucherNotPending
(4059). A signer that is not the voucher’s owner fails with NotVoucherOwner (4060).
Ownership
TransferOwnership (129)
Gives a dWallet to a new owner. The dWallet must be Active. The pause does not apply.
Data: the new owner, 32 bytes, not all zeros (InvalidAuthority, 4031).
Accounts in signer mode:
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | owner | no | yes |
| 1 | dwallet | yes | no |
Accounts in program mode:
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | caller_program | no | no |
| 1 | cpi_authority | no | yes |
| 2 | dwallet | yes | no |
Gas deposits
See Gas Deposits for what a deposit is and what the network charges.
CreateDeposit (136)
Creates the GasDeposit of one request key. The request key proves it agrees with an Ed25519
signature, checked by the Ed25519 precompile in an earlier instruction of the same transaction.
The signed message is:
version (u16, 2) || "ika_protocol::gas::proof_of_possession" || chain_number (u32) ||
network (u8) || 32 || the signer's address (32) || incarnation (u64)
The incarnation is the life the instruction opens: 1 for a new deposit, and the closed deposit’s incarnation plus one for a reopen. So the proof of a life that ended does not reopen the deposit.
All integers are little-endian. The chain number and the network are the coordinator’s. The
signer is account 0, the wallet that creates the deposit. It becomes the deposit’s owner, the
only key that can withdraw. A paused coordinator refuses the instruction (Paused, 4030).
The same instruction reopens a closed deposit, with the same data and accounts. A payout that paid
everything closes the deposit and keeps its account. A create on it opens the deposit’s next life:
the signer becomes the owner, incarnation goes up by one, and no rent is paid. A deposit that is
open, or whose withdrawal is pending, is refused with AccountAlreadyInitialized.
Data, 97 bytes:
| Field | Size | Meaning |
|---|---|---|
user_pubkey | 32 | The request key |
pop_signature | 64 | The request key’s signature over the message above |
bump | 1 | The deposit’s canonical bump |
Accounts:
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | signer | no | yes |
| 1 | gas_deposit, ["gas_deposit", user_pubkey] | yes | no |
| 2 | coordinator | no | no |
| 3 | payer | yes | yes |
| 4 | system_program | no | no |
| 5 | instructions sysvar | no | no |
After those come the payer’s IKA token account and the treasury vault (both writable), the token
program, the event authority, the program, and last the deposit fee recipient (writable). While a
fee is set, the recipient must be the coordinator’s (InvalidDepositFeeRecipient, 4083). The fee
comes out of sol_amount, and the rest is credited. A sol_amount below the fee is refused
(BelowDepositFee, 4082).
createDepositInstructions in @ika.xyz/pre-alpha-solana/instructions builds the precompile
instruction and this one, in order.
TopUp (137)
Adds IKA, SOL, or both to a deposit. Anyone may top up any deposit that is not closed
(DepositClosed, 4080); a deposit whose withdrawal is pending accepts it. A top-up that moves
nothing is refused (EmptyTopUp, 4038). Each coin’s amount must be zero or at least the
coordinator’s minimum balance in that coin (BelowMinimumTopUp, 4078).
Data, 16 bytes: ika_amount (u64), then sol_amount (u64).
Accounts:
| # | Account | Writable | Signer | Meaning |
|---|---|---|---|---|
| 0 | gas_deposit | yes | no | The deposit |
| 1 | coordinator | no | no | Names the treasury vault and the IKA mint |
| 2 | user_token_account | yes | no | The IKA source. payer must be its owner |
| 3 | treasury_vault | yes | no | The coordinator’s treasury vault |
| 4 | token_program | no | no | The SPL Token program |
| 5 | payer | yes | yes | Pays the SOL and owns the token account |
| 6 | system_program | no | no | The system program |
| 7 | event_authority | no | no | Emits GasDeposited |
| 8 | program | no | no | This program |
| 9 | fee_recipient | yes | no | The coordinator’s deposit fee recipient, paid the deposit fee out of sol_amount, which credits the rest. Any writable account when no fee is set; another while a fee is set is refused (InvalidDepositFeeRecipient, 4083). A sol_amount below the fee is refused (BelowDepositFee, 4082), and one that is only the fee is an empty top-up (EmptyTopUp) |
RequestWithdraw (141)
A deposit’s owner asks for the whole deposit back. The request carries no amount. It names the
token account the IKA is paid to. The network then pays the withdrawal with its own transaction,
SettleGasWithdrawal (167), and the owner sends nothing more. See
Gas Deposits for the payout.
The program refuses any signer but the owner, the request key included, with
AuthorityMismatch (4004). The owner may be a program’s address that signs through
invoke_signed. The IKA destination must be an initialized, unfrozen SPL token account of the
IKA mint, or the request is refused with InvalidIkaDestination (4077).
A request is final. There is no cancel, and a second request while one is pending is refused
with WithdrawalAlreadyPending (4076). A closed deposit is refused with DepositClosed (4080),
and a request for another incarnation than the deposit’s with GasDepositIncarnationMismatch
(4081). The payout that pays everything closes the deposit, and the owner reopens it with
CreateDeposit.
Nothing cancels a pending request: only the network’s payout ends it, and a TransferGasDeposit
is refused while it is pending. A pause does not stop a request.
The request sets the deposit’s pending flag and records the IKA destination. It advances the
deposit’s withdrawal_sequence and its sequence, and emits GasWithdrawalRequested (128).
Data, 8 bytes: incarnation (u64, little-endian), the deposit’s life the request is for. Any
other length is refused with InvalidInstructionData.
Accounts:
| # | Account | Writable | Signer | Meaning |
|---|---|---|---|---|
| 0 | owner | no | yes | The deposit’s owner. The payout sends the SOL to it |
| 1 | gas_deposit | yes | no | The deposit |
| 2 | coordinator | no | no | Names the IKA mint and the epoch |
| 3 | ika_destination | no | no | The token account the IKA is paid to |
| 4 | event authority, ["__event_authority"] | no | no | Signs the event’s self-invocation |
| 5 | the ika program | no | no | The target of that self-invocation |
The mock network pays no withdrawal. On the devnet pre-alpha, a request stays pending, and the deposit’s funds stay where they are.
TransferGasDeposit (166)
The deposit’s owner names a new owner. A zero owner is refused with InvalidAuthority, and any
other signer with AuthorityMismatch (4004). A pause does not stop it.
A transfer is refused while a withdrawal request is pending, with
TransferWhileWithdrawalPending (4079). A request is final: the payout sends the SOL to the owner
and the IKA to the token account the request recorded, and only that payout ends the request. The
owner can transfer the deposit again once the payout has landed. A transfer leaves the pending
flag and withdrawal_sequence unchanged.
A closed deposit is refused with DepositClosed (4080), and a transfer for another incarnation
than the deposit’s with GasDepositIncarnationMismatch (4081).
Every transfer advances the deposit’s sequence and emits GasDepositTransferred (126).
Data, 40 bytes: new_owner (32), incarnation (8, little-endian). Accounts, in order: the owner (signer), the deposit (writable),
the event authority, the program.
Encryption keys and shares
See Encrypted Shares for the whole flow.
RegisterEncryptionKey (153)
Creates a holder’s EncryptionKey for one curve. Anyone may send it and pay for it. The
authority is the holder’s Ed25519 signature over the registration message, in an Ed25519
precompile instruction right before this one. That precompile instruction must hold exactly one
signature. The program reads the encryption key from the signed message, never from this
instruction’s data. A paused coordinator refuses it (Paused, 4030).
The registration message is the BCS encoding of: the version 1 as a u16, the domain
ika_encryption_key as a byte vector, the chain number (u32), the network (u8), the curve
(u16), and the encryption key as a byte vector. The chain number and the network are the
coordinator’s.
Data, 36 bytes: signer_public_key (32), signature_scheme (1, always 0), curve (u16),
bump (1).
Accounts:
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | holder: the signer key as an address | no | no |
| 1 | encryption_key, ["encryption_key", holder, curve_le] | yes | no |
| 2 | coordinator | no | no |
| 3 | payer | yes | yes |
| 4 | system_program | no | no |
| 5 | instructions sysvar | no | no |
| 6 | event authority, ["__event_authority"] | no | no |
| 7 | the ika program | no | no |
One key exists per holder and curve. A second registration fails with
AccountAlreadyInitialized.
AcceptEncryptedUserShare (165)
A holder accepts its encrypted share. Anyone may send it and pay for it. The authority is the
holder’s Ed25519 signature over the share’s acceptance_digest, in an Ed25519 precompile
instruction right before this one, holding exactly one signature. A paused coordinator refuses
it (Paused, 4030). It has no data.
Accounts:
| # | Account | Writable | Signer |
|---|---|---|---|
| 0 | coordinator | no | no |
| 1 | dwallet | yes | no |
| 2 | encrypted_share | yes | no |
| 3 | instructions sysvar | no | no |
| 4 | event authority | no | no |
| 5 | the ika program | no | no |
The checks, in order:
| Check | Error |
|---|---|
| The coordinator is not paused | Paused (4030) |
| The share belongs to the dWallet | ShareOfAnotherDWallet (4072) |
| The share is not accepted yet | ShareAlreadyAccepted (4073) |
| An Ed25519 precompile instruction comes right before | InvalidAttestation (4009) |
It holds one signature, by the holder, over acceptance_digest | InvalidAcceptanceSignature (4074) |
| A first share: the dWallet waits for its holder or is Active. A re-encrypted share: the dWallet is Active | InvalidDWalletState (4005) |
Network instructions
The network sends these with its own transactions. An integrator never sends them, but sees their effects on chain.
| Number | Instruction | What it writes |
|---|---|---|
| 130 | CommitNetworkDkg | A new NetworkEncryptionKey, or the network’s signature into an unsigned one |
| 131 | CommitNetworkKeyReconfiguration | A NetworkReconfigurationOutput for one key and epoch |
| 132 | CommitDWallet | A new DWallet and its creation attestation. The owner is the request’s intended_chain_sender |
| 134 | CommitEncryptedUserSecretKeyShare | A holder’s EncryptedUserSecretKeyShare and its attestation |
| 135 | CommitPublicUserSecretKeyShare | A dWallet’s public share attestation. It makes a waiting dWallet Active |
| 138 | SettleGas | Charges a deposit for served requests |
| 140 | CommitSignature | A signature into a voucher. A pending or revoked SignatureVoucher, or a FutureSignatureVoucher that holds step 1’s result |
| 144 | AdvanceEpoch | The coordinator’s epoch |
| 145 | SettleGasWithoutDelivery | Charges for a signature the network gave up delivering, and closes its voucher with status 2 |
| 149 | SetPauser | The coordinator’s pauser |
| 150 | SettleGasCharge | A GasCharge record, and the charge |
| 163 | CommitPartialUserSignature | Step 1’s result into a FutureSignatureVoucher |
| 164 | SetChainIdentifier | A new chain identifier that applies at the next epoch |
| 167 | SettleGasWithdrawal | A deposit’s pending withdrawal: takes the withdrawal’s charge first, then pays what is left, the SOL to the owner and the IKA to the recorded destination. Writes a GasWithdrawalCharge record |
| 168 | SetMinFirstDeposit | The coordinator’s minimum first deposit, in IKA and in SOL. CreateDeposit and every TopUp must leave the deposit’s balance net of debt at or above it |
| 169 | SetMinBalance | The coordinator’s minimum balance to start a new action. The network refuses a new request against a deposit below it. Each coin a TopUp adds must be zero or at least it |
| 170 | SetDepositFee | The coordinator’s deposit fee in lamports, which every CreateDeposit and TopUp pays out of its sol_amount, and its recipient, the network-owned address that sent it |
A network instruction is valid only when it is signed by an active network key’s
noa_public_key. On the devnet pre-alpha, the mock holds the one network key and sends these
transactions itself.
Account Reference
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
This page lists the byte layout of every account the ika program keeps for dWallets. Use it to read an account from a client or from your own program. The program also keeps accounts for the network’s own operation. An integrator does not read them, so they are not listed here.
How to read an account
Every account starts with a two-byte header. Byte 0 is the account type’s tag, and byte 1 is the layout version. Every layout is version 1. All integers are little-endian. A key is 32 raw bytes.
Before you trust an account’s bytes, check three things:
- The account’s owner is the ika program.
- Byte 0 is the tag of the type you expect.
- The account’s length is the type’s length. A type marked “header” below has a fixed part and then data of varying length, so check that the account is at least that long.
Every account type has the same owner, the ika program. So the owner check alone does not tell you which type an account is. The tag does.
| Account | Tag | Length in bytes | Address |
|---|---|---|---|
DWalletCoordinator | 96 | 727 | ["dwallet_coordinator"] |
DWallet | 97 | 185 | see The dWallet’s address |
NetworkEncryptionKey | 98 | 199 | ["network_encryption_key", noa_public_key] |
GasDeposit | 99 | 205 | ["gas_deposit", user_pubkey] |
EncryptedUserSecretKeyShare | 101 | header 214 | ["dwallet", "encrypted_user_share", root, holder] |
NetworkReconfigurationOutput | 102 | 182 | ["network_reconfig", noa_public_key, epoch_le] |
DWalletAttestation | 104 | header 101 | see Attestation accounts |
GasCharge | 106 | 91 | ["gas_charge", charge_id] |
GasWithdrawalCharge | 112 | 67 | ["gas_withdrawal_charge", user_pubkey, withdrawal_sequence_le] |
EncryptionKey | 107 | header 120 | ["encryption_key", signer_public_key, curve_le] |
SignatureVoucher | 108 | 304 | none: a fresh address the issuer picks |
FutureSignatureVoucher | 109 | 1941 | none: a fresh address the issuer picks |
Every address in the table is a program-derived address (PDA) of the ika program, with the
seeds listed. epoch_le is the epoch as eight little-endian bytes. curve_le is the curve as
two little-endian bytes. The SDK carries a table of every tag, seed and instruction byte an integrator uses, in
sdk/solana/src/wire-tables-data.ts.
The dWallet’s address
A dWallet’s address is derived from its curve and its public key. Take the curve as two little-endian bytes and append the public key. Split that buffer into chunks of 32 bytes, the most one Solana seed may hold. Each chunk is one seed. We call this list of chunks the root.
| Public key | Buffer | Chunks |
|---|---|---|
| 32 bytes (Curve25519, Ristretto) | 34 bytes | 32, 2 |
| 33 bytes (compressed secp256k1, secp256r1) | 35 bytes | 32, 3 |
A dWallet made by key generation lives at ["dwallet", "record", root...].
An imported dWallet lives at ["dwallet", "imported_record", root..., session_identifier].
The session identifier is the one of the import request that created it, and the dWallet
stores it at offset 153. The same key can be imported more than once. Each import makes its own
dWallet, so the identifier is part of the address.
Every account that belongs to one dWallet starts its seeds with "dwallet", then a word that
names the account’s kind, then the root. The kind comes before the root on purpose. A root has
no fixed length, so a word after it could be read as part of a longer root, and two kinds of
account could get one address.
DWalletCoordinator (tag 96)
One account for the whole program, at ["dwallet_coordinator"]. It holds the epoch, the pause
and this deployment’s fixed values.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | epoch | 8 | The network’s epoch on this chain. Only the network moves it, with AdvanceEpoch |
| 10 | total_dwallets_created | 8 | How many dWallets CommitDWallet has created |
| 18 | paused | 1 | 1 while the program is paused. See Pauses |
| 19 | bump | 1 | This account’s bump |
| 20 | ika_mint | 32 | The IKA token’s mint |
| 52 | treasury_vault | 32 | The token account that holds every deposit’s IKA |
| 84 | pauser | 32 | The key that may pause and unpause. All zeros means no pauser |
| 116 | chain_identifier_len | 1 | The length of the next field |
| 117 | chain_identifier | 40 | This chain’s ERC-7930 chain identifier, padded with zeros |
| 157 | collected_ika | 8 | IKA the network has charged and not yet paid to stakers |
| 165 | paused_signing_parameters | 395 | The curves, algorithms and hashes the network refuses. See below |
| 560 | pauser_protocol_version | 8 | The protocol version that last set pauser |
| 568 | vault_authority_bump | 1 | The bump of ["vault_authority"], which owns treasury_vault |
| 569 | chain_number | 4 | This chain’s fixed number. Signed messages name it |
| 573 | pending_chain_identifier_len | 1 | The length of the next field. Zero when nothing waits |
| 574 | pending_chain_identifier | 40 | A new chain identifier that waits for an epoch |
| 614 | pending_chain_identifier_effective_epoch | 8 | The epoch the waiting identifier applies at |
| 622 | chain_identifier_protocol_version | 8 | The protocol version that last set a waiting identifier |
| 630 | network | 1 | 1 mainnet, 2 testnet, 3 a local or test network |
| 631 | min_first_deposit_ika | 8 | The minimum first deposit in IKA’s smallest unit. CreateDeposit and every TopUp must leave the balance net of debt at or above it. Zero is no minimum |
| 639 | min_first_deposit_sol | 8 | The same minimum in lamports |
| 647 | min_first_deposit_protocol_version | 8 | The protocol version that last set it. SetMinFirstDeposit refuses one not above it |
| 655 | min_balance_ika | 8 | The minimum balance net of debt to start a new action, in IKA’s smallest unit. The network enforces it on requests. The program checks only that a TopUp’s IKA amount is zero or at least it |
| 663 | min_balance_sol | 8 | The same minimum in lamports |
| 671 | min_balance_protocol_version | 8 | The protocol version that last set it. SetMinBalance refuses one not above it |
The paused signing parameters, from offset 165:
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 165 | revision | 8 | Counts every change to the three lists |
| 173 | curves_len | 1 | How many entries of the next list are in use |
| 174 | curves | 128 | Up to 32 curve numbers, four bytes each |
| 302 | signature_algorithms_len | 1 | As above |
| 303 | signature_algorithms | 128 | Up to 32 signature algorithm numbers |
| 431 | hash_schemes_len | 1 | As above |
| 432 | hash_schemes | 128 | Up to 32 hash scheme numbers |
On the devnet pre-alpha the coordinator holds chain number 1 and network 3.
DWallet (tag 97)
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | owner | 32 | Who controls the dWallet: a wallet, or a program’s CPI authority |
| 34 | curve | 2 | 0 secp256k1, 1 secp256r1, 2 Curve25519, 3 Ristretto |
| 36 | state | 1 | See the states below |
| 37 | public_key_len | 1 | The length of the public key |
| 38 | public_key | 65 | The dWallet’s public key, padded with zeros |
| 103 | created_epoch | 8 | The epoch the dWallet was created in |
| 111 | noa_public_key | 32 | The network key that holds the network’s share of this dWallet |
| 143 | is_imported | 1 | 1 for an imported key, 0 for a generated one |
| 144 | bump | 1 | This account’s bump |
| 145 | _reserved | 8 | Zero |
| 153 | session_identifier | 32 | An imported dWallet’s import session. Zero for a generated one |
The states:
| Value | State | Meaning |
|---|---|---|
| 0 | DKGInProgress | Not written by the current program |
| 1 | Active | Usable: vouchers can be issued and the owner can be changed |
| 2 | Frozen | Not written by the current program |
| 3 | AwaitingKeyHolderSignature | Created with an encrypted share that its holder has not accepted yet |
A dWallet only moves from 3 to 1. See Encrypted Shares.
NetworkEncryptionKey (tag 98)
The record of one network key. The network’s address on Solana for that key is
noa_public_key: every transaction the network sends for the key is signed by it.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | noa_public_key | 32 | The key’s Ed25519 public key, and the network’s signing address |
| 34 | state | 1 | 0 waiting for its key generation, 1 active, 2 waiting for a reconfiguration, 3 active after a reconfiguration |
| 35 | created_epoch | 8 | The epoch the record was created in |
| 43 | last_reconfig_epoch | 8 | The highest epoch with a reconfiguration record. 0 if none |
| 51 | dkg_output_digest | 32 | The Blake2b-256 digest of the key’s network key-generation output |
| 83 | bump | 1 | This account’s bump |
| 84 | _reserved | 16 | Zero |
| 100 | dkg_output_proof_len | 1 | The length of the next field. 0 while the record is unsigned |
| 101 | dkg_output_proof | 98 | The network’s signature over this record |
NetworkReconfigurationOutput (tag 102)
One per network key and epoch in which the key was reconfigured.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | noa_public_key | 32 | The network key |
| 34 | epoch | 8 | The epoch of the reconfiguration |
| 42 | reconfig_output_digest | 32 | The Blake2b-256 digest of the reconfiguration’s output |
| 74 | reconfiguration_output_proof_len | 1 | The length of the next field. 0 while unsigned |
| 75 | reconfiguration_output_proof | 98 | The network’s signature over this record |
| 173 | bump | 1 | This account’s bump |
| 174 | _reserved | 8 | Zero |
GasDeposit (tag 99)
One per request key: the Ed25519 key that signs the user’s gRPC requests. The wallet that
creates it owns it (owner). Only the owner requests a withdrawal, which the network then pays;
the request key only pays for requests. See Gas Deposits.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | user_pubkey | 32 | The request key this deposit pays for |
| 34 | ika_balance | 8 | IKA available for request fees, in IKA’s smallest unit |
| 42 | sol_balance | 8 | Lamports available for the network’s own transactions |
| 50 | total_ika_deposited | 8 | All IKA ever added |
| 58 | total_ika_consumed | 8 | All IKA ever charged |
| 66 | total_sol_deposited | 8 | All lamports ever added |
| 74 | total_sol_consumed | 8 | All lamports ever charged |
| 82 | withdrawal_sequence | 8 | Counts withdrawal requests. Nothing else advances it |
| 90 | last_settlement_epoch | 8 | The epoch of the last charge |
| 98 | created_epoch | 8 | The epoch the deposit was created in |
| 106 | bump | 1 | This account’s bump |
| 107 | ika_debt | 8 | IKA charged beyond the balance. The next charge takes it first |
| 115 | sol_debt | 8 | Lamports charged beyond the balance |
| 123 | sequence | 8 | Counts every change to the account. 1 at creation |
| 131 | owner | 32 | The deposit’s owner: the wallet that signed CreateDeposit, or the owner a TransferGasDeposit named since |
| 163 | withdrawal_pending | 1 | 1 while a withdrawal request waits for the network’s payout |
| 164 | ika_destination | 32 | The token account the pending request’s IKA is paid to. Zeros when none is pending |
A request advances withdrawal_sequence and sequence. The payout, top-ups and charges advance
only sequence.
GasCharge (tag 106)
A record the network writes when it charges for work it delivered nothing for. Its address is derived from the charge’s id, so the same charge is written only once.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | charge_id | 32 | The charge’s id |
| 34 | user_pubkey | 32 | The deposit charged |
| 66 | ika_amount | 8 | The IKA asked for |
| 74 | sol_amount | 8 | The lamports asked for, this record’s rent included |
| 82 | epoch | 8 | The epoch of the charge |
| 90 | bump | 1 | This account’s bump |
GasWithdrawalCharge (tag 112)
The record of one withdrawal’s charge. Its address is derived from the deposit’s request key and
the withdrawal counter the request was made at. SettleGasWithdrawal writes it when it takes the
withdrawal’s charge and pays the deposit out, or when it charges a request that is no longer
pending. Nothing closes it, so a second payout of the same request is refused. A payout short of
its charge writes none.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | user_pubkey | 32 | The deposit charged |
| 34 | withdrawal_sequence | 8 | The withdrawal counter the request was made at |
| 42 | ika_amount | 8 | The IKA charged |
| 50 | sol_amount | 8 | The lamports charged, this record’s rent included |
| 58 | epoch | 8 | The epoch the payout landed in |
| 66 | bump | 1 | This account’s bump |
SignatureVoucher (tag 108)
The right to one signature. See Signature Vouchers.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | dwallet | 32 | The dWallet’s address |
| 34 | message_digest | 32 | The Keccak-256 of the message |
| 66 | message_metadata_digest | 32 | The Keccak-256 of the message’s metadata, or zeros for none |
| 98 | owner | 32 | Who controls the voucher |
| 130 | signature_scheme | 2 | The signature scheme number |
| 132 | has_signing_key | 1 | 1 when signing_key is set |
| 133 | signing_key | 32 | The Ed25519 key a sign request must be signed by |
| 165 | issued_epoch | 8 | The epoch the voucher was issued in |
| 173 | status | 1 | 0 pending, 1 signed, 2 closed by a charge, 3 revoked |
| 174 | signature_len | 2 | The signature’s length. 0 while none is stored |
| 176 | signature | 128 | The signature, padded with zeros |
FutureSignatureVoucher (tag 109)
The right to one signature made in two steps. See Future Signature Vouchers.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 to 172 | The same fields as SignatureVoucher, at the same offsets | ||
| 173 | status | 1 | 0 open, 1 partially signed, 2 signed, 3 closed by a charge, 4 revoked |
| 174 | attestation_proof | 98 | The network’s signature over step 1’s result |
| 272 | has_partial_signature | 1 | 1 once step 1 wrote its result |
| 273 | attestation_len | 2 | The length of the next field’s content |
| 275 | attestation | 1536 | Step 1’s result, padded with zeros |
| 1811 | signature_len | 2 | The signature’s length. 0 while none is stored |
| 1813 | signature | 128 | The signature, padded with zeros |
EncryptedUserSecretKeyShare (tag 101)
One holder’s encrypted copy of the user’s share of a dWallet. The fixed part is 214 bytes. The
encrypted share follows it, encrypted_share_len bytes long. See
Encrypted Shares.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | dwallet | 32 | The dWallet the share belongs to |
| 34 | encryption_key_owner | 32 | The holder: the Ed25519 key whose registered encryption key encrypts the share |
| 66 | source_share | 32 | The share this one was re-encrypted from. Zero for the first share |
| 98 | is_re_encrypted | 1 | 1 for a re-encrypted share |
| 99 | created_epoch | 8 | The epoch the share was stored in |
| 107 | bump | 1 | This account’s bump |
| 108 | accepted | 1 | 1 once the holder accepted the share |
| 109 | _reserved | 7 | Zero |
| 116 | encrypted_share_len | 2 | The length of the encrypted share after offset 214 |
| 118 | acceptance_signature | 64 | The holder’s acceptance signature. Zero until accepted |
| 182 | acceptance_digest | 32 | The digest the holder signs to accept |
| 214 | encrypted share | varies | The encrypted share and its proof |
An imported dWallet’s share lives at
["dwallet", "imported_encrypted_user_share", root..., session_identifier, holder].
EncryptionKey (tag 107)
A holder’s registered encryption key for one curve. The fixed part is 120 bytes. The
encryption key follows it, encryption_key_len bytes long.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | signer_public_key | 32 | The holder’s Ed25519 key |
| 34 | signature_scheme | 1 | 0, Ed25519, the only scheme accepted |
| 35 | curve | 2 | The curve the encryption key is for |
| 37 | encryption_key_len | 2 | The length of the key after offset 120 |
| 39 | signature | 64 | The holder’s signature over the registration message |
| 103 | created_epoch | 8 | The epoch the key was registered in |
| 111 | bump | 1 | This account’s bump |
| 112 | _reserved | 8 | Zero |
| 120 | encryption key | varies | The encryption key |
DWalletAttestation (tag 104)
A record of something the network signed about a dWallet. Each has a 101-byte header, then the attested fields.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 2 | bump | 1 | This account’s bump |
| 3 | attestation_proof | 98 | The network’s proof: a variant byte (0), the attestation’s version (0), the signing network key (32) and the signature (64) |
| 101 | fields | varies | The attested fields, in order. The session identifier comes first |
One account per kind:
| Kind | Address |
|---|---|
| The dWallet’s creation | ["dwallet", "attestation", root...] |
| An imported dWallet’s creation | ["dwallet", "imported_attestation", root..., session_identifier] |
| An encrypted share | ["dwallet", "encrypted_share_attestation", root..., holder] |
| The public share | ["dwallet", "public_user_share", root...] |
The imported dWallet’s encrypted share and public share have the same pattern with the words
imported_enc_share_attestation and imported_public_user_share, and the session identifier
after the root.
The program stores these accounts and never reads them. A client reads them to check what the network signed. To check one, rebuild the attestation’s bytes from the fields, rebuild the message the network signed, and verify the signature under a network key you trust. Response Types describes the attestations and the signed message. The SDKs do this check for you.
Event Reference
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
The ika program emits an event by calling itself. The call is the program’s EmitEvent
instruction (number 228), signed by the program’s event authority, ["__event_authority"].
The event’s bytes are that instruction’s data. So an event appears in a transaction as an inner
instruction of the ika program, and it cannot be lost to a truncated log. Only the program can
emit one, because EmitEvent refuses any call its event authority did not sign.
The bytes of an event
An event’s data has three parts:
tag (8) || event number (1) || the event's fields
The tag is the eight bytes e4 45 a5 2e 51 cb 9a 1d. They are the tag Anchor uses for its own
events, so a reader that parses Anchor events finds these too. The event number names the event.
The fields follow in the order the tables below give. Integers are little-endian.
To read the events of a transaction:
- Fetch the transaction with its inner instructions.
- Keep the inner instructions whose program is the ika program.
- Keep those whose data starts with the eight tag bytes.
- Read the event number, then the fields.
Check that the transaction succeeded before you act on an event. A failed transaction can still show inner instructions that ran before the failure.
No event for a voucher or a signature
Issuing a voucher emits no event, and neither does writing its signature. To learn that a
signature is ready, read the voucher account. Its status at offset 173 becomes 1, and its
signature is at offset 176. See Signature Vouchers.
dWallet events
| Number | Event | Emitted by |
|---|---|---|
| 113 | DWalletCommitted | CommitDWallet |
| 114 | EncryptedShareCommitted | CommitEncryptedUserSecretKeyShare |
| 115 | PublicShareCommitted | CommitPublicUserSecretKeyShare |
| 118 | EncryptionKeyRegistered | RegisterEncryptionKey |
| 123 | EncryptedShareAccepted | AcceptEncryptedUserShare |
| 124 | GasChargedWithoutDelivery | SettleGasCharge |
| 125 | DWalletActivated | AcceptEncryptedUserShare or CommitPublicUserSecretKeyShare |
| 126 | GasDepositTransferred | TransferGasDeposit |
The gas deposit events, 106 to 108 and 126 to 132, are listed in Gas deposit events.
DWalletCommitted (113)
The network created a dWallet.
| Field | Size | Meaning |
|---|---|---|
dwallet | 32 | The new dWallet’s address |
attestation_proof | 98 | The network’s proof over the dWallet’s attestation |
attestation_fields | rest | The attestation’s fields, as the attestation account stores them |
EncryptedShareCommitted (114)
The network stored a holder’s encrypted share.
| Field | Size | Meaning |
|---|---|---|
encrypted_share | 32 | The share account’s address |
dwallet | 32 | The dWallet |
encryption_key_owner | 32 | The holder |
source_share | 32 | The share it was re-encrypted from. Zero for a first share |
is_re_encrypted | 1 | 0 or 1 |
created_epoch | 8 | The epoch |
acceptance_digest | 32 | The digest the holder signs to accept |
attestation_proof | 98 | The network’s proof over the share’s attestation |
encrypted_share_len | 2 | The length of the next field |
encrypted_share | varies | The encrypted share |
attestation_fields | rest | The share attestation’s fields |
PublicShareCommitted (115)
The network stored a dWallet’s public share. If the dWallet waited for its holder,
DWalletActivated comes first.
| Field | Size | Meaning |
|---|---|---|
dwallet | 32 | The dWallet |
attestation_proof | 98 | The network’s proof over the public share’s attestation |
attestation_fields | rest | The attestation’s fields, the public share included |
EncryptionKeyRegistered (118)
| Field | Size | Meaning |
|---|---|---|
encryption_key_entry | 32 | The EncryptionKey account’s address |
signer_public_key | 32 | The holder |
signature_scheme | 1 | 0, Ed25519 |
curve | 2 | The curve |
epoch | 8 | The epoch |
signature | 64 | The holder’s signature over the registration message |
encryption_key_len | 2 | The length of the next field |
encryption_key | varies | The registered encryption key |
EncryptedShareAccepted (123)
| Field | Size | Meaning |
|---|---|---|
encrypted_share | 32 | The share account’s address |
dwallet | 32 | The dWallet |
encryption_key_owner | 32 | The holder |
acceptance_digest | 32 | The digest the holder signed |
acceptance_signature | 64 | The holder’s signature |
dwallet_state | 1 | The dWallet’s state afterwards: always 1, Active |
DWalletActivated (125)
A dWallet moved from waiting for its holder to Active. A dWallet emits it at most once. A dWallet created Active never emits it.
| Field | Size | Meaning |
|---|---|---|
dwallet | 32 | The dWallet |
GasChargedWithoutDelivery (124)
The network charged a deposit for work it delivered nothing for. With reason 1 or 2, it also says that a dWallet or share commit ended without being written. Then no dWallet or share was created for that session, and there is nothing to accept.
| Field | Size | Meaning |
|---|---|---|
charge_id | 32 | The charge’s id |
user_pubkey | 32 | The deposit charged |
ika_amount | 8 | The IKA charged |
sol_amount | 8 | The lamports charged |
epoch | 8 | The epoch |
reason | 1 | 0 a plain charge, 1 a dWallet commit ended, 2 a share commit ended |
ended_session_identifier | 32 | The ended commit’s session. Zeros for reason 0 |
Gas deposit events
Every instruction that changes a gas deposit emits one event. Each one starts with the deposit’s state after the change, 90 bytes:
| Field | Size | Meaning |
|---|---|---|
user_pubkey | 32 | The deposit’s request key |
sequence | 8 | The deposit’s sequence after the change. It grows by one on every change, so a reader applies a state only when its sequence is above the one it holds |
withdrawal_sequence | 8 | The withdrawal counter |
ika_balance | 8 | The IKA balance |
sol_balance | 8 | The lamport balance |
ika_debt | 8 | The IKA debt |
sol_debt | 8 | The lamport debt |
withdrawal_pending | 1 | 1 while a withdrawal request waits for the network’s payout |
incarnation | 8 | The deposit’s life: 1 at the first create, one more at each reopen |
closed | 1 | 1 once a payout that paid everything ended the deposit’s life |
The fields that follow the state, per event:
| Number | Event | Emitted by | Fields after the state |
|---|---|---|---|
| 127 | GasDepositCreated | CreateDeposit | owner (32), IKA added (8), lamports added (8), epoch (8) |
| 106 | GasDeposited | TopUp | IKA added (8), lamports added (8), epoch (8) |
| 128 | GasWithdrawalRequested | RequestWithdraw | owner (32), IKA destination (32), epoch (8) |
| 108 | GasSettled | every charge: SettleGas, SettleGasWithoutDelivery, SettleGasCharge (after its GasChargedWithoutDelivery) and SettleGasWithdrawal | IKA charged (8), lamports charged (8), IKA collected (8), lamports collected (8), epoch (8). The charge collects the debt first, then the new amounts, up to the balance. What it cannot collect becomes debt, which the state shows |
| 107 | GasWithdrawn | a SettleGasWithdrawal that pays | owner (32), IKA destination (32), IKA paid (8), lamports paid (8), IKA kept (8), lamports kept (8), epoch (8). Kept is what a destination could not take. It stays in the deposit |
| 129 | WithdrawalShortOfCharge | a SettleGasWithdrawal for a pending request whose balance is below its debt plus the charge, in either coin. It takes and pays nothing, and the request stays pending | the message’s withdrawal counter (8), IKA charge (8), lamport charge (8), epoch (8) |
| 133 | GasChargeSkipped | a charge (SettleGas, SettleGasCharge, SettleGasWithoutDelivery or SettleGasWithdrawal) that names another incarnation than the deposit’s, or reaches a closed deposit. It took nothing | incarnation named (8), IKA asked for (8), lamports asked for (8), epoch (8) |
| 132 | WithdrawalNotPaid | a SettleGasWithdrawal that names a counter with no pending request. Only a payout ends a request, so the network sends such a payout only by mistake. The withdrawal was charged, after its GasSettled, and nothing was paid | the message’s withdrawal counter (8), epoch (8) |
| 126 | GasDepositTransferred | TransferGasDeposit | the deposit’s address (32), the previous owner (32), the new owner (32) |
Network and coordinator events
These record what the network and the pauser changed. An integrator rarely needs them.
| Number | Event | Fields |
|---|---|---|
| 110 | NetworkKeyRegistered | noa_public_key (32), dkg_output_digest (32), created_epoch (8) |
| 111 | SigningParameterPaused | kind (1: 0 curve, 1 algorithm, 2 hash), value (u32), revision (u64) |
| 112 | SigningParameterUnpaused | the same fields |
| 116 | DWalletPauserSet | pauser (32, zeros for none), protocol_version (8) |
| 117 | NetworkKeyReconfigurationCommitted | noa_public_key (32), epoch (8), reconfig_output_digest (32), proof length (1), proof (98) |
| 119 | NetworkKeyDkgSigned | noa_public_key (32), dkg_output_digest (32), proof length (1), proof (98) |
| 120 | EpochAdvanced | epoch (8) |
| 121 | ChainIdentifierStaged | length (1), the identifier, the epoch it applies at (8), protocol_version (8) |
| 122 | ChainIdentifierApplied | length (1), the identifier, the epoch it applied at (8) |
| 130 | MinFirstDepositSet | IKA minimum (8, zero for none), lamport minimum (8, zero for none), protocol_version (8). Emitted by SetMinFirstDeposit |
| 131 | MinBalanceSet | the same fields. Emitted by SetMinBalance |
| 134 | DepositFeeSet | the fee in lamports (8, zero for none), the recipient (32), protocol_version (8). Emitted by SetDepositFee |
The program emits other events for the network’s own operation. They are not listed here.
Error Reference
Pre-alpha. The devnet pre-alpha is a mock network with no MPC. Read the warning in the introduction first.
When the ika program refuses an instruction, the transaction fails with one of two kinds of
error. A check that only this program makes fails with ProgramError::Custom(code), and the
code is in the tables below. A check every Solana program makes fails with one of Solana’s own
errors, listed at the end.
Your program sees these codes when its CPI into the ika program fails. The CPI fails the whole transaction, so the code reaches the client unchanged.
dWallet errors (4000 to 4083)
These are the codes an integrator can meet. Codes missing from the list are retired and never returned.
| Code | Name | When |
|---|---|---|
| 4004 | AuthorityMismatch | A withdrawal is requested, or a deposit is handed to a new owner, by a key that is not the deposit’s owner. The request key is refused too |
| 4005 | InvalidDWalletState | The dWallet is not Active: a voucher, a transfer or an accept needs it Active, or waiting for its holder |
| 4007 | InvalidCurve | The network committed a curve the program does not number |
| 4009 | InvalidAttestation | A signed message is not where the instruction expects it. For example, no Ed25519 precompile instruction comes right before an accept |
| 4012 | InvalidNetworkSignature | The network key named does not match the signer |
| 4013 | NetworkKeyNotActive | The network key’s record is not active |
| 4025 | ArithmeticOverflow | A sum would not fit in its integer |
| 4029 | InvalidTreasuryVault | The token account passed is not the coordinator’s treasury vault |
| 4030 | Paused | The coordinator is paused. See Pauses |
| 4031 | InvalidAuthority | A key being set is all zeros, such as a new owner |
| 4032 | InvalidPublicKeyLength | The network committed a public key of the wrong length for its curve |
| 4033 | InvalidEpoch | An epoch value is not the one the instruction allows |
| 4036 | PauserMismatch | The signer is not the coordinator’s pauser |
| 4038 | EmptyTopUp | A top-up moves no IKA and no SOL |
| 4045 | TooManyPausedSigningParameters | A pause would make a list of paused signing parameters too long |
| 4046 | UnsupportedEncryptionKeyCurve | An encryption key is registered for a curve above 3 |
| 4047 | UnsupportedEncryptionKeySignatureScheme | An encryption key’s holder uses a signature scheme other than Ed25519 |
| 4048 | InvalidEncryptionKeySignature | The precompile before a registration does not hold exactly one signature by the holder |
| 4049 | InvalidEncryptionKeyRegistrationSignature | The signed registration message is for another chain, network or curve |
| 4050 | EncryptionKeyHolderMismatch | The holder account is not the key that signed the registration |
| 4057 | SourceShareOfAnotherDWallet | A re-encrypted share names a source share of another dWallet |
| 4059 | VoucherNotPending | A voucher’s signing key is set, or the voucher revoked, after it ended |
| 4060 | NotVoucherOwner | The signer is not the voucher’s owner |
| 4062 | FutureVoucherNotOpenForStep | A future voucher is not in the state the step needs |
| 4070 | DkgOutputDigestMismatch | A network key’s record holds another key-generation digest |
| 4071 | ReconfigurationOutputDigestMismatch | A reconfiguration record holds another digest |
| 4072 | ShareOfAnotherDWallet | The share accepted belongs to another dWallet |
| 4073 | ShareAlreadyAccepted | The share was already accepted |
| 4074 | InvalidAcceptanceSignature | The acceptance is not one signature by the holder over the share’s digest |
| 4075 | BelowMinimumDeposit | A CreateDeposit or TopUp would leave the deposit’s balance net of debt below the minimum first deposit, in IKA or in SOL. The minimum counts the deposit’s total, not the amount one call adds |
| 4076 | WithdrawalAlreadyPending | A withdrawal is requested while a request is already pending. A request is final: only the network’s payout ends it |
| 4077 | InvalidIkaDestination | The IKA destination a withdrawal request names is not an initialized, unfrozen token account of the IKA mint |
| 4078 | BelowMinimumTopUp | A TopUp adds a coin with an amount above zero and below the coordinator’s minimum balance in that coin. A zero amount adds nothing of its coin and is not checked |
| 4079 | TransferWhileWithdrawalPending | A TransferGasDeposit while a withdrawal request is pending. A request is final, so the deposit cannot change hands until the network’s payout ends it |
| 4080 | DepositClosed | A TopUp, RequestWithdraw or TransferGasDeposit on a closed deposit. A payout that paid everything closed it, and only a CreateDeposit reopens it |
| 4081 | GasDepositIncarnationMismatch | A RequestWithdraw or TransferGasDeposit for another incarnation than the deposit’s current life |
| 4082 | BelowDepositFee | A CreateDeposit or TopUp whose sol_amount is below the coordinator’s deposit fee while a fee is set |
| 4083 | InvalidDepositFeeRecipient | A CreateDeposit or TopUp whose fee recipient is not the coordinator’s while a deposit fee is set |
The program also defines codes 4000 to 4003, 4006, 4008, 4010, 4011, 4014 to 4024, 4026 to 4028 and 4034. The current program returns none of them. They keep their numbers so that an old client reads a code the same way.
Codes 4040 to 4042 were the refusals of the owner’s claim of a withdrawal with a release the network signed. The network now pays a withdrawal itself, so the claim and its codes are gone. They are never given to another error.
The examples’ own errors
The example programs return codes of their own, from 0 up. One belongs to every integrator’s
checklist: InvalidBump, 11 in the voting programs and 12 in the multisig programs. It refuses a
bump a client chose that is not the canonical bump of its seeds. See
invariant 6.
Program-wide errors (900 to 906)
These belong to the program’s upgrade path, which only the network uses. An integrator meets none of them.
Solana’s own errors
| Error | Usual cause in this program |
|---|---|
InvalidAccountOwner | An account that should be the ika program’s is owned by another program |
InvalidAccountData | An account has the wrong tag or the wrong length for its type |
InvalidInstructionData | The instruction data is not exactly the length its layout gives, or a flag byte has an unknown bit |
MissingRequiredSignature | A required signer did not sign. For a CPI, the caller’s CPI authority does not match the owner |
InvalidArgument | The caller program is not executable, or the CPI authority is not its ["__ika_cpi_authority"] address |
InvalidSeeds | An account is not at the address its seeds and bump give |
AccountAlreadyInitialized | The account to create already exists. A voucher address that holds anything fails here |
NotEnoughAccountKeys | The instruction got fewer accounts than it needs |
IncorrectProgramId | The system program or the token program passed is not the real one. From a CPI crate’s DWalletContext: the dwallet_program passed is not the ika program the crate was built for, and nothing was called |
Every instruction’s data must be exactly the length its layout gives. A longer or shorter
instruction is refused with InvalidInstructionData, even when the extra bytes are zeros.