Sign and broadcast transactions
Build a transaction, have io.sign sign it, and broadcast it yourself
Use io.sign on its own to sign transactions you build. Your code builds the transaction, io.sign collects approvals from your signers and returns a signature, and your code broadcasts the signed transaction through your own RPC endpoint.
How it works
- Build the unsigned transaction.
- Create a signature request with the bytes to sign.
- Your signers approve the request, and io.sign returns the signature.
- Attach the signature to the transaction, check it, and broadcast it.
Before you start
- A vault that has finished key generation, with enough signers available to meet its threshold. See Vaults, signers, and thresholds.
- The vault's public key and address. If you sign with a derivation path, use the public key and address for that path.
- Your io.sign API URL, and a token that can create and read signature requests for the vault. See Authentication.
- Test funds on a test network.
Create a signature request
Send POST /v2/vaults/{vaultId}/signatures:
{
"expiresAt": "2026-11-01T12:00:00Z",
"memo": "Payout 1042",
"signatures": [
{
"coseAlgorithm": "eskec256",
"contentType": "application/octet-stream+hex",
"dataToSign": ["02f86f..."],
"chainId": 137,
"metadata": {
"contextType": "application/evm-rlp-v1+hex",
"serializedData": "02f86f..."
}
}
]
}| Field | Description |
|---|---|
signatures | Exactly one entry. |
signatures[].coseAlgorithm | es256k or eskec256 for ECDSA on secp256k1, or eddsa for Ed25519. See What to put in dataToSign. |
signatures[].contentType | How dataToSign is encoded: application/octet-stream+hex, application/octet-stream+base64, or text/plain. Use application/x-eip712+json for EIP-712 typed data. |
signatures[].dataToSign | Up to 20 items to sign. The response returns one signature for each, in the same order. |
signatures[].derivationPath | Optional. A non-hardened path such as m/0/1. Leave it out to sign with the vault's root key. |
signatures[].chainId | Optional. The EVM chain ID, for EIP-155 and EIP-712 signatures. |
signatures[].metadata | Optional, but recommended. The unsigned transaction, so signers can see what they're approving. contextType names the format, such as application/evm-rlp-v1+hex, and serializedData holds the transaction. |
expiresAt | Optional. When the request expires if it isn't signed. Must be between 30 seconds and 24 hours away. The default is 24 hours. |
memo | Optional. A note of up to 500 characters. |
Send an idempotency-key header of up to 50 characters, such as a UUID. If you send the same request again with the same key, for example after a network error, io.sign returns the original request instead of creating a second one.
What to put in dataToSign
dataToSignio.sign hashes the data before signing it, as each network expects. Send the bytes the network hashes, not the hash itself:
| Network | coseAlgorithm | dataToSign | io.sign then |
|---|---|---|---|
| EVM | eskec256 | The unsigned transaction | Hashes it with Keccak-256 and signs with secp256k1. |
| Bitcoin | es256k | The SHA-256 hash of the BIP143 preimage | Hashes it with SHA-256 again and signs with secp256k1. |
| Solana | eddsa | The compiled transaction message | Signs it with Ed25519. |
| XRP Ledger | eddsa | The encodeForSigning bytes, including the signing prefix | Signs it with Ed25519. |
If you send a finished EVM or Bitcoin hash with these content types, io.sign hashes it again, and the network rejects the signature. To sign a finished 32-byte hash, use application/octet-stream+hex;kind=digest with es256k or eskec256.
Build dataToSign and metadata.serializedData from the same transaction, so signers approve what you sign.
Wait for the signature
Read the request with GET /v2/vaults/{vaultId}/signatures/{id} until it reaches a final status, or subscribe to signature.* webhooks instead of polling.
| Status | Meaning |
|---|---|
| voting | Waiting for signers to approve. |
| presigning | Approved. Signers are preparing to sign. |
| signing | Signers are signing. |
| completed | Final. The signatures are in signatures[0].signature. |
| rejected | Final. Signers rejected the request. |
| failed | Final. Signing failed. errors says why. |
| expired | Final. The request wasn't signed before expiresAt. |
| cancelled | Final. The request was cancelled. |
Each signature is hex: 64 bytes of r and s, followed by a recovery value v:
- For ECDSA,
vis the recovery ID,0or1. If you setchainId,vis the EIP-155 value instead:chainId × 2 + 35 + recovery ID. - For Ed25519,
vis always0. Drop it to get the 64-byte signature.
Check each signature against the vault's public key before you broadcast.
Recipes
Each recipe signs and broadcasts one native-asset transfer:
| Network | Recipe | Transaction |
|---|---|---|
| Bitcoin | Sign and broadcast BTC | One confirmed P2WPKH input, a P2WPKH recipient, and change back to the sender. |
| EVM | Sign and broadcast EVM | An EIP-1559 transfer. |
| Solana | Sign and broadcast SOL | A SOL transfer with a recent blockhash. |
| XRP Ledger | Sign and broadcast XRP | An XRP payment from an Ed25519 key, with an optional destination tag. |
Token transfers, Bitcoin Taproot or multiple inputs, Solana durable nonces, and XRP multisigning build transactions differently. Don't use these recipes for them unchanged.
Set up the recipes
-
Use Node.js 22 or later.
-
Save the shared helper below as
io-sign.mjs, and a recipe's script beside it. -
Install the SDK versions the recipes were written for:
npm install --save-exact [email protected] [email protected] [email protected] \ @solana/[email protected] [email protected] [email protected] -
Create a
.envfile with these settings, plus the settings from your recipe:IO_SIGN_API_URL=https://sign.example.com IO_SIGN_TOKEN=<token> VAULT_ID=<vault-id> # Optional: leave out to sign with the vault's root key. # DERIVATION_PATH=m/0/1IO_SIGN_API_URLis the base URL, without/v2. Keep the token valid until signers have approved. Don't commit the.envfile.
Shared helper
The helper creates the signature request with an idempotency key, and waits up to 10 minutes for the signature. It sets the request to expire after 11 minutes, so the request doesn't outlive the script. The Solana and XRP recipes also check their network's own deadline while they wait.
/**
* Shared helpers for the io.sign transaction recipes.
*
* Creates io.sign signature requests, waits for them to complete, and decodes
* and checks the signatures they return.
*/
import { createPublicKey, randomUUID, verify } from 'node:crypto';
import { pathToFileURL } from 'node:url';
const FINAL_FAILURE_STATUSES = ['rejected', 'expired', 'failed', 'cancelled'];
const POLL_INTERVAL_MS = 2_000;
const MAX_WAIT_MS = 10 * 60_000;
// Expire the request shortly after the helper stops waiting, so it can't be signed later.
const REQUEST_LIFETIME_MS = 11 * 60_000;
const API_TIMEOUT_MS = 15_000;
const RPC_TIMEOUT_MS = 20_000;
// DER prefix for an Ed25519 public key (SubjectPublicKeyInfo).
const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
/**
* Returns an environment variable, or throws if it isn't set.
*/
export function required(name) {
const value = process.env[name];
if (!value) {
throw new Error(`Set ${name}`);
}
return value;
}
/**
* Parses a positive integer setting as a BigInt.
*/
export function positiveInteger(value, name) {
if (!/^[1-9][0-9]*$/.test(String(value))) {
throw new Error(`${name} must be a positive integer`);
}
return BigInt(value);
}
/**
* Decodes hex, with or without a 0x prefix.
*/
export function hexBytes(value) {
const hex = value.replace(/^0x/, '');
if (!/^(?:[0-9a-fA-F]{2})+$/.test(hex)) {
throw new Error('Invalid hexadecimal bytes');
}
return Buffer.from(hex, 'hex');
}
/**
* Returns the 64-byte signature (r and s) from an io.sign signature.
*/
export function signatureBytes(value, algorithm) {
const bytes = hexBytes(value);
if (algorithm === 'eddsa' && bytes.length === 64) {
return bytes;
}
// io.sign appends a recovery byte to Ed25519 signatures too; it is always zero.
if (bytes.length === 65 && (algorithm !== 'eddsa' || bytes[64] === 0)) {
return bytes.subarray(0, 64);
}
throw new Error(`Unexpected ${algorithm} signature encoding`);
}
/**
* Splits an ECDSA signature into r, s, and y-parity, accepting a recovery ID,
* a legacy 27 or 28 value, or an EIP-155 value for the chain ID.
*/
export function ecdsaParts(value, chainId) {
const bytes = hexBytes(value);
if (bytes.length < 65) {
throw new Error('Expected r, s, and recovery suffix');
}
const v = BigInt('0x' + bytes.subarray(64).toString('hex'));
let parity;
if (v <= 1n) {
parity = v;
} else if (v === 27n || v === 28n) {
parity = v - 27n;
} else {
parity = v - 35n - 2n * BigInt(chainId);
}
if (parity !== 0n && parity !== 1n) {
throw new Error('Invalid recovery suffix or chain ID');
}
return {
r: '0x' + bytes.subarray(0, 32).toString('hex'),
s: '0x' + bytes.subarray(32, 64).toString('hex'),
yParity: Number(parity),
};
}
/**
* Checks an Ed25519 signature against the message and a raw 32-byte public key.
*/
export function verifyEd25519(message, publicKey, signature) {
if (publicKey.length !== 32 || signature.length !== 64) {
throw new Error('Invalid Ed25519 key or signature');
}
const key = createPublicKey({
format: 'der',
type: 'spki',
key: Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(publicKey)]),
});
if (!verify(null, message, key, signature)) {
throw new Error('Signature does not match the message and public key');
}
}
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
/**
* Creates a signature request and waits for its signatures.
*
* `checkFresh` runs before each step, so a recipe can stop when its
* transaction expires on the network.
*/
export async function requestSignature(config, item, checkFresh = async () => {}) {
const {
apiUrl,
token,
vaultId,
fetchImpl = fetch,
intervalMs = POLL_INTERVAL_MS,
maxWaitMs = MAX_WAIT_MS,
} = config;
const endpoint = `${apiUrl.replace(/\/$/, '')}/v2/vaults/${encodeURIComponent(vaultId)}/signatures`;
const deadline = Date.now() + maxWaitMs;
async function callApi(url, method, body, headers = {}) {
const response = await fetchImpl(url, {
method,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
...headers,
},
...(body ? { body: JSON.stringify(body) } : {}),
signal: AbortSignal.timeout(API_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`io.sign HTTP ${response.status}; inspect the existing request before retrying`);
}
return response.json();
}
await checkFresh();
// Sending the same idempotency key again returns the original request instead of creating another.
const idempotencyKey = randomUUID();
console.log(`Idempotency key: ${idempotencyKey}`);
const created = await callApi(endpoint, 'POST', {
expiresAt: new Date(Date.now() + REQUEST_LIFETIME_MS).toISOString(),
signatures: [{ contentType: 'application/octet-stream+hex', ...item }],
}, { 'idempotency-key': idempotencyKey });
if (!created.id) {
throw new Error('io.sign returned no request ID');
}
console.log(`io.sign request: ${created.id}`);
while (Date.now() < deadline) {
await checkFresh();
const request = await callApi(`${endpoint}/${encodeURIComponent(created.id)}`, 'GET');
if (request.status === 'completed') {
const signatures = request.signatures?.[0]?.signature;
const complete = Array.isArray(signatures) &&
signatures.length === item.dataToSign.length &&
signatures.every((signature) => typeof signature === 'string');
if (!complete) {
throw new Error('Missing signature results');
}
await checkFresh();
return signatures;
}
if (FINAL_FAILURE_STATUSES.includes(request.status)) {
throw new Error(`io.sign request ${created.id}: ${request.status}`);
}
await sleep(intervalMs);
}
throw new Error(`Stopped waiting for ${created.id}; this does not cancel it. Inspect its status before retrying.`);
}
/**
* Returns a signing function configured from IO_SIGN_API_URL, IO_SIGN_TOKEN,
* VAULT_ID, and the optional DERIVATION_PATH.
*/
export function signerFromEnvironment() {
const config = {
apiUrl: required('IO_SIGN_API_URL'),
token: required('IO_SIGN_TOKEN'),
vaultId: required('VAULT_ID'),
};
const derivationPath = process.env.DERIVATION_PATH;
return (item, checkFresh) => requestSignature(
config,
{ ...item, ...(derivationPath ? { derivationPath } : {}) },
checkFresh,
);
}
/**
* Returns a JSON-RPC client for the given URL.
*/
export function jsonRpc(url, authorization) {
let id = 0;
return async (method, params = []) => {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(authorization ? { Authorization: authorization } : {}),
},
body: JSON.stringify({ jsonrpc: '2.0', id: ++id, method, params }),
signal: AbortSignal.timeout(RPC_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`RPC HTTP ${response.status}`);
}
const body = await response.json();
if (body.error) {
throw new Error(`RPC ${method}: ${body.error.message}`);
}
return body.result;
};
}
/**
* Runs `main` when the file is run directly, and reports errors without a stack trace.
*/
export function runMain(url, main) {
if (process.argv[1] && pathToFileURL(process.argv[1]).href === url) {
main().catch((error) => {
console.error(error.message);
process.exitCode = 1;
});
}
}If something fails
- The script stops waiting. This doesn't cancel the request. Use the printed request ID to check it with
GET /v2/vaults/{vaultId}/signatures/{id}, or cancel it withPOST /v2/vaults/{vaultId}/signatures/{id}/cancel. - Creating the request fails with a network error. Send it again with the same idempotency key. io.sign returns the original request if it was created.
- Broadcasting fails with a network error. Check the transaction ID with your RPC provider first, because the network may have accepted it. Send the same signed transaction again only if it didn't. Don't build a new transfer automatically.
- Something in the transaction changes. A new nonce, UTXO, fee, blockhash, destination, amount, or XRP sequence makes a different transaction, which needs a new signature request and new approvals.
- You send several transactions at once. Assign EVM nonces and XRP sequences, and reserve Bitcoin UTXOs, in your application. The recipes send one transaction at a time.
Test before use
Test these recipes against a testnet and your own test environment before you use them with real assets.
Updated 17 days ago