# Paralock documentation > Paralock does trustless swaps and payments between shielded ZEC and stablecoins on EVM chains (Tempo, Base, Ethereum, Arbitrum, Robinhood Chain and HyperEVM). There is a lock on each chain and one secret opens both, so either both sides settle or both refund: no bridge, custodian or wrapped token. The TypeScript SDK is published on npm as the `@paralock/*` packages; a Rust port is in progress. Every page of https://paralock.xyz/docs in reading order. Index: https://paralock.xyz/llms.txt --- # Introduction Source: https://paralock.xyz/docs Markdown: https://paralock.xyz/docs/introduction.md Section: Getting started > What Paralock is, who it is for, and what ships in the repository today. Paralock lets you swap shielded ZEC for stablecoins, or pay someone an exact dollar amount from shielded ZEC, with no bridge, custodian or wrapped token in between. Settlement happens on the two native chains: Zcash on one side and an EVM chain on the other. | Chain | Stablecoin | |---|---| | Tempo | OUSD | | Base, Ethereum, Arbitrum, HyperEVM | USDC | | Robinhood Chain | USDC on the devnet; a 6-decimal MockUSD test token on Robinhood Chain Testnet, which has no USDC | [Where Paralock works](https://paralock.xyz/docs/networks) lists every network, Zcash backend and wallet in detail. > **Warning:** Paralock is experimental and has not been audited by a third party. The escrow contracts are deployed on six public testnets only, and there is no mainnet support. In both modes the Zcash leg is a transparent output, so you shield your ZEC before and after a swap. **Use these docs from your AI tools** - **Index:** [`/llms.txt`](https://paralock.xyz/llms.txt) lists every page with a one-line summary - **Everything:** [`/llms-full.txt`](https://paralock.xyz/llms-full.txt) has every page in one file - **Any page:** append `.md` to its URL, or ask for it with `Accept: text/markdown` - **Skill:** `npx skills add bitfalt/paralock` teaches a coding agent the SDK and its safety rules - **MCP server:** `https://paralock.xyz/mcp` is read-only and keyless, with `list_docs`, `read_doc`, `search_docs` and `get_deployments` **Claude Code**: ```sh claude mcp add --transport http paralock https://paralock.xyz/mcp ``` **Codex**: ```sh codex mcp add paralock --url https://paralock.xyz/mcp ``` **Cursor** (`.cursor/mcp.json`): ```json { "mcpServers": { "paralock": { "url": "https://paralock.xyz/mcp" } } } ``` **VS Code** (`.mcp.json`): ```json { "mcpServers": { "paralock": { "type": "http", "url": "https://paralock.xyz/mcp" } } } ``` **Gemini CLI**: ```sh gemini mcp add --transport http --scope user paralock https://paralock.xyz/mcp ``` **Pi**: ```sh pi mcp add paralock --url https://paralock.xyz/mcp ``` Claude Desktop and claude.ai, OpenCode, Windsurf (now Devin Desktop), Zed, Cline and the details for each: [For AI agents](https://paralock.xyz/docs/ai-agents#connect-the-mcp-server). ## Two locks, one key A swap has two parties. The **taker** has ZEC and wants dollars. The **maker** holds stablecoins, quotes a price and earns a spread. Each of them locks funds on their own chain, and one secret opens both locks: 1. The taker picks a secret and keeps it to itself. 2. The taker locks ZEC on Zcash. Only the maker can take it, and only with the secret. If nobody takes it by block N, the taker gets it back. 3. The maker checks that lock, then locks stablecoins on the EVM chain. The taker can take them with the secret before time T. After T, the maker gets them back. T comes well before block N. 4. The taker claims the stablecoins. Claiming makes the secret public. 5. The maker uses the now-public secret to claim the ZEC. Either both sides settle or both refund. The Zcash script and the EVM contract enforce this, not a person or a company. [How it works](https://paralock.xyz/docs/how-it-works) walks through every step, both modes and every failure case. Paralock has two modes: - **`htlc`** (hash time-locked contract): the secret is a 32-byte preimage, and the same sha256 hash locks both chains. - **`adaptor`** (private mode, experimental): the ZEC sits in an ordinary 2-of-2 multisig, the EVM escrow releases on a signature, and the secret is hidden inside ECDSA adaptor signatures. No hash or other shared value appears on either chain. ## Who it is for - **Wallets:** add "pay in dollars" to a Zcash wallet. Users spend shielded savings anywhere stablecoins work, without an exchange account. - **Apps and shops:** accept payment from ZEC holders and receive exact dollars through a [payment link](https://paralock.xyz/docs/pay). You never touch ZEC. - **Agents:** an AI agent that holds ZEC can buy dollars just in time to pay for an API. See [For AI agents](https://paralock.xyz/docs/ai-agents). - **Makers:** run the other side of the swap, provide stablecoin liquidity and earn the spread. See [Run a maker](https://paralock.xyz/docs/run-a-maker). The SDK is a public good under the MIT license. The business model is running the maker: it quotes the price and earns the spread on every swap it fills. The protocol is symmetric, so anyone running the SDK can be a maker, including peer to peer. ## What's in the box | Component | What it is | Version | Status | |---|---|---|---| | [`@paralock/sdk`](https://paralock.xyz/docs/sdk) | `createTaker` and `createMaker`, both swap modes, crash-safe persistence, recovery, quote validation, maker limits, an HTTP maker API | 0.3.2 | Shipped | | [`@paralock/zcash`](https://paralock.xyz/docs/zcash) | Zcash HTLCs and 2-of-2 locks, v5 transactions, ZIP 244 signing, ZIP 317 fees, a Zebra RPC client. Browser-safe | 0.3.2 | Shipped | | [`@paralock/adaptor`](https://paralock.xyz/docs/adaptor) | ECDSA adaptor signatures on secp256k1 with DLEQ proofs. Browser-safe | 0.1.4 | Experimental | | [`@paralock/evm`](https://paralock.xyz/docs/evm) | viem clients for both escrows and a verified network registry | 0.3.2 | Shipped | | [`@paralock/lightwalletd`](https://paralock.xyz/docs/lightwalletd) | A Zcash backend over a lightwalletd or Zaino server, so you don't run a full node | 0.1.3 | Shipped | | [`paralock` CLI](https://paralock.xyz/docs/cli) | `npx paralock`: `doctor`, `dev`, `devnet`, `maker`, `swap`, `pay`, `swaps`, `resume`, `refund`. A one-command local devnet with Zcash regtest and up to six EVM chains | 0.3.2 | Shipped | | [Rust SDK](https://paralock.xyz/docs/rust) | `paralock` on crates.io: taker and maker engines, Zcash RPC and lightwalletd backends, durable stores, the maker HTTP server and client. Built on `paralock-core` (the protocol core, also for wasm32) and `paralock-evm` (alloy clients). Wire-compatible with `@paralock/sdk` | 0.1.1 | Shipped | | [Rust CLI](https://paralock.xyz/docs/rust-cli) | `paralock-cli`: a standalone `paralock` binary for swaps, payments, recovery and a maker on any network, configured by `paralock.toml`. Prebuilt for macOS and Linux | 0.1.1 | Shipped | | [Contracts](https://paralock.xyz/docs/contracts) | `ParalockHTLC` and `ParalockAdaptorEscrow`, deployed and source-verified on Tempo Moderato, Base Sepolia, Sepolia, Arbitrum Sepolia, Robinhood Chain Testnet and HyperEVM Testnet | | Testnets only | | [Protocol spec](https://github.com/bitfalt/paralock/blob/main/spec/PROTOCOL.md) | The wire protocol, both flows and the safety rules, with cross-language test vectors in `spec/vectors` | v1.1 | Draft | | Examples | TypeScript: `quickstart`, `payroll`, `sell-a-secret` on the devnet, and `testnet` on public testnets. Rust: six in `examples/rust` | | Shipped | | Web app | Pay with payment links, and Swap, at `/app` | | Shipped | | Agent docs | A skill, `llms.txt`, Markdown pages and an MCP server | | Shipped | The npm packages are at 0.3.2 (0.3.0 was the CLI's first npm release), and features this site marks "in 0.3.0" need 0.3.0 or newer. They are ESM-only and need Node.js 20 or newer; `@paralock/zcash`, `@paralock/adaptor` and `@paralock/evm` also run in browsers. The Rust crates are published on crates.io at 0.1.1. ```sh npm install @paralock/sdk # also installs @paralock/zcash, /evm and /adaptor npx paralock dev # a local devnet and a maker npx paralock swap --zec 1 # your first swap on it ``` ### Rust The same protocol is published in Rust, as four crates on [crates.io](https://crates.io/crates/paralock): - [`paralock`](https://docs.rs/paralock): the Rust SDK. Embed a taker or a maker (served with axum) in a Rust service, with no Node.js process. It interoperates with the TypeScript SDK on the wire. - [`paralock-core`](https://docs.rs/paralock-core): the protocol core. Pure and synchronous (no I/O), byte-for-byte equal to the TypeScript packages on the shared vectors in `spec/vectors`, and it builds for wasm32. - [`paralock-evm`](https://docs.rs/paralock-evm): alloy clients for both escrows, Tempo fee tokens and the verified network registry. - [`paralock-cli`](https://docs.rs/paralock-cli): the standalone `paralock` binary. ```sh cargo add paralock --features evm,price-feed # the SDK, with the builders that connect to RPC URLs curl -fsSL https://paralock.xyz/install | sh # or the binary: cargo install paralock-cli ``` See [Rust SDK](https://paralock.xyz/docs/rust) and [Rust CLI](https://paralock.xyz/docs/rust-cli). ## Status | Feature | Status | |---|---| | htlc mode, end to end on the devnet and on public testnets ([first runs](https://github.com/bitfalt/paralock/blob/main/docs/TESTNET-RUNS.md)) | Shipped | | Private mode (adaptor signatures) | Experimental | | Privacy hygiene: shield before and after, fresh recipient, relayed claim, standard amounts, jitter | Shipped | | Fully shielded Zcash leg (FROST) | In research | | Testnet deployments on six EVM testnets | Shipped | | Rust SDK, protocol core and `paralock` binary on crates.io | Shipped | | Mainnet | Not supported; only after an audit | Swaps currently run in one direction: the taker sells ZEC for stablecoins. Refunds pay a transparent Zcash address. The [roadmap](https://paralock.xyz/docs/roadmap) lists what is shipped, in progress, next and in research, with the reason for each. ## Where to go next - [Quickstart](https://paralock.xyz/docs/quickstart): run a full swap on your machine in a few minutes. - [Where Paralock works](https://paralock.xyz/docs/networks): the networks, Zcash nodes, wallets and runtimes it supports today. - [How it works](https://paralock.xyz/docs/how-it-works): the protocol, the timelines and why nothing can be stolen. - [Payments and payment links](https://paralock.xyz/docs/pay): pay an exact dollar amount to anyone. - [Rust SDK](https://paralock.xyz/docs/rust): embed a taker or a maker in a Rust service, or use the `paralock` binary. - [Swap on public testnets](https://paralock.xyz/docs/testnet): a real swap between Zcash testnet and Tempo Moderato. - [Security model](https://paralock.xyz/docs/security): what you trust, and what is still missing. - [Roadmap](https://paralock.xyz/docs/roadmap): what ships next, and why. --- # Quickstart Source: https://paralock.xyz/docs/quickstart Markdown: https://paralock.xyz/docs/quickstart.md Section: Getting started > Run a complete ZEC-to-stablecoin swap on a local devnet, then drive the same flow from your own code with the SDK. This page takes you from nothing to a completed swap on your machine. The local devnet runs a Zcash regtest chain, three EVM chains by default (six with `--evm all`), both escrow contracts and a maker, so nothing touches a public network and no real funds are involved. > **Note:** `npx paralock` runs the [CLI](https://paralock.xyz/docs/cli) from npm with no clone of the repository. To work on the code, use a checkout instead: run `pnpm install && pnpm build` and use `pnpm paralock` instead, the same commands run from the workspace build. The web app and the examples need a checkout. ## Prerequisites Install these first. `npx paralock doctor` checks every one of them and prints the same fix commands. | Tool | Why | Install | |---|---|---| | Node.js 20 or newer | Runs the CLI and the packages | From [nodejs.org](https://nodejs.org), or `nvm install --lts` | | Docker or OrbStack | Runs the Zcash regtest node; the daemon must be running | `brew install orbstack` on macOS (or Docker Desktop); Docker Engine on Linux, usable without `sudo` | | [Foundry](https://getfoundry.sh) 1.8 or newer | Only for `anvil`, which runs the local EVM chains (including `anvil --network tempo`). The contracts are deployed from bytecode embedded in `@paralock/evm` | `curl -L https://foundry.paradigm.xyz \| bash && foundryup` | | [`ths`](https://github.com/zcashlabs/thus-spoke-zakura) | A one-command Zcash regtest (Zakura plus lightwalletd) with a faucet and a dashboard | `curl --proto '=https' --tlsv1.2 -fsSL https://raw.githubusercontent.com/zcashlabs/thus-spoke-zakura/main/install.sh \| sh` | | pnpm (checkout only) | The workspace's package manager, for the web app and the examples | `corepack enable pnpm`, or `npm install -g pnpm` | The commands, ready to copy: ```sh nvm install --lts # or install Node 20+ from nodejs.org brew install orbstack # macOS; or Docker Desktop / Docker Engine curl -L https://foundry.paradigm.xyz | bash && foundryup curl --proto '=https' --tlsv1.2 -fsSL https://raw.githubusercontent.com/zcashlabs/thus-spoke-zakura/main/install.sh | sh corepack enable pnpm # only to work in a checkout; or: npm install -g pnpm ``` ## 1. Check your machine ```sh npx paralock doctor ``` `doctor` prints where the CLI keeps its state, then checks Node, the Docker daemon, `ths`, that `anvil` is 1.8 or newer and supports `--network tempo`, and that every port is free or already used by the matching Paralock service. In a checkout it also checks pnpm, installed dependencies and built packages. Each failed check prints the command that fixes it. Fix them and run `doctor` again until all required checks pass. The CLI keeps the devnet's state (endpoints, keys, swap stores, logs) in `/.paralock` inside a checkout of the repository, and otherwise in `$PARALOCK_HOME` or `~/.paralock`. This page calls it the state directory. ## 2. Optional: clone and build The CLI is all you need for steps 3 to 7 and 9 to 10. For the web app (step 8) and the SDK examples, work in a checkout: ```sh git clone https://github.com/bitfalt/paralock && cd paralock pnpm install && pnpm build ``` `pnpm build` compiles every package, including the CLI that `pnpm paralock` runs. From the repository root, `pnpm paralock ` does what `npx paralock ` does, with the state in `.paralock/`. ## 3. Start everything ```sh npx paralock dev ``` This one command: 1. runs `doctor` and stops if a required check fails; 2. starts Zcash regtest through `ths` (a Zakura node plus lightwalletd); 3. starts one anvil per EVM chain: by default **Tempo, Base and Ethereum**. Add `--evm all` for all six, which adds Arbitrum, Robinhood Chain and HyperEVM, or pick chains with a comma-separated list such as `--evm tempo,arbitrum`; 4. deploys `ParalockHTLC`, `ParalockAdaptorEscrow` and a local stablecoin on each EVM chain (an OUSD stand-in on Tempo, a 6-decimal MockUSD "USDC" elsewhere) and writes every endpoint, address and key to `devnet.json` in the state directory; 5. starts the maker in the background on port 7420 (change it with `--maker-port`), which quotes every devnet chain in both modes and mines a regtest block every 3 seconds; 6. in a checkout, with `--web` (`pnpm paralock dev --web`), starts the web app on `http://localhost:3000` (change the port with `--web-port`). It reuses anything that is already running, so you can run it again at any time, for example with `--evm all` to add chains. When it finishes, it prints the endpoints and the next commands to try. Logs of the background processes are in `maker.log` and `web.log` in the state directory. > **Note:** The devnet maker prices ZEC from CoinGecko and falls back to a fixed $1,270 when the feed is unreachable. That fallback exists only on the devnet: a fixed price with real funds would let anyone trade against you at a stale rate. ### What's running | Service | Address | |---|---| | Zcash RPC (Zakura regtest) | `http://127.0.0.1:18232` | | lightwalletd | `127.0.0.1:9067` | | ths dashboard (wallet balances, faucet) | `http://127.0.0.1:32805` | | Tempo, Base, Ethereum anvils | ports 8545, 8546, 8547 (chain ids 31337, 31338, 31339) | | Arbitrum, Robinhood Chain, HyperEVM anvils (`--evm all`) | ports 8548, 8549, 8550 (chain ids 31340, 31341, 31342) | | Maker | `http://127.0.0.1:7420` | | Web app (`--web`, checkout only) | `http://localhost:3000` | `npx paralock devnet status` prints the state directory, the chain heights and the contract addresses. The devnet assigns these roles: | Role | Zcash | EVM | |---|---|---| | Taker | ths account 1 holds the shielded savings; ths account 2 is the swap address Paralock spends from | anvil dev account 1 | | Maker | ths account 5 | anvil dev account 0 | | Relayer | none | anvil dev account 2 | > **Warning:** Anvil's dev keys are public. Never use them on a real network. The state directory holds the ths mnemonic and devnet keys: keep it private. In a checkout it is `.paralock/`, which is gitignored, so keep it out of commits. ## 4. Swap ZEC for stablecoins `dev` returns once everything is up; the maker (and the web app, if you started it) keeps running in the background. In the same terminal or a second one: ```sh npx paralock swap --zec 1 ``` This sells 1 ZEC for OUSD on Tempo in htlc mode. The CLI prints the quote (amount, rate, the 40-block Zcash refund window and the 45-second EVM lock), unshields what the swap needs (the quoted ZEC plus a small fee buffer) from the taker's shielded balance into the swap address, and then prints each step: | Status | What happened | |---|---| | `quoted` | The maker accepted the HTLC and reserved its OUSD; the taker broadcasts its funding next | | `zcash_locked` | The taker locked the ZEC in a Zcash HTLC | | `evm_locked` | The maker locked OUSD on Tempo; the taker verified recipient, token, amount and time left | | `evm_claimed` | The taker claimed the OUSD, which made the secret public | | `completed` | The maker used the secret to claim the ZEC | Leftover change goes back into the taker's shielded balance, and the maker shields the ZEC it claimed. > **Note:** The devnet runs with short windows so you can watch the failure cases: a 40-block Zcash window at one block every 3 seconds (about 2 minutes) and a 45-second EVM lock. Public networks use much longer windows; see [How it works](https://paralock.xyz/docs/how-it-works#timelines). ## 5. Try private mode ```sh npx paralock swap --zec 1 --chain base --private ``` Same swap, settled on Base in USDC, in private mode (`adaptor`): the ZEC sits in a plain 2-of-2 multisig, and the secret travels inside adaptor signatures, so no hash appears on either chain. Add `--fresh-recipient --relay` to receive at a new address created for this swap, with a relayer paying the claim gas. [Privacy](https://paralock.xyz/docs/privacy) explains each option. ## 6. Pay someone an exact amount ```sh npx paralock pay --usd 25 --to 0x90F79bf6EB2c4f870365E785982E1f101E93b906 --chain base --label "Acme Coffee" ``` The recipient (here anvil dev account 3) receives exactly 25.00 USDC. The maker quotes exact-out: the dollar amount is fixed and the ZEC amount rounds up. See [Payments and payment links](https://paralock.xyz/docs/pay). ## 7. Watch a refund ```sh npx paralock swap --zec 0.5 --refund-demo ``` The taker locks 0.5 ZEC and the maker never responds. Once the chain reaches the refund height, the taker takes the ZEC back and shields it again. No funds are lost. ## 8. Use the web app The web app ships with the repository, not with the CLI. In a checkout, start it with `pnpm paralock dev --web` (or `pnpm --filter web dev`), then open `http://localhost:3000/app`. With the devnet running, the app's API routes run the real SDK against your local chains. It has two flows: **Swap** (sell an amount of ZEC) and **Pay** (send exact dollars to an address). A payment link such as `http://localhost:3000/app?pay=0x90F79bf6EB2c4f870365E785982E1f101E93b906&usd=25&chain=base&label=Acme%20Coffee` opens Pay with everything filled in. ## 9. Recover a swap Every swap the CLI or the web app starts is saved in the state directory's `taker/` store before anything is broadcast: ```sh npx paralock swaps # unfinished swaps npx paralock resume # continue one after a crash or restart npx paralock refund # take the ZEC back once its refund height is reached ``` [Persistence and recovery](https://paralock.xyz/docs/recovery) covers what is stored and how the engines resume. ## 10. Stop the devnet ```sh npx paralock devnet down ``` This stops the maker and web app that `dev` started, runs `ths stop`, stops the anvils Paralock started, and deletes `devnet.json`. Processes Paralock didn't start are left running. The swap stores in `taker/` and `maker/` are kept. ### Step by step instead of `dev` `dev` combines these commands, which you can also run yourself: ```sh npx paralock devnet up --evm all # Zcash regtest + EVM anvils + contracts, writes devnet.json npx paralock maker # terminal 1: the maker on :7420 (stays in the foreground) npx paralock swap --zec 1 # terminal 2 pnpm --filter web dev # in a checkout: the web app (Next.js allows one dev server per checkout) ``` ## Use the SDK in your own code The CLI is a thin layer over `@paralock/sdk`. The `examples/quickstart` app is the "hello world": about 60 lines that build a taker with `createTaker`, get a validated quote, swap, and demonstrate the refund path. Run it against the devnet, from a checkout: ```sh pnpm paralock dev --evm all # from the repo root pnpm --filter @paralock/example-quickstart start # quote, swap, done (htlc mode) pnpm --filter @paralock/example-quickstart start -- --private # private mode (adaptor) pnpm --filter @paralock/example-quickstart start -- --refund # the maker never locks: refund ``` Here is its core. To use it in another project, `npm install @paralock/sdk @paralock/zcash`. `devnetFilePath()` finds the devnet the same way the CLI does: `/.paralock/devnet.json` inside a checkout, otherwise in `$PARALOCK_HOME` or `~/.paralock`, so a devnet started with `npx paralock dev` is found from any directory. ```ts import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { type Swap, createTaker, devnetFilePath } from "@paralock/sdk"; import { ZcashRpc, bytesToHex, randomKeyPair } from "@paralock/zcash"; // Endpoints, contract addresses and the taker's EVM key, read from the devnet as plain config. // devnetFilePath() looks in the CLI's state directory (see above); it throws if no devnet is running. const devnet = JSON.parse(readFileSync(devnetFilePath(), "utf8")); const base = devnet.evm.base; // A Zcash key for the swap address. Keep it: htlc refunds are signed with it. mkdirSync(".quickstart", { recursive: true, mode: 0o700 }); if (!existsSync(".quickstart/zcash.key")) { writeFileSync(".quickstart/zcash.key", bytesToHex(randomKeyPair().privateKey), { mode: 0o600 }); } const taker = createTaker({ zcash: { rpcUrl: devnet.zcash.rpc, network: "regtest", key: readFileSync(".quickstart/zcash.key", "utf8") }, evm: { base: { rpcUrl: base.rpc, chainId: base.chainId, htlc: base.htlc, adaptorEscrow: base.adaptorEscrow, account: devnet.taker.evmKey, fromBlock: base.startBlock, tokens: [base.tokens[base.quoteToken]], // only accept quotes that pay this stablecoin }, }, maker: devnet.maker.url, store: ".quickstart/swaps", // secrets and refund data, written before anything is broadcast limits: { minClaimWindowSeconds: 15 }, // the devnet's EVM locks last 45 s mineZcash: (blocks) => new ZcashRpc(devnet.zcash.rpc).generate(blocks), // devnet only onUpdate: (swap: Swap) => console.log(swap.status.padEnd(14), swap.events.at(-1)?.detail ?? ""), }); // Fund the swap address. On the devnet the ths faucet pays it; elsewhere you send ZEC from your wallet. await fetch(`${devnet.zcash.dashboard}/api/v1/faucet/address`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ address: taker.zcashAddress, amount_zatoshi: 10_050_000, idempotency_key: crypto.randomUUID() }), }); const quote = await taker.quote(10_000_000n, "base", "htlc"); // 0.1 ZEC, validated const swap = await taker.swap(quote); // lock ZEC, verify the maker's lock, claim console.log(`${swap.evm.recipient} received ${Number(swap.evm.amount) / 1e6} ${quote.tokenSymbol}`); ``` What each part does: - **Amounts are `bigint`.** ZEC is in zatoshi (1 ZEC = 100,000,000 zat), so `10_000_000n` is 0.1 ZEC. Dollars are in token base units with 6 decimals. - **`tokens`** lists the stablecoins you accept on this chain. The taker rejects any quote that pays a different token. - **`store`** is a directory for a `FileSwapStore`. The swap secret and refund data are written there before the funding transaction is broadcast, so a crash never strands your ZEC. - **`taker.quote`** asks the maker for a price and validates it: the maker's key, the chain id (also checked against your RPC node), the token, the lock windows and the expiry. - **`taker.swap`** has the maker accept and reserve its stablecoins, then locks the ZEC, waits for the maker's EVM lock, verifies it on-chain and only then claims. - **`mineZcash`** mines regtest blocks so a refund doesn't wait for real time. Leave it out anywhere else. The refund path is two calls. `lockOnly` funds the Zcash lock without involving the maker, and `refund` returns the ZEC once the refund height is reached. It also works from a fresh process, because everything it needs is in the store. ```ts const quote = await taker.quote(10_000_000n, "base", "htlc"); const locked = await taker.lockOnly(quote); // fund the Zcash lock but never involve the maker await taker.refund(locked.id); // waits for the refund height, then returns the ZEC ``` On a real network you pass your own node, contracts, keys and maker URL to the same `createTaker` call; [Where Paralock works](https://paralock.xyz/docs/networks) lists the supported networks and Zcash backends. Contract addresses and start blocks for the public testnets are in `contracts/deployments/.json` and on the [contracts page](https://paralock.xyz/docs/contracts). ## From Rust The [Rust SDK](https://paralock.xyz/docs/rust) and the [`paralock` binary](https://paralock.xyz/docs/rust-cli) run against the same devnet, and trade with the TypeScript maker that `dev` started. With the binary (`cargo install paralock-cli`, or `curl -fsSL https://paralock.xyz/install | sh`): ```sh paralock --devnet doctor # reads devnet.json from the state directory paralock --devnet swap --zec 0.1 # htlc on Tempo, against the maker on :7420 paralock --devnet swap --zec 0.1 --chain base --private ``` From code, `examples/rust/rust-quickstart` is the Rust "hello world": `create_taker`, one quote, one swap, in about 100 lines. From a checkout: ```sh cargo run -p rust-quickstart # 0.1 ZEC to USDC on Base, htlc mode cargo run -p rust-quickstart -- --zec 0.25 --chain tempo # to OUSD on Tempo ``` In another project, `cargo add paralock --features evm,price-feed` and `cargo add tokio --features macros,rt-multi-thread`; the [Rust SDK page](https://paralock.xyz/docs/rust#a-taker) has a complete taker. The other Rust examples cover an axum maker, payments, a recovery daemon, the protocol core alone and public testnets. ## Next steps - [Swap on public testnets](https://paralock.xyz/docs/testnet): the same flow between Zcash testnet and Tempo Moderato, through a public lightwalletd server. - [Where Paralock works](https://paralock.xyz/docs/networks): which networks, Zcash nodes and wallets you can use beyond the devnet. - [How it works](https://paralock.xyz/docs/how-it-works): what happens at each step and why it is safe. - [`@paralock/sdk` reference](https://paralock.xyz/docs/sdk): every option and default. - [CLI reference](https://paralock.xyz/docs/cli): every command and flag. - [Rust SDK](https://paralock.xyz/docs/rust): the same protocol from Rust, and the [`paralock` binary](https://paralock.xyz/docs/rust-cli). --- # Where Paralock works Source: https://paralock.xyz/docs/networks Markdown: https://paralock.xyz/docs/networks.md Section: Getting started > The networks, Zcash nodes, wallets and runtimes Paralock works with today, and how to deal with the current Zcash testnet split. Building on Zcash means picking a network, a node, a wallet and a chain for the other side, and they all have to agree. This page lists what Paralock works with today, so you can set up the right combination on the first try. ## At a glance | | Status | |---|---| | Zcash regtest (local devnet) | Works. `npx paralock dev` runs one with [ths](https://github.com/zcashlabs/thus-spoke-zakura). | | Zcash testnet | Works. The testnet is currently split into two chains; see [the testnet split](#the-zcash-testnet-split). | | Zcash mainnet | Not supported yet. The code is experimental and not audited by a third party. | | EVM testnets | Escrows deployed and source-verified on six: Tempo Moderato, Base Sepolia, Sepolia, Arbitrum Sepolia, Robinhood Chain Testnet and HyperEVM Testnet. See [Contracts and deployments](https://paralock.xyz/docs/contracts). | | EVM local chains | Works. The devnet runs an anvil per chain (Tempo in `anvil --network tempo` mode). | | EVM mainnets | Not supported yet. Nothing is deployed on mainnet. | | Direction | ZEC to stablecoins (swap or pay). Stablecoins to ZEC is on the roadmap. | ## Zcash: what Paralock builds and reads - **Transactions:** Paralock builds transparent v5 transactions (ZIP 225) and signs them with ZIP 244 signature hashes. Its locks are P2SH: a hashlock HTLC in `htlc` mode, a 2-of-2 multisig in `adaptor` mode. - **Consensus branch id:** it is never hardcoded. Paralock signs with the branch id your backend reports for the next block, so the same code works on regtest, either testnet chain and mainnet. Since 0.3.0 the `@paralock/zcash` builders require it (and the network) explicitly, instead of defaulting to NU6.3's. - **Network upgrades:** refunds and claims in `adaptor` mode are signed before they are broadcast, and a signature commits to a branch id. If an upgrade would activate before a swap's refund height, the engines refuse the swap (`unsafe_timeouts`) instead of creating a refund that could never be mined. - **v6 transactions:** wallets from the NU6.3 (Ironwood) era send v6 transactions. Paralock reads them in address histories (the lightwalletd client gets their txids from the server's compact blocks), and keeps building v5 for its own locks, claims and refunds. | Network upgrade | Branch id | Where | |---|---|---| | NU6.3 (Ironwood) | `0x37a5165b` | Mainnet since block 3,428,143. Testnet (Zebra chain). The local devnet. | | NU7 | `0x77190ad9` | Testnet only, on Zakura nodes, since block 4,465,026. | ## The Zcash testnet split Zakura 2.2.0 activated NU7 on testnet at block **4,465,026**. Zebra, the Zcash Foundation's reference node, did not. Since that block the testnet has two chains: | | NU6.3 chain | NU7 chain | |---|---|---| | Nodes | Zebra | Zakura 2.2.0 or later | | Branch id | `0x37a5165b` | `0x77190ad9` | | Public lightwalletd | None we know of | `testnet.zec.rocks:443` | | Explorer | [zexplorer.app/testnet](https://zexplorer.app/testnet) | Look transactions up through `testnet.zec.rocks` | > **Warning:** Coins received after block 4,465,026 exist only on the chain that mined them. Your faucet, your wallet's > server, your Paralock backend and your maker must all be on the same chain. If a wallet shows a balance that Paralock > can't see (or the other way around), they are on different chains. To check which chain a server follows, read its branch id: ```ts import { LightwalletdClient } from "@paralock/lightwalletd"; const server = new LightwalletdClient("testnet.zec.rocks:443"); const info = await server.getLightdInfo(); console.log(info.consensusBranchId, info.blockHeight); // "77190ad9" → the NU7 chain server.close(); ``` With a node's JSON-RPC, read `consensus.chaintip` from `getblockchaininfo`. To check where a faucet pays, look its transaction up on each chain: it exists on only one. Paralock doesn't prefer either chain. The ecosystem is moving to NU7: faucets that send with older wallets have paused until those wallets support it. For the [testnet guide](https://paralock.xyz/docs/testnet) we use the NU7 chain, because it has a public lightwalletd server, so the swap needs no node of your own. ### Getting testnet ZEC | Faucet | Chain | Pays to | Amount | |---|---|---|---| | [Valar faucet](https://faucet.testnet.valargroup.dev) (Zakura team) | NU7 | Unified, Sapling and transparent addresses | 0.125 TAZ per IP per day | | [jinolabs faucet](https://zcashfaucet.jinolabs.xyz) | Paused for the NU7 upgrade | Shielded addresses | 0.1 TAZ per address per day | > **Tip:** The Valar faucet pays transparent addresses, so you can request TAZ straight to your swap address (`tm…`) > and skip the wallet entirely. ## Zcash backends Paralock talks to Zcash through the `ZcashNode` interface, so you choose the backend. | Backend | Package | When to use it | |---|---|---| | Zebra or Zakura JSON-RPC | `ZcashRpc` in `@paralock/zcash` | You run a node. It sees the mempool, so spends are noticed before they are mined. | | lightwalletd or Zaino (gRPC) | `LightwalletdClient` in `@paralock/lightwalletd` | You don't run a node. It sees only mined transactions. | | Anything else | Implement `ZcashNode` | Custody APIs, indexers, tests. Seven required methods; see [@paralock/zcash](https://paralock.xyz/docs/zcash). | zcashd is end of life and isn't tested. ## Wallets The ZEC for a swap comes from a **transparent** address: `tm…` on testnet and regtest, `t1…` on mainnet. Any wallet that can send to a transparent address can fund one. Shield the ZEC before the swap, send only the swap amount to the swap address, and shield change and refunds again afterwards. [Privacy](https://paralock.xyz/docs/privacy) explains why. - Paralock never sees your wallet's seed. It only uses the key of the swap address. - If your TAZ arrived in a shielded wallet, send it to your `tm…` address. The wallet has to follow the same chain and sign for it: on the NU7 chain, a wallet built on upstream librustzcash still signs with the NU6.3 branch id, and the node rejects the transaction ("incorrect consensus branch id") until it supports NU7. ## EVM chains | Chain | Local devnet | Public testnet | Stablecoin | |---|---|---|---| | Tempo | anvil `--network tempo`, chain id 31337 | Moderato, 42431 | OUSD (TIP-20); fees in pathUSD | | Base | anvil, 31338 | Base Sepolia, 84532 | USDC | | Ethereum | anvil, 31339 | Sepolia, 11155111 | USDC | | Arbitrum | anvil, 31340 | Arbitrum Sepolia, 421614 | USDC | | Robinhood Chain | anvil, 31341 | Robinhood Chain Testnet, 46630 | MockUSD test token (no USDC on that testnet) | | HyperEVM | anvil, 31342 | HyperEVM Testnet, 998 | USDC | The escrows are plain Solidity. Tempo's fee tokens are the only chain-specific part, and they're handled by the client. Other EVM chains work once you deploy the two contracts with `contracts/script/Deploy.s.sol` (see [Deploy it yourself](https://paralock.xyz/docs/contracts#deploy-it-yourself)). The SDK names six chains today (`EvmChain`); adding one is a small change, described in the repository's `AGENTS.md`. ## Runtimes | Package | Node.js 20+ | Browsers | Notes | |---|---|---|---| | `@paralock/zcash` | Yes | Yes | Pure TypeScript, no Node built-ins | | `@paralock/adaptor` | Yes | Yes | Pure TypeScript, no Node built-ins | | `@paralock/evm` | Yes | Yes | Built on viem | | `@paralock/sdk` | Yes | No | The file store and the maker server use Node APIs | | `@paralock/lightwalletd` | Yes | No | gRPC over HTTP/2 | The local devnet needs Node.js 20 or newer, macOS or Linux with Docker or OrbStack, ths and Foundry's anvil. Windows isn't tested. ## Not supported yet The [roadmap](https://paralock.xyz/docs/roadmap) says what is planned and why. - **Mainnet** on either side. The code isn't audited by a third party. - **A shielded Zcash lock.** The Zcash leg is transparent in both modes; a fully shielded leg (FROST) is in research. - **Stablecoins to ZEC.** Only ZEC to stablecoins today. - **Solana.** On the roadmap: an HTLC program, and private mode through `secp256k1_recover`. --- # How it works Source: https://paralock.xyz/docs/how-it-works Markdown: https://paralock.xyz/docs/how-it-works.md Section: Getting started > The roles, both swap protocols step by step, the timelines that keep them safe, every failure case, and how quotes are priced. A Paralock swap puts one lock on Zcash and one on an EVM chain, and makes a single secret open both. This page explains the two protocols in the order the engines run them, then why the timing rules make theft impossible. ## Roles | Role | Has | Does | In the SDK | |---|---|---|---| | **Taker** | ZEC in a transparent address | Picks the secret, locks ZEC first, claims the stablecoins last | `Taker` (`createTaker`) | | **Maker** | Stablecoin inventory on one or more EVM chains | Quotes a price, locks stablecoins after verifying the taker's lock, claims the ZEC | `Maker` (`createMaker`), served over HTTP with `makerHandler` | | **Recipient** | An EVM address | Receives the stablecoins: the taker itself, a fresh address, or a third party (Pay) | The `recipient` in the EVM lock | | **Relayer** (optional) | Gas on the EVM chain | Submits the taker's claim so the recipient needs no gas | `relayer` on the taker's chain config | The recipient is fixed when the maker locks. Anyone can submit a claim, but the escrow only ever pays that recipient, so a relayer can delay a claim but never redirect it. ## The locks **On Zcash** the taker's ZEC goes into a P2SH output. - In `htlc` mode it is a hash time-locked contract (HTLC): ```zscript OP_IF # claim: the maker, with the secret OP_SIZE 32 OP_EQUALVERIFY # a 32-byte secret OP_SHA256 OP_EQUALVERIFY # whose sha256 is the hashlock OP_ELSE # refund: the taker, after a timeout OP_CHECKLOCKTIMEVERIFY OP_DROP OP_ENDIF OP_CHECKSIG # signed by the key picked above ``` The maker can spend it with the 32-byte secret and its own signature. The taker can spend it with its own signature once the chain reaches `refundHeight`. - In `adaptor` mode it is a plain 2-of-2 multisig (`OP_2 OP_2 OP_CHECKMULTISIG`) of a fresh taker key and a fresh maker key. Any spend needs both signatures. On-chain it looks like any other multisig. **On the EVM chain** the maker's stablecoins go into one of two escrows: - `ParalockHTLC` pays the recipient when someone submits the secret whose sha256 is the hashlock, before `expiry`. The `Claimed` event publishes the secret. - `ParalockAdaptorEscrow` pays the recipient when someone submits a signature from a one-time `signer` key over `claimDigest(id)`, before `expiry`. The `Claimed` event publishes the signature. From `expiry` on, anyone can call `refund`, which returns the funds to the maker. Both contracts store one slot per swap and mark it settled forever, so a hashlock or escrow id can never be reused. See [Contracts and deployments](https://paralock.xyz/docs/contracts). ## The htlc flow The swap id in this mode is the hashlock. ```text htlc mode, message by message Participants: Taker, Maker, Zcash, EVM chain. Quote: 1. Taker → Maker: GET /quote 2. Maker → Taker: quote: amounts, rate, keys, windows; valid for 60 s Commit, then fund: 3. Taker: draws the secret, builds the HTLC, signs the funding and saves both. Nothing is sent yet. 4. Taker → Maker: POST /swaps: script, funding outpoint, fundingExpiryHeight, recipient 5. Maker: checks the script byte for byte, consumes the quote, reserves the stablecoins 6. Maker → Taker: the swap, accepted 7. Taker → Zcash: broadcast the funding Lock: 8. Zcash → Maker: funding has minZcashConfirmations 9. Maker → EVM chain: lock under the same hashlock, expiry T 10. EVM chain → Taker: lock found: recipient, token, amount, time left checked Settle: 11. Taker → EVM chain: claim with the secret; the recipient is paid 12. EVM chain → Maker: the Claimed event publishes the secret 13. Maker → Zcash: claim the ZEC with the secret ``` 1. **Quote.** The taker calls `taker.quote(zat, chain, "htlc")`. The maker answers with the amounts, the rate, its long-term Zcash public key, its EVM address, the lock windows (`zcashLockBlocks`, `evmLockSeconds`) and an expiry 60 seconds out. The taker validates all of it against its own configuration and limits. 2. **Prepare.** The taker draws a random 32-byte secret, computes `hashlock = sha256(secret)`, builds the HTLC with `refundHeight = tip + zcashLockBlocks`, and signs a funding transaction that expires if it isn't mined within 40 blocks. Zcash v5 transaction ids (ZIP 244) don't commit to signatures, so the funding txid is final before anything is sent. It writes the secret and the signed funding to its store. 3. **Accept.** Before broadcasting anything, the taker re-checks that the quote hasn't expired and sends the maker the quote id, the redeem script, the funding outpoint, the funding's expiry height (`fundingExpiryHeight`) and the recipient (`POST /swaps`). The maker checks that the script matches its HTLC template byte for byte, that it pays the maker's key, that the funding expiry is above its tip and at most `maxFundingExpiryBlocks` (45) ahead, that the window is still safe, that the refund height is at most twice the policy's window away, and that it has the inventory. Only then does it consume the quote (a refused accept leaves it usable) and reserve the stablecoins. If anything fails here, nothing was broadcast: the taker abandons the swap. 4. **Fund.** The taker broadcasts the funding. If the funding is still unmined 2 blocks after its expiry height, it can never be mined, and the maker drops the reservation. 5. **Maker locks.** Once the funding has `minZcashConfirmations` and holds at least the quoted ZEC, the maker re-checks the window, saves the lock parameters and locks the stablecoins in `ParalockHTLC` under the same hashlock, with `expiry = now + evmLockSeconds`. 6. **Taker verifies.** The taker finds the lock by its hashlock, waits for `minEvmConfirmations`, and checks the recipient, the token, the amount and that at least `minClaimWindowSeconds` remain before expiry. 7. **Taker claims.** The taker (or its relayer) submits the secret. The recipient is paid, and the secret is now public in the `Claimed` event. 8. **Maker claims.** The maker reads the secret from the event, saves its Zcash claim, then broadcasts it and rebroadcasts until it has `minZcashConfirmations`. > **Note:** In htlc mode the same hashlock appears on both chains, so anyone can pair the two legs of a swap. Private mode removes that link. ## The adaptor flow Private mode replaces the hash with an adaptor signature. An **adaptor signature** is a pre-signature "encrypted" to a point `Y = y·G`: anyone can check it, whoever knows `y` can complete it into a normal ECDSA signature, and whoever holds the pre-signature and later sees the completed signature can compute `y`. The secret is `y`, and it only ever travels inside signatures. The swap id in this mode is the quote id. ```text Private mode (adaptor), message by message Participants: Taker, Maker, Zcash, EVM chain. Quote: 1. Taker → Maker: GET /quote in adaptor mode 2. Maker → Taker: quote with a fresh Zcash key for this quote Commit, then fund: 3. Taker: draws y (Y = y·G) and a fresh 2-of-2 key, signs the funding and saves them. Nothing is sent yet. 4. Taker → Maker: POST /adaptor/swaps: 2-of-2 key, Y, funding txid and expiry, refund height, recipient 5. Maker: checks the proposal, reserves the stablecoins, signs the taker's time-locked refund 6. Maker → Taker: refund signature, claim address, branch id, one-time signer 7. Taker: verifies the refund signature and saves it. Its ZEC can always come back now. 8. Taker → Zcash: broadcast the funding Lock: 9. Zcash → Taker: funding confirmed 10. Taker → Maker: pre-signature on the maker's Zcash claim, encrypted to Y 11. Maker: checks it with preVerify, waits for minZcashConfirmations 12. Maker → EVM chain: lock: recipient, signer, amount, expiry T, salt 13. Taker → Maker: resends its pre-signature 14. Maker → Taker: escrow id and the maker's EVM pre-signature, encrypted to Y 15. EVM chain → Taker: lock found: recipient, token, amount, signer, time left checked Settle: 16. Taker → EVM chain: claim with the pre-signature completed by y 17. EVM chain → Maker: the Claimed event publishes the signature 18. Maker: extracts y and completes the taker's Zcash pre-signature with it 19. Maker → Zcash: claim the 2-of-2 ``` 1. **Quote.** The taker calls `taker.quote(zat, chain, "adaptor")`. The maker generates a fresh Zcash key for this quote and stores it before returning the quote, so the 2-of-2 reveals nothing about which maker it is. 2. **Prepare.** The taker draws the adaptor secret `y` and its point `Y`, a fresh per-swap multisig key, builds the 2-of-2 address and signs a funding transaction but does **not** broadcast it. Zcash v5 transaction ids (ZIP 244) don't commit to signatures, so the funding txid is final before anything is sent. The taker checks that no network upgrade activates before the refund height, then stores `y`, the multisig key and the funding. 3. **Propose.** The taker re-checks that the quote hasn't expired and sends the maker the 2-of-2 key, `Y`, the funding txid and expiry height, the amount, the refund height and address, and the recipient (`POST /adaptor/swaps`). 4. **Maker signs the refund.** The maker checks the amount equals the quote, the funding expiry (as in htlc mode), the window is safe, the refund height is at most twice the policy's window away, no upgrade activates before it, and it has the inventory. It consumes the quote and reserves the stablecoins until the funding confirms, or until 2 blocks after the funding's expiry height if it is never mined. It builds both possible spends of the 2-of-2: the taker's refund (time-locked with `lock_time = refundHeight`) and its own claim. It signs the refund, creates a one-time EVM `signer` key, and returns the refund signature, its claim address, the consensus branch id and the signer. 5. **Taker funds.** The taker checks the branch id against its own node, rebuilds the lock and the refund, verifies the maker's refund signature and that the signer's public key matches its address. It saves the refund signature, and only then broadcasts the funding. From here on the taker can always get its ZEC back after the refund height. 6. **Taker pre-signs the maker's claim.** Once the funding confirms, the taker creates an adaptor pre-signature on the maker's Zcash claim, encrypted to `Y` with a DLEQ proof, and sends it (`POST /adaptor/swaps/:id/presignature`). The maker verifies it with `preVerify`: once `y` is known, it becomes a valid signature. 7. **Maker locks.** When the funding has `minZcashConfirmations` and holds exactly the proposed amount, the maker re-checks the window, builds the escrow lock (recipient, signer, amount, expiry and a random salt), pre-signs its `claimDigest` with the one-time signer key encrypted to `Y`, saves everything and locks the stablecoins in `ParalockAdaptorEscrow`. 8. **Taker verifies.** The taker gets the escrow id and the pre-signature from the maker by resending its own pre-signature (the maker's public swap view never shows them), finds the lock on-chain, waits for confirmations, and checks recipient, token, amount, signer, the pre-signature and the time left. 9. **Taker claims.** The taker completes the pre-signature with `y` into a normal low-S ECDSA signature and claims (directly or through a relayer). The signature is now public, but only the maker can turn it into `y`, because only the maker holds the matching pre-signature. 10. **Maker claims.** The maker extracts `y` from its pre-signature and the published signature, completes the taker's Zcash pre-signature with it, adds its own signature and claims the 2-of-2. Nothing on either chain is shared between the legs: Zcash sees an ordinary 2-of-2 spend, and the EVM chain sees a signature from a key used once. [Privacy](https://paralock.xyz/docs/privacy) covers what an observer can still infer. ## Timelines Two deadlines govern every swap: - **Refund height N:** a Zcash block height, set when the taker prepares the lock (`tip + zcashLockBlocks`). From N on, the taker can take its ZEC back. - **Expiry T:** a Unix time, set when the maker locks (`now + evmLockSeconds`). Before T only the recipient can be paid; from T on, the maker can take its stablecoins back. ```text The two windows of one swap Lanes: Zcash (ZEC), EVM chain (dollars). In time order: 1. [Zcash] The taker funds the Zcash lock. Its refund height N (tip + zcashLockBlocks) was fixed when the taker built it. 2. [EVM chain] The maker locks the stablecoins, but only if at least safetyFactor × evmLockSeconds remain before N. T = now + evmLockSeconds. 3. [EVM chain] The taker claims before T, with at least minClaimWindowSeconds to spare. The claim makes the secret public. 4. [EVM chain, T] Expiry T: from here on, the maker can take its stablecoins back. 5. [Zcash] The maker claims the ZEC with the now-public secret. The claim must be mined before N. 6. [Zcash, N] Refund height N: from here on, the taker can take its ZEC back. Durations: - EVM lock: evmLockSeconds - Zcash time left when the maker locks: at least safetyFactor (2) × the EVM lock Not to scale. With MAINNET_POLICY, N is 144 blocks (about 3 h) after the taker builds its lock and the EVM lock lasts 1 h, so the maker has about an hour to lock, and at least another hour remains after T for its claim. ``` The rule: when the maker locks, the Zcash time left before N must be at least `safetyFactor` times the EVM lock. `assertSafeWindows(policy, blocksUntilRefund, evmLockSeconds)` enforces it by checking `blocksUntilRefund × zcashBlockSeconds ≥ evmLockSeconds × safetyFactor`, and throws `ParalockError("unsafe_timeouts")` otherwise. | Policy | Zcash window | Block time | EVM lock | Zcash confirmations | Safety factor | |---|---|---|---|---|---| | `MAINNET_POLICY` | 144 blocks (about 3 h) | 75 s | 3,600 s (1 h) | 2 | 2× | | `examples/testnet` | 96 blocks (about 2 h) | 75 s | 1,800 s (30 min) | 1 | 2× | | `DEVNET_POLICY` | 40 blocks (about 2 min) | 3 s | 45 s | 1 | 2× | Take `MAINNET_POLICY`. The EVM lock lasts 3,600 s, so when the maker locks, at least 2 × 3,600 = 7,200 s, or 96 blocks of 75 s, must remain before N. The taker sets N 144 blocks ahead when it builds its lock, so the maker has about 48 blocks (an hour) from then to lock; after that it abandons the swap instead of locking. And since T is one hour after the maker's lock, at least another hour of Zcash window remains after T. The maker runs this check when the policy is created, when it accepts a swap, right before it locks, and again before sending the lock transaction, when it also refuses if fewer than `minEvmLockSecondsLeft` (30) seconds of EVM lock would remain. ### Why the factor is 2× The ordering protects whoever learns the secret second: the maker. The taker reveals the secret by claiming, at the latest just before T. The maker then needs its Zcash claim mined before N. If N came first, the taker could claim the stablecoins and also refund the ZEC. `N > T` alone is not enough, because: - Zcash block times vary around 75 seconds. If blocks come faster, N arrives earlier in wall-clock time. - The maker needs time to see the claim, build its transaction, broadcast it and wait for confirmations, through mempool congestion or a short outage. A factor of 2 leaves at least as much time after T as the EVM lock itself lasted. The taker has its own timing rule. A claim mined after T reverts, but its calldata still makes the secret public, and then the maker could claim the ZEC and refund the stablecoins. So the taker refuses to claim unless at least `minClaimWindowSeconds` (default 30 s) remain, both when it verifies the lock and right before it claims. On Ethereum L1, set it to several minutes. ## What if | What goes wrong | What happens | |---|---| | The maker never locks | The taker's ZEC waits until N, then the taker refunds it: with its own key (htlc) or with the refund the maker pre-signed (adaptor) | | The maker locks different terms | The taker refuses to claim (`lock_mismatch`) and reveals nothing. The maker refunds after T, the taker after N | | The maker's lock expires too soon | The taker doesn't claim (`timeout`). Both sides refund | | The taker never claims | The secret stays private, so the maker can't touch the ZEC. The maker refunds after T; the taker refunds after N | | The taker claims | The claim reveals the secret, and the maker has until N, well after T, to claim the ZEC | | Someone copies the secret from the mempool | Nothing to steal. The EVM lock only pays the recipient, and the Zcash lock also needs the maker's signature (htlc) or both parties' signatures (adaptor) | | The taker funds the wrong script or amount | The maker refuses and never locks, so it risks nothing | | The funding never confirms | It expires after 40 blocks, so it can't confirm hours later. Nothing was locked, and 2 blocks later the maker drops its reservation | | The quote expires, or the maker refuses, before it commits | Nothing was broadcast: the taker abandons the swap and gets the maker's error (for example `quote_expired`) | | Either side crashes | Everything needed to continue or refund was stored before each step. See [Persistence and recovery](https://paralock.xyz/docs/recovery) | | The maker goes offline after the taker claims | The maker must claim before N. If it stays offline past N, the taker could also refund the ZEC. This is the maker's risk, never the taker's | ## Why nothing can be stolen - **Funds have exactly two exits.** The ZEC goes to the maker (secret plus the maker's signature) or back to the taker (after N). The stablecoins go to the recipient (secret or signature, before T) or back to the maker (from T). No third party can take either. - **The taker reveals nothing before the maker's lock is verified on-chain:** recipient, token, amount, signer, confirmations and time left. - **The maker locks nothing before the taker's ZEC is confirmed** in a lock it rebuilt byte for byte, holding the right amount, with enough window left. It only reserves inventory, until the funding confirms or expires. - **The taker funds nothing before the maker commits:** in htlc mode the maker has accepted the HTLC and reserved its stablecoins; in private mode it has also signed the taker's refund. - **In private mode, the taker funds only after holding a valid refund** signed by the maker. That is safe because the funding txid can't change after signing. - **Whoever learns the secret second always has time to use it,** because of the window ordering above. - **Secrets are single-use.** The contracts mark every hashlock and escrow id settled forever. These guarantees assume the code is correct (it has not been audited by a third party) and that each party is online before its deadline. The [Security model](https://paralock.xyz/docs/security) lists every assumption. ## Quotes and pricing A quote is the maker's offer: amounts, rate, keys, lock windows and an expiry. The maker honors it for 60 seconds by default (`quoteTtlSeconds`), the taker rejects one that expires within 5 seconds, and each quote can start only one swap. The taker has the maker commit before it broadcasts its funding, so the quote only has to last from the quote to that commitment, a few seconds, never a Zcash block. Right before asking, the taker re-checks the expiry (allowing 5 seconds of clock skew) and fails without broadcasting if it has passed. The maker prices from its feed (for example `zecUsdPrice()`, which reads CoinGecko) minus its spread: ```text rate = price × (1 − spreadBps / 10,000) default spreadBps: 50 (0.5%) ``` There are two kinds of quotes: - **Exact-in** (`taker.quote(zat, …)`): you fix the ZEC. The stablecoin amount is `(zat − zcashFeeZat) × rate`, rounded down. - **Exact-out** (`taker.quoteExactOut(usd, …)`): you fix the dollars, for a payment. The ZEC amount is `usd / rate`, rounded up, plus `zcashFeeZat`. The recipient always receives the full amount. `zcashFeeZat` is 10,000 zat (0.0001 ZEC), the maker's own Zcash claim fee, priced into every quote. A worked example with a feed price of $1,280 and the default spread, so `rate` = 1,280 × 0.995 = $1,273.60: | Quote | Input | Result | |---|---|---| | Exact-in | 1 ZEC (100,000,000 zat) | (100,000,000 − 10,000) zat × 1,273.60 = 1,273.472640 USD | | Exact-out | $25.00 (25,000,000 units) | 1,962,940 zat + 10,000 zat = 1,972,940 zat (0.0197294 ZEC) | On top of the quote, the taker pays the Zcash fee of its funding transaction (ZIP 317: 5,000 zat per logical action, at least 10,000 zat) and the EVM gas of its claim, unless a relayer submits it. To guard against a bad rate, pass your own `price` to `createTaker`: quotes worse than `limits.maxSlippageBps` (default 200, or 2%) against your price are rejected. --- # Roadmap Source: https://paralock.xyz/docs/roadmap Markdown: https://paralock.xyz/docs/roadmap.md Section: Getting started > What Paralock ships today, what is being built, what comes next and what is still research, each with the reason it matters. This is Paralock's official roadmap. Every shipped item links to something you can check: a package, a deployment, a verified contract, a recorded swap or the spec. Work that hasn't shipped has no dates: it ships when it's built, tested and reviewed. - **Shipped:** usable today, on the devnet or public testnets - **Next:** planned, in rough order - **In research:** open questions remain before it can be built > **Warning:** Paralock is experimental and has not been audited by a third party. The escrows run on public testnets only. Mainnet comes after an audit, not before. ## Shipped - **The TypeScript SDK.** [`@paralock/sdk`](https://www.npmjs.com/package/@paralock/sdk), [`@paralock/zcash`](https://www.npmjs.com/package/@paralock/zcash), [`@paralock/adaptor`](https://www.npmjs.com/package/@paralock/adaptor), [`@paralock/evm`](https://www.npmjs.com/package/@paralock/evm) and [`@paralock/lightwalletd`](https://www.npmjs.com/package/@paralock/lightwalletd) on npm, MIT-licensed. Why: any wallet, app or agent can add trustless ZEC-to-stablecoin swaps without a bridge or a custodian. - **Both swap modes.** htlc mode, and private mode with ECDSA adaptor signatures (experimental), on Tempo, Base, Ethereum, Arbitrum, Robinhood Chain and HyperEVM. See [How it works](https://paralock.xyz/docs/how-it-works). Why: private mode leaves no hash or other shared value linking the two chains. - **Escrows on six public testnets, with verified sources.** `ParalockHTLC` and `ParalockAdaptorEscrow` on Tempo Moderato, Base Sepolia, Sepolia, Arbitrum Sepolia, Robinhood Chain Testnet and HyperEVM Testnet, each an exact bytecode match on Sourcify or Tempo's verifier. See [deployments](https://paralock.xyz/docs/contracts#deployments). Why: anyone can check the code that holds the funds. - **The first public testnet swaps.** On 2026-10-12, Zcash testnet to Tempo Moderato: run 1 failed safely and refunded, and exposed a quote-expiry bug that the devnet's 3-second blocks hid; run 2, with the fix, swapped 0.015 TAZ for 19.39 OUSD in 3 min 39 s; run 3, driven by the Rust SDK, swapped 0.003 TAZ for 3.72 OUSD. Every transaction is in [`docs/TESTNET-RUNS.md`](https://github.com/bitfalt/paralock/blob/main/docs/TESTNET-RUNS.md). Why: real block times and public infrastructure find bugs a local devnet can't. - **The hardened protocol, in 0.3.0 on npm.** [`@paralock/sdk`](https://www.npmjs.com/package/@paralock/sdk) and its packages, and the [`paralock` CLI](https://www.npmjs.com/package/paralock)'s first npm release (`npx paralock`). The maker accepts and reserves before any ZEC moves (`fundingExpiryHeight`), its public swap view carries no adaptor data, and `@paralock/zcash` parses strictly and needs an explicit branch id and network. Why: they close the bug from run 1, and port the failure-handling fixes from the Rust reviews to TypeScript. - **The protocol spec and test vectors.** [`spec/PROTOCOL.md`](https://github.com/bitfalt/paralock/blob/main/spec/PROTOCOL.md) (protocol v1.1) with cross-language vectors in [`spec/vectors`](https://github.com/bitfalt/paralock/tree/main/spec/vectors). Why: a second implementation can prove it is byte-for-byte compatible. - **The `paralock` CLI.** `npx paralock dev` starts Zcash regtest, up to six EVM chains, the contracts and a maker, with no clone needed (0.3.0 is its first npm release). See [CLI](https://paralock.xyz/docs/cli). Why: a full swap on your machine in minutes, before touching a testnet. - **Pay and payment links.** Exact dollars to any address, from the CLI, the SDK or a link that opens the [web app](https://paralock.xyz/app). See [Payments](https://paralock.xyz/docs/pay). Why: the person you pay never needs ZEC, gas or an app. - **Docs for agents.** A skill, `llms.txt`, every page as Markdown and a read-only MCP server. See [For AI agents](https://paralock.xyz/docs/ai-agents). Why: coding agents integrate from the source of truth instead of guessing. - **The Rust SDK, on crates.io.** [`paralock`](https://crates.io/crates/paralock) 0.1.0 (taker and maker engines, Zcash RPC and lightwalletd backends, durable stores, the maker HTTP server and client, a price feed), on [`paralock-core`](https://crates.io/crates/paralock-core) (the protocol core, checked against the same vectors) and [`paralock-evm`](https://crates.io/crates/paralock-evm) (alloy clients), with API docs on docs.rs. Wire-compatible with `@paralock/sdk`. The three library crates went through internal security reviews before release, with every finding fixed and covered by a regression test; the failure-handling fixes were ported to the TypeScript SDK for 0.3.0. See [Rust SDK](https://paralock.xyz/docs/rust). Why: makers and services written in Rust embed Paralock directly, and one core checked once against the vectors can serve every language. - **The `paralock` binary.** [`paralock-cli`](https://crates.io/crates/paralock-cli) 0.1.0: quote, swap, pay, recovery and a maker from one executable configured by `paralock.toml`, prebuilt for macOS and Linux (`curl -fsSL https://paralock.xyz/install | sh`). See [Rust CLI](https://paralock.xyz/docs/rust-cli). Why: a maker runs as a single executable, without a Node.js runtime. ## Next - **Bindings from the Rust core.** napi for Node.js, wasm for browsers, uniffi for Swift and Kotlin, PyO3 for Python, and Go, all on `paralock-core`. Why: wallets and apps on every platform get the same tested code instead of reimplementing the protocol. - **A hosted testnet maker.** Zcash testnet end to end against a maker that is always on. Why: trying Paralock on a public network shouldn't require running your own maker. - **A third-party security audit.** Of the contracts, the protocol and the core. Why: nothing should hold real funds on code that only its authors have reviewed. - **Mainnet, after the audit.** Starting with OUSD on Tempo. Why: shielded ZEC holders get real dollars without a bridge, but only once the code has been audited. - **A maker network.** A request-for-quote network where many makers compete for each swap, with peer-to-peer offers on top; Paralock would earn a small routing fee. Why: competing quotes give better prices and no single point of failure. - **Dollars to ZEC.** The reverse direction, so a taker can buy ZEC with stablecoins. Why: today swaps only sell ZEC. - **Refunds straight to a shielded address.** Why: today a refund lands on a transparent address and has to be shielded again. - **Wallet integrations.** "Pay in dollars" and "swap to dollars" inside Zcash wallets. Why: most people will meet Paralock in a wallet they already use, not in a terminal. - **MPP payments.** A Zcash payment method for the Machine Payments Protocol. Why: agents could pay HTTP 402 APIs straight from shielded ZEC, without buying stablecoins first. - **Solana.** An HTLC program with the same sha256 hashlock, and private mode through `secp256k1_recover`, which needs no cross-curve proofs. Why: stablecoin liquidity on Solana, through the same protocol. ## In research - **A fully shielded Zcash leg.** Shielded notes controlled by a FROST 2-of-2 (RedPallas), Schnorr adaptor signatures, a cross-group DLEQ proof between Pallas and secp256k1, and a time-locked pre-signed refund. Open work: the cross-curve proof, Ironwood support in FROST, and wallet support for jointly controlled notes. See [Privacy](https://paralock.xyz/docs/privacy#level-3-a-fully-shielded-zcash-leg). Why: the Zcash leg of a swap would become an ordinary shielded transaction, with only the EVM leg visible. ## Follow along - The [repository](https://github.com/bitfalt/paralock) and its [issues](https://github.com/bitfalt/paralock/issues) are where work happens. - [Security model](https://paralock.xyz/docs/security) lists what is still missing before real funds. - Ideas and questions are welcome as GitHub issues. --- # Payments and payment links Source: https://paralock.xyz/docs/pay Markdown: https://paralock.xyz/docs/pay.md Section: Guides > Pay an exact dollar amount to any address from shielded ZEC, share payment links that open the Pay flow prefilled, and keep receipts. The stablecoin side of a swap doesn't have to pay the person swapping. It can pay **any address**: a shop, a contributor, a friend. That is Pay. The recipient receives an exact dollar amount in stablecoins and never deals with ZEC, and settlement is the same atomic swap, so nobody custodies anything in between. ## How a payment works 1. The recipient shares an EVM address, a dollar amount and a chain, for example in a payment link. 2. Your taker asks the maker for an **exact-out** quote: the dollar amount is fixed, and the ZEC amount is computed from it and rounded up. 3. You lock that ZEC on Zcash. The maker locks the stablecoins on the EVM chain with the recipient's address as the payee. 4. Your taker verifies the maker's lock (recipient, token, amount, time left) and claims, which pays the recipient. The recipient address is part of the EVM lock, so the funds can only go there. The recipient doesn't sign anything, run anything or pay gas: the claim is submitted by your EVM account or by a relayer. ## Pay with the SDK Use `quoteExactOut` instead of `quote`, then pass `recipient` (and optionally `label`) to `swap`. Here `taker` comes from `createTaker`, as in the [Quickstart](https://paralock.xyz/docs/quickstart#use-the-sdk-in-your-own-code): ```ts import { SwapFailedError } from "@paralock/sdk"; const quote = await taker.quoteExactOut(25_000_000n, "base", "adaptor"); // exactly 25.00 USDC console.log(`Costs ${Number(quote.zecAmountZat) / 1e8} ZEC at $${quote.rate.toFixed(2)}/ZEC`); try { const swap = await taker.swap(quote, { recipient: "0x90F79bf6EB2c4f870365E785982E1f101E93b906", label: "Acme Coffee", privacy: { relayClaim: true }, }); console.log(`Paid ${swap.payment?.label}: claim ${swap.evm.claimTx}`); } catch (err) { if (!(err instanceof SwapFailedError)) throw err; await taker.refund(err.swap.id); // the ZEC comes back after the refund height } ``` - **`usdAmount`** is in token base units with 6 decimals, so `25_000_000n` is $25.00. Convert user input without floating point: ```ts /** "1850.50" → 1850500000n (6-decimal token units), without floating point. */ function usdUnits(usd: string): bigint { if (!/^\d+(\.\d{1,6})?$/.test(usd)) throw new Error(`not a dollar amount: ${usd}`); const [whole, frac = ""] = usd.split("."); return BigInt(whole!) * 1_000_000n + BigInt(frac.padEnd(6, "0")); } ``` - **`chain`** and **`mode`**: `"tempo"` pays OUSD; the other chains pay USDC. `"adaptor"` (private mode) keeps any shared value off both chains; `"htlc"` is the default. - **`recipient`** must be a non-zero `0x` address. It takes precedence over `privacy.freshRecipient`. - **`label`** is stored with the swap as `swap.payment.label`, for your receipts and UI. It never goes on-chain. - **`relayClaim`** lets the relayer configured on that chain submit the claim, so your own EVM account needs no gas. The quote checks that matter for payments: `quoteExactOut` rejects a quote unless it is marked exact-out and its `usdAmount` equals what you asked for, and the taker refuses to claim unless the maker locked at least that amount for that recipient. ### What a payment costs At a feed price of $1,280 and the default 0.5% spread, the maker's rate is $1,273.60 per ZEC, and paying $25.00 costs 1,972,940 zat (0.0197294 ZEC): 1,962,940 zat at that rate, rounded up, plus 10,000 zat for the maker's own Zcash claim fee. You also pay the Zcash fee of your funding transaction (at least 10,000 zat) and, unless it is relayed, the gas of the claim. [How it works](https://paralock.xyz/docs/how-it-works#quotes-and-pricing) shows the formulas. > **Tip:** Quotes are short-lived (60 seconds by default). Ask for the quote right before you call `swap`, after the user has confirmed the amount. ## Pay from the CLI On the local devnet (`pnpm paralock` in a checkout): ```sh npx paralock pay --usd 25 --to 0x90F79bf6EB2c4f870365E785982E1f101E93b906 --chain base --label "Acme Coffee" npx paralock pay --usd 42.50 --to 0x90F79bf6EB2c4f870365E785982E1f101E93b906 --chain tempo --private --relay ``` | Flag | Meaning | |---|---| | `--usd ` | Dollars the recipient receives (required) | | `--to <0x…>` | Recipient address (required) | | `--chain ` | `tempo` (default), `base`, `ethereum`, `arbitrum`, `robinhood` or `hyperevm` | | `--label ` | A name for the payment | | `--private` | Private mode (adaptor) | | `--relay` | The devnet relayer submits the claim | | `--no-shield` | Don't unshield first or reshield change afterwards | ## Payment links The web app opens the Pay flow prefilled from a link: ```text /app?pay=
&usd=&chain=&label=&mode=private ``` | Parameter | Required | Accepted values | |---|---|---| | `pay` | Yes | The recipient's `0x` address. Without `pay` the URL isn't a payment link | | `usd` | No | A dollar amount such as `25`, `19.99` or `$1,200.50`: up to 6 decimals; a leading `$` and commas are ignored | | `chain` | No | `tempo`, `base`, `ethereum`, `arbitrum`, `robinhood` or `hyperevm`. Anything else is ignored | | `label` | No | The name shown to the payer, trimmed and cut to 60 characters | | `mode` | No | `private` (or `adaptor`) for private mode; `standard` (or `htlc`) for htlc mode | For example, `/app?pay=0x90F79bf6EB2c4f870365E785982E1f101E93b906&usd=4.50&chain=base&label=Acme%20Coffee` asks the payer for exactly $4.50 in USDC on Base, labeled "Acme Coffee". When a page opens from a link, the app keeps the chain the link chose instead of silently switching it. `/app?flow=pay` opens an empty Pay form, and older links on `/` (`/?pay=…`) redirect to `/app` with the same query string. The app also has a **Request a payment** section that builds these links: enter your address, the price, the chain, an optional name and whether to use private mode, then copy the link. > **Note:** The app's header shows which backend it runs. "Local devnet" means swaps go through the real SDK against your local chains (`pnpm paralock dev --web`, from a checkout). "Preview, simulated maker" means a simulated maker on simulated chains, where no funds move; deployments without a local devnet, such as hosted previews, run in this mode. ### Build links in code The link format is plain query parameters, so any language can produce it: ```ts import type { EvmChain, Hex } from "@paralock/sdk"; interface PaymentRequest { to: Hex; usd: string; chain: EvmChain; label?: string; private?: boolean; } function paymentLink(origin: string, p: PaymentRequest): string { const q = new URLSearchParams({ pay: p.to, usd: p.usd, chain: p.chain }); if (p.label) q.set("label", p.label); if (p.private) q.set("mode", "private"); return `${origin.replace(/\/$/, "")}/app?${q.toString()}`; } paymentLink("https://paralock.xyz", { to: "0x90F79bf6EB2c4f870365E785982E1f101E93b906", usd: "4.50", chain: "base", label: "Acme Coffee" }); ``` ## Receipts `swap` resolves with the full public record of the payment. It never contains secrets or keys; those stay in the store. Keep the fields you need as a receipt: ```ts import { type Swap, toJson } from "@paralock/sdk"; function receiptOf(swap: Swap) { return { swapId: swap.id, status: swap.status, mode: swap.mode, paidTo: swap.evm.recipient, label: swap.payment?.label, amount: swap.evm.amount, // token base units (6 decimals) token: swap.quote.tokenSymbol, chain: swap.evm.chain, chainId: swap.evm.chainId, claimTx: swap.evm.claimTx, // proof of payment on the EVM chain zecPaidZat: swap.zcash.amountZat, zcashLockTx: swap.zcash.fundingTxid, at: swap.events.at(-1)?.at, // Unix ms of the last step }; } console.log(toJson(receiptOf(swap))); // toJson writes bigints as decimal strings ``` - **`claimTx`** is the transaction that paid the recipient. On Tempo, the TIP-20 transfer also carries the swap's hashlock or escrow id as its memo. - **`status`** is `completed` once the maker has also claimed the ZEC, or `evm_claimed` if the maker's claim wasn't seen within `timeouts.followMakerMs` (60 seconds by default). Either way, the recipient has been paid. - **`swap.events`** is the full timeline, with a transaction id per step. The `examples/payroll` app (in the repository) does all of this in a loop: it pays four contributors exact amounts on four chains from a shielded treasury, in private mode with relayed claims, refunds any failed payment and writes `receipts-.json`. One run paid $4,665.75 on Tempo, Base, Arbitrum and Ethereum. ```sh pnpm paralock dev --evm all pnpm --filter @paralock/example-payroll start ``` ## Privacy of a payment The recipient sees an ordinary stablecoin transfer from the escrow contract. In htlc mode, the same hashlock on both chains lets anyone pair your Zcash lock with the payment; private mode removes that link. In both modes the Zcash leg is transparent, so unshield only what the payment needs and shield change and refunds again. See [Privacy](https://paralock.xyz/docs/privacy). --- # Swap on public testnets Source: https://paralock.xyz/docs/testnet Markdown: https://paralock.xyz/docs/testnet.md Section: Guides > Run a real swap between Zcash testnet (TAZ) and OUSD on Tempo Moderato with examples/testnet, through a public lightwalletd server. The `examples/testnet` app runs a real Paralock swap on public test networks: Zcash testnet coins (TAZ) for OUSD on Tempo Moderato. Every step is a real transaction, and testnet coins have no value. | Side | Network | How the example reaches it | |---|---|---| | Zcash | Zcash testnet | The public lightwalletd server `testnet.zec.rocks:443`, through `@paralock/lightwalletd`, so you don't run a node | | EVM | Tempo Moderato (chain id 42431) | `https://rpc.moderato.tempo.xyz`, with the escrows from `contracts/deployments/42431.json` | | Maker | In the same process | `createMaker` runs next to the taker, so the demo is one command | In production the maker is a separate service behind `makerHandler`, and the taker passes its URL instead of the `Maker` object. See [Run a maker](https://paralock.xyz/docs/run-a-maker). [Where Paralock works](https://paralock.xyz/docs/networks) lists the other networks, Zcash backends and wallets you can combine. > **Warning:** Testnets only. The contracts are experimental and not audited by a third party, and there is no mainnet deployment. Never reuse a testnet key on a real network. ## The first public runs The first public testnet swaps are recorded, with every transaction, in [`docs/TESTNET-RUNS.md`](https://github.com/bitfalt/paralock/blob/main/docs/TESTNET-RUNS.md): | Run | Mode | Result | |---|---|---| | 1 | htlc | 0.1 TAZ. Failed safely: the taker broadcast its funding first, the 60-second quote expired while it confirmed, and the maker refused. The taker refunded at the refund height; nothing was lost. The fix has the maker accept and reserve before any ZEC moves (in 0.3.0) | | 2 | htlc | 0.015 TAZ for 19.39 OUSD, completed in 3 min 39 s with a relayed claim | | 3 | htlc | 0.003 TAZ for 3.72 OUSD with the Rust SDK, completed in about 4 minutes with a relayed claim | All three ran on the NU7 testnet chain through `testnet.zec.rocks:443`: runs 1 and 2 with this example, run 3 with its Rust counterpart, [`examples/rust/rust-testnet`](#with-the-rust-sdk). ## What you need | Variable | What it is | |---|---| | `ZEC_TAKER_KEY` | A transparent Zcash testnet private key (32 bytes of hex) whose `tm…` address holds the TAZ you will swap | | `ZEC_MAKER_KEY` | The maker's transparent Zcash key. The TAZ the maker claims goes to its address; it needs no funds | | `EVM_MAKER_KEY` | A Moderato account holding OUSD for the maker to lock, plus pathUSD for transaction fees | | `EVM_RELAYER_KEY` | Optional. An account with pathUSD that pays the claim fee, so the recipient needs nothing. It can't redirect the OUSD | | `LIGHTWALLETD_URL` | Optional. Default `testnet.zec.rocks:443` | | `TEMPO_RPC_URL` | Optional. Default `https://rpc.moderato.tempo.xyz` | Inside a Paralock checkout, any key variable you don't set falls back to a file in `.paralock/`: `testnet-zcash.json` (taker), `testnet-maker-zcash.json`, `testnet-deployer.json` (maker EVM) and `testnet-relayer.json`, each shaped like `{ "privateKey": "…" }`. The taker's own EVM key is created on the first run in `.paralock/testnet-taker-evm.json`. That directory is gitignored. > **Note:** Tempo has no native gas token: fees are paid in a TIP-20 stablecoin, here pathUSD. The taker's EVM key only signs the claim when no relayer is set, and in that case its address needs pathUSD for the fee. ### Make the Zcash keys Any random 32 bytes is a valid key. Generate one for the taker and one for the maker, and print the taker's testnet address (run the last command from `examples/testnet`, where `@paralock/zcash` is installed): ```sh export ZEC_TAKER_KEY=$(openssl rand -hex 32) export ZEC_MAKER_KEY=$(openssl rand -hex 32) node --input-type=module -e "import { keyAddress, keyPairFromPrivate } from '@paralock/zcash'; console.log(keyAddress(keyPairFromPrivate(process.env.ZEC_TAKER_KEY), 'testnet'))" ``` Keep both keys. The taker's key signs htlc-mode refunds, so losing it can strand a locked swap. ### Get TAZ into the transparent address Paralock spends from a transparent address (`tm…`). The [Valar faucet](https://faucet.testnet.valargroup.dev) pays on the NU7 chain that this example uses; for the first public runs, its TAZ went to a zcash-devtool wallet and from there to the taker's `tm…` address. Whatever wallet you use must follow the same side of the testnet split (see the note below). Wait for one confirmation (about 75 seconds). > **Note:** Zcash testnet is currently split in two. `testnet.zec.rocks`, the server this example uses, follows the NU7 chain that Zakura activated (consensus branch `0x77190ad9`), while Zebra, many faucets and explorers such as zexplorer.app follow the NU6.3 chain (branch `0x37a5165b`). Paralock works on either chain, but your lightwalletd server or node must be on the same chain as your TAZ: coins received on one chain don't exist on the other. [The Zcash testnet split](https://paralock.xyz/docs/networks#the-zcash-testnet-split) explains how to check which chain a server or a faucet follows. ## Run it From the repository root, after `pnpm install && pnpm build`: ```sh pnpm --filter @paralock/example-testnet start -- --zec 0.2 # swap 0.2 TAZ (htlc mode) pnpm --filter @paralock/example-testnet start -- --zec 0.2 --private # private mode (adaptor): nothing on-chain links the legs pnpm --filter @paralock/example-testnet start -- --pay 20 --to 0x… # pay exactly 20 OUSD to someone else pnpm --filter @paralock/example-testnet start -- --zec 0.2 --fresh # receive at a fresh address made for this swap ``` Without `--zec` or `--pay`, it swaps 0.1 TAZ. The example lowers the maker's minimum to 0.002 TAZ (`minZecAmountZat: 200_000n`; the default is 0.01) and keeps the default maximum of 10, so a swap must be between 0.002 and 10 TAZ. A payment therefore has to be worth at least 0.002 ZEC at the current price (about $2.54 at $1,270 per ZEC); smaller amounts fail with `limit_exceeded`. The example first prints the taker's address and its confirmed TAZ balance, and stops if it is empty. Then it quotes from the live ZEC price (TAZ is priced as if it were ZEC), runs the swap, prints one line per step, and ends with the transactions: the Zcash lock, the Tempo lock, the Tempo claim and, once it is seen, the maker's Zcash claim. Tempo steps link to the Moderato explorer. No public explorer indexes the NU7 chain yet, so Zcash steps print the txid: look it up through a lightwalletd server on that chain, for example with `getRawTransaction` on a `LightwalletdClient` for `testnet.zec.rocks:443`. ## The core of it ```ts const zcash = new LightwalletdClient("testnet.zec.rocks:443"); const maker = createMaker({ zcash: { network: "testnet", node: zcash, key }, evm: { tempo: { …, token: OUSD } }, price: zecUsdPrice(), policy }); const taker = createTaker({ zcash: { network: "testnet", node: zcash, key }, evm: { tempo: { …, tokens: [OUSD] } }, maker }); const quote = await taker.quote(20_000_000n, "tempo", "adaptor"); const swap = await taker.swap(quote); ``` Both parties share one `LightwalletdClient`, which implements the same `ZcashNode` interface as a Zebra RPC client. On Tempo, both set `feeToken` to pathUSD. Full source: `examples/testnet/src/index.ts`. ## Timing Zcash testnet blocks come about every 75 seconds, so a swap takes a few minutes, most of it spent waiting for Zcash blocks: 1. The maker accepts the swap and reserves the OUSD before the taker broadcasts anything, so the 60-second quote only has to last a few seconds. Then the taker's funding needs one block to confirm. 2. The maker polls every 15 seconds, sees the confirmed funding and locks OUSD. Tempo confirms in under a second. 3. The taker verifies the lock and claims on Tempo. 4. The maker's Zcash claim needs one more block. lightwalletd only reports mined transactions, so neither side sees a transaction until it is in a block. Run 2 above took 3 min 39 s from the maker's acceptance to its Zcash claim. The example raises the taker's waits for the slower chain: up to 60 minutes for the funding to confirm (`fundingConfirmationMs`) and for the maker's lock (`makerLockMs`), and up to 20 minutes to watch the maker's ZEC claim (`followMakerMs`). It also requires 120 seconds of EVM lock left before claiming (`minClaimWindowSeconds`), instead of the default 30. ## The testnet policy The example passes its own timeout policy to the maker: ```ts const TESTNET_POLICY: TimeoutPolicy = { zcashLockBlocks: 96, // refund height N = tip + 96 blocks: about 2 hours at 75 s evmLockSeconds: 1800, // expiry T = 30 minutes after the maker locks zcashBlockSeconds: 75, // used to compare the two clocks minZcashConfirmations: 1, // the maker waits for one confirmation of the funding and of its own claim safetyFactor: 2, // the Zcash time left must be at least 2× the EVM lock }; ``` When the maker locks, at least 2 × 1,800 = 3,600 seconds (48 blocks) must remain before N. N starts 96 blocks out, so the maker has about 48 blocks (an hour) after the taker builds its lock to lock the OUSD, or it abandons the swap. Whoever learns the secret always has time to use it. [How it works](https://paralock.xyz/docs/how-it-works#timelines) explains the rule; `MAINNET_POLICY` uses 144 blocks and a one-hour EVM lock. ## If a swap stalls Both parties persist everything before each step: the maker in `.paralock/testnet-swaps/maker`, the taker in `.paralock/testnet-swaps/taker`. Every run of the example calls `maker.start()`, which resumes the maker's unfinished swaps for as long as that run lasts: it claims the TAZ if the taker claimed, or refunds the OUSD after T. A real maker runs as a long-lived service, so this happens on every restart. If the taker's TAZ is locked and the swap can't finish, refund it after the refund height with a short script that opens the same store: ```ts import { LightwalletdClient } from "@paralock/lightwalletd"; import { type Hex, createTaker } from "@paralock/sdk"; const zcash = new LightwalletdClient("testnet.zec.rocks:443"); const taker = createTaker({ zcash: { network: "testnet", node: zcash, key: process.env.ZEC_TAKER_KEY! }, evm: { tempo: { rpcUrl: "https://rpc.moderato.tempo.xyz", chainId: 42431, htlc: "0xD9B278625B5946B8CD15dad6c0c776095B8D0513", adaptorEscrow: "0xd2f352Fa313d23b3536dAA3d783263C03CED2673", fromBlock: 39235852, account: process.env.EVM_TAKER_KEY as Hex, // the key in .paralock/testnet-taker-evm.json tokens: ["0x20c0000000000000000000006a37DA5C996874BE"], // OUSD }, }, maker: "http://127.0.0.1:7420", // refund() never contacts the maker store: ".paralock/testnet-swaps/taker", // the example's taker store, from the repo root }); for (const swap of await taker.pendingSwaps()) { console.log(`${swap.id}: ${swap.status}, refund opens at block ${swap.zcash.refundHeight}`); await taker.refund(swap.id); // waits for the refund height (about 75 s per block), then broadcasts } zcash.close(); ``` In htlc mode the refund is signed with `ZEC_TAKER_KEY`; in private mode it uses the refund the maker pre-signed, which is in the store. See [Persistence and recovery](https://paralock.xyz/docs/recovery). ## With the Rust SDK [`examples/rust/rust-testnet`](https://github.com/bitfalt/paralock/tree/main/examples/rust/rust-testnet) runs the same swap with the [Rust SDK](https://paralock.xyz/docs/rust): a Rust taker and an in-process Rust maker, the `Lightwalletd` backend on `testnet.zec.rocks:443`, and the Moderato escrows from `paralock-evm`'s registry (`testnet_deployment(42431)`). It reads the same variables and `.paralock/testnet-*.json` files as the TypeScript example, with its own swap stores (`.paralock/testnet-swaps/rust-maker` and `rust-taker`), since the two SDKs' record formats differ. ```sh cargo run -p rust-testnet -- --quote-only # keys, balance and a live quote; nothing moves cargo run -p rust-testnet # swap 0.003 TAZ (htlc mode) cargo run -p rust-testnet -- --zec 0.005 --private # private mode cargo run -p rust-testnet -- --resume # finish a swap after an interruption cargo run -p rust-testnet -- --refund # TAZ back after the refund height ``` > **Note:** Small amounts pay a large share in fees. The maker prices its own Zcash claim fee (10,000 zat) into every quote, which is 3.3% of 0.003 TAZ. The Rust taker's rate check allows that fixed fee on top of its slippage limit (`TakerLimits::maker_fee_zat`), while the TypeScript taker's `maxSlippageBps` has to cover it. The Rust example also allows 5% slippage as headroom for a price that moves between the two parties' reads; keep the defaults for real amounts. For a terminal instead of code, the [`paralock` binary](https://paralock.xyz/docs/rust-cli) reaches the same deployments from a `paralock.toml` with `network = "testnet"`. ## Other testnets The escrows are also deployed on Base Sepolia, Sepolia, Arbitrum Sepolia, Robinhood Chain Testnet and HyperEVM Testnet. Each `contracts/deployments/.json` lists `htlc`, `adaptorEscrow`, the tokens and `startBlock` (pass it as `fromBlock`). Testnet USDC comes from [faucet.circle.com](https://faucet.circle.com); Robinhood Chain Testnet has no USDC, so a 6-decimal MockUSD test token stands in. The [contracts page](https://paralock.xyz/docs/contracts) has every address. The `testnet` example is wired for Tempo Moderato; for another chain, change the `evm` entry and the token. --- # Run a maker Source: https://paralock.xyz/docs/run-a-maker Markdown: https://paralock.xyz/docs/run-a-maker.md Section: Guides > Configure createMaker, price your quotes, choose a timeout policy and limits, fund inventory, persist state, serve the HTTP API, and understand what a maker earns and risks. A **maker** is the counterparty in every swap: it quotes a price, locks stablecoins once the taker's ZEC is safely locked, and claims the ZEC when the taker claims the stablecoins. It earns the spread between its quote and the market price. The protocol is symmetric, so anyone can run one with the SDK; running the maker is also Paralock's business model. > **Warning:** The code is experimental and not audited by a third party, and the escrows are deployed on testnets only. Paralock has no mainnet deployment. `MAINNET_POLICY` and the mainnet checks exist so the defaults are safe, not as an invitation to run a maker with real funds. ## What you need - **A Zcash backend:** a Zebra or Zakura JSON-RPC node (`rpcUrl`), or any `ZcashNode`, such as a lightwalletd server through [`@paralock/lightwalletd`](https://paralock.xyz/docs/lightwalletd). - **A transparent Zcash key.** Its public key goes into htlc quotes. Claimed ZEC goes to `payoutAddress` (by default the key's own address). - **An EVM account on each chain you quote,** holding the stablecoin inventory and gas. - **A durable store,** backed up. - **A price feed.** - **A public HTTPS endpoint** for takers, behind TLS and a rate limiter. - **Uptime** for as long as any swap is open: about three hours per swap with `MAINNET_POLICY`. ## Create the maker ```ts import { createServer } from "node:http"; import { type Hex, createMaker, makerHandler, zecUsdPrice } from "@paralock/sdk"; const maker = createMaker({ zcash: { network: "testnet", rpcUrl: "http://127.0.0.1:18232", // a Zebra or Zakura node (or `node: new LightwalletdClient(…)`) key: process.env.MAKER_ZEC_KEY!, // its pubkey goes into htlc quotes payoutAddress: process.env.MAKER_PAYOUT_ADDRESS, // where claimed ZEC goes (default: the key's own address) }, evm: { tempo: { rpcUrl: "https://rpc.moderato.tempo.xyz", chainId: 42431, htlc: "0xD9B278625B5946B8CD15dad6c0c776095B8D0513", adaptorEscrow: "0xd2f352Fa313d23b3536dAA3d783263C03CED2673", fromBlock: 39235852, account: process.env.MAKER_EVM_KEY as Hex, feeToken: "0x20C0000000000000000000000000000000000000", // pathUSD pays Tempo fees token: { address: "0x20c0000000000000000000006a37DA5C996874BE", symbol: "OUSD" }, }, base: { rpcUrl: "https://sepolia.base.org", chainId: 84532, htlc: "0xD9B278625B5946B8CD15dad6c0c776095B8D0513", adaptorEscrow: "0xd2f352Fa313d23b3536dAA3d783263C03CED2673", fromBlock: 48009147, account: process.env.MAKER_EVM_KEY as Hex, token: { address: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", symbol: "USDC", decimals: 6 }, }, }, price: zecUsdPrice(), // CoinGecko, cached 60 s; no fixed fallback spreadBps: 50, // 0.5% below the feed price limits: { maxZecAmountZat: 500_000_000n, maxConcurrentSwaps: 20 }, // 5 ZEC per swap, 20 at once store: "./paralock-maker", // quotes, swaps and per-swap keys; back it up log: (message) => console.log(message), afterClaim: async (swap) => console.log(`claimed ${swap.zcash.amountZat} zat in ${swap.zcash.claimTxid}`), }); await maker.start(); // resumes every unfinished swap ``` The addresses above are the Tempo Moderato and Base Sepolia deployments from `contracts/deployments/.json`. See [Contracts and deployments](https://paralock.xyz/docs/contracts) for the others. ### Options | Option | Default | Meaning | |---|---|---| | `zcash.network` | required | `"mainnet"`, `"testnet"` or `"regtest"` | | `zcash.rpcUrl` / `zcash.node` | one is required | A Zebra or Zakura JSON-RPC URL (with optional `rpcAuth`), or any `ZcashNode`. `node` wins | | `zcash.key` | required | The maker's transparent private key: hex, bytes or a `KeyPair` | | `zcash.payoutAddress` | the key's address | Transparent address that receives claimed ZEC | | `evm..rpcUrl`, `chainId` | required | The chain's RPC endpoint and id | | `evm..htlc` | required | The `ParalockHTLC` address | | `evm..adaptorEscrow` | none | The `ParalockAdaptorEscrow` address. Leave it out to offer only htlc mode on this chain | | `evm..account` | required | A `0x` private key or a viem `Account`, for example one backed by a KMS | | `evm..fromBlock` | `0` | The escrows' deployment block (`startBlock` in the deployment file). Lock lookups scan logs from here, so set it on public chains | | `evm..feeToken` | none | Tempo only: the TIP-20 that pays fees | | `evm..token` | required | `{ address, symbol, decimals? }`: the stablecoin you quote here (decimals default to 6) | | `evm..rpcTimeoutMs`, `rpcRetryCount` | 10 s, 3 | Per-request timeout, and retries on network errors, 5xx and 429 | | `price` | required | `() => Promise`: USD per ZEC | | `spreadBps` | 50 | Your spread below the price, in basis points (1 bps = 0.01%) | | `policy` | `MAINNET_POLICY` | The timeout policy (below) | | `limits` | `DEFAULT_MAKER_LIMITS` | Per-swap and capacity limits (below) | | `store` | in memory | A directory (`FileSwapStore`) or any `SwapStore`. Required on mainnet | | `pollIntervalMs` | a fifth of a Zcash block, 1 to 15 s | How often settlement loops poll the chains | | `afterClaim` | none | Runs after each ZEC claim confirms, for example to shield it. Errors are logged, never fatal | | `log` | none | Receives progress and alert messages | ## Pricing Every quote starts from `price()` and applies your spread: ```text rate = price × (1 − spreadBps / 10,000) exact-in: stablecoins = (zat − zcashFeeZat) × rate rounded down exact-out: zat = stablecoins / rate + zcashFeeZat rounded up ``` `zcashFeeZat` (10,000 zat by default) covers your own Zcash claim transaction, so it comes out of every quote. With a $1,280 feed price and 50 bps, `rate` is $1,273.60: selling 1 ZEC yields $1,273.47, and a $25 payment costs 0.0197294 ZEC. `zecUsdPrice(options)` reads CoinGecko's simple price API: | Option | Default | Meaning | |---|---|---| | `url` | CoinGecko | Any endpoint that returns `{ "zcash": { "usd": } }` | | `cacheMs` | 60,000 (60 s) | Reuse a fetched price for this long | | `maxStaleMs` | 300,000 (5 min) | When the feed fails, keep serving the last good price for at most this long | | `timeoutMs` | 3,000 (3 s) | Request timeout | | `fallback` | none | A fixed price for devnets and demos only | Without `fallback`, an outage longer than `maxStaleMs` makes quoting throw `ParalockError("unavailable")`. That is deliberate: a fixed or stale price lets anyone trade against you at the wrong rate. Any async function works as `price`, so you can plug in your own oracle or several feeds. Takers can check you too: a taker that passes its own `price` rejects quotes worse than its `maxSlippageBps` (default 200, or 2%). ## The timeout policy | Field | `MAINNET_POLICY` | Meaning | |---|---|---| | `zcashLockBlocks` | 144 | Blocks from the taker's lock to its refund height N: about 3 hours at 75 s | | `evmLockSeconds` | 3,600 | How long your EVM lock stays claimable: expiry T is 1 hour after you lock | | `zcashBlockSeconds` | 75 | Expected Zcash block time, used to compare the two clocks | | `minZcashConfirmations` | 2 | Confirmations you wait for on the taker's funding, and on your own ZEC claim | | `safetyFactor` | 2 | The Zcash time left before N must be at least this many times the EVM lock | `createMaker` rejects a policy whose values aren't positive integers, whose `safetyFactor` is below 1, or whose own windows fail `assertSafeWindows`. The maker then checks the window again for every swap: when it accepts the taker's lock, right before it locks, and before it sends the lock transaction. If the window has become too short, it abandons the swap instead of locking. [How it works](https://paralock.xyz/docs/how-it-works#timelines) explains why. Keep the policy inside what takers accept by default: a Zcash window of 10 to 288 blocks and an EVM lock of 30 to 86,400 seconds. For the devnet there is `DEVNET_POLICY` (40 blocks, 45 s, 3 s blocks), and `examples/testnet` uses 96 blocks and 1,800 s. ## Limits | Limit | Default | Meaning | |---|---|---| | `minZecAmountZat` | 1,000,000 (0.01 ZEC) | Smallest swap. Must exceed `zcashFeeZat` | | `maxZecAmountZat` | 1,000,000,000 (10 ZEC) | Largest swap | | `maxConcurrentSwaps` | 10 | Swaps in flight at once; more get `busy` (HTTP 429) | | `maxOpenQuotes` | 1,000 | Unexpired quotes held at once (each private-mode quote carries a fresh key) | | `quoteTtlSeconds` | 60 | How long a quote is honored. Takers commit before broadcasting their funding, so this covers seconds of work, not a block | | `maxFundingExpiryBlocks` | 45 | Furthest a taker's `fundingExpiryHeight` may be above your tip: bounds how long an unfunded reservation holds inventory. An htlc accept without one (older takers) gets `tip + 45` as its deadline, applied only while you have never seen its funding | | `minEvmLockSecondsLeft` | 30 | EVM seconds your lock must still have when you send it; with less you abandon instead of locking, since a taker couldn't claim in time | | `zcashFeeZat` | 10,000 | ZEC priced into each quote for your own claim (the ZIP 317 minimum) | | `checkInventory` | true | Check the stablecoin balance before quoting and before locking | `maker.effectiveLimits` returns the limits in force. ## Inventory and gas On each chain you quote, the maker's account needs: - **Stablecoin inventory.** With `checkInventory`, a quote or a new swap is refused with `insufficient_liquidity` unless your balance, minus what swaps that haven't locked yet have reserved, covers the amount. The balance is checked again right before locking. - **Gas.** Each lock may first send an approval: allowances are exact, never unlimited. Then the lock, and a refund whenever a taker doesn't claim. On Tempo there is no native gas token: fees are paid in a TIP-20 stablecoin such as pathUSD (set `feeToken`), and a lock costs about 305,000 gas, of which about 250,000 is the one new storage slot (TIP-1000). On the other chains you pay in the native token. On Zcash, the maker spends nothing up front: its claim fee comes out of the ZEC it claims. ## Persistence The maker writes to its store before every step that matters: - each quote, with its fresh per-quote Zcash key in private mode, **before the quote is returned**; - each swap, with the one-time EVM signer key and the taker's pre-signature (private mode); - the EVM lock parameters **before locking**, since they are what a refund needs; - its ZEC claim transaction **before broadcasting** it. `createMaker` refuses a non-durable store on mainnet. Use a `FileSwapStore` directory (pass a path) or your own `SwapStore` backed by a database, and back it up like a wallet: in private mode the per-quote key that claims the ZEC exists nowhere else. Use one store per maker process. See [Persistence and recovery](https://paralock.xyz/docs/recovery). ## Restarts and recovery `await maker.start()` loads the store, drops expired quotes, and resumes every unfinished swap. The HTTP handler also calls it on the first request, and it is safe to call more than once. Each swap is a persisted state machine: | Stage | Waiting for | |---|---| | `proposed` | The taker's pre-signature (private mode). The stablecoins are reserved. Dropped once the funding is unmined 2 blocks past its declared `fundingExpiryHeight`, or once locking would no longer be safe | | `funding` | The taker's funding to be broadcast and reach `minZcashConfirmations` with the right amount. The stablecoins are reserved (the taker commits before it broadcasts). Dropped like `proposed` | | `locking` | The EVM lock to appear on-chain. Locks are idempotent, so resending after a crash is safe | | `locked` | The taker's claim, or expiry T | | `claiming` | The maker's ZEC claim to confirm. It is rebroadcast until it does | | `refunding` | The EVM refund after T | The final stages are `completed`, `refunded`, `abandoned` (nothing was locked) and `lost`. `lost` means the Zcash lock was spent by someone else, the taker's refund, before your claim confirmed; the maker logs an `ALERT` line. It happens only when your claim didn't confirm before the refund height N: the maker was offline or stuck, or its claim wasn't mined in time. `await maker.stop()` stops the settlement loops and waits for them; the next `start()` resumes them. For an operator view, `maker.listSwaps()` returns every swap's public data and `maker.getStage(id)` its internal stage. ## Serve it over HTTP `makerHandler(maker, options)` is a web-standard `(Request) => Promise` handler, so it runs in Node.js through a small adapter, and in Bun or Deno directly. ```ts const handle = makerHandler(maker, { cors: { origin: ["https://app.example"] } }); createServer(async (req, res) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); // also cap the size here or at your proxy const response = await handle( new Request(`http://maker${req.url}`, { method: req.method, headers: req.headers as HeadersInit, body: chunks.length ? Buffer.concat(chunks) : undefined, }), ); res.writeHead(response.status, Object.fromEntries(response.headers)).end(await response.text()); }).listen(7420); // behind a TLS-terminating proxy with rate limiting ``` | Route | Purpose | |---|---| | `GET /quote?zat=…&chain=…&mode=…` | Exact-in quote (`?usd=…` instead of `zat` for exact-out). `chain` defaults to `tempo`, `mode` to `htlc` | | `POST /swaps` | htlc mode: the taker's HTLC and its signed funding, before the taker broadcasts it. You check it and reserve the stablecoins | | `POST /adaptor/swaps` | Private mode: the taker's proposal; you reserve the stablecoins and return your signed refund | | `POST /adaptor/swaps/:id/presignature` | Private mode: the taker's pre-signature on your claim | | `GET /swaps/:id` | One swap's public view: status, both legs and events, never the adaptor point, pre-signatures, signer key or salt | | `GET /health` | `{ ok, chains, zcashPubkey }` | | `GET /swaps` | Every swap, only with `exposeSwapList: true` | | Handler option | Default | Meaning | |---|---|---| | `cors` | off | `{ origin: "*" }` or a list of allowed origins | | `maxBodyBytes` | 16 KiB | Larger bodies get HTTP 413 | | `exposeSwapList` | false | Leave it off: a public list would let anyone link swaps | | `onError` | `console.error` | Receives unexpected errors. Clients only get a generic 500 | Errors come back as `{ error, code }` with the HTTP status of the `ParalockError` code, for example 410 for `quote_expired` and 503 for `insufficient_liquidity`. Version 0.3.0 changed this API in two ways: `GET /swaps/:id` no longer includes the adaptor data (the taker gets it in the answer to its own pre-signature request), and private-mode proposals must carry `fundingExpiryHeight`. A 0.3.0 maker therefore refuses private-mode swaps from takers older than 0.3.0; those can still swap in htlc mode. > **Warning:** TLS and rate limiting are left to your deployment. The handler caps body sizes and open quotes, but it doesn't limit requests per client. Put it behind a reverse proxy that terminates TLS and rate-limits `/quote` and the POST routes. Takers connect with a URL (`createTaker({ maker: "https://maker.example" })`), which uses `HttpMakerApi`: a 30-second timeout, 2 retries on network errors, 5xx and 429, and response validation. If your API needs a key, takers pass it with `makerHttp: { headers }`. ## What a maker earns and risks **Earnings:** the spread on every filled swap. At 50 bps, a $1,000 swap earns about $5 before costs. The Zcash claim fee is already priced in. **Costs and risks:** | Risk | What it is | What limits it | |---|---|---| | Liveness | You must claim the ZEC before N once the taker claims. Offline past N, the taker could refund the ZEC as well, and you lose the stablecoins | The 2× window leaves at least an hour after T with `MAINNET_POLICY`; `start()` resumes on restart. Monitor uptime | | Free option | After you lock, the taker can walk away if the price moves against it. Your inventory stays locked until T, then you pay the refund gas | Short EVM locks, short quote TTL, and the spread | | Price | You end up holding ZEC, priced minutes earlier | Your spread; hedge outside the SDK | | Inventory lockup | Each swap ties up stablecoins until it settles or refunds | `maxConcurrentSwaps`, per-swap limits | | Gas | Approval, lock, and refund on unclaimed swaps | Spread; Tempo fees are paid in stablecoins | | Reorgs | A funding or lock could disappear | `minZcashConfirmations`; the maker re-checks a lock that vanished | | Network upgrades | A Zcash upgrade before N invalidates pre-signed spends | Private-mode proposals are refused if an upgrade activates before the refund height | | Losing the store | In private mode, the key that claims the ZEC exists only there | Durable store, backups | | Software | Not audited by a third party | Small limits, testnets only | ## Operational checklist - Use a durable store, one per process, on reliable storage, with encrypted backups. - Keep keys in environment variables or a KMS (`account` accepts a viem `Account`). Never commit them. - Set `fromBlock` to the deployment block on every chain, and take addresses from the deployment files or `knownNetwork(chainId)` from `@paralock/evm`. - Use `zecUsdPrice()` without `fallback`, or your own feed. - Fund stablecoin inventory and gas on every chain you quote, and alert on low balances. - Run under a process supervisor that restarts on failure; `start()` resumes every swap. - Terminate TLS and rate-limit at a proxy. Keep CORS restricted and `exposeSwapList` off. - Watch the logs for `ALERT` lines and `abandoned` swaps. - Prefer a full node (Zebra or Zakura) over lightwalletd: it sees mempool spends (`getTxOut`) and reports upcoming network upgrades. lightwalletd sees only mined transactions, and reports upgrades only on servers recent enough to send `lightwalletProtocolVersion`. - Use `afterClaim` to move claimed ZEC into the shielded pool. - Start with small `maxZecAmountZat` and `maxConcurrentSwaps`. --- # Privacy Source: https://paralock.xyz/docs/privacy Markdown: https://paralock.xyz/docs/privacy.md Section: Guides > The three privacy levels, the PrivacyOptions that implement level 1, private mode with adaptor signatures, and what an observer can still see. Paralock removes the middleman, but privacy depends on what the two chains reveal. A swap has two legs: ZEC locked on Zcash and stablecoins locked on an EVM chain. Both locks are public. The goal is that neither your shielded history nor the link between the two legs leaks. > **Warning:** In every mode the Zcash leg is a transparent output, not a shielded one. Shield your ZEC before and after a swap, and read the [limitations](#honest-limitations) below. ## Three levels | | Level 1: hygiene | Level 2: adaptor signatures | Level 3: fully shielded leg | |---|---|---|---| | Status | Shipped | Experimental | In research | | How | `PrivacyOptions` and shielding in your wallet | `mode: "adaptor"` | FROST 2-of-2 shielded notes | | Swap visible on Zcash? | Yes: a transparent HTLC | Yes, but only as an ordinary 2-of-2 multisig | No: a normal shielded transaction | | A shared value links the two chains? | Yes: the same sha256 hashlock | None | None | | Linked to your wallet history? | No, if you shield before and after and use a fresh recipient | No | No | | Amount and timing correlation | Reduced: standard amounts, jitter | Reduced | Reduced | Level 1 and level 2 combine: use private mode and every hygiene option together. ## Level 1: hygiene These measures don't hide that a swap happened, or the link between its two legs. They keep a swap from linking to the rest of your activity. ### Shield before and after The taker spends from one transparent key. Keep your savings in the shielded pool, and before each swap move **only the swap amount** (plus fees) from your shielded balance to that key's transparent address, `taker.zcashAddress`. Change and refunds go to `zcash.returnAddress` (by default the same address); shield them again. The maker does the same with the ZEC it claims, for example in its `afterClaim` hook. The SDK doesn't move shielded funds: your wallet does. The devnet shows the pattern: the CLI unshields each swap from ths account 1 into the dedicated swap address (account 2) and reshields change afterwards, and `examples/payroll` does the same for a treasury. ### Fresh recipient `freshRecipient: true` pays the stablecoins to a new EVM address created for this swap, instead of an address that already has a history. Its private key is kept in the store and passed to `onFreshRecipient`; read it back with `taker.freshRecipient(id)`. That key controls the funds, so the taker refuses this option unless the store is durable or you set `onFreshRecipient`. If you pass a `recipient` (a payment), it wins over `freshRecipient`. ### Relayed claim A fresh address has no gas. `relayClaim: true` lets the `relayer` account configured on that chain submit the claim and pay its gas. The relayer can't redirect the funds: the escrow always pays the recipient fixed at lock time. It could refuse or fail to relay; then the swap fails with `SwapFailedError` (the SDK doesn't fall back by itself), and `taker.resume(id, { relayClaim: false })` submits the claim from your own EVM account before the lock expires. That account pays the gas and is linked to the claim; the recipient stays the one in the lock. ### Standard amounts `standardAmountsOnly: true` refuses any amount other than 0.1, 0.5, 1 or 5 ZEC (`STANDARD_AMOUNTS_ZAT`), so an unusual amount doesn't single out your swap. It applies to the ZEC amount, so use it with exact-in quotes (`taker.quote`). An exact-out payment almost never lands on a standard amount. ### Timing jitter `jitterMs: n` waits a random 0 to `n` milliseconds before claiming, so the claim doesn't line up exactly with the maker's lock. Keep it well inside the EVM lock: the taker re-checks the time left after the jitter, and if fewer than `minClaimWindowSeconds` remain it refuses to claim, and both sides refund. ### All together ```ts import { type Hex, createTaker } from "@paralock/sdk"; const taker = createTaker({ zcash: { rpcUrl: "http://127.0.0.1:18232", network: "testnet", key: process.env.ZEC_KEY!, returnAddress: process.env.ZEC_RETURN_ADDRESS }, evm: { base: { rpcUrl: "https://sepolia.base.org", chainId: 84532, // Base Sepolia: the escrows are deployed on testnets only htlc: "0xD9B278625B5946B8CD15dad6c0c776095B8D0513", adaptorEscrow: "0xd2f352Fa313d23b3536dAA3d783263C03CED2673", account: process.env.EVM_KEY as Hex, relayer: process.env.RELAYER_KEY as Hex, // pays the claim gas; can't redirect the funds fromBlock: 48009147, // startBlock from contracts/deployments/84532.json }, }, maker: "https://maker.example", store: "./paralock-taker", // fresh-recipient keys are kept here too onFreshRecipient: (account, swap) => console.log(`swap ${swap.id} pays ${account.address}; store its key safely`), }); const quote = await taker.quote(50_000_000n, "base", "adaptor"); // 0.5 ZEC, private mode const swap = await taker.swap(quote, { privacy: { freshRecipient: true, // pay a new address created for this swap relayClaim: true, // the relayer submits the claim, so that address needs no gas standardAmountsOnly: true, // refuse anything but 0.1, 0.5, 1 or 5 ZEC jitterMs: 60_000, // wait a random 0 to 60 s before claiming }, }); const recipient = await taker.freshRecipient(swap.id); // { address, privateKey }: it controls the stablecoins ``` The same options on the devnet CLI: ```sh npx paralock swap --zec 0.5 --chain base --private --fresh-recipient --relay --standard-only --jitter 10000 ``` The devnet saves fresh-recipient keys to `recipients.jsonl` in the CLI's [state directory](https://paralock.xyz/docs/cli#state-directory). **What level 1 still leaks:** the HTLC is transparent, and the same hashlock appears on both chains, so anyone can pair the two legs of a swap. ## Level 2: adaptor signatures Private mode (`mode: "adaptor"`, or `--private` in the CLI) removes every shared value from the chains: - **On Zcash,** the ZEC sits in a plain 2-of-2 multisig of a fresh taker key and a fresh maker key made for this quote. Spending it looks like any other multisig spend. - **On the EVM chain,** `ParalockAdaptorEscrow` pays the recipient when given a signature from a one-time `signer` key over `claimDigest(id)`. The escrow id is a hash of the lock's parameters, including a random salt. - **The secret is `y`,** the discrete logarithm of an adaptor point `Y = y·G` that only the two parties ever see. The taker's claim publishes a completed signature. Only the maker, who holds the matching pre-signature, can compute `y` from it, and then complete the taker's pre-signature on the Zcash claim. Since 0.3.0, the maker's public swap view (`GET /swaps/:id`) never contains `Y`, the pre-signatures, the signer's key or the salt: the maker sends them only in answers to the taker's own requests. [How it works](https://paralock.xyz/docs/how-it-works#the-adaptor-flow) walks through the ten steps. The cryptography is in [`@paralock/adaptor`](https://paralock.xyz/docs/adaptor): ECDSA adaptor signatures on secp256k1 with Chaum–Pedersen DLEQ proofs and hedged nonces. **What level 2 still leaks:** - the amounts and timing of the two legs (use standard amounts and jitter); - the fact that a 2-of-2 multisig was used on Zcash; - an interaction with `ParalockAdaptorEscrow` on the EVM chain; - to whoever learns the swap id (the quote id): both legs. The maker's public view of a swap lists both chains' transactions and the amounts to anyone who asks with the id, so keep swap ids out of logs and shared links. An observer who suspects a swap can still correlate amounts and time windows, but has no cryptographic link between the legs. > **Warning:** Adaptor ECDSA has had far less scrutiny than Schnorr adaptor signatures, and this code is not audited by a third party. Treat private mode as experimental. ## Level 3: a fully shielded Zcash leg Status: **In research.** Level 2 still shows a transparent multisig on Zcash. Removing it needs the shielded pool: - **FROST 2-of-2 shielded notes.** Orchard spend authorization uses RedPallas, which FROST already supports. The taker would pay into a note that both parties control jointly. - **Schnorr adaptor signatures,** which are simpler and better studied than the ECDSA version and extend naturally to FROST. - **A cross-group DLEQ proof,** showing the same `y` is valid on Pallas (Zcash) and on secp256k1 (EVM), as BTC⇄XMR swaps do for ed25519. - **A time-locked refund.** A v5 transaction's `lock_time` applies to the whole transaction, so a pre-signed shielded refund can be time-locked too. The result would be an ordinary shielded transaction on Zcash, with only the EVM leg visible. Open work: a cross-curve proof implementation, Ironwood support in FROST (in progress), and wallet support for jointly controlled notes (PCZT helps). The [roadmap](https://paralock.xyz/docs/roadmap) tracks it. ## What observers can still see | Who | htlc mode | Private mode | |---|---|---| | Anyone watching Zcash | The transparent swap address funding the HTLC, the amount, the hashlock, the claim or refund, and the secret once claimed | The swap address funding a 2-of-2, the amount, and the spend with two ordinary signatures | | Anyone watching the EVM chain | The maker's lock, recipient, amount, expiry, the hashlock, and the secret in `Claimed` | The maker's lock, recipient, amount, expiry, the one-time signer, and the signature in `Claimed` | | Both chains together | The same hashlock pairs the legs | Only amount and timing correlation | | The maker | Both legs of your swap, and whatever your connection reveals, such as your IP address | The same: it is your counterparty | | Your lightwalletd server | The addresses you query and the transactions you send | The same | | The relayer | The claim it submits, which becomes public anyway | The same | ## Honest limitations - **The Zcash leg is transparent in both modes.** Shielding before and after keeps your history out of it, but the lock, its amount and its spend are public. - **The maker sees everything about your swap.** No mode hides your swap from your counterparty. Reach it over a network path you are comfortable with. - **Amounts and timing correlate.** Standard amounts and jitter reduce this; they don't remove it, especially when few swaps happen. - **What you do next can re-link.** Moving funds from a fresh recipient into an address you already use links them. - **Light servers learn your addresses.** A lightwalletd server sees which transparent addresses you query and what you broadcast. Run your own node or server if that matters. - **On Tempo, transfers carry a memo:** the hashlock (htlc mode) or the escrow id (private mode). In private mode the escrow id doesn't relate to anything on Zcash. --- # Persistence and recovery Source: https://paralock.xyz/docs/recovery Markdown: https://paralock.xyz/docs/recovery.md Section: Guides > How the engines persist secrets and keys before every irreversible step, and how to resume or refund a swap after a failure, a crash or a restart. A swap spans minutes to hours on two chains. A crash in the middle must never strand funds, so both engines write everything they need to a **store** before each irreversible step: broadcasting a funding transaction, locking stablecoins, handing out a pre-signature. After a restart, the store holds enough to finish the swap or refund it. ## Stores A store is any implementation of the `SwapStore` interface: `get`, `put`, `delete`, `list(prefix)`, and a `durable` flag. `put` must resolve only once the record would survive a crash or power loss. | Store | Durable | Use it for | |---|---|---| | `MemorySwapStore` | No | Tests and throwaway sessions. Everything is lost on exit | | `FileSwapStore(dir)` | Yes | A single process on one machine. One JSON file per record | | Your own `SwapStore` | You decide | A database, replicated storage, a KMS-backed vault | Pass `store` to `createTaker` or `createMaker` as a directory path (which creates a `FileSwapStore`) or as a `SwapStore` object. Without it, both default to a `MemorySwapStore`, and both factories **refuse a non-durable store on mainnet**. The taker also refuses `freshRecipient` with a non-durable store unless you set `onFreshRecipient`, because the fresh address's key would be lost. `FileSwapStore` creates its directory with mode 0700 and each file with mode 0600. Every `put` writes a temporary file, fsyncs it, renames it over the old one and fsyncs the directory, so a record is always either the old version or the new one, never a torn write. Use one store directory per process. For a database, serialize records with `encodeRecord` and `decodeRecord`, which round-trip bigints exactly: ```ts import { type StoredRecord, type SwapStore, decodeRecord, encodeRecord } from "@paralock/sdk"; /** Any key-value database with durable writes. */ interface Kv { get(key: string): Promise; set(key: string, value: string): Promise; // resolves only once the write is durable delete(key: string): Promise; keysWithPrefix(prefix: string): Promise; } class KvSwapStore implements SwapStore { readonly durable = true; constructor(private readonly kv: Kv) {} async get>(key: string): Promise { const json = await this.kv.get(key); return json === undefined ? undefined : decodeRecord(json); } put(key: string, record: StoredRecord): Promise { return this.kv.set(key, encodeRecord(record)); // bigints round-trip exactly } delete(key: string): Promise { return this.kv.delete(key); } async list>(prefix: string): Promise<{ key: string; record: T }[]> { const keys = (await this.kv.keysWithPrefix(prefix)).sort(); const out: { key: string; record: T }[] = []; for (const key of keys) { const record = await this.get(key); if (record) out.push({ key, record }); } return out; } } ``` Keys are short ASCII paths of at most 200 characters (`[A-Za-z0-9._:/-]`), and writes to the same key may arrive concurrently: the last one must win. ## Persist before broadcast | Party | Written to the store | Before | |---|---|---| | Taker (htlc) | The secret and the signed funding transaction | Asking the maker to accept the HTLC, and so before broadcasting the funding | | Taker (private) | The adaptor secret `y`, the per-swap multisig key and the signed funding | Sending the proposal to the maker | | Taker (private) | The maker's signature on the time-locked refund | Broadcasting the funding | | Taker (private) | Its pre-signature on the maker's claim | Sending it to the maker | | Taker | A fresh recipient's private key | Anything is locked | | Taker | The signed refund transaction | Broadcasting the refund | | Maker | Each quote, with its per-quote Zcash key in private mode | Returning the quote | | Maker (private) | The one-time EVM signer key and the accepted proposal | Answering the proposal | | Maker | The EVM lock parameters (what a refund needs) | Locking | | Maker | Its ZEC claim transaction | Broadcasting the claim | ## What's stored | Key | Contents | |---|---| | `taker/` | The public `Swap`, its stage and options, the signed funding, the return address, and the secrets: the htlc secret, or the adaptor secret, multisig key, the maker's refund signature and both pre-signatures. Also the fresh recipient's key and the signed refund, if any | | `maker/quote/` | An open quote, and its per-quote Zcash key in private mode. Deleted when the quote is used or expires | | `maker/swap/` | The public `Swap`, its stage, the per-swap Zcash key and one-time signer key (private mode), the proposal, the pre-signatures, the EVM lock parameters and the claim transaction | `FileSwapStore` turns `/` into `~` in file names, so `taker/` is `taker~.json`. The swap id is the hashlock in htlc mode and the quote id in private mode. > **Warning:** Records hold secrets and private keys. Treat the store like a wallet file: restrict access, back it up, and never share it. The public `Swap` objects that `swap()`, `getSwap()` and `pendingSwaps()` return never contain secrets. ## When a swap fails `taker.swap()` resolves when the stablecoins are claimed. If something fails **after** the ZEC was locked, it throws `SwapFailedError`, which carries the swap (`err.swap`) and the code of the underlying error (`err.code`, for example `lock_mismatch` or `timeout`). The swap stays in the store, so you can refund it now or after a restart: ```ts import { SwapFailedError } from "@paralock/sdk"; try { await taker.swap(quote); } catch (err) { if (err instanceof SwapFailedError) { console.log(`swap ${err.swap.id} failed (${err.code}): ${err.message}`); await taker.refund(err.swap.id); // waits for the refund height, then returns the ZEC } else { throw err; // nothing was locked } } ``` If it fails **before** anything was broadcast, `swap()` rethrows the original error, and the record is marked `abandoned`: no funds moved. That includes the maker refusing to commit (for example `quote_expired` or `insufficient_liquidity`), because the taker broadcasts its funding only after the maker accepted it. If the funding broadcast itself fails and the node doesn't report the transaction, the swap is **not** abandoned, since a node may have it anyway: `swap()` throws `SwapFailedError` and the swap stays pending until `resume` settles it. ## After a crash or restart `taker.pendingSwaps()` returns every persisted swap that isn't finished, meaning its ZEC may still be locked. A recovery loop at startup: ```ts for (const swap of await taker.pendingSwaps()) { try { await taker.resume(swap.id); // claims if the maker's lock is there and still safe to claim } catch { await taker.refund(swap.id); // waits for the refund height, then returns the ZEC } } ``` ### Taker stages | Stage | Meaning | Finished? | |---|---|---| | `prepared` | Funding signed, not broadcast; the maker hasn't committed | No | | `reserved` | htlc: the maker accepted the HTLC and reserved its stablecoins; the funding is broadcast next | No | | `proposed` | Private mode: the maker's refund signature is held and the maker reserved its stablecoins; the funding is broadcast next | No | | `funded` | Funding broadcast | No | | `accepted` | The maker has all it needs to lock (htlc: the funding confirmed; private: the pre-signature was sent) | No | | `locked` | The maker's lock was verified | No | | `claimed` | Stablecoins claimed; the secret is public | Yes | | `completed` | The maker claimed the ZEC | Yes | | `refunded` | The ZEC came back | Yes | | `abandoned` | Nothing was locked: the funding was never broadcast, or it expired without being mined | Yes | ### `resume(id, { claim? })` `resume` continues the state machine from the stored stage: - A finished swap is returned as it is. - A swap whose funding already reached the network continues from `funded`, whatever stage it was saved at. - A swap stuck at `prepared` (the maker never committed) is marked `abandoned`, and its funding is **not** broadcast. - A swap stuck at `reserved` or `proposed` (the maker committed, the funding wasn't broadcast) is broadcast late only if all of these hold: the tip is at least 5 blocks below the funding's expiry height, at least `minZcashLockBlocks` of the refund window remain, and the maker still holds the swap (`getSwap`). The maker re-checks its timeout policy on every poll and drops a reservation it can no longer lock safely, so that last check covers the windows. Otherwise the swap is marked `abandoned`. If the taker had already handed the funding to a node (a broadcast that failed ambiguously), it is never abandoned while that funding could still be mined: `resume` throws `conflict` until 2 blocks after the funding's expiry height. - Otherwise it waits for the funding to confirm, verifies the maker's lock, and claims if the lock is still safe to claim. If the funding expires without being mined, the swap is marked `abandoned`. If the claim already landed before the crash, it finds it on-chain instead of claiming twice. `resume(id, { claim: true })` claims a swap that was started with `swap(quote, { claim: false })`, and `resume(id, { relayClaim: false })` submits the claim from your own EVM account after a relayer refused. If the maker's lock never appears, was refunded, or expires too soon, `resume` throws, and you refund. ### `refund(id, { wait? })` `refund` takes the ZEC back from a persisted swap: 1. It checks that the lock is still unspent. If the maker already claimed it, or the funding never confirmed, it throws a `conflict` error. 2. It waits until the chain reaches the refund height, polling every 15 seconds. With `{ wait: false }` it throws `conflict` ("the refund opens at block N") instead of waiting. 3. It builds the refund. In htlc mode it signs with the taker's Zcash key from your configuration; in private mode it completes the refund the maker pre-signed, using the multisig key from the store. 4. It stores the signed refund, broadcasts it (rebroadcasting the stored one if you call `refund` again), and waits for it to confirm. The refund pays the return address recorded when the swap started. `refund` accepts an id or a `Swap`, and works from a fresh process: everything it needs is in the store and your configuration. It also works on a swap marked `abandoned` if its funding reached the chain after all. > **Note:** In htlc mode, keep **both** the store and the Zcash key: the store has the swap, but the refund is signed with the key you configure. In private mode the per-swap keys live in the store. `taker.getSwap(id)` returns the public view of any stored swap, and `taker.freshRecipient(id)` the fresh recipient's key, if one was used. ## From the CLI On the devnet, the CLI keeps the taker store in `taker/` inside its [state directory](https://paralock.xyz/docs/cli#state-directory): `.paralock/taker` in a checkout, else under `$PARALOCK_HOME` or `~/.paralock`. In a checkout the web app shares that store, so these commands work for swaps started from either: ```sh npx paralock swaps # unfinished swaps: id, mode, status, amount, chain, refund height npx paralock resume # resume(id, { claim: true }), print progress, then reshield change npx paralock refund # refund once the refund height is reached, then reshield npx paralock refund --no-shield # refund without reshielding (resume takes --no-shield too) ``` When a CLI swap fails after locking, the CLI refunds it automatically and prints the `paralock refund ` command in case the process is interrupted. The devnet maker keeps its state in `maker/` in the same directory, so restarting `npx paralock maker` resumes its swaps. ## Maker restarts `await maker.start()` loads the store, deletes expired quotes and resumes every unfinished swap: it waits for the taker's funding, locks, watches for the taker's claim, claims the ZEC (rebroadcasting until it confirms) or refunds after the EVM expiry. Locks are idempotent on-chain, so resending one after a crash is safe. The HTTP handler calls `start()` on the first request too. [Run a maker](https://paralock.xyz/docs/run-a-maker#restarts-and-recovery) lists the maker's stages. ## Backups - Back up the store continuously, not once a day: a record written seconds before a crash can be the only copy of a key that claims or refunds funds. - Encrypt backups. They contain secrets and private keys. - Keep the Zcash signing key alongside the store (htlc-mode refunds need it), and the fresh-recipient keys, which control swapped stablecoins. - Restore a store to exactly one process. Two processes driving the same swaps can race each other. - Keep records of finished swaps as long as you need receipts; nothing deletes them automatically. --- # For AI agents Source: https://paralock.xyz/docs/ai-agents Markdown: https://paralock.xyz/docs/ai-agents.md Section: Guides > How coding assistants and autonomous agents learn and use Paralock through the skill, llms.txt, Markdown pages and the MCP server, and the safety rules for moving funds. Paralock is built to be used by agents as well as people. Coding assistants can learn the SDK from a skill, a plain-text index and an MCP server. Autonomous agents that hold ZEC can use the SDK to get exact dollars just in time, for example to pay an API. | You want to | Use | |---|---| | Have a coding assistant integrate Paralock into your project | [The skill](#the-skill) | | Give any model the docs as plain text | [`llms.txt` and Markdown pages](#docs-as-plain-text) | | Let an assistant search the docs and fetch contract addresses on demand | [The MCP server](#the-mcp-server), then [connect it](#connect-the-mcp-server) | | Have an agent work on the Paralock repository itself | [`AGENTS.md`](#working-on-the-repository) | ## The skill The skill teaches a coding agent how to integrate Paralock: the packages and what each is for, a taker and a maker in a few lines, the two modes, the safety rules below, local testing and a troubleshooting table. Install it in your project: ```sh npx skills add bitfalt/paralock ``` It installs `skills/paralock/SKILL.md` from the repository into each agent's skills folder (`.claude/skills` for Claude Code, `.agents/skills` for Codex, Cursor, OpenCode, Gemini CLI, GitHub Copilot, Zed, Cline and Pi), and `-a ` picks the agents. The [skills CLI](https://github.com/vercel-labs/skills#supported-agents) lists every agent and path. Agents that support skills load it when a task matches: paying dollars from ZEC, accepting ZEC for a stablecoin payment, running a maker, or using Zcash HTLCs, 2-of-2 locks or ECDSA adaptor signatures from TypeScript. ## Docs as plain text | URL | What it is | |---|---| | `https://paralock.xyz/llms.txt` | An index of the documentation with a one-line summary per page, following the `llms.txt` convention | | `https://paralock.xyz/llms-full.txt` | Every page in one plain-text file, to paste into a context window | | `https://paralock.xyz/docs/.md` | Any single page as Markdown, for example `https://paralock.xyz/docs/quickstart.md`. The page URL with `Accept: text/markdown` returns the same | Point a model at `llms.txt` first and let it fetch only the pages it needs. The slugs match the docs URLs: `quickstart`, `how-it-works`, `pay`, `sdk`, `contracts`, `roadmap` and so on. In these files, tabbed examples are listed one after another under their labels, and diagrams are written out as numbered steps. ## The MCP server The Paralock MCP server exposes the documentation and the contract deployments as tools, over Streamable HTTP at `https://paralock.xyz/mcp`. It needs no key or sign-in, and every tool is read-only: the server never holds keys, signs or sends transactions. | Tool | What it returns | |---|---| | `list_docs` | The documentation pages, with their slugs, titles, sections and URLs | | `read_doc` | One page as Markdown, by slug | | `search_docs` | The sections that best match a query, with a snippet and a link | | `get_deployments` | The testnet contract deployments: `ParalockHTLC` and `ParalockAdaptorEscrow` addresses, quote tokens, start blocks, explorer and verified-source links, per chain | ## Connect the MCP server Pick your tool. Each tab has the command, the config file entry, or both; they do the same thing. The server is named `paralock` everywhere. **Claude Code**: ```sh claude mcp add --transport http paralock https://paralock.xyz/mcp ``` `.mcp.json`: ```json { "mcpServers": { "paralock": { "type": "http", "url": "https://paralock.xyz/mcp" } } } ``` The command adds it for you in this project. Add `--scope user` for every project, or `--scope project` to write the `.mcp.json` above and share it with your team. **Claude Desktop**: ```text Customize → Connectors → + Add → Add custom connector Name paralock URL https://paralock.xyz/mcp Authentication No sign in ``` The same connector works in Claude Desktop and on claude.ai. On Team and Enterprise plans an Owner adds it first, under Organization settings → Connectors (Add → Custom → Web); members then connect it under Customize → Connectors. The Free plan allows one custom connector. **Codex**: ```sh codex mcp add paralock --url https://paralock.xyz/mcp ``` `~/.codex/config.toml`: ```toml [mcp_servers.paralock] url = "https://paralock.xyz/mcp" ``` The Codex CLI and the IDE extension share this file. A trusted project can keep the same entry in `.codex/config.toml`. **OpenCode** (`opencode.json`): ```json { "$schema": "https://opencode.ai/config.json", "mcp": { "paralock": { "type": "remote", "url": "https://paralock.xyz/mcp", "enabled": true } } } ``` In the project root, or in `~/.config/opencode/opencode.json` for every project. **Cursor** (`.cursor/mcp.json`): ```json { "mcpServers": { "paralock": { "url": "https://paralock.xyz/mcp" } } } ``` In the project, or in `~/.cursor/mcp.json` for every project. Or install it in one click with this [Cursor link](cursor://anysphere.cursor-deeplink/mcp/install?name=paralock&config=eyJ1cmwiOiJodHRwczovL3BhcmFsb2NrLnh5ei9tY3AifQ==). **VS Code** (`.mcp.json`): ```json { "mcpServers": { "paralock": { "type": "http", "url": "https://paralock.xyz/mcp" } } } ``` For GitHub Copilot in VS Code. Put the same entry in `~/.copilot/mcp-config.json` for every workspace. VS Code still reads the older `.vscode/mcp.json`, now deprecated, whose top-level key is `servers` instead of `mcpServers`. **Windsurf** (`~/.config/devin/mcp_config.json`): ```json { "mcpServers": { "paralock": { "serverUrl": "https://paralock.xyz/mcp" } } } ``` Windsurf is now Devin Desktop, and this is the file its Cascade agent reads. For the Devin Local agent and the Devin CLI, run `devin mcp add -s user paralock https://paralock.xyz/mcp` instead. **Gemini CLI**: ```sh gemini mcp add --transport http --scope user paralock https://paralock.xyz/mcp ``` `~/.gemini/settings.json`: ```json { "mcpServers": { "paralock": { "type": "http", "url": "https://paralock.xyz/mcp" } } } ``` Or `.gemini/settings.json` in a project (the command's default scope). **Zed** (`settings.json`): ```json { "context_servers": { "paralock": { "url": "https://paralock.xyz/mcp" } } } ``` Zed 0.214 or newer. Or Settings → AI → MCP Servers → Add Remote Server. **Cline**: ```sh cline mcp add paralock https://paralock.xyz/mcp --transport http --yes ``` `cline_mcp_settings.json`: ```json { "mcpServers": { "paralock": { "type": "streamableHttp", "url": "https://paralock.xyz/mcp", "disabled": false, "autoApprove": [] } } } ``` Keep `"type": "streamableHttp"`: without it, Cline assumes the legacy SSE transport. The Cline CLI keeps this file in `~/.cline/data/settings/`; in the VS Code extension, open it from the MCP Servers view. **Pi**: ```sh pi mcp add paralock --url https://paralock.xyz/mcp ``` `~/.pi/agent/mcp.json`: ```json { "mcpServers": { "paralock": { "url": "https://paralock.xyz/mcp", "description": "Paralock docs and testnet deployments" } } } ``` Pi supports MCP natively over Streamable HTTP (not SSE). Add `-l` to write `.pi/mcp.json` in the project instead, which Pi reads once you trust the project. `pi mcp list` shows whether the server answers. | Tool | Remote MCP over HTTP | Skill with `npx skills add` | |---|---|---| | Claude Code | Yes | Yes | | Claude Desktop, claude.ai | Yes, as a custom connector | No: upload the skill folder as a ZIP under Customize → Skills | | Codex (CLI and IDE) | Yes | Yes | | OpenCode | Yes | Yes | | Cursor | Yes | Yes | | VS Code (GitHub Copilot) | Yes | Yes | | Windsurf (Devin Desktop) | Yes | Yes | | Gemini CLI | Yes | Yes | | Zed | Yes, from 0.214 | Yes | | Cline | Yes | Yes | | Pi | Yes | Yes | > **Tip:** Have the assistant call `get_deployments` instead of copying addresses from memory. Contract addresses and start blocks must come from the deployment records, never from a guess. ### Without remote MCP Every tool above can reach the server. For one that can't (no MCP, or only local stdio servers): - Give it the docs as text: `https://paralock.xyz/llms-full.txt` in one file, or `llms.txt` and the `.md` pages it needs. - Install the skill, which works without any network access once installed. - If it runs local stdio servers only, a bridge such as [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) (`npx mcp-remote https://paralock.xyz/mcp`) can stand in, at your own discretion: it is a third-party package. ## Working on the repository To work **on** Paralock rather than with it, read [`AGENTS.md`](https://github.com/bitfalt/paralock/blob/main/AGENTS.md) at the repository root (`CLAUDE.md` imports it). It is written for Codex, Claude Code, Cursor, Copilot, Gemini and humans, and covers the repository map, the build and test commands, the protocol invariants, the code conventions, recipes (adding an EVM chain, an example, publishing) and known gotchas. The web app has its own `apps/web/AGENTS.md` with notes on its Next.js version. ## Safety rules for agents that move funds An agent that calls `taker.swap()` or runs a maker moves real value on real chains. Paralock is experimental and not audited by a third party, and it is deployed on testnets only: tell the user so before acting, and treat any mainnet use as the user's own risk. These rules come from the skill. Never break them: 1. **Never bypass `assertSafeWindows`** or shorten windows below a policy's `safetyFactor`. The Zcash refund must outlast the EVM lock. 2. **Never reveal the secret, or complete an adaptor signature, before verifying the maker's EVM lock on-chain.** The engines already do this. Don't reimplement the flow by hand. 3. **Use a durable `store` for anything with real value, and keep it backed up.** It holds secrets, per-swap keys and pre-signed refunds. Losing it can mean losing funds. 4. **Never reuse a secret, hashlock or adaptor point.** 5. **Keep keys in environment variables or a KMS** (`account` accepts a viem `Account`). Never commit them, print them or paste them into a prompt. 6. **Take addresses from the network registry** (`knownNetwork(chainId)` from `@paralock/evm`) or the deployment files. Don't hardcode guesses. Mistakes agents commonly make, and how to avoid them: - **Amounts are `bigint` in base units.** ZEC is in zatoshi (`100_000_000n` is 1 ZEC); dollars have 6 decimals (`25_000_000n` is $25). Never pass a float. - **Quotes expire in about 60 seconds.** Quote right before `swap()`; a stale quote fails with `quote_expired`. - **`lock_mismatch` is a refusal, not a bug to work around.** The maker's lock didn't match the agreed terms. Refund with `taker.refund(id)` after the refund height; never override the check. - **`SwapFailedError` means ZEC is locked.** Keep `err.swap.id` and call `taker.refund(err.swap.id)`; it waits for the refund height. - **Swaps take minutes on public networks.** Zcash blocks come about every 75 seconds. Don't treat a slow swap as a failure, and don't start a second swap with the same funds. ## Paying for APIs An agent that holds ZEC can pay an exact dollar amount to any address with [Pay](https://paralock.xyz/docs/pay): `taker.quoteExactOut(amount, chain, mode)` followed by `taker.swap(quote, { recipient })`. Paralock itself doesn't speak x402 or MPP. Use Pay to put exact stablecoins at the address an API asks for. A Zcash payment method for MPP, so agents can pay HTTP 402 APIs straight from shielded ZEC, is on the [roadmap](https://paralock.xyz/docs/roadmap). --- # @paralock/sdk Source: https://paralock.xyz/docs/sdk Markdown: https://paralock.xyz/docs/sdk.md Section: Reference > Reference for the maker and taker engines: factories and their options, methods, core types, stores, the HTTP transport, errors and helpers. `@paralock/sdk` runs both sides of a swap between ZEC and stablecoins on EVM chains. The **taker** sells ZEC: it locks ZEC on Zcash and receives stablecoins, for itself or for a third party (a payment). The **maker** quotes, locks stablecoins on the EVM chain and claims the ZEC. Either both legs settle or both refund. The SDK wires a Zcash backend, the EVM escrow clients and a durable store. It persists every secret before it matters, and it resumes or refunds swaps after a crash. Start with [`createTaker`](#createtaker) or [`createMaker`](#createmaker). Everything else is exported for custom wiring. > **Warning:** Experimental and not audited by a third party. Use testnets and the local devnet only. In both modes the Zcash leg is a transparent output, and in htlc mode the same hashlock appears on both chains. ## Install ```sh npm install @paralock/sdk ``` This page describes version 0.3.0. New in 0.3.0 the maker accepts and reserves before the taker broadcasts its htlc funding (`fundingExpiryHeight`, the `reserved` stage), the maker's public swap view no longer carries adaptor data, and the devnet helpers find the CLI's state directory outside a checkout. A 0.3.0 maker refuses private-mode proposals from older takers, which can still swap in htlc mode. Node.js 20 or newer (the SDK uses `node:crypto` and `node:fs`, so it does not run in a browser). It depends on [`@paralock/zcash`](https://paralock.xyz/docs/zcash), [`@paralock/adaptor`](https://paralock.xyz/docs/adaptor), [`@paralock/evm`](https://paralock.xyz/docs/evm) and `viem`. Units used on this page: | Value | Unit | |---|---| | ZEC amounts | `bigint` zatoshi (1 ZEC = 100,000,000 zat) | | Stablecoin amounts | `bigint` token base units (6 decimals: 25 USDC = `25_000_000n`) | | Zcash windows | blocks | | EVM windows and expiries | seconds (expiries are Unix seconds) | | Timeouts and intervals ending in `Ms` | milliseconds | | Hex values | `` `0x${string}` `` (`Hex`), except Zcash txids: display-order hex without `0x` | ## createTaker ```ts function createTaker(options: CreateTakerOptions): Taker ``` Builds a [`Taker`](#taker) from plain configuration. It throws `ParalockError("invalid_request")` for a bad key, address, URL or chain entry, when no EVM chain is configured, and when `zcash.network` is `"mainnet"` and the store is not durable. ```ts import { type Hex, createTaker } from "@paralock/sdk"; const taker = createTaker({ zcash: { network: "testnet", rpcUrl: "http://127.0.0.1:18232", key: process.env.ZEC_KEY! }, evm: { base: { rpcUrl: "https://sepolia.base.org", chainId: 84532, // Base Sepolia htlc: HTLC, // ParalockHTLC adaptorEscrow: ESCROW, // ParalockAdaptorEscrow (private mode) account: process.env.EVM_KEY as Hex, fromBlock: DEPLOY_BLOCK, // tokens: defaults to the registry's USDC for chain id 84532 }, }, maker: "https://maker.example", store: "./paralock-taker", // a FileSwapStore: secrets and refund data }); const quote = await taker.quoteExactOut(25_000_000n, "base", "adaptor"); // exactly 25 USDC const swap = await taker.swap(quote, { recipient: "0x1111111111111111111111111111111111111111" }); ``` Contract addresses and deployment blocks are listed on [Contracts and deployments](https://paralock.xyz/docs/contracts). ### CreateTakerOptions | Option | Type | Default | Meaning | |---|---|---|---| | `zcash` | `ZcashOptions & { returnAddress?: string }` | required | Zcash backend and signing key. See [Zcash options](#zcash-options). | | `evm` | `Partial>` | required | One entry per chain you accept stablecoins on. At least one. See [Chain options](#chain-options-taker). | | `maker` | `string \| MakerApi` | required | Maker URL (wrapped in an `HttpMakerApi`) or any `MakerApi`, such as an in-process `Maker`. | | `makerHttp` | `HttpMakerApiOptions` | `{}` | Options of the HTTP client when `maker` is a URL. See [HttpMakerApi](#httpmakerapi). | | `store` | `SwapStore \| string` | `MemorySwapStore` | Where secrets, per-swap keys and refund data are persisted. A string is a directory for a `FileSwapStore`. A durable store is required on mainnet. | | `limits` | `Partial` | `DEFAULT_TAKER_LIMITS` | Quote and claim bounds. See [TakerLimits](#takerlimits). | | `timeouts` | `Partial` | `DEFAULT_TAKER_TIMEOUTS` | How long each step may take. See [TakerTimeouts](#takertimeouts). | | `price` | `() => Promise` | none | Your own USD per ZEC price. When set, quotes beyond `limits.maxSlippageBps` are rejected. | | `onUpdate` | `(swap: Swap) => void` | none | Called with the updated swap after every status change. | | `onFreshRecipient` | `(account: { address: Hex; privateKey: Hex }, swap: Swap) => void` | none | Receives the key of each fresh recipient address. That key controls the swapped stablecoins. | | `log` | `(message: string) => void` | none | Diagnostic messages, prefixed `[taker]`. | | `mineZcash` | `(blocks: number) => Promise` | none | Devnets only: mines Zcash blocks while waiting. | ### Zcash options `ZcashOptions` is shared by `createTaker` and `createMaker`. | Field | Type | Default | Meaning | |---|---|---|---| | `network` | `"mainnet" \| "testnet" \| "regtest"` | required | Zcash network. Addresses are checked against it. | | `key` | `KeyPair \| Hex \| string \| Uint8Array` | required | The transparent signing key: a 32-byte secp256k1 private key (hex with or without `0x`, or bytes) or a `KeyPair`. | | `rpcUrl` | `string` | none | Zebra or Zakura JSON-RPC endpoint. Give `rpcUrl` or `node`. | | `rpcAuth` | `{ username: string; password: string }` | none | HTTP basic auth for `rpcUrl`. | | `node` | `ZcashNode` | none | Any backend implementing [`ZcashNode`](https://paralock.xyz/docs/zcash#the-zcashnode-interface), for example a [`LightwalletdClient`](https://paralock.xyz/docs/lightwalletd). Overrides `rpcUrl`. | | `returnAddress` | `string` | the key's own address | Taker only. Transparent address that receives funding change and refunds. | | `payoutAddress` | `string` | the key's own address | Maker only. Transparent address that receives claimed ZEC. | The taker funds swaps from the key's P2PKH address (`taker.zcashAddress`). Keep the key: htlc-mode refunds are signed with it. ### Chain options (taker) The key is an `EvmChain` name (`tempo`, `base`, `ethereum`, `arbitrum`, `robinhood`, `hyperevm`). The `chainId` selects the network, so `base` with `chainId: 84532` is Base Sepolia. These fields come from `EvmChainOptions` and are shared with the maker: | Field | Type | Default | Meaning | |---|---|---|---| | `rpcUrl` | `string` | required | HTTP(S) JSON-RPC endpoint. | | `chainId` | `number` | required | Expected chain id. Before the first swap the taker checks that the RPC really serves it. | | `htlc` | `Hex` | required | `ParalockHTLC` address (htlc mode). | | `adaptorEscrow` | `Hex` | none | `ParalockAdaptorEscrow` address. Omit it to disable private (`adaptor`) mode on this chain. | | `account` | `Account \| Hex` | required | Signer: a viem `Account` (for example from a KMS) or a `0x` 32-byte private key. | | `fromBlock` | `bigint \| number` | `0` | Block the escrows were deployed in. Event scans start here. Set it on public chains. | | `feeToken` | `Hex` | none | Tempo only: the TIP-20 token that pays transaction fees. | | `tempo` | `boolean` | by chain id | Force or disable Tempo's transaction format. | | `rpcTimeoutMs` | `number` | `10_000` | Per-request RPC timeout, in milliseconds. | | `rpcRetryCount` | `number` | `3` | RPC retries on network errors, 5xx and 429 responses. | The taker adds `TakerEvmChainOptions`: | Field | Type | Default | Meaning | |---|---|---|---| | `tokens` | `readonly Hex[]` | registry tokens for `chainId` | Stablecoins you accept here. Quotes paying any other token are rejected. Defaults to the tokens [`KNOWN_NETWORKS`](https://paralock.xyz/docs/evm#known-networks) lists for `chainId`. Required where the registry lists none (local chains, Robinhood Chain Testnet). | | `tokenDecimals` | `number` | `6` | Decimals of those tokens, for the slippage check. | | `relayer` | `Account \| Hex` | none | A second account that submits claims (with `privacy.relayClaim`), so a fresh recipient needs no gas. It can't redirect funds. | | `minConfirmations` | `number` | `limits.minEvmConfirmations` | Confirmations of the maker's lock before the taker reveals anything. | | `minClaimWindowSeconds` | `number` | `limits.minClaimWindowSeconds` | Seconds the maker's lock must still have left when the taker claims. Raise it on slow chains (minutes on Ethereum L1). | ### TakerLimits `DEFAULT_TAKER_LIMITS` holds the defaults. `TakerLimits` extends `QuoteLimits`. | Field | Type | Default | Meaning | |---|---|---|---| | `maxZcashLockBlocks` | `number` | `288` | Longest Zcash refund window accepted, in blocks. Caps how long a silent maker can strand your ZEC. | | `minZcashLockBlocks` | `number` | `10` | Shortest Zcash refund window accepted, in blocks. | | `minEvmLockSeconds` | `number` | `30` | Shortest EVM lock accepted, in seconds. | | `maxEvmLockSeconds` | `number` | `86_400` | Longest EVM lock accepted, in seconds. | | `maxZecAmountZat` | `bigint` | `100_000_000_000n` (1,000 ZEC) | Largest swap accepted, in zatoshi. | | `expiryMarginSeconds` | `number` | `5` | Reject quotes that expire within this many seconds. | | `maxSlippageBps` | `number` | `200` (2%) | Maximum shortfall against your `price`, in basis points. Exact-in quotes: how few dollars you get. Exact-out quotes: how much extra ZEC you pay. Only checked when `price` is set. | | `minClaimWindowSeconds` | `number` | `30` | Seconds the EVM lock must still have left when the taker verifies it and when it claims. A claim mined after the expiry reverts but still publishes the secret, so leave room. | | `minEvmConfirmations` | `number` | `1` | Confirmations of the maker's EVM lock before revealing (reorg protection). | ### TakerTimeouts `DEFAULT_TAKER_TIMEOUTS` holds the defaults. All values are milliseconds. | Field | Default | Meaning | |---|---|---| | `fundingConfirmationMs` | `1_800_000` (30 min) | Wait for the funding transaction to confirm. Also used for the refund transaction. | | `makerLockMs` | `1_800_000` (30 min) | Wait for the maker's EVM lock. The wait also ends when the Zcash tip reaches the refund height. | | `followMakerMs` | `60_000` (60 s) | After claiming, wait this long for the maker to report its ZEC claim. Informational: the swap resolves either way. | | `pollIntervalMs` | `2_000` (2 s) | Delay between polls. | ## createMaker ```ts function createMaker(options: CreateMakerOptions): Maker ``` Builds a [`Maker`](#maker). Call `await maker.start()` to resume unfinished swaps, then serve it with [`makerHandler`](#makerhandler). It throws `ParalockError("invalid_request")` for bad configuration (including a `spreadBps` outside `[0, 10000)` or `limits.minZecAmountZat` not above `limits.zcashFeeZat`), and `ParalockError("unsafe_timeouts")` for an incoherent `policy`. ```ts import { createServer } from "node:http"; import { type Hex, createMaker, makerHandler, zecUsdPrice } from "@paralock/sdk"; const maker = createMaker({ zcash: { network: "testnet", rpcUrl: "http://127.0.0.1:18232", key: process.env.ZEC_KEY!, payoutAddress: PAYOUT }, evm: { base: { rpcUrl: "https://sepolia.base.org", chainId: 84532, htlc: HTLC, adaptorEscrow: ESCROW, account: process.env.EVM_KEY as Hex, fromBlock: DEPLOY_BLOCK, token: { address: USDC, symbol: "USDC", decimals: 6 }, }, }, price: zecUsdPrice(), // no fixed fallback: an outage stops quoting spreadBps: 50, limits: { maxZecAmountZat: 500_000_000n, maxConcurrentSwaps: 20 }, store: "./paralock-maker", }); await maker.start(); // resumes every unfinished swap const handle = makerHandler(maker, { cors: { origin: ["https://app.example"] } }); createServer(async (req, res) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); // also cap the size at your proxy const headers = new Headers(); for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string") headers.set(k, v); const body = chunks.length ? Buffer.concat(chunks) : undefined; const response = await handle(new Request(`http://maker${req.url}`, { method: req.method, headers, body })); res.writeHead(response.status, Object.fromEntries(response.headers)).end(await response.text()); }).listen(7420); ``` See [Run a maker](https://paralock.xyz/docs/run-a-maker) for operations. ### CreateMakerOptions | Option | Type | Default | Meaning | |---|---|---|---| | `zcash` | `ZcashOptions & { payoutAddress?: string }` | required | Zcash backend, the htlc claim key and where claimed ZEC goes. See [Zcash options](#zcash-options). | | `evm` | `Partial>` | required | One entry per chain the maker serves. At least one. See [Chain options](#chain-options-maker). | | `price` | `() => Promise` | required | USD per ZEC, for example [`zecUsdPrice()`](#zecusdprice). | | `spreadBps` | `number` | `50` | Spread below `price`, in basis points. Must be in `[0, 10000)`. | | `policy` | `TimeoutPolicy` | `MAINNET_POLICY` | Lock windows and confirmations. See [Timeout policy](#timeout-policy). | | `limits` | `Partial` | `DEFAULT_MAKER_LIMITS` | Per-swap and capacity limits. See [MakerLimits](#makerlimits). | | `store` | `SwapStore \| string` | `MemorySwapStore` | Quotes, swaps and per-swap keys. A string is a `FileSwapStore` directory. A durable store is required on mainnet. | | `pollIntervalMs` | `number` | a fifth of `policy.zcashBlockSeconds`, clamped to 1 to 15 s | How often settlement loops poll the chains, in milliseconds. | | `afterClaim` | `(swap: Swap) => Promise` | none | Runs after the maker's ZEC claim confirms, for example to shield it. Errors are logged, never fatal. | | `log` | `(message: string) => void` | none | Diagnostic messages, prefixed `[maker]`. | ### Chain options (maker) `MakerEvmChainOptions` takes every `EvmChainOptions` field from the [taker table](#chain-options-taker) (`rpcUrl`, `chainId`, `htlc`, `adaptorEscrow`, `account`, `fromBlock`, `feeToken`, `tempo`, `rpcTimeoutMs`, `rpcRetryCount`) plus: | Field | Type | Default | Meaning | |---|---|---|---| | `token` | `{ address: Hex; symbol: string; decimals?: number }` | required | The stablecoin quoted on this chain. `decimals` defaults to `6`. | ### MakerLimits `DEFAULT_MAKER_LIMITS` holds the defaults. | Field | Type | Default | Meaning | |---|---|---|---| | `minZecAmountZat` | `bigint` | `1_000_000n` (0.01 ZEC) | Smallest swap, in zatoshi. Must exceed `zcashFeeZat`. | | `maxZecAmountZat` | `bigint` | `1_000_000_000n` (10 ZEC) | Largest swap, in zatoshi. | | `maxConcurrentSwaps` | `number` | `10` | Swaps in flight (proposed, funding, locking, locked or settling) at once. | | `maxOpenQuotes` | `number` | `1_000` | Unexpired quotes held at once. Each adaptor quote carries a fresh key. | | `quoteTtlSeconds` | `number` | `60` | How long a quote is honored, in seconds. A taker commits before broadcasting its funding, so this only covers a few seconds of work. | | `maxFundingExpiryBlocks` | `number` | `45` | Furthest a taker's `fundingExpiryHeight` may be above the tip. Bounds how long an unfunded reservation holds inventory. The SDK's taker uses 40 (`FUNDING_EXPIRY_DELTA`); the other 5 absorb a maker node that lags the taker's. An htlc accept without `fundingExpiryHeight` gets the deadline `tip + maxFundingExpiryBlocks`, which only drops a funding the maker has never seen. | | `minEvmLockSecondsLeft` | `number` | `30` | Seconds of EVM time the lock must still have left when the maker sends it; with less, the maker abandons the swap instead of locking (the SDK's taker won't claim with less than its `minClaimWindowSeconds`, 30 by default). | | `zcashFeeZat` | `bigint` | `10_000n` | ZEC the maker spends on its own claim transaction (ZIP 317 fee of a one-input, one-output spend), in zatoshi. Priced into every quote. | | `checkInventory` | `boolean` | `true` | Check the stablecoin balance, minus amounts reserved by other swaps, before quoting and before locking. | ## Taker ```ts class Taker { constructor(cfg: TakerConfig); } ``` The taker side of a ZEC to stablecoin swap. It holds the secret (htlc mode) or the adaptor secret (adaptor mode) and reveals it only by claiming on the EVM chain, after verifying the maker's lock on-chain. Every secret and key is written to the store before any transaction is broadcast, so `resume` and `refund` work after a crash. | Member | Signature | Behavior | |---|---|---| | `zcashAddress` | `get zcashAddress(): string` | The transparent address this taker funds swaps from. | | `quote` | `quote(zecAmountZat: bigint, chain: EvmChain = "tempo", mode: SwapMode = "htlc"): Promise` | Exact-in quote: sell `zecAmountZat`. Rejects a quote with different terms than requested, then validates it. | | `quoteExactOut` | `quoteExactOut(usdAmount: bigint, chain: EvmChain = "tempo", mode: SwapMode = "htlc"): Promise` | Exact-out quote: deliver exactly `usdAmount` token base units. The ZEC amount rounds up. Validated. | | `validateQuote` | `validateQuote(quote: Quote): Promise` | Runs [`validateQuote`](#validation) against this taker's chains and limits, checks once per process that each RPC serves the configured chain id, and checks slippage when `price` is set. Throws `quote_rejected`. | | `swap` | `swap(quote: Quote, opts: SwapOptions = {}): Promise` | Runs the whole swap. See [Running a swap](#running-a-swap). | | `lockOnly` | `lockOnly(quote: Quote, payTo?: { recipient?: Hex; label?: string }): Promise` | Funds the Zcash lock and stops once the funding confirms, for example to demo a refund. In htlc mode the maker is never contacted. In adaptor mode the proposal step still runs, because the maker's refund signature is required before funding. | | `resume` | `resume(id: string, options: { claim?: boolean; relayClaim?: boolean } = {}): Promise` | Continues a persisted swap. See [Resuming a swap](#resuming-a-swap). | | `refund` | `refund(swapOrId: Swap \| string, options: { wait?: boolean } = {}): Promise` | Refunds the Zcash lock. See [Refunding a swap](#refunding-a-swap). | | `getSwap` | `getSwap(id: string): Promise` | The public view of a persisted swap. | | `pendingSwaps` | `pendingSwaps(): Promise` | Persisted swaps that are not finished: their ZEC may still be locked. | | `freshRecipient` | `freshRecipient(id: string): Promise<{ address: Hex; privateKey: Hex } \| undefined>` | The fresh recipient account of a swap, if one was used. Its key controls the stablecoins. | ### Running a swap `swap(quote, opts)` validates the quote, persists the secret, keys and signed funding, has the maker commit to the funding (htlc: `accept`, which consumes the quote and reserves the maker's stablecoins; adaptor: the maker signs the refund), and only then broadcasts it. Right before asking the maker, it re-checks the quote's expiry (with 5 s of allowance for clock skew) and fails without broadcasting if it has passed. It then waits for the maker's EVM lock and verifies it: recipient, token, amount, signer and release pre-signature (adaptor mode), `minConfirmations` and at least `minClaimWindowSeconds` left. Only then does it claim, which reveals the secret. It resolves once the stablecoins are claimed, after waiting up to `timeouts.followMakerMs` for the maker's ZEC claim (status `completed` if seen, `evm_claimed` otherwise). Errors: - Before anything is broadcast, errors are thrown as they are, usually a `ParalockError`: `quote_rejected` (validation), `invalid_request` (a bad option), `conflict` (the quote was already used), `unsafe_timeouts` (adaptor mode: a network upgrade activates before the refund height), `quote_expired` (the quote expired before the maker committed), or the maker's own error when it refuses to commit (`busy`, `insufficient_liquidity`, …). The swap is marked abandoned. - Once the funding may have reached the network, it throws [`SwapFailedError`](#errors). The swap stays in the store and `taker.refund(err.swap.id)` returns the ZEC once the refund height is reached. A funding broadcast that fails without the node reporting the transaction also throws `SwapFailedError`: a node may have it anyway, so the swap stays pending until `resume` settles it. ```ts import { SwapFailedError } from "@paralock/sdk"; try { await taker.swap(quote, { privacy: { freshRecipient: true, relayClaim: true } }); } catch (err) { if (!(err instanceof SwapFailedError)) throw err; // nothing was locked console.log(`failed after locking (${err.code}); refunding`); await taker.refund(err.swap.id); // waits for the refund height } ``` ### SwapOptions | Field | Type | Default | Meaning | |---|---|---|---| | `claim` | `boolean` | `true` | `false` stops after verifying the maker's lock, without claiming (a demo where both sides refund). The swap resolves with status `evm_locked`. | | `privacy` | `PrivacyOptions` | `{}` | Level-1 privacy options. See [PrivacyOptions](#privacyoptions). | | `recipient` | `Hex` | the taker's EVM account | Pay someone else (the Pay flow): the stablecoins go to this address. | | `label` | `string` | none | Label for the payment, for example a merchant name. Stored in `swap.payment.label`. | ### PrivacyOptions These options don't hide the link between the two legs of one swap (adaptor mode does that). They keep a swap from linking to the rest of your activity. See [Privacy](https://paralock.xyz/docs/privacy). | Field | Type | Default | Meaning | |---|---|---|---| | `freshRecipient` | `boolean` | `false` | Pay the stablecoins to a new address created for this swap. Needs a durable store or an `onFreshRecipient` handler, or `swap` throws `invalid_request`. Ignored when `recipient` is set. | | `relayClaim` | `boolean` | `false` | Let the chain's `relayer` account submit the claim, so the recipient needs no gas. The relayer can't redirect the funds. | | `standardAmountsOnly` | `boolean` | `false` | Refuse amounts other than `STANDARD_AMOUNTS_ZAT` (0.1, 0.5, 1 and 5 ZEC). | | `jitterMs` | `number` | `0` | Wait a uniformly random 0 to `jitterMs` milliseconds before claiming. | ### Resuming a swap `resume(id, { claim, relayClaim })` continues a persisted swap after a restart. It claims if the maker's lock is there and still safe to claim, and follows the maker's ZEC claim. `claim` overrides the option the swap was started with, so `resume(id, { claim: true })` claims a swap started with `claim: false`. `relayClaim: false` submits the claim from your own EVM account, for example after the relayer refused (the SDK doesn't fall back by itself); the recipient stays the one in the lock. A finished swap is returned as it is. A swap interrupted before its funding reached the network is resumed conservatively: - `prepared` (the maker never committed): marked abandoned (status `failed`, nothing was locked); the funding is not broadcast. - `reserved` or `proposed` (the maker committed): the funding is broadcast late only if the tip is at least `FUNDING_BROADCAST_MARGIN_BLOCKS` (5) below its expiry height, at least `limits.minZcashLockBlocks` of the refund window remain, and the maker still holds the swap. The maker re-checks its timeout policy on every poll and drops a reservation it can no longer lock safely, so that check covers the windows. Otherwise the swap is marked abandoned. - A funding that was already handed to a node is never given up on while it could still be mined: `resume` throws `conflict` until the tip is more than `FUNDING_EXPIRY_MARGIN_BLOCKS` (2) past its expiry height, then marks the swap abandoned. ### Refunding a swap `refund(swapOrId, { wait })` refunds the Zcash lock once the chain tip reaches the swap's refund height. By default it waits for that height (polling every `max(pollIntervalMs, 15 s)`, or mining with `mineZcash` on a devnet). With `wait: false` it throws `ParalockError("conflict")` with the message "the refund opens at block N" instead. It works after a restart: everything it needs is in the store. It resolves once the refund transaction confirms. It throws `not_found` when the swap isn't in this taker's store, and `conflict` when the lock was already spent (the maker claimed it) or the funding never confirmed. ```ts for (const swap of await taker.pendingSwaps()) { try { await taker.resume(swap.id); // claims if the maker's lock is there and still safe to claim } catch { await taker.refund(swap.id); // waits for the refund height, then returns the ZEC } } ``` See [Persistence and recovery](https://paralock.xyz/docs/recovery). ### Swap ids | Mode | `swap.id` | |---|---| | `htlc` | The hashlock: `0x` plus 64 hex characters. | | `adaptor` | The quote id (a UUID). Nothing on-chain links the legs, so no on-chain value is used. | ### TakerStage The taker persists an internal stage per swap (`TakerSwapRecord.stage`): | Stage | Meaning | |---|---| | `prepared` | Funding signed, not broadcast. The maker hasn't committed. | | `reserved` | htlc mode: the maker accepted the HTLC and reserved its stablecoins. The funding is broadcast next. | | `proposed` | Adaptor mode: the maker's refund signature is held and the maker reserved its stablecoins. The funding is broadcast next. | | `funded` | Funding broadcast. | | `accepted` | The maker has all it needs to lock: htlc, the funding confirmed; adaptor, the pre-signature was sent. | | `locked` | Maker's lock verified. | | `claimed` | Stablecoins claimed: the secret is public (htlc) or the signature is published (adaptor). | | `completed` | The maker claimed the ZEC. | | `refunded` | ZEC refunded. | | `abandoned` | Nothing was locked: the funding was never broadcast, or it expired without being mined. | ### TakerConfig `new Taker(config)` takes already-built clients instead of plain options. Use it to plug in your own EVM client library or a custody API. | Field | Type | Meaning | |---|---|---| | `network` | `Network` | Zcash network. | | `zcash` | `ZcashNode` | Zcash backend. | | `zcashKey` | `KeyPair` | Funding key. | | `returnAddress` | `string` | Change and refunds. Default: the key's address. | | `chains` | `Partial>` | Per chain: `htlc: EvmClient`, `adaptor?: AdaptorEvmClient`, `relayer?: { htlc; adaptor? }`, `tokens?`, `tokenDecimals?`, `minConfirmations?`, `minClaimWindowSeconds?`. | | `maker` | `MakerApi` | The maker. | | `store`, `limits`, `timeouts`, `price`, `onUpdate`, `onFreshRecipient`, `log`, `mineZcash` | | As in `CreateTakerOptions`. | | `minClaimWindowSeconds` | `number` | Deprecated: use `limits.minClaimWindowSeconds`. | `MakerApi` is the interface a taker uses to talk to a maker: `quote`, `quoteExactOut`, `accept`, `getSwap`, `proposeAdaptor`, `adaptorPreSignature`, with the same signatures as on [`Maker`](#maker). `Maker` and `HttpMakerApi` both implement it. ## Maker ```ts class Maker implements MakerApi { constructor(cfg: MakerConfig); } ``` The market-maker side of ZEC to stablecoin swaps on every configured EVM chain, in both modes. It never locks stablecoins before the taker's ZEC is confirmed in a lock it verified byte for byte, with the exact value, while the remaining Zcash window still outlasts the EVM lock by `policy.safetyFactor`. Every quote, swap and per-swap key is persisted before it is used. | Member | Signature | Behavior | |---|---|---| | `start` | `start(): Promise` | Loads persisted quotes and swaps and resumes settlement of every unfinished swap. Idempotent. The request handlers call it implicitly. | | `stop` | `stop(): Promise` | Stops the settlement loops and waits for them to wind down. They resume on the next `start()`. | | `quote` | `quote(zecAmountZat: bigint, chain: EvmChain = "tempo", mode: SwapMode = "htlc"): Promise` | Exact-in quote. Pays `zatToUsdUnits(zecAmountZat - zcashFeeZat, rate, decimals)`, rounded down. | | `quoteExactOut` | `quoteExactOut(usdAmount: bigint, chain: EvmChain = "tempo", mode: SwapMode = "htlc"): Promise` | Exact-out quote. Asks `usdUnitsToZat(usdAmount, rate, decimals) + zcashFeeZat`, rounded up. | | `accept` | `accept(request: AcceptRequest): Promise` | htlc mode: checks the taker's HTLC against the quote (template byte for byte, claim key, capacity, `fundingExpiryHeight`, window, refund height at most twice `policy.zcashLockBlocks` ahead, inventory), and only then consumes the quote, reserves the stablecoins and starts watching the funding, which a 0.3 taker broadcasts only after this returns. A refused accept leaves the quote usable. Idempotent for an identical request. | | `proposeAdaptor` | `proposeAdaptor(proposal: AdaptorProposal): Promise` | Adaptor mode, step 2: checks the proposal (which must carry `fundingExpiryHeight`) and signs the taker's time-locked refund before the taker funds anything; consumes the quote and reserves the stablecoins. Idempotent for an identical proposal. | | `adaptorPreSignature` | `adaptorPreSignature(swapId: string, request: AdaptorPreSignatureRequest): Promise` | Adaptor mode, steps 3 and 4: verifies the taker's pre-signature on the maker's claim, then in the background waits for the funding and locks stablecoins. Returns the taker's view of the swap, with `adaptorPoint` and `adaptor` (the escrow pre-signature once locked). Idempotent: the taker resends its stored pre-signature to poll for the lock; an invalid one is refused. | | `getSwap` | `getSwap(id: string): Swap \| undefined` | Public view of a swap (synchronous): without `adaptorPoint` and `adaptor`. | | `listSwaps` | `listSwaps(): Swap[]` | Public views of every swap this maker knows (as `getSwap`). | | `getStage` | `getStage(id: string): MakerStage \| undefined` | Internal stage of a swap, for operators. | | `zcashPubkey` | `get zcashPubkey(): Hex` | The maker's long-term Zcash public key (htlc claims). Adaptor quotes use a fresh key each. | | `chains` | `get chains(): EvmChain[]` | Chains this maker serves. | | `effectiveLimits` | `get effectiveLimits(): Readonly` | Limits after defaults are applied. | The quoted `rate` is `price × (1 − spreadBps / 10,000)`, in USD per ZEC. Quote errors: `invalid_request` (unknown chain, bad mode, chain not served, private mode not configured), `busy` (too many open quotes or swaps in flight), `limit_exceeded` (outside `minZecAmountZat` to `maxZecAmountZat`, or a zero dollar amount), `insufficient_liquidity` (not enough stablecoin after reservations) and `unavailable` (price feed down). ### MakerStage | Stage | Meaning | |---|---| | `proposed` | Adaptor mode: waiting for the taker's pre-signature. | | `funding` | The stablecoins are reserved; waiting for the taker's Zcash funding to be broadcast and confirm with `policy.minZcashConfirmations`. Abandoned once the funding is still unmined more than `FUNDING_EXPIRY_MARGIN_BLOCKS` (2) past the declared `fundingExpiryHeight` (without one: past `tip + maxFundingExpiryBlocks` at the accept, if the maker never saw the funding), or once the window is too short to lock. | | `locking` | Lock parameters persisted; sending or confirming the EVM lock. | | `locked` | Waiting for the taker's claim or the EVM expiry. | | `claiming` | Claim built and persisted; broadcasting until it confirms. | | `refunding` | Refunding the EVM lock after its expiry. | | `completed` | Terminal: the maker claimed the ZEC. | | `refunded` | Terminal: the EVM lock was refunded. | | `abandoned` | Terminal: nothing was locked (no pre-signature, late funding, wrong value, unsafe window, no inventory). | | `lost` | Terminal: the taker refunded the ZEC before the maker's claim confirmed. Logged as an `ALERT`. | ### Protocol messages | Type | Fields | |---|---| | `AcceptRequest` | `quoteId: string`, `redeemScript: Hex`, `fundingTxid: string`, `fundingVout: number`, `takerEvmAddress: Hex`, `fundingExpiryHeight?: number` (the funding's last minable block; optional, absent from 0.1 and 0.2 takers) | | `AdaptorProposal` | `quoteId`, `takerZcashPubkey: Hex`, `adaptorPoint: Hex`, `fundingTxid`, `fundingVout`, `amountZat: string` (decimal zatoshi, must equal the quote), `refundHeight: number`, `refundAddress: string`, `takerEvmRecipient: Hex`, `fundingExpiryHeight?: number` (as in `AcceptRequest`; optional in the type, but a 0.3 maker refuses proposals without it, since older private-mode takers can't complete against it) | | `AdaptorProposalAccepted` | `swapId`, `makerRefundSignature: Hex` (DER plus sighash byte), `claimTo: string`, `branchId: number`, `signer: Hex`, `signerPubkey: Hex` | | `AdaptorPreSignatureRequest` | `takerPreSignature: string` (162-byte encoded pre-signature, see [@paralock/adaptor](https://paralock.xyz/docs/adaptor)) | `adaptorSpends(args)` builds the two spends of the 2-of-2 lock (time-locked refund and claim) exactly as both parties must, so their sighashes match. See [How it works](https://paralock.xyz/docs/how-it-works) for the protocol. ### MakerConfig `new Maker(config)` takes built clients: `network`, `zcash: ZcashNode`, `zcashKey: KeyPair`, `zcashPayoutAddress: string`, `chains: Partial>`, `price`, `spreadBps: number` (required here), `policy: TimeoutPolicy` (required here), and optional `limits`, `store`, `pollIntervalMs`, `afterClaim`, `log`. `quoteTtlSeconds` is deprecated: use `limits.quoteTtlSeconds`. `ChainClients` is `{ chain, chainId, token, tokenSymbol, tokenDecimals, htlc: EvmClient, adaptor?: AdaptorEvmClient }`. ## Core types ### Quote A maker's offer. The taker validates it before acting on it. | Field | Type | Meaning | |---|---|---| | `id` | `string` | Quote id (UUID). One swap per quote. | | `direction` | `"ZEC_TO_USD"` | The only direction today: the taker sells ZEC. | | `mode` | `SwapMode` | `"htlc"` or `"adaptor"`. | | `chain` | `EvmChain` | Chain the stablecoins are paid on. | | `chainId` | `number?` | Chain id on the maker's side. The taker rejects a mismatch. Absent from 0.1 makers. | | `zecAmountZat` | `bigint` | ZEC the taker sends, in zatoshi. | | `usdAmount` | `bigint` | Stablecoin the taker receives, in token base units (6 decimals). | | `token` | `Hex` | Stablecoin address. | | `tokenSymbol` | `string` | For display. | | `rate` | `number` | USD per ZEC used for this quote, after the spread. | | `makerZcashPubkey` | `Hex` | Compressed secp256k1 key the maker uses on Zcash: the HTLC claimer, or its half of the 2-of-2. | | `makerEvmAddress` | `Hex` | The maker's EVM account. | | `zcashLockBlocks` | `number` | Blocks until the taker may refund on Zcash. | | `evmLockSeconds` | `number` | Seconds until the maker may refund on the EVM chain. | | `expiresAt` | `number` | Unix seconds after which the quote is no longer honored. | | `exactOut` | `boolean?` | Set for exact-dollar quotes: `usdAmount` is fixed and the ZEC amount rounds up. | ### Swap The public view of a swap. It never contains secrets or private keys; those live only in the `SwapStore`. | Field | Type | Meaning | |---|---|---| | `id` | `string` | See [Swap ids](#swap-ids). | | `quote` | `Quote` | The quote it was made from. | | `mode` | `SwapMode` | `"htlc"` or `"adaptor"`. | | `hashlock` | `Hex?` | htlc mode: sha256 of the secret, visible on both chains. | | `adaptorPoint` | `Hex?` | Adaptor mode: the adaptor point, exchanged off-chain only. In the taker's own view and the maker's answer to the taker's pre-signature; never in the maker's public view. | | `status` | `SwapStatus` | Current status. | | `zcash` | `ZcashLeg` | The Zcash side. | | `evm` | `EvmLeg` | The EVM side. | | `adaptor` | `AdaptorSwapData?` | Adaptor mode: protocol data only the two parties hold (`escrowId`, `signer`, `signerPubkey`, `salt`, `evmPreSignature`). Never in the maker's public view. Don't publish it: with `adaptorPoint` and the claim on-chain, `evmPreSignature` reveals `y`. `escrowId`, `signer` and `salt` are visible in the escrow's `Locked` event. Any `Swap` lists both legs' transactions, so share swap views only with whoever may link them. | | `payment` | `{ recipient: Hex; label?: string }?` | Set when the stablecoins pay someone other than the taker. | | `events` | `SwapEvent[]` | Timeline. | ### SwapStatus | Status | Meaning | |---|---| | `quoted` | Created; nothing on-chain yet. | | `zcash_locked` | The taker funded the Zcash lock. | | `evm_locked` | The maker locked stablecoins on the EVM chain. | | `evm_claimed` | The taker claimed on the EVM chain: the secret is revealed. | | `completed` | The maker claimed the ZEC. | | `refunded_zcash` | The taker refunded the ZEC. | | `refunded_evm` | The maker refunded the stablecoins. | | `failed` | Something failed. The last event's `detail` says what. | ### ZcashLeg | Field | Type | Meaning | |---|---|---| | `htlcAddress` | `string` | P2SH address holding the ZEC: an HTLC (htlc mode) or a 2-of-2 multisig (adaptor mode). | | `redeemScript` | `Hex` | Its redeem script. | | `refundHeight` | `number` | Block height from which the taker can refund. | | `amountZat` | `bigint` | Locked ZEC, in zatoshi. | | `fundingTxid`, `fundingVout` | `string?`, `number?` | The lock output. | | `claimTxid`, `refundTxid` | `string?` | The maker's claim or the taker's refund. | ### EvmLeg | Field | Type | Meaning | |---|---|---| | `chain`, `chainId` | `EvmChain`, `number` | Where the stablecoins are locked. | | `contract` | `Hex` | The escrow contract. | | `token` | `Hex` | The stablecoin. | | `amount` | `bigint` | Token base units. | | `recipient` | `Hex` | Fixed at lock time: the taker, a fresh address or a payee. | | `expiry` | `number?` | Unix seconds from which the maker can refund. | | `lockTx`, `claimTx`, `refundTx` | `Hex?` | Transaction hashes. | ### SwapEvent | Field | Type | Meaning | |---|---|---| | `status` | `SwapStatus` | Status reached. | | `chain` | `Chain` | `"zcash"` or an `EvmChain`. | | `at` | `number` | Unix milliseconds. | | `txid` | `string?` | Related transaction. | | `detail` | `string?` | Human-readable description. | ### SwapMode and EvmChain ```ts type SwapMode = "htlc" | "adaptor"; type EvmChain = "tempo" | "base" | "ethereum" | "arbitrum" | "robinhood" | "hyperevm"; type Chain = "zcash" | EvmChain; ``` `EVM_CHAIN_NAMES: Record` maps them to display names (`"Robinhood Chain"`, `"HyperEVM"`, …). `createTaker` and `createMaker` accept only these six names. Each one works with any chain id and RPC where the Paralock escrows are deployed (for example its testnet); another chain needs a new `EvmChain` name. ## Timeout policy The maker's EVM lock must expire well before the taker's Zcash refund height, so whoever learns the secret always has time to use it on the other chain. The rule: Zcash blocks left × `zcashBlockSeconds` must be at least `safetyFactor` × EVM lock seconds. | Field | Type | Meaning | |---|---|---| | `zcashLockBlocks` | `number` | Blocks between funding and the taker's Zcash refund height. | | `evmLockSeconds` | `number` | Seconds the maker's EVM lock stays claimable. | | `zcashBlockSeconds` | `number` | Expected Zcash block interval in seconds, used to compare the two clocks. | | `minZcashConfirmations` | `number` | Confirmations the maker waits for on the Zcash funding (and on its own claim). | | `safetyFactor` | `number` | The remaining Zcash window must be at least this many times longer than the EVM lock. | | Field | `MAINNET_POLICY` | `DEVNET_POLICY` | |---|---|---| | `zcashLockBlocks` | `144` (about 3 h at 75 s blocks) | `40` (about 2 min) | | `evmLockSeconds` | `3600` (1 h) | `45` | | `zcashBlockSeconds` | `75` | `3` | | `minZcashConfirmations` | `2` | `1` | | `safetyFactor` | `2` | `2` | `MAINNET_POLICY` is the default of `createMaker` on every network (Zcash testnet also has 75 s blocks). `DEVNET_POLICY` uses short windows so refunds can be demoed on the local devnet. `assertValidPolicy(policy)` and `assertSafeWindows(policy, blocksUntilZcashRefund, evmLockSeconds)` throw `ParalockError("unsafe_timeouts")`. The maker checks the window when it accepts a lock and again right before it locks stablecoins. Two constants govern the funding's expiry height (`FUNDING_EXPIRY_DELTA`, 40 blocks after it is built): `FUNDING_BROADCAST_MARGIN_BLOCKS` (5), the taker broadcasts a funding only while the tip is at least this far below its expiry; and `FUNDING_EXPIRY_MARGIN_BLOCKS` (2), once the tip is more than this far past it and the funding is unmined, both sides treat it as dead (the maker drops its reservation, the taker abandons the swap). ## Stores ### SwapStore ```ts interface SwapStore { readonly durable: boolean; get>(key: string): Promise; put(key: string, record: StoredRecord): Promise; delete(key: string): Promise; list>(prefix: string): Promise<{ key: string; record: T }[]>; } ``` | Member | Meaning | |---|---| | `durable` | `false` for stores that lose data on restart. The engines then refuse risky options (fresh recipients without a handler) and the factories refuse it on mainnet. | | `get` | The record under `key`, or `undefined`. | | `put` | Creates or replaces the record. Must resolve only once the record survives a crash or power loss. Concurrent writes to one key: the last one wins. | | `delete` | Removes `key` (no-op if absent). | | `list` | Every record whose key starts with `prefix`, sorted by key. | Keys are short ASCII paths: `[A-Za-z0-9._:/-]`, at most 200 characters, no `..`, not starting with `/` (`assertStoreKey` checks this). The taker writes `taker/`; the maker writes `maker/quote/` and `maker/swap/`. > **Warning:** Records hold swap secrets, adaptor secrets, per-swap private keys and refund signatures. Treat the store like a wallet file: restrict access, back it up, never share it. ### MemorySwapStore and FileSwapStore | Class | `durable` | Behavior | |---|---|---| | `new MemorySwapStore()` | `false` | In-process map. Everything is lost on exit. For tests and throwaway sessions. | | `new FileSwapStore(dir: string)` | `true` | One JSON file per record in `dir` (created with mode 0700; files 0600). Each `put` writes a temporary file, fsyncs it, renames it over the old one and fsyncs the directory, so a record is never torn. Writes to one key are serialized in-process. Use one directory per process. | ### Custom stores `encodeRecord(record)` and `decodeRecord(json)` serialize records to JSON with bigints tagged as `{ "$bigint": "123" }`, so a database-backed store round-trips them exactly. ```ts import { type StoredRecord, type SwapStore, assertStoreKey, decodeRecord, encodeRecord } from "@paralock/sdk"; /** Your database client. */ interface Kv { get(key: string): Promise; set(key: string, value: string): Promise; delete(key: string): Promise; scan(prefix: string): Promise<[string, string][]>; } /** A store over any key-value database with durable writes. */ class KvSwapStore implements SwapStore { readonly durable = true; constructor(private readonly db: Kv) {} async get>(key: string): Promise { const json = await this.db.get(key); return json === undefined ? undefined : decodeRecord(json); } async put(key: string, record: StoredRecord): Promise { assertStoreKey(key); await this.db.set(key, encodeRecord(record)); // must be durable when it resolves } async delete(key: string): Promise { await this.db.delete(key); } async list>(prefix: string): Promise<{ key: string; record: T }[]> { const rows = await this.db.scan(prefix); // sorted by key return rows.map(([key, json]) => ({ key, record: decodeRecord(json) })); } } ``` ## HTTP transport Bigints travel as decimal strings. `toJson(value)` encodes them; `reviveQuote` and `reviveSwap` restore the bigint fields of JSON received from a maker. ### makerHandler ```ts function makerHandler(maker: Maker, options?: MakerHandlerOptions): (req: Request) => Promise ``` A web-standard `Request` to `Response` handler, so it runs in Node (through a small adapter, as in the [createMaker example](#createmaker)), Bun, Deno, Next.js route handlers and Cloudflare Workers. Put it behind TLS and a rate limiter. | Option | Type | Default | Meaning | |---|---|---|---| | `cors` | `{ origin: string \| readonly string[] }` | none (same origin only) | `"*"` or a list of allowed origins. | | `maxBodyBytes` | `number` | `16_384` (16 KiB) | Largest request body. Larger bodies get `413` with code `invalid_request`. | | `exposeSwapList` | `boolean` | `false` | Serve `GET /swaps`. Off by default because it lets anyone link swaps. | | `onError` | `(err: unknown, req: Request) => void` | `console.error` | Receives unexpected errors. Their details are never sent to clients. | Routes: | Method and path | Body | Response | Mode | |---|---|---|---| | `GET /quote?zat=&chain=&mode=` | | `Quote` (exact-in) | both | | `GET /quote?usd=&chain=&mode=` | | `Quote` (exact-out; `usd` wins over `zat`) | both | | `POST /swaps` | `AcceptRequest` | `Swap` | htlc | | `POST /adaptor/swaps` | `AdaptorProposal` | `AdaptorProposalAccepted` | adaptor | | `POST /adaptor/swaps/:id/presignature` | `AdaptorPreSignatureRequest` | `Swap`, the taker's view with the adaptor data | adaptor | | `GET /swaps/:id` | | `Swap` public view (no adaptor data), or `404` | both | | `GET /swaps` | | `Swap[]` public views, only with `exposeSwapList` | both | | `GET /health` | | `{ ok: true, chains: EvmChain[], zcashPubkey: Hex }` | | | `OPTIONS *` | | `204` with CORS headers | | `chain` defaults to `tempo` and `mode` to `htlc`. Amounts must be 1 to 30 decimal digits. Swap ids in paths are a UUID or a `0x` hashlock. Responses carry `cache-control: no-store`. Errors are JSON `{ "error": string, "code": ParalockErrorCode }` with the code's HTTP status (see [Errors](#errors)). Unexpected errors become a generic `500` with code `internal`, or `503` with code `unavailable` when the maker's Zcash node fails. ### HttpMakerApi ```ts class HttpMakerApi implements MakerApi { constructor(url: string, options?: HttpMakerApiOptions); readonly url: string; health(): Promise<{ ok: boolean; chains: EvmChain[]; zcashPubkey?: string }>; } ``` Talks to a `makerHandler` over HTTP and validates every response (`parseQuote`) before use. `getSwap` returns `undefined` on `404`. Failed requests throw `ParalockError` with the maker's code (or `unavailable` when the code is unknown or the maker is unreachable) and a message prefixed `maker: `. | Option | Type | Default | Meaning | |---|---|---|---| | `timeoutMs` | `number` | `30_000` | Per-request timeout, in milliseconds. | | `retries` | `number` | `2` | Retries on network errors, timeouts and 5xx or 429 responses, with backoff from 500 ms to 5 s. Every maker endpoint is idempotent. | | `headers` | `Record` | none | Extra headers, for example an API key. | ## Errors ```ts class ParalockError extends Error { readonly code: ParalockErrorCode; readonly status: number; // HTTP status of the code } ``` Expected failures throw `ParalockError` with a stable `code`. Messages are safe to show to a counterparty: they never include keys, secrets, RPC URLs or stack traces. | Code | HTTP | Meaning | |---|---|---| | `invalid_request` | 400 | Malformed input or configuration. | | `quote_rejected` | 422 | The taker refused a maker's quote (bad key, token, chain id, window, price…). | | `quote_expired` | 410 | The quote is unknown, used or past its expiry. | | `not_found` | 404 | No such swap. | | `conflict` | 409 | The request conflicts with the swap's state (a different proposal for the same quote, a quote already used, a refund that isn't open yet). | | `limit_exceeded` | 422 | Outside the maker's per-swap limits. | | `busy` | 429 | Too many open quotes or concurrent swaps. | | `insufficient_liquidity` | 503 | The maker lacks the stablecoin inventory. | | `unsafe_timeouts` | 422 | The Zcash window doesn't outlast the EVM lock by the safety factor, or a network upgrade falls inside it. | | `lock_mismatch` | 422 | An on-chain lock doesn't match the agreed terms. | | `unavailable` | 503 | A dependency (node, price feed, maker) is unreachable. | | `timeout` | 504 | Waited too long for something on-chain. | | `internal` | 500 | Anything else. Its message is never sent to clients. | | Export | Meaning | |---|---| | `SwapFailedError` | Extends `ParalockError`. Thrown by `swap`, `lockOnly` and `resume` when a swap fails after the ZEC was locked. `err.swap` is the persisted swap; `err.code` is the cause's code, or `internal`. | | `isParalockError(err)` | True for a `ParalockError`, also across duplicated module copies (checked by shape). | | `errorMessage(err)` | The message of any thrown value. | ```ts import { isParalockError } from "@paralock/sdk"; try { await taker.quote(10_000_000n, "base", "adaptor"); } catch (err) { if (isParalockError(err) && err.code === "busy") { // the maker is at capacity: retry later } else throw err; } ``` ## Helpers ### zecUsdPrice ```ts function zecUsdPrice(opts?: PriceFeedOptions): () => Promise ``` USD per ZEC from CoinGecko (or `url`), cached, with bounded staleness. Pass the result as `price`. | Option | Type | Default | Meaning | |---|---|---|---| | `fallback` | `number` | none | Price used when the feed is down and nothing recent is cached. Devnets and demos only: a fixed price lets anyone trade against you at a stale rate. Without it, an outage throws `unavailable`. | | `cacheMs` | `number` | `60_000` | Reuse a fetched price for this long. | | `maxStaleMs` | `number` | `300_000` | When the feed fails, keep serving the last good price for at most this long. | | `timeoutMs` | `number` | `3_000` | Request timeout. | | `url` | `string` | CoinGecko simple price | Endpoint returning `{ zcash: { usd } }`. | `zatToUsdUnits(zat, usdPerZec, decimals)` converts zatoshi to token base units, rounding down. `usdUnitsToZat(usdUnits, usdPerZec, decimals)` converts back, rounding up so a payee always gets the full amount. Both use the price truncated to 6 decimal places. ### Retry and polling | Export | Signature | Meaning | |---|---|---| | `retry` | `retry(fn: (attempt: number) => Promise, options?: RetryOptions): Promise` | Retries failures with exponential backoff. Use only for idempotent operations. | | `pollUntil` | `pollUntil(check: () => Promise, options: PollOptions): Promise` | Calls `check` until it returns something other than `undefined`. Errors from `check` are treated as transient and retried with backoff (up to 30 s). Throws `ParalockError("timeout")` on timeout or give-up. | | `sleep` | `sleep(ms: number, signal?: AbortSignal): Promise` | Rejects with the signal's reason if aborted. | | `backoffDelay` | `backoffDelay(attempt: number, minMs: number, maxMs: number): number` | Equal-jitter backoff: between half and all of `min × 2^attempt`, capped at `max`. | `RetryOptions`: `retries` (default `3`, extra attempts after the first), `minDelayMs` (`250`), `maxDelayMs` (`10_000`), `signal`, `shouldRetry(err, attempt)` (return `false` to fail at once), `onRetry(err, attempt, delayMs)`. `PollOptions`: `what` (used in the timeout message, required), `intervalMs` (required), `timeoutMs` (default: never), `giveUp()` (stop as soon as it returns true), `signal`, `onError(err)`, `onIdle()` (runs after every unsuccessful check; devnets mine a block there). ```ts import { pollUntil } from "@paralock/sdk"; const confirmed = await pollUntil( async () => ((await node.getRawTransaction(txid)).confirmations ?? 0) > 0 || undefined, { what: `transaction ${txid}`, intervalMs: 5_000, timeoutMs: 600_000 }, ); ``` ### Wiring and keys | Export | Signature | Meaning | |---|---|---| | `connectEvmChain` | `connectEvmChain(chain: EvmChain, options: EvmChainOptions, account?: Account \| Hex): { htlc: EvmClient; adaptor?: AdaptorEvmClient }` | Connects one chain's escrows and returns the engine clients. `account` defaults to `options.account`. | | `zcashKeyFrom` | `zcashKeyFrom(key: KeyPair \| Hex \| string \| Uint8Array): KeyPair` | A Zcash `KeyPair` from a private key or an existing pair. | | `zcashNodeFrom` | `zcashNodeFrom(options: { node?; rpcUrl?; rpcAuth? }): ZcashNode` | `options.node`, or a `ZcashRpc` for `rpcUrl`. | | `evmAddressOf` | `evmAddressOf(publicKey: Uint8Array \| string): Hex` | Ethereum address of a secp256k1 public key (compressed or uncompressed). | | `freshEvmAccount` | `freshEvmAccount(): { address: Hex; privateKey: Hex }` | A new EVM account for one swap's stablecoins. | | `newSecret` | `newSecret(): { secret: Hex; hashlock: Hex }` | A 32-byte swap secret and its sha256 hashlock. | | `hashlockOf` | `hashlockOf(secret: Hex): Hex` | sha256 of a 32-byte secret. | | `toHex`, `fromHex` | | Bytes to `0x` hex and back. | ### Privacy and amounts | Export | Meaning | |---|---| | `STANDARD_AMOUNTS_ZAT` | `[10_000_000n, 50_000_000n, 100_000_000n, 500_000_000n]`: 0.1, 0.5, 1 and 5 ZEC, in zatoshi. | | `isStandardAmount(zat)` | True for one of them. | | `jitter(maxMs = 0)` | Waits a uniformly random 0 to `maxMs` milliseconds. | | `MAX_ZAT` | 21 million ZEC in zatoshi. | ### Validation Everything that crosses a trust boundary is validated with these. Failures throw `ParalockError` (`quote_rejected` for `validateQuote`, `invalid_request` for the parsers). | Export | Meaning | |---|---| | `validateQuote(quote, ctx: QuoteContext)` | Checks a quote before committing: configured chain and chain id, private mode available, accepted token, valid maker key and address, positive amounts within `maxZecAmountZat`, windows within limits, not expiring within `expiryMarginSeconds`, and slippage when `ctx.price` is set. `QuoteContext` is `{ limits, chains, price?, now? }`. | | `DEFAULT_QUOTE_LIMITS` | The quote fields of `DEFAULT_TAKER_LIMITS`. | | `parseQuote(body)` | Parses a quote from untrusted JSON (shape only). | | `parseAcceptRequest(body)`, `parseAdaptorProposal(body, network)`, `parsePreSignatureRequest(body)` | Validate maker request bodies. | | `parseAmount(value, what, bounds?)`, `parseInteger(value, what, bounds?)` | Strict integer parsing (no fractions, signs or exponents). | | `isHex(value, bytes?)`, `isEvmAddress(value)`, `isEvmChain(value)`, `isSwapMode(value)`, `isQuoteId(value)`, `assertEvmAddress`, `assertPubkey` | Type guards. `isEvmAddress` rejects the zero address. | ### Zcash backend helpers | Export | Meaning | |---|---| | `isUnspent(node, address, txid, vout)` | Uses `getTxOut` (sees mempool spends) when the backend has it, else the address's confirmed UTXOs. | | `assertNoUpgradeBefore(node, height, log?)` | Throws `unsafe_timeouts` if a network upgrade activates at or before `height`: pre-signed spends commit to today's consensus branch id. Backends without `upgradeBefore` skip the check (logged). | ### Engine interfaces `EvmClient` (htlc mode) and `AdaptorEvmClient` (adaptor mode) are what the engines need from an EVM chain: `lock`, `claim`, `refund`, `getLock`, `getLockedSwap`, `outcome`, `now`, `blockNumber`, `rpcChainId`, `tokenBalance`, plus `idOf` and `claimDigest` for the adaptor escrow. `evmClientFrom(chain, htlc)` and `adaptorClientFrom(chain, escrow)` implement them over [@paralock/evm](https://paralock.xyz/docs/evm). Implement them yourself to use another EVM library or a custody API. The deprecated `waitForClaimPreimage` and `waitForClaimSignature` remain; poll `outcome` instead. ## Devnet helpers Built on the same factories, for the local devnet that [`paralock devnet up`](https://paralock.xyz/docs/cli) describes in `devnet.json`, in the CLI's [state directory](https://paralock.xyz/docs/cli#state-directory): | Export | Meaning | |---|---| | `devnetTaker(cfg, opts?)` | A `DevnetTaker`: the taker (ths account 2 on Zcash, anvil dev account 1, dev account 2 relaying), its HTTP maker client, `prepareFunds(amountZat, { fromShielded })` and `reshield()`. | | `devnetMaker(cfg, opts?)` | The devnet maker (ths account 5, anvil dev account 0) with `DEVNET_POLICY`. It shields claimed ZEC again. | | `DevnetSwapRunner` | Runs devnet swaps as background jobs for a UI backend: `quote`, `quoteExactOut`, `start`, `get`, `refund`. | | `loadDevnetFile(start?)`, `devnetFilePath(start?)` | Find and read `devnet.json` in the state directory as seen from `start` (default: the working directory). Throw if there is none. | | `paralockStateDir(options?)` | The state directory: `/.paralock` inside a Paralock checkout, else `$PARALOCK_HOME`, else `~/.paralock`. `options` is `{ cwd?, env? }`. Since 0.3.0. | | `findParalockCheckout(start?)` | The root of the checkout containing `start` (a directory with both `pnpm-workspace.yaml` and `contracts/src/ParalockHTLC.sol`), or `undefined`. Since 0.3.0. | | `devnetStorePath(role, start?)` | `taker/` or `maker/` next to `devnet.json`. | | `saveRecipient(entry, start?)` | Appends a fresh recipient key to `recipients.jsonl` next to `devnet.json`. | | `devnetChainOptions(net, account)`, `DEVNET_TAKER_LIMITS` | Chain options of a devnet chain; taker limits for the devnet's short windows (`minClaimWindowSeconds: 15`). | | `ThsClient`, `mnemonicFromThsLog` | Client for the local ths (Zcash regtest) dashboard API. | > **Note:** The devnet helpers use anvil's public development keys and a fixed fallback price. Never point them at a real network. --- # @paralock/zcash Source: https://paralock.xyz/docs/zcash Markdown: https://paralock.xyz/docs/zcash.md Section: Reference > Reference for the browser-safe Zcash package: keys and addresses, HTLCs, 2-of-2 multisig locks, v5 transactions, ZIP 244 signature hashes, ZIP 317 fees and the node interface. `@paralock/zcash` builds the Zcash side of a Paralock swap in pure TypeScript: sha256 HTLCs, 2-of-2 multisig locks with pre-signed time-locked refunds, v5 transactions with ZIP 244 signature hashes (checked against the official test vectors), ZIP 317 fees, and a Zebra or Zakura JSON-RPC client. It is browser-safe: no Node built-ins. Its only dependencies are `@noble/hashes`, `@noble/curves` and `@scure/base`. > **Warning:** Experimental and not audited by a third party. Use testnets and regtest only. The locks are transparent: they are visible on-chain. ## Install ```sh npm install @paralock/zcash ``` This page describes version 0.3.0. New in 0.3.0 the transaction builders require `branchId` and `network` (no default branch id), and parsing is strict: canonical CompactSize, only the six v5 sighash types, curve-checked HTLC keys, and a preimage check in `buildHtlcClaim` before it signs. Conventions: - Amounts are `bigint` zatoshi (1 ZEC = 100,000,000 zat). - Txids are display-order hex without `0x`. - Functions that take `Uint8Array | string` accept bytes or hex, with or without `0x`. Returned hex (pubkeys, hashlocks in `Htlc.params`) is lowercase without `0x`. - `Network` is `"mainnet" | "testnet" | "regtest"`. Regtest shares testnet's address prefixes. - Heights and lock times are block heights, never timestamps. ## Keys and addresses | Export | Signature | Meaning | |---|---|---| | `KeyPair` | `{ privateKey: Uint8Array; publicKey: Uint8Array }` | 32-byte secret scalar and 33-byte compressed public key. | | `randomKeyPair` | `randomKeyPair(): KeyPair` | A fresh key pair from a CSPRNG. | | `keyPairFromPrivate` | `keyPairFromPrivate(privateKey: Uint8Array \| string): KeyPair` | The pair of a 32-byte private key. Throws if the scalar is out of range. | | `isValidPublicKey` | `isValidPublicKey(publicKey: Uint8Array \| string): boolean` | True for a 33-byte compressed point on the curve. | | `assertValidPublicKey` | `assertValidPublicKey(publicKey, what = "public key"): void` | Throws unless `isValidPublicKey`. | | `keyAddress` | `keyAddress(key: KeyPair, network: Network): string` | The key's P2PKH address. | | `keyScriptPubKey` | `keyScriptPubKey(key: KeyPair): Uint8Array` | The key's P2PKH scriptPubKey. | | `signDigest` | `signDigest(digest: Uint8Array, privateKey: Uint8Array, hashType: number): Uint8Array` | Low-S, strict-DER ECDSA over a 32-byte digest, with the sighash type byte appended. RFC 6979 deterministic nonces. | | `p2pkhAddress` | `p2pkhAddress(pubkey: Uint8Array, network: Network): string` | P2PKH address of a compressed public key. | | `p2shAddress` | `p2shAddress(redeemScript: Uint8Array, network: Network): string` | P2SH address of a redeem script. | | `encodeP2pkh`, `encodeP2sh` | `(hash: Uint8Array, network: Network) => string` | Base58check encoding of a 20-byte hash. | | `decodeTransparentAddress` | `decodeTransparentAddress(address: string): TransparentAddress` | `{ kind: "p2pkh" \| "p2sh"; hash; network }`. Testnet and regtest addresses report `network: "testnet"`. Throws on a bad checksum, length or prefix. | | `isTransparentAddress` | `isTransparentAddress(address: unknown, network?: Network): boolean` | Valid transparent address, for `network` when given. | | `scriptPubKeyForAddress` | `scriptPubKeyForAddress(address: string, network?: Network): Uint8Array` | The scriptPubKey paying `address`. With `network`, a mainnet address can't slip into a testnet transaction (or the reverse). | | Network | P2PKH prefix | P2SH prefix | |---|---|---| | `mainnet` | `t1…` | `t3…` | | `testnet`, `regtest` | `tm…` | `t2…` | ## HTLC ### The script The HTLC is a P2SH output. Its redeem script puts the claim branch first, with a sha256 hashlock and a 32-byte size check: ```zscript OP_IF # claim branch OP_SIZE 32 OP_EQUALVERIFY # a 32-byte secret OP_SHA256 OP_EQUALVERIFY # whose sha256 is the hashlock OP_ELSE # refund branch, from refundHeight OP_CHECKLOCKTIMEVERIFY OP_DROP OP_ENDIF OP_CHECKSIG # signed by the key picked above ``` The two ways to spend it (scriptSigs): ```zscript OP_1 # claim: works before and after the timeout OP_0 # refund: only after refundHeight ``` A refund sets `lock_time = refundHeight` and a non-final input sequence, so it can be mined once the tip reaches `refundHeight` (in block `refundHeight + 1` or later). The same `hashlock` (sha256 of the secret) locks the EVM side, see [`ParalockHTLC`](https://paralock.xyz/docs/contracts). ### Creating and parsing | Export | Signature | Meaning | |---|---|---| | `HtlcParams` | `{ hashlock; claimPubkey; refundPubkey: Uint8Array \| string; refundHeight: number }` | `hashlock` is 32 bytes; both keys are compressed and must differ; `refundHeight` is an absolute block height. | | `Htlc` | `{ params; redeemScript; scriptPubKey; address }` | `params` holds lowercase hex (`hashlock`, `claimPubkey`, `refundPubkey`) and `refundHeight`. | | `createHtlc` | `createHtlc(params: HtlcParams, network: Network): Htlc` | Builds the HTLC. Both keys must be valid curve points. | | `htlcFromRedeemScript` | `htlcFromRedeemScript(redeemScript: Uint8Array \| string, network: Network): Htlc` | Parses and validates a redeem script against the template, byte for byte. This is how a maker checks a taker's lock. | | `parseHtlcRedeemScript` | `parseHtlcRedeemScript(script): { hashlock; claimPubkey; refundPubkey: string; refundHeight: number }` | The parameters of a redeem script. Throws `"not a Paralock HTLC script"` unless it rebuilds to the same bytes. | | `htlcRedeemScript` | `htlcRedeemScript(p: HtlcParams): Uint8Array` | The raw redeem script. | | `extractPreimage` | `extractPreimage(scriptSig: Uint8Array \| string, hashlock: Uint8Array \| string): Uint8Array \| undefined` | The 32-byte secret, if `scriptSig` is a claim of an HTLC with this hashlock. | | `claimScriptSig`, `refundScriptSig` | | The two scriptSigs, size-checked. | | `PREIMAGE_SIZE` | `32` | The secret is exactly 32 bytes (enforced by `OP_SIZE`). | ### Building transactions Every builder returns a `SignedTx`: | Field | Type | Meaning | |---|---|---| | `tx` | `TransparentTx` | The signed transaction. | | `hex` | `string` | Raw hex for `sendrawtransaction`. | | `txid` | `string` | Display-order txid. Final before signing: v5 txids (ZIP 244) don't commit to signatures. | | `fee` | `bigint` | Fee paid, in zatoshi. | They take a `Utxo` (`{ txid: string; vout: number; value: bigint; scriptPubKey: Uint8Array | string }`) and the shared `TxOptions`: | Option | Type | Default | Meaning | |---|---|---|---| | `branchId` | `number` | required | Consensus branch id of the next block. Read it from the node (`getNextBranchId`). There is no default: signatures commit to it, and a chain on another upgrade (e.g. a testnet on NU7) uses another id. | | `expiryHeight` | `number` | `0` (never expires) | Last block the transaction may be mined in. Nodes reject transactions that expire within 3 blocks of the tip. | | `fee` | `bigint` | ZIP 317 | Override the fee, in zatoshi. Must be at least 0 and below the value spent. | | `network` | `Network` | required | Every address is checked against it. | | Builder | Arguments (plus `TxOptions`) | Behavior | |---|---|---| | `buildHtlcFunding` | `{ htlc, amount, utxos, key, changeScriptPubKey? }` | Funds the HTLC as output 0 from P2PKH UTXOs owned by `key`. Change, when any, is output 1. | | `buildHtlcClaim` | `{ htlc, utxo, key, preimage, to }` | Claims with the secret. `key` must be the claim key, and `sha256(preimage)` must equal the hashlock (checked before signing). Pays `utxo.value` minus the fee to `to`. | | `buildHtlcRefund` | `{ htlc, utxo, key, to }` | Refunds after the timeout. `key` must be the refund key. | | `buildP2pkhSpend` | `{ utxos, key, outputs: { address?; scriptPubKey?; value }[], changeScriptPubKey? }` | Spends **every** given UTXO into `outputs`. Change goes to `changeScriptPubKey` (default: the key's address); change below `MIN_CHANGE` goes to the fee. | Builders throw on a missing or malformed `branchId` or `network`, insufficient funds, a UTXO the key doesn't own, a duplicate UTXO, a UTXO value outside `(0, MAX_MONEY]`, an output below `DUST_LIMIT`, a negative fee override or one not below the value spent, or an amount that doesn't cover the fee. > **Note:** Paralock sets `expiryHeight` only on funding transactions (`tip + FUNDING_EXPIRY_DELTA`, 40 blocks), so a stuck funding can't confirm hours later. Claims and refunds keep `0`: they are often signed long before they are broadcast and must stay valid until mined. ## End-to-end HTLC example The taker locks 0.1 ZEC for the maker. The maker claims with the secret, or the taker refunds after 144 blocks. Anyone can read the secret from the claim. ```ts import { FUNDING_EXPIRY_DELTA, ZcashRpc, buildHtlcClaim, buildHtlcFunding, buildHtlcRefund, createHtlc, extractPreimage, keyAddress, keyPairFromPrivate, } from "@paralock/zcash"; const network = "testnet"; const rpc = new ZcashRpc("http://127.0.0.1:18232", { timeoutMs: 15_000, retries: 3 }); const taker = keyPairFromPrivate(process.env.TAKER_KEY!); // funds the lock; can refund it const maker = keyPairFromPrivate(process.env.MAKER_KEY!); // claims it with the secret // 1. A 32-byte secret. Its sha256 is the hashlock. const secret = crypto.getRandomValues(new Uint8Array(32)); const hashlock = new Uint8Array(await crypto.subtle.digest("SHA-256", secret)); // 2. The HTLC: the maker claims with the secret, the taker refunds from block tip + 144. const tip = await rpc.getBlockCount(); const branchId = await rpc.getNextBranchId(); // always sign with the node's next branch id const htlc = createHtlc( { hashlock, claimPubkey: maker.publicKey, refundPubkey: taker.publicKey, refundHeight: tip + 144 }, network, ); // 3. Fund it from the taker's UTXOs. The funding expires if it isn't mined within 40 blocks. const amount = 10_000_000n; // 0.1 ZEC const funding = buildHtlcFunding({ htlc, amount, utxos: await rpc.getAddressUtxos([keyAddress(taker, network)]), // all of them are spent key: taker, branchId, network, expiryHeight: tip + FUNDING_EXPIRY_DELTA, }); await rpc.sendRawTransaction(funding.hex); const utxo = { txid: funding.txid, vout: 0, value: amount, scriptPubKey: htlc.scriptPubKey }; // 4a. The maker claims with the secret. The fee (10,000 zat) comes out of the HTLC. const claim = buildHtlcClaim({ htlc, utxo, key: maker, preimage: secret, to: keyAddress(maker, network), branchId, network }); await rpc.sendRawTransaction(claim.hex); // 4b. Or, once the tip reaches refundHeight, the taker refunds. const refund = buildHtlcRefund({ htlc, utxo, key: taker, to: keyAddress(taker, network), branchId, network }); // 5. Anyone can read the secret from the confirmed claim. const spend = await rpc.findSpend(htlc.address, funding.txid, 0); const revealed = spend && extractPreimage(spend.vin[0]!.scriptSig!.hex, htlc.params.hashlock); ``` ## 2-of-2 multisig Private (adaptor) mode locks ZEC in a plain 2-of-2 multisig with BIP 67 sorted keys. On-chain it looks like any multisig: no hashlock, no timelock. The refund path is a pre-signed transaction with a `lock_time`. ```zscript OP_2 OP_2 OP_CHECKMULTISIG # redeem script, keys sorted OP_0 # any spend: both signatures, in key order ``` | Export | Signature | Meaning | |---|---|---| | `Multisig2of2` | `{ pubkeys: [string, string]; redeemScript; scriptPubKey; address }` | `pubkeys` are sorted lowercase hex, in redeem-script order. | | `createMultisig2of2` | `createMultisig2of2(pubkeyA, pubkeyB, network): Multisig2of2` | Sorts the keys. Both must be valid and different. | | `multisigFromRedeemScript` | `multisigFromRedeemScript(redeemScript, network): Multisig2of2` | Parses and validates against the sorted template, byte for byte. Throws on unsorted keys. | | `MultisigSpend` | `{ multisig; tx; sighash; fee; prevValue }` | An unsigned spend and the ZIP 244 `SIGHASH_ALL` digest both keys sign. | | `buildMultisigSpend` | `buildMultisigSpend({ multisig, utxo, to, lockTime? } & TxOptions): MultisigSpend` | Spends the output to one address, minus the fee. With `lockTime` (a block height) it becomes a refund that can't be mined before that height. | | `signMultisigSpend` | `signMultisigSpend(spend, key: KeyPair): Uint8Array` | One key's signature: DER plus the `SIGHASH_ALL` byte. | | `verifyMultisigSignature` | `verifyMultisigSignature(spend, pubkey, signature): boolean` | Checks a counterparty's signature (low-S, `SIGHASH_ALL`), for example the maker's refund signature. False unless `pubkey` is one of the 2-of-2's two keys. | | `finalizeMultisigSpend` | `finalizeMultisigSpend(spend, signatures: Record): SignedTx` | Assembles the scriptSig. `signatures` is keyed by compressed pubkey hex (lowercase, no `0x`). Both signatures are always verified first. | | `multisigSignaturesFromScriptSig` | `multisigSignaturesFromScriptSig(scriptSig): [Uint8Array, Uint8Array]` | The two signatures of a confirmed spend, in redeem-script key order. | A signature can come from anywhere, for example one completed from an [adaptor pre-signature](https://paralock.xyz/docs/adaptor) with `der(sig)` plus the sighash byte. ```ts import { bytesToHex, buildMultisigSpend, createMultisig2of2, finalizeMultisigSpend, signMultisigSpend, verifyMultisigSignature, } from "@paralock/zcash"; const multisig = createMultisig2of2(alice.publicKey, bob.publicKey, "testnet"); const utxo = { txid: fundingTxid, vout: 0, value: 10_000_000n, scriptPubKey: multisig.scriptPubKey }; // Alice's time-locked refund, signed by Bob BEFORE Alice funds the multisig. const refund = buildMultisigSpend({ multisig, utxo, to: aliceAddress, lockTime: refundHeight, branchId, network: "testnet" }); const bobSig = signMultisigSpend(refund, bob); if (!verifyMultisigSignature(refund, bob.publicKey, bobSig)) throw new Error("bad refund signature: don't fund"); // After refundHeight, Alice completes and broadcasts it. const signed = finalizeMultisigSpend(refund, { [bytesToHex(alice.publicKey)]: signMultisigSpend(refund, alice), [bytesToHex(bob.publicKey)]: bobSig, }); ``` This is safe because the funding txid is final before anyone signs it: v5 txids don't commit to signatures. ## Transactions Paralock builds transparent-only v5 transactions (ZIP 225). | Export | Signature | Meaning | |---|---|---| | `TransparentTx` | `{ branchId; lockTime; expiryHeight; inputs: TxIn[]; outputs: TxOut[] }` | A transparent-only v5 transaction. | | `TxIn` | `{ prevTxid: string; vout: number; scriptSig: Uint8Array; sequence: number }` | `prevTxid` is display-order hex. | | `TxOut` | `{ value: bigint; scriptPubKey: Uint8Array }` | `value` in zatoshi. | | `PrevOut` | `{ value: bigint; scriptPubKey: Uint8Array }` | The output an input spends, needed for signature hashes. | | `serializeTx` | `serializeTx(tx: TransparentTx): Uint8Array` | v5 serialization with empty Sapling and Orchard bundles. | | `parseTx` | `parseTx(data: Uint8Array \| string): TransparentTx & { shieldedRaw: Uint8Array }` | Parses the header and transparent bundle of any v5 transaction. Shielded bundles are returned undecoded in `shieldedRaw`. Throws for other versions. | | `txid` | `txid(tx: TransparentTx, shielded?: ShieldedDigests): string` | ZIP 244 txid, display order. `shielded` defaults to the empty-bundle digests. | | `transparentTxid` | `transparentTxid(hex: string): string \| undefined` | The txid of a raw transparent-only v5 transaction, or `undefined` if it has shielded parts or doesn't parse. | | `serializeOutpoint`, `serializeTxOut`, `headerBytes` | | Serialization pieces. | ## Signature hashes (ZIP 244) ```ts function transparentSighash( tx: TransparentTx, index: number, prevouts: PrevOut[], hashType: number = SIGHASH_ALL, shielded?: ShieldedDigests, ): Uint8Array ``` The ZIP 244 signature digest for transparent input `index`. `prevouts` lists the value and scriptPubKey of every spent output, in input order. For a P2SH input the scriptPubKey is the P2SH script, not the redeem script. All six sighash types are supported and checked against the official vectors; Paralock uses `SIGHASH_ALL` everywhere. | Constant | Value | |---|---| | `SIGHASH_ALL` | `0x01` | | `SIGHASH_NONE` | `0x02` | | `SIGHASH_SINGLE` | `0x03` | | `SIGHASH_ANYONECANPAY` | `0x80` (modifier) | The digest building blocks are exported too: `blake2b256(personalization, data)`, `headerDigest`, `prevoutsDigest`, `sequenceDigest`, `outputsDigest`, `transparentTxidDigest`, `emptySaplingDigest`, `emptyOrchardDigest`, `txidPersonalization(branchId)` and the `ShieldedDigests` type. > **Warning:** A pre-signed spend commits to the consensus branch id. It becomes invalid if a network upgrade activates before it is mined. Check with `ZcashNode.upgradeBefore(height)`. ## Fees (ZIP 317) ```ts function zip317Fee(tx: Pick): bigint ``` The ZIP 317 conventional fee of a transparent-only transaction, in zatoshi: ```text 5000 × max(2, max(ceil(inputBytes / 150), ceil(outputBytes / 34))) ``` Inputs are sized with their final scriptSig, so pass a transaction with placeholder signatures of realistic length. The builders use 73-byte placeholders (the DER maximum plus the sighash byte), so the fee never comes out short. A one-input, one-output HTLC or 2-of-2 spend costs 10,000 zat. | Constant | Value | Meaning | |---|---|---| | `MARGINAL_FEE` | `5_000n` | Zatoshi per logical action. | | `GRACE_ACTIONS` | `2` | Every transaction pays for at least this many actions. | | `P2PKH_STANDARD_INPUT_SIZE` | `150` | Bytes. | | `P2PKH_STANDARD_OUTPUT_SIZE` | `34` | Bytes. | ## Constants and limits | Constant | Value | Meaning | |---|---|---| | `BRANCH_ID_NU6_3` | `0x37a5165b` | Consensus branch id of NU6.3 ("Ironwood"), for reference. No builder defaults to it: pass the node's live value. | | `TX_VERSION_5` | `5` | Transaction version. | | `V5_VERSION_GROUP_ID` | `0x26a7270a` | v5 version group id. | | `OVERWINTERED_FLAG` | `0x80000000` | Header flag. | | `SEQUENCE_FINAL` | `0xffffffff` | `lock_time` is ignored for this input. | | `SEQUENCE_ENABLE_LOCKTIME` | `0xfffffffe` | Non-final: `lock_time` and `OP_CHECKLOCKTIMEVERIFY` are enforced. Used by refunds. | | `DUST_LIMIT` | `1_000n` | Outputs below this many zatoshi are refused. | | `MIN_CHANGE` | `1_000n` | Change below this goes to the fee. Same as `DUST_LIMIT`. | | `MAX_MONEY` | `2_100_000_000_000_000n` | 21 million ZEC in zatoshi. | | `FUNDING_EXPIRY_DELTA` | `40` | Blocks. Paralock's funding transactions expire at `tip + 40`. | | `MAX_SCRIPT_ELEMENT_SIZE` | `520` | Bytes: the largest push, so the largest P2SH redeem script. | | `MAX_STANDARD_SCRIPTSIG_SIZE` | `1650` | Bytes: larger scriptSigs are not relayed. | `assertOutputValue(value, what?)`, `assertExpiryHeight(expiryHeight)` and `assertP2shSizes(redeemScript, scriptSig)` throw when a value breaks these limits. ## The ZcashNode interface `ZcashNode` is the backend the [SDK engines](https://paralock.xyz/docs/sdk) depend on. `ZcashRpc` implements all of it. Light backends such as [`LightwalletdClient`](https://paralock.xyz/docs/lightwalletd) implement the required methods and may omit the optional ones. | Method | Required | Meaning | |---|---|---| | `getBlockCount(): Promise` | yes | Height of the chain tip. | | `getNextBranchId(): Promise` | yes | Consensus branch id the next block uses. Sign with it. | | `getAddressUtxos(addresses: string[]): Promise<(Utxo & { address: string; height: number })[]>` | yes | Confirmed UTXOs of transparent addresses, with the height they were mined at. | | `getAddressTxids(addresses: string[]): Promise` | yes | Confirmed txids touching transparent addresses. | | `getRawTransaction(txid: string): Promise` | yes | A mempool or mined transaction. Rejects if unknown. | | `sendRawTransaction(hex: string): Promise` | yes | Broadcasts and returns the txid. Must succeed if the node already has the transaction. | | `findSpend(address: string, txid: string, vout: number): Promise` | yes | The confirmed transaction spending `txid:vout`, found through `address`'s history. | | `getTxOut?(txid, vout, includeMempool?): Promise` | no | The unspent output, mempool spends included; `null` if spent or unknown. Without it the engines query confirmed UTXOs instead. | | `upgradeBefore?(height: number): Promise` | no | The first network upgrade activating after the next block and at or before `height`. Without it the engines skip the upgrade check, with a logged warning. | | `generate?(blocks: number): Promise` | no | Regtest only: mines blocks. | | Type | Fields | |---|---| | `NodeTransaction` | `txid`, `hex`, `height?`, `confirmations?` (0 or absent in the mempool), `vin: { txid?; vout?; coinbase?; scriptSig?: { hex } }[]` | | `NodeTxOut` | `confirmations`, `value` (in ZEC, not zatoshi), `scriptPubKey: { hex }` | | `UpcomingUpgrade` | `name`, `activationHeight`, `branchId` | ## ZcashRpc ```ts class ZcashRpc implements ZcashNode { constructor(url: string, options?: ZcashRpcOptions); } ``` JSON-RPC client for Zebra and Zakura nodes (and zcashd-compatible endpoints). Browser-safe: it uses `fetch`. Every call has a timeout. Idempotent calls are retried with exponential backoff on transport failures (network errors, timeouts, HTTP 5xx, non-JSON bodies). JSON-RPC errors are thrown at once. | Option | Type | Default | Meaning | |---|---|---|---| | `auth` | `{ username: string; password: string }` | none | HTTP basic auth (Zebra cookie auth or rpcuser/rpcpassword). | | `timeoutMs` | `number` | `15_000` | Per-request timeout, in milliseconds. | | `retries` | `number` | `3` | Extra attempts after a transport failure. Never after a JSON-RPC error. `generate` is never retried. | | `retryDelayMs` | `number` | `250` | First retry delay. Doubles each attempt, with jitter, capped at 5 s. | | `fetch` | `typeof fetch` | global `fetch` | Custom `fetch` implementation. | A bare `{ username, password }` second argument is still accepted (0.1 compatibility). | Method | Meaning | |---|---| | `call(method, params = [])` | Raw JSON-RPC call. | | `getBlockCount()` | `getblockcount`. | | `getBlockchainInfo()` | `getblockchaininfo`: `BlockchainInfo` with `chain`, `blocks`, `upgrades`, `consensus`. | | `getNextBranchId()` | Parses `getblockchaininfo.consensus.nextblock`. | | `upgradeBefore(height)` | The first upgrade in `upgrades` activating after the next block and at or before `height`. | | `getAddressUtxos(addresses)` | `getaddressutxos` (P2PKH and P2SH). | | `getAddressTxids(addresses)` | `getaddresstxids` (confirmed). | | `getTxOut(txid, vout, includeMempool = true)` | `gettxout`: `TxOutInfo`, or `null` when spent or unknown. | | `sendRawTransaction(hex)` | Returns the txid. Retried on transport failures (resending identical bytes is harmless). If the node already has a transparent-only transaction, that counts as success. | | `getRawTransaction(txid)` | `getrawtransaction 1`: `RawTransaction` with `confirmations` and `vout`. | | `getRawMempool()` | Txids in the mempool. | | `generate(n)` | Regtest only: mines `n` blocks. Never retried. | | `findSpend(address, txid, vout)` | Scans `address`'s history for the confirmed spend of `txid:vout`. | ### Errors | Class | Fields | When | |---|---|---| | `ZcashRpcError` | `method`, `code` (the JSON-RPC error code), `message`, `alreadyKnown` | The node answered with a JSON-RPC error. Not retried: the request reached the node and was refused. `alreadyKnown` is true when `sendrawtransaction` was refused because the node already has the transaction (mempool or chain). | | `ZcashRpcTransportError` | `method`, `message`, `cause` | The node could not be reached, timed out, or didn't answer JSON-RPC, after all retries. | ```ts import { ZcashRpcError } from "@paralock/zcash"; try { await rpc.sendRawTransaction(hex); } catch (err) { if (!(err instanceof ZcashRpcError && err.alreadyKnown)) throw err; // already broadcast: fine } ``` ## Low-level helpers | Area | Exports | |---|---| | Script | `OP` (opcodes), `hash160`, `pushData`, `scriptNum`, `pushNumber`, `p2pkhScript`, `p2shScript`, `decompile` | | Bytes | `bytesToHex`, `hexToBytes`, `concatBytes`, `toBytes` (bytes or hex with or without `0x`), `u32le`, `i64le`, `compactSize`, `withLength`, `Reader`, `txidToBytes`, `bytesToTxid`, `isTxid` | ## Security notes - Public keys are checked to be valid compressed points. HTLC claim and refund keys must differ. - Signatures are low-S, strict DER, with RFC 6979 nonces. `finalizeMultisigSpend` verifies both signatures. - The builders require `network`, so an address from the wrong network is rejected, and `branchId`, so nothing is signed for the wrong upgrade. - Read the branch id from your node and check `upgradeBefore` for pre-signed spends. - Redeem scripts and scriptSigs are checked against consensus and relay size limits. - Check counterparty scripts with `htlcFromRedeemScript` or `multisigFromRedeemScript`: both rebuild the template and compare bytes. --- # @paralock/adaptor Source: https://paralock.xyz/docs/adaptor Markdown: https://paralock.xyz/docs/adaptor.md Section: Reference > Reference for ECDSA adaptor signatures on secp256k1 with DLEQ proofs: pre-sign, pre-verify, adapt, extract, encodings and security notes. `@paralock/adaptor` implements ECDSA adaptor signatures on secp256k1 with Chaum–Pedersen DLEQ proofs. A pre-signature on a digest is "encrypted" to a point `Y = y·G`: - anyone can check it without learning `y`; - whoever knows `y` completes it into a normal low-S ECDSA signature; - whoever holds the pre-signature and later sees that signature learns `y`. Completing a signature on one chain therefore reveals the secret needed on another, with no hash or other shared value on-chain. Paralock's private (`adaptor`) mode is built on it. Pure TypeScript on `@noble/curves` and `@noble/hashes`; browser-safe. > **Warning:** Experimental and not audited by a third party. ECDSA adaptor signatures have seen far less scrutiny than Schnorr ones. Use testnets only. ## Install ```sh npm install @paralock/adaptor ``` This page describes version 0.1.2 (the release before it is 0.1.1). The API hasn't changed since 0.1.0: 0.1.1 added hedged nonces and range checks, and 0.1.2 bounds nonce retries. ## The math in brief A pre-signature on digest `m` under private key `x` (public key `X = x·G`), encrypted to the adaptor point `Y = y·G`: ```text k random (hedged nonce) R' = k·G R = k·Y r = R.x mod n s' = k⁻¹(m + r·x) mod n π = DLEQ proof that log_G(R') = log_Y(R) ``` | Step | Who | Computation | |---|---|---| | Pre-verify | anyone | Check `π`, then check `s'⁻¹(m·G + r·X) = R'`. This proves `(r, s')` becomes a valid signature under `X` once `y` is applied, without revealing `y`. | | Adapt | holder of `y` | `s = s'·y⁻¹`. The effective nonce is `k·y`, so `(r, s)` verifies under `X`. Normalized to low-S. | | Extract | holder of the pre-signature | `y = ±s'·s⁻¹`, choosing the sign whose `y·G` equals `Y` (the sign is lost by low-S normalization). | ## Example ```ts import { adapt, adaptorKeyPair, decodePreSignature, encodePreSignature, extract, preSign, preVerify, recoveryId, verify, } from "@paralock/adaptor"; // The signer's key pair. Any secp256k1 key works; adaptorKeyPair() also makes one. const signer = adaptorKeyPair(); // The 32-byte digest to sign, for example an escrow's claimDigest. const digest = crypto.getRandomValues(new Uint8Array(32)); // Taker: the adaptor secret y and its point Y. const { secret, point } = adaptorKeyPair(); // Maker: pre-sign, encrypted to Y, and send it (162 bytes, as hex). const wire = encodePreSignature(preSign(signer.secret, digest, point)); // Taker: parse and ALWAYS verify before relying on it. const pre = decodePreSignature(wire); if (!preVerify(signer.point, digest, point, pre)) throw new Error("invalid pre-signature"); // Taker: complete it with y and publish the signature (here, for EVM ecrecover). const sig = adapt(pre, secret); const v = 27 + recoveryId(signer.point, digest, sig); verify(signer.point, digest, sig); // true // Maker: seeing (r, s) on-chain, recover y. const recovered = extract(pre, sig, point); // the same 32 bytes as `secret` ``` ## API `Bytes` is `Uint8Array | string`: bytes, or hex with or without `0x`. | Export | Signature | Meaning | |---|---|---| | `adaptorKeyPair` | `adaptorKeyPair(): { secret: Uint8Array; point: Uint8Array }` | A fresh secret `y` (32 bytes) and its point `Y` (33-byte compressed). | | `preSign` | `preSign(privateKey: Bytes, digest: Bytes, adaptorPoint: Bytes): PreSignature` | Pre-signs a 32-byte digest with a DLEQ proof. A fresh hedged nonce on every call. Throws if the key is not in `[1, n)`, the digest is not 32 bytes, or the point is invalid, and, since 0.1.2, if 8 nonces in a row are unusable (only a broken random number generator does that) instead of looping. | | `preVerify` | `preVerify(publicKey: Bytes, digest: Bytes, adaptorPoint: Bytes, pre: PreSignature): boolean` | True if `pre` becomes a valid signature by `publicKey` on `digest` once `y` is applied. Checks the DLEQ proof and every range. Returns `false` (never throws) on malformed input. | | `adapt` | `adapt(pre: PreSignature, adaptorSecret: Bytes): Signature` | Completes the pre-signature with `y`. Always returns low-S. Throws if `y` or `s'` is out of range. | | `extract` | `extract(pre: PreSignature, sig: Signature, adaptorPoint: Bytes): Uint8Array` | Recovers `y` (32 bytes) from the pre-signature and the published signature. Throws if `sig` doesn't belong to `pre`. | | `verify` | `verify(publicKey: Bytes, digest: Bytes, sig: Signature): boolean` | Standard ECDSA verification of a prehashed digest. Low-S required. | | `compact` | `compact(sig: Signature): Uint8Array` | 64-byte `r ‖ s`. | | `der` | `der(sig: Signature): Uint8Array` | DER encoding, as used in Zcash scriptSigs. Append the sighash type byte yourself (`0x01` for `SIGHASH_ALL`). | | `recoveryId` | `recoveryId(publicKey: Bytes, digest: Bytes, sig: Signature): 0 \| 1` | The recovery id such that `ecrecover(digest, 27 + id, r, s)` returns `publicKey`. Throws if neither value recovers it. | | `encodePreSignature` | `encodePreSignature(pre: PreSignature): string` | The 162-byte wire format, as 324 lowercase hex characters without `0x`. | | `decodePreSignature` | `decodePreSignature(data: Bytes): PreSignature` | Parses the wire format. Throws unless it is exactly 162 bytes. It does **not** check ranges or points: call `preVerify`. | | `secretToHex` | `secretToHex(secret: Uint8Array): string` | Hex of an adaptor secret, without `0x`. | ### Types | Type | Fields | |---|---| | `PreSignature` | `R: Uint8Array` (`k·Y`, compressed; its x coordinate is the final `r`), `Rp: Uint8Array` (`k·G`, compressed), `s: bigint` (`s'`), `proof: DleqProof` | | `DleqProof` | `c: bigint` (challenge), `z: bigint` (response) | | `Signature` | `r: bigint`, `s: bigint` | ## Wire format `encodePreSignature` writes 162 bytes. Scalars are 32-byte big-endian. | Offset | Bytes | Field | |---|---|---| | 0 | 33 | `R = k·Y`, compressed | | 33 | 33 | `R' = k·G`, compressed | | 66 | 32 | `s'` | | 98 | 32 | DLEQ challenge `c` | | 130 | 32 | DLEQ response `z` | The SDK sends pre-signatures in this format (`AdaptorPreSignatureRequest.takerPreSignature`, `Swap.adaptor.evmPreSignature`). ## How Paralock uses it Both pre-signatures in a private-mode swap are encrypted to the taker's point `Y`. Only the taker knows `y`. See [How it works](https://paralock.xyz/docs/how-it-works) and [Privacy](https://paralock.xyz/docs/privacy) for the full protocol. 1. The taker pre-signs the maker's Zcash claim (the ZIP 244 sighash of the 2-of-2 spend) with its multisig key. The maker pre-verifies it. 2. The maker locks stablecoins in `ParalockAdaptorEscrow` and pre-signs the escrow's `claimDigest(id)` with a one-time signer key. The taker pre-verifies it, along with the lock. 3. The taker adapts the escrow pre-signature with `y` and claims with `v = 27 + recoveryId(...)`. The escrow's `Claimed` event publishes `(r, s)`. 4. The maker extracts `y` from its pre-signature and that `(r, s)`, adapts the taker's Zcash pre-signature, and claims the ZEC with `der(sig)` plus the `SIGHASH_ALL` byte. No hash, preimage or other shared value appears on either chain. ## Security notes - **Hedged nonces.** Each pre-signature nonce is `sha512("paralock/adaptor/nonce/v1" ‖ x ‖ m ‖ Y ‖ 32 random bytes)` reduced mod n; the DLEQ nonce uses its own tag and mixes in `k` and the points. Fresh randomness makes every nonce unique, and mixing in the secret and the message means a broken or repeated RNG output still can't produce the same nonce for two different messages, which would leak the key. Two calls never share a nonce. - **DLEQ proof and domain separation.** The challenge is `sha256("paralock/adaptor/dleq/v1" ‖ G ‖ Y ‖ R' ‖ R ‖ T1 ‖ T2) mod n` over 33-byte compressed points: a fixed-length, protocol-specific encoding. It is part of the wire format; changing it breaks compatibility. - **Low-S.** `adapt` always returns low-S and `verify` requires it, matching the EVM escrow (which rejects high-S as `MalleableSignature`) and Zcash standardness rules. `extract` tries both signs, so normalization never loses the secret. - **Range checks.** Private keys and adaptor secrets must be in `[1, n)`. `preVerify` rejects out-of-range `s'` and proof values and invalid points. - **Always call `preVerify`** on a pre-signature you receive, before acting on it. `decodePreSignature` only parses. --- # @paralock/evm Source: https://paralock.xyz/docs/evm Markdown: https://paralock.xyz/docs/evm.md Section: Reference > Reference for the viem clients of ParalockHTLC and ParalockAdaptorEscrow, the verified network registry, Tempo specifics, errors and ABIs. `@paralock/evm` provides [viem](https://viem.sh) clients for Paralock's two EVM escrows, on Tempo and any other EVM chain (Base, Ethereum, Arbitrum, Robinhood Chain, HyperEVM, local anvils): - **`ParalockHTLC`** (htlc mode): a sha256 hash-time-locked escrow. `createEvmHtlc`. - **`ParalockAdaptorEscrow`** (adaptor mode): releases to a fixed recipient on a one-time signer's signature over `claimDigest(id)`. No hash on-chain. `createAdaptorEscrow`. Both contracts store one slot per swap, pay only the recipient fixed at lock time (anyone may submit the claim, for example a relayer), and mark ids and hashlocks settled forever. See [Contracts and deployments](https://paralock.xyz/docs/contracts) for the contracts themselves and their addresses. > **Warning:** Experimental and not audited by a third party. The contracts are deployed on testnets only. ## Install ```sh npm install @paralock/evm viem ``` This page describes version 0.3.0. New in 0.3.0: `approveAndLock`, `outcome`, `now`, `blockNumber`, `maxLockSeconds`, the chain-id check, pinned lock lookups, verified read-backs, coordinated sends and `deployParalockContracts` with the embedded artifacts. Its only dependency is `viem`. Amounts are `bigint` token base units (the supported stablecoins have 6 decimals: 25 USDC = `25_000_000n`). Expiries are Unix seconds. ## createEvmHtlc ```ts function createEvmHtlc(options: CreateEvmHtlcOptions): EvmHtlc ``` ```ts import { createEvmHtlc, knownNetwork } from "@paralock/evm"; import type { Hex } from "viem"; const base = knownNetwork(84532)!; // Base Sepolia const usdc = base.tokens.USDC!; const htlc = createEvmHtlc({ rpcUrl: base.rpcUrl!, chainId: base.chainId, contract: HTLC, account: process.env.EVM_KEY as Hex, fromBlock: DEPLOY_BLOCK, // the contract's deployment block }); const swap = { hashlock, // sha256 of the 32-byte secret: the same value as the Zcash HTLC's token: usdc, sender: htlc.walletClient!.account.address, recipient, amount: 25_000_000n, // 25 USDC expiry: (await htlc.now()) + 3600n, // Unix seconds in chain time, 1 h from now }; await htlc.approveAndLock(swap); // checks the swap, approves exactly the amount if needed, then locks const preimage = await htlc.waitForClaimPreimage(hashlock, { timeoutMs: 3_600_000 }); // the secret, once claimed ``` ### Options `CreateEvmHtlcOptions` and `CreateAdaptorEscrowOptions` share these fields (`EvmConnectionOptions` plus the scan settings): | Option | Type | Default | Meaning | |---|---|---|---| | `rpcUrl` | `string` | required | JSON-RPC endpoint. | | `chainId` | `number` | required | Expected chain id. The escrow clients check the node's `eth_chainId` against it once (then cached) before their first read or send, and throw `ChainIdMismatchError` on a mismatch. | | `contract` | `Address` | required | `ParalockHTLC` or `ParalockAdaptorEscrow` address. | | `account` | `Account \| Hex` | none | Signer: a viem `Account` or a `0x` private key. Omit it for a read-only client; sending then throws. | | `fromBlock` | `bigint` | `0n` | First block to scan for events: the contract's deployment block. Set it on public chains. | | `maxBlockRange` | `bigint` | `50_000n` | Largest block span per `eth_getLogs` request. Scans run newest-first and stop at the first match; a span the node refuses is halved (and kept smaller) automatically. | | `feeToken` | `Address` | none | Tempo only: the TIP-20 that pays gas. Implies `tempo: true`. | | `tempo` | `boolean` | by chain id | Use Tempo's transaction format. Default: true when `feeToken` is set or `chainId` is in `TEMPO_CHAIN_IDS`. | | `pollingIntervalMs` | `number` | `500` | Poll interval for receipts and waiters, in milliseconds. | | `rpcTimeoutMs` | `number` | `10_000` | Per-request RPC timeout, in milliseconds. | | `rpcRetryCount` | `number` | `3` | Retries per RPC request on network errors and 5xx or 429 responses, with exponential backoff. | | `receiptTimeoutMs` | `number` | `180_000` | How long to wait for a sent transaction to be mined before throwing, in milliseconds. | | `maxLockSeconds` | `number` | `10_000_000` | The furthest a new lock's expiry may be ahead of the chain's time, in seconds. `lock` refuses anything later (for example an expiry in milliseconds) before approving or sending. | ### EvmHtlc | Member | Signature | Behavior | |---|---|---| | `address`, `chain`, `publicClient`, `walletClient` | | The contract and the viem clients. `walletClient` is `undefined` without an `account`. | | `approveAndLock` | `approveAndLock(swap: HtlcSwap): Promise` | Checks the swap as `lock` does, approves exactly `swap.amount` if needed, then locks. Serialized per account, token and contract (process-wide) until the lock is mined, so concurrent locks never overwrite each other's exact approvals. A refused lock leaves no approval behind. Resolves with `{ approval, lock }`. | | `approveIfNeeded` | `approveIfNeeded(token: Address, amount: bigint): Promise` | Approves exactly `amount` unless the allowance already covers it. Never unlimited. Takes the same lock as `approveAndLock`. | | `lock` | `lock(swap: HtlcSwap): Promise` | Locks funds. The account must be `swap.sender` and have approved the contract. Throws `InvalidLockError` before sending unless the amount, recipient and hashlock are non-zero and `now < expiry ≤ now + maxLockSeconds` in chain time. | | `claim` | `claim(swap: HtlcSwap, preimage: Hex): Promise` | Pays `swap.recipient` by revealing the 32-byte secret. Checks `sha256(preimage)` locally first. Any account may submit it. | | `refund` | `refund(swap: HtlcSwap): Promise` | Returns the funds to `swap.sender` once `swap.expiry` has passed. Any account may submit it. | | `now`, `blockNumber` | `() => Promise` | The latest block's timestamp (Unix seconds) and number. Expiries are compared against chain time, never local time. | | `getState` | `getState(hashlock: Hex): Promise` | `{ status: "empty" \| "active" \| "settled", raw }`. | | `getLockedSwap` | `getLockedSwap(hashlock: Hex): Promise` | The swap rebuilt from its `Locked` event and checked against the on-chain commitment. | | `getLock` | `getLock(hashlock: Hex): Promise \| undefined>` | The same, plus `blockNumber` and `transactionHash` of the lock. State and logs are read at one pinned block. Confirmations = latest block − `blockNumber` + 1. | | `outcome` | `outcome(hashlock: Hex): Promise` | Where the swap stands, read at one pinned block: `{ status: "empty" }`, `"active"`, `"refunded"`, or `{ status: "claimed", preimage }` with the preimage checked to hash to the hashlock. Throws `SettlementNotIndexedError` if settled but the event isn't served yet (retry), `InvalidResponseError` if the node returns a preimage that doesn't match. | | `waitForLocked` | `waitForLocked(hashlock: Hex, options?: WaitOptions): Promise` | Resolves once a swap is locked (at once if it already is). | | `waitForClaimPreimage` | `waitForClaimPreimage(hashlock: Hex, options?: WaitOptions): Promise` | Resolves with the preimage once claimed (checked as in `outcome`). Rejects with `SwapRefundedError` if refunded, `HtlcTimeoutError` on timeout. | | `tokenBalance` | `tokenBalance(token: Address, owner: Address): Promise` | ERC-20 or TIP-20 `balanceOf`. | `WaitOptions` is `{ timeoutMs?: number; signal?: AbortSignal }`. Without `timeoutMs` a waiter waits forever. `TxResult` is `{ hash: Hex; blockNumber: bigint; gasUsed: bigint }`, returned once the transaction is mined and successful. `LockReceipt` is `{ approval: TxResult | undefined; lock: TxResult }`. Every transaction of one account through one RPC endpoint is prepared, signed and broadcast under one process-wide lane: local accounts (private keys, KMS accounts) get an explicit nonce, so concurrent swaps never reuse one. Separate processes sending from one key are not coordinated: give each its own key. Transactions sent through `walletClient` directly bypass the lane. ## createAdaptorEscrow ```ts function createAdaptorEscrow(options: CreateAdaptorEscrowOptions): AdaptorEscrow ``` Same options as [`createEvmHtlc`](#options), with `contract` set to the `ParalockAdaptorEscrow` address. ```ts import { createAdaptorEscrow, randomSalt } from "@paralock/evm"; const escrow = createAdaptorEscrow({ rpcUrl, chainId: 84532, contract: ESCROW, account, fromBlock: DEPLOY_BLOCK }); const swap = { token: usdc, sender, recipient, signer, amount: 25_000_000n, expiry, salt: randomSalt() }; const { lock } = await escrow.approveAndLock(swap); const id = lock.id; const digest = escrow.claimDigest(id); // what `signer` signs: raw, no EIP-191 prefix // Later, anyone submits signer's signature; the funds go to swap.recipient. await escrow.claim(swap, signature); const { v, r, s } = await escrow.waitForClaimSignature(id, { timeoutMs: 60_000 }); ``` ### AdaptorEscrow | Member | Signature | Behavior | |---|---|---| | `address`, `chainId`, `chain`, `publicClient`, `walletClient` | | The contract, its configured chain id and the viem clients. | | `approveAndLock` | `approveAndLock(swap: AdaptorSwap): Promise>` | As on `EvmHtlc`: checks, exact approval if needed, lock; serialized per account, token and contract. | | `approveIfNeeded` | `approveIfNeeded(token: Address, amount: bigint): Promise` | Exact allowance, only if needed. | | `lock` | `lock(swap: AdaptorSwap): Promise` | Locks funds and resolves with the swap id. Checks that the contract computes the same id. Throws `InvalidLockError` before sending on a zero signer, amount or recipient, or an expiry outside `(now, now + maxLockSeconds]`. | | `claim` | `claim(swap: AdaptorSwap, signature: ClaimSignatureInput): Promise` | Pays `swap.recipient` with `swap.signer`'s signature over `claimDigest(id)`. Normalizes the signature (`normalizeClaimSignature`) and checks it recovers to `swap.signer` before sending. Any account may submit it. | | `refund` | `refund(swap: AdaptorSwap): Promise` | Returns the funds to `swap.sender` once `swap.expiry` has passed. | | `idOf` | `idOf(swap: AdaptorSwap): Hex` | The swap id, computed locally (`keccak256(abi.encode(swap))`), identical to the contract's `idOf`. | | `claimDigest` | `claimDigest(id: Hex): Hex` | The digest the signer signs, computed locally for this chain and contract. Synchronous. | | `getState` | `getState(id: Hex): Promise` | `{ status: "empty" \| "active" \| "settled", raw: 0 \| 1 \| 2 }`. | | `now`, `blockNumber` | `() => Promise` | The latest block's timestamp and number. | | `getLockedSwap`, `getLock` | `(id: Hex) => Promise`, `Promise \| undefined>` | The swap rebuilt from its `Locked` event and checked against its id, state and logs read at one pinned block; `getLock` adds `blockNumber` and `transactionHash`. | | `outcome` | `outcome(id: Hex): Promise` | Like `EvmHtlc.outcome`; `claimed` carries `signature`, checked to be canonical and to recover, over this chain's `claimDigest(id)`, to the swap's signer. | | `waitForLocked` | `waitForLocked(id: Hex, options?: WaitOptions): Promise` | Resolves once locked. | | `waitForClaimSignature` | `waitForClaimSignature(id: Hex, options?: WaitOptions): Promise` | Resolves with the published `{ v, r, s }` once claimed (checked as in `outcome`). Rejects with `SwapRefundedError` if refunded, `HtlcTimeoutError` on timeout. | | `tokenBalance` | `tokenBalance(token: Address, owner: Address): Promise` | `balanceOf`. | ## Swap data | Type | Fields | |---|---| | `HtlcSwap` | `hashlock: Hex`, `token: Address`, `sender: Address` (locks, refunded after expiry), `recipient: Address` (paid on claim), `amount: bigint`, `expiry: bigint` (Unix seconds from which only a refund is possible) | | `AdaptorSwap` | `token`, `sender`, `recipient`, `signer: Address` (whose signature releases the funds), `amount`, `expiry`, `salt: Hex` (32 random bytes that make the id unique and unlinkable) | | `LockInfo` | `swap: S`, `blockNumber: bigint`, `transactionHash: Hex` | | `ClaimSignature` | `v: number` (27 or 28), `r: Hex`, `s: Hex` (low) | | `ClaimSignatureInput` | `r: Hex`, `s: Hex`, and `v?: number \| bigint` (0, 1, 27 or 28) or viem's `yParity?: number` | | Helper | Meaning | |---|---| | `hashlockOf(preimage: Hex): Hex` | sha256 of a 32-byte secret: the hashlock on both chains. | | `commitmentOf(swap: HtlcSwap): Hex` | `keccak256(abi.encode(swap))`: what `ParalockHTLC` stores while a swap is active. | | `statusOf(raw: Hex): HtlcStatus` | Maps a `stateOf` word: `0` empty, `1` (`SETTLED_STATE`) settled, anything else active. | | `SETTLED_STATE`, `EMPTY_STATE` | The two fixed state words. | | `adaptorSwapId(swap: AdaptorSwap): Hex` | The escrow id, exactly as the contract computes it. | | `adaptorClaimDigest({ chainId, contract, id }): Hex` | `keccak256(abi.encode(keccak256("ParalockAdaptorClaim"), chainId, contract, id))`. | | `ADAPTOR_CLAIM_TYPEHASH` | `keccak256("ParalockAdaptorClaim")`. | | `normalizeClaimSignature(sig: ClaimSignatureInput): ClaimSignature` | `v` to 27 or 28; a high `s` becomes `n − s` with the recovery bit flipped. Throws on an out-of-range value. | | `randomSalt(): Hex` | 32 random bytes for `AdaptorSwap.salt`. | | `adaptorStatusOf(raw: number): AdaptorStatus` | Maps the contract's `Status` enum. | | `assertBytes32(value, name)` | Throws a `TypeError` unless `value` is `0x` plus 64 hex characters. | ## Known networks `KNOWN_NETWORKS` is a registry of public networks, each value checked on 2026-10-11 against the chain's official docs (and Circle's USDC list), with a live `eth_chainId` call per RPC and `symbol()` / `decimals()` per token. A field is left out where no official source gives it. | Export | Signature | |---|---| | `KNOWN_NETWORKS` | `readonly KnownNetwork[]` | | `knownNetwork` | `knownNetwork(chainId: number): KnownNetwork \| undefined` | | `knownNetworks` | `knownNetworks(chain: EvmChainName): KnownNetwork[]` (mainnet first) | `KnownNetwork` is `{ chain, chainId, name, testnet, rpcUrl?, explorerUrl?, nativeCurrency?, usdc?, tokens: Record }`. | Network | `chain` | Chain id | Testnet | Official RPC | Explorer | |---|---|---|---|---|---| | Tempo | `tempo` | 4217 | no | `https://rpc.tempo.xyz` | `https://explore.tempo.xyz` | | Tempo Testnet (Moderato) | `tempo` | 42431 | yes | `https://rpc.moderato.tempo.xyz` | `https://explore.testnet.tempo.xyz` | | Base | `base` | 8453 | no | `https://mainnet.base.org` | `https://basescan.org` | | Base Sepolia | `base` | 84532 | yes | `https://sepolia.base.org` | `https://sepolia.basescan.org` | | Ethereum | `ethereum` | 1 | no | none (bring your own) | none | | Sepolia | `ethereum` | 11155111 | yes | none (bring your own) | `https://sepolia.etherscan.io` | | Arbitrum One | `arbitrum` | 42161 | no | `https://arb1.arbitrum.io/rpc` | `https://arbiscan.io` | | Arbitrum Sepolia | `arbitrum` | 421614 | yes | `https://sepolia-rollup.arbitrum.io/rpc` | `https://sepolia.arbiscan.io` | | Robinhood Chain | `robinhood` | 4663 | no | `https://rpc.mainnet.chain.robinhood.com` | `https://robinhoodchain.blockscout.com` | | Robinhood Chain Testnet | `robinhood` | 46630 | yes | `https://rpc.testnet.chain.robinhood.com` | `https://explorer.testnet.chain.robinhood.com` | | HyperEVM | `hyperevm` | 999 | no | `https://rpc.hyperliquid.xyz/evm` | `https://hyperevmscan.io` | | HyperEVM Testnet | `hyperevm` | 998 | yes | `https://rpc.hyperliquid-testnet.xyz/evm` | none | Stablecoins (`tokens`; all have 6 decimals): | Network | Tokens | |---|---| | Tempo, Moderato | `OUSD` `0x20c0000000000000000000006a37DA5C996874BE`, `pathUSD` `0x20c0000000000000000000000000000000000000`, `USDC.e` (Stargate-bridged; `0x20c000000000000000000000b9537d11c60e8b50` on Tempo, `0x20c0000000000000000000009e8d7eb59b783726` on Moderato) | | Base | `USDC` `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | | Base Sepolia | `USDC` `0x036CbD53842c5426634e7929541eC2318f3dCF7e` | | Ethereum | `USDC` `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` | | Sepolia | `USDC` `0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238` | | Arbitrum One | `USDC` `0xaf88d065e77c8cC2239327C5EDb3A432268e5831` | | Arbitrum Sepolia | `USDC` `0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d` | | Robinhood Chain | `USDG` `0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168` | | Robinhood Chain Testnet | none (the Paralock deployment uses a MockUSD test token, `0xD9B278625B5946B8CD15dad6c0c776095B8D0513`, listed as `USDC` in `contracts/deployments/46630.json`; see [deployments](https://paralock.xyz/docs/contracts#deployments)). The SDK's `createTaker` without `tokens` on 46630 fails with a message pointing to it: pass it in `tokens` to accept it. | | HyperEVM | `USDC` `0xb88339CB7199b77E23DB6E890353E22632Ba630f` | | HyperEVM Testnet | `USDC` `0x2B3370eE501B4a559b57D449569354196457D8Ab` | The SDK's `createTaker` uses these tokens as the default accepted stablecoins for a chain id. `plainEvmChain` uses the name, gas token and explorer. ## Tempo Tempo has no native gas token: fees are paid in TIP-20 USD stablecoins. Every TIP-20 token lives at an address starting with `0x20c0…`. - **Fee token.** With `feeToken` set, every transaction is sent as a Tempo (`0x76`) transaction paying fees in that token. Set it on Moderato and mainnet to a stablecoin the account holds, for example `TEMPO_TOKENS.PathUSD` or `OUSD`. Without it, plain EIP-1559 transactions are sent and the node picks the account's fee token (its FeeManager preference, preset for anvil dev accounts). - **Chain detection.** `TEMPO_CHAIN_IDS` is `[4217, 42431, 31318, 1337, 31337]`: mainnet, Moderato, Tempo devnet, `tempo node --dev`, and the Paralock devnet's `anvil --network tempo` (`ANVIL_TEMPO_CHAIN_ID`, 31337). 31337 is also plain anvil's default id: pass `tempo: false` to use it as an ordinary EVM chain. - **Memos.** On TIP-20 tokens the contracts move funds with `transferFromWithMemo` / `transferWithMemo`, with the hashlock or escrow id as memo, so explorers can link every movement to its swap. - **Storage cost.** Each new storage slot costs about 250k gas (TIP-1000), so a `ParalockHTLC` lock costs about 305k gas on a local Tempo chain. ```ts import { TEMPO_TOKENS, createEvmHtlc } from "@paralock/evm"; const htlc = createEvmHtlc({ rpcUrl: "https://rpc.moderato.tempo.xyz", chainId: 42431, contract: HTLC, account, fromBlock: DEPLOY_BLOCK, feeToken: TEMPO_TOKENS.PathUSD, // pay gas in pathUSD }); ``` `TEMPO_TOKENS` lists `PathUSD`, `AlphaUSD`, `BetaUSD`, `ThetaUSD` (dev tokens, pre-funded on local chains and from the Moderato faucet) and `OUSD` (Open USD on Tempo mainnet and Moderato). | Chain helper | Meaning | |---|---| | `evmChain(chainId, rpcUrl, options?: { feeToken?; tempo? }): Chain` | The viem chain: Tempo's config on Tempo chains, a plain one elsewhere. Throws if `feeToken` is set on a non-Tempo chain. | | `tempoChain(chainId, rpcUrl, feeToken?)` | A viem Tempo chain. Mainnet and Moderato keep their explorer metadata; any other id is treated as a local Tempo node. | | `plainEvmChain(chainId, rpcUrl, name?): Chain` | A plain EVM chain. Known networks get their name, gas token and explorer; anything else is an ETH chain. | | `isTempoChainId(chainId): boolean` | True for an id in `TEMPO_CHAIN_IDS`. | | `createEvmClients(options: EvmConnectionOptions): EvmClients` | `{ chain, publicClient, walletClient }` for a chain. | ## Errors | Class | Fields | When | |---|---|---| | `TransactionRevertedError` | `hash` | A sent transaction was mined but reverted. | | `SwapRefundedError` | `id`, `hashlock` (the same value) | A claim waiter found that the swap was refunded instead. | | `HtlcTimeoutError` | | A waiter gave up after `timeoutMs`. Thrown by both clients. | | `ChainIdMismatchError` | `expected`, `actual` | The RPC node serves another chain than `chainId`. Nothing was read from it or sent to it. | | `InvalidLockError` | | `lock` or `approveAndLock` refused the swap before approving or sending anything: an expiry not in `(now, now + maxLockSeconds]`, a sender other than the account, or a zero amount, recipient, hashlock or signer. | | `InvalidResponseError` | | The node returned data that fails verification: a `Locked` event that doesn't match the on-chain state or its id, a log outside the filter, a revealed preimage that doesn't hash to the hashlock, or a claim signature that isn't canonical or isn't the swap signer's over this chain's digest. Such data is never returned. | | `SettlementNotIndexedError` | `id` | `outcome` found the swap settled, but the node doesn't serve its `Claimed` / `Refunded` event yet. Retry later. | Every write is simulated first (`simulateContract`), so a call that would revert throws viem's contract error, carrying the contract's custom error (for example `SwapExpired`), before any transaction is sent. Plain `Error`s are thrown for a read-only client asked to send, a preimage that doesn't match the hashlock (in `claim`), a claim signature that doesn't recover to `swap.signer` (in `claim`), and a lock that is on-chain but whose `Locked` event isn't in the scanned range (check `fromBlock`). > **Warning:** A claim mined after the expiry reverts but still publishes the secret (the preimage or the signature is in the transaction's calldata). Claim with time to spare. ## ABIs and deployment | Export | Meaning | |---|---| | `paralockHtlcAbi`, `paralockHtlcBytecode` | `ParalockHTLC`. | | `paralockAdaptorEscrowAbi`, `paralockAdaptorEscrowBytecode` | `ParalockAdaptorEscrow`. | | `mockUsdAbi`, `mockUsdBytecode` | `MockUSD`, a 6-decimal test token. | | `deployParalockHtlc(options)`, `deployParalockAdaptorEscrow(options)`, `deployMockUsd(options)` | Deploy to local chains and tests. Options: `EvmConnectionOptions` with a required `account`. Resolve with `TxResult & { address }`. For real networks use `contracts/script/Deploy.s.sol` (see [Contracts](https://paralock.xyz/docs/contracts#deploy-it-yourself)). | The ABIs are generated from the Foundry build (`pnpm --filter @paralock/evm generate:abi`) and typed `as const`, so viem infers argument and event types. The aliases from the package's earlier name, `@paralock/tempo`, remain: `createTempoHtlc`, `createTempoClients`, `TempoHtlc`, `TempoClients`, `TempoConnectionOptions`, `CreateTempoHtlcOptions`. ## Security notes - Set `fromBlock` to the deployment block on public chains: lock lookups scan logs from there. - `getLock` and `getLockedSwap` rebuild a swap from its `Locked` event and check it against the on-chain commitment (HTLC) or id (adaptor escrow). Use `getLock().blockNumber` to require confirmations before acting on a lock. - Allowances are exact, never unlimited. - Fee-on-transfer and other non-standard ERC-20s are rejected by the contracts. --- # @paralock/lightwalletd Source: https://paralock.xyz/docs/lightwalletd Markdown: https://paralock.xyz/docs/lightwalletd.md Section: Reference > Reference for LightwalletdClient, a ZcashNode backed by a lightwalletd or Zaino gRPC server, so swaps don't need a full Zcash node. `@paralock/lightwalletd` lets a lightwalletd-compatible gRPC server (lightwalletd or Zaino) act as the Zcash backend for Paralock swaps. You don't have to run or sync a full node. `LightwalletdClient` implements [`ZcashNode`](https://paralock.xyz/docs/zcash#the-zcashnode-interface) from `@paralock/zcash`, so you can pass it anywhere the [SDK](https://paralock.xyz/docs/sdk) takes a Zcash node. > **Warning:** Experimental and not audited by a third party. Use testnets only. ## Install ```sh npm install @paralock/lightwalletd ``` This page describes version 0.1.1 (the release before it is 0.1.0). 0.1.1 parses v1 to v4 transactions to their last byte before hashing them and exports the `LightdInfo` type. Node.js 20 or newer only (it uses gRPC through `@grpc/grpc-js`). The service definitions ship in the package's `proto/` directory. ## Example ```ts import { LightwalletdClient } from "@paralock/lightwalletd"; import { createTaker } from "@paralock/sdk"; const zcash = new LightwalletdClient("testnet.zec.rocks:443"); // TLS on port 443 const taker = createTaker({ zcash: { network: "testnet", node: zcash, key: process.env.ZEC_KEY! }, evm: { tempo: moderato }, maker: "https://maker.example", store: "./paralock-taker", }); const utxos = await zcash.getAddressUtxos([taker.zcashAddress]); console.log(`${utxos.reduce((n, u) => n + u.value, 0n)} zat confirmed`); // …quote and swap as usual, then: zcash.close(); ``` [Swap on public testnets](https://paralock.xyz/docs/testnet) walks through a full testnet swap that uses this client. ## LightwalletdClient ```ts class LightwalletdClient implements ZcashNode { constructor(url: string, options?: LightwalletdOptions); readonly url: string; readonly target: string; // host:port the channel connects to readonly tls: boolean; close(): void; getLightdInfo(): Promise; } ``` | Option | Type | Default | Meaning | |---|---|---|---| | `tls` | `boolean` | by URL | Use TLS. Default: true, except for `http://` and `grpc://` URLs and loopback hosts (`localhost`, `127.x.x.x`, `::1`), which use plaintext. | | `timeoutMs` | `number` | `30_000` | Deadline of each call, in milliseconds. A streaming call must finish within it. | | `retries` | `number` | `3` | Extra attempts after a transport failure: gRPC `UNAVAILABLE`, `DEADLINE_EXCEEDED` or `RESOURCE_EXHAUSTED` (rate limited). | | `retryDelayMs` | `number` | `250` | First retry delay. Doubles each attempt, with jitter, capped at 5 s. | | `log` | `(message: string) => void` | `console.warn` | Warnings, such as a server that can't report network upgrades. | Call `close()` when you are done: it closes the gRPC channel. `getLightdInfo()` returns the server's `GetLightdInfo` answer (chain name, block height, consensus branch id, next upgrade). ### URL forms | URL | Transport | Default port | |---|---|---| | `https://host[:port]`, `grpcs://host[:port]` | TLS | 443 | | `http://host[:port]`, `grpc://host[:port]` | plaintext | 9067 | | `host[:port]` | TLS, or plaintext for a loopback host | 443 (TLS), 9067 (plaintext) | A path after the host is not allowed. The `tls` option overrides the scheme. ```ts new LightwalletdClient("testnet.zec.rocks:443"); // TLS new LightwalletdClient("https://zec.rocks"); // TLS, port 443 new LightwalletdClient("http://127.0.0.1:9067"); // plaintext: the local devnet's lightwalletd ``` ## Method mapping | `ZcashNode` method | gRPC call | Notes | |---|---|---| | `getBlockCount` | `GetLatestBlock` | | | `getNextBranchId` | `GetLightdInfo.consensusBranchId` | Throws if a network upgrade activates at the next block: retry after it is mined. | | `upgradeBefore` | `GetLightdInfo.upgradeName` / `upgradeHeight` | `branchId` is always `0` (not reported). Needs a server that reports `lightwalletProtocolVersion`; older servers skip the check with one warning. | | `getAddressUtxos` | `GetAddressUtxos` | Confirmed UTXOs. | | `getAddressTxids` | `GetTaddressTransactions` | Falls back to `GetTaddressTxids` on older servers. Txids are computed locally; v6 txids come from `GetBlockRange` compact blocks. | | `findSpend` | `GetTaddressTransactions` | Scans the address's mined transactions for the spend. | | `getRawTransaction` | `GetTransaction` | `confirmations` is computed from the tip; 0 while in the mempool. | | `sendRawTransaction` | `SendTransaction` | Returns the locally computed txid. "Already known" counts as success. | | `getTxOut` | not implemented | | | `generate` | not implemented | | ## Differences from a full node - **No `getTxOut`.** The swap engines check confirmed UTXOs instead, so a spend that is still in the mempool isn't seen until it is mined. - **Mined history only.** Address queries return mined transactions. - **Txids are computed locally.** lightwalletd streams raw transactions without their ids. This package hashes v1 to v4 (double SHA-256) and v5 (ZIP 244, including the Sapling and Orchard digests; tested against the official vectors). For v6 transactions it takes the txid from the server's compact blocks. - **v6 transactions can't be decoded.** `getRawTransaction` rejects them. Paralock's own lock, claim and refund transactions are v5. - **Upgrade check.** It needs a server that reports `lightwalletProtocolVersion`. Older servers skip the check, with a warning. ## Errors ```ts class LightwalletdError extends Error { readonly method: string; // the gRPC method, e.g. "SendTransaction" readonly code: number; // gRPC status code, or the node's error code for SendTransaction get alreadyKnown(): boolean; } ``` Thrown for a gRPC failure (after retries) or for a transaction the server refused (`SendTransaction` with a non-zero error code). `alreadyKnown` is true when a broadcast was refused because the node already has the transaction; `sendRawTransaction` treats that as success itself. Plain `Error`s are thrown when the server returns a different transaction or txid than requested, reports an invalid branch id, or when an upgrade activates at the next block. ## Txid utilities | Export | Signature | Meaning | |---|---|---| | `txidOf` | `txidOf(data: Uint8Array \| string): string` | The txid of a raw transaction (v1 to v5), display-order hex. | | `decodeTx` | `decodeTx(data: Uint8Array \| string): DecodedTx` | `{ txid, version, inputs: RawInput[] }`. Parses every version to its last byte (since 0.1.1, v1 to v4 structurally, including Sprout JoinSplits and Sapling descriptions, checked against the ZIP 143 and ZIP 243 vectors) and throws on trailing or missing data, so a txid is only computed over one whole transaction. Throws `UnsupportedVersionError` for v6 and later. | | `RawInput` | `{ prevTxid?: string; vout?: number; scriptSig: Uint8Array }` | A transparent input. Coinbase inputs have no `prevTxid`. | | `UnsupportedVersionError` | `version: number` | A transaction version this module can't decode. | | `shieldedDigests` | `shieldedDigests(raw: Uint8Array): ShieldedDigests` | ZIP 244 Sapling and Orchard digests of a v5 transaction's shielded part. | ```ts import { UnsupportedVersionError, decodeTx } from "@paralock/lightwalletd"; try { const { txid, version, inputs } = decodeTx(rawHex); console.log(txid, version, inputs.length); } catch (err) { if (err instanceof UnsupportedVersionError) console.log(`v${err.version}: not decodable here`); else throw err; } ``` ## Servers Public servers run by the Zcash community: | Network | Server | |---|---| | Testnet | `testnet.zec.rocks:443` (the NU7 chain; see [the testnet split](https://paralock.xyz/docs/networks#the-zcash-testnet-split)) | | Mainnet | `zec.rocks:443`, `na.zec.rocks:443`, `eu.zec.rocks:443`, `ap.zec.rocks:443`, `sa.zec.rocks:443` | The local devnet runs lightwalletd at `http://127.0.0.1:9067` (see [CLI](https://paralock.xyz/docs/cli)). --- # CLI Source: https://paralock.xyz/docs/cli Markdown: https://paralock.xyz/docs/cli.md Section: Reference > Reference for the paralock CLI: the local devnet, the devnet maker, swaps and payments from the terminal, recovery commands, and the files it writes. The `paralock` CLI on npm runs the whole Paralock stack on your machine: a Zcash regtest network, one local EVM chain per supported chain, the contracts, a maker, and swaps and payments from the terminal. It runs with `npx paralock`, with no clone of the repository (version 0.3.0 is its first npm release); to work on the code, run it from a checkout (see [Setup](#setup)). ## npm CLI or Rust binary Paralock has two command-line tools, both named `paralock`. They speak the same protocol and share the [state directory](#state-directory), so they work together on one devnet. | | npm CLI (this page) | [Rust binary](https://paralock.xyz/docs/rust-cli) | |---|---|---| | Package | `paralock` on npm, built on `@paralock/sdk` | `paralock-cli` on crates.io, built on the `paralock` crate | | Install | `npx paralock` (Node.js 20+) | `curl -fsSL https://paralock.xyz/install \| sh`, or `cargo install paralock-cli` | | Networks | The local devnet only: devnet keys, devnet maker | Any network, from a `paralock.toml`, or the devnet with `--devnet` | | Devnet | Starts and stops it: `dev`, `devnet up`, `devnet status`, `devnet down` | Uses the one this CLI started | | Commands | `doctor`, `dev`, `devnet`, `maker`, `swap`, `pay`, `swaps`, `resume`, `refund` | `doctor`, `quote`, `swap`, `pay`, `swaps`, `resume`, `refund`, `maker`, `version`; `--json` and exit codes for scripts | `npx paralock` always runs the npm CLI. A bare `paralock` runs whichever is first on your `PATH`; the Rust binary answers `paralock version`. > **Note:** Everything the CLI starts is a local devnet. Its keys are public development keys and its funds are worthless. For public testnets, see [Swap on public testnets](https://paralock.xyz/docs/testnet). ## Setup Run it with npx from any directory: ```sh npx paralock doctor npx paralock dev --evm all ``` Inside a checkout of the repository, use the workspace build instead, after `pnpm install && pnpm build`: `pnpm paralock ` runs `node packages/cli/dist/main.js `. The commands and flags are the same, so replace `npx paralock` with `pnpm paralock` in the examples below. Without a command, or with an unknown one, the CLI prints the help. Prerequisites, all checked by [`doctor`](#doctor): Node.js 20 or newer, a running Docker daemon (OrbStack or Docker Desktop on macOS), [ths](https://github.com/zcashlabs/thus-spoke-zakura) (Thus Spoke Zakura, the Zcash regtest environment), and Foundry's `anvil` 1.8 or newer with `--network tempo`. The contracts are deployed from bytecode embedded in `@paralock/evm`, so `forge` and the repository aren't needed. Inside a checkout, `doctor` also checks pnpm, installed dependencies and built packages. ### State directory The CLI keeps the devnet's state (`devnet.json`, the ths log, swap stores, keys and logs) in one directory: 1. inside a Paralock checkout (a directory with both `pnpm-workspace.yaml` and `contracts/src/ParalockHTLC.sol`, searched upward from the working directory): `/.paralock`, whatever `PARALOCK_HOME` says; 2. otherwise `$PARALOCK_HOME`, when it is set and not empty; 3. otherwise `~/.paralock`. `doctor` and `devnet status` print the directory in use. The SDK resolves it the same way (`paralockStateDir`), so the devnet helpers find the same `devnet.json`. This page writes paths relative to that directory, for example `taker/`. ## Commands | Command | What it does | |---|---| | `paralock doctor [--evm ] [--maker-port ]` | Checks prerequisites and ports, and prints a fix for each problem. | | `paralock dev [--evm ] [--maker-port ] [--web] [--web-port ] [--ths-log ]` | Everything at once: doctor, devnet, maker, and optionally the web app (from a checkout only). Reuses whatever is already running. | | `paralock devnet up [--evm ] [--maker-port ] [--ths-log ]` | Starts Zcash regtest and the EVM chains, deploys the contracts, writes `devnet.json`. | | `paralock devnet status` | The state directory, and the heights and addresses of the running devnet. | | `paralock devnet down` | Stops what Paralock started and deletes the devnet file. | | `paralock maker [--port ]` | Runs the devnet maker over HTTP (default: the devnet's maker port, 7420 unless set with `--maker-port`). | | `paralock swap --zec [options]` | Swaps ZEC for stablecoins as the devnet taker. | | `paralock pay --usd --to <0x…> [options]` | Pays an exact dollar amount from shielded ZEC. | | `paralock swaps` | Lists unfinished swaps saved in `taker/`. | | `paralock resume [--no-shield]` | Continues a saved swap after a crash or restart, then reshields change. | | `paralock refund [--no-shield]` | Refunds a saved swap's ZEC once its refund height is reached. | | `paralock --version` | Prints the version. | ### Chains `--evm ` takes a comma-separated list from `tempo`, `base`, `ethereum`, `arbitrum`, `robinhood`, `hyperevm`, or `all`. The default is `tempo,base,ethereum`. Each chain runs on its own anvil: | Chain | Port | Chain id | Stablecoin | |---|---|---|---| | `tempo` | 8545 | 31337 | OUSD stand-in (TIP-20), `anvil --network tempo` | | `base` | 8546 | 31338 | MockUSD "USDC" | | `ethereum` | 8547 | 31339 | MockUSD "USDC" | | `arbitrum` | 8548 | 31340 | MockUSD "USDC" | | `robinhood` | 8549 | 31341 | MockUSD "USDC" | | `hyperevm` | 8550 | 31342 | MockUSD "USDC" | Other local services: | Service | Address | |---|---| | Zcash RPC (Zakura regtest) | `http://127.0.0.1:18232` | | lightwalletd | `http://127.0.0.1:9067` | | ths dashboard | `http://127.0.0.1:32805` | | Maker | `http://127.0.0.1:7420` (change it with `--maker-port`) | | Web app (`dev --web`, checkout only) | `http://localhost:3000` | ## doctor ```sh npx paralock doctor [--evm ] [--maker-port ] ``` Prints the state directory, then checks, in order: Node.js 20 or newer; inside a checkout, pnpm, installed dependencies and built packages (every package has its `dist/`); the Docker daemon; ths; `anvil` 1.8 or newer and its `--network tempo` support; and the ports above for the selected chains and the maker. A port that is in use passes if the service on it is the one Paralock would start there (it will be reused). The web port is only a warning unless `dev --web` will use it. Each failed check prints a fix, for example `foundryup`, or `pnpm build` in a checkout. The exit code is 1 if a required check fails. ## dev ```sh npx paralock dev [--evm ] [--maker-port ] [--web] [--web-port ] [--ths-log ] ``` | Flag | Default | Meaning | |---|---|---| | `--evm ` | `tempo,base,ethereum` | Chains to run. | | `--maker-port ` | `7420` | Port of the maker, recorded in `devnet.json`. | | `--web` | off | Also start the web app (`next dev`). Checkout only: the web app ships with the repository, not with the CLI. Elsewhere `dev` says how to get it and starts everything else. | | `--web-port ` | `3000` | Port of the web app. Implies `--web`. | | `--ths-log ` | none | Captured `ths start` output, when ths was started outside Paralock (see [devnet up](#devnet-up)). | Runs `doctor` (and stops if a required check fails), then `devnet up`, then starts the maker in the background (`maker.pid`, log in `maker.log`) and, with `--web` in a checkout, the web app (`web.pid`, `web.log`). A healthy maker or web app that is already running is reused. A maker that `dev` started is restarted if it doesn't quote every devnet chain yet. It ends by printing the running services and the next commands to try. ```sh npx paralock dev --evm all pnpm paralock dev --evm all --web # in a checkout: the web app too ``` ## devnet up ```sh npx paralock devnet up [--evm ] [--maker-port ] [--ths-log ] ``` 1. **Zcash.** Starts ths (Zakura regtest and lightwalletd) with `ths start --no-open`, captures its output to `ths.log` and waits up to 3 minutes for it to be ready. The ths mnemonic appears only in that output. If ths is already running and `ths.log` is missing, the command fails: run `ths stop` and retry, or pass `--ths-log ` with the output of your own `ths start`. 2. **EVM chains.** Starts one anvil per chain with a 1-second block time (`anvil-.pid` and `.log`), or reuses an anvil already answering on the port with the right chain id. 3. **Contracts.** Deploys `ParalockHTLC`, `ParalockAdaptorEscrow` and the local stablecoin on each chain from the bytecode embedded in `@paralock/evm` (no Foundry project needed), as `contracts/script/Deploy.s.sol` would: the OUSD stand-in on Tempo, a MockUSD "USDC" elsewhere, minted to anvil dev accounts 0 and 1. It records them in `contracts/deployments/.json` in a checkout, or `deployments/.json` in the state directory elsewhere. Recorded contracts still live on the chain are reused. 4. **Devnet file.** Writes `devnet.json` (with the maker URL, from `--maker-port`, the previous devnet or 7420) and prints the endpoints, contract addresses, keys and ths account balances. Chains from an earlier `devnet up` that are still running stay in the file, so `devnet up --evm arbitrum` adds Arbitrum to a running devnet. | Role | Zcash (ths account) | EVM (anvil dev account) | |---|---|---| | Maker | account 5 | dev 0 | | Taker | account 1 (shielded wallet) and account 2 (swap address) | dev 1 | | Relayer | | dev 2 | The taker's savings stay shielded in account 1. Each swap unshields exactly what it needs into account 2's transparent address, which only Paralock spends from. Change and refunds go back to account 1 and are shielded again. ## devnet status and devnet down ```sh npx paralock devnet status npx paralock devnet down ``` `status` prints the state directory, the Zcash regtest height and, per chain, the RPC, block height, contract addresses, quote token and the block event scans start from. `down` stops the maker and web app started by `dev`, runs `ths stop`, stops the anvils Paralock started, and deletes `devnet.json` and `ths.log`. Processes Paralock did not start are left running. The swap stores (`taker/`, `maker/`) and `recipients.jsonl` are kept. ## maker ```sh npx paralock maker [--port ] ``` Runs the devnet maker over HTTP with [`makerHandler`](https://paralock.xyz/docs/sdk#makerhandler), for every devnet chain and both modes, on `--port` or else the devnet's maker port (7420 unless `devnet up` or `dev` set another with `--maker-port`). It: - persists quotes, swaps and per-swap keys in `maker/`, so a restarted maker resumes every unfinished swap; - mines a Zcash regtest block every 3 seconds (regtest has no miners); - uses `DEVNET_POLICY` (40-block Zcash window, 45-second EVM lock), a 50 bps spread, and the CoinGecko price with a fixed $1,270 fallback (devnet only); - quotes 0.0002 to 5 ZEC (20,000 to 500,000,000 zat), keeps quotes for 120 seconds and handles up to 25 swaps at once; - shields the ZEC it claims back into its shielded balance; - allows CORS from any origin and caps request bodies at 16 KiB. `Ctrl-C` (or `SIGTERM`) stops it cleanly. ## swap ```sh npx paralock swap --zec [options] ``` Swaps ZEC from the devnet taker's wallet for the stablecoin on a chain. The maker must be running. | Flag | Default | Meaning | |---|---|---| | `--zec ` | required | ZEC to sell, in decimal ZEC (`0.5`), converted to zatoshi. | | `--chain ` | `tempo` | Where to receive the stablecoins. Must be a chain of the running devnet. | | `--private` | off | Adaptor-signature mode: no hash on either chain. | | `--fresh-recipient` | off | Receive at a new address created for this swap. Its key is appended to `recipients.jsonl`. | | `--relay` | off | Let the relayer (anvil dev account 2) submit the claim, so the recipient needs no gas. | | `--standard-only` | off | Only allow 0.1, 0.5, 1 or 5 ZEC. | | `--jitter ` | none | Random delay of up to this many milliseconds before claiming. | | `--no-shield` | off | Don't unshield first or reshield after. The faucet funds the swap address directly. | | `--refund-demo` | off | Lock ZEC and let the maker vanish, then refund after the Zcash timeout. | What it does: gets a validated quote and prints it (amounts, rate, mode, both lock windows); unshields the amount plus fees from the taker's shielded balance into the swap address (topping up from the faucet if needed); runs the swap, printing each step; then shields leftover change again. If the swap fails after the ZEC is locked, it waits for the refund height, refunds, and exits with code 1. The swap is saved in `taker/`, so `paralock refund ` also works after a restart. ```sh npx paralock swap --zec 1 # ZEC to OUSD on Tempo (htlc mode) npx paralock swap --zec 1 --chain base --private # ZEC to USDC on Base, no hash on either chain npx paralock swap --zec 0.5 --fresh-recipient --relay --standard-only npx paralock swap --zec 0.5 --refund-demo # the maker never locks; refund after the timeout ``` See [Privacy](https://paralock.xyz/docs/privacy) for what each privacy flag hides. ## pay ```sh npx paralock pay --usd --to <0x…> [options] ``` Pays someone an exact dollar amount from shielded ZEC: an exact-out quote, so the recipient gets exactly `--usd` and the ZEC amount rounds up. | Flag | Default | Meaning | |---|---|---| | `--usd ` | required | Dollars to deliver, in decimal (`42.50`), converted to 6-decimal token units. | | `--to <0x…>` | required | The recipient's EVM address. | | `--chain ` | `tempo` | Chain to pay on. | | `--private` | off | Adaptor-signature mode. | | `--relay` | off | Let the relayer submit the claim. | | `--label ` | none | A label for the payment, such as a merchant name. | | `--no-shield` | off | Don't unshield first or reshield after. | ```sh npx paralock pay --usd 25 --to 0xShop… --chain base --label "Acme Coffee" npx paralock pay --usd 42.50 --to 0xShop… --chain tempo --private --relay ``` See [Payments and payment links](https://paralock.xyz/docs/pay). ## swaps, resume and refund ```sh npx paralock swaps npx paralock resume [--no-shield] npx paralock refund [--no-shield] ``` | Command | Behavior | |---|---| | `swaps` | Lists unfinished swaps in `taker/` (their ZEC may still be locked): id, mode, status, amount, chain and refund block. In a checkout the web app shares this store, so swaps started there appear too. | | `resume ` | Calls `taker.resume(id, { claim: true })`: claims if the maker's lock is there and still safe to claim, then follows the maker's ZEC claim. A funding that never reached the network is broadcast late only if the maker committed to it, it is at least 5 blocks from its expiry and the maker still holds the swap; otherwise the swap is marked abandoned. Then shields change and refunds again, unless `--no-shield`. | | `refund ` | Calls `taker.refund(id)`: waits for the refund height (mining regtest blocks), broadcasts the refund and prints its txid. Then shields the refunded ZEC, unless `--no-shield`. | The swap id is the hashlock (htlc mode) or the quote id (adaptor mode); `swaps` prints it. See [Persistence and recovery](https://paralock.xyz/docs/recovery). ## Files in the state directory The [state directory](#state-directory) holds the ths mnemonic, development keys and fresh-recipient keys: keep it private and never commit it. In a checkout it is `.paralock/`, which is gitignored. | Path | Written by | Contents | |---|---|---| | `devnet.json` | `devnet up` | Endpoints, contract addresses, quote tokens, start blocks, the maker URL, the ths mnemonic and the dev keys. Read by the SDK's `loadDevnetFile`. | | `ths.log` | `devnet up` | Captured `ths start` output, including the mnemonic. | | `anvil-.pid`, `anvil-.log` | `devnet up` | Each anvil Paralock started. | | `maker.pid`, `maker.log`, `web.pid`, `web.log` | `dev` | The maker and web app `dev` started in the background. | | `maker/` | `maker` | The maker's `FileSwapStore`: quotes, swaps and per-swap keys. | | `taker/` | `swap`, `pay`, `swaps`, `resume`, `refund`, the web app | The taker's `FileSwapStore`: secrets, keys and refund data. | | `recipients.jsonl` | `swap --fresh-recipient`, the web app | One line per fresh recipient: address, private key, swap id, chain, time. | | `deployments/.json` | `devnet up`, outside a checkout | The local chains' contracts. In a checkout they go to `contracts/deployments/.json` instead, for the local chain ids 31337 to 31342. | --- # Contracts and deployments Source: https://paralock.xyz/docs/contracts Markdown: https://paralock.xyz/docs/contracts.md Section: Reference > Reference for ParalockHTLC and ParalockAdaptorEscrow: storage model, functions, events, errors, security properties, token support and testnet deployments. Paralock's EVM leg is two small escrow contracts. Each holds a maker's stablecoins for a taker until the swap settles one way or the other: - **`ParalockHTLC`** (htlc mode): a sha256 hash-time-locked escrow. It pairs with a transparent P2SH HTLC on Zcash that uses the same hashlock. - **`ParalockAdaptorEscrow`** (adaptor mode): released by an ECDSA signature from a one-time `signer` over `claimDigest(id)`. No hashlock on-chain, so nothing links the two legs. The completed adaptor signature `(r, s)` published in `Claimed` gives the maker the secret for the Zcash side. Both work with TIP-20 stablecoins on Tempo and standard ERC-20s elsewhere. They have no owner, admin, pause switch or upgrade path. The TypeScript clients are in [@paralock/evm](https://paralock.xyz/docs/evm). > **Warning:** Experimental and not audited by a third party. Deployed on testnets only. Don't lock real funds. ## Storage model Each contract writes one storage slot per swap. Tempo charges about 250k gas for every new slot (TIP-1000), so nothing else is stored. | Contract | Key | Value | |---|---|---| | `ParalockHTLC` | `hashlock` | `keccak256(abi.encode(swap))` while active, then `SETTLED` (`bytes32(uint256(1))`) forever. `0` if never used. | | `ParalockAdaptorEscrow` | `id = keccak256(abi.encode(swap))` | `Status`: `0` empty, `1` active, `2` settled forever. | Callers pass the full `Swap` struct back to `claim` and `refund`. The contract recomputes the commitment or id, so changing any field addresses a different swap and fails. The `Locked` event carries every field, so a watcher can rebuild the struct from the log alone (the [@paralock/evm](https://paralock.xyz/docs/evm) clients do this). ## ParalockHTLC ```solidity struct Swap { bytes32 hashlock; // sha256 of the 32-byte secret; unique key of the swap address token; // TIP-20 or ERC-20 held in escrow address sender; // locks the funds; refunded after expiry (the maker) address recipient; // paid on claim (the taker, or a payee) uint256 amount; // token base units uint64 expiry; // Unix seconds from which the swap can only be refunded } enum Status { Empty, Active, Settled } ``` ### Functions (HTLC) | Function | Behavior | |---|---| | `lock(Swap calldata s)` | Locks `s.amount` of `s.token` under `s.hashlock`. The caller must be `s.sender` and must have approved the contract for at least `s.amount`. `s.expiry` must be in the future. | | `claim(Swap calldata s, bytes32 preimage)` | Pays `s.recipient` when `sha256(preimage) == s.hashlock`. Callable by anyone before `s.expiry`. Publishes the preimage in `Claimed`. | | `refund(Swap calldata s)` | Returns the funds to `s.sender`. Callable by anyone from `s.expiry` on. | | `stateOf(bytes32 hashlock) returns (bytes32)` | Raw state: `0`, the commitment, or `SETTLED`. | | `statusOf(bytes32 hashlock) returns (Status)` | Lifecycle status. | | `isActive(bytes32 hashlock) returns (bool)` | True while locked and not yet claimed or refunded. | | `commitment(Swap calldata s) returns (bytes32)` | `keccak256(abi.encode(s))`: the value stored while active. | | `SETTLED() returns (bytes32)` | The settled sentinel, `bytes32(uint256(1))`. | ### Events (HTLC) | Event | When | |---|---| | `Locked(bytes32 indexed hashlock, address indexed sender, address indexed recipient, address token, uint256 amount, uint64 expiry)` | Funds were locked. | | `Claimed(bytes32 indexed hashlock, bytes32 preimage)` | The recipient was paid. `preimage` is the secret that unlocks the Zcash leg. | | `Refunded(bytes32 indexed hashlock)` | The sender was refunded. | ### Errors (HTLC) | Error | Cause | |---|---| | `NotSender()` | `msg.sender` is not `s.sender` (lock). | | `InvalidHashlock()` | The hashlock is zero. | | `InvalidAmount()` | The amount is zero. | | `InvalidRecipient()` | The recipient is the zero address. | | `InvalidExpiry()` | The expiry is not in the future. | | `HashlockUsed(bytes32 hashlock)` | The hashlock was already used by an active or settled swap. | | `SwapNotFound(bytes32 hashlock)` | No swap was ever locked under this hashlock. | | `SwapSettled(bytes32 hashlock)` | Already claimed or refunded. | | `SwapMismatch(bytes32 hashlock)` | The provided parameters don't match the locked swap. | | `InvalidPreimage()` | `sha256(preimage)` is not the hashlock. | | `SwapExpired(uint64 expiry)` | Claim at or after the expiry. | | `SwapNotExpired(uint64 expiry)` | Refund before the expiry. | | `TokenTransferFailed(address token)` | The token call failed without a reason, or returned false. | | `UnsupportedToken(address token)` | The escrow received a different amount than requested (fee-on-transfer or rebasing token). | ## ParalockAdaptorEscrow ```solidity struct Swap { address token; // TIP-20 or ERC-20 held in escrow address sender; // locks the funds; refunded after expiry (the maker) address recipient; // paid on claim address signer; // whose signature over claimDigest(id) releases the funds uint256 amount; // token base units uint64 expiry; // Unix seconds from which the swap can only be refunded bytes32 salt; // random: makes the id unique and unlinkable } enum Status { Empty, Active, Settled } ``` ### Functions (adaptor escrow) | Function | Behavior | |---|---| | `lock(Swap calldata s) returns (bytes32 id)` | Locks `s.amount` of `s.token` for `s.recipient` and returns `id = keccak256(abi.encode(s))`. The caller must be `s.sender` and must have approved the contract. `s.signer` must be non-zero; `s.salt` should be random. | | `claim(Swap calldata s, uint8 v, bytes32 r, bytes32 sigS)` | Pays `s.recipient` with `s.signer`'s signature over `claimDigest(id)`. Callable by anyone (for example a relayer) before `s.expiry`. Publishes `(v, r, s)` in `Claimed`. | | `refund(Swap calldata s)` | Returns the funds to `s.sender`. Callable by anyone from `s.expiry` on. | | `claimDigest(bytes32 id) returns (bytes32)` | `keccak256(abi.encode(CLAIM_TYPEHASH, block.chainid, address(this), id))`: the raw digest the signer signs, with no EIP-191 prefix. | | `idOf(Swap calldata s) returns (bytes32)` | `keccak256(abi.encode(s))`. | | `statusOf(bytes32 id) returns (Status)` | Lifecycle status. | | `isActive(bytes32 id) returns (bool)` | True while locked and not yet claimed or refunded. | | `CLAIM_TYPEHASH() returns (bytes32)` | `keccak256("ParalockAdaptorClaim")`, the digest's domain tag. | ### Events (adaptor escrow) | Event | When | |---|---| | `Locked(bytes32 indexed id, address indexed sender, address indexed recipient, address token, address signer, uint256 amount, uint64 expiry, bytes32 salt)` | Funds were locked. | | `Claimed(bytes32 indexed id, uint8 v, bytes32 r, bytes32 s)` | The recipient was paid. `(r, s)` is the completed adaptor signature, from which the maker extracts the adaptor secret. | | `Refunded(bytes32 indexed id)` | The sender was refunded. | ### Errors (adaptor escrow) | Error | Cause | |---|---| | `NotSender()` | `msg.sender` is not `s.sender` (lock). | | `InvalidAmount()` | The amount is zero. | | `InvalidRecipient()` | The recipient is the zero address. | | `InvalidSigner()` | The signer is the zero address. | | `InvalidExpiry()` | The expiry is not in the future. | | `SwapExists(bytes32 id)` | A swap with this id was already locked (active or settled). | | `SwapNotFound(bytes32 id)` | No swap was ever locked under this id (unknown or tampered parameters). | | `SwapSettled(bytes32 id)` | Already claimed or refunded. | | `SwapExpired(uint64 expiry)` | Claim at or after the expiry. | | `SwapNotExpired(uint64 expiry)` | Refund before the expiry. | | `InvalidSignature()` | The signature does not recover to `s.signer`. | | `MalleableSignature()` | `s` is in the upper half of the curve order, or `v` is not 27 or 28. | | `TokenTransferFailed(address token)` | The token call failed without a reason, or returned false. | | `UnsupportedToken(address token)` | The escrow received a different amount than requested. | ## Security properties - **Single-use ids.** A hashlock or escrow id is marked settled forever after a claim or refund, and can never be locked again (`HashlockUsed`, `SwapExists`). In htlc mode this matters: the preimage is public once claimed, so re-locking under it would let anyone take the funds. - **Recipient fixed at lock time.** Anyone may submit `claim` or `refund`, so relayers and watchtowers can settle on a party's behalf, but funds only ever go to `s.recipient` (claim) or `s.sender` (refund). - **Tamper-proof parameters.** The stored commitment (HTLC) or the id itself (adaptor escrow) covers every field of the swap. Changing any field fails with `SwapMismatch` or `SwapNotFound`. - **Expiry rules.** `lock` needs `expiry > block.timestamp`. `claim` works only while `block.timestamp < expiry`; `refund` only when `block.timestamp >= expiry`. The two windows never overlap. - **Canonical signatures (adaptor escrow).** The claim signature must have `v` in {27, 28} and a low `s`, so the published `(r, s)` is exactly the completed adaptor signature and can't be swapped for its malleated twin. The digest binds the chain id and the contract address, so a signature never replays elsewhere. `ecrecover`'s zero-address failure value can't match, because `signer` is never zero. - **Checks, effects, interactions.** State is updated and the event emitted before any token transfer. Token reverts are bubbled up (for example TIP-20 `InsufficientAllowance`). - **No privileged roles.** No owner, admin, pause or upgrade. The protocol around the contracts (window ordering, verify before revealing) is described in [Security model](https://paralock.xyz/docs/security). ## Token support | Token type | Detection | Transfers | |---|---|---| | TIP-20 (Tempo) | Address starts with Tempo's reserved prefix `0x20c000000000000000000000` (no external call) | `transferFromWithMemo` on lock and `transferWithMemo` on claim and refund, with the hashlock (HTLC) or id (adaptor escrow) as memo, so explorers can link every movement to its swap. | | ERC-20 (other chains) | Any other address | `transferFrom` and `transfer` with SafeERC20-style checks: a `false` return reverts, and empty return data is accepted only from a contract. The lock checks the escrow's balance delta, so fee-on-transfer tokens revert with `UnsupportedToken`. Rebasing tokens are not supported. | `MockUSD` is a 6-decimal test token (symbol `USDC`) that only its deployer can mint. The devnet deploys it on its local plain-EVM chains. ### Gas Measured on local chains (anvil): | Call | `ParalockHTLC`, Tempo | `ParalockAdaptorEscrow`, Tempo | Plain EVM (MockUSD) | |---|---|---|---| | `lock` | about 305,000 (250k is the new slot) | about 317,000 | about 88,000 to 93,000 | | `claim` | about 56,000 to 61,000 | about 66,000 | about 49,000 (66,000 when the recipient's balance slot is new) | | `refund` | about 54,500 | about 60,000 | about 43,000 | On Tempo an account's first transaction costs about 250k more (a new nonce slot). ## Deployments | Network | Chain ID | ParalockHTLC | ParalockAdaptorEscrow | Quote token | Start block | |---|---|---|---|---|---| | Tempo Testnet (Moderato) | 42431 | [`0xD9B278625B5946B8CD15dad6c0c776095B8D0513`](https://explore.testnet.tempo.xyz/address/0xD9B278625B5946B8CD15dad6c0c776095B8D0513) ([source](https://explore.testnet.tempo.xyz/address/0xD9B278625B5946B8CD15dad6c0c776095B8D0513)) | [`0xd2f352Fa313d23b3536dAA3d783263C03CED2673`](https://explore.testnet.tempo.xyz/address/0xd2f352Fa313d23b3536dAA3d783263C03CED2673) ([source](https://explore.testnet.tempo.xyz/address/0xd2f352Fa313d23b3536dAA3d783263C03CED2673)) | OUSD [`0x20c0000000000000000000006a37DA5C996874BE`](https://explore.testnet.tempo.xyz/address/0x20c0000000000000000000006a37DA5C996874BE) | 39235852 | | Base Sepolia | 84532 | [`0xD9B278625B5946B8CD15dad6c0c776095B8D0513`](https://sepolia.basescan.org/address/0xD9B278625B5946B8CD15dad6c0c776095B8D0513) ([source](https://repo.sourcify.dev/84532/0xD9B278625B5946B8CD15dad6c0c776095B8D0513)) | [`0xd2f352Fa313d23b3536dAA3d783263C03CED2673`](https://sepolia.basescan.org/address/0xd2f352Fa313d23b3536dAA3d783263C03CED2673) ([source](https://repo.sourcify.dev/84532/0xd2f352Fa313d23b3536dAA3d783263C03CED2673)) | USDC [`0x036CbD53842c5426634e7929541eC2318f3dCF7e`](https://sepolia.basescan.org/address/0x036CbD53842c5426634e7929541eC2318f3dCF7e) | 48009147 | | Sepolia | 11155111 | [`0x9a6f3F47423f590afd1Df06E2729057b10baB1a1`](https://sepolia.etherscan.io/address/0x9a6f3F47423f590afd1Df06E2729057b10baB1a1) ([source](https://repo.sourcify.dev/11155111/0x9a6f3F47423f590afd1Df06E2729057b10baB1a1)) | [`0xf44bc4Cc4B4b6b94E4142Bb403cCeEa82AFd55B7`](https://sepolia.etherscan.io/address/0xf44bc4Cc4B4b6b94E4142Bb403cCeEa82AFd55B7) ([source](https://repo.sourcify.dev/11155111/0xf44bc4Cc4B4b6b94E4142Bb403cCeEa82AFd55B7)) | USDC [`0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238`](https://sepolia.etherscan.io/address/0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238) | 11897116 | | Arbitrum Sepolia | 421614 | [`0xD9B278625B5946B8CD15dad6c0c776095B8D0513`](https://sepolia.arbiscan.io/address/0xD9B278625B5946B8CD15dad6c0c776095B8D0513) ([source](https://repo.sourcify.dev/421614/0xD9B278625B5946B8CD15dad6c0c776095B8D0513)) | [`0xd2f352Fa313d23b3536dAA3d783263C03CED2673`](https://sepolia.arbiscan.io/address/0xd2f352Fa313d23b3536dAA3d783263C03CED2673) ([source](https://repo.sourcify.dev/421614/0xd2f352Fa313d23b3536dAA3d783263C03CED2673)) | USDC [`0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d`](https://sepolia.arbiscan.io/address/0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d) | 318328857 | | Robinhood Chain Testnet | 46630 | [`0x9a6f3F47423f590afd1Df06E2729057b10baB1a1`](https://explorer.testnet.chain.robinhood.com/address/0x9a6f3F47423f590afd1Df06E2729057b10baB1a1) ([source](https://repo.sourcify.dev/46630/0x9a6f3F47423f590afd1Df06E2729057b10baB1a1)) | [`0xf44bc4Cc4B4b6b94E4142Bb403cCeEa82AFd55B7`](https://explorer.testnet.chain.robinhood.com/address/0xf44bc4Cc4B4b6b94E4142Bb403cCeEa82AFd55B7) ([source](https://repo.sourcify.dev/46630/0xf44bc4Cc4B4b6b94E4142Bb403cCeEa82AFd55B7)) | USDC (MockUSD test token) [`0xD9B278625B5946B8CD15dad6c0c776095B8D0513`](https://explorer.testnet.chain.robinhood.com/address/0xD9B278625B5946B8CD15dad6c0c776095B8D0513) ([source](https://repo.sourcify.dev/46630/0xD9B278625B5946B8CD15dad6c0c776095B8D0513)) | 133451919 | | HyperEVM Testnet | 998 | `0xD9B278625B5946B8CD15dad6c0c776095B8D0513` ([source](https://repo.sourcify.dev/998/0xD9B278625B5946B8CD15dad6c0c776095B8D0513)) | `0xd2f352Fa313d23b3536dAA3d783263C03CED2673` ([source](https://repo.sourcify.dev/998/0xd2f352Fa313d23b3536dAA3d783263C03CED2673)) | USDC `0x2B3370eE501B4a559b57D449569354196457D8Ab` | 66684352 | Source verified: exact bytecode match on Sourcify (Tempo: Tempo's contract verifier). The Solidity source is in [`contracts/src`](https://github.com/bitfalt/paralock/tree/main/contracts/src). - **Same addresses on most chains.** Contract addresses come from the deployer's address and nonce. The deployer's nonces matched on most testnets, so `ParalockHTLC` and `ParalockAdaptorEscrow` have the same addresses there. - **Sepolia and Robinhood Chain Testnet differ.** On Sepolia a failed first deployment used up nonces. On Robinhood Chain Testnet a MockUSD token had to be deployed first. Both contracts therefore landed at other addresses on these two chains. - **Robinhood Chain Testnet uses MockUSD.** The chain has no USDC, so the deployment uses a MockUSD test token (6 decimals), listed as `USDC` in its deployment file. The SDK's network registry lists no stablecoin for this chain: pass the token in the taker's `tokens` option. - **Use `startBlock`.** Each `contracts/deployments/.json` records `startBlock`, the block event scans start from. Pass it as `fromBlock` to the SDK and the clients. Deployment files have this shape: ```json { "chain": "base", "chainId": 84532, "htlc": "0x…", "adaptorEscrow": "0x…", "deployer": "0x…", "quoteToken": "USDC", "startBlock": 48009147, "tokens": { "USDC": "0x036CbD53842c5426634e7929541eC2318f3dCF7e" } } ``` ## Deploy it yourself The contracts are a Foundry project in `contracts/`. Build and test them first: ```sh cd contracts forge build forge test # 146 tests: ERC-20, MockUSD and in-process TIP-20 suites ``` `TEMPO_FORK_URL=http://localhost:8545 forge test` also runs the HTLC suite against a live Tempo node; without it that fork suite is skipped. `script/Deploy.s.sol` deploys both contracts and writes `deployments/.json`. It is idempotent: contracts recorded in an existing file are reused while the chain still holds exactly their current bytecode. | Variable | Meaning | |---|---| | `PRIVATE_KEY` | Deployer key. Required on public networks (local chains default to anvil dev account 0). | | `USDC` | The stablecoin to record on non-Tempo chains. On Tempo the script records OUSD. | | `FOUNDRY_NETWORK` | Set `FOUNDRY_NETWORK=ethereum` for every non-Tempo chain: `foundry.toml` defaults to Tempo's EVM. | | `PARALOCK_EVM_CHAIN` | Override the chain name (`tempo`, `base`, `ethereum`, `arbitrum`, `robinhood`, `hyperevm`) derived from the chain id. | ```sh # Tempo Moderato: fees paid in pathUSD PRIVATE_KEY=0x… forge script script/Deploy.s.sol --rpc-url moderato --broadcast --tempo.fee-token PathUSD # Base Sepolia (any non-Tempo chain) PRIVATE_KEY=0x… USDC=0x036CbD53842c5426634e7929541eC2318f3dCF7e FOUNDRY_NETWORK=ethereum \ forge script script/Deploy.s.sol --rpc-url https://sepolia.base.org --broadcast # Sepolia prices contract creation far above forge's local simulation: skip it PRIVATE_KEY=0x… USDC=0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238 FOUNDRY_NETWORK=ethereum \ forge script script/Deploy.s.sol --rpc-url "$SEPOLIA_RPC_URL" --broadcast --skip-simulation ``` > **Note:** On Arbitrum-based chains (Arbitrum, Robinhood Chain) `block.number` inside the script is the L1 block. Replace `startBlock` in the written file with the L2 block from the broadcast receipts. Verify the source on Sourcify (non-Tempo chains need `FOUNDRY_NETWORK=ethereum` here too): ```sh FOUNDRY_NETWORK=ethereum forge verify-contract
src/ParalockHTLC.sol:ParalockHTLC \ --verifier sourcify --chain-id FOUNDRY_NETWORK=ethereum forge verify-contract
src/ParalockAdaptorEscrow.sol:ParalockAdaptorEscrow \ --verifier sourcify --chain-id ``` After changing a contract, regenerate the TypeScript ABIs with `pnpm --filter @paralock/evm generate:abi`. For local chains, [`paralock devnet up`](https://paralock.xyz/docs/cli#devnet-up) runs the deployment for you. --- # Rust SDK Source: https://paralock.xyz/docs/rust Markdown: https://paralock.xyz/docs/rust.md Section: Rust > The four Rust crates on crates.io (paralock-core, paralock-evm, the paralock SDK and the paralock-cli binary), with install, feature flags, a taker, a maker embedded in axum, the trust model, interop with TypeScript and the minimum Rust version. Paralock's protocol is also published in Rust, as four crates on [crates.io](https://crates.io/crates/paralock) (version 0.1). With them a Rust service can embed a taker or a market maker without a Node.js process. The engines are a port of `@paralock/sdk` (protocol v1.1) and speak the same wire protocol, so a Rust taker swaps with a TypeScript maker, a TypeScript taker with a Rust maker, in both modes. > **Warning:** The crates are experimental. The protocol core, the EVM layer and the SDK went through internal security reviews before their first release, and every finding was fixed with a regression test, but none of the crates has been audited by a third party. The escrows run on public testnets only, and in both modes the Zcash leg is a transparent output. ## The crates | Crate | What it is | Docs | Rust | |---|---|---|---| | [`paralock-core`](https://crates.io/crates/paralock-core) | The protocol core: Zcash scripts and v5 transactions, ZIP 244 signature hashes, ZIP 317 fees, ECDSA adaptor signatures with DLEQ proofs, EVM escrow ids and claim digests, the wire messages and both parties' composite safety checks. Pure and synchronous (no I/O, no clock, no async), and it builds for `wasm32-unknown-unknown` | [docs.rs](https://docs.rs/paralock-core) | 1.85 | | [`paralock-evm`](https://crates.io/crates/paralock-evm) | The EVM layer on [alloy](https://alloy.rs) 2.x: clients for `ParalockHTLC` and `ParalockAdaptorEscrow`, a send pipeline with fee bumps and transaction status, Tempo fee tokens through `tempo-alloy`, escrow code verification, the verified network registry with Paralock's testnet deployments, and a deploy helper for local chains | [docs.rs](https://docs.rs/paralock-evm) | 1.95 | | [`paralock`](https://crates.io/crates/paralock) | The SDK: the `Taker` and `Maker` engines, Zcash backends (`ZcashRpc` for Zebra or Zakura, `Lightwalletd`), durable stores (`FileStore`, `MemoryStore`), the maker HTTP server (axum) and client, and a price feed | [docs.rs](https://docs.rs/paralock) | 1.95 | | [`paralock-cli`](https://crates.io/crates/paralock-cli) | The standalone `paralock` binary: `doctor`, `quote`, `swap`, `pay`, `swaps`, `resume`, `refund` and `maker`. See [Rust CLI](https://paralock.xyz/docs/rust-cli) | [docs.rs](https://docs.rs/paralock-cli) | 1.95 | Each crate builds on the one before it: `paralock-core` ← `paralock-evm` ← `paralock` ← `paralock-cli`. Every id, digest and safety check comes from `paralock-core`, which is checked byte for byte against the same cross-language vectors (`spec/vectors`) as the TypeScript packages. Which one you need: - **A wallet, an app or another language binding** that builds and checks the locks itself: `paralock-core`. - **A Rust service that swaps or runs a maker:** `paralock` with the `evm` feature. - **A terminal, a script or a maker without writing code:** the [`paralock` binary](https://paralock.xyz/docs/rust-cli). ## Install **cargo add**: ```sh cargo add paralock --features evm,lightwalletd,price-feed # a taker that reaches Zcash through lightwalletd cargo add paralock --features evm,server,price-feed # a maker served with axum cargo add tokio --features macros,rt-multi-thread,net ``` **Cargo.toml** (`Cargo.toml`): ```toml [dependencies] paralock = { version = "0.1", features = ["evm", "server", "price-feed"] } tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] } ``` **Core only**: ```sh cargo add paralock-core # with the OS random number generator cargo add paralock-core --no-default-features # without the OS RNG (wasm32): pass your own ``` The engines need a Tokio runtime. The `lightwalletd` feature reaches Zcash through a lightwalletd or Zaino server instead of a full node. ### Feature flags | Crate | Feature | Default | What it adds | |---|---|---|---| | `paralock` | `client` | yes | `HttpMakerApi`: talk to any Paralock maker over HTTP. Responses go through `paralock-core`'s strict parsers | | `paralock` | `tempo` | yes | With `evm`: Tempo transactions that pay gas in a chosen TIP-20 (`EvmChainOptions::fee_token`). Turn default features off to drop `tempo-alloy`; Tempo then uses plain EIP-1559 transactions | | `paralock` | `evm` | | `paralock-evm` clients for both escrows and the `create_taker` / `create_maker` builders that connect to RPC URLs | | `paralock` | `server` | | `maker_router` and `serve`: an axum `Router` with exactly the protocol's routes and JSON | | `paralock` | `lightwalletd` | | `Lightwalletd`: a `ZcashNode` over lightwalletd or Zaino gRPC (tonic, rustls) | | `paralock` | `price-feed` | | `CoinGecko`: a cached USD/ZEC price with bounded staleness | | `paralock-evm` | `tempo` | yes | Tempo `0x76` transactions with a fee token, through `tempo-alloy` | | `paralock-core` | `std` | yes | The OS random number generator (`paralock_core::OsRng`) and k256's precomputed tables. Without it the crate builds for `wasm32-unknown-unknown` | Always included in `paralock`: the `Taker` and `Maker` engines, `ZcashRpc` (JSON-RPC over rustls), `MemoryStore` and `FileStore`. ## A taker The builders take the same options as the TypeScript factories. This taker sells 0.1 ZEC for USDC on Base Sepolia in private mode, through a public lightwalletd server (features `evm`, `lightwalletd` and `price-feed`): ```rust use std::sync::Arc; use paralock::builder::*; use paralock::paralock_evm::testnet_deployment; use paralock::{CoinGecko, EvmChain, Hex, Network, SwapMode, SwapOptions, TakerPriceCheck}; #[tokio::main] async fn main() -> Result<(), Box> { // The transparent key that funds swaps, and a Zcash backend: a public lightwalletd server here, so there is no // node to run. For real value, use your own node (see "Trust model"). let zcash = ZcashOptions::new( Network::Testnet, ZcashBackend::Lightwalletd { url: "testnet.zec.rocks:443".into() }, std::env::var("ZEC_KEY")?, ); // Paralock's escrows on Base Sepolia, from paralock-evm's verified registry. let d = testnet_deployment(84532).ok_or("no Base Sepolia deployment")?; let htlc = Hex::from_bytes(d.htlc.as_slice()); let mut base = EvmChainOptions::new("https://sepolia.base.org", 84532, htlc, std::env::var("EVM_KEY")?); base.adaptor_escrow = Some(Hex::from_bytes(d.adaptor_escrow.as_slice())); // enables private mode base.from_block = Some(d.start_block); // event scans start at the deployment block // base.verify_rpc_url = Some("https://…".into()); // a second endpoint: both must report the same lock let options = CreateTakerOptions::new( zcash, MakerEndpoint::Url("https://maker.example".into()), StoreOption::Dir("./paralock-taker".into()), // secrets are persisted here before anything is broadcast TakerPriceCheck::Source(Arc::new(CoinGecko::new()?)), // refuses quotes beyond 2 % slippage ) // No tokens listed: the chain's known stablecoins (USDC on Base Sepolia). .with_chain(EvmChain::Base, TakerEvmChainOptions::new(base, vec![])); let taker = create_taker(options).await?; let quote = taker.quote(10_000_000, EvmChain::Base, SwapMode::Adaptor).await?; // 0.1 ZEC, private mode let swap = taker.swap("e, SwapOptions::default()).await?; println!("{} {:?}", swap.id, swap.status); Ok(()) } ``` - **Amounts are integers in base units:** `u64` zatoshi for ZEC (`10_000_000` is 0.1 ZEC) and `u128` token units with 6 decimals for dollars. - **`quote` checks the quote** against what you asked for (amount, chain, mode), the maker's key, the chain id, the token, the windows and your price. The rate check allows the maker's fixed Zcash claim fee on top of the slippage (`TakerLimits::maker_fee_zat`, 10,000 zat). - **`swap` verifies before it reveals.** It re-checks the maker's lock right before claiming (through the second endpoint too, when set) and simulates the claim first, because a claim that reverts still publishes the secret. - **To pay someone else,** quote exact-out and set the recipient: `taker.quote_exact_out(25_000_000, EvmChain::Base, SwapMode::Adaptor)`, then `SwapOptions { recipient: Some(…), label: Some("Acme Coffee".into()), ..Default::default() }`. If a swap fails after the ZEC was locked, the error carries the persisted swap (`err.failed_swap()`). After a crash, the store has everything needed to finish or refund: ```rust use paralock::ResumeOptions; async fn recover(taker: ¶lock::Taker) -> paralock::Result<()> { for swap in taker.pending_swaps().await? { // Claims if the maker's lock is there and still safe to claim; follows a claim sent before a crash. if taker.resume(&swap.id, ResumeOptions::default()).await.is_err() { taker.refund(&swap.id, true).await?; // waits for the refund height, then returns the ZEC } } Ok(()) } ``` ## A maker embedded in axum `create_maker` plus `paralock::serve` is a complete maker. It quotes from your price feed, locks only what it verified, and settles every swap it commits to: ```rust use std::sync::Arc; use paralock::builder::*; use paralock::paralock_evm::testnet_deployment; use paralock::{CoinGecko, CorsOrigins, EvmChain, Hex, Network, ServerOptions}; #[tokio::main] async fn main() -> Result<(), Box> { // The key that claims htlc swaps, and your own full node: a maker locks stablecoins on what it reports. let zcash = ZcashOptions::new( Network::Testnet, ZcashBackend::Rpc { url: "http://127.0.0.1:18232".into(), auth: None }, std::env::var("ZEC_KEY")?, ); let d = testnet_deployment(84532).ok_or("no Base Sepolia deployment")?; let mut base = EvmChainOptions::new("https://sepolia.base.org", 84532, Hex::from_bytes(d.htlc.as_slice()), std::env::var("EVM_KEY")?); base.adaptor_escrow = Some(Hex::from_bytes(d.adaptor_escrow.as_slice())); base.from_block = Some(d.start_block); let usdc = Hex::from_bytes(d.token("USDC").ok_or("no USDC")?.as_slice()); let store = StoreOption::Dir("./paralock-maker".into()); let mut options = CreateMakerOptions::new(zcash, Arc::new(CoinGecko::new()?), store) .with_chain(EvmChain::Base, MakerEvmChainOptions::new(base, usdc, "USDC")); options.spread_bps = Some(50.0); // policy and limits: MAINNET_POLICY and DEFAULT_MAKER_LIMITS unless set let maker = create_maker(options).await?; maker.start().await?; // resumes every unfinished swap // ServerOptions::default() has the limits for the open internet on. Put TLS in front (a reverse proxy). let server = ServerOptions { cors: Some(CorsOrigins::Any), ..ServerOptions::default() }; let listener = tokio::net::TcpListener::bind("127.0.0.1:7420").await?; paralock::serve(listener, maker.clone(), server).await?; Ok(()) } ``` To mount the protocol inside your own axum app, nest `maker_router`. The timeout, concurrency and rate limits travel with it; the rate limit needs the client's address, so serve the app with connect info (or set `client_address` behind a proxy): ```rust use std::net::SocketAddr; use paralock::{RateLimit, ServerOptions, maker_router}; async fn mount(maker: paralock::Maker) -> std::io::Result<()> { let options = ServerOptions { rate_limit: Some(RateLimit { per_minute: 60, burst: 20 }), ..ServerOptions::default() }; let app = axum::Router::new().nest_service("/paralock", maker_router(maker, options)); let listener = tokio::net::TcpListener::bind("127.0.0.1:7420").await?; // The per-client rate limit needs the peer address: serve with connect info. axum::serve(listener, app.into_make_service_with_connect_info::()).await } ``` Takers then use `https://host/paralock` as the maker URL. The router serves the same routes as [`makerHandler`](https://paralock.xyz/docs/run-a-maker#serve-it-over-http): `GET /health`, `GET /quote`, `POST /swaps`, `POST /adaptor/swaps`, `POST /adaptor/swaps/{id}/presignature`, `GET /swaps/{id}` (the public view), and `GET /swaps` only with `expose_swap_list`. Node and internal failures become generic 503 and 500 bodies, and bodies over 16 KiB get 413. Unlike the TypeScript handler, the Rust server limits requests itself. `ServerOptions::default()` is meant for the open internet: | Option | Default | What happens | |---|---|---| | `request_timeout` | 30 s | `504 timeout`. A commitment still running completes in its own task, and the client's retry (the POSTs are idempotent) gets its result | | `max_concurrent_requests` | 256 | Beyond it, `429 busy` at once | | `rate_limit` | 120 per minute per client, bursts of 30 | On `GET /quote`, the POSTs and `GET /swaps`: `429 busy` with `retry-after`. IPv6 clients are grouped by /64 | | `client_address` | the TCP peer | Behind a reverse proxy, `ClientAddress::Header("x-forwarded-for".into())` | | `max_connections`, `idle_timeout` | 1,024, 75 s | `serve` only. With `maker_router` in your own app, connection limits are your server's job | `ServerOptions::unlimited()` turns them all off, for tests or behind a proxy that enforces its own. `serve_with_shutdown` stops gracefully on a signal. For another HTTP framework, call `Maker::accept_value`, `propose_adaptor_value` and `adaptor_pre_signature_value` with the parsed JSON body, and map errors with `paralock::maker::client_error`. ## What the engines guarantee - **Persist before broadcast.** Secrets, adaptor secrets, per-swap keys, refund signatures, lock parameters, claims and refunds are durably stored before the transaction they protect is sent. `FileStore` writes a temporary file, fsyncs it, renames it and fsyncs the directory (0700 directory, 0600 files, one process per directory through an exclusive lock). - **The maker commits first (protocol v1.1).** The taker has the maker accept its funding (htlc) or sign its refund (private mode) before it broadcasts anything. - **Verify before revealing.** The taker re-runs `verify_htlc_lock` or `verify_adaptor_lock` (recipient, token, amount, signer, the pre-signature on its own chain's digest, confirmations, time left) right before claiming, and simulates the claim. On Ethereum L1 the claim window defaults to at least 5 minutes and 3 confirmations. - **The claim is followed until it is mined.** The taker stores its decision to claim and every claim transaction (hash, nonce, fees) as soon as it is out. A stuck claim is replaced at the same nonce with higher fees; after a restart, `resume` follows the stored claim before sending anything new. A claim by anyone else that paid the recipient counts as success. - **The maker locks only what it verified,** and records that it sent its lock before sending it. In htlc mode it never adopts a lock someone else made under its hashlock: it drops the swap at once if it never sent its own, otherwise once its own lock's expiry has passed. - **One bad record never stops the others.** Records load one at a time; one that can't be read is moved to the store's quarantine (`SwapStore::quarantine`, a `quarantine/` directory in a `FileStore`) with an error log, and every other swap resumes. - **No secrets in logs.** `tracing` output never contains keys, secrets, preimages or pre-signatures, and `Debug` of records, configurations and errors is redacted. Since 0.3.0 the TypeScript SDK has the same record quarantine, lock-sent marker and saved claim hash, and redacts its errors; the second RPC endpoint and claim fee bumps are Rust-only for now. [Persistence and recovery](https://paralock.xyz/docs/recovery) covers the TypeScript side. ## Trust model The protocol keeps funds safe against the counterparty. Each party still trusts **its own nodes**: - **The taker trusts its EVM RPC endpoint** for the maker's lock and the time left before it reveals the secret. A lying endpoint could make it reveal against a lock that doesn't exist, and the ZEC would be lost. Set `EvmChainOptions::verify_rpc_url` to a second, independent endpoint: the last check before claiming then needs both to report the same lock and both to pass every check. - **The maker trusts its Zcash backend** for the taker's funding before it locks stablecoins. A full node (Zebra or Zakura) verifies the chain. A lightwalletd or Zaino server does no proof-of-work verification, and one run by someone else could report a funding that doesn't exist: a maker should use its own full node, or its own lightwalletd in front of it. - **Both trust their EVM endpoints** for the escrows' state. The builders check every escrow address against the contract code the crate was built with (`verify_escrow_code`) before using it, and on mainnet open the store directory restricted to its owner. ## Interop with TypeScript - **Wire format.** Requests and responses are the TypeScript SDK's JSON, field for field. `tests/conformance.rs` replays all 53 recorded exchanges of `spec/vectors/messages.json` against `maker_router` and gets identical status codes and bodies. - **Protocol core.** `paralock-core` recomputes every vector in `spec/vectors` (scripts, transactions, txids, sighashes, escrow ids, digests, adaptor pre-signatures, messages) and the official ZIP 244 vectors. - **Live devnet.** Rust taker with TypeScript maker, TypeScript taker with Rust maker, Rust with Rust, and refunds in both modes all complete on the devnet that `npx paralock dev` runs. The Rust SDK also completed a swap on public testnets: run 3 in [Swap on public testnets](https://paralock.xyz/docs/testnet#the-first-public-runs). - **Stores don't mix.** The Rust store format differs from the TypeScript one, so a swap started by one SDK is resumed or refunded by the same SDK. - **Versions.** The Rust crates speak protocol v1.1, like `@paralock/sdk` 0.3.0. A 0.3.0-era maker refuses private-mode swaps from takers older than 0.3.0 ([why](https://paralock.xyz/docs/run-a-maker#serve-it-over-http)). ## Examples Six runnable examples live in [`examples/rust`](https://github.com/bitfalt/paralock/tree/main/examples/rust). The devnet ones run against `npx paralock dev` (or `pnpm paralock dev` in a checkout): | Example | What it shows | Runs on | |---|---|---| | `rust-quickstart` | The smallest swap: a Rust taker against the TypeScript maker, with `create_taker` | Devnet | | `rust-maker-server` | A maker inside your own axum app: the router under `/paralock`, health and Prometheus metrics, graceful shutdown | Devnet | | `rust-pay` | Exact dollars to someone else: exact-out quote, private mode, relayed claim, a receipt checked on-chain | Devnet | | `rust-recovery` | A recovery daemon: resumes what can continue, refunds what is past its refund height, `--dry-run`, `--watch` | Devnet | | `rust-core-htlc` | `paralock-core` alone: keys, HTLCs, funding, claim and refund transactions, the lock checks, adaptor signatures | Offline | | `rust-testnet` | A real swap: TAZ over lightwalletd to OUSD on Tempo Moderato, with an in-process maker | Zcash testnet and Tempo Moderato | ```sh git clone https://github.com/bitfalt/paralock && cd paralock pnpm install && pnpm build && pnpm paralock dev --evm all # the devnet and the TypeScript maker cargo run -p rust-quickstart # 0.1 ZEC to USDC on Base, htlc mode ``` ## Minimum Rust version and platforms - `paralock-core` needs Rust 1.85 (edition 2024). It forbids `unsafe`, its parsers of untrusted data return errors instead of panicking, and it builds for `wasm32-unknown-unknown` without default features. - `paralock-evm`, `paralock` and `paralock-cli` need Rust 1.95, set by alloy 2.x and `tempo-alloy`. - The `paralock` binary ships prebuilt for macOS and Linux on x86_64 and arm64; elsewhere, `cargo install paralock-cli`. ## Security reviews and tests Before 0.1.0, `paralock-core` had one internal security review, and `paralock-evm` with `paralock` had another. Every finding is fixed in 0.1.0 with a regression test: the reviewers' reproductions are in `tests/audit.rs` of `paralock-core` and `paralock` (plus fuzzing of the script templates and signatures in `paralock-core`), and the `paralock-evm` fixes are covered by its integration tests against local anvils. The crates' `CHANGELOG.md` files list each finding and its fix. These were reviews by the project, not a third-party audit; an external audit is on the [roadmap](https://paralock.xyz/docs/roadmap) before mainnet. ```sh cargo test --workspace # every crate and example cargo test -p paralock-core --test interop -- --ignored # TypeScript re-checks Rust output (needs Node) cargo test -p paralock-core --test regtest -- --ignored --test-threads=1 # broadcasts to a local Zebra regtest ``` --- # Rust CLI Source: https://paralock.xyz/docs/rust-cli Markdown: https://paralock.xyz/docs/rust-cli.md Section: Rust > The standalone paralock binary from paralock-cli. Install it with cargo or the installer, configure paralock.toml, use the local devnet, run quote, swap, pay, swaps, resume, refund and a maker, and script it with --json and exit codes. `paralock-cli` builds `paralock`, a single binary on the [Rust SDK](https://paralock.xyz/docs/rust): swap ZEC for stablecoins, pay exact dollar amounts, recover saved swaps and run a market maker, with no Node.js process. It speaks the same protocol as the TypeScript SDK, so it trades with TypeScript makers and serves TypeScript takers, in htlc and private mode. It complements the [npm CLI](https://paralock.xyz/docs/cli) rather than replacing it. `npx paralock` runs the whole local devnet (Zcash regtest, anvils, contracts, a maker); the Rust binary takes its configuration from a `paralock.toml` file, so it can point at any network, or at that devnet with `--devnet`. > **Warning:** Experimental and not audited by a third party. The escrows run on public testnets only, and in both modes the Zcash leg is transparent on chain (shield before and after). Start with testnet coins and small amounts. ## Install ```sh curl -fsSL https://paralock.xyz/install | sh # macOS and Linux, x86_64 and arm64 curl -fsSL https://paralock.xyz/install | PARALOCK_VERSION=cli-v0.1.1 sh # a given release cargo install paralock-cli # from source, Rust 1.95 or newer ``` The [installer](https://paralock.xyz/install) is a short POSIX shell script; read it before you pipe it to `sh`. It: 1. picks the build for your machine: `aarch64-apple-darwin`, `x86_64-apple-darwin`, `x86_64-unknown-linux-gnu` or `aarch64-unknown-linux-gnu` (Linux builds need glibc 2.35 or newer), and the native build under Rosetta; 2. downloads `paralock-.tar.gz` and `SHA256SUMS` from the [GitHub release](https://github.com/bitfalt/paralock/releases/tag/cli-v0.1.1) (the latest one, or `PARALOCK_VERSION`); 3. refuses to install unless the tarball's SHA-256 matches `SHA256SUMS`; 4. installs the binary to `${PARALOCK_HOME:-$HOME/.paralock}/bin/paralock`, replacing an older one atomically, and prints the line to add that directory to your `PATH`. The release binaries are built by GitHub Actions from the `cli-v*` tag. Windows has no prebuilt binary and isn't tested. ```sh paralock version # paralock 0.1.1 (paralock-cli, protocol v1.1; experimental, not audited) paralock --help ``` > **Note:** The npm CLI's command is also called `paralock`. `npx paralock` always runs the npm one; a bare `paralock` runs whichever comes first on your `PATH`. `paralock version` (a command) exists only in the Rust binary. ## Try it on the local devnet `--devnet` reads `devnet.json` from the same state directory as the npm CLI: `/.paralock` inside a Paralock checkout, else `$PARALOCK_HOME`, else `~/.paralock`. Starting and stopping the devnet stays in the npm CLI (`npx paralock dev`, or `pnpm paralock dev` from a checkout). ```sh npx paralock dev # Zcash regtest, anvils, contracts and the TypeScript maker paralock --devnet doctor paralock --devnet swap --zec 0.1 # htlc on Tempo, against the TypeScript maker on :7420 paralock --devnet swap --zec 0.1 --chain base --private paralock --devnet --evm-account 5 maker --port 7424 # a Rust maker on anvil account 5 (fund it first) paralock --devnet --maker-url http://127.0.0.1:7424 swap --zec 0.1 paralock --devnet swap --zec 0.1 --private --refund-demo # lock, let the maker vanish, refund ``` On the devnet the taker uses its own Zcash key (`/rust-cli/taker-zcash.key`), funded from the ths faucet as needed, and the devnet's taker and relayer accounts on the EVM chains; `--evm-account N` picks anvil dev account N instead. `--lightwalletd` reaches Zcash through lightwalletd. The Rust maker mines a regtest block only when the chain has stalled for 6 seconds (when no TypeScript maker is mining); `--no-mine` turns that off. The devnet price falls back to a fixed value when CoinGecko is unreachable, and anvil's dev keys are public. ## Configuration: `paralock.toml` Without `--devnet`, the binary reads `paralock.toml` from `--config `, else `$PARALOCK_CONFIG`, else `./paralock.toml`, else `/paralock.toml`. This is the complete, commented example shipped with the crate ([`paralock.example.toml`](https://github.com/bitfalt/paralock/blob/main/crates/paralock-cli/paralock.example.toml)): ```toml # paralock.toml: the configuration of the `paralock` binary. # # Where it is read from: --config , else $PARALOCK_CONFIG, else ./paralock.toml, else # /paralock.toml (/.paralock in a Paralock checkout, else $PARALOCK_HOME, else ~/.paralock). # For the local devnet, skip this file and use `paralock --devnet …`. # # Keys: every private key comes from an environment variable (key_env) or a file only you can read (key_file, # `chmod 600`; paralock warns about looser permissions). A key written here by value (key = "…") is refused unless # allow_inline_keys = true, which is meant for throwaway testnet keys. # # Paralock is experimental and not audited. The Zcash leg is transparent on chain. Start small. network = "mainnet" # mainnet | testnet | regtest maker_url = "https://maker.example" # the maker that `quote`, `swap` and `pay` trade with (or --maker-url) # store_dir = "~/.paralock/rust-mainnet" # swap stores (/taker, /maker): back them up, they hold keys # allow_inline_keys = false [zcash] rpc = "http://127.0.0.1:8232" # a Zebra / Zakura JSON-RPC endpoint… # lightwalletd = "https://zec.rocks:443" # …or a lightwalletd / Zaino server (no full node needed) # rpc_user = "paralock" # basic auth: with rpc_password_env or rpc_password_file, # rpc_password_env = "ZEBRA_RPC_PASSWORD" # rpc_cookie_file = "~/.cache/zebra/.cookie" # or Zebra's cookie file key_env = "PARALOCK_ZCASH_KEY" # the transparent key that funds swaps (32 bytes of hex) # key_file = "~/.paralock/zcash.key" # return_address = "t1…" # change and refunds (default: the key's own address) # One section per EVM chain: tempo, base, ethereum, arbitrum, robinhood, hyperevm. On a testnet whose chain id # Paralock has deployed to, htlc, adaptor_escrow, from_block and the token default to that deployment. [evm.base] rpc = "https://mainnet.base.org" # verify_rpc = "https://base.other-provider.example" # taker: a second, independent endpoint; the last check # # before claiming needs both to report the same lock chain_id = 8453 htlc = "0x…" # ParalockHTLC adaptor_escrow = "0x…" # ParalockAdaptorEscrow: enables --private from_block = 0 # the deployment block (event scans start here) key_env = "PARALOCK_EVM_KEY" # your account on this chain (receives the stablecoins; pays claim gas) # relayer_key_env = "PARALOCK_RELAYER_KEY" # a second account that submits claims for `--relay` # tokens = ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"] # taker: stablecoins you accept (default: known ones) token = { address = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", symbol = "USDC", decimals = 6 } # maker: quoted # fee_token = "0x20c0…" # Tempo only: the TIP-20 that pays fees # rpc_timeout_seconds = 10 [price] source = "coingecko" # quotes are checked against this price (and makers quote from it) # url = "https://…" # another endpoint answering { "zcash": { "usd": } } # fixed = 50.0 # regtest / testnet only [taker] # max_slippage_bps = 200 # refuse quotes more than 2 % below your price # min_claim_window_seconds = 30 # time left on the maker's lock before claiming (the floor is 30) # min_evm_confirmations = 1 # max_zcash_lock_blocks = 288 # longest your ZEC may stay locked if the maker vanishes # max_zec = "1000" # `paralock maker`. A maker on the open internet: keep the defaults, run it behind TLS, back up its store. [maker] listen = "127.0.0.1:7420" # payout_address = "t1…" # where claimed ZEC goes (default: the maker key's address) # zcash_key_env = "PARALOCK_MAKER_ZCASH_KEY" # default: [zcash].key_* spread_bps = 50 policy = "mainnet" # mainnet | devnet (devnet is refused on mainnet) min_zec = "0.01" max_zec = "10" max_concurrent_swaps = 10 quote_ttl_seconds = 60 # check_inventory = true # cors = ["https://app.example"] # or ["*"] # expose_swap_list = false # GET /swaps lets anyone link swaps # request_timeout_seconds = 30 # 0 disables # max_concurrent_requests = 256 # rate_limit_per_minute = 120 # per client, on GET /quote and the POSTs; rate_limit = false disables # rate_limit_burst = 30 # client_ip_header = "x-forwarded-for" # behind a reverse proxy that sets it # max_connections = 1024 # idle_timeout_seconds = 75 # finished_swaps_in_memory = 256 ``` The example is written for mainnet so every field appears, but Paralock has no mainnet deployment: the `0x…` escrow addresses stay placeholders until there is one. On a testnet, `rpc` and `chain_id` are enough for a chain Paralock has deployed to. For example, against Base Sepolia through a public lightwalletd server (`paralock doctor` then checks the server, both escrows' code, your balances, the maker and the price): ```toml network = "testnet" maker_url = "https://maker.example" [zcash] lightwalletd = "https://testnet.zec.rocks:443" key_env = "PARALOCK_ZCASH_KEY" [evm.base] rpc = "https://sepolia.base.org" chain_id = 84532 # htlc, adaptor_escrow, from_block and USDC come from the deployment key_env = "PARALOCK_EVM_KEY" ``` - **Keys** come from environment variables (`key_env`) or files (`key_file`); a key file readable by other users gets a warning, and a key written in the file by value is refused unless `allow_inline_keys = true`. - **Testnet defaults.** On a chain id with a Paralock deployment, `htlc`, `adaptor_escrow`, `from_block` and the token default to it ([Contracts and deployments](https://paralock.xyz/docs/contracts#deployments) lists them). - **Price.** CoinGecko by default. A fixed price, or a fallback, is refused on mainnet. - **`[taker]`** sets the slippage, the claim window and the longest acceptable Zcash lock. **`[maker]`** sets the listen address, payout address, spread, policy, limits and the HTTP server's limits. - **Stores** live in `store_dir` (default `/rust-`), under `taker/` and `maker/`. They hold secrets and per-swap keys: back them up and keep them private. Their format differs from the TypeScript SDK's, so finish a swap with the tool that started it. ## Commands | Command | What it does | |---|---| | `paralock doctor [--maker]` | Checks the Zcash backend (network, height, branch id), each EVM RPC (chain id), the contracts' code, your keys and balances, the maker's `/health` and the price feed. With `--maker`, the maker side: its keys, inventory and listen address. Exit 1 if a required check fails | | `paralock quote --zec 0.5 [--chain base] [--private]` | A quote, checked as a swap would check it (keys, chain id, token, windows, price). `--usd 25` asks for an exact-out quote. Nothing is locked | | `paralock swap --zec 0.5 [options]` | The whole swap. Also `--fresh-recipient`, `--relay`, `--standard-only`, `--jitter `, `--refund-demo` | | `paralock pay --usd 25 --to 0x… [--label "Acme Coffee"] [options]` | Pays exactly 25 dollars of the chain's stablecoin to an address, from ZEC | | `paralock swaps [--all]` | Lists the swaps in the taker's store, unfinished ones by default. Works while a swap runs | | `paralock resume [--no-relay]` | Continues a saved swap after a crash or restart. `--no-relay` claims from your own account even if the swap was started with `--relay` | | `paralock refund [--no-wait]` | Refunds a saved swap's ZEC once its refund height is reached. Works with the EVM RPC down | | `paralock maker [--listen \| --port ] [--no-mine]` | Runs a maker: the protocol's HTTP API with the SDK's server (request timeout, concurrency and per-client rate limits, connection caps) and the settlement loops. Unfinished swaps resume on restart | | `paralock version` | The version and protocol version | `swap` and `pay` share `--chain` (default `tempo`, or the only configured chain), `--private`, `--relay`, `--no-refund` and `--yes`. Options for every command: `--config `, `--devnet`, `--maker-url `, `--json`, `-v` / `-vv`, and on the devnet `--evm-account ` and `--lightwalletd`. Progress is printed as the swap moves, one line per step with its transaction: ```text Quote: 0.1 ZEC → 127.55 OUSD on tempo @ $1276.85/ZEC Mode htlc (a shared sha256 hashlock on both chains) Zcash refund window 40 blocks · tempo lock 45s · quote 9e1ff79b-… Swapping: [zcash ] zcash_locked Locked 0.1 ZEC in the Zcash HTLC 17b1e6e9… [tempo ] evm_locked Maker locked 127.55 OUSD; terms verified 0x723f21f7… [tempo ] evm_claimed Received 127.55 OUSD; the secret is now public 0xc53ef4cd… [zcash ] completed Maker claimed the ZEC with the secret 0dbfee45… ``` If a swap fails after its ZEC was locked, `swap` and `pay` wait for the refund height and refund it, unless `--no-refund`. The swap is saved either way, so `paralock refund ` also works after a restart. On mainnet they ask for confirmation unless `--yes`. ## Scripts: `--json` and exit codes `--json` prints exactly one JSON document on stdout: `{ "ok": true, … }` with the quote, the swap or the checks, or `{ "ok": false, "error": { "code", "message", "hint", "exitCode" }, "swap"? }`. `paralock maker --json` prints newline-delimited records instead: `listening`, then one `swap` record per status change, then `stopped`. Warnings and logs (`-v`, `-vv`, `RUST_LOG`) go to stderr. | Exit code | Meaning | |---|---| | 0 | Success: a swap completed, a refund landed, every required doctor check passed | | 1 | Failure, and nothing irreversible happened: an unreachable node, a refused quote… | | 2 | Usage or configuration error | | 3 | A swap failed after locking ZEC: refunded, or refundable with `paralock refund ` | ```sh paralock --json quote --zec 0.1 --chain base | jq -r '.usd' # the dollars quoted, as a decimal string paralock --json swap --zec 0.1 --chain base > swap.json || echo "exit $?: see .error.hint in swap.json" ``` ## Running a maker `paralock maker` serves the protocol with the Rust SDK's server and runs the settlement loops in the same process. A maker on the open internet should keep the `[maker]` defaults, sit behind TLS (a reverse proxy, with `client_ip_header` set so the per-client rate limit sees real clients), use its own full node rather than someone else's lightwalletd, and keep its store backed up. [Run a maker](https://paralock.xyz/docs/run-a-maker) covers pricing, limits, inventory and what a maker earns and risks; those apply to the binary too. --- # Security model Source: https://paralock.xyz/docs/security Markdown: https://paralock.xyz/docs/security.md Section: Trust > The invariants Paralock never breaks, what a malicious maker, taker, relayer or observer can and can't do, what you still trust, and the known limitations. Paralock's goal is that neither party can take the other's funds, and that no third party ever holds them. This page states what the code guarantees, what it assumes, and where it falls short. > **Warning:** Paralock is experimental and **not audited** by a third party. The escrows are deployed on six public testnets only, and there is no mainnet support. In both modes the Zcash leg is a transparent output. ## Protocol invariants The SDK, the contracts and every change to them keep these rules: 1. **Window ordering.** When the maker locks, the Zcash refund window must outlast the EVM lock by at least the policy's `safetyFactor` (2×), so whoever learns the secret can always use it in time. `assertSafeWindows` enforces this. 2. **Verify before revealing.** The taker reveals the secret, or completes the adaptor signature, only after verifying the maker's EVM lock on-chain: recipient, token, amount, signer and time left. 3. **Verify before funding (private mode).** The taker broadcasts the 2-of-2 funding only after it holds a valid maker signature on its time-locked refund. This is safe because Zcash v5 txids (ZIP 244) don't commit to signatures, so the funding txid can't change after signing. 4. **Single-use secrets.** Hashlocks and escrow ids are never reusable: the contracts mark them settled forever. 5. **Persist before broadcast.** Secrets, adaptor secrets, multisig keys and refund signatures are in the store before any funding transaction is sent. 6. **The recipient is fixed at lock time.** Anyone may submit a claim, as a relayer does, but funds only ever go to the recipient in the lock. 7. **Signatures.** Low-S everywhere, a fresh random nonce for every adaptor pre-signature, and the DLEQ proof of every received pre-signature is checked (`preVerify`). 8. **Byte-for-byte checks.** The maker accepts a Zcash lock only if its redeem script matches the maker's own template exactly. The escrow contracts have no owner, admin, pause or upgrade function. Once funds are locked, only `claim` (to the recipient, before expiry) and `refund` (to the sender, from expiry on) can move them, and anyone may submit either. ## Threat model ### A malicious maker | Can | Can't | |---|---| | Never lock, keeping your ZEC locked until the refund height. Your default limits cap that window at 288 blocks, about 6 hours at 75 seconds | Take your ZEC without the secret, which you reveal only by claiming its lock | | Quote a poor rate. Pass your own `price` to reject quotes beyond `maxSlippageBps` (default 2%) | Get you to claim a lock with the wrong recipient, token or amount, or with too little time left: the taker checks each on-chain and refuses (`lock_mismatch`, `timeout`) | | Go offline mid-swap. You refund after the refund height | Withhold your refund in private mode: you fund only after verifying its signature on your refund | | See both legs of your swap and your network address | Make you sign for the wrong consensus branch: you check its branch id against your own node | ### A malicious taker | Can | Can't | |---|---| | Lock ZEC and walk away after the maker locks (the "free option"). The maker's inventory stays locked until expiry, and it pays the refund gas. The spread prices this in | Get the stablecoins without revealing the secret, or the adaptor secret, to the maker | | Request many quotes or proposals. Capped by `maxOpenQuotes` (1,000), `maxConcurrentSwaps` (10) and the 60-second quote lifetime | Make the maker lock against a tampered script, a different claim key or a short funding: the maker rebuilds the lock byte for byte and checks the value | | Reserve inventory and never fund. The maker commits before the funding is broadcast, so each reservation holds stablecoins, and counts against `maxConcurrentSwaps`, until the declared `fundingExpiryHeight` (at most `maxFundingExpiryBlocks`, 45 blocks, ahead) plus 2 blocks. An htlc accept that declares no expiry gets the same deadline from the maker's tip, as long as the maker never sees a transaction paying the lock. A funding that is broadcast but kept unmined holds it until the window gets too short to lock, at most about twice the policy window | Get the maker to lock without a confirmed funding: it locks only once the funding has `minZcashConfirmations` | | Stall until its refund nears. The maker re-checks the window right before locking and abandons the swap instead | Refund its ZEC before the refund height: consensus rejects it | | Send an invalid pre-signature or a far-away refund height | Pass the maker's checks: pre-signatures are verified, and refund heights more than twice the policy window away are refused in both modes. A refused commitment leaves its quote usable | ### A relayer A relayer can refuse or delay a claim. Then the claim has to be submitted from another account before the lock expires: the SDK doesn't fall back automatically, but `taker.resume(id, { relayClaim: false })` submits it from your own EVM account. A relayer only sees data that becomes public anyway. It can't redirect funds, because the escrow pays the recipient fixed at lock time. ### Observers, miners and the mempool - **Copying the secret from the mempool gains nothing.** The EVM lock only pays its recipient, and the Zcash lock also needs the maker's signature (htlc) or both parties' signatures (private mode). - **Linking:** in htlc mode, anyone can pair the two legs through the shared hashlock. Private mode leaves only amount and timing correlation. See [Privacy](https://paralock.xyz/docs/privacy). - **Delays and censorship:** a party whose transactions are held back long enough can miss a deadline. The 2× window and the taker's minimum claim window (`minClaimWindowSeconds`) leave a margin, not a guarantee. - **Reorgs:** the maker waits for `minZcashConfirmations` (2 with `MAINNET_POLICY`) and the taker for `minEvmConfirmations` (1 by default) before acting. Raise them on chains with deeper reorgs. ### Your infrastructure The engines believe your nodes. A malicious or broken Zcash node or EVM RPC endpoint could hide a lock or report a false one. The taker checks that each EVM RPC serves the configured chain id, and the Rust SDK also checks each escrow's deployed code (`verify_escrow_code`), but neither can detect a node that lies about chain state. Use nodes you run or trust. In the Rust SDK, `EvmChainOptions::verify_rpc_url` adds a second, independent EVM endpoint: the taker's last check before revealing the secret then needs both to report the same lock. ## What you trust | You trust | Why | How to reduce it | |---|---|---| | The code | It has had internal security reviews (the Rust crates before 0.1.0, with the fixes ported to the TypeScript SDK in 0.3.0) but no third-party audit, and ECDSA adaptor signatures have had far less scrutiny than Schnorr ones | Small amounts, testnets, reading the source and tests | | The maker's price | Only for the rate, never with your funds | `price` and `maxSlippageBps` on the taker | | Your own liveness | The taker must claim before expiry, with `minClaimWindowSeconds` to spare; the maker must claim the ZEC before the refund height | Durable stores, `resume` and `maker.start()` after restarts, supervised processes | | Your nodes | They report chain state | Run your own Zebra or Zakura node and EVM RPC; in Rust, a second EVM endpoint with `verify_rpc_url` | | The chains | Bounded reorgs, and transactions included within the windows | Confirmations, the 2× safety factor | ## Key management | Key | Holds | Advice | |---|---|---| | Taker's Zcash key | The ZEC being swapped; signs htlc-mode refunds | Fund it only with what you are about to swap. Keep it as long as any swap is open | | Per-swap keys | The 2-of-2 halves, the maker's per-quote key, the one-time EVM signer | Generated per swap and kept in the store. Never reused | | EVM accounts | The taker's claims; the maker's inventory and gas | Use a viem `Account` backed by a KMS or HSM for the maker; `account` accepts one | | Relayer | Gas only | A separate account with a small balance | | Fresh-recipient keys | The stablecoins received by a fresh address | Durable store or `onFreshRecipient`, then move them somewhere safe | | The store | All secrets above | A wallet file: mode 0600 in a 0700 directory, encrypted backups, one process | Never commit keys. Anvil's development keys are public, and `.paralock/` (the devnet's mnemonic and keys) is gitignored. ## Known limitations - **The Zcash leg is transparent.** In both modes the lock, its amount and its spend are public. A fully shielded leg is in research. - **lightwalletd can't see the mempool.** It reports only mined transactions and has no `getTxOut`, so with `@paralock/lightwalletd` the engines notice a spend only after it is mined. The server also learns which addresses you query. - **Network upgrades vs pre-signed spends.** In private mode the taker's refund and the maker's claim are signed long before they are broadcast, and they commit to the current consensus branch id. A Zcash network upgrade that activates first invalidates them. Both sides refuse a private-mode swap if an upgrade activates before its refund height, but only when the backend can report upgrades: `ZcashRpc` can, lightwalletd only with servers recent enough to send `lightwalletProtocolVersion`, and backends that can't skip the check with a log line. - **No rate limiting in the TypeScript handler.** `makerHandler` caps body sizes and open quotes, but per-client limits and TLS are left to your deployment. The Rust server (`paralock::serve`, `maker_router`) has a request timeout, a concurrency cap and per-client rate limits on by default; TLS is still your reverse proxy's job. - **A late claim leaks.** A claim mined after expiry reverts, but its calldata still reveals the secret. The taker refuses to claim with less than `minClaimWindowSeconds` left (30 s by default); use minutes on Ethereum L1. - **The free option is real.** A taker can abandon a swap after the maker locks. It costs the maker time and gas, and it is priced into the spread rather than prevented. - **One direction, transparent refunds.** Swaps only sell ZEC for stablecoins, and refunds pay a transparent Zcash address. - **Public swap lookups.** `GET /swaps/:id` on a maker returns a swap's public view to anyone who knows its id. In private mode that view has no adaptor point, pre-signatures, signer key or salt (the taker gets them in the answer to its own pre-signature request), but it still lists both legs' transactions and the amounts, so a leaked swap id links them. The list endpoint is off by default. - **Default price source.** `zecUsdPrice()` reads CoinGecko. A maker depends on that feed unless it brings its own. ## Test coverage | Suite | What it covers | |---|---| | `packages/zcash` | ZIP 244 txid and all six transparent sighash types against the official test vectors; strict parsing (canonical CompactSize, curve-checked keys, required branch id and network); RPC timeouts, retries and duplicate broadcasts; key, address-network, dust and signature checks; live regtest: HTLC fund, claim and refund (refund rejected before the timeout), 2-of-2 claim with an adaptor-completed signature, pre-signed refund only after its lock time, wrong secret rejected | | `packages/adaptor` | Pre-sign, pre-verify, adapt, verify, extract over random rounds; tampering and out-of-range scalars rejected; fresh nonces per call; bounded nonce retries; EVM `ecrecover` compatibility | | `packages/evm` | Both escrow clients against local Tempo and plain EVM chains, including lock lookups with block numbers | | `packages/sdk` | Both engines on fake chains in both modes; restart and resume of both parties; secrets persisted before funding; reservation before the htlc funding is broadcast; the public swap view without adaptor data; claim rebroadcast; refunds from the store; a maker refusing an underfunded 2-of-2, a delayed funding and a missing pre-signature; maker limits; stores; quote and request validation; retries; factories; HTTP handler and client; the shared protocol vectors | | `packages/lightwalletd` | Txid vectors and live regtest through lightwalletd | | `contracts` | Both escrows: happy paths, wrong secret or signer, high-s signatures, expiry edges, double claims, reuse, tampering, fuzzing, real TIP-20 tokens | | `crates/paralock-core` | Every vector in `spec/vectors` and the official ZIP 244 vectors, property tests and fuzzing of the script templates and signatures, the security review's reproductions (`tests/audit.rs`), and cross-checks run by the TypeScript packages | | `crates/paralock-evm` | Both escrow clients against local anvils (plain EVM and Tempo), the send pipeline with fee bumps, code verification and the network registry | | `crates/paralock` | Both engines in both modes, crashes and resumes, store quarantine, claim tracking, the HTTP server against all 53 recorded exchanges in `spec/vectors/messages.json`, server limits, and the review's reproductions | The live regtest suites run only when a local node is up. End-to-end swaps have also been run on the devnet (htlc mode on Tempo; private mode on Tempo, Base and Ethereum; a fresh recipient with a relayed claim; the maker-vanishes refund in both modes; the taker-never-claims double refund) and on public testnets, recorded in [`docs/TESTNET-RUNS.md`](https://github.com/bitfalt/paralock/blob/main/docs/TESTNET-RUNS.md). ```sh pnpm --filter @paralock/sdk test cd contracts && forge test cargo test --workspace ``` ## Reporting a vulnerability Please report security issues privately, not in a public issue. Use a private GitHub security advisory on [bitfalt/paralock](https://github.com/bitfalt/paralock/security/advisories) (Security tab, "Report a vulnerability"). If that option isn't available, open an issue that asks for a private security contact, without any details, and the maintainer will follow up. Use public [GitHub issues](https://github.com/bitfalt/paralock/issues) for bugs that don't put funds at risk. --- # FAQ Source: https://paralock.xyz/docs/faq Markdown: https://paralock.xyz/docs/faq.md Section: Trust > Short answers to the questions people ask most about Paralock's trust model, privacy, costs, timing, chains and roadmap. ## Is Paralock trustless? Nobody but the two parties ever holds the funds. The ZEC sits in a Zcash script and the stablecoins in an EVM contract, and one secret opens both, so either both sides settle or both refund. There is no bridge, custodian, wrapped token or operator key, and the escrows have no admin functions. You still trust three things: the code, which is experimental and not audited by a third party; the maker's price, which you can bound with your own price feed; and your own liveness, since you must claim before the EVM lock expires. The [Security model](https://paralock.xyz/docs/security) lists every assumption. ## Can someone front-run my swap or steal the secret from the mempool? No. Copying the secret gains nothing. The EVM escrow pays only the recipient fixed when the maker locked, no matter who submits the claim, and the Zcash lock also needs the maker's signature (htlc mode) or both parties' signatures (private mode). The one timing risk is claiming too close to expiry: a claim mined late reverts but still reveals the secret. The taker refuses to claim with less than `minClaimWindowSeconds` left (30 seconds by default). ## How is this different from CrossPay, NEAR Intents or THORChain? Those routes give good UX, but an intermediary holds your funds while the swap is in flight. Zodl's CrossPay spends shielded ZEC through NEAR Intents market makers, and deposits move through NEAR's PoA bridge, which holds them in a treasury. THORChain's ZEC pool keeps funds in validator-held vaults. With Paralock, only the two parties ever hold the funds, and the SDK is self-hostable: a wallet can embed it, and anyone can run a maker. Paralock also settles natively on Tempo in OUSD, which isn't a NEAR Intents destination. ## Is the Zcash leg private? Not by itself: in both modes it is a transparent output, so the lock, its amount and its spend are public. Paralock keeps it from touching your shielded history. You unshield only the swap amount, shield change and refunds again, and can receive at a fresh address through a relayer. Private mode goes further: no hash or other shared value links the two chains, leaving only amount and timing correlation. A fully shielded Zcash leg using FROST is in research. See [Privacy](https://paralock.xyz/docs/privacy). ## Can I use it with real money? No. Paralock is experimental and not audited by a third party. The escrows are deployed on six public testnets, and there is no mainnet deployment. The SDK has mainnet settings (`MAINNET_POLICY`, and a durable store is required on mainnet) so its defaults are safe, but mainnet use would be at your own risk. The [roadmap](https://paralock.xyz/docs/roadmap) puts a hosted testnet maker and a third-party audit before mainnet. ## Which chains does it support? Zcash on one side. On the other: | Chain | Stablecoin | Testnet deployment | |---|---|---| | Tempo | OUSD | Tempo Moderato | | Base | USDC | Base Sepolia | | Ethereum | USDC | Sepolia | | Arbitrum | USDC | Arbitrum Sepolia | | Robinhood Chain | MockUSD test token on testnet (it has no USDC) | Robinhood Chain Testnet | | HyperEVM | USDC | HyperEVM Testnet | The local devnet runs all six (`--evm all`). Adding another EVM chain takes a small change to the SDK and the devnet, described in the repository's `AGENTS.md`. [Where Paralock works](https://paralock.xyz/docs/networks) has the details, including the current Zcash testnet split. ## How long does a swap take? On the local devnet, it's quick, because the devnet mines a Zcash block every 3 seconds. On public networks, a few minutes, mostly spent waiting for Zcash blocks, which come about every 75 seconds. The maker waits for the funding to confirm (2 confirmations with `MAINNET_POLICY`, 1 in the testnet example) before locking, and Tempo confirms in under a second. The proposed NU7 upgrade would cut Zcash blocks to 25 seconds. If the maker never locks, your ZEC waits until the refund height: about 3 hours with `MAINNET_POLICY`, and never more than 288 blocks (about 6 hours) under the taker's default limits. ## What does a swap cost? - **The maker's spread,** set by the maker: 50 basis points (0.5%) by default. - **The maker's Zcash claim fee,** 10,000 zat (0.0001 ZEC), priced into every quote. - **Your Zcash funding fee,** under ZIP 317 at least 10,000 zat. - **The EVM gas of your claim,** unless a relayer submits it. On Tempo, fees are paid in a stablecoin. The SDK charges no protocol fee. [How it works](https://paralock.xyz/docs/how-it-works#quotes-and-pricing) has a worked example. ## Does the person I pay need ZEC, gas or an app? No. With Pay, the recipient only shares an address and an amount, for example as a payment link. The escrow sends the stablecoins straight to that address, and your account or a relayer submits the claim. See [Payments and payment links](https://paralock.xyz/docs/pay). ## Can I run my own maker? Yes. The protocol is symmetric and the SDK is MIT-licensed: `createMaker` plus `makerHandler` give you a maker with an HTTP API. You need stablecoin inventory and gas on each chain you quote, a durable store, a price feed, and uptime while your swaps are open. In return you earn the spread. See [Run a maker](https://paralock.xyz/docs/run-a-maker). ## What happens if I go offline in the middle of a swap? You lose nothing; at worst the swap doesn't happen. - **Before your claim:** the secret stays with you, so the maker can't take your ZEC. The maker refunds its stablecoins after the EVM expiry, and you refund your ZEC once the chain reaches the refund height, whenever you come back. `taker.refund(id)` or `paralock refund ` does it from the store. - **During a crash:** everything needed was stored before each step. `taker.resume(id)` continues, and if your claim already landed, it finds it on-chain. See [Persistence and recovery](https://paralock.xyz/docs/recovery). - **After your claim:** you already have the stablecoins. Liveness matters more for the maker: once you claim, it must claim the ZEC before the refund height. ## Do I need to run a Zcash node? No. `@paralock/lightwalletd` uses a lightwalletd or Zaino server, such as `testnet.zec.rocks:443`, as the Zcash backend. A Zebra or Zakura node works too, and sees more: mempool spends and upcoming network upgrades. Makers should prefer a full node. ## Why Tempo? Tempo is built for stablecoin payments. It has no native gas token: fees are paid in stablecoins, so a payer never needs a volatile asset. It confirms in under a second, so the EVM side of a swap is fast. Every TIP-20 transfer into or out of the escrows carries the swap's hashlock or escrow id as a memo, which makes reconciliation easy. OUSD settles there natively, and Tempo isn't reachable through NEAR Intents. Paralock works the same on Base, Ethereum, Arbitrum, Robinhood Chain and HyperEVM. ## Can I swap dollars for ZEC? Not yet. Today the taker always sells ZEC for stablecoins. USD to ZEC, and refunds straight to a shielded address, are on the [roadmap](https://paralock.xyz/docs/roadmap). ## What about Solana? It's on the [roadmap](https://paralock.xyz/docs/roadmap): a Solana program with the same sha256 hashlock. Private mode can work there too, because Solana programs can check secp256k1 signatures (`secp256k1_recover`), so no cross-curve proofs are needed. The roadmap also includes a request-for-quote network where many makers compete, and a Zcash payment method for MPP so agents can pay HTTP 402 APIs from shielded ZEC. ## Is there a Rust SDK? Yes. Four crates are on crates.io: [`paralock`](https://paralock.xyz/docs/rust), the SDK with the taker and maker engines (the maker served with axum); [`paralock-core`](https://docs.rs/paralock-core), the protocol core, byte-for-byte compatible with the TypeScript packages on the shared test vectors and buildable for wasm32; [`paralock-evm`](https://docs.rs/paralock-evm), alloy clients for both escrows; and [`paralock-cli`](https://paralock.xyz/docs/rust-cli), the standalone `paralock` binary. A Rust taker trades with a TypeScript maker and the other way round. Bindings for Node.js, browsers, Swift, Kotlin, Python and Go are planned on top of the core; see the [roadmap](https://paralock.xyz/docs/roadmap). ## What's planned next? The [roadmap](https://paralock.xyz/docs/roadmap) lists everything that is shipped, in progress, next and in research, each with the reason it matters.