HALFKEY
Mainnet · capped beta

Build

SDK reference

The TypeScript the HALFKEY site runs on. Real function names, real argument shapes.

Overview

The HALFKEY SDK is the TypeScript the HALFKEY site runs on. It ships in the HALFKEY repo under sdk/ (source published after launch, BSL 1.1); there is no separate npm package. Import the modules by path. They run in the browser and in Node (the repo runs them with node --test).

  • Protocol layer, no Solana dependency: keys.ts (key split, wallet-derived halves, Monero addresses, quotes), xmrverify.ts (view-key lock check), collect.ts (sweep).
  • Solana adapters: program.ts (instruction encoders and account decoders), taker.ts (the taker flow), jupiter.ts, stealth.ts, platform.ts, v15.ts, zecswap.ts.
  • Dependencies: @solana/web3.js, @noble/curves, @noble/hashes, bs58, and monero-ts (loaded only to collect).
Every check a user's safety depends on lives in the SDK, not in UI code. Functions like prepareSolToXmr and verifyXmrToSolEscrow throw on any term that doesn't match; never catch and continue.

Modules

ModuleWhat it doesMain exports
sdk/keys.tsKey halves from a wallet signature, Monero addresses, signed quotesKEY_MESSAGE rootFromSignature checkDeterministic deriveHalf newSwapId sharedWallet verifyQuote
sdk/discovery.tsMakers straight from the on-chain registryfetchMakers probeEndpoints parseEndpointField
sdk/taker.tsQuotes, the SOL → XMR handshake, XMR → SOL checks, phases, refundsapi checkQuote prepareSolToXmr verifyXmrToSolEscrow findMySwaps phaseOf refundSafe fullSpendKey
sdk/program.tsInstruction encoders, account decoders, error namesixReady ixAbort ixClaim ixRefund decodeEscrow decodeConfig errName
sdk/xmrverify.tsCheck a Monero lock with the view key, on two nodesverifyLock verifyLockCrossChecked
sdk/collect.tsSweep the XMR in-process, or export keyscollect exportKeys
sdk/stealth.tsFresh Solana addresses for XMR → SOLderiveStealthMeta stealthClaimerForSwap scanStealth StealthSigner sweep
sdk/jupiter.tsAny coin in (or out) through JupiterbuildRoute impactLevel composeSell sellQuote findUnlocked
sdk/pay.tsPay-link keys and invoiceslinkMaster payKeys encodeInvoice invoiceId
sdk/platform.tsPaying links, cashout vaults, OTC acceptancegetLink preparePay collectKeys vaultOf acceptOtc platformApi
sdk/otc.tsRFQs, firm quotes, tranche plansnewRfq checkOtcQuote planTranches
sdk/v15.tsStaking and the burn auctionixPoolStake ixPoolClaim claimableRewards burnQuote ixBurnTake
sdk/refundtowers.tsXMR → SOL refund towers: check receipts, rebuild a released halfcheckAcks verifyShare combine
sdk/zecswap.tsZEC taker checks and pre-signed spendszecKeys verifySolToZecOffer checkZecLock presignClaim verifyZecToSolOffer

Connection and your key

Your half of every swap key derives from one signature over K.KEY_MESSAGE. Sign it twice the first time and refuse wallets whose signatures differ: they couldn't rebuild the key on another device.

TypeScript
import { Connection, PublicKey } from '@solana/web3.js';
import * as K from './sdk/keys.ts';
import * as P from './sdk/program.ts';
import * as T from './sdk/taker.ts';

const conn = new Connection(RPC_URL, 'confirmed');
const pid = new PublicKey(PROGRAM_ID);
const configAddress = PublicKey.findProgramAddressSync([Buffer.from('config')], pid)[0];
const cfg = P.decodeConfig((await conn.getAccountInfo(configAddress))!.data);

const msg = new TextEncoder().encode(K.KEY_MESSAGE);
const sig1 = await wallet.signMessage(msg);
const sig2 = await wallet.signMessage(msg);
if (!K.checkDeterministic(sig1, sig2)) throw new Error('this wallet cannot rebuild its key');
const root = K.rootFromSignature(sig1);      // keep in memory only

Finding makers

Makers are read from the on-chain registry; no HALFKEY server is involved. Each entry lists one or more endpoints, and probeEndpoints skips any endpoint that answers for another program or another maker.

TypeScript
import { fetchMakers, probeEndpoints } from './sdk/discovery.ts';

const { makers } = await fetchMakers(conn, pid);   // falls back to known authorities if the RPC refuses the scan
const live = (await Promise.all(makers.filter((m) => m.active).map((m) => probeEndpoints(m, pid, { timeoutMs: 5000 }))))
  .filter((x) => x && x.info.online);
// each: { endpoint, info: MakerInfo }  (info.spreadBps, info.directions, info.t0Secs, ...)

Quotes

FunctionReturns
T.api.info(endpoint)The maker's terms: directions, size range, spread, indicative rate, fee, deadlines.
T.api.quote(endpoint, direction, amount)A signed quote. Direction 1 takes the SOL amount in its smallest unit (1 SOL = 10⁹); direction 2 takes piconero (1 XMR = 10¹²). Firm for 60 seconds.
T.checkQuote(sq, makerAuthority, direction, cfg, nowSecs)null if the quote is valid for this maker, direction and program fee; otherwise the reason.

SOL → XMR: handshake and lock

prepareSolToXmr runs the whole handshake and checks everything the maker returns before anything is signed: the maker's key is a valid point that doesn't cancel yours, the fee matches the program, the deadlines are safe, the shared address is right, at least one watchtower acknowledged the view key, and the consent signature verifies. It returns the two instructions to sign.

TypeScript
const { endpoint, info } = live[0];
const maker = new PublicKey(info.maker);
const sq = await T.api.quote(endpoint, P.DIR_SOL_TO_XMR, 1_000_000_000n);   // 1 SOL
const now = await chainNow(conn);       // chain time from the Clock sysvar (chainNow in maker/lib.ts)
const why = T.checkQuote(sq, maker, 1, cfg, now);
if (why) throw new Error(why);

const swapId = K.newSwapId();
const half = K.deriveHalf(root, swapId);
const prepared = await T.prepareSolToXmr({
  pid, endpoint, makerAuthority: maker, cfg, policy: T.MAINNET_POLICY,
  sq, swapId, locker: wallet.publicKey, half, net: 'mainnet',
  watchtowers, nowSecs: now,             // [{ url, pubkey }] from your config
});
await send(prepared.ixs);                // [consent, lock] in one transaction
// prepared.escrow: the swap account · prepared.shared.address: the Monero address both halves open

send is your wallet adapter: build a transaction from the instructions, sign, send, confirm. To sell a coin other than SOL, put a Jupiter route in front of the same two instructions (below).

Tracking a swap

TypeScript
const acct = await conn.getAccountInfo(prepared.escrow);
const e = P.decodeEscrow(acct!.data, prepared.escrow);
const phase = T.phaseOf(e, wallet.publicKey, now, T.MAINNET_POLICY);
// 'waiting-xmr' | 'releasing' | 'auto-release' | 'collect' | 'refund' | 'refunded'
// | 'deposit' | 'claim-sol' | 'xmr-back' | 'paid' | 'done'

const st = await T.api.status(endpoint, prepared.escrow.toBase58());
// { phase, xmrLockTx?, confirmations?, required? }: the maker's hint, never proof

const mine = await T.findMySwaps(conn, pid, wallet.publicKey);   // every swap this wallet is a side of

The maker's status is a hint. Only show "Maker sent your XMR" after your own check below. The maker can claim only after your ready, so release once that check passes.

Checking the XMR and releasing early

TypeScript
import { verifyLockCrossChecked } from './sdk/xmrverify.ts';

const check = await verifyLockCrossChecked({
  daemonUri: 'https://node-a.example,https://node-b.example',   // two independent nodes must agree
  txHash: st.xmrLockTx!,
  spendPub: K.pointAdd(e.claimPoint, e.refundPoint),
  viewSecret: half.view,
  minAmount: e.xmrAmount,
  minConf: 10,
});
// check.amount is proven against the output's commitment; check.confirmations counts to 10
if (check.ok) await send([P.ixReady(pid, wallet.publicKey, prepared.escrow)]);   // the maker can claim at once

verifyLock (one node) also answers for a transaction still in the mempool: inPool: true, amount checked, 0 confirmations. That is what turns "Maker sent your XMR" green after a minute or two.

Cancel and refund

CallWhen
P.ixAbort(pid, who, escrow, makerAuthority)Before t0: the locker or a listed watchtower cancels. Reveals nothing.
T.refundSafe(conn, escrow)true once the escrow is cancelled or past t1 at finalized commitment. Only then may your refund secret leave the browser.
T.api.relayRefund(endpoint, escrow, secretHex)Asks the maker to submit your refund and pay its fee. The program pays only you.
P.ixRefund(pid, payer, escrow, locker, makerAuthority, secret)Submit the refund yourself. In SOL → XMR, secret is your half's spend scalar, which lets the maker take its XMR back.

Collecting the XMR

TypeScript
import { collect, exportKeys } from './sdk/collect.ts';

const settled = P.decodeEscrow((await conn.getAccountInfo(prepared.escrow))!.data, prepared.escrow);
const myHalf = T.myHalfFor(root, settled, wallet.publicKey);     // throws if this wallet didn't make the swap
const spendKey = T.fullSpendKey(settled, myHalf);                 // the maker's revealed half + yours
const restoreHeight = T.restoreHeightFor(settled, moneroTipHeight, now);

const r = await collect({
  spendKey, viewKey: myHalf.view, net: 'mainnet', daemonUri: MONEROD, restoreHeight,
  destination: '4...your address', expectPiconero: settled.xmrAmount,
  onProgress: (m, pct) => console.log(m, pct),
});
// r.txHashes, r.sweptPiconero, r.feePiconero

const keys = exportKeys(spendKey, myHalf.view, 'mainnet', restoreHeight);   // for Cake Wallet or Feather

collect runs monero-ts in-process; the full spend key never leaves it. In a browser, call setMoneroWorkerUrl first if monero.worker.js isn't served next to the page.

XMR → SOL and fresh addresses

The maker locks SOL first. Before showing a deposit address, check its proof that it knows its key half, the escrow on chain, and the refund towers' receipts: fetch each tower's GET <url>/ack/<escrow> and pass them as refundTowers: { listed, minAcks, acks }. Without enough receipts it throws, and no address is shown.

TypeScript
import * as ST from './sdk/stealth.ts';

const meta = ST.deriveStealthMeta(root);                                  // view + spend keys from your root
const { swapId, claimer } = await ST.stealthClaimerForSwap(conn, pid, meta, maker);   // your browser picks R
const half = K.deriveHalf(root, swapId);
const sq = await T.api.quote(endpoint, P.DIR_XMR_TO_SOL, 1_000_000_000_000n);          // 1 XMR in piconero
const res = await T.api.swap<T.SwapResponseXmrToSol>(endpoint, {
  quote: sq.quote, sig: sq.sig, swapId: K.toHex(swapId), taker: claimer.toBase58(),
  takerSpendPub: K.toHex(half.spendPub), viewSecret: K.toHex(half.view),
});
const { depositAddress, depositBy } = await T.verifyXmrToSolEscrow({
  conn, pid, escrow: new PublicKey(res.escrow), makerAuthority: maker, sq,
  claimer, half, makerSpendPub: K.fromHex(res.makerSpendPub), net: 'mainnet',
  policy: T.MAINNET_POLICY, nowSecs: await chainNow(conn), terms: T.termsOf(info),
  makerKeyProof: K.fromHex(res.makerKeyProof),
});
// show depositAddress and the "send by" time depositBy

After 10 confirmations the maker says ready; then claim with T.relayClaimEverywhere, passing your watchtowers and half.spend as the secret. It sends the same signed claim through every watchtower at once, each paying the fee; one landing is enough. The maker never submits it, because the claim carries your secret. The claim is signed by the one-time address: new ST.StealthSigner(ST.oneTimeSecret(meta, swapId)). Later, ST.scanStealth(conn, pid, meta) finds every fresh-address balance and ST.sweep({ conn, signer, to }) moves it; the address pays its own fee.

Any coin through Jupiter

TypeScript
import * as J from './sdk/jupiter.ts';

const route = await J.buildRoute({ inputMint: COIN_MINT, outputMint: J.WSOL, amount: coinAmount, taker: wallet.publicKey.toBase58() });
if (J.impactLevel(route) === 'refuse') throw new Error('price impact above 10%');
// quote the maker for at most route.minOut, run prepareSolToXmr as above, then:
const swap = J.routeInstructions(route, wallet.publicKey);
const alts = await J.loadAlts(conn, route);
const { blockhash } = await conn.getLatestBlockhash('confirmed');
const c = J.composeSell({
  user: wallet.publicKey, blockhash, route, swap, alts,
  lockIxs: prepared.ixs, lockLamports: quotedSol,   // the maker's quote, never more than route.minOut
  memo: saleMemo,                                     // J.soldMemo(...): tags the sale so any device finds it
});
// c.mode === 'one': one atomic transaction; 'two': the sale, then the lock (send the lock only after the sale confirmed)

J.findUnlocked(conn, pid, wallet) finds sales that landed without their lock on any device, so the user can lock or keep the SOL. J.sellQuote turns a route and a maker quote into the numbers the card shows.

Pay links and invoices

FunctionWhat it does
getLink(conn, pid, name)Reads /pay/name from chain, or null.
preparePay({ pid, endpoint, makerAuthority, cfg, policy, sq, link, payer, swapId, net, watchtowers, nowSecs })The pay handshake: watchtowers the maker accepts, a consent bound to the link, every term checked. Returns [consent, lock].
payPhase(escrow, chainNow)pending · releasing · paid · refund · refunded.
paymentsTo(conn, pid, link)Every payment to a link, for the recipient.
collectKeys(root, link, escrow, net)The recipient's one-time spend and view keys for a settled payment; pass them to collect.
linkMaster(root, name)The link's master secret and point, from the owner's wallet root.
encodeInvoice(inv)decodeInvoice(s), invoiceId(inv): an invoice is an XMR amount and a memo; its hash is the payment id.

Cashout vaults

FunctionWhat it does
vaultOf(conn, pid, owner)The owner's vault account, or null.
vaultEscrows(conn, pid, vault)Every conversion the vault made.
vaultFree(conn, vault)SOL in the vault available to convert.
P.ixVaultCreate, P.ixVaultTighten, P.ixVaultPropose, P.ixVaultApplyCreate a vault, tighten it at once, or propose a change that applies after the timelock.
P.ixVaultWithdrawRequest, P.ixVaultWithdrawWithdraw to the owner, after the timelock.

OTC

TypeScript
import * as O from './sdk/otc.ts';
import { platformApi, acceptOtc } from './sdk/platform.ts';

const rfq = O.newRfq(1, size, minFill, wallet.publicKey.toBase58());       // side 1: sell SOL for XMR
const sig = K.toHex(await wallet.signMessage(O.rfqBytes(rfq)));
const ans = await platformApi.otcRfq(endpoint, rfq, sig);                   // { status, quote?, sig? }
const bad = O.checkOtcQuote(ans.quote!, ans.sig!, rfq, maker.toBytes(), { feeBps: [cfg.feeBps, cfg.holderFeeBps], capLamports: cap, now });
if (bad) throw new Error(bad);
const tranches = await acceptOtc({ conn, pid, endpoint, makerAuthority: maker, cfg, policy: T.MAINNET_POLICY,
  quote: ans.quote!, sig: ans.sig!, rfq, root, taker: wallet.publicKey, net: 'mainnet', nowSecs: now,
  watchtowers, capLamports: cap, signAccept: (b) => wallet.signMessage(b) });
// side 1: each tranche carries its [consent, lock]; sign them all in one wallet prompt

Staking and the burn

FunctionWhat it does
V.ixPoolStake(pid, owner, mint, source, amount)Stake $HALFKEY. Runs the fee split first.
V.ixPoolUnstakeRequest(pid, owner, amount = 0n)Stop earning now (0 = all); the tokens leave after the unbond delay.
V.ixPoolUnstake(pid, owner, mint, dest)Return unbonded tokens after the delay.
V.ixPoolClaim(pid, owner)Pay all owed rewards in SOL. No return value, so it can sit first in a transaction with a lock after it.
V.claimableRewards(pool, staker, balances)What a claim would pay right now, including the unsplit fees.
V.ixSplitFees(pid, who)Run the 50/50 split. Anyone can.
V.burnQuote(burn, vaultBalance, rentKeep, now)The current lot, price and $HALFKEY cost of a burn take.
V.ixBurnTake(pid, buyer, mint, source, maxBurn, minSol)Burn $HALFKEY from your account for a lot of the burn balance, within your bounds.

Import as import * as V from './sdk/v15.ts'.

ZEC

FunctionSideWhat it does
zecKeys(root, swapId)bothClaim and refund keys, the secret and its hash lock, all from your wallet root.
verifySolToZecOffer(offer, ctx)SOL → ZECChecks the maker's offer with no chain access; returns the Solana lock terms.
checkZecLock(rpc, upgrades, offer, lock, now, policy)SOL → ZECChecks the maker's ZEC lock on a node: script, amount, confirmations, refund height, no upgrade inside the window.
presignClaim(offer, value, claimPriv, dest, net, branch)SOL → ZECYour ZEC claim, signed before the secret exists, for the watchtowers.
solToZecLockIxs(pid, taker, lock, consentSig)SOL → ZECThe [consent, lock] instructions.
verifyZecToSolOffer(offer, ctx)ZEC → SOLThe deposit address really is your hash lock and refund key, with a sane refund height.
presignRefund(offer, fundTxid, vout, value, refundPriv, dest, net, branch)ZEC → SOLYour ZEC refund for after the refund height.
verifyZecToSolLock(htlc, ctx)ZEC → SOLChecks the maker's SOL lock before you claim.

Errors

P.errName(e) turns a program error from a failed transaction into its name (for example TooLate for a claim past the deadline, BondLocked for an early withdraw). SDK checks throw plain Errors with a sentence that says what didn't match; show it to the user as is.

SOL $— XMR $— 1 SOL = — XMR Monero block — · — Watchtowers — Solana mainnet · Monero mainnet