# Ksana documentation > Ksana is a proof-of-work smart-contract chain that confirms in about five seconds, writes every block into Bitcoin, and lets Bitcoin alone decide what is final. Every English page of the docs at https://ksana.network/docs/, in the order of their sidebar. Contracts have a reference of their own for AI assistants: https://ksana.network/llms-contracts.txt. --- # Ksana documentation URL: https://ksana.network/docs/ > How to use Ksana, build on it and run it, starting from the public signet. Ksana is a smart-contract chain whose blocks confirm in about five seconds and are written into Bitcoin. Producers mine its blocks with their own proof of work and put each block’s data into Bitcoin transactions, paying the Bitcoin fees themselves. Which blocks are final is decided from Bitcoin’s chain alone, with no bridge, committee or sequencer in between, and a block is final once its data has six Bitcoin confirmations and five more blocks have secured the decision. Your account is your Taproot address, contracts are WebAssembly modules written in Rust, and anyone with a Bitcoin node can rebuild the whole chain. - [Quickstart](https://ksana.network/docs/quickstart/) Get test KSA and send your first operation, in a browser or from a terminal. - [How Ksana works](https://ksana.network/docs/how-it-works/) The fast lane, settlement into Bitcoin, and finality decided from Bitcoin. - [Confirmations](https://ksana.network/docs/confirmations/) Fast-confirmed, on Bitcoin and final: what each mark means and how long to wait. - [Signet wallet](https://ksana.network/docs/wallet/) The web wallet and explorer of the public signet, with Unisat or Xverse. ## By what you want to do ### Use the signet - [The public signet](https://ksana.network/docs/signet/): endpoints, the faucet and how the signet differs from mainnet - [The signet wallet](https://ksana.network/docs/wallet/): send on path B or path C, top up, and explore - [Accounts](https://ksana.network/docs/accounts/): your address, your keys and your balances - [Operations and fees](https://ksana.network/docs/submitting-ops/): what an operation costs on each path ### Build an app - [TypeScript SDK](https://ksana.network/docs/sdk/): keys, wallets, operations and the RPC clients, for Node.js and browsers - [JSON-RPC](https://ksana.network/docs/rpc/): every method of the node and the indexer - [ksana-cli](https://ksana.network/docs/cli/): the command-line client, for scripts and quick checks - [Confirmations](https://ksana.network/docs/confirmations/): which mark to wait for before you act on a payment ### Write a contract - [Your first contract](https://ksana.network/docs/first-contract/): a poll written, compiled and deployed in the browser, with the playground - [Write a contract](https://ksana.network/docs/contracts/): a Rust contract from an empty project to a deployment - [The contract SDK](https://ksana.network/docs/contract-sdk/): every function, type and constant a contract uses - [Host functions](https://ksana.network/docs/host-functions/): what a contract can call, and the gas each call costs - [Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/): verify Bitcoin payments from a contract - [Assets and tokens](https://ksana.network/docs/tokens/): built-in assets, [KS-20](https://ksana.network/docs/ks-20/) tokens and [KS-721](https://ksana.network/docs/ks-721/) collections - [Example contracts](https://ksana.network/docs/example-contracts/) and the [token and pool tutorial](https://ksana.network/docs/token-and-pool/) - For AI assistants: the [contract reference](https://ksana.network/llms-contracts.txt) in one file, and these docs as [llms.txt](https://ksana.network/llms.txt) and [llms-full.txt](https://ksana.network/llms-full.txt) ### Run a node or an indexer - [Run a node](https://ksana.network/docs/run-a-node/): follow the signet, produce blocks and settle them on Bitcoin - [Run an indexer](https://ksana.network/docs/run-an-indexer/): rebuild the chain from Bitcoin alone and check the nodes - [Mining](https://ksana.network/docs/mining/): proof of work, difficulty, rewards and what settling costs - [Parameters](https://ksana.network/docs/parameters/): every protocol value of devnet, signet and mainnet [KSA and rewards](https://ksana.network/docs/ksa/), [Security](https://ksana.network/docs/security/), the [FAQ](https://ksana.network/docs/faq/) and the [Glossary](https://ksana.network/docs/glossary/) cover the rest. ## Where the project stands - **Specification frozen.** The consensus rules in [`docs/SPEC.md`](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md) were frozen on 5 October 2026. A change from then on goes through the upgrade mechanism the specification defines or, before mainnet, a restart of the test networks from genesis. - **Public signet.** The [public signet](https://ksana.network/docs/signet/) has run on Bitcoin’s signet since 13 October 2026, with hosted seed nodes, an indexer, the web wallet and a faucet. Its coins are test coins with no value. - **Mainnet not launched.** The signet runs for at least four weeks first, to watch settlements and the carrier reward on a real Bitcoin fee market. The source code, the specification and the design decisions are in the repository at [https://github.com/ksana-in-bitcoin/ksana](https://github.com/ksana-in-bitcoin/ksana). --- # Quickstart URL: https://ksana.network/docs/quickstart/ > Get test KSA on the public signet and send your first operation, from a browser wallet or from the command line, then watch it become final on Bitcoin. This page takes you from nothing to a transfer that is final on Bitcoin. Everything happens on the [public signet](https://ksana.network/docs/signet/), Ksana’s test network on Bitcoin’s signet: the coins have no value, and mainnet has not launched. Pick one route. [In the browser](#in-the-browser) needs a Bitcoin wallet extension and a few minutes. [From the command line](#from-the-command-line) needs a Rust toolchain and shows every value the network returns. Either way, your operation passes three marks: *Figure: An operation is fast-confirmed in seconds, on Bitcoin once the transaction that carries its block is mined, and final after six Bitcoin confirmations and five more blocks that secure the decision.* | Mark | What it means | On the signet | | --- | --- | --- | | Fast-confirmed | A producer put your operation in a block and every node executed it. | about 5 seconds | | On Bitcoin | The block’s data is in a Bitcoin block, readable by anyone. | usually the next Bitcoin block after the settlement is sent | | Final | Every node and indexer decided from Bitcoin that the block is final when that data had six confirmations, and the Bitcoin block of that decision has six confirmations too. | six confirmations about 50 minutes after it reached Bitcoin, final about 50 minutes later | [Confirmations](https://ksana.network/docs/confirmations/) explains what each mark guarantees and how long to wait for each kind of payment. ## In the browser You need Unisat or Xverse as a browser extension. The signet wallet page talks to the hosted signet node, so there is nothing to install besides the wallet. ### Set up a Bitcoin wallet Switch the wallet to **Bitcoin Signet** and use a **Taproot (P2TR)** address. Your Ksana account is your Taproot address: KSA and bitcoin share it, each on its own chain. Other address types cannot hold KSA. - **Unisat**: choose the Taproot address type. - **Xverse**: the account’s Ordinals address is the Taproot one, and the page uses it. The page asks the wallet which network it is set to and refuses any other, because a `tb1…` address alone does not tell signet from testnet. ### Connect to the signet wallet Open [https://signet.ksana.network/](https://signet.ksana.network/), choose **Wallet**, then **Connect wallet**, and pick your wallet. Approve the connection in the extension. The page asks only for signatures. It never sees your keys and never holds your coins. ### Claim test KSA An empty wallet shows **Claim test KSA** under its balance; the **Receive** page has the same faucet as **Get test KSA from the signet faucet**. Either sends 100 KSA to your account. The faucet pays each account once a day. The KSA arrives in a few seconds, as soon as a producer includes the faucet’s transfer. ### Send KSA Choose **Send**, paste a recipient (a `tb1p…` address, or an account as 64 hex digits) and an amount. Leave the way to submit at **Sponsored** (path B): the fee is a small amount of KSA, and the page suggests one. Choose **Review and sign**, check the recipient’s first and last characters, then **Sign and submit**. The wallet asks you to sign one message (BIP322). No bitcoin moves and no Bitcoin fee is paid. ### Watch the three marks After you sign, the Send page turns into the operation’s progress: **Pending**, **Fast-confirmed**, **On Bitcoin**, **BTC final**. It reaches Fast-confirmed within seconds. The other two follow the Bitcoin blocks, so leave the page open or come back later: the wallet’s **In progress** list and **Activity** keep track, and **View in explorer** shows each Bitcoin transaction involved. [The signet wallet](https://ksana.network/docs/wallet/) covers the rest of the page: path C, top-ups, the explorer, and using your own node. ## From the command line `ksana-cli` is the command-line client of a Ksana node. Here it talks to the hosted signet node over HTTPS; the faucet is a plain HTTP API, called with `curl`. ### Build ksana-cli The tested platform is Ubuntu 22.04. Install a C toolchain, `clang` and `libclang` (RocksDB is compiled from source), `git`, `curl`, `jq` (other pages use it to pick fields out of JSON) and `rustup`: ```sh title="Prerequisites on Ubuntu 22.04" sudo apt-get update sudo apt-get install -y build-essential clang libclang-dev git curl jq curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain none . "$HOME/.cargo/env" ``` Clone the repository and build. `rustup toolchain install` reads `rust-toolchain.toml` and installs the pinned Rust (1.98.1). The first build compiles RocksDB and wasmtime and can take half an hour on a small machine. ```sh git clone https://github.com/ksana-in-bitcoin/ksana cd ksana rustup toolchain install cargo build --release --locked -p ksana-cli export PATH="$PWD/target/release:$PATH" ksana-cli --version ``` ```output ksana-cli 0.1.0 ``` ### Make a key Point the CLI at the signet node, then create a key file. `key` writes a new random secret key to the file (mode `0600`) when the file does not exist, and prints its account and address; it never prints the secret. ```sh export KSANA_RPC=https://signet.ksana.network/rpc ksana-cli --chain signet key alice.key ``` ```output { "account": "db3fd0c741d4ba7641a00125bb7e76765ec923a4b86323b901dfb85fb16dea2b", "address": "tb1pmvlap36p6ja8vsdqqyjmklnkwe0vjgayhp3j8wgpm7u9lvtdag4s9ngk3n", "internal_key": "8ff637a4906fb51061c45cbff37ca22e753313b1d5d56bd7676c7dc5a17fc098", "script": "5120db3fd0c741d4ba7641a00125bb7e76765ec923a4b86323b901dfb85fb16dea2b" } ``` `address` and `account` are the same 32 bytes, written two ways: the Taproot address and its output key in hex. `--chain signet` makes `key` print a signet address; on every other command it makes the CLI refuse a node on another network. The key file is the only copy of the secret key: anyone who reads it controls the account, and losing it loses the account. ### Ask the faucet Send your address to the faucet. Replace the address below with the `address` your `key` command printed. ```sh curl -sS https://signet.ksana.network/faucet -H 'content-type: application/json' \ --data '{"to": "tb1pmvlap36p6ja8vsdqqyjmklnkwe0vjgayhp3j8wgpm7u9lvtdag4s9ngk3n"}' ``` ```output {"op_id":"89a278baadbd3162118630a5119a456c18af6e3e7c5b5d0761c62bb20656d7f0","to":"db3fd0c741d4ba7641a00125bb7e76765ec923a4b86323b901dfb85fb16dea2b","amount":"10000000000","nonce":"1"} ``` The faucet sends 100 KSA (`10000000000` base units: KSA has 8 decimals) as an ordinary transfer, and `op_id` identifies it. It answers as soon as the node accepts the transfer. Each account can ask once a day; [Public signet](https://ksana.network/docs/signet/) lists the other limits. ### Check your balance A few seconds later the transfer is in a block: ```sh ksana-cli account @alice.key ``` ```output { "account": "db3fd0c741d4ba7641a00125bb7e76765ec923a4b86323b901dfb85fb16dea2b", "address": "tb1pmvlap36p6ja8vsdqqyjmklnkwe0vjgayhp3j8wgpm7u9lvtdag4s9ngk3n", "at": { "hash": "d8a91f8bdec0fd69849615308b8b800eec04e6f0aee037ed6fa6e97950604cc1", "height": "26" }, "balances": [ { "amount": "10000000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000" } ], "locked_fees": [], "nonce": "0" } ``` `@alice.key` stands for the account of the key in that file; an address or 64 hex digits work too. The asset ID of KSA is 64 zeros. If `balances` is still empty, wait a few seconds and ask again. ### Send 1 KSA Make a second key to send to, then transfer 1 KSA (`100000000` base units) to it on path B with a fee of 1 base unit: ```sh ksana-cli --chain signet key bob.key ksana-cli --chain signet transfer --key alice.key --to @bob.key \ --amount 100000000 --fee-token 1 --wait ``` ```output { "account": "db3fd0c741d4ba7641a00125bb7e76765ec923a4b86323b901dfb85fb16dea2b", "nonce": "0", "op_id": "262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9", "status": { "block": { "hash": "2681d67b65bc2dabad6ada543bffcb4562ed5dfdb89c8e57f1dc89f75a021e4f", "height": "27" }, "index": 0, "receipt": { "asset_changes": [ { "amount": "100000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000", "events": 0, "from": "db3fd0c741d4ba7641a00125bb7e76765ec923a4b86323b901dfb85fb16dea2b", "kind": "transfer", "to": "9baa61325ed3b2e169065bdff5ffffe5f5b20ca90bf5f35301f44fb515d039cf" } ], "error": null, "events": [], "gas_used": "10000", "op_id": "262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9", "output": "", "success": true }, "status": "fast_confirmed" } } ``` `--wait` polls the node until the operation is executed; this one was fast-confirmed in block 27 about four seconds after it was sent. `--fee-token` is the path B fee in KSA base units, paid to the producer. `ksana-cli estimate-fee` prints the node’s suggestion, which was `1` just before this transfer: the signet nodes include any fee of at least `1` while their blocks have room. The receipt’s `asset_changes` lists what the operation did to built-in assets, here the 1 KSA from alice’s account to bob’s, as this version of the node records it; the signet’s nodes executed this transfer before they recorded such changes, so for it they answer `null`. ### Follow it to final The status of the operation changes from `fast_confirmed` to `btc_final` once its block is final: ```sh ksana-cli op 262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9 ``` ```output { "block": { "hash": "2681d67b65bc2dabad6ada543bffcb4562ed5dfdb89c8e57f1dc89f75a021e4f", "height": "27" }, "index": 0, "receipt": { "asset_changes": [ { "amount": "100000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000", "events": 0, "from": "db3fd0c741d4ba7641a00125bb7e76765ec923a4b86323b901dfb85fb16dea2b", "kind": "transfer", "to": "9baa61325ed3b2e169065bdff5ffffe5f5b20ca90bf5f35301f44fb515d039cf" } ], "error": null, "events": [], "gas_used": "10000", "op_id": "262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9", "output": "", "success": true }, "status": "btc_final" } ``` In between, the block’s settlement shows the on-Bitcoin mark: `settled` turns `true` once the Bitcoin transactions carrying this block, and every block before it, are mined. This answer is from when they had four confirmations (`jq` leaves out `txs`, the raw transactions): ```sh ksana-cli settlement 27 | jq 'del(.txs)' ``` ```output { "block": { "hash": "2681d67b65bc2dabad6ada543bffcb4562ed5dfdb89c8e57f1dc89f75a021e4f", "height": "27" }, "btc_final": false, "carrier": { "hash": "338c18790906240dd8c9943ce84e3b983b24fe2469811e19c45df773f73d0250", "height": "31" }, "carrier_account": "b40c816d58ee2578da0118a9c6feeca74b80280f92030bdfa510821ae2887954", "commit_txid": "393b36ea0b049dcd64ec8dfe39f558485965fecace3552d3da8cf95f463c5308", "commit_txid_rpc": "08533c465ff98cdad35235cecafe65594858f539fe8dec64cd9d040bea363b39", "confirmed": { "block": "c2d6d161fdef456778a3df4f2ffe65a4627ad100ccbd24122d78fd5006000000", "confirmations": 4, "height": 327281, "txid": "d2232fdbfa7d9b6f16c65cfc60645ccb4ca38fb6aa32f7711d0128b745124f5a" }, "settled": true, "status": "confirmed", "txid": "d2232fdbfa7d9b6f16c65cfc60645ccb4ca38fb6aa32f7711d0128b745124f5a", "txid_rpc": "5a4f1245b728011d71f732aab68fa34ccb5c6460fc5cc6166f9b7dfadb2f23d2" } ``` Block 27 had no settlement of its own: the settlement of block 31 carried its data (`carrier`), and signet block 327,281 included it. `btc_final` turns `true` five Bitcoin blocks after the sixth confirmation, once the Bitcoin block that gave it has six of its own. `txid_rpc` is the reveal transaction’s ID as explorers write it, as in [this one on mempool.space](https://mempool.space/signet/tx/5a4f1245b728011d71f732aab68fa34ccb5c6460fc5cc6166f9b7dfadb2f23d2). ## How long it took This page’s transfer went out on 21 October 2026 at 04:55:27 UTC. The times are when `ksana-cli` first showed each mark; after `--wait` returned, it was asked about every 15 seconds. | Mark | Seen at (UTC) | After sending | | --- | --- | --- | | Fast-confirmed, in block 27 | 04:55:31 | 4 seconds | | On Bitcoin, in signet block 327,281 | 05:02:04 | 7 minutes | | Six confirmations, at signet block 327,286 | 05:31:42 | 36 minutes | | Final, at signet block 327,291 | 05:44:09 | 49 minutes | The settlement of block 19 was still waiting for a signet block when this transfer went out, so block 27 had no settlement of its own: its data went with the settlement of block 31, whose contract deployment, at over 10 KiB, is large enough to settle without waiting. Signet block 327,281, the first in 21 minutes, confirmed both settlements. The sixth confirmation came 30 minutes after the on-Bitcoin mark, and final 12 minutes after that: the ten signet blocks after 327,281 came between 2 seconds and 10 minutes apart, about 4 minutes on average. Signet blocks come every ten minutes on average, so expect about an hour to the sixth confirmation and about 110 minutes to final, and sometimes more. ## Where to go next - [How Ksana works](https://ksana.network/docs/how-it-works/) The fast lane, settlement into Bitcoin, and finality decided from Bitcoin. - [Operations and fees](https://ksana.network/docs/submitting-ops/) Path B, path C and top-ups, and what each costs. - [ksana-cli](https://ksana.network/docs/cli/) Every command: queries, contracts, path C and the exchange. - [Run a node](https://ksana.network/docs/run-a-node/) Follow the signet yourself, check every block against Bitcoin, and mine. --- # How Ksana works URL: https://ksana.network/docs/how-it-works/ > Ksana executes your operations in its own fast blocks within seconds, writes every block’s data into Bitcoin transactions, and decides from Bitcoin data alone which blocks are final. Ksana is a smart contract system whose record lives on Bitcoin. Producers mine blocks every few seconds and execute operations at once; the data of every block then goes into ordinary Bitcoin transactions, and a block becomes final once that data has six Bitcoin confirmations and five more blocks have secured the decision. Anyone with a Bitcoin node can rebuild and check the whole state from Bitcoin alone. Mainnet has not launched: the [public signet](https://ksana.network/docs/signet/) runs everything this page describes. ## Two chains, one record *Figure: Fast-lane blocks run above and Bitcoin blocks below: each settlement drops a stretch of the fast lane into a Bitcoin block, and its operations move from fast-confirmed to on Bitcoin to final. The break in both rails leaves out five Bitcoin blocks.* Ksana splits the work between two chains. The **fast lane**, Ksana’s own chain of proof-of-work blocks, orders and executes operations within seconds. **Bitcoin** stores the data of every fast-lane block and decides finality: at six confirmations of that data every node decides the block final, and once that decision is six blocks deep too, undoing it takes a Bitcoin reorganization of at least six blocks. So every operation passes three marks: **fast-confirmed** once a fast-lane block has executed it (about 5 seconds), **on Bitcoin** once the block’s data is in a Bitcoin block, and **final** once that data has six Bitcoin confirmations and five more blocks have secured the decision. [Confirmations](https://ksana.network/docs/confirmations/) explains what each mark guarantees and how long to wait for it. Bitcoin never moves into Ksana. A contract can check that a Bitcoin payment happened, with a Merkle proof against a Bitcoin header or by reading the transaction that carried its operation, but no Ksana rule can spend bitcoin. BTC changes hands only in Bitcoin transactions that you sign yourself, as in a [top-up](https://ksana.network/docs/submitting-ops/#top-up). ## The fast lane ### Producers and proof of work Anyone can produce blocks: start `ksana-node` with a producer account and it mines. A producer collects operations, executes them, writes the resulting state root into the block header and solves a proof of work. The work is Argon2id with 2 MiB of memory, about 1 ms per attempt on one CPU core, chosen so that ordinary computers can mine and a browser can verify a header. The difficulty adjusts at every block so that blocks come about every 5 seconds while there are operations to include; with nothing to include, producers mine empty blocks, which are harder and come minutes apart. Producers earn KSA for their blocks. [Mining](https://ksana.network/docs/mining/) covers the algorithm, the difficulty and the costs, and [KSA and rewards](https://ksana.network/docs/ksa/) the rewards. ### A block DAG, not a chain At one block every 5 seconds, two producers often find blocks at nearly the same moment. Instead of discarding one, Ksana keeps both: a block names up to 10 parents, so the blocks form a directed acyclic graph (DAG), and GHOSTDAG, the protocol Kaspa uses, puts the whole graph in one order. Each block has a **selected parent**, the parent with the most work behind it, and following selected parents back from the best tip gives the **main chain**. A main-chain block merges the blocks in its past that nothing has ordered yet, its **merge set**: it executes their entries first, in a fixed order, then its own. An operation in a merged block takes effect at the height of the main-chain block that merges it; an entry that conflicts with one ordered before it (the same operation twice, a nonce already used, a balance already spent) is skipped and pays no fee. GHOSTDAG also colors blocks blue or red. A blue block was visible to the rest of the network in good time; a red block stayed out of sight too long, possibly an attacker’s, and still has its entries executed but earns no block reward. ### Anchors Every block names a Bitcoin block, its **anchor**. A producer anchors `ANCHOR_DEPTH` blocks below its Bitcoin tip (1 on signet, 2 on mainnet, 0 on devnet) and never below the anchors of the block’s parents. Execution reads Bitcoin only up to the anchor: the path C transactions a block must include, the Bitcoin headers a contract may read, and which blocks’ data has landed. So every node computes the same result whatever its own Bitcoin tip. The depth absorbs shallow Bitcoin reorganizations: one of at most `ANCHOR_DEPTH` blocks orphans no anchor, so the main chain and its state stay as they are. A deeper one takes the blocks anchored on the orphaned Bitcoin blocks off the main chain, and their path B operations return to the entry pool to be included again with the same op ID, on the nodes that hold [the second halves of their signatures](https://ksana.network/docs/submitting-ops/#signatures-in-a-block). ## Settlement into Bitcoin *Figure: A settlement is a commit and reveal pair: the producer’s funding pays the commit, and the reveal’s Taproot witness carries the KSN1 envelope with the block’s data.* A block’s data reaches Bitcoin in a **settlement** of two transactions. The **commit transaction** spends the producer’s own bitcoin and creates a Taproot output committing to a script that holds the data. The **reveal transaction** spends that output, so the data appears in its witness, inside a `KSN1` envelope. The commit’s only output is that commitment, and the reveal’s only output returns the change to the producer, who can raise the pair’s fee by spending it in a child transaction (CPFP). The data in the envelope may be compressed with zstd; a node decompresses it before checking it against the block. Two transactions are needed because in a single one the data could sit only in a witness element that no signature covers, which any relayer could swap without changing the transaction ID; committing to the script in an output first fixes it. In the witness, each byte of data costs a quarter of a vbyte. The **payload** in the envelope holds the block’s header and entries, the headers of earlier blocks that have not counted on Bitcoin yet, and the entries (bodies) of earlier blocks that carried no settlement. A header **counts** on Bitcoin once its anchor is on Bitcoin’s best chain and its parents have counted, so a payload carries every header its block needs; a body lands only with its counted header, and only when it matches the header’s entries root. Headers and entries are encoded compactly: in a run of empty blocks each header after the first takes 14 bytes, and a path B KSA transfer takes 79 to 143 bytes. An ordinary settlement measured 154 vB for the commit and 209 vB for the reveal on regtest. A block with no entries, or only path C entries, needs only its header on Bitcoin, because anyone can derive its entries from Bitcoin. A producer broadcasts a settlement once the block that carries it is 2 blocks deep on the main chain (`SETTLEMENT_DEPTH`), so that a brief fork of the fast lane does not send two conflicting settlements to Bitcoin. The signed transactions travel inside the block, so any node can broadcast them. ### Batching and who pays Not every block carries a settlement. By default a block carries one when there is a body to land (its own or an earlier block’s) and no earlier settlement is still waiting to confirm; otherwise it leaves its body for the next settlement, unless the bodies waiting, or its own, pass 10 KiB (an eighth of the payload limit). A busy chain therefore sends about one settlement per Bitcoin block, carrying everything since the last one. The producer whose block carries a settlement pays its Bitcoin fee from its own funding wallet. In return it becomes the **carrier** of every block whose data that settlement lands first, and earns 5% of those blocks’ rewards and half of their path B fees. You pay only KSA on path B, and only your own Bitcoin fee on path C. ### When data does not land The fast lane depends on its data reaching Bitcoin, so the rules make sure someone lands it: - **Rescue**: when a settlement cannot confirm (its funding was spent, or its fee stays too low), or confirmed before the headers it needs from earlier blocks had counted and so landed nothing, nodes send the same payload again with their own funding, taking turns in main-chain order. - **Republish**: anyone may send missing headers and bodies in a payload that names a payee. The payee becomes the carrier of the blocks whose data it lands first, when that data lands more than `ANCHOR_DEPTH` + 2 Bitcoin blocks above their anchor (more than 3 on the signet), which leaves the producers’ own settlements time to land first. - **Unlock**: nobody receives a block’s rewards or fees until the data of that block and of every block before it is on Bitcoin, so every later producer wants missing data landed. - **Backlog limit**: when a body is still missing 6 Bitcoin blocks after its block’s anchor (`SETTLEMENT_TIMEOUT`), new blocks may hold only path C entries until it lands. Path B pauses; path C keeps working. ## Finality from Bitcoin Every node and every indexer decides finality with the same function of Bitcoin data, so they reach the same answer without trusting one another. The headers that count on Bitcoin form a DAG of their own. At each Bitcoin height, the function takes the heaviest fast-lane chain among those headers and walks it from the last block decided final: a block is **decided final** when its data, and the data of the blocks it merges, has 6 Bitcoin confirmations (`BTC_FINALITY_CONFS`) and executing it gives a valid result. Nodes and indexers report it **final** (`btc_final`) once the Bitcoin block of that decision has 6 confirmations too, so at the earliest five Bitcoin blocks after the sixth confirmation of its data. What this means when someone builds a competing fast-lane chain: - Until a block is final, a heavier chain can replace it. That is the risk you weigh when you accept a fast confirmation. - A heavier chain that keeps its data off Bitcoin cannot become final. A lighter chain that lands its data in time is finalized first, and the heavier one is finalized out. - When a lighter competing chain appears on Bitcoin and a node’s own chain is still missing there one Bitcoin block later, the node republishes its headers at its highest fee rate, so the honest chain lands before the other side’s data has six confirmations. - Fast-lane hashrate alone cannot undo a final block: that takes a Bitcoin reorganization of at least 6 blocks, reaching the Bitcoin block that decided it, and every Bitcoin block mined after that makes the reorganization deeper. [Security](https://ksana.network/docs/security/#bitcoin-reorgs) covers Bitcoin reorgs. Only a valid block is decided final. A block whose anchor, or the anchor of a block it merges, is not on the Bitcoin best chain is excluded first, and a block whose execution is invalid is excluded together with every block built on it; the function then takes the next best chain. Every node’s main chain must pass through the blocks decided final, and a node that lacks one rebuilds it from the data on Bitcoin. `ksana_getChainInfo` reports the newest final block as `finalized`. ## Getting an operation in You can send an operation in two ways: - **Path B (sponsored)**: sign the operation with a fee in KSA and send it to any node. A producer includes it within seconds and pays the Bitcoin fee that lands it. - **Path C (native)**: put the operation in a Bitcoin transaction of your own, in a `KSN1` data output, and pay the Bitcoin fee. Once the transaction has 2 confirmations on signet (5 on mainnet), the fast lane must include it, ahead of every other entry: **forced inclusion**. A producer may refuse path B operations, but a block that leaves out a path C operation is invalid. Path C is the guarantee that no producer can keep you out, and the way to act with bitcoin alone: in a top-up, one Bitcoin transaction pays a seller for KSA held in an exchange contract. [Operations and fees](https://ksana.network/docs/submitting-ops/) covers both paths, the fees and top-ups. ## The indexer *Figure: Wallets and apps call a node’s JSON-RPC, nodes anchor to Bitcoin and land their settlements there, and the indexer rebuilds the chain from bitcoind alone and checks the state roots.* The indexer connects only to bitcoind, never to a Ksana node. It reads the payloads on Bitcoin, rebuilds the block DAG, chooses the main chain by the same rules as the nodes, executes every block with the same code and checks each block’s state root against its header. The signatures are among what it checks: a block on Bitcoin holds half of each path B signature and one aggregate for the rest, and the indexer verifies that aggregate. It runs the same finality function and reports the same `finalized` block. So the record does not depend on any Ksana node staying online or honest: if every node vanished, anyone could rebuild the full state from Bitcoin. The indexer disqualifies a block with an invalid body or a wrong state root and chooses its main chain again. [Run an indexer](https://ksana.network/docs/run-an-indexer/) shows how to run one and compare it with a node. ## Execution Contracts are WebAssembly modules, usually written in Rust with `ksana-contract-sdk`, and run by wasmtime 49.0.1. The rules exclude everything that could differ between machines (floating point, unbounded memory and stack, a changing wasmtime version), so the same state and the same entries give the same state root on every computer. Accounts, KSA and other built-in assets are native modules: a transfer needs no contract. Every operation carries a gas limit, `max_gas`. Ordinary WebAssembly instructions cost 1 gas, host functions and built-in actions have fixed prices (a KSA transfer costs 10,000), and an operation that would use more than its limit fails. An operation that fails while it runs still pays its fee and uses its nonce; everything else it did is rolled back. State lives in a Jellyfish Merkle tree, and each block header carries the tree’s root after the block executes: the **state root** that nodes and indexers compare. A block that holds no entries and merges none writes no state, so its state root equals its selected parent’s. [Write a contract](https://ksana.network/docs/contracts/) starts the contract side. ## The full rules The specification, `docs/SPEC.md`, holds every rule this page summarizes: - [§6 Fast-lane blocks, consensus and fork choice](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#6-fast-lane-blocks-consensus-and-fork-choice): GHOSTDAG, anchors, difficulty, and [§6.5 BTC-anchored finality](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#65-btc-anchored-finality). - [§7 Settlement transactions and forced inclusion](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#7-settlement-transactions-and-forced-inclusion): the data format, settlement, rescue, forced inclusion, batching and republishing. - [§8 Fees, incentives and unlocking](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#8-fees-incentives-and-unlocking): fees, rewards, the carrier and unlocking. - [§9 VM and execution environment](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#9-vm-and-execution-environment) and [§10.3 Standalone indexer](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#103-standalone-indexer). --- # Confirmations and finality URL: https://ksana.network/docs/confirmations/ > An operation passes three marks. It is fast-confirmed within seconds, on Bitcoin once its block’s data is in a Bitcoin block, and final after six Bitcoin confirmations and five more blocks that secure the decision. This page says what each mark protects against and how long to wait. Every operation you send passes three marks, and you choose which one to wait for by what is at stake. A fast confirmation is protected only by the fast lane’s own proof of work; a final block can be undone only by reorganizing at least six blocks of Bitcoin. Mainnet has not launched, and the public signet, where you can watch the marks today, has too little hashrate for its fast confirmations to protect much ([see below](#on-the-signet)). ## The three marks *Figure: The three marks of an operation, and the six confirmations before the last: fast-confirmed in about 5 seconds, on Bitcoin with the next Bitcoin block after its settlement, six Bitcoin confirmations about an hour after you send, and final five Bitcoin blocks later.* | Mark | What has happened | Typical time | | --- | --- | --- | | Fast-confirmed | The node’s main chain accepted the operation, and it executed successfully. | About 5 seconds | | On Bitcoin | The data of the block that accepted it, and of every block before it, is in a Bitcoin block. | The next Bitcoin block after its settlement goes out | | Final | Every node and indexer decided from Bitcoin that the block is final when that data had 6 confirmations, and the Bitcoin block of that decision has 6 confirmations too. | From about 110 minutes | On the way to final, the data reaches six Bitcoin confirmations about an hour after you send. That is the depth Bitcoin wallets treat as settled, and the Bitcoin block that gives it is where every node decides the block final. The [signet wallet](https://ksana.network/docs/wallet/) shows it as a step of its own, but it is not a status of the RPC, and not final yet: see [Final](#final). ## Statuses in the RPC `ksana_getOpStatus`, which `ksana-cli op` and the SDK’s `getOpStatus` call, answers with one of five statuses: | Status | Meaning | | --- | --- | | `pending` | In this node’s entry pool, not in a block yet. | | `fast_confirmed` | Included and executed successfully: the fast-confirmed mark. | | `failed` | Included, but it failed, and its changes were rolled back. The fee is still paid, and the nonce is used, except by a path C operation that failed its checks (version, chain ID, length, fee mode, signature or nonce). | | `skipped` | Included only by merged blocks that could not execute it (a duplicate, a nonce already used, a balance already spent). No fee is charged, and the status can still change. | | `btc_final` | Executed successfully, and the main-chain block that accepted it is final. | What to watch for when you read them: - **On Bitcoin is not an op status.** Ask for the settlement of the op’s block with `ksana_getSettlement`: `settled` turns true once the data of the main-chain block that accepted it, and of everything before it, is on Bitcoin, and `btc_final` once it is final. A block with no settlement of its own, an empty block or one holding only path C operations, answers `-32004`. Once a main-chain block is settled or final, so is every block below it, so read the marks from the next block up that has a settlement. - **A failed op stays `failed`**, even after its block is final. Check `btc_final` of its block’s settlement to know that the failure itself is final. - **`skipped` is not the end.** A skipped op that is still valid returns to the entry pool and can be included again, so it may read `pending` and then `fast_confirmed`. - **An unknown op is an error**, code `-32004`. A path C operation is unknown to the nodes until a block includes it, and an op that left the entry pool (replaced by one with a higher fee, or evicted from a full pool) returns the same error. - **`block`** gives the hash of the block that included the op and, as `height`, the height of the main-chain block that accepted it: for a merged block, the height where its operations took effect. ## What each mark guarantees ### Fast-confirmed Your operation has executed on the node’s main chain: balances and contract state include it, and later operations build on it. Only the fast lane’s proof of work protects it. Until its block is final, a heavier fast-lane chain can replace the block, and a payment is reversed if the sender gets a conflicting operation (another one with the same nonce) into that chain. A Bitcoin reorganization can also take a fast-confirmed block back. One of at most `ANCHOR_DEPTH` blocks (1 on signet, 2 on mainnet) orphans no anchor and leaves the main chain as it is, and a deeper one takes the blocks anchored on the orphaned Bitcoin blocks off the main chain. Their path B operations return to the entry pool and are included again with the same op ID, so an honest payment comes back by itself (on a node that rebuilt the block from Bitcoin and so lacks [the second halves of its signatures](https://ksana.network/docs/submitting-ops/#signatures-in-a-block), it does not, and the sender submits it again); only a sender who gets a different operation with the same nonce in first turns such a reorganization into a reversal. ### On Bitcoin The data of the block that accepted your operation, and of every block before it, is in a Bitcoin block. From now on anyone with a Bitcoin node can read the operation and recompute its effect without any Ksana node, and an indexer executes the block once it is 2 blocks deep in the fast lane or decided final. The rewards and fees of the block can now be paid out. This mark is about availability, not finality. A heavier fast-lane chain can still replace the block until it is final, and a Bitcoin reorganization can take the transaction that carries the data out of its block until it confirms again. ### Final The main-chain block that accepted your operation is on the final chain. When its data and the data of the blocks it merges had 6 Bitcoin confirmations and its execution was checked, every node and indexer reached the same decision from Bitcoin data alone: the block is final. They report it final once the Bitcoin block of that decision has 6 confirmations too, so at the earliest five Bitcoin blocks after the sixth confirmation of the data. Until then a heavier fast-lane chain together with a Bitcoin reorganization of fewer than 6 blocks could still replace the block, so the six confirmations alone are not final. Once final, no fast-lane chain can replace it, however much hashrate is behind it: a competing chain counts only if its headers had counted on Bitcoin, each after its parents, by the Bitcoin block that gave your block’s data its sixth confirmation. Undoing it takes a Bitcoin reorganization of at least 6 blocks that reaches the Bitcoin block of the decision. With a heavier fast-lane chain on the new Bitcoin branch, that is enough; without one, your block is decided again on the new branch, and it leaves the final chain only if the reorganization also removes its data, 5 blocks deeper still. A final block grows safer with every Bitcoin block after it, as a Bitcoin transaction does ([Security](https://ksana.network/docs/security/#bitcoin-reorgs)). ## How long each mark takes - **Fast-confirmed**: about 5 seconds for path B on signet and mainnet alike. A path C operation is fast-confirmed only once its Bitcoin transaction has `NATIVE_CONFIRMATIONS` + `ANCHOR_DEPTH` confirmations: 2 on signet, 5 on mainnet. - **On Bitcoin**: a settlement goes out once the block is 2 fast-lane blocks deep, and its data lands in the next Bitcoin block that takes it, about 10 minutes on average on both networks. While an earlier settlement is still waiting to confirm, your block’s data waits for the next one, which adds about one Bitcoin block. - **Final**: the data has six confirmations five Bitcoin blocks after it lands, about an hour after you send the operation; every node decides the block final there, and reports it final five Bitcoin blocks later, once the Bitcoin block of that decision has six confirmations too: from about 110 minutes after you send. On a quiet chain the 2 blocks after yours are usually empty blocks, which take minutes ([Mining](https://ksana.network/docs/mining/) explains why), so the settlement leaves a few minutes later than on a busy chain. Here is the transfer of the [quickstart](https://ksana.network/docs/quickstart/#how-long-it-took), on the signet on 21 October 2026, with each step at the time it was first seen: | Time (UTC) | What happened | Mark | | --- | --- | --- | | 04:55:31 | Block 27 includes a KSA transfer, while the settlement of block 19 still waits for a signet block. | Fast-confirmed | | 04:56:35 | Block 31 holds a contract deployment of over 10 KiB, enough to settle without waiting, and carries a settlement with block 27’s body. | | | 04:56:52 | Block 33 makes block 31 2 blocks deep, and its settlement goes out. | | | 05:02:04 | Signet block 327,281, the first in 21 minutes, confirms that settlement and block 19’s. | On Bitcoin, after 7 minutes | | 05:31:42 | Signet block 327,286 gives it 6 confirmations: block 27 is decided final. | Six confirmations, after 36 minutes | | 05:44:09 | Signet block 327,291 gives signet block 327,286, which decided it, its sixth confirmation. | Final, after 49 minutes | ## How long to wait How safe a fast confirmation is depends on the attacker’s share of the fast lane’s hashrate and on whether the chain is busy. In the model of [SPEC §10.4](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#104-the-two-confirmation-statuses), an attacker with a share α of the hashrate mines a private branch from the parent of the block that holds your payment and publishes it if it pulls ahead. These tables give the chance that a payment you accepted after the given wait is reversed (the best of three attacker strategies, 50,000 simulated races per cell). A busy chain, where blocks carry other users’ operations: | Wait | α = 5% | α = 10% | α = 20% | | --- | --- | --- | --- | | 30 seconds | 2.0% | 7.5% | 27% | | 1 minute | 1.5% | 6.5% | 25% | | 5 minutes | 0.06% | 0.91% | 9.3% | | 10 minutes | 0.03% | 0.37% | 5.7% | | 30 minutes | 0.002% | 0.05% | 2.3% | An idle chain, where only empty blocks follow yours: | Wait | α = 5% | α = 10% | α = 20% | | --- | --- | --- | --- | | 30 seconds | 26% | 43% | 69% | | 1 minute | 20% | 33% | 58% | | 5 minutes | 4.3% | 13% | 37% | | 10 minutes | 1.8% | 7.7% | 28% | | 30 minutes | 0.38% | 2.6% | 13% | On an idle chain the honest work arrives in empty blocks of weight 12 to 120, each taking minutes, so for minutes your payment is protected by little more than its own block. On a busy chain an attacker’s lucky empty block weighs as much as 12 honest blocks and counts as soon as it is found, which is why even there short waits carry some risk. So choose by what is at stake: - **Small amounts**: fast-confirmed is enough. - **Moderate amounts on a busy chain**: wait about 5 minutes. - **Large amounts, or anything that matters on an idle chain**: wait for final. A miner who can reorganize Bitcoin is a different threat: against such a miner a fast confirmation is worth only its anchor’s Bitcoin confirmations. Reversing a block made m Bitcoin blocks ago takes a reorganization of at least `ANCHOR_DEPTH` + 1 + m blocks, 3 + m on mainnet; such a miner could double-spend bitcoin as well. Undoing a final block takes a Bitcoin reorganization of at least 6 blocks, as [Final](#final) explains. ### On the signet The signet’s difficulty was set for its two seed nodes, which mine on one CPU core each, so a computer with a few cores can outpace them. Use the signet to see how the marks behave, not to judge how safe they are; signet coins have no value anyway. ## Reading the marks Ask a node for the op’s status, then for the settlement of the block that included it: ```typescript title="TypeScript" import { KsanaRpcClient, RpcError, SIGNET } from '@ksana/sdk'; const rpc = new KsanaRpcClient('https://signet.ksana.network/rpc'); await rpc.getParams(SIGNET); // throws ChainMismatchError for a node on another network const opId = '262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9'; const status = await rpc.getOpStatus(opId); // throws RpcError -32004 for an unknown op let mark = 'none yet'; if (status.block !== null && (status.status === 'fast_confirmed' || status.status === 'btc_final')) { mark = 'fast-confirmed'; // From the op's height up, the first main-chain block with a settlement of its own const tip = (await rpc.getChainInfo()).tip.height; for (let height = status.block.height; height <= tip; height++) { try { const settlement = await rpc.getSettlement(height); if (settlement.settled) mark = 'on Bitcoin'; if (settlement.btc_final) mark = 'final'; break; } catch (e) { if (!(e instanceof RpcError && e.code === -32004)) throw e; // none of its own } } } console.log(status.status, mark); ``` ```sh title="CLI" export KSANA_RPC=https://signet.ksana.network/rpc ksana-cli --chain signet op 262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9 ksana-cli --chain signet settlement \ 2681d67b65bc2dabad6ada543bffcb4562ed5dfdb89c8e57f1dc89f75a021e4f \ | jq '{status, settled, btc_final}' ``` ```sh title="curl" op=262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9 curl -s https://signet.ksana.network/rpc -H 'content-type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"ksana_getOpStatus","params":["'$op'"]}' \ | jq .result ``` The op status, as `ksana-cli` printed it for the transfer in the timeline above, with its `asset_changes` as this version of the node records them (the signet’s nodes executed this transfer before they recorded such changes, so for it they answer `null`): ```output { "block": { "hash": "2681d67b65bc2dabad6ada543bffcb4562ed5dfdb89c8e57f1dc89f75a021e4f", "height": "27" }, "index": 0, "receipt": { "asset_changes": [ { "amount": "100000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000", "events": 0, "from": "db3fd0c741d4ba7641a00125bb7e76765ec923a4b86323b901dfb85fb16dea2b", "kind": "transfer", "to": "9baa61325ed3b2e169065bdff5ffffe5f5b20ca90bf5f35301f44fb515d039cf" } ], "error": null, "events": [], "gas_used": "10000", "op_id": "262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9", "output": "", "success": true }, "status": "btc_final" } ``` And the settlement of block 27, which a later block carried: ```output { "status": "confirmed", "settled": true, "btc_final": true } ``` `status` here is the settlement’s own progress: `pending` before it is broadcast (the block is not 2 blocks deep yet, or no block carries its data yet), `broadcast` while it waits for a Bitcoin block, and `confirmed` once the data is in one; `confirmed.confirmations` then counts its Bitcoin confirmations. For the chain as a whole, `ksana_getChainInfo` reports the newest final block as `finalized`: an operation accepted at or below `finalized.height` on the node’s main chain is final. The indexer’s `indexer_status` reports `finalized` from Bitcoin alone, so comparing the two checks the node. The [signet wallet](https://ksana.network/docs/wallet/) shows the same marks for every operation it sends, and the sixth confirmation as a milestone before final. --- # Accounts and addresses URL: https://ksana.network/docs/accounts/ > Your Ksana account is your Taproot address. The key behind a `tb1p` or `bc1p` address receives bitcoin on Bitcoin, holds KSA and tokens on Ksana, and signs your operations. ## One key, one address A Ksana account is 32 bytes: the output key of a Taproot address (a BIP86 key-path key, with no script tree). The address is the bech32m spelling of the same 32 bytes, so an account and its address convert into each other both ways. Wherever Ksana asks for an account (ksana-cli, the TypeScript SDK, the node’s `--producer`), you can give the address or the 64 hex digits. | Network | Address starts with | Bitcoin network | | --- | --- | --- | | devnet | `bcrt1p` | regtest | | signet | `tb1p` | signet | | mainnet | `bc1p` | mainnet (Ksana mainnet has not launched) | There is one thing to copy and nothing to convert: the address someone gives you for bitcoin is the one you use to send them KSA, and pasting it in the wrong place still lands on their key. Other address types (`tb1q` P2WPKH, P2SH, legacy) cannot be accounts. Only a Taproot address is a single 32-byte key that signs, and clients refuse to read anything else as an account. `ksana-cli key` creates a key file when it does not exist (64 hex digits, file mode 0600) and prints both forms: ```sh ksana-cli --chain signet key alice.key ``` ```output { "account": "5b276a0956672ea3037ef7758651f99ac7d0bd18b7a6ba31d913fe3855a29f03", "address": "tb1ptvnk5z2kvuh2xqm77a6cv50entrap0gck7nt5vwez0lrs4dznupsucam9p", "internal_key": "50515c21347f82ea2eb7fdadc95c50d812ea1490e042e67289144278e79931d8", "script": "51205b276a0956672ea3037ef7758651f99ac7d0bd18b7a6ba31d913fe3855a29f03" } ``` `account` is the Taproot output key that operations name, and `address` is the same bytes as a signet address. `internal_key` is the untweaked key inside it, and `script` is the address’s output script, `OP_1` followed by the account. With the SDK, `parseAccount` reads either form and `accountToAddress` spells an account as an address: ```typescript import { accountToAddress, parseAccount, toHex } from '@ksana/sdk'; const address = 'tb1ptvnk5z2kvuh2xqm77a6cv50entrap0gck7nt5vwez0lrs4dznupsucam9p'; const account = parseAccount(address, 'signet'); // 32 bytes: the Taproot output key console.log(toHex(account)); // 5b276a0956672ea3037ef7758651f99ac7d0bd18b7a6ba31d913fe3855a29f03 console.log(accountToAddress(account, 'signet') === address); // true ``` **A key file is a Bitcoin key too.** Whoever holds `alice.key` can spend the bitcoin sent to its address as well as its KSA. Keep test keys for test networks: the same key is the same account on every network, and its `bc1p` spelling is a real Bitcoin address. ## Keys and signatures Every operation carries a signature by its account. Two forms are accepted, and both prove control of the same Taproot key: - **BIP340**, used by ksana-cli and by the SDK with a local key: a Schnorr signature verified against the account itself. Because the account is the tweaked output key, the signer signs with the BIP86-tweaked private key, as a Taproot key-path spend does. - **BIP322 simple**, used by browser wallets: the wallet signs a text message, the operation’s signature hash written as 64 lowercase hex digits, with its Taproot address. Unisat signs with `signMessage(message, 'bip322-simple')`; Xverse signs with its Ordinals address, which is Taproot. Xverse’s payment address, usually P2SH-P2WPKH, cannot be an account. The signature hash is a tagged hash (`Ksana/VmOp/v1`) of the operation without its signature; for path C it also covers the outpoint that the carrying Bitcoin transaction’s first input spends. The tag keeps a Ksana signature from ever being valid as a Bitcoin transaction signature. The chain ID in the operation keeps it from being replayed on another network, and the nonce keeps it from running twice on this one. Both forms end in one Schnorr signature of 64 bytes. You submit it whole; a block keeps the first half of a path B operation’s signature and one aggregate for the second halves of all of them, which is verified for the block as a whole ([Signatures in a block](https://ksana.network/docs/submitting-ops/#signatures-in-a-block)). **Read what you sign.** The protection is one-way. A page that asks your wallet for a BIP322 signature of a “random” string of 64 hex digits may be showing you the signature hash of a Ksana operation that spends your KSA. Sign Ksana operations only where you see the decoded operation first, as the [signet wallet](https://ksana.network/docs/wallet/) shows it before you sign. ## Nonces Each account has a nonce: 0 for a new account, and one higher after each of its operations that runs, whether it succeeds or fails. An operation’s nonce must equal the account’s nonce when it executes, so each operation runs once, in the order you numbered them. - **Several path B operations**: a node’s entry pool keeps up to 64 operations per account, numbered from the account’s nonce, at most 8 of them behind a gap in the numbering. A new operation with the same nonce replaces the waiting one only with a fee at least a tenth higher, and higher by at least the node’s relay floor. ksana-cli fills in the account’s nonce from the node, so to send a second operation before the first is included, pass `--nonce` with the next number. - **Path C**: an operation with the wrong nonce, or a signature that does not check out, fails without using the nonce. Path B and path C share the nonce, and a path C operation runs only after its Bitcoin confirmations, so a path B operation with the same nonce that gets in first makes the path C operation fail, and its Bitcoin fee is lost. While a path C operation waits, give your path B operations the nonces after it. - **Top-ups** sign their claim with a one-time key at nonce 0, so they never compete with your account’s operations ([Operations and fees](https://ksana.network/docs/submitting-ops/#top-up)). ## Balances and assets The chain keeps one balance table for every 32-byte account, people and contracts alike, with an amount per asset: - **KSA**, the built-in token: asset ID of 32 zero bytes, 8 decimals. Amounts are whole numbers of base units: 1 KSA is 100,000,000 base units. - **Built-in assets issued by contracts**: a contract creates its own assets with the `asset_create` or `asset_issue` host function. Each asset ID is the SHA-256 of the contract ID followed by a 32-byte `sub_id` that the contract picks. These assets move with the same transfer action as KSA and can be attached to contract calls. An asset’s issuer may hold capabilities it declared when it created the asset, such as freezing an account or pausing the asset; `ksana_getAsset` lists them, and none of them lets the issuer take a balance ([Host functions](https://ksana.network/docs/host-functions/#assets)). - **Token contracts**, such as the `token` example, keep balances in their own storage. You move those by calling the contract, and the account query does not list them: ask the contract, for example with its `balance_of` method. `ksana-cli account` (the RPC method `ksana_getAccount`) shows an account’s nonce and built-in balances. This is the signet faucet’s account: ```sh export KSANA_RPC=https://signet.ksana.network/rpc ksana-cli --chain signet account tb1pmenq8uzjl4dl4tjk0z32yzhx4e87ftsqezwmwz3wl6n59xz34lqqlgaqc2 ``` ```output { "account": "de6603f052fd5bfaae5678a2a20ae6ae4fe4ae00c89db70a2efea7429851afc0", "address": "tb1pmenq8uzjl4dl4tjk0z32yzhx4e87ftsqezwmwz3wl6n59xz34lqqlgaqc2", "at": { "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f", "height": "61" }, "balances": [ { "amount": "9999949999999995", "asset": "0000000000000000000000000000000000000000000000000000000000000000" } ], "locked_fees": [], "nonce": "5" } ``` `at` is the block the answer comes from. `locked_fees` lists, for a producer, the rewards and fees that will be credited once its blocks’ data is on Bitcoin ([KSA and rewards](https://ksana.network/docs/ksa/)). ## Contracts have IDs, not addresses A contract is named by a 32-byte contract ID: - deployed from an account: the SHA-256 of the deployer’s account, the deploy operation’s nonce as 8 little-endian bytes, and the SHA-256 of the code, one after another; - created by another contract: the SHA-256 of the creating contract’s ID, a 32-byte salt it chooses, and the SHA-256 of the code. A contract ID is not a key: nobody can sign for it, and only the contract’s own code moves its assets. That is why a contract has no address, and why you write it as 64 hex digits. It shares the balance table with every other account, so you can send KSA to a contract ID with an ordinary transfer. **Never send bitcoin to a contract ID.** Some contract IDs happen to be valid Taproot keys, and for those ksana-cli’s `account` command and the SDK’s `accountToAddress` print a `tb1p` address. Nobody holds a key for it: bitcoin sent there can never be spent. ## Bitcoin and KSA stay apart Your address holds bitcoin on Bitcoin and KSA on Ksana, and the two ledgers never mix: - Bitcoin sent to your address gives you no KSA, and KSA cannot be withdrawn as bitcoin. - Your Bitcoin wallet shows your bitcoin; the [signet wallet](https://ksana.network/docs/wallet/), ksana-cli or any node shows your KSA. - To turn bitcoin into KSA, [top up](https://ksana.network/docs/submitting-ops/#top-up): one Bitcoin transaction pays a seller who has locked KSA in an exchange contract, and the contract credits you. The full rules for accounts, signatures and nonces are in [SPEC §4](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#4-accounts-signatures-and-vmop). --- # Operations, paths and fees URL: https://ksana.network/docs/submitting-ops/ > Everything you do on Ksana is one signed operation. Send it to any node and pay a fee in KSA (path B), or put it in a Bitcoin transaction of your own and pay only the Bitcoin fee (path C). A transfer, a contract call and a deployment are all operations: one signed message from one account. Path B sends it through any Ksana node for a fee in KSA; path C sends it through Bitcoin for the Bitcoin fee alone, and no producer can refuse it. ## What an operation is An operation, a `VmOp` in the code, has these fields, in this order (the order is the encoding): | Field | What it holds | | --- | --- | | `version` | 2, the current format | | `chain_id` | The network: 1002 on signet, 1000 on mainnet, 1001 on devnet. The operation is valid nowhere else. | | `account` | The signing account ([Accounts](https://ksana.network/docs/accounts/)) | | `nonce` | The account nonce this operation uses | | `fee` | `Token { amount }`, a KSA amount in base units, for path B; `BtcNative` for path C | | `max_gas` | The most gas the operation may use | | `action` | What to do | | `sig` | A BIP340 or BIP322 simple signature over all of the above | The action is one of three: - `AssetTransfer { asset, to, amount }` moves KSA or another built-in asset to an account or a contract. - `Call { contract, method, args, funds }` calls a contract method with Borsh-encoded arguments. - `Deploy { code, init_args, funds }` deploys WebAssembly code and runs its `init`. `funds` attaches up to 16 built-in assets to a call or a deployment, in ascending order of asset ID and each above zero; they move to the contract before it runs. An operation is encoded with Borsh, at most 65,536 bytes. The op ID of a path C operation is the SHA-256 of the whole encoding, signature included; the op ID of a path B operation is the SHA-256 of the encoding with the first half of its signature, the form a block holds it in (see [Signatures in a block](#signatures-in-a-block)). ## Two paths in *Figure: Path B, where you sign one message and a producer includes it within seconds for a fee in KSA, beside path C, where your own Bitcoin transaction carries the operation and every producer must include it once it confirms.* | | Path B: sponsored | Path C: native | | --- | --- | --- | | Sent to | Any Ksana node, with `ksana_submitOp` | Bitcoin, in your own transaction | | Fee | KSA, to the producer and the carrier | BTC, to Bitcoin miners only | | Takes effect | In the next block, within seconds | After 2 Bitcoin confirmations on signet, 5 on mainnet | | A producer can refuse it | Yes | No | Use path B for everyday work. Use path C when you hold no KSA, when no producer will take your operation, or to pay bitcoin and act in the same transaction, as a top-up does. ## Path B: sponsored Sign the operation with `fee: Token { amount }` and submit it to any node with `ksana_submitOp`. The node checks it (format, chain ID, signature, a nonce not below the account’s, a balance that covers the fees of all your queued operations), keeps it in its entry pool and passes it to its peers. A node that produces blocks answers only once the operation is in its next block template, so a producer usually includes it within seconds, and later pays the Bitcoin fee to land it. A refusal comes back as an error: `-32010` for an operation that breaks a consensus rule (a path C operation sent here among them, and one sent with half a signature), `-32011` for one that this node’s policy turns down, such as a fee below its floor, a full pool or a replacement that does not raise the fee enough. The fee is taken before the operation runs and is kept even when the operation fails. It stays locked with the block until the block’s data is on Bitcoin, then half goes to the block’s carrier and the rest to its producer; when the producer carried its own block, or nobody qualifies as carrier, the producer takes all of it ([KSA and rewards](https://ksana.network/docs/ksa/)). ### Fee rate and floors Producers rank operations by fee rate, not by the fee alone. An operation’s cost is the larger of its encoded size in bytes and its `max_gas` converted to bytes at the block’s ratio of data to gas (`max_gas * 81920 / 100000000`); its fee rate is `fee * 1024 / cost`, in base units per KiB. So an operation that reserves a large share of a block’s gas pays for that share, and cannot push out cheaper operations with a slightly larger fee. A KSA transfer signed with BIP340 is 216 bytes. With a `max_gas` of 10,000, which a transfer uses exactly, its cost is 216 bytes; with ksana-cli’s default `max_gas` of 1,000,000 its cost is 819, and the same fee buys a lower rate. Set `max_gas` close to what the operation needs. Each node sets its own floors. They are policy, not consensus: | Flag | Default | Effect | | --- | --- | --- | | `--min-token-fee` | 1 base unit | Packing floor: the smallest fee this node puts in its blocks | | `--min-fee-per-kib` | 0 | The lowest fee rate this node packs | | `--ksa-price-sat` | None | What one KSA is worth to the operator, in sat: an op must then also pay for its bytes at the Bitcoin fee rate the node pays | | `--min-relay-token-fee` | The packing floor | Relay floor: the smallest fee this node admits and forwards (the lower of the two floors applies) | An operation above the relay floor but below the packing floor still enters the pool and travels on, for a producer with a lower floor. No network-wide price exists: each producer prices KSA against its own Bitcoin costs. A producer run with `--ksa-price-sat` does so at every Bitcoin block: an op’s data lands on Bitcoin as witness data, compressed and with half of its signature, in less than an eighth of a vB per byte, so it asks each KiB of an op’s encoded size for the KSA worth 128 vB at the fee rate it pays. This floor goes by the op’s size alone, whatever its `max_gas`, and applies beside the two above. When that rate rises, an op that was enough a block ago waits in the pool until the rate falls, another producer packs it, or you replace it with a higher fee. Ask a node what it suggests with `ksana-cli estimate-fee` (the RPC method `ksana_estimateFee`): ```sh export KSANA_RPC=https://signet.ksana.network/rpc ksana-cli --chain signet estimate-fee ``` ```output { "at": { "hash": "d8a91f8bdec0fd69849615308b8b800eec04e6f0aee037ed6fa6e97950604cc1", "height": "26" }, "feerate_sat_vb": "2", "path_b": { "amount": "1", "per_kib": "4" } } ``` `path_b.per_kib` is the median, over the last 20 main-chain blocks, of the lowest path B fee rate in each block that has one, and `path_b.amount` is that rate applied to a plain transfer with a `max_gas` of 10,000, rounded up and at least the packing floor. A node run with `--ksa-price-sat` also returns `path_b.per_kib_data`, what it asks per KiB of an op’s encoded size, and its `path_b.amount` covers that as well. `feerate_sat_vb` is the Bitcoin fee rate the node pays for its own settlements now, a reference for path C transactions. ### The entry pool The entry pool is local policy too: by default a node’s pool holds up to 10,000 operations or 32 MiB, and up to 64 operations per account, numbered from the account’s nonce, at most 8 of them behind a gap in the numbering. A new operation with the same account and nonce replaces the waiting one only with a fee at least a tenth higher, and higher by at least the node’s relay floor; the refusal names the least fee that does. When the pool is full, it evicts the operations that stand lowest (behind a nonce gap first, then by fee rate) instead of refusing newcomers. A replaced or evicted operation is gone, and its op ID answers `-32004`. ### Signatures in a block You sign and submit an operation with its whole signature, and pools and peers hold it that way. A block holds less. A BIP340 signature has two halves of 32 bytes; the producer keeps the first half of each path B signature in the operation’s entry and ends the block with one more entry, the **aggregate**: 32 bytes that stand for all the second halves (BIP340 half-aggregation). The header’s `entries_root` covers the halves and the aggregate, and this is the form that goes onto Bitcoin, so the n path B signatures of a block take 32n + 32 bytes there instead of 64n. Every node, and the indexer from Bitcoin alone, checks the aggregate against all the path B operations of the block at once, and a block whose aggregate fails is invalid. An aggregate that verifies cannot be made for an operation its account did not sign. What changes for you: - **The op ID** of a path B operation is taken over the form with half the signature, so it is the same before and after inclusion. `ksana_submitOp` returns it. - **One signature alone** cannot be checked from a block or from Bitcoin, only all of a block’s together. Keep the signed operation if you need to show its signature by itself. - **After a reorganization** a node returns a block’s path B operations to its pool only if it holds their second halves. These travel between nodes beside the block and are not on Bitcoin, so a node that rebuilt the block from Bitcoin has none, and there the operation has to be submitted again. Path C operations are not aggregated: each carries its whole signature in its own Bitcoin transaction. The rules are in [SPEC §4.5](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#45-half-aggregated-signatures-in-a-block-d-154). ## Path C: native Path C puts the operation in a Bitcoin transaction of your own. The operation, with `fee: BtcNative`, goes into an `OP_RETURN` output that begins with the `KSN1` marker; you fund the transaction from any coins, pay the Bitcoin fee and broadcast it to Bitcoin. Bitcoin Core 30 and later relay such large `OP_RETURN` outputs by default, while earlier versions need `-datacarriersize=100000`. The signature covers the outpoint that the transaction’s first input spends. An output can be spent only once, so a copy of your operation in someone else’s transaction fails authentication and does not use your nonce. ksana-cli and the [TypeScript SDK](https://ksana.network/docs/sdk/) build these transactions; with a browser wallet, the wallet signs the operation first and the transaction after it. ### Forced inclusion A block anchored at Bitcoin height A must start with every path C transaction confirmed at or below A − `NATIVE_CONFIRMATIONS` + 1 that its parents have not included, in Bitcoin order. Producers anchor `ANCHOR_DEPTH` blocks below their Bitcoin tip, so your transaction is included once it has `NATIVE_CONFIRMATIONS` + `ANCHOR_DEPTH` confirmations: 2 on signet, 5 on mainnet, 1 on devnet. A block that leaves one out is invalid, so no producer can keep your operation out. Forced entries are not bound by the block’s gas limit; each counts as its `max_gas`, up to 1,000,000. An operation that asks for more than 1,000,000 (`NATIVE_MAX_GAS`) fails and uses its nonce. ### What path C costs A path C operation pays producers nothing: you pay only the Bitcoin fee, and it is not refunded if the operation fails. A KSA transfer with one input and change, built with the SDK, came to 330 vB, which is 660 sats at 2 sat/vB (672 sats when a wallet signs the operation with BIP322). The nodes do not know your operation until a block includes it: until then `ksana_getOpStatus` answers `-32004`, so follow the Bitcoin transaction meanwhile. ksana-cli funds and broadcasts the transaction from a wallet in your own bitcoind: ```sh ksana-cli --chain signet transfer --key alice.key --to @bob.key --amount 100000000 \ --native --btc-rpc-url http://127.0.0.1:38332 --btc-wallet --wait --timeout 3600 ``` `--btc-rpc-user` and `--btc-rpc-pass` (or `KSANA_BTC_RPC_PASS`) give your bitcoind’s credentials. Keep the long `--timeout`: the operation needs two signet blocks, far beyond the default 120 seconds, and a `--wait` that times out prints only an error. A contract called on path C can read the transaction that carries the call with the `native_tx` host function, which is how it checks a payment made in that same transaction ([Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/)). ## Top-up: KSA for BTC A top-up buys KSA with bitcoin in one Bitcoin transaction, through an exchange contract such as the `ksa-exchange` example. Exchange contracts are applications, not protocol rules, and anyone can deploy one. 1. **Agree**: you and a seller settle, off-chain, the amount, the price in KSA base units per sat and the account to credit. 2. **Lock** (the seller, on path B): the seller locks KSA in the contract with the price, a payment script used by this lock alone, your account as the beneficiary and an expiry Bitcoin height. The terms cannot change afterwards. 3. **Pay and claim** (you, on path C): one Bitcoin transaction pays the payment script and carries the claim operation. A one-time key signs the claim at nonce 0, bound to the transaction’s first input, so it never collides with your account’s nonces and a copy cannot take it. 4. **Credit**: once the transaction is force-included, the contract reads it with `native_tx` and credits the beneficiary with the sats paid times the price, up to what is still locked. A payment that buys only part leaves the rest locked for you. The seller can take back what is still locked 6 Bitcoin blocks after the expiry, so your payment has to confirm at Bitcoin height expiry + 6 − `NATIVE_CONFIRMATIONS` − 1 at the latest (the SDK’s `payBy`). The SDK and ksana-cli read the lock first and refuse to pay when the beneficiary is not you, when the lock is not open, when fewer than 3 Bitcoin blocks are left before the expiry, or when the payment is more or less than the locked KSA is worth (flags allow a partial payment or an overpayment). One top-up transaction is about 381 vB. The [signet wallet](https://ksana.network/docs/wallet/) and [ksana-cli](https://ksana.network/docs/cli/) both do top-ups. ## Receipts and gas Every included operation gets a receipt with `success`, `gas_used`, `output` (what a call returned), `events`, `error` and `asset_changes`, the changes it made to built-in assets in the order it made them ([JSON-RPC](https://ksana.network/docs/rpc/#ksana_getopstatus) lists their kinds). Gas measures execution. Ordinary WebAssembly instructions cost 1 gas, host functions have fixed prices, and the built-in actions start from fixed amounts: | Action | Gas | | --- | --- | | `AssetTransfer` | 10,000 | | `Call` | 20,000, plus 10,000 per attached asset, 1 per byte of the contract’s code, and the execution | | `Deploy` | 100,000, plus 20 per byte of code, 10,000 per attached asset, and the execution of `init` | The limit is exact: an operation that would use more than its `max_gas` fails. Deploying the example token used 776,169 gas ([Token and pool tutorial](https://ksana.network/docs/token-and-pool/)). A block takes path B operations only while the `max_gas` of its entries adds up to at most 100,000,000 (a path C entry counts at most 1,000,000), which is one more reason to keep `max_gas` close to what you need. [Host functions](https://ksana.network/docs/host-functions/) lists every price. ## Failed ops and invalid blocks Three different things can go wrong, and only the first is about your operation: - **A failed operation** is included, but its execution fails: out of gas, a contract trap or revert, invalid attached funds, an insufficient balance. Its receipt has `success: false` and `gas_used` equal to `max_gas`; the fee is charged and the nonce used, and every other change and event is rolled back. A path C operation that fails its checks (version, chain ID, length, fee mode, signature or nonce) fails too, but leaves the nonce unchanged. The block stays valid. - **A skipped entry** sits in a merged block and cannot run where the merge puts it, for example because another block already ran the same operation. It pays nothing and changes nothing, and an operation that is still valid returns to the pool. - **An invalid block** breaks a consensus rule: an aggregate that does not verify over its path B signatures, a wrong nonce among its own entries, a missing path C entry or a wrong state root. Nodes refuse it or keep it off the main chain, so an operation in it counts only where a valid block runs it. A **local fault**, such as a storage or bitcoind error, is none of these: the node retries and never judges a block invalid because of one. The full rules are in [SPEC §5](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#5-the-two-submission-paths) (the two paths and top-up), [§7.4](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#74-forced-inclusion-of-native-transactions) (forced inclusion) and [§8](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#8-fees-incentives-and-unlocking) (fees and gas). --- # KSA, rewards and fees URL: https://ksana.network/docs/ksa/ > KSA is Ksana’s built-in token. It pays path B fees and rewards the producers who make blocks and land their data on Bitcoin. On mainnet all of it is issued as block rewards on a fixed schedule, capped at 210,000,000 KSA. KSA is a built-in asset of Ksana’s virtual machine, not a contract: its name is `KSA`, its asset ID is 32 zero bytes, and it has 8 decimals. Amounts are whole numbers of **base units**, and 1 KSA is 100,000,000 base units. You need KSA for path B fees; path C uses bitcoin alone ([Operations and fees](https://ksana.network/docs/submitting-ops/)). ```sh export KSANA_RPC=https://signet.ksana.network/rpc ksana-cli --chain signet asset ``` ```output { "asset": "0000000000000000000000000000000000000000000000000000000000000000", "at": { "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f", "height": "61" }, "capabilities": [], "decimals": 8, "issuer": "0000000000000000000000000000000000000000000000000000000000000000", "name": "KSA", "paused": false, "symbol": "KSA", "total_supply": "11001412730000000" } ``` On the signet that total is 110,014,127.3 KSA: the 110,000,000 KSA of its genesis allocations plus the rewards paid so far. Signet KSA has no value, and mainnet has not launched. ## Supply and issuance *Figure: KSA issued over the first 40 years of mainnet: the halvings and the 210,000,000 KSA cap.* New KSA comes into existence only as block rewards. On mainnet the cap is 210,000,000 KSA (`KSA_MAX_SUPPLY`), there is no genesis allocation, and the reward schedule adds up to the cap: every slot of every period together pays 209,999,996 KSA, 4 KSA short because integer halving rounds down. The cap is also enforced when rewards are paid, so the total supply can never pass it. ### Reward slots Rewards follow the DAA score, which grows by each block’s weight and advances one unit per 5 seconds on target. A block with entries has weight 1; an empty block has weight 12 to 120 ([Mining](https://ksana.network/docs/mining/) explains why). A block of weight w takes w **reward slots**, the w DAA scores up to its own, and each slot pays the reward of its halving period: 4.2 KSA in mainnet’s first period. Empty and non-empty blocks therefore earn the same per unit of time, so producers gain nothing by making empty blocks on purpose, or by breaking a run of them. The main-chain block and the blue blocks it merges are rewarded. Red blocks, the ones GHOSTDAG judges to have stayed out of sight too long, get no block reward, though the path B fees in them are still paid. ### Halving periods The reward per slot halves at the end of each period. On mainnet a period is twice as long as the one before at each of the first two halvings, and from then on every period lasts 8 years: | Period | About | KSA per slot | Issued by its end | | --- | --- | --- | --- | | 0 | Years 0 to 2 | 4.2 | 52,500,000 (25%) | | 1 | Years 2 to 6 | 2.1 | 105,000,000 (50%) | | 2 | Years 6 to 14 | 1.05 | 157,500,000 (75%) | | 3 | Years 14 to 22 | 0.525 | 183,750,000 (87.5%) | | 4 | Years 22 to 30 | 0.2625 | 196,875,000 (93.75%) | | 5 to 28 | 8 years each | Half the period before | 209,999,996 (about 100%) | Periods are counted in DAA score (12,500,000, then 25,000,000, then 50,000,000 each), so the years assume the 5-second target. The last base unit is paid in period 28, and from DAA score 1,387,500,000, about 220 years in, the reward is zero. The signet and devnet use other values: 9.9 KSA per slot, periods of 25,228,800 DAA score (about 4 years) that all have the same length, and a cap of 1,000,000,000 KSA, which leaves room for test allocations. [Parameters](https://ksana.network/docs/parameters/) lists every value. ## Who gets each slot Each slot is paid when its block unlocks. The block’s carrier gets 5% of it, 0.21 KSA in mainnet’s first period and 0.495 KSA on the signet, and the producer gets the rest, apart from the block share that slots carry while the protocol’s rules set one, paid to the account the genesis config names. When the block has no carrier, or its producer is its carrier, the producer keeps the carrier’s part too. If a payout runs into the cap, the block share is paid first, then the carrier, and the producer takes what remains. ### The carrier The **carrier** of a block is whoever first landed its data on Bitcoin. For a settlement, that is the producer of the block that carried it; for a republish, the payee it names, but only when the data lands more than `ANCHOR_DEPTH` + 2 Bitcoin blocks above the block’s anchor (more than 3 on the signet, more than 4 on mainnet), so that nobody earns by racing to land data that its own producer was about to land. The carrier gets 5% of each slot of the block (`CARRIER_BPS`) and half of the block’s path B fees (`CARRIER_FEE_BPS`). Landing other blocks’ data costs bitcoin, and the carrier reward pays for it: that is what lets one settlement per Bitcoin block carry the data of many blocks. In mainnet’s first period, carriers together earn at most about 3,629 KSA a day from rewards. A rescue copies the original payload, so the original carrier keeps the reward and the rescuer pays without income. ## Paid at unlock Rewards and path B fees are not credited when a block is made. They are paid at **unlock**: a later main-chain block carries an unlock entry that pays everything up to some position, and it may reach a block only once the data of that block and of every block before it is on Bitcoin. Until then they show under `locked_fees` in `ksana_getAccount`. Here is a signet producer’s list: ```sh ksana-cli --chain signet account tb1penqxc08g69mt8sgp8rw5uuy88yu6n3kuq4vh73d2ec28aukq057s0vh4h2 \ | jq '.locked_fees[0:4]' ``` ```output [ { "amount": "9504000000", "block_hash": "4e84fb7c6994100d9182bb223c5fc185eeefc48b4572b85944f0a11f2b50a6e5" }, { "amount": "19008000000", "block_hash": "ade1d16fe24a8426c8044347828d451604770174aaecedc1c0509d27741909cf" }, { "amount": "95040000000", "block_hash": "794b6cdc4b766205404b3845f0629294ad65a9842154ae860c2d43e8ebea76ad" }, { "amount": "19008000000", "block_hash": "64f7c7796e8c4dd91bd9e38f7d1a6be9c4de409dcc25d50c8e426cf27af75331" } ] ``` All four are empty blocks this producer made, of weight 12, 24, 120 and 24, so they pay 12, 24, 120 and 24 slots: the producer’s share together with the carrier’s, because it landed their data itself or nobody has landed it yet. When it lands another producer’s block first, the list also holds that block’s carrier part: 5% of each slot, 0.495 KSA on the signet. The node projects these amounts from the current chains, so one can still change, for example when another producer’s settlement lands a block’s data first. Paying only after the data is on Bitcoin makes producers want every block’s data landed, their own and everyone else’s: one block with missing data holds back the income of every block after it. ## Where fees go - **Path B fees** (KSA): taken from you before the operation runs, locked with the block, and paid at unlock, half to the block’s carrier and half to its producer (all to the producer when it carried its own block or nobody qualifies as carrier). - **Bitcoin fees for settlements**: paid in BTC by whoever lands the data, usually the producer whose block carries the settlement. Producers earn KSA and pay bitcoin; an exchange contract lets them sell KSA for bitcoin. - **Path C fees**: paid in BTC to Bitcoin miners only. Producers receive no fee for them. Nothing is burned: fees go to producers and carriers in full. A contract can burn KSA it holds with `asset_burn`, which lowers the total supply. ## Genesis | Network | Genesis allocation | Block share account | | --- | --- | --- | | mainnet | None: the rewards alone reach the cap | A placeholder that no node accepts, to be filled in before launch | | signet | 100,000,000 KSA to the faucet, 10,000,000 KSA to the operator | Set in `signet/genesis.json` | | devnet | 10,000 KSA to a test account, written by `devnet/init.sh` | A generated account | On mainnet no KSA exists before the first block, and every KSA after it is a block reward. The full rules are in [SPEC §8.5](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#85-locking-and-cumulative-unlock-of-sponsored-fees) (unlocking) and [§8.6](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#86-ksa-and-block-rewards) (KSA and block rewards). --- # Mining and producing blocks URL: https://ksana.network/docs/mining/ > Anyone can produce Ksana blocks with an ordinary CPU. Run a node with a producer account and a Bitcoin funding wallet, mine with Argon2id, and earn KSA for the blocks you make and the data you land on Bitcoin. Producing blocks is open to anyone: no stake, no registration and no permission. A producer is a `ksana-node` that collects operations, executes them, solves a proof of work, and pays to land its blocks’ data on Bitcoin; it earns KSA in return. Mainnet has not launched, so today you mine on the [public signet](https://ksana.network/docs/signet/). [Run a node](https://ksana.network/docs/run-a-node/) has the setup step by step. ## What a producer needs - **A node and bitcoind**: `ksana-node` with `--producer `, the account that receives your rewards, connected to a bitcoind on the same network (started with `-txindex`) and to peers. - **A funding key**: `--btc-funding-key-file`, a separate key whose Taproot address holds the bitcoin that pays for settlements. On signet and mainnet the node also needs `--btc-funding-wallet`, a watch-only wallet in the same bitcoind that lists the funding address’s coins, because scanning signet’s whole UTXO set takes 30 to 50 seconds. - **A CPU core**: `ksana-node` mines on a single thread. The funding key is optional. Without one, the node still produces blocks with path B operations, and other producers land their data and take the carrier reward. If no one does, the backlog limit stops path B after 6 Bitcoin blocks ([How it works](https://ksana.network/docs/how-it-works/)). Each block you make follows the same steps: pick the anchor, `ANCHOR_DEPTH` Bitcoin blocks below your tip; merge the other tips of the DAG; put in the path C entries the block must force, then an unlock entry, then path B operations by fee rate; execute; solve the proof of work; sign the settlement, if the block carries one; and broadcast the block to peers. The settlement goes to Bitcoin once the block is 2 blocks deep. ## Argon2id proof of work The proof of work is Argon2id (RFC 9106) over the Borsh-encoded block header, with 2 MiB of memory, one pass and one lane. The salt is `ksana-pow` followed by the chain ID, so work done for one network is worthless on another, and the 32-byte output is read as a little-endian number that must not exceed the block’s target. The block hash, the block’s identifier, stays `sha256d` of the header. One evaluation takes about 1 ms on one core of an ordinary CPU, and a header takes about 13 ms to verify in JavaScript, so a browser can check a block itself. Syncing a busy year of headers costs about 1.7 hours of one core. Why Argon2id: - **Not SHA-256.** Bitcoin’s ASIC hashrate could be rented to overwhelm an independent SHA-256 chain, and ordinary computers could not take part. - **Not RandomX.** Verifying one header would take 33 ms and 256 MB of memory (or 2 GB kept resident), and browsers have no practical way to run it. - **Not merged mining.** Every merged-mined header would have to carry a Bitcoin header, a coinbase and a Merkle branch, 700 to 900 bytes, onto Bitcoin with it. - **Not proof of stake.** Ksana’s security comes from Bitcoin and from hashrate, and holding KSA should not decide who produces blocks. Argon2id is not CPU-only. At 2 MiB its speed is bound by memory bandwidth, a GPU has 10 to 30 times an ordinary CPU’s, and its advantage in hashrate per unit of cost is estimated to be of the same order: far smaller than that of ASICs on SHA-256, but not zero, and not measured yet. Before mainnet the memory and the number of passes may be retuned by the measured GPU advantage. ## Difficulty Difficulty adjusts every block with aserti3-2d, Bitcoin Cash’s algorithm, anchored at the genesis block and counted by DAA score: the target is one unit of DAA score every 5 seconds, with a half-life of 7,200 seconds. A 10-fold change of hashrate takes about 10,000 blocks to absorb, and an idle chain’s difficulty wanders by about 20%. | Network | Lowest difficulty (`POW_LIMIT_BITS`) | What it means | | --- | --- | --- | | mainnet | `0x1f00ffff` | About 65,536 evaluations per block: about 13 cores for a block every 5 seconds | | signet | `0x1f0fffff` | About 4,096 evaluations per block: about 3.5 seconds of one core | | devnet | `0x207fffff` | Bitcoin regtest’s easiest target | A genesis config can start harder: the signet’s genesis `bits`, `0x1f068db8`, expects about 10,000 evaluations per block, sized for its two seed nodes on one core each. A block’s timestamp must be later than the median of the 11 blocks before it on its selected chain, at most 15 seconds ahead of the receiving node’s clock, and at most 4 hours ahead of its anchor’s Bitcoin block time. The last rule keeps a privately mined chain from borrowing a large difficulty discount with made-up times; it also means the fast lane pauses if Bitcoin finds no block for more than about 4 hours. ## Two-speed difficulty When a producer has nothing to include, no operation and no unlock entry, it makes an **empty block**, and empty blocks are harder. The first empty block after a block with entries has weight 12; each further one in a row on the selected chain doubles, up to 120: 12, 24, 48, 96, then 120. A block of weight w must meet a target w times smaller, adds w to the DAA score and takes w reward slots. So an idle chain makes a block about every 1, 2, 4, 8 and then 10 minutes. The moment an operation reaches the entry pool, producers drop the empty-block template and mine a block of weight 1, at the normal target: the first operation waits about one ordinary block, 5 seconds. Empty and non-empty blocks with the same parents have the same `bits`, so nothing else changes. Why empty blocks weigh more: - **Every header lands on Bitcoin**, and the indexer and finality need them all. Compared with a fixed weight of 12, the streak cuts an idle day from about 1,440 headers (about 26 KB) to about 144 (about 2.6 KB). - **Banning empty blocks would cost more.** Rewards make miners produce the cheapest valid block the difficulty allows, so they would fill blocks with self-transfers instead, about 70 times the bytes. - **The cap matches Bitcoin.** At 120 an idle chain still makes about one header per Bitcoin block, so finality can advance block by block. - **Rewards are fair either way.** A block of weight w earns w slots, so the expected reward per unit of time is the same for empty and non-empty blocks, and neither making empty blocks nor breaking a streak pays. ## GHOSTDAG Blocks found at nearly the same time are all kept: a block names up to 10 parents, and GHOSTDAG orders the DAG. K = 16 bounds how many blue blocks a blue block may have outside its own past and future; blocks beyond that, ones that stayed out of sight too long, are red. Red blocks still have their entries executed and their path B fees paid, but they earn no block reward. A block’s merge set holds at most 128 blocks, its selected parent included, and only blocks whose blue score is at most 720 below its selected parent’s (`MERGE_DEPTH`, about an hour at 5-second blocks) and whose selected chain passes through its merge-depth root. That keeps every check close to the tip, so a long side chain forked from an old block can never be merged. The selected parent and the main chain go by **chain work**: the work of a block’s blue past plus its own. Counting a block’s own work matters on an idle chain. Without it, a miner could withhold a run of cheap weight-1 blocks while an honest heavy empty block was being found, then publish them and turn the honest block red. ## Settlement costs The producer whose block carries a settlement pays its Bitcoin fee. A commit and reveal pair costs about 243 vB plus a quarter of a vbyte per byte of envelope data, and the node compresses the payload with zstd when that makes it at least 32 bytes shorter; on signet an ordinary pair measured 111 vB for the commit and 238 vB for the reveal, with a 425-byte payload. An idle network still sends a pair about every two Bitcoin blocks, because the unlock entry that pays out rewards is an entry, so its block needs a body on Bitcoin. On the idle signet that is 62 to 72 pairs a day for the whole network, about 700 sats each at 2 sat/vB. Settlement batching is on by default: a block leaves its body to the next settlement while an earlier one is still waiting to confirm, so a busy chain sends about one settlement per Bitcoin block. `--no-settlement-batching` makes every block with a body carry its own settlement: its operations become final sooner, at the cost of more Bitcoin fees. Settlements spend only confirmed outputs and never each other, so you can fund at most as many settlements per Bitcoin block as your funding address has confirmed outputs. `--funding-pool-target` (default 64) keeps that many by splitting the largest output into pieces of at least 100,000 sats; 0 turns splitting off. ### Fee policy These flags are your own policy. They decide what your node pays for every Bitcoin transaction it sends: settlements, rescues, republishes, splits and fee bumps. | Flag | Default | Effect | | --- | --- | --- | | `--settlement-conf-target` | 3 | Bitcoin blocks for bitcoind’s `estimatesmartfee`; not asked while a lighter competing chain is on Bitcoin, when your node pays the cap | | `--settlement-feerate` | 2 sat/vB | The floor: paid while bitcoind’s mempool holds at most half a block and the last Bitcoin block was at most half full, and when bitcoind has no estimate | | `--max-settlement-feerate` | 1,000 sat/vB | The cap; paid at once while a lighter competing chain is on Bitcoin | | `--revenue-address` | none | With `--hot-wallet-cap-sat` (1,000,000 sats): a separate sweep transaction moves what the funding address holds above the cap here | A pair your node sent that waits 2 Bitcoin blocks below bitcoind’s estimate gets a child transaction (CPFP) spending the reveal’s change output, which lifts both to the estimate; if the estimate rises again, a richer child replaces it. Whether or not the mempool has room, a pair still waiting after 2 Bitcoin blocks is lifted to at least twice its own rate, and twice that again for every further block, up to the cap, whatever bitcoind estimates. When the change cannot pay that rate, the child pays all of it above the dust limit, so set the cap to what you are willing to spend on one pair. A pair that waited while there seemed to be room and that a Bitcoin block found 2 minutes or more later leaves out is lifted at once to at least the next-block estimate, and your node pays the estimate for the next 6 Bitcoin blocks. Only your funding key can spend that change, so no one else can attach a child of their own to the pair. When a settlement cannot confirm at all, other nodes rescue it with their own funding, in turns that follow the main chain. The signet’s two seed nodes run with `--settlement-feerate 2 --max-settlement-feerate 5 --min-block-interval-ms 1000 --funding-pool-target 0` and a watch-only funding wallet; `signet/ksana-signet.sh` in the repository has their full command line. ## Rewards for producers You earn, for each block you make, the producer’s part of its reward slots at unlock, and the carrier’s 5% too when you carried the block yourself. You also earn its path B fees (half of them when someone else carried it), and as a carrier, 5% of each slot and half of the path B fees of other blocks whose data your settlements land first. Everything is paid only once the data is on Bitcoin; [KSA and rewards](https://ksana.network/docs/ksa/) explains the split and the unlock. The full rules are in [SPEC §6.6](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#66-ghostdag-and-work) (GHOSTDAG, work and two-speed difficulty), [§6.7](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#67-difficulty-adjustment-asert) (difficulty) and [§7.7](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md#77-the-producers-funding-wallet) (the funding wallet and fee rate). --- # The public signet URL: https://ksana.network/docs/signet/ > Ksana’s public test network runs on Bitcoin’s signet. Use it to try wallets, apps, contracts and nodes with coins that have no value. The public signet is the Ksana network to use today. It runs on Bitcoin’s public signet, the test network Bitcoin Core joins with `-signet`, so its settlements are real Bitcoin transactions in real signet blocks, mined by signet’s miners. Mainnet has not launched. | | | | --- | --- | | Network name | `signet` (`--chain signet` for the node, the indexer and the CLI) | | Chain ID | 1002 | | Bitcoin network | signet: addresses start with `tb1`, accounts with `tb1p` | | Started | 21 October 2026, anchored at signet height 327,273 | | Genesis config | [`signet/genesis.json`](https://github.com/ksana-in-bitcoin/ksana/blob/main/signet/genesis.json) in the repository | **Test coins only.** Signet KSA and signet bitcoin (sBTC) have no value. Keep test keys and real keys apart, and never send real bitcoin to an address you made for the signet. ## What the project hosts The project runs one server at `signet.ksana.network` with Bitcoin Core on signet, two seed nodes that produce and settle blocks, an indexer that checks them, the web wallet, a KSA faucet and a small Bitcoin RPC proxy. Everything else on the network is run by whoever joins: you can follow the chain with [your own node](https://ksana.network/docs/run-a-node/), check it with [your own indexer](https://ksana.network/docs/run-an-indexer/), and mine. | Service | Address | Called from other origins | | --- | --- | --- | | Web wallet and explorer | `https://signet.ksana.network/` | | | Node JSON-RPC over HTTP | `https://signet.ksana.network/rpc` | yes | | Node JSON-RPC over WebSocket | `wss://signet.ksana.network/rpc` | yes | | Indexer JSON-RPC | `https://signet.ksana.network/indexer` | no | | Bitcoin RPC proxy | `https://signet.ksana.network/btc` | no | | KSA faucet | `https://signet.ksana.network/faucet` | no | | Seed node P2P | `{{signet.p2p}}` | | Only the node’s RPC answers browser pages from other origins (it is served with CORS `*`). A web app on its own domain can call `https://signet.ksana.network/rpc` directly from the browser, but reaches the indexer, the Bitcoin RPC proxy and the faucet only through its own server. Command-line tools and servers can call all of them. ```sh title="Ask the node for the chain tip" curl -sS https://signet.ksana.network/rpc -H 'content-type: application/json' \ --data '{"jsonrpc":"2.0","id":1,"method":"ksana_getChainInfo","params":[]}' ``` ```output {"jsonrpc":"2.0","id":1,"result":{"chain_id":1002,"tip":{"height":"61","hash":"d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f"},"daa_score":"1860","protocol_version":2,"next_upgrade":null,"max_known_version":2,"finalized":{"height":"38","hash":"ab3fe1dcb95f0d76cd171210567f571fcd81cc8f7559d68da7dd38348eec7cf2"}}} ``` The [JSON-RPC reference](https://ksana.network/docs/rpc/) lists every method of the node and the indexer. ## The faucet The faucet sends 100 KSA from its genesis allocation to any signet account, as an ordinary path B transfer. The web wallet calls it for you; from anywhere else, `POST` a JSON body with your account: ```sh curl -sS https://signet.ksana.network/faucet -H 'content-type: application/json' \ --data '{"to": "tb1pgtxpryjkcus8l9cazy7eprtxml6hnuhefe3wa55sylmp7n2jf5kshm2h5s"}' ``` ```output {"op_id":"032d7d956cff983e57db09411a345aae134aa12b8b0c72305f8cdccfad4bb4b2","to":"42cc119256c7207f971d113d908d66dff579f2f94e62eed29027f61f4d524d2d","amount":"10000000000","nonce":"2"} ``` `to` takes a signet Taproot address or the account as 64 hex digits. The answer comes once the node has accepted the transfer into its pool, not once a block includes it: follow `op_id` with `ksana-cli op` or `ksana_getOpStatus`. `amount` is in base units (KSA has 8 decimals). A `GET` returns the faucet’s own state: ```sh curl -sS https://signet.ksana.network/faucet ``` ```output {"chain_id":1002,"account":"de6603f052fd5bfaae5678a2a20ae6ae4fe4ae00c89db70a2efea7429851afc0","address":"tb1pmenq8uzjl4dl4tjk0z32yzhx4e87ftsqezwmwz3wl6n59xz34lqqlgaqc2","balance":"9999949999999995","amount":"10000000000","cooldown_hours":24,"waiting":0} ``` `waiting` counts the transfers the faucet has sent that no block has included yet. ### Faucet limits | Limit | Answer when it is reached | | --- | --- | | One request per account every 24 hours | 429 `this account already received KSA; it can ask again in N hour(s)` | | Five requests per client address a day | 429 `this address has asked too often today` | | 30 requests per client address a minute | 429 `too many requests from this address; slow down` | | About 120 transfers an hour for everyone together | 429 `the faucet is busy; try again in a few minutes` | | 48 transfers waiting for a block | 503 `the faucet has many transfers waiting for a block; try again in a minute` | Every error is a JSON object `{"error": ""}`, and the 429 and 503 answers carry a `Retry-After` header in seconds where the wait is known. A malformed body or account gets 400 with the reason, and a refusal by the node 502 `the node refused the transfer: …`. ## The Bitcoin RPC proxy `https://signet.ksana.network/btc` lets the web wallet build and broadcast path C and top-up transactions without a Bitcoin node of your own. It passes four bitcoind methods, one JSON-RPC request per call, with their parameters checked: | Method | Notes | | --- | --- | | `getblockcount` | cached for 2 seconds | | `getblockchaininfo` | cached for 2 seconds | | `estimatesmartfee` | a target of 1 to 1008 blocks, cached for 60 seconds | | `sendrawtransaction` | the signed transaction in hex | ```sh curl -sS https://signet.ksana.network/btc -H 'content-type: application/json' \ --data '{"jsonrpc":"2.0","id":1,"method":"estimatesmartfee","params":[2]}' ``` ```output {"jsonrpc":"2.0","id":1,"result":{"feerate":0.00020055,"blocks":2}} ``` It also passes two `GET` paths of mempool.space’s signet API: `esplora/block-height/0` and `esplora/address//utxo`, which lists the coins of a signet Taproot address. Every other method is refused, `scantxoutset` included: one scan of signet’s UTXO set takes 30 to 50 seconds. Each client address may make 120 requests a minute, 20 of them broadcasts and 30 of them Esplora requests. The proxy has no wallet methods. `ksana-cli`’s path C and `top-up` commands fund their transactions from a wallet in your own bitcoind, as [ksana-cli](https://ksana.network/docs/cli/) shows. ## Signet bitcoin You need sBTC only for what pays Bitcoin fees yourself: a path C operation, a top-up, or settling the blocks you mine. Path B transfers and the faucet need none. Get sBTC from any public Bitcoin signet faucet; the project does not run one. Send it to your Taproot address, the same one that holds your KSA. A path C transfer at 2 sat/vB costs about 700 sats of fee, so a few thousand sats go a long way. A producer that settles its own blocks needs more: [Run a node](https://ksana.network/docs/run-a-node/) gives the amounts. ## How the signet differs from mainnet The signet runs the same rules as mainnet and shares most of its values: blocks every 5 seconds, GHOSTDAG with K = 16, finality decided at six Bitcoin confirmations and secured by five more blocks, the same gas limits, Argon2id with 2 MiB, and the same carrier shares. These values differ: | Parameter | Signet | Mainnet | | --- | --- | --- | | Chain ID | 1002 | 1000 | | `ANCHOR_DEPTH` (how far a block’s anchor trails the Bitcoin tip) | 1 | 2 | | `NATIVE_CONFIRMATIONS` | 1 | 3 | | A path C operation is included after | 2 Bitcoin confirmations | 5 Bitcoin confirmations | | Reward per reward slot | 9.9 KSA | 4.2 KSA | | Halving period, in DAA score | 25,228,800, every period the same | 12,500,000, then 25,000,000, then 50,000,000 | | KSA cap | 1,000,000,000 | 210,000,000 | | Genesis allocation | 100,000,000 KSA to the faucet, 10,000,000 to the operator account | none | | Lowest difficulty (`pow_limit_bits`) | `0x1f0fffff` | `0x1f00ffff` | devnet, the local network on Bitcoin’s regtest, has the signet’s values except chain ID 1001, `ANCHOR_DEPTH` 0 and the lowest difficulty `0x207fffff`. [Parameters](https://ksana.network/docs/parameters/) lists every value for the three networks. When nobody sends operations, the signet’s producers make empty blocks, which are up to 120 times harder than a block with entries, so an idle signet slows from about a block a minute to about one every ten minutes. The first operation brings back blocks every few seconds. [Mining](https://ksana.network/docs/mining/) explains this two-speed difficulty. ## Restarts from genesis Before mainnet, a change to the consensus rules restarts the signet from genesis with a new `signet/genesis.json`. A restart starts a new chain: balances, contracts and operation history do not carry over, while your keys and addresses stay valid and hold nothing on the new chain. After a restart: - Pull the repository for the new `signet/genesis.json` and the code that goes with it. - Start your node and indexer with a new data directory. A data directory keeps the genesis config it was made with, and the node and the indexer refuse it with `data directory belongs to a different genesis config`. - Ask the faucet for test KSA again. --- # The signet wallet URL: https://ksana.network/docs/wallet/ > The web wallet and block explorer at https://signet.ksana.network/. Connect Unisat or Xverse, get test KSA, send on path B or path C, top up with signet bitcoin, and see where each operation landed on Bitcoin. The signet wallet is a web page that is both a wallet and a block explorer for the [public signet](https://ksana.network/docs/signet/). It keeps no keys: your browser wallet signs, and the page reads the chain from a Ksana node, an indexer and a Bitcoin RPC, the hosted ones unless you choose your own. The page is built from the [ksana-web](https://github.com/ksana-in-bitcoin/ksana-web) repository. Its footer and **Settings** › **About** show the commit it was built from, and that repository's README explains how to rebuild that commit and compare the files byte for byte. ## Supported wallets | Wallet | Set it to | Account the page uses | | --- | --- | --- | | Unisat | Bitcoin Signet, Taproot address type | the wallet’s Taproot address | | Xverse | Signet | the Ordinals address, which is the Taproot one | Your Ksana account is your Taproot (P2TR) address, so the page accepts no other address type. It also checks that the wallet is on signet before connecting, and again before it signs a path C or top-up transaction: a `tb1` address alone does not tell signet from testnet, so the page asks the wallet which network it is set to (Unisat’s `getChain`, Xverse’s `wallet_getNetwork`). ## Connect Open [https://signet.ksana.network/](https://signet.ksana.network/), choose **Wallet**, then **Connect wallet**, pick your wallet and approve the request in the extension. The page asks only for signatures: path B operations are signed as one BIP322 message, path C and top-up transactions as a PSBT. **Settings** shows the connected address and **Disconnect wallet**. The wallet home shows your balances, in this order: - **Bitcoin · signet**: the sats on your address, read from mempool.space’s signet API through the hosted Bitcoin RPC proxy. The page reads them when the wallet opens and after each Bitcoin block; the corner button refreshes them. - **Ksana · KSA**: your balance, split into the part that is already BTC-final and the changes that are not final yet (**BTC-final balance**, **Incoming, not final yet**, **Outgoing and fees, not final yet**, **Current balance (available now)**). - **Tokens**: the other assets, [built-in assets and KS-20 tokens](https://ksana.network/docs/tokens/) in one list, each with its BTC-final amount while part of it is not final. Under its symbol, a built-in asset names the contract that issued it (**Issued by**), and a KS-20 token its standard and its own contract (**KS-20 ·**). - **NFTs**: the KS-721 collections you hold NFTs of, with how many. Anyone can send any account a token under any name, so the wallet lists only what you asked for: KSA, the assets your own operations moved (you sent them, attached them to a call, called their contract, or were paid them by a call you made), and those you keep. It goes by the operations it has read: an asset that only operations older than those your activity shows moved stays folded until you choose **Show older operations** or keep it. Anything else is folded under **Other assets** (and **Other collections**), each with its whole ID, its contract and **Keep**, which keeps it in the list on this device; **Fold away** folds it again. Every symbol opens the asset’s page: its whole ID, its contract, its supply and the operations that moved it, with a token’s largest holders, or what a built-in asset’s issuer can still do (mint, freeze, allowlist, pause). Check them before you keep a token named like one you know. ## Get test KSA With an empty wallet, the KSA card says “No KSA yet” and offers **Claim test KSA**. The **Receive** page has the same faucet as **Get test KSA from the signet faucet**, next to your address and its QR code. Either sends 100 KSA, once a day per account; when the faucet refuses, a notice gives its reason. [Public signet](https://ksana.network/docs/signet/) lists the faucet’s limits. ## Send on path B Path B is the default: you pay a small fee in KSA, and the producer that includes your operation pays the Bitcoin fee of settling it. 1. Choose **Send**. Paste a **Recipient**: a `tb1p…` address, or an account as 64 hex digits. Check the first and last 8 characters the page shows; it warns when the account has no record on the chain yet. 2. Choose the **Asset**, KSA unless you pick another, and enter the **Amount**. KSA has 8 decimals. 3. Under **How to submit**, keep **Sponsored**. The fee is the node’s suggestion, taken from the lowest path B fee rates of the last 20 blocks (1 base unit on the signet today). **Advanced** lets you set another fee and `max_gas`. 4. Choose **Review and sign**. The page states what you are doing in one sentence, shows the full recipient address, lists any warnings, and folds the exact operation (the VmOp and its signature hash) at the end. 5. Choose **Sign and submit** and sign the message in your wallet. The Send page then follows the operation through **Pending**, **Fast-confirmed**, **On Bitcoin**, **6 BTC confirmations** and **BTC final**. **Send another** becomes available once it is fast-confirmed, so that the next operation does not reuse its nonce. [Confirmations](https://ksana.network/docs/confirmations/) explains the marks. ### Send a token A KS-20 token is sent the same way: choose it under **Asset**. Its transfer is a call of the token’s `transfer`, so before you review it the page asks the node to try it as you. What the try used, plus half, becomes the operation’s `max_gas`, which **Advanced** shows, and a transfer the token refuses, for too small a balance or by its own rules, is said on the page instead of failing on the chain with its fee paid. The page refuses the token’s own contract as the recipient, and warns when the recipient is a contract: a plain transfer does not tell a contract it received tokens, so one that does not take KS-20 tokens can neither use nor return them, and tokens go to a contract through its [`transfer_and_call`](https://ksana.network/docs/ks-20/#pay-a-contract-in-one-operation). The review gives the token’s whole ID: check it against the token you mean, since anyone can give a token any name. Incoming transfers follow a **Large-amount threshold**, 10,000 KSA unless you change it on **Receive** or in **Settings**. Below it, fast confirmation counts as received; at or above it, the wallet reminds you to wait for BTC final. ## Contract playground The [contract playground](https://ksana.network/docs/playground/) is a page of its own, at [playground.ksana.network](https://playground.ksana.network/): eight example contracts to use, edit, compile and deploy on the signet. The wallet links it in its top bar and footer and on its home, and a contract's page offers **Open in the playground**, which opens that contract there. ## Path C from the page Path C puts your operation in a Bitcoin transaction of your own. Every producer must include it once the transaction has its confirmations, so no producer can keep it out; you pay the Bitcoin miner fee in sBTC and no KSA fee. [Operations and fees](https://ksana.network/docs/submitting-ops/) compares the two paths. Path C sits under **More ways to submit** on the Send page. It opens there by itself, marked **Recommended**, when you lack the KSA for a path B fee, when settlements are backlogged, or when producers have not included your operations. An operation that waited too long offers **Switch to Path C** (or **Resubmit via Path C**) with the same nonce. - **Funds**: your Taproot address needs a little sBTC. A transfer at 2 sat/vB costs about 700 sats of fee. The page lists your address’s coins through mempool.space’s signet API; when that does not answer it says so, and you can try again or enter outputs by hand as `txid:vout:sats`. - **Signing**: the page builds the transaction and the wallet signs its inputs as a PSBT. The operation’s signature is bound to the transaction’s first input, so it cannot be copied into another transaction. - **Broadcast**: through the hosted Bitcoin RPC proxy. Without a broadcast route the page gives you the signed raw transaction to broadcast yourself. - **Inclusion**: on the signet, the next fast-lane block anchored at or above the transaction’s Bitcoin block includes it, which takes 2 Bitcoin confirmations (`NATIVE_CONFIRMATIONS` 1 plus `ANCHOR_DEPTH` 1). Until then the node does not know the operation. If a path B operation with the same nonce gets in first, the path C operation is recorded as failed and its miner fee is not refunded. The page explains this before you sign a resubmission. ## Top up A top-up buys KSA with sBTC from a seller, in one Bitcoin transaction. The seller first locks KSA for your account in an exchange contract (the example `ksa-exchange` contract), with a price in KSA per sat, a payout address and an expiry height. Your payment to that address carries the claim operation as path C, and once it is included the contract credits the KSA to the account the seller named in the lock. 1. Get the exchange contract’s ID (64 hex digits) and the lock number from the seller. 2. Choose **Top up**, enter the **Exchange contract** and **Lock number**, and choose **Load**. The page shows the seller, the beneficiary (you), the price, the locked KSA, the payout address and how many Bitcoin blocks remain before the expiry. 3. Enter the **Amount to pay** in sats. **All** fills in the amount that buys all the locked KSA. Paying less buys part of it and leaves the rest locked for you; paying more buys nothing more. 4. Check the **BTC outputs** that pay for it and the **Miner fee**, then choose **Sign and broadcast** and sign the PSBT in your wallet. The page refuses a lock whose beneficiary is someone else, and a payment when 3 or fewer Bitcoin blocks are left before the expiry; it warns when 4 or fewer are left. After broadcasting it shows the Bitcoin transaction, the claim operation, and the height before which the payment should confirm. The KSA arrives once the claim is force-included, 2 Bitcoin confirmations later on the signet. The claim is signed with a one-time key made for this payment, not with your account’s key, so it uses none of your account’s nonces. There is no standing seller on the signet: someone with KSA has to lock some for you. To try a top-up alone, play the seller with a second key and the [`exchange` commands of ksana-cli](https://ksana.network/docs/cli/#exchange), then pay from the page. ## History and the explorer The wallet home lists operations that are not final yet under **In progress**, each with its progress and an estimate of when it will be final, and everything else under **Activity** (filter by **Sent**, **Received** or **Failed**). An operation marked **Stuck** has a reason in its details. The explorer pages work without a wallet: - **Overview**: the fast lane and Bitcoin as two lanes, the latest blocks and operations. - **Blocks** and **Settlements**: every fast-lane block with its parents, entries and the settlement that carried it; settlement, path C and republish transactions with their commit and reveal structure. - **Operations**: the latest operations, and an operation’s journey from its block to the Bitcoin transaction that carried it, with the changes it made to assets and its tokens’ events in their units. - **Assets**: a page for each built-in asset, KSA’s included, and for each KS-20 token and KS-721 collection: its whole ID, its supply, what its issuer can still do or its largest holders, and the operations that moved it. - **Verify**: the indexer’s state roots compared with the node’s, the two kinds of confirmation, and the network’s parameters. The search box takes heights, block hashes, op IDs, Bitcoin txids and heights, contract IDs, accounts, and an asset’s symbol, name or ID. A Bitcoin transaction or block the node does not know links to mempool.space. ## Use your own node The network chip in the top bar (**signet · node**) opens the **Data source** panel; **Settings** has the same panel. Enter the **Node JSON-RPC** URL of your node, choose the **signet** network, and connect. - Your node must allow the page’s origin: start it with `--rpc-cors https://signet.ksana.network` (or `'*'`). [Run a node](https://ksana.network/docs/run-a-node/) shows the command. - **Indexer JSON-RPC** and **Bitcoin RPC** are optional, and work only as a path on the page’s own origin, because neither the indexer nor bitcoind sends CORS headers. On the hosted page you can keep the hosted ones, `/indexer` and `/btc`. Without an indexer, the Verify page has nothing to compare and the page notes that “BTC final” is then only the node’s word. - The same choice fits in the address bar: `?rpc=&indexer=&btc=&chain=signet`. `?source=sim` switches to the in-browser simulator, a devnet that needs no services. The page reads the node’s chain ID before syncing and again before every signature, and refuses a node on another network. To run the page itself on your machine with proxies to your own node, indexer and bitcoind, follow the README of [ksana-web](https://github.com/ksana-in-bitcoin/ksana-web). ## Troubleshooting | What you see | What to do | | --- | --- | | Extension not found | Install Unisat or Xverse, then reload the page. | | … isn’t a Taproot address; switch to a Taproot account in your wallet. | Switch the wallet to its Taproot address (in Xverse, the Ordinals address). | | … is set to …, but this page’s network runs on BTC signet | Switch the wallet’s Bitcoin network to signet. | | The node is on another network | The page and the node disagree on the network: choose signet in the Data source panel, or connect to a signet node. | | Can’t reach … Make sure the node is running and allows … via `--rpc-cors`. | Start your node with `--rpc-cors` for this page’s origin. | | The faucet did not send KSA | The notice gives the faucet’s reason; most often the account already received KSA today. | | Not enough KSA for the sponsor fee | Claim test KSA, top up, or send on path C. | | No usable BTC output for the miner fee | Send sBTC to your address and wait for it to confirm. | | Couldn’t read BTC outputs | mempool.space did not answer: try again, or enter outputs by hand. | | Skipped, awaiting re-inclusion | The operation was in a parallel block that could not execute it. Nothing was charged; it returns to the pool and is included again. | | Settlement backlog at limit; fast paths paused | Settlements are waiting on Bitcoin. Balances already in effect stay; path C still works. | --- # Run a node URL: https://ksana.network/docs/run-a-node/ > A Ksana node follows the chain from its peers and checks every block against Bitcoin through your own bitcoind. Give it an account and it produces blocks; give it a funding key and it settles them on Bitcoin. A node keeps the fast lane’s block DAG, executes every block it accepts, and serves JSON-RPC to wallets, apps and `ksana-cli`. It reads Bitcoin through a bitcoind you run, which is how it checks anchors, settlements, forced inclusion of path C operations and finality without trusting anyone. This page sets one up on the [public signet](https://ksana.network/docs/signet/); mainnet has not launched. ## What a node does - **Following**: with no account given, the node syncs blocks from its peers, checks each one, relays blocks and operations, and answers RPC calls. - **Producing**: with `--producer `, it also mines blocks (Argon2id proof of work on one CPU core) and earns their rewards and path B fees. - **Settling**: with a funding key as well, it pays the Bitcoin transactions that write its blocks’ data into Bitcoin. Without one, other producers carry that data and take the carrier’s part of the reward. [Mining](https://ksana.network/docs/mining/) explains how producing and settling pay; this page covers the setup. ## Requirements | Need | What to provide | | --- | --- | | System | Ubuntu 22.04 is the tested platform. | | Rust | the version in `rust-toolchain.toml` (1.98.1), installed by `rustup` | | Bitcoin | Bitcoin Core on signet with `-txindex=1`, on the same machine or reachable over plain HTTP | | Disk | about 30 GB for bitcoind’s signet chain with its index; the node’s own data directory is small | | Memory | about 150 MiB for the node; bitcoind needs its own | | CPU | one core while producing, as mining keeps it busy | | Ports | TCP 9000 open for P2P; keep the node’s RPC (8545) and bitcoind’s RPC (38332) local | For scale: the hosted signet runs bitcoind, two producing nodes, the indexer and the web services on one server with 4 cores and 8 GB of memory, and its operator’s guide asks for at least 2 cores, 4 GB and 80 GB of disk with one producing node. In a 10-hour devnet soak test, each node ended at 130 to 149 MiB of resident memory, and a node’s data directory held about 58 MB after 7,308 blocks. ## Build Install the build tools and `rustup` as in the [quickstart](https://ksana.network/docs/quickstart/), then build the node, the indexer, the CLI and the key tool in one go: ```sh git clone https://github.com/ksana-in-bitcoin/ksana cd ksana rustup toolchain install cargo build --release --locked -p ksana-node -p ksana-indexer -p ksana-cli --bins ``` This leaves `ksana-node`, `ksana-keytool`, `ksana-indexer` and `ksana-cli` in `target/release/`. The first build compiles RocksDB, wasmtime and, for the node and the indexer, jemalloc from source: it takes about half an hour on 2 cores, and on a machine with 4 GB of memory it needs some swap. ## Run bitcoind on signet Install Bitcoin Core from [bitcoincore.org](https://bitcoincore.org/) (the hosted signet runs 31.1), choose an RPC password, and start it on signet with a transaction index: ```sh export KSANA_BTC_RPC_PASS='' bitcoind -signet -daemon -server -txindex=1 -rpcuser=ksana -rpcpassword="$KSANA_BTC_RPC_PASS" \ -rpcbind=127.0.0.1 -rpcallowip=127.0.0.1 BCLI="bitcoin-cli -signet -rpcuser=ksana -rpcpassword=$KSANA_BTC_RPC_PASS" $BCLI getblockchaininfo | jq '{blocks, initialblockdownload}' ``` The first sync downloads the signet chain and takes a few hours. Wait until `initialblockdownload` is `false`: the node refuses to start while bitcoind’s best chain does not yet contain the signet’s genesis anchor (`the genesis anchor block (height 327273) is not on bitcoind's best chain`). bitcoind’s signet RPC port is 38332. Bitcoin Core 30 or later also relays the large `OP_RETURN` output of the path C transactions you send with `ksana-cli`; earlier versions need `-datacarriersize=100000` for that. Settlements carry their data in a Taproot witness, which every version relays. ## The genesis config Every node and indexer of a network starts from the same genesis config. The signet’s is `signet/genesis.json` in the repository: ```json title="signet/genesis.json" { "timestamp": "1792553063", "btc_anchor": { "height": 327273, "hash": "41cb1fa60f4a0803b02024c7c0fd9cabb094f2935e7fcc4e7a63f03011000000" }, "bits": 520523192, "allocations": [ { "account": "de6603f052fd5bfaae5678a2a20ae6ae4fe4ae00c89db70a2efea7429851afc0", "amount": "10000000000000000" }, { "account": "6431409abb9b8434defe68b0e066cf76610ac7b1cf49f2d02bc807543877dc0e", "amount": "1000000000000000" } ], "block_share_account": "0073719af1ae0718ca4fde1055e6c5c34157eefd54302c9b19deb28927ce8d8c" } ``` It fixes the start time, the Bitcoin block the chain is anchored to (its hash in Bitcoin’s internal byte order, the reverse of what explorers show), the starting difficulty, the genesis allocations (the faucet’s and the operator’s KSA) and the block share account. A data directory remembers the config it was made with, and the node refuses another one with `data directory belongs to a different genesis config`. When the signet [restarts from genesis](https://ksana.network/docs/signet/#restarts-from-genesis), pull the repository and start with a new data directory. ## Follow the signet From the repository’s directory, with `KSANA_BTC_RPC_PASS` set as above: ```sh target/release/ksana-node --chain signet --data-dir ~/ksana-signet/node \ --genesis signet/genesis.json \ --btc-rpc-url http://127.0.0.1:38332 --btc-rpc-user ksana \ --p2p-listen /ip4/0.0.0.0/tcp/9000 --peer {{signet.p2p}} ``` - `--chain signet` selects the signet’s parameters; without it the node runs devnet. - `--data-dir` holds the block store, the state, the node’s P2P identity (`p2p.key`) and its pruning checkpoint. The directory is created when missing. - `--btc-rpc-url` and `--btc-rpc-user` reach bitcoind, and the node reads the password from `KSANA_BTC_RPC_PASS`, which keeps it out of the process list (`--btc-rpc-pass` works too). Only `http://` URLs work. - `--p2p-listen` turns on the P2P network and `--peer` dials the hosted seed node; repeat `--peer` for more peers. The node takes up to 100 inbound peers, at most 4 from one address, and a peer that sends three invalid blocks or operations is banned for a minute, with its address ([local policy defaults](https://ksana.network/docs/parameters/#local-policy-defaults)). The node logs to standard error. It prints `[ksana-node] network layer started: peer id …` and `[ksana-node] started: main-chain height …, tip …`, then `ksana-node rpc=127.0.0.1:8545` on standard output once its RPC listens. It then syncs from the seed node, and each time finality moves forward it logs `[ksana-node] BTC final: block … at height …`. Ctrl-C or `SIGTERM` stops it. ### The RPC The node answers JSON-RPC over HTTP and WebSocket on `--rpc-addr`, by default `127.0.0.1:8545` (an IP address and port; a host name is refused). The RPC has no authentication, so keep it local, or put it behind a proxy you control if others should use it. It takes batches of at most 64 calls and bodies of at most 1 MiB, and holds at most 100 connections and 16 subscriptions on each WebSocket connection ([limits](https://ksana.network/docs/rpc/#limits)); these have no flags, and a proxy in front of it can limit each client further. Point `ksana-cli --rpc http://127.0.0.1:8545` or your app at it. A browser page on another origin needs `--rpc-cors`: `--rpc-cors https://signet.ksana.network` lets the [signet wallet](https://ksana.network/docs/wallet/) use your node as its data source, `--rpc-cors '*'` allows every origin, and a comma-separated list allows several. ### Check that it works Once your node has caught up, its tip matches the hosted node’s (give or take the newest block): ```sh for rpc in http://127.0.0.1:8545 https://signet.ksana.network/rpc; do curl -sS "$rpc" -H 'content-type: application/json' \ --data '{"jsonrpc":"2.0","id":1,"method":"ksana_getChainInfo","params":[]}' | jq -c .result.tip done ``` Then: - Watch the log for `decided final` and `BTC final` lines: they show that your node decides finality from your bitcoind. - Read an account through your node, for example `ksana-cli --rpc http://127.0.0.1:8545 account @alice.key`. - Run an [indexer](https://ksana.network/docs/run-an-indexer/) next to it and compare state roots. ## Produce blocks ### Choose a payee account `--producer` names the account that receives your blocks’ rewards and path B fees: a `tb1p…` address from a wallet you control, or the `account` of a key file: ```sh target/release/ksana-keytool producer.key | jq . ``` ```output { "account": "02ee9753ea3f23d2cdd3c1d5b5caba98acc43e07074f8e8ec59db63d7dffe6fe", "funding_script": "512002ee9753ea3f23d2cdd3c1d5b5caba98acc43e07074f8e8ec59db63d7dffe6fe", "internal_key": "e7798d3c642863091e43f81dc4cc24acd6726b23702e4ebce8ae00cdffd50084", "mainnet_address": "bc1pqthfw5l28u3a9nwnc82mtj46nzkvg0s8qa8cark9nkmr6l0lumlqgkmm4q", "regtest_address": "bcrt1pqthfw5l28u3a9nwnc82mtj46nzkvg0s8qa8cark9nkmr6l0lumlqj88j64", "signet_address": "tb1pqthfw5l28u3a9nwnc82mtj46nzkvg0s8qa8cark9nkmr6l0lumlql7d500" } ``` `ksana-keytool ` creates the key file (mode `0600`) when it does not exist and prints the key’s account and its addresses. Use `account`, not `internal_key`: the account is the Taproot output key. `ksana-cli key` reads the same files, so `ksana-cli account @producer.key` later shows what the account has earned. Add `--producer ` to the command above. The node then mines on one core. Each block pays its producer a part of the 9.9 KSA of each of its reward slots on the signet, plus the path B fees it includes; it unlocks once the block’s data is on Bitcoin, and until then `ksana-cli account` lists it under `locked_fees`. [KSA and rewards](https://ksana.network/docs/ksa/) has the details. ### Settle your own blocks Without a funding key your blocks still include path B operations, and other producers’ settlements carry their data to Bitcoin. The node that lands a block’s data is its carrier: out of your part, it takes 5% of each of the block’s reward slots and half of its path B fees. To settle your blocks yourself, give the node a funding key: a hot wallet on signet whose sBTC pays for the commit and reveal transactions. On the signet the node lists the key’s coins through a watch-only wallet in your bitcoind and refuses to start without one, because a scan of signet’s whole UTXO set takes 30 to 50 seconds. ### Make the funding key ```sh target/release/ksana-keytool funding.key | jq . ``` `signet_address` is where the sBTC goes, and `funding_script` is its output script. ### Make the watch-only wallet Do this before you send the sBTC, so that the wallet sees it arrive: ```sh SCRIPT=$(target/release/ksana-keytool funding.key | jq -r .funding_script) $BCLI -named createwallet wallet_name=ksana-funding disable_private_keys=true blank=true \ load_on_startup=true DESC=$($BCLI getdescriptorinfo "raw($SCRIPT)" | jq -r .descriptor) $BCLI -rpcwallet=ksana-funding importdescriptors '[{"desc": "'"$DESC"'", "timestamp": "now"}]' ``` If the sBTC confirmed before the import, rescan from a signet height before it arrived: `$BCLI -rpcwallet=ksana-funding rescanblockchain `. ### Fund the address Send sBTC to `signet_address` in at least three outputs, since each settlement in flight uses one. 0.006 sBTC in all is enough to start; a node that produces a third of the blocks spends about 0.00017 sBTC a day at 2 sat/vB (up to 0.00035 with traffic), so 0.02 sBTC lasts it about eight weeks. Wait for the outputs to confirm. ### Start the node with the key ```sh target/release/ksana-node --chain signet --data-dir ~/ksana-signet/node \ --genesis signet/genesis.json \ --btc-rpc-url http://127.0.0.1:38332 --btc-rpc-user ksana \ --p2p-listen /ip4/0.0.0.0/tcp/9000 --peer {{signet.p2p}} \ --producer --btc-funding-key-file funding.key \ --btc-funding-wallet ksana-funding --funding-pool-target 0 ``` The node checks the wallet at startup and logs `the funding outputs are listed from bitcoind's wallet ksana-funding`. If the wallet does not watch the address it refuses to start, naming the descriptor to import. A settlement pair is about 300 to 360 vB, so about 700 sats at 2 sat/vB. Even an idle signet sends one about every two Bitcoin blocks, paid by the producer of the block that carries it. Check the funds with `$BCLI -rpcwallet=ksana-funding listunspent 0` and top up below 0.002 sBTC or three outputs: a node out of funds keeps producing, but its blocks’ data waits for another producer to carry it. `--funding-pool-target 0` keeps the outputs as you sent them. By default (64) the node splits its largest output into pieces of at least 100,000 sats whenever it has fewer than 64 usable ones; the hosted seed nodes run with 0 and are funded with several outputs instead. **The funding key is a hot wallet.** The node signs with it automatically, and anyone who reads `funding.key` can spend what the address holds. Keep only what settlements need there; a revenue address takes the rest. ### Fee policy These flags set what your node pays for its own Bitcoin transactions (settlements, rescues and republishes). They are local policy: other nodes do not check them. | Flag | Default | What it sets | | --- | --- | --- | | `--settlement-feerate` | `2` | The lowest fee rate in sat/vB: paid while the next Bitcoin block has room, and when bitcoind has no estimate. | | `--max-settlement-feerate` | `1000` | The highest fee rate, bumps included; paid at once while a lighter competing chain is on Bitcoin. | | `--settlement-conf-target` | `3` | The confirmation target, in Bitcoin blocks, for bitcoind’s `estimatesmartfee`. | While bitcoind’s mempool holds at most half a block (500,000 vB) and the last Bitcoin block was at most half full (2,000,000 weight units), the next Bitcoin block has room for everything waiting, and the node pays the floor, or the mempool’s own minimum when that is higher. Otherwise it pays bitcoind’s estimate within the floor and the cap. While a lighter competing chain is on Bitcoin it pays the cap instead, whatever bitcoind estimates and whatever room there is; when its funding outputs cannot pay the cap, it pays bitcoind’s next-block estimate. A settlement pair that has waited 2 Bitcoin blocks while paying less than the estimate gets a CPFP child that spends the reveal’s change; with or without room in the mempool, one still waiting after 2 blocks gets a child that lifts it to at least twice its own rate, and twice that again for every further block, up to the cap. When the pair’s change cannot pay that rate, the child pays all of it above the dust limit. A pair that waited while there seemed to be room, and that a Bitcoin block found 2 minutes or more after the node first saw it waiting leaves out, does not wait for the second block: it is lifted at once to at least the next-block estimate, and for the next 6 Bitcoin blocks the node pays the estimate for its new transactions whatever room shows. The node keeps that in memory only, so a restart forgets it. Keep the floor at 2 on the signet: on 13 October 2026 signet’s blocks took nothing below 2 sat/vB while transactions at 1 sat/vB waited. Cap it at 5 like the hosted seed nodes (`--max-settlement-feerate 5`): bitcoind’s estimate can stay far above what signet’s blocks take, as it stayed at 100 sat/vB from 16 October 2026. Path B has its own local policy: `--min-token-fee` (default 1) is the lowest fee in KSA base units your blocks include, `--min-relay-token-fee` the lowest your node admits and relays (by default the same), and `--min-fee-per-kib` (default 0, no limit) a floor on the fee rate. With `--ksa-price-sat`, what one KSA is worth to you in sat (for example `0.5`), a node that settles also asks each op for the KSA worth 128 vB per KiB of its encoded size at the Bitcoin fee rate it pays now, whatever the op’s `max_gas`, and sets that floor again at each Bitcoin block. The option has no default: the protocol sets no exchange rate, and without it the floors stay fixed. [Operations and fees](https://ksana.network/docs/submitting-ops/) explains how they apply. ### Revenue address `--revenue-address ` keeps the hot wallet small. Settlement change always returns to the funding address, so the node can bump any settlement it sent. When the funding coins available for settlements hold more than `--hot-wallet-cap-sat` (default 1,000,000 sats) by at least 100,000 sats and a tenth of the cap, the node sends a separate sweep transaction that moves that excess, less its fee, to the revenue address; the funding address keeps the cap. It needs `--btc-funding-key-file`, and the address must be a standard signet address other than the funding address. ### Other producer flags | Flag | Default | What it does | | --- | --- | --- | | `--carrier-payee ` | the `--producer` account | Receives the carrier reward when your node’s republish lands another block’s data. | | `--no-settlement-batching` | batching on | Each block that needs a settlement sends its own, instead of the next block carrying a backlog in one pair. | | `--min-block-interval-ms ` | `0` | The shortest gap between two of your blocks; the seed nodes use 1000. | ## Pruning and memory Pruning is on by default and keeps the node’s memory bounded. Once a block has been BTC-final for 144 Bitcoin blocks (about a day on the signet), the node drops from memory what no chain it can still switch to needs, in steps of 1,000 blocks. Each pruning writes `pruning.ckpt` to the data directory, and a restart continues from it. The block store on disk keeps every block, so the node still serves old blocks to peers that sync from far behind. `--no-pruning` keeps the whole history in memory, which grows with the chain. On Linux the node allocates with jemalloc and bounds RocksDB’s write buffers and cache; at each pruning it logs RocksDB’s memory use. ## Contract code and memory The node keeps the compiled code of every contract it has run in `vm-cache` under the data directory, so a contract is compiled once and read back after a restart. `--vm-code-cache-mib` bounds the directory (16,384 by default; `0` keeps none); past the limit the files used least recently are deleted and compiled again when called. The files are loaded as machine code: keep the directory writable by the node alone, as you do its binary. Contract instances take their memory from a pool the node keeps resident instead of asking the operating system for new pages each time. `--vm-pooled-calls` is the number of contract calls that use the pool at once (1 by default; `0` turns it off); a further call waits. Each may keep up to 1 GiB resident once contracts have used that much. The pool clears memory fastest on Linux 6.7 and later. If the pool cannot be set up, the node says so in its log and runs without it. Neither option changes what a block computes. A Bitcoin reorganization deeper than what a pruned node keeps stops it with a message that it must be resynced: start it again with an empty data directory. Such a reorganization would have to undo blocks that were final for a day. ## Common startup errors | Message | Cause | | --- | --- | | `BTC data source error: … Connection refused` | bitcoind is not running, or `--btc-rpc-url` is wrong. | | `the genesis anchor block (height 327273) is not on bitcoind's best chain` | bitcoind has not synced that far, or runs on another network. | | `data directory belongs to a different genesis config` | The directory belongs to another network or an earlier signet. | | `--btc-funding-key-file on signet needs --btc-funding-wallet as well` | Add the watch-only wallet. | | `--peer requires --p2p-listen as well` | Add `--p2p-listen`. | --- # Run an indexer URL: https://ksana.network/docs/run-an-indexer/ > The indexer rebuilds the whole chain from Bitcoin alone. It reads what settlements wrote into Bitcoin, executes every main-chain block and checks each block’s state root, so you can verify a node without trusting it. `ksana-indexer` talks to no Ksana node. It needs only a bitcoind on the same Bitcoin network, from which it collects the block headers and bodies that settlements and republishes wrote into Bitcoin. From those it builds the same block DAG and main chain as a node, executes the main-chain blocks, and checks that every block’s `state_root` matches what it computed. *Figure: Nodes talk to each other and read and write Bitcoin; the indexer only reads Bitcoin, and its state roots must match theirs.* ## Why run one - **Check a node.** When your indexer and a node report the same state root at a height, that node’s state there is exactly what the data on Bitcoin implies. This works for the hosted node too. - **Depend on Bitcoin alone.** Everything the indexer uses is on Bitcoin, so it shows that the chain can be rebuilt even if every Ksana node disappeared. - **Check finality.** It decides which blocks are final from Bitcoin with the same rules as a node, and raises an alarm when something does not add up. The [signet wallet](https://ksana.network/docs/wallet/)’s **Verify** page shows the same comparison for the hosted indexer and node. ## Build and run The indexer builds with the node (see [Run a node](https://ksana.network/docs/run-a-node/)), or on its own: ```sh cargo build --release --locked -p ksana-indexer ``` It needs bitcoind on signet with `-txindex=1`, synced past the signet’s genesis anchor; [Run a node](https://ksana.network/docs/run-a-node/#run-bitcoind-on-signet) shows how to start one. Then, from the repository’s directory: ```sh export KSANA_BTC_RPC_PASS='' target/release/ksana-indexer --chain signet --data-dir ~/ksana-signet/indexer \ --genesis signet/genesis.json \ --btc-rpc-url http://127.0.0.1:38332 --btc-rpc-user ksana ``` `--chain signet` and the genesis config must be the same as the nodes’, and the data directory remembers the genesis config it was made with. The password comes from `KSANA_BTC_RPC_PASS` (or `--btc-rpc-pass`), and bitcoind is reached over plain `http://` only. | Flag | Default | What it sets | | --- | --- | --- | | `--rpc-addr ` | `127.0.0.1:8546` | Where the JSON-RPC listens. | | `--poll-ms ` | `500` | The pause between two rounds of reading bitcoind. | | `--no-pruning` | pruning on | Keep the whole history in memory. | | `--vm-code-cache-mib ` | `16384` | The size limit of the compiled contract code kept in `vm-cache` under the data directory; `0` keeps none. | | `--vm-pooled-calls ` | `1` | Contract calls that take their memory from a pool kept resident (up to 1 GiB each); `0` turns the pool off. | The indexer has no CORS option: a browser page reaches it only through a proxy on the page’s own origin, as the hosted wallet does with `https://signet.ksana.network/indexer`. At startup it logs `[ksana-indexer] started: verified height …, state root …` to standard error and `ksana-indexer rpc=127.0.0.1:8546` to standard output. As it catches up it logs `verified up to height … (block tree main-chain height …, BTC height …)`, `decided final: block … at height …` when finality moves forward, and `BTC-final: block … at height …` when the BTC-final tip follows. A first sync of the signet takes as long as reading its Bitcoin blocks since the genesis anchor. ### How far it trails the node The indexer sees a block only once a settlement or republish has carried the block’s data into a Bitcoin block. It then verifies a main-chain block once that block has 2 confirmations on its main chain (`SETTLEMENT_DEPTH` on the signet) or is final. So its verified height trails a node’s tip by the blocks whose data has not reached a Bitcoin block yet, usually the last several minutes of blocks on the signet. ## The JSON-RPC The indexer answers two methods, over HTTP and WebSocket. `indexer_status` reports how far it got: ```sh curl -sS https://signet.ksana.network/indexer -H 'content-type: application/json' \ --data '{"jsonrpc":"2.0","id":1,"method":"indexer_status","params":[]}' ``` ```output {"jsonrpc":"2.0","id":1,"result":{"height":"51","hash":"5b69b10223571ab01bdee3080d8e1ed25c8ace4fc420f744d23b7d8d5db15981","state_root":"bd7ad23935fc366400a48eb8591696171be864520fd981c3204f9d5e64cc0963","btc_height":327291,"finalized":{"height":"38","hash":"ab3fe1dcb95f0d76cd171210567f571fcd81cc8f7559d68da7dd38348eec7cf2"},"halted":null}} ``` - `height`, `hash` and `state_root`: the highest block it has executed and verified. - `btc_height`: the Bitcoin height it has read up to (a number, unlike the fast-lane heights). - `finalized`: its BTC-final tip, from Bitcoin by the same rule as a node’s. - `halted`: `null` while all is well; otherwise why it stopped ([below](#alarms)). `indexer_stateRoot` takes a height, `"latest"` or a block hash, and answers for verified blocks only; for any other it returns `-32004`, `the block has not yet been executed and verified by the indexer`: ```sh curl -sS https://signet.ksana.network/indexer -H 'content-type: application/json' \ --data '{"jsonrpc":"2.0","id":1,"method":"indexer_stateRoot","params":["29"]}' ``` ```output {"jsonrpc":"2.0","id":1,"result":{"height":"29","hash":"88ab3dd805eac5654cdd752dc1a0a50c2c8d4fac581e2c46b2bd65bc7f35bb50","state_root":"2138690c600b998a923498e86eea30bef23c9ae5ee5d4eea79527e9a04d25f78"}} ``` `ksana-cli` cannot talk to an indexer, as it needs a node’s methods; use `curl` or the [TypeScript SDK](https://ksana.network/docs/sdk/)’s indexer client. ## Compare state roots with a node This script compares the last five heights the indexer verified with the node’s blocks at the same heights. Set `NODE` and `INDEXER` to yours, or keep the hosted ones; it needs `curl` and `jq`. ```sh title="compare-roots.sh" NODE=https://signet.ksana.network/rpc INDEXER=https://signet.ksana.network/indexer call() { # url method params curl -sS "$1" -H 'content-type: application/json' \ --data "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"$2\",\"params\":$3}" | jq -c .result } top=$(call "$INDEXER" indexer_status '[]' | jq -r .height) for h in $(seq $((top - 4)) "$top"); do a=$(call "$INDEXER" indexer_stateRoot "[\"$h\"]" | jq -c '[.hash, .state_root]') b=$(call "$NODE" ksana_getBlock "[\"$h\"]" | jq -c '[.hash, .header.state_root]') if [ "$a" = "$b" ]; then echo "$h same $a"; else echo "$h DIFFERENT indexer $a node $b"; fi done ``` ```output 47 same ["c52236bffa3e7c70c065fb44c81ce32c5926384a32e290cb6ef0fdadc9c777f6","2b467e3a07620190a59be9fc28fd31e913c132178f5fa4773011e51e9cb523ea"] 48 same ["2ca734d18afaae94bf0ac04c55a5d17a47a198f4512a19eb19f1c1b867635e41","e99d23768dbb247f974ca842623c26072832101b82db58a64cbf5d177f8e45e8"] 49 same ["ce36e3736a66c3773ed309cae018dd6e51fe2e4ad1e11b7d46893238026882a6","bd7ad23935fc366400a48eb8591696171be864520fd981c3204f9d5e64cc0963"] 50 same ["a8975ea2295f05403e1f943a09a3c28467415449302481dae475602f4ab4c8b5","bd7ad23935fc366400a48eb8591696171be864520fd981c3204f9d5e64cc0963"] 51 same ["5b69b10223571ab01bdee3080d8e1ed25c8ace4fc420f744d23b7d8d5db15981","bd7ad23935fc366400a48eb8591696171be864520fd981c3204f9d5e64cc0963"] ``` The block hashes must match as well as the state roots. Blocks 48 and 49 here each hold an operation, which changes the state root; 50 and 51 are empty blocks, which change no state, so they keep the root of 49. A difference right after a Bitcoin reorganization or a switch of main chain can last until both sides have followed it. A difference that stays at heights both have long passed means that the node and the indexer executed the same block differently: keep both data directories and report it as the [Security](https://ksana.network/docs/security/) page describes. ## Alarms The indexer reports problems on standard error as lines that start with `[ksana-indexer] alarm`. Most describe something it handles by itself: | Alarm | What the indexer does | | --- | --- | | `block … at height … is invalid (…)` | The nodes reject that block too; it leaves it out and chooses the main chain again. | | `block … cannot land (…)` | It leaves the block out and chooses the main chain again. | | `a BTC reorg took the anchor of main-chain block … off the BTC best chain` | It retreats below that block and chooses the main chain again. | | `block … met the BTC finality condition but is invalid` | It keeps that block, and every block built on it, out of finality. | A Bitcoin reorg that revokes only decisions not reported yet is not an alarm: the indexer logs `a BTC reorg revoked finality decisions, taking back nothing reported as BTC-final` and decides again on the new chain. Four alarms of the highest level need you: - `alarm (highest level): … processing halted`, also shown in `indexer_status` as `halted`, stops the indexer. A block that Bitcoin made final turned out invalid: either the fast lane finalized an invalid block, or Ksana’s software computes differently on different machines. Keep the data directory and report it. - `alarm (highest level): a BTC reorg took back BTC-final block … at height …` means that a Bitcoin reorganization of at least 6 blocks reached the Bitcoin block that decided a block the indexer had reported final. The indexer goes on with the new chain and reports the block final again if it is decided again; whatever you counted as final from that block on needs checking. - `the payload contains a block header of protocol version …, but this indexer only supports up to …` means the network has upgraded its rules. The indexer stops before the change; update it from the repository. - `cannot check block header … in the payload` means this machine could not compute a header’s proof of work, a local fault such as memory it could not allocate. The indexer judges nothing, logs `sync failed (will retry later)` and tries again; if the alarm keeps coming back, look at the machine. ## Restarts and pruning The indexer keeps its work in the data directory (`state/`, `index/`, `indexer.json` and `pruning.ckpt`). After a restart it first checks its stored state against the data on Bitcoin, waiting while bitcoind is behind, and then logs `verification against the BTC data complete: continuing from height …`. Pruning is on by default and works as on a node: memory keeps only what the main chains it can still follow need, the verified main chain below that is answered from the index on disk, and each pruning writes a checkpoint the next start continues from. In a 10-hour devnet soak test the indexer ended at 67 MiB of resident memory with a data directory of about 45 MB after 7,308 blocks. The indexer starts over from the genesis anchor by itself when it cannot continue from what it kept: after a Bitcoin reorganization deeper than that, when the main chain leaves its pruning root, or when its index is lost. It logs an alarm and rebuilds everything from bitcoind, which takes as long as a first sync. After a signet [restart from genesis](https://ksana.network/docs/signet/#restarts-from-genesis), give it the new genesis config and a new data directory. --- # The command-line client URL: https://ksana.network/docs/cli/ > `ksana-cli` talks to one Ksana node over JSON-RPC. It makes keys, reads accounts, blocks and operations, sends transfers and contract calls on path B or path C, and runs both sides of a top-up. `ksana-cli` reads the chain through a node’s JSON-RPC and signs operations on your machine with a key file, so no node ever sees your secret key. For path C and top-ups it also uses a wallet in your own bitcoind. The examples run against the [public signet](https://ksana.network/docs/signet/), the network to use today; mainnet has not launched. Their receipts show `asset_changes` as this version of the node records them; for these operations, which the signet’s nodes executed before they recorded the changes, `ksana-cli` prints `null`. ## Install Build it from the repository. The [quickstart](https://ksana.network/docs/quickstart/) lists the Ubuntu packages and the `rustup` setup the build needs. ```sh git clone https://github.com/ksana-in-bitcoin/ksana cd ksana rustup toolchain install cargo build --release --locked -p ksana-cli target/release/ksana-cli --version ``` ```output ksana-cli 0.1.0 ``` The binary is `target/release/ksana-cli`; put that directory on your `PATH` or copy the file into one. `ksana-cli --help` lists the commands, and `ksana-cli --help` lists a command’s options. ## Global options | Option | Default | What it sets | | --- | --- | --- | | `--rpc ` | `http://127.0.0.1:8545`, or `KSANA_RPC` | The node’s JSON-RPC address, over HTTP or HTTPS. | | `--chain ` | none | `devnet`, `signet` or `mainnet`: the network you expect the node to be on. | Both may come before or after the command. Every command except `key` first reads the node’s chain ID and signs for that network. With `--chain`, a node on another network is refused before anything is signed or sent: ```output ksana-cli: the node at https://signet.ksana.network/rpc is on signet (chain ID 1002), not devnet (--chain): refusing to sign for one network and send to another; drop --chain to use the node's network, or point --rpc at a devnet node ``` Pass `--chain signet` whenever you sign, so that a wrong `--rpc` cannot make you sign for another network. ### Environment variables | Variable | Stands for | | --- | --- | | `KSANA_RPC` | `--rpc` | | `KSANA_BTC_RPC_URL` | `--btc-rpc-url` (path C and top-ups) | | `KSANA_BTC_RPC_USER` | `--btc-rpc-user` | | `KSANA_BTC_RPC_PASS` | `--btc-rpc-pass` | An option on the command line wins over its variable. `ksana-cli --help` prints the current value of each variable next to its option, the bitcoind password included, so keep that output to yourself. ### Output and exit codes Results go to standard output as JSON with sorted keys; amounts, nonces and heights are decimal strings. Errors go to standard error as `ksana-cli: ` and exit with code 1, and a mistake in the options exits with code 2. An operation that a block includes but whose execution fails still exits with 0 and shows `"failed"`, so scripts should check `.status.status`. Wherever a command takes an account, you can write a Taproot address of the node’s network (`tb1p…` on the signet), the account as 64 hex digits, or `@` for the account of a key file. Amounts are always base units: KSA has 8 decimals, so 1 KSA is `100000000`. ## Keys ```sh ksana-cli --chain signet key alice.key ``` ```output { "account": "42cc119256c7207f971d113d908d66dff579f2f94e62eed29027f61f4d524d2d", "address": "tb1pgtxpryjkcus8l9cazy7eprtxml6hnuhefe3wa55sylmp7n2jf5kshm2h5s", "internal_key": "99b49d4d105d713742dcb48a5e09fab5edf9b564869d99c7ff73ab65dd76e9f2", "script": "512042cc119256c7207f971d113d908d66dff579f2f94e62eed29027f61f4d524d2d" } ``` `key` writes a new random secret key to the file (mode `0600`) when the file does not exist, and reads it when it does. It never contacts the node and never prints the secret. The file holds the secret key as 64 hex digits, the same format `ksana-keytool` and the node’s funding key use. When a key file can be read by its group or by every user of the machine, every command that reads it prints a warning on standard error and goes on; `chmod 600` the file to silence it. `account` is the Taproot output key, which is your account; `address` is the same 32 bytes as a Taproot address; `internal_key` is the key before the Taproot tweak, and `script` the address’s output script. Without `--chain` or `--network`, `key` prints a devnet address (`bcrt1p…`); `--network regtest|signet|testnet|mainnet` picks the address encoding directly. [Accounts](https://ksana.network/docs/accounts/) explains how keys, accounts and addresses relate. **Back up your key files.** A key file is the only copy of its secret key: whoever reads it controls the account, and losing it loses the account. Keep keys for the signet apart from keys that hold anything of value. ## Read the chain These commands only read. Each answer names the block it was read at in `at`. ### `account` ```sh ksana-cli account @bob.key ``` ```output { "account": "7e3f2a17f6af3db190101f3e5d55347a7f0eb83184c2be79ec8ac464da617f41", "address": "tb1p0clj59lk4u7mryqsrul964f50flsawp3snptu70v3tzxfknp0aqsey62tx", "at": { "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f", "height": "61" }, "balances": [ { "amount": "100000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000" } ], "locked_fees": [], "nonce": "0" } ``` `balances` lists what the account can spend now, one entry per asset; KSA is the asset of 64 zeros. `nonce` is the nonce the account’s next operation must carry. `locked_fees` lists income that is not unlocked yet, such as a producer’s fees and block rewards, one entry per block; it moves into `balances` once the block’s data is on Bitcoin. An account that has never been used shows nonce `0` and empty lists. With a node that indexes the token standards, `account` also lists `tokens`, the KS-20 tokens the account holds with their balances, `[{ "contract", "balance" }]`, and `nfts`, the KS-721 collections it holds NFTs of with how many, `[{ "contract", "count" }]`. A node without the index leaves both out. ### `asset` ```sh ksana-cli asset ``` ```output { "asset": "0000000000000000000000000000000000000000000000000000000000000000", "at": { "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f", "height": "61" }, "capabilities": [], "decimals": 8, "issuer": "0000000000000000000000000000000000000000000000000000000000000000", "name": "KSA", "paused": false, "symbol": "KSA", "total_supply": "11001412730000000" } ``` Without an argument it shows KSA; give an asset ID (64 hex digits) for another asset. KSA’s `total_supply` is the genesis allocation plus the block rewards unlocked so far. ### `contract` `ksana-cli contract ` shows a contract’s `code_hash`, its `deployer`, the `standards` it declared and the position of the operation that declared them. It works for any contract; [`ksana_getContract`](https://ksana.network/docs/rpc/#ksana_getcontract) describes the fields. ### `token` `ksana-cli token ` shows what the node’s index knows of a KS-20 token or a KS-721 collection: its standard and extensions, name, symbol and decimals, its supply and number of holders, and `irregular`, `true` when the index had to leave out one of its events. [`ksana_getToken`](https://ksana.network/docs/rpc/#ksana_gettoken) describes the fields. ### `holders` `ksana-cli holders ` lists a token’s or a collection’s holders, the largest balance first. A page holds 50 by default; `--limit ` asks for 1 to 500, and `--after ` continues after an earlier page, given that page’s `next`. `nfts` and `approvals` page the same way. ### `nfts` `ksana-cli nfts ` lists the NFTs an account holds, by collection and then token ID. `--contract ` keeps the NFTs of one collection. ### `approvals` `ksana-cli approvals ` lists the approvals an account gave: KS-20 allowances, KS-721 operators and the accounts approved to move single NFTs, as their latest events set them, expired or not. What is left of an allowance is the token’s `allowance` view, which [`query`](#query) reads. A node without the index refuses `contract`, `token`, `holders`, `nfts` and `approvals` with error `-32601`. The index tells what an account holds; ask the contract with `query` for an amount you act on. ### `op` ```sh ksana-cli op 032d7d956cff983e57db09411a345aae134aa12b8b0c72305f8cdccfad4bb4b2 ``` ```output { "block": { "hash": "8948675528f5bdfd5f928bc0ee70ebeec9b3a96612738a4a883247824d9bf4d8", "height": "28" }, "index": 0, "receipt": { "asset_changes": [ { "amount": "10000000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000", "events": 0, "from": "de6603f052fd5bfaae5678a2a20ae6ae4fe4ae00c89db70a2efea7429851afc0", "kind": "transfer", "to": "42cc119256c7207f971d113d908d66dff579f2f94e62eed29027f61f4d524d2d" } ], "error": null, "events": [], "gas_used": "10000", "op_id": "032d7d956cff983e57db09411a345aae134aa12b8b0c72305f8cdccfad4bb4b2", "output": "", "success": true }, "status": "btc_final" } ``` `block.height` is the height of the main-chain block that accepted the operation’s block, `index` its place among the block’s entries, and `receipt` the result of executing it, whose `asset_changes` lists what the op did to built-in assets, in order (the [RPC page](https://ksana.network/docs/rpc/#ksana_getopstatus) lists the kinds). `status` is one of these: | Status | Meaning | | --- | --- | | `pending` | In the node’s entry pool, not in a block yet. | | `fast_confirmed` | Included and executed successfully. | | `failed` | Included, but the execution failed; the fee is charged anyway. | | `skipped` | Included only by a parallel block that could not execute it; nothing is charged, and it goes back to the pool to be included again. | | `btc_final` | Executed successfully, and its block is final on Bitcoin. | An operation the node does not know is an error, `ErrorObject { code: ServerError(-32004), message: "unknown op", … }`. A path C operation stays unknown until a block includes it. [Confirmations](https://ksana.network/docs/confirmations/) explains what each status guarantees. ### `block` `ksana-cli block` takes `latest`, a height or a block hash. A height names the main-chain block at that height; a hash can name any block, parallel blocks included. **The block that included this page’s transfer** ```sh ksana-cli block 29 ``` ```output { "accepted_height": "29", "entries": [ { "Sponsored": { "op": { "account": "42cc119256c7207f971d113d908d66dff579f2f94e62eed29027f61f4d524d2d", "action": { "AssetTransfer": { "amount": "100000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000", "to": "7e3f2a17f6af3db190101f3e5d55347a7f0eb83184c2be79ec8ac464da617f41" } }, "chain_id": 1002, "fee": { "Token": { "amount": "1" } }, "max_gas": "1000000", "nonce": "0", "sig": { "Bip340": "8ee2feb60ec2b4ab2861db2a8a756703ac527b43409f67594a0686f0a832bd356d219e01a72a5a1377e7c9f9152e0148b4788ce4ce1e9c63d7d3fa565cec124b" }, "version": 2 } } } ], "hash": "88ab3dd805eac5654cdd752dc1a0a50c2c8d4fac581e2c46b2bd65bc7f35bb50", "header": { "bits": 520499087, "btc_anchor": { "hash": "c770c385e86ae4792f479f8a8c0fd3fde68b3fb604d47911afa42c5103000000", "height": 327279 }, "entries_root": "11677bbe5187d3b8021bcc06edc2e6cf7eeda32fcd804c8d38bc155120cca92d", "height": "29", "nonce": "1357", "parents": [ "8948675528f5bdfd5f928bc0ee70ebeec9b3a96612738a4a883247824d9bf4d8" ], "producer": "ccc06c3ce8d176b3c10138dd4e70873939a9c6dc05597f45aace147ef2c07d3d", "state_root": "2138690c600b998a923498e86eea30bef23c9ae5ee5d4eea79527e9a04d25f78", "timestamp": "1792558561", "version": 2 }, "merged": [], "receipts": [ { "asset_changes": [ { "amount": "100000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000", "events": 0, "from": "42cc119256c7207f971d113d908d66dff579f2f94e62eed29027f61f4d524d2d", "kind": "transfer", "to": "7e3f2a17f6af3db190101f3e5d55347a7f0eb83184c2be79ec8ac464da617f41" } ], "error": null, "events": [], "gas_used": "10000", "op_id": "9e3c9bbeacd422ef8888c9992dc0f7024e1b8ae08edec0ed8dc5897495766503", "output": "", "success": true } ], "settlement": null } ``` The header names the block’s `parents`, the Bitcoin block it is anchored to (`btc_anchor`, whose hash is in Bitcoin’s internal byte order), its `producer` and its `state_root`. `entries` and `receipts` pair up by position; `merged` lists the parallel blocks this block merges, and `settlement` holds the commit and reveal transactions the block carries, or `null`. ### `settlement` `ksana-cli settlement ` shows the Bitcoin transactions that carry a block’s data, and where they are: - `status`: `pending` (not sent yet), `broadcast` (sent, waiting for a Bitcoin block) or `confirmed`, with the Bitcoin block and its confirmation count under `confirmed`. - `settled`: `true` once this block and every block before it are on Bitcoin. This is the on-Bitcoin mark. - `btc_final`: `true` once the block is final. - `carrier`: the later block whose settlement carried this block’s data, when producers batched it; `null` when the block carries its own. - `carrier_account`: the account paid the carrier reward for landing the block’s data on Bitcoin, the producer of the block whose settlement carried it or a republisher’s payee; `null` when there is none, and the producer keeps that part. - `txid_rpc` and `commit_txid_rpc`: the reveal and commit transaction IDs as Bitcoin explorers write them; `txid` and `commit_txid` are the same in internal byte order, as are the hashes under `confirmed`. A block with no body to land, an empty block or one holding only path C operations, has no settlement unless it carries one itself: the command answers `-32004` with `that block has no settlement transactions`. The [quickstart](https://ksana.network/docs/quickstart/#follow-it-to-final) shows a full answer. ### `estimate-fee` ```sh ksana-cli estimate-fee ``` ```output { "at": { "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f", "height": "61" }, "feerate_sat_vb": "2", "path_b": { "amount": "1", "per_kib": "4" } } ``` `path_b.amount` is the node’s suggested `--fee-token` for a plain KSA transfer, in base units, and `path_b.per_kib` the suggested fee per KiB of an operation’s cost, for larger operations. A node run with `--ksa-price-sat` adds `path_b.per_kib_data`, the fee it asks per KiB of an operation’s encoded size. `feerate_sat_vb` is the Bitcoin fee rate the node pays for its own settlements now, a reference for `--btc-fee-rate`. All of them are suggestions; [Operations and fees](https://ksana.network/docs/submitting-ops/) explains how fees work. ## Send a transfer ```sh ksana-cli --chain signet transfer --key alice.key --to @bob.key \ --amount 100000000 --fee-token 1 --wait ``` ```output { "account": "42cc119256c7207f971d113d908d66dff579f2f94e62eed29027f61f4d524d2d", "nonce": "0", "op_id": "9e3c9bbeacd422ef8888c9992dc0f7024e1b8ae08edec0ed8dc5897495766503", "status": { "block": { "hash": "88ab3dd805eac5654cdd752dc1a0a50c2c8d4fac581e2c46b2bd65bc7f35bb50", "height": "29" }, "index": 0, "receipt": { "asset_changes": [ { "amount": "100000000", "asset": "0000000000000000000000000000000000000000000000000000000000000000", "events": 0, "from": "42cc119256c7207f971d113d908d66dff579f2f94e62eed29027f61f4d524d2d", "kind": "transfer", "to": "7e3f2a17f6af3db190101f3e5d55347a7f0eb83184c2be79ec8ac464da617f41" } ], "error": null, "events": [], "gas_used": "10000", "op_id": "9e3c9bbeacd422ef8888c9992dc0f7024e1b8ae08edec0ed8dc5897495766503", "output": "", "success": true }, "status": "fast_confirmed" } } ``` `transfer` moves `--amount` base units of KSA to `--to`; `--asset ` sends another asset. Without `--wait` the command prints `account`, `nonce` and `op_id` as soon as the node accepts the operation, and you follow it with `ksana-cli op`. ### Options for sending `transfer`, `deploy`, `call` and the `exchange` commands that change state (`deposit`, `withdraw`, `lock`, `release`) share these options. Each needs `--key` and exactly one of `--fee-token` and `--native`. | Option | Default | What it does | | --- | --- | --- | | `--key ` | required | The key file that signs; its account sends the operation. | | `--fee-token ` | | Path B: the fee in KSA base units, paid to the producer. | | `--native` | | Path C: carry the operation in your own Bitcoin transaction ([below](#path-c-with-bitcoind)). | | `--nonce ` | the account’s nonce | The operation’s nonce. | | `--max-gas ` | `1000000` | The execution limit; a failed operation uses all of it. | | `--sig ` | `bip340` | `bip340`, or `bip322`, the scheme browser wallets use. | | `--wait` | off | Wait until a block includes the operation ([below](#waiting-and-timeouts)). | | `--timeout ` | `120` | How long `--wait` waits. | The default nonce is the account’s nonce at the chain tip, and it does not count operations still waiting in the node’s pool. If you send a second operation before the first is in a block, both carry the same nonce and the node refuses the second with `-32011`: `an op with the same nonce already exists; replacing it needs a sponsored fee of at least `. Use `--wait` between operations, or give each one its `--nonce`. With the same nonce, a `--fee-token` of at least the fee the message names replaces an operation that is still waiting: a tenth more than its fee, and at least the node’s relay floor more. ## Contracts Contracts are WebAssembly modules. [Write a contract](https://ksana.network/docs/contracts/) covers building one, and the [token and pool tutorial](https://ksana.network/docs/token-and-pool/) deploys and uses two on the signet step by step. ### `deploy` ```sh ksana-cli --chain signet deploy --key alice.key \ --code crates/ksana-execution/tests/data/token.wasm \ --init-args 040000005465737403000000545354080010a5d4e80000000000000000000000 \ --fee-token 1 --wait | tee deploy.json ``` `--code` is the wasm file and `--init-args` the hex of the arguments the contract’s `init` receives (none by default). `--fund` attaches assets to `init` ([below](#arguments-and-attached-funds)). The repository keeps a built token at `crates/ksana-execution/tests/data/token.wasm`; its `init` takes a name, a symbol, the decimals and the supply, here `"Test"`, `"TST"`, 8 and 1,000,000,000,000 base units. Deploying costs 100,000 gas plus 20 gas per byte of code before `init` runs, so the default `--max-gas` of 1,000,000 covers code up to about 40 KB. A whole operation, code included, must fit in 64 KiB (`MAX_OP_BYTES`). ### Find the contract ID `deploy` does not print the new contract’s ID: you compute it. It is the SHA-256 of the deploying account, the deploy operation’s nonce as an 8-byte little-endian integer, and the SHA-256 of the code. This shell function computes it with Python: ```sh contract_id() { # account nonce wasm-file python3 -c 'import hashlib, sys code = hashlib.sha256(open(sys.argv[3], "rb").read()).digest() seed = bytes.fromhex(sys.argv[1]) + int(sys.argv[2]).to_bytes(8, "little") + code print(hashlib.sha256(seed).hexdigest())' "$@" } contract_id 6b77bade530385d352e9d68ab6af57d110a4bb27d92dcc3221fe32f8f683bd8a 0 \ crates/ksana-execution/tests/data/token.wasm ``` ```output e36da19a8adccf6dcfd8c73dccf16a64c032067dc89f28b2ceecdf14c27d392d ``` That is a token deployed on the signet from account `6b77bade…` with nonce 0, with the code and the `init` arguments of the `deploy` above, and the `query` below reads it. For your own deployment, pass the `account` and `nonce` that `deploy` printed (this uses `jq`): ```sh TOKEN=$(contract_id "$(jq -r .account deploy.json)" "$(jq -r .nonce deploy.json)" \ crates/ksana-execution/tests/data/token.wasm) ``` When `init` emits an event, as the token’s does, the deploy receipt’s `events[].contract` shows the same ID. ### `query` `query` runs a contract method on the node without sending anything, so it costs no fee and needs no key: ```sh ksana-cli query --contract e36da19a8adccf6dcfd8c73dccf16a64c032067dc89f28b2ceecdf14c27d392d \ --method metadata ``` ```output { "asset_changes": [], "error": null, "events": [], "gas_used": "37555", "op_id": null, "output": "04000000546573740300000054535408", "success": true } ``` `output` is the method’s return value in hex, here the Borsh encoding of `("Test", "TST", 8)`. `--args` passes arguments, `--caller ` sets the caller the method sees (32 zero bytes by default), and `--fund` simulates attached assets. ### `call` `call` sends a contract call as an operation. This one moves 250 base units of the token you deployed above, which `init` gave to your account, to another account; the arguments `(to, amount)` are encoded as Borsh: ```sh TO=7e3f2a17f6af3db190101f3e5d55347a7f0eb83184c2be79ec8ac464da617f41 AMOUNT=fa000000000000000000000000000000 # 250 as a 16-byte little-endian integer ksana-cli --chain signet call --key alice.key --contract "$TOKEN" \ --method transfer --args "$TO$AMOUNT" --fee-token 1 --wait ``` The result has the same shape as a transfer’s. A method that reverts gives `"status": "failed"` with the reason in `.status.receipt.error`, and the command still exits with 0. ### Arguments and attached funds `--args` and `--init-args` take the raw argument bytes in hex (a `0x` prefix is allowed); `ksana-cli` does not encode anything for you. The example contracts read Borsh: a tuple of the arguments in order, a single argument as itself, and no bytes for none. | Type | Borsh encoding | | --- | --- | | `u8`, `u32`, `u64`, `u128` | little-endian, 1, 4, 8 or 16 bytes | | `[u8; 32]` (an account or contract ID) | the 32 bytes | | `String`, `Vec` | the length as a 4-byte little-endian integer, then the bytes | `--fund` attaches assets to `deploy`, `call` and `query`: `--fund 5000` attaches 5,000 base units of KSA, and `--fund :` another asset. Repeat it for several assets, at most 16, each asset once. ## Path C with bitcoind With `--native`, the operation travels in a Bitcoin transaction of your own instead of a node’s pool: you pay the Bitcoin fee and no KSA fee, and every producer must include the operation once the transaction has its confirmations. [Operations and fees](https://ksana.network/docs/submitting-ops/) explains when that helps. `ksana-cli` builds the transaction, has a bitcoind wallet add inputs and change and sign them, signs the operation over the transaction’s first input, and broadcasts it. You need: - your own bitcoind on the same Bitcoin network as the node (signet for the public signet), reachable over plain `http://`: the CLI has no TLS for bitcoind; - a wallet in it holding some sBTC; a transfer at the default 2 sat/vB costs about 700 sats of fee; - Bitcoin Core 30 or later, or `-datacarriersize=100000`, so that your bitcoind relays the transaction’s large `OP_RETURN` output. The hosted Bitcoin RPC proxy has no wallet methods, so it cannot do this. [Run a node](https://ksana.network/docs/run-a-node/) shows how to set up bitcoind on signet. ```sh export KSANA_BTC_RPC_URL=http://127.0.0.1:38332 export KSANA_BTC_RPC_USER=ksana export KSANA_BTC_RPC_PASS= ksana-cli --chain signet transfer --key alice.key --to @bob.key --amount 100000000 \ --native --btc-wallet ``` The command prints `account`, `nonce`, `op_id` and `btc_txid`, the Bitcoin transaction ID as explorers write it. `--btc-wallet` names the bitcoind wallet that pays (bitcoind’s only loaded wallet when you leave it out), and `--btc-fee-rate` sets the fee rate in sat/vB (default 2). The command refuses a rate above `--max-btc-fee-rate` (default 1000) before it funds or signs anything, so a mistyped rate does not pay a large fee. On the signet a block includes the operation once its transaction has 2 Bitcoin confirmations (`NATIVE_CONFIRMATIONS` 1 plus `ANCHOR_DEPTH` 1); on mainnet it will take 5. Until then `ksana-cli op ` answers `unknown op`. Leave out `--wait`, or give it `--timeout 3600`: the default 120 seconds runs out long before. **Keep the account quiet until it is included.** A path C operation carries the account’s nonce. If a path B operation of the same account takes that nonce first, the path C operation fails when it is included and its Bitcoin fee is spent. On path C, `--max-gas` must stay at or below 1,000,000 (`NATIVE_MAX_GAS`), or the operation fails on chain and uses its nonce. ## Exchange A top-up sells KSA for bitcoin through an exchange contract: the seller locks KSA for one buyer, and the buyer’s Bitcoin payment carries the claim. The `exchange` commands are the seller’s side, written for the example contract `ksa-exchange`. On the signet nobody runs a standing exchange, so to try it you deploy one yourself. ```sh (cd contracts && cargo rustc --release --locked --target wasm32-unknown-unknown \ --package ksa-exchange --crate-type cdylib) WASM=contracts/target/wasm32-unknown-unknown/release/ksa_exchange.wasm ksana-cli --chain signet deploy --key seller.key --code $WASM --fee-token 1 --wait \ | tee exchange.json EXCHANGE=$(contract_id "$(jq -r .account exchange.json)" "$(jq -r .nonce exchange.json)" $WASM) ``` The contract’s `init` takes no arguments, and `contract_id` is the function from [Find the contract ID](#find-the-contract-id). Then, as the seller: ```sh ksana-cli --chain signet exchange lock --key seller.key --fee-token 1 \ --exchange "$EXCHANGE" --ksa 3000000 --price 100 --fund 3000000 \ --address --beneficiary \ --expiry --wait ``` This locks 3,000,000 base units of KSA for the buyer at 100 base units per sat, so 30,000 sats buy all of it. The result’s `lock` field is the lock number; give it and the exchange ID to the buyer. - `--fund` attaches KSA to the call, which goes into your available balance in the contract before the lock takes `--ksa` from it. `exchange deposit --amount ` adds to that balance ahead of time, and `exchange withdraw --amount ` takes from it; neither touches a lock. - `--address` (or `--script `) is where the buyer pays. Use a fresh address for every lock: the contract refuses a payment script that any earlier lock used. - `--expiry` is a Bitcoin height above the one the current block is anchored to (`header.btc_anchor.height` in `ksana-cli block latest`). Signet makes a block about every ten minutes, so add enough for the buyer to pay. - `exchange release --lock ` returns what is still locked to your available balance. It works only once the anchored Bitcoin height reaches the expiry plus 6 blocks. Two commands only read: ```sh ksana-cli exchange show --exchange "$EXCHANGE" --lock 0 ksana-cli exchange balance --exchange "$EXCHANGE" --seller @seller.key ``` `show` prints the lock’s `seller`, `beneficiary`, payment `script`, `price`, the `ksa` still locked, `expiry`, `sats_for_all` (the sats that buy all of it) and its `state`: `open`, `released`, or `claimed` with what was paid. `balance` prints your available balance in the contract. ## Top-up `top-up` is the buyer’s side. One Bitcoin transaction pays the lock’s address and carries the claim as a path C operation, signed with a one-time key, so your own account signs nothing and spends no nonce. ```sh ksana-cli --chain signet top-up --exchange --lock \ --beneficiary @buyer.key --sats 30000 --btc-wallet ``` Before paying, the command reads the lock and refuses to pay when: - its beneficiary is not `--beneficiary`, since the KSA would go to someone else; - it is not open; - you pass `--exchange-code-hash` and the node gives another code hash for the exchange contract (the SHA-256 of its code, as `ksana-cli contract` prints it). Pass the hash of the code you reviewed when the contract ID came from someone else. The check asks the node, so it guards against a wrong contract and not against a node that lies; - 3 or fewer Bitcoin blocks are left before its expiry (`--expiry-margin`, default 3); - `--sats` differs from what buys all the KSA still locked. `--allow-partial` lets you buy part of it and leave the rest locked for you; `--allow-overpay` lets you pay more, which buys nothing more. It needs bitcoind as [path C](#path-c-with-bitcoind) does, and prints the `op_id` of the claim, the `btc_txid`, the Bitcoin fee, the `ksa` you get, the lock’s terms and `pay_by`, the Bitcoin height by which the payment must confirm: after it, the seller’s release may run first. The KSA reaches the beneficiary when a block includes the claim, 2 Bitcoin confirmations later on the signet. The [signet wallet](https://ksana.network/docs/wallet/) does the same from a browser. ## Waiting and timeouts `--wait` asks the node for the operation’s status every half second and returns at `fast_confirmed`, `failed` or `btc_final`; a `pending` or `skipped` operation keeps it waiting. After `--timeout` seconds (default 120) it prints the status if the last one it saw was `skipped`, and otherwise stops with an error and exit code 1: ```output ksana-cli: timed out waiting for the op to be included (120 seconds) ``` **The operation may still be on its way.** A timeout does not cancel anything: the operation was sent, and with path C or `top-up` the Bitcoin transaction was broadcast. The error also replaces the result, so the `op_id` and `btc_txid` are not printed. To find out what happened: - Run `ksana-cli account` for the sending account: when `nonce` has gone up, a block has included the operation. - For path C, look for the transaction in the funding wallet (`bitcoin-cli -signet -rpcwallet= listtransactions`) and wait for its confirmations. - List the account’s latest operations, newest first, with the node’s `ksana_getAccountOps` method. It takes the account as 64 hex digits and gives each operation’s `op_id` and status (this uses `jq`): ```sh ACCOUNT=$(ksana-cli account @alice.key | jq -r .account) BODY='{"jsonrpc":"2.0","id":1,"method":"ksana_getAccountOps","params":["'$ACCOUNT'",null,5]}' curl -sS https://signet.ksana.network/rpc -H 'content-type: application/json' \ --data "$BODY" | jq .result ``` ```output { "ops": [ { "op_id": "9e3c9bbeacd422ef8888c9992dc0f7024e1b8ae08edec0ed8dc5897495766503", "status": "btc_final", "block": { "height": "29", "hash": "88ab3dd805eac5654cdd752dc1a0a50c2c8d4fac581e2c46b2bd65bc7f35bb50" }, "index": 0, "position": "29:0:0" }, { "op_id": "032d7d956cff983e57db09411a345aae134aa12b8b0c72305f8cdccfad4bb4b2", "status": "btc_final", "block": { "height": "28", "hash": "8948675528f5bdfd5f928bc0ee70ebeec9b3a96612738a4a883247824d9bf4d8" }, "index": 0, "position": "28:0:0" } ], "next": null, "at": { "height": "61", "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f" } } ``` The list covers the operations the account signed, the transfers it received and the operations whose token events or changes to built-in assets name it; the second one here is the faucet’s. Do not send an operation again with a new nonce until you know the first one failed, or both can go through. The [JSON-RPC reference](https://ksana.network/docs/rpc/) describes `ksana_getAccountOps` and its paging. ## Common errors | Message | What to do | | --- | --- | | `reading the chain ID of the node at …: … Connection refused` | The node is not running or `--rpc` is wrong. | | `… Method not found …` while reading the chain ID | `--rpc` points at something other than a node, such as an indexer. | | `invalid account: invalid address: validation error` | The address belongs to another network than the node’s. | | `the following required arguments were not provided: <--fee-token \|--native>` | Choose path B (`--fee-token`) or path C (`--native`). | | `-32011` … `an op with the same nonce already exists` | An earlier operation is still waiting; wait for it or set `--nonce`. | | `bitcoind …: … https feature is not enabled` | Use `http://` for bitcoind. | | `bitcoind fundrawtransaction: … Method not found` | That bitcoind has no wallet, as with the hosted proxy. Use your own bitcoind with a wallet. | --- # TypeScript SDK URL: https://ksana.network/docs/sdk/ > The @ksana/sdk package builds, signs and sends Ksana operations from Node.js and browsers, connects Bitcoin wallets, and reads nodes and indexers. The SDK lives in `sdk/ts` of the repository, as the package `@ksana/sdk`. It runs in Node.js 20.19 or later and in browsers, and its library code uses only Web APIs. It speaks the node’s [JSON-RPC API](https://ksana.network/docs/rpc/) for you: byte strings are `Uint8Array`, `u64` and `u128` values are `bigint`, and `u8` and `u32` values are `number`. Every example on this page type-checks against the packed SDK, and the examples shown with their output ran against the public signet on 21 October 2026. Mainnet has not launched, so the examples use the signet. ## Install the SDK The package is not on npm. Build it from the repository, pack it into a tarball, and install the tarball in your project: ```sh git clone https://github.com/ksana-in-bitcoin/ksana (cd ksana/sdk/ts && npm ci && npm run build && npm pack) mkdir -p my-app/vendor && mv ksana/sdk/ts/ksana-sdk-0.1.0.tgz my-app/vendor/ cd my-app npm init -y npm pkg set type=module npm install ./vendor/ksana-sdk-0.1.0.tgz ``` npm records the tarball in `package.json`, so `npm ci` works later without the clone. Build before you pack: a tarball packed without `npm run build` holds no code. The package is an ES module, and its types are reachable only through its `exports` map: - In TypeScript, set `moduleResolution` to `node16`, `nodenext` or `bundler`. The older `node` setting cannot find the types. - In a browser, use a bundler such as Vite or esbuild: the SDK imports its dependencies by package name. - Import everything from `@ksana/sdk`. Deeper paths into the package are blocked. **Keep the SDK and the node together.** The SDK rejects any result field it does not know. An SDK older than the node therefore fails with an `RpcTransportError` whose message starts with `malformed result`. Build the SDK from the same version of the repository as the node you use, and rebuild the tarball when the node moves ahead. ## Connect to a node ```typescript title="connect.ts" import { KsanaRpcClient, SIGNET } from '@ksana/sdk'; const rpc = new KsanaRpcClient('https://signet.ksana.network/rpc', { timeoutMs: 30_000 }); // The parameters to sign with. A node on another network throws ChainMismatchError here. const params = await rpc.getParams(SIGNET); const { tip, finalized } = await rpc.getChainInfo(); console.log(`chain ${params.chain_id}, tip ${tip.height}, finalized ${finalized.height}`); ``` ```output chain 1002, tip 60, finalized 38 ``` `getParams` reads the node’s chain ID and returns that network’s parameters, which every builder and signer takes. With the network you expect as its argument, here `SIGNET`, it throws `ChainMismatchError` when the node is on another network, before you sign anything. The SDK has no default network; its three parameter sets are `DEVNET`, `SIGNET` and `MAINNET`. `finalized` is the newest final block. The client also takes `headers` and a `fetch` function in its options, and it has no timeout unless you set `timeoutMs`. ## Keys and accounts A Ksana account is the Taproot output key of a secret key: 32 bytes, the witness program of its `tb1p` address on the signet and its `bc1p` address on mainnet. The SDK has no key generator, so draw random bytes until they form a valid key. The key files of `ksana-cli` hold the secret key as 64 hex digits, and `ksana-cli --chain signet key alice.key` creates one: ```typescript title="keys.ts" import { readFile } from 'node:fs/promises'; import { fromHex, isValidSecretKey, randomBytes } from '@ksana/sdk'; /** A new secret key: 32 random bytes that are a valid secp256k1 key. */ export function newSecretKey(): Uint8Array { for (;;) { const key = randomBytes(32); if (isValidSecretKey(key)) return key; } } /** Reads a key file of ksana-cli or ksana-keytool: the secret key as 64 hex digits. */ export async function readKeyFile(path: string): Promise { return fromHex((await readFile(path, 'utf8')).trim(), 32, path); } ``` ```typescript title="accounts.ts" import { accountOf, accountToAddress, parseAccount, toHex } from '@ksana/sdk'; import { readKeyFile } from './keys.js'; const account = accountOf(await readKeyFile('alice.key')); // 32 bytes: the Taproot output key const address = accountToAddress(account, 'signet'); console.log(toHex(account)); console.log(address); // parseAccount takes 64 hex digits or a Taproot address of the given network console.log(toHex(parseAccount(address, 'signet')) === toHex(account)); ``` ```output b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d tb1pklkarsaaegsk2dxgh4ug9tru6q6x63gge8emdeltt8fpxm6r7zwse04hlm true ``` `parseAccount(text, network)` takes 64 hex digits or a Taproot address of that network, and refuses other address types. A contract has an ID but no address, and `accountToAddress` cannot tell a contract ID from an account, since about half of all 32-byte strings are valid keys. The client’s methods take an account as bytes or 64 hex digits, never as an address, so run `parseAccount` on what users type. ## Send an op on path B A path B op pays its fee in KSA and goes straight to a node. You need the account’s next nonce, a fee, a gas limit and a signature. ### With a key ```typescript title="transfer.ts" import { type KsanaRpcClient, type Params, type UnsignedVmOp, VMOP_VERSION, accountOf, encodeVmOp, ksaAssetId, pathBFee, signedVmop, } from '@ksana/sdk'; /** Sends `amount` base units of KSA to `to` on path B and returns the op's ID. */ export async function transfer( rpc: KsanaRpcClient, params: Params, secretKey: Uint8Array, to: Uint8Array, amount: bigint, ): Promise { const account = accountOf(secretKey); const [{ nonce }, estimate] = await Promise.all([rpc.getAccount(account), rpc.estimateFee()]); const maxGas = 10_000n; // a KSA transfer uses exactly 10,000 gas const unsigned: UnsignedVmOp = { version: VMOP_VERSION, chain_id: params.chain_id, account, nonce, // the account's next nonce fee: { kind: 'Token', amount: estimate.path_b.amount }, max_gas: maxGas, action: { kind: 'AssetTransfer', asset: ksaAssetId(), to, amount }, }; // The node's rates are per KiB of the op's cost and of its size: measure the signed op, then sign the real fee. const size = encodeVmOp(signedVmop(unsigned, secretKey)).length; const fee = pathBFee(params, estimate.path_b, size, maxGas); const op = signedVmop({ ...unsigned, fee: { kind: 'Token', amount: fee } }, secretKey); const { op_id } = await rpc.submitOp(op); // RpcError -32010 or -32011 when the node refuses it return op_id; } ``` - **Nonce.** `getAccount` returns the account’s next nonce. A node queues up to 64 ops per account, so for a burst of ops you can count up from there. - **Fee.** A flat amount of KSA in base units, charged even when the op fails. `estimateFee` suggests `path_b.amount` for a plain transfer and `path_b.per_kib` per KiB of an op’s cost: its encoded size or its gas limit converted to bytes, whichever is larger. A node whose operator set a KSA price also returns `path_b.per_kib_data`, per KiB of the op’s encoded size alone. `pathBFee` gives the fee of an op from all three. The suggestion moves with recent blocks, and a signet node accepts 1 base unit. - **Gas.** A KSA transfer uses exactly 10,000 gas. A call costs 20,000 plus 1 per byte of the contract’s code plus 10,000 per attached asset plus what the method uses: see [Host functions and gas](https://ksana.network/docs/host-functions/). - **Refusals.** `submitOp` throws `RpcError` -32010 for an invalid op, such as a used nonce or a balance that cannot cover the fees. It throws -32011 when the node’s policy refuses the op, such as a fee below the node’s floor. When the node produces blocks, `submitOp` returns once its block template has taken the op, after at most 5 seconds. To call a contract, use the action `{ kind: 'Call', contract, method, args, funds }`, with `args` as described under [Call contracts](#call-contracts). Attached `funds` must be sorted by asset ID: pass them through `sortFunds`, then `checkFunds`. ### With a browser wallet ```typescript title="wallet.ts" import { KsanaRpcClient, SIGNET, UnisatAdapter, type UnsignedVmOp, VMOP_VERSION, type WalletAdapter, XverseAdapter, btcNetworkOf, encodeVmOp, fromHex, ksaAssetId, pathBFee, signVmopWithWallet, } from '@ksana/sdk'; const rpc = new KsanaRpcClient('https://signet.ksana.network/rpc', { timeoutMs: 30_000 }); /** Connects Unisat or Xverse, checks its network, and returns its Ksana account. */ export async function connect( kind: 'unisat' | 'xverse', ): Promise<{ wallet: WalletAdapter; address: string; account: Uint8Array }> { const wallet: WalletAdapter = kind === 'unisat' ? new UnisatAdapter() : new XverseAdapter(); const params = await rpc.getParams(SIGNET); // A tb1 address does not tell the signet from testnet: ask the wallet, which may not know. const network = await wallet.getNetwork?.(); if (network !== undefined && network.network !== btcNetworkOf(params)) { throw new Error(`switch the wallet to Bitcoin Signet (it is on ${network.name})`); } const { address, account } = await wallet.getAccount(); // throws unless the address is Taproot return { wallet, address, account: fromHex(account, 32) }; } /** Sends KSA on path B: the wallet signs a message, and no bitcoin moves. Returns the op's ID. */ export async function send( wallet: WalletAdapter, account: Uint8Array, to: Uint8Array, amount: bigint, ): Promise { const params = await rpc.getParams(SIGNET); const [{ nonce }, estimate] = await Promise.all([rpc.getAccount(account), rpc.estimateFee()]); const maxGas = 10_000n; const unsigned: UnsignedVmOp = { version: VMOP_VERSION, chain_id: params.chain_id, account, nonce, fee: { kind: 'Token', amount: estimate.path_b.amount }, max_gas: maxGas, action: { kind: 'AssetTransfer', asset: ksaAssetId(), to, amount }, }; // A wallet's signature encodes in at most 67 bytes: size the op without asking the wallet twice. const placeholder = { kind: 'Bip322Simple' as const, bytes: new Uint8Array(67) }; const size = encodeVmOp({ ...unsigned, sig: placeholder }).length; const fee = pathBFee(params, estimate.path_b, size, maxGas); const final: UnsignedVmOp = { ...unsigned, fee: { kind: 'Token', amount: fee } }; // The wallet shows a message to sign: the op's sighash in hex. const op = await signVmopWithWallet(final, wallet); return (await rpc.submitOp(op)).op_id; } ``` - **Adapters.** `UnisatAdapter` and `XverseAdapter` wrap the wallets’ injected providers and throw when the extension is missing. Both implement `WalletAdapter`, which you can implement for another wallet. - **Taproot only.** The wallet’s Taproot address is the Ksana account, and `getAccount` throws for any other address type. In Xverse, that is the Ordinals address. - **No bitcoin.** For path B the wallet signs a text message with BIP322, the op’s sighash in hex, so it needs no coins. - **Network.** A `tb1` address looks the same on the signet and on testnet, so ask the wallet with `getNetwork`, which may not know. In tests, `MockUnisatWallet` plays Unisat with a local key: set `globalThis.unisat = new MockUnisatWallet({ secretKey, network: 'signet' })` before you connect. The wallet examples on this page ran that way, with nothing submitted or broadcast. ## Follow an op ```typescript title="follow.ts" import type { KsanaRpcClient, OpStatus } from '@ksana/sdk'; /** Polls an op once a second until it is executed or final, or until `timeoutMs` passes. */ export async function waitFor( rpc: KsanaRpcClient, opId: Uint8Array, timeoutMs = 120_000, ): Promise { const deadline = Date.now() + timeoutMs; for (;;) { const status = await rpc.getOpStatus(opId); // RpcError -32004 while the node does not know it if (status.status !== 'pending' && status.status !== 'skipped') return status; if (Date.now() > deadline) throw new Error(`still ${status.status} after ${timeoutMs} ms`); await new Promise((resolve) => setTimeout(resolve, 1_000)); } } ``` | Status | Meaning | | --- | --- | | `pending` | in the node’s entry pool | | `fast_confirmed` | executed successfully in a main-chain block | | `failed` | included, but execution failed: the fee is charged, and `receipt.error` says why | | `skipped` | included only by merged blocks that could not execute it; not charged, and back in the pool | | `btc_final` | executed successfully, and its block is final | A failed op never becomes `btc_final`. This example follows the transfer of the [quickstart](https://ksana.network/docs/quickstart/#send-1-ksa), then reads its block’s settlement: ```typescript title="follow-demo.ts" import { KsanaRpcClient, fromHex } from '@ksana/sdk'; import { waitFor } from './follow.js'; const rpc = new KsanaRpcClient('https://signet.ksana.network/rpc', { timeoutMs: 30_000 }); const opId = fromHex('262b5d466a9f2fc69b2362c38352b635dce95d4385514ac994137891a8cf3dc9', 32); const status = await waitFor(rpc, opId); console.log(`${status.status} in block ${status.block?.height}, gas ${status.receipt?.gas_used}`); if (status.block !== null) { const s = await rpc.getSettlement(status.block.hash); const confirmations = s.confirmed?.confirmations ?? 0; console.log(`settlement ${s.status}, ${confirmations} confirmations`); console.log(`Bitcoin txid ${s.txid_rpc}`); console.log(`btc_final ${s.btc_final}`); } ``` ```output btc_final in block 27, gas 10000 settlement confirmed, 11 confirmations Bitcoin txid 5a4f1245b728011d71f732aab68fa34ccb5c6460fc5cc6166f9b7dfadb2f23d2 btc_final true ``` This run read the settlement the moment the op became `btc_final`, five Bitcoin blocks after the settlement’s sixth confirmation, so the count reads 11. The example passes the block’s hash to `getSettlement`, because a merged block has a settlement of its own, and `txid_rpc` is the Bitcoin transaction’s ID in the order explorers show. For a block with no settlement of its own, an empty block or one holding only path C operations, it throws `RpcError` -32004; [Confirmations](https://ksana.network/docs/confirmations/#reading-the-marks) reads the marks from a later block instead. A receipt’s `asset_changes` lists what the op did to built-in assets, in the order it did it, each an `AssetChange` told apart by its `kind` (the [RPC page](https://ksana.network/docs/rpc/#ksana_getopstatus) lists the kinds). It is `null` when the node did not record them: a receipt it stored before it did, or any receipt of a node from before. With the `status` of the example above, and `toHex` imported from `@ksana/sdk` too: ```typescript for (const change of status.receipt?.asset_changes ?? []) { if (change.kind === 'transfer' || change.kind === 'payout') { console.log(`${change.kind}: ${change.amount} to ${toHex(change.to)}`); } } ``` ## Watch new blocks ```typescript title="blocks.ts" import { subscribeBlocks, toHex } from '@ksana/sdk'; const sub = subscribeBlocks( 'wss://signet.ksana.network/rpc', (block) => { console.log(`block ${block.height} ${toHex(block.hash)}, ${block.entries} entries`); sub.close(); // one block is enough for this example }, { onError: (error) => console.error('subscription:', error.message) }, ); ``` ```output block 61 d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f, 0 entries ``` `subscribeBlocks` calls your function for each block the node connects to its main chain. It needs a global `WebSocket`, which browsers and Node.js 22 or later have; on Node.js 20, pass a WebSocket class in `options.WebSocket`. The subscription does not reconnect, and it does not report a closed connection. When the chain is idle, blocks come minutes apart, so silence does not prove the socket is alive: call `getChainInfo` now and then, and subscribe again when it shows blocks the socket missed. After a reorganization the new blocks arrive, and nothing marks the ones removed. ## Read accounts and assets ```typescript title="state.ts" import { KsanaRpcClient, equalBytes, formatOpPosition, ksaAssetId, parseAccount, toHex, } from '@ksana/sdk'; const rpc = new KsanaRpcClient('https://signet.ksana.network/rpc', { timeoutMs: 30_000 }); const address = 'tb1pklkarsaaegsk2dxgh4ug9tru6q6x63gge8emdeltt8fpxm6r7zwse04hlm'; const account = parseAccount(address, 'signet'); const info = await rpc.getAccount(account); const ksa = info.balances.find((b) => equalBytes(b.asset, ksaAssetId()))?.amount ?? 0n; console.log(`nonce ${info.nonce}, ${ksa} base units of KSA, at block ${info.at.height}`); // The account's ops, newest first: pass `next` as `before` for the next page const page = await rpc.getAccountOps(account, { limit: 3 }); for (const op of page.ops) console.log(`${op.status} at ${op.block.height}: ${toHex(op.op_id)}`); console.log('next', page.next === null ? null : formatOpPosition(page.next)); ``` ```output nonce 9, 6975669407 base units of KSA, at block 61 fast_confirmed at 39: 85aa965def12e9cc329dc120f9fcabf2ad165b70731917fc47158e0b87b42f0d btc_final at 38: 797d9dc411ae59e79ce0aa8a369ec151f9416f7afb18569c0181fe81ebecc2e0 btc_final at 37: 98db7cf37f05452b4f988a54bc3c53589cf44b41daf2c19883a7b02f64fed625 next 37:0:0 ``` - `getAccount` returns the next nonce and the balances of built-in assets that are not zero. Tokens that live in a contract’s storage are not among them: `getAccountAssets` lists them, as under [Use KS-20 and KS-721 tokens](#use-ks-20-and-ks-721-tokens). - `getAsset(id)` returns an asset’s name, symbol, decimals, supply and issuer, the capabilities its issuer holds and whether it is paused. KSA’s ID is `ksaAssetId()`, 32 zero bytes, and KSA has 8 decimals and no capabilities. - `getAssetStatus(asset, account)` returns the account’s flags for the asset and whether the asset’s rules let it send and receive the asset now. Check it before sending an asset whose `capabilities` are not empty. - `getBlock(id)` takes `'latest'`, a height or a hash, and `entries[i]` pairs with `receipts[i]`. - `getAccountOps` and `getLatestOps` list ops newest first, at most 500 a page. Pass `page.next` as `before` until it is `null`. ## Call contracts Contracts take and return raw bytes, by convention in Borsh: a method’s arguments are a tuple encoded back to back, one argument is encoded as itself, and none is empty bytes. The SDK exports `u32le`, `u64le` and the `ByteReader` class, but nothing for `u128`, strings or contract IDs, so add these helpers: ```typescript title="borsh.ts" import { type ByteReader, concatBytes, sha256, u32le, u64le, utf8 } from '@ksana/sdk'; /** A deployed contract's ID: sha256(deployer, the deploy op's nonce as u64 LE, sha256(code)). */ export function contractId(deployer: Uint8Array, nonce: bigint, code: Uint8Array): Uint8Array { return sha256(concatBytes(deployer, u64le(nonce), sha256(code))); } /** Borsh u128: 16 bytes, little-endian. */ export function u128le(value: bigint): Uint8Array { if (value < 0n || value >= 1n << 128n) throw new RangeError(`not a u128: ${value}`); const out = new Uint8Array(16); for (let i = 0; i < 16; i++) out[i] = Number((value >> BigInt(8 * i)) & 0xffn); return out; } /** Borsh String: the UTF-8 length as u32 LE, then the bytes. */ export function borshString(text: string): Uint8Array { const bytes = utf8(text); return concatBytes(u32le(bytes.length), bytes); } /** Borsh Vec: the length as u32 LE, then the bytes (not the SDK's varBytes). */ export function borshBytes(bytes: Uint8Array): Uint8Array { return concatBytes(u32le(bytes.length), bytes); } /** Reads a Borsh u128. */ export function readU128(reader: ByteReader): bigint { const bytes = reader.read(16); let value = 0n; for (let i = 15; i >= 0; i--) value = (value << 8n) | BigInt(bytes[i] ?? 0); return value; } ``` `contractId` gives a deployed contract’s ID, which the deploy’s receipt does not return. For the tutorial’s token, `contractId(account, 0n, code)` gives `6569e81e…0c329658`, the ID the token has on the signet. Watch out for the SDK’s own `varBytes`: it writes Bitcoin’s length prefix, not Borsh’s. `call` runs one method on the latest state, with no key, no fee and nothing on chain. This example reads the tutorial’s pool and simulates a swap: ```typescript title="call.ts" import { ByteReader, KsanaRpcClient, type Receipt, concatBytes, fromHex, ksaAssetId, } from '@ksana/sdk'; import { readU128, u128le } from './borsh.js'; const rpc = new KsanaRpcClient('https://signet.ksana.network/rpc', { timeoutMs: 30_000 }); const pool = fromHex('eb5ca55289984d64598a12303a0638ee9dd6edc50f4bebe6d43a7a46121fc745', 32); const me = fromHex('b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d', 32); /** The output of a successful call; a revert or any other failure throws. */ function output(receipt: Receipt): ByteReader { if (!receipt.success) throw new Error(receipt.error ?? 'the call failed'); return new ByteReader(receipt.output, 'output'); } // reserves() -> (u128, u128): no arguments, so empty bytes const noArgs = new Uint8Array(0); const reserves = output(await rpc.call({ contract: pool, method: 'reserves', args: noArgs })); const [tut, ksa] = [readU128(reserves), readU128(reserves)]; reserves.finish(); // throws if bytes are left over console.log(`reserves: ${tut} TUT, ${ksa} KSA (base units)`); // swap(id_in, amount_in, min_out) -> u128, simulated as `me` with 1 KSA attached const amountIn = 100_000_000n; const quote = await rpc.call({ contract: pool, method: 'swap', args: concatBytes(ksaAssetId(), u128le(amountIn), u128le(1n)), funds: [{ asset: ksaAssetId(), amount: amountIn }], caller: me, }); console.log(`1 KSA buys ${readU128(output(quote))} TUT base units; gas ${quote.gas_used}`); ``` ```output reserves: 4952249151934 TUT, 2524330584 KSA (base units) 1 KSA buys 188160627188 TUT base units; gas 169247 ``` - **Caller.** It defaults to 32 zero bytes. Set `caller` when the method reads its caller, or when you attach `funds`, which the simulation moves out of the caller’s balance. - **Gas.** `gas_used` is what the same call uses in an op: the tutorial’s real swap used 169,247 gas too. A failed call reports its `max_gas`, which defaults to the block limit of 100,000,000. - **Failures.** A revert or a missing contract gives `success: false` and the reason in `error`, such as `revert: unknown method`. - **Load.** A node runs at most 4 calls at once and answers a fifth with error -32009. ## Use KS-20 and KS-721 tokens A contract that follows a token standard, KS-20 for fungible tokens or KS-721 for NFTs, says so in its view `standards()`. The SDK speaks both [standards](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/STANDARDS.md): it reads their views with `call`, builds their operations as actions and decodes their events. ```typescript title="tokens.ts" import { type KsanaRpcClient, type Receipt, decodeStandardEvent, equalBytes, ks20BalanceOf, ks20Transfer, readKs20, } from '@ksana/sdk'; /** What a wallet shows of a KS-20 token, or null for a contract that does not declare KS-20. */ export async function tokenRow(rpc: KsanaRpcClient, token: Uint8Array, holder: Uint8Array) { const info = await readKs20(rpc, token); // standards(), then metadata(), total_supply() and capabilities() if (info === null) return null; const balance = await ks20BalanceOf(rpc, token, holder); // in base units return { ...info, balance }; } /** The action that sends `amount` base units of the token: sign it into a VmOp as on path B. */ export function sendToken(token: Uint8Array, to: Uint8Array, amount: bigint) { return ks20Transfer(token, to, amount); } /** The token's own events in an op's receipt, read by its declaration. */ export function tokenEvents(receipt: Receipt, token: Uint8Array, standards: string[]) { return receipt.events .filter((event) => equalBytes(event.contract, token)) .flatMap((event) => decodeStandardEvent(standards, event.data) ?? []); } ``` - **Discovery.** `readStandards` returns a contract’s declaration, the standard first and then its extensions, such as `KS-20-burnable` or `KS-721-enumerable`, or `null` for a contract that declares none. `readKs20` and `readKs721` read the rest one view at a time, since a node runs at most 4 calls at once. - **Capabilities.** `capabilities` lists what the token’s rules let someone do now, in this order: `mint`, `freeze`, `allowlist`, `pause`, `clawback`, `fee` and `upgrade`. A token with `fee` gives the recipient less than the amount sent, and the sender’s balance drops by exactly the amount. - **Operations.** The builders return a `Call` action: `ks20Transfer`, `ks20TransferFrom`, `ks20Approve`, `ks20TransferAndCall` and the others, and `ks721Transfer`, `ks721SetOperator` and the others for NFTs. They refuse a zero amount and the zero account or the token itself as recipient, which every token would refuse on chain after charging the op’s fee. `ks20TransferAndCall` moves tokens into a contract and calls that contract in the same op. `assetTransfer` sends either kind of asset, a built-in one or a KS-20 token, named by an `AssetRef`. - **Approvals.** `ks20Approve(token, spender, amount, expiresAt)` sets an allowance that counts until the block timestamp reaches `expiresAt`, in seconds, or for good when it is `null`. Approve the amount you need, with an expiry; `0n` revokes the allowance. - **Refusals.** A view the contract refuses throws `StandardCallError`, whose `reason` is the revert reason: one of the standards’ fixed English phrases, or `rejected: …` for the token’s own rules. - **NFT IDs.** KS-721 token IDs are 32 bytes. `ks721TokenId(7n)` is the ID of serial number 7, and `ks721Serial` reads the number back, or gives `null` for an ID that holds a hash. A node indexes the standards’ events, and six methods read its index: `getAccountAssets` lists everything an account holds, `getNfts` its NFTs and `getApprovals` the approvals it gave; `getToken`, `getTokenHolders` and `getContract` describe a contract. The lists come a page at a time: pass `after: page.next` until `next` is `null`. ```typescript title="assets.ts" import type { AccountAsset, KsanaRpcClient } from '@ksana/sdk'; /** Everything an account holds by the node’s index: built-in assets, then KS-20 tokens and KS-721 collections. */ export async function allAssets(rpc: KsanaRpcClient, account: Uint8Array): Promise { const assets: AccountAsset[] = []; let after: string | null = null; do { const page = await rpc.getAccountAssets(account, { after, limit: 500 }); assets.push(...page.assets); after = page.next; } while (after !== null); return assets; } ``` - **What and how much.** The index tells what an account holds, and the token’s views tell how much: read `ks20BalanceOf` before you send. The index lists an allowance as it was approved, and `ks20Allowance` gives what is left of it. - **Kinds.** An `AccountAsset` is a built-in asset (`kind: 'asset'`), a KS-20 token (`'token'`, with its `balance`) or a KS-721 collection (`'nft'`, with the `count` of NFTs held). An approval is an `allowance`, an `operator` or the approval of one NFT (`'token'`); its `expires_at` is a block timestamp in seconds, or `null`. - **Tokens.** `getToken` gives a token’s standard, metadata, supply and number of holders, and `irregular` is `true` once the index had to leave out one of its events. It and `getTokenHolders` throw `RpcError` -32004 for a contract that declared neither standard. - **Older nodes.** A node without the index throws `RpcError` -32601 (`RPC_ERROR_CODES.METHOD_NOT_FOUND`). ## Send an op on path C A path C op travels in a Bitcoin transaction that your wallet signs and pays for, and it needs no KSA. Producers must include it once the transaction has 2 confirmations on the signet, 5 on mainnet. [Operations and fees](https://ksana.network/docs/submitting-ops/) explains the path, and this function builds the transaction: ```typescript title="pathc.ts" import { type KsanaRpcClient, type Params, type UnsignedVmOp, type Utxo, VMOP_VERSION, type WalletAdapter, buildNativeTx, extractTransaction, ksaAssetId, nativeFirstInput, opId, signVmopWithWallet, } from '@ksana/sdk'; /** * Builds a path C KSA transfer: the op rides in a Bitcoin transaction that the wallet signs and * pays for. Returns the raw transaction to broadcast and the op's ID. */ export async function nativeTransfer( rpc: KsanaRpcClient, params: Params, wallet: WalletAdapter, account: Uint8Array, utxos: Utxo[], // the account's confirmed coins to: Uint8Array, amount: bigint, feeRate: number, // sat/vB ): Promise<{ raw: Uint8Array; opId: Uint8Array }> { const first = utxos[0]; if (first === undefined) throw new Error('no coins to pay the Bitcoin fee'); const unsigned: UnsignedVmOp = { version: VMOP_VERSION, chain_id: params.chain_id, account, nonce: (await rpc.getAccount(account)).nonce, // plus your path C ops still waiting fee: { kind: 'BtcNative' }, // no KSA fee: the Bitcoin transaction pays max_gas: 10_000n, // at most params.native_max_gas action: { kind: 'AssetTransfer', asset: ksaAssetId(), to, amount }, }; // The signature covers the transaction's first input, so choose that coin before signing. const op = await signVmopWithWallet(unsigned, wallet, { firstInput: nativeFirstInput(first) }); const draft = buildNativeTx({ op, utxos, changeScript: first.script, feeRate, params }); const signed = await wallet.signPsbt(draft.psbt, draft.inputs.map((_, index) => ({ index }))); return { raw: extractTransaction(signed), opId: opId(op) }; } ``` - **Coins.** The SDK does not list coins: get the account’s confirmed coins from your own bitcoind or an Esplora API. A `Utxo` holds the txid in internal byte order (`txidFromRpc` converts an explorer’s), `vout`, `value` in sats, `script` and the wallet’s `tapInternalKey`. For the account’s own address the script is `p2trScriptFromOutputKey(account)`. - **The transaction.** Output 0 carries the op in a KSN1 `OP_RETURN`, then come any `payments`, then the change. Only Taproot key-path and P2WPKH coins can be spent. - **Broadcast.** Send `toHex(raw)` with bitcoind’s `sendrawtransaction`. Bitcoin Core 30 and later relay the large `OP_RETURN` by default; older versions need `-datacarriersize=100000`. - **Tracking.** `getOpStatus` answers -32004 until a block includes the op, and `getAccount` does not count path C ops still waiting. - **Gas.** `max_gas` can be at most 1,000,000, `params.native_max_gas`. With a key instead of a wallet, sign the op with `signedVmop(unsigned, secretKey, undefined, nativeFirstInput(first))`, and the transaction with `extractTransaction(signNativeTx(draft.psbt, secretKey))`. ## Top up with KSA A top-up buys KSA with bitcoin from a seller’s lock in a [`ksa-exchange` contract](https://ksana.network/docs/example-contracts/#ksa-exchange). One Bitcoin transaction pays the lock’s script and carries a path C op that calls `claim`: ```typescript title="topup.ts" import { type KsanaRpcClient, SIGNET, type Utxo, type WalletAdapter, buildTopUp, extractTransaction, fromHex, getLock, p2trScriptFromOutputKey, quoteTopUp, } from '@ksana/sdk'; /** * Buys all the KSA that lock `lockId` of a ksa-exchange contract still holds, for the wallet's * own account. Returns the raw transaction to broadcast, the claim op's ID, and the Bitcoin * height the transaction must confirm by. */ export async function topUp( rpc: KsanaRpcClient, wallet: WalletAdapter, utxos: Utxo[], // the wallet's confirmed coins exchange: Uint8Array, lockId: bigint, btcHeight: number, // the Bitcoin tip, for the expiry check feeRate: number, // sat/vB ): Promise<{ raw: Uint8Array; opId: Uint8Array; payBy: number }> { const params = await rpc.getParams(SIGNET); const buyer = fromHex((await wallet.getAccount()).account, 32); const lock = await getLock(rpc, exchange, lockId); const { satsForAll } = quoteTopUp(lock, 0n); // the sats that buy everything still locked const draft = buildTopUp({ exchange, lockId, lock, beneficiary: buyer, // refused unless it is the lock's beneficiary sats: satsForAll, currentBtcHeight: btcHeight, utxos, changeScript: p2trScriptFromOutputKey(buyer), feeRate, params, }); const signed = await wallet.signPsbt(draft.psbt, draft.inputs.map((_, index) => ({ index }))); return { raw: extractTransaction(signed), opId: draft.opId, payBy: draft.payBy }; } ``` - `checkExchangeCode(rpc, exchange, codeHash)` throws when the node gives another code hash for the exchange contract than the one you reviewed. Call it first when the contract ID came from someone else. It asks the node, so it guards against a wrong contract and not against a node that lies. - `getLock` reads the lock. `quoteTopUp(lock, sats)` gives the KSA that `sats` buy, and `satsForAll`, the sats that buy all of it. - `buildTopUp` refuses a lock whose beneficiary is not the buyer, a lock that is not open, and a lock that expires within 3 Bitcoin blocks (`expiryMargin`). It also refuses an amount other than `satsForAll`, unless you pass `allowPartial` or `allowOverpay`. - A fresh one-time key signs the claim op with nonce 0, so it uses none of your account’s nonces. - The transaction must confirm by Bitcoin height `payBy`. After that, the seller’s `release` may run first. ## Query the indexer ```typescript title="indexer.ts" import { IndexerRpcClient, KsanaRpcClient, equalBytes } from '@ksana/sdk'; const rpc = new KsanaRpcClient('https://signet.ksana.network/rpc', { timeoutMs: 30_000 }); const indexer = new IndexerRpcClient('https://signet.ksana.network/indexer', { timeoutMs: 30_000, }); // The indexer rebuilds the state from Bitcoin alone; compare its state root with the node's block. const status = await indexer.status(); const { header } = await rpc.getBlock(status.height); console.log(`indexer at ${status.height}, Bitcoin ${status.btc_height}, halted ${status.halted}`); console.log('same state root as the node:', equalBytes(status.state_root, header.state_root)); ``` ```output indexer at 51, Bitcoin 327291, halted null same state root as the node: true ``` The indexer rebuilds Ksana’s state from Bitcoin alone, so a state root that matches the node’s shows that the node’s state follows from what is on Bitcoin. It trails the node, because it executes a block only once the block has 2 confirmations or is final. `stateRoot(id)` gives the root of one block it has verified, and [Run an indexer](https://ksana.network/docs/run-an-indexer/) explains the rest. **Calls from web pages.** On the public signet, only `https://signet.ksana.network/rpc` answers pages from other origins. `https://signet.ksana.network/indexer`, `https://signet.ksana.network/btc` and `https://signet.ksana.network/faucet` answer servers and the signet’s own page, so reach them through your own server. ## Handle errors ```typescript title="errors.ts" import { ChainMismatchError, KsanaRpcClient, MAINNET, RPC_ERROR_CODES, RpcError, } from '@ksana/sdk'; const rpc = new KsanaRpcClient('https://signet.ksana.network/rpc', { timeoutMs: 30_000 }); try { await rpc.getOpStatus(new Uint8Array(32)); // no op has this ID } catch (e) { if (!(e instanceof RpcError) || e.code !== RPC_ERROR_CODES.NOT_FOUND) throw e; console.log(e.code, e.message); } try { await rpc.getParams(MAINNET); // the node is on the signet } catch (e) { if (!(e instanceof ChainMismatchError)) throw e; console.log(e.chainId, e.expected, e.message.split(':')[0]); } ``` ```output -32004 ksana_getOpStatus: unknown op 1002 1000 the node is on signet (chain ID 1002), not mainnet (chain ID 1000) ``` | Error | When | | --- | --- | | `RpcError` | the node answered with a JSON-RPC error: `code` holds its code, and the message starts with the method | | `RpcTransportError` | the request failed or timed out, or the answer could not be parsed | | `ChainMismatchError` | the node is on another network than the one you passed | | `StandardCallError` | a contract refused a view of a token standard: `reason` holds its revert reason | | `Error`, `RangeError`, `TypeError` | a builder refused its input, before anything was sent | `RPC_ERROR_CODES` names -32601, -32602, -32603, -32004, -32010 and -32011. It does not name -32009, the answer to a fifth concurrent `call`, so compare that code directly. The [JSON-RPC API](https://ksana.network/docs/rpc/#errors) explains every code. --- # JSON-RPC API URL: https://ksana.network/docs/rpc/ > Every method of a Ksana node’s JSON-RPC interface and of the indexer’s, with the JSON conventions, the errors, and real calls to the public signet. A Ksana node answers JSON-RPC 2.0 over HTTP and WebSocket on one port. The indexer answers two methods of its own. Wallets, apps, [ksana-cli](https://ksana.network/docs/cli/) and the [TypeScript SDK](https://ksana.network/docs/sdk/) all use this interface. Every example on this page is a real call to the public signet, made on 21 October 2026. Mainnet has not launched. The receipts show `asset_changes` as this version of the node records them; for these operations, which the signet’s nodes executed before they recorded the changes, the nodes answer `null`. ## Endpoints | Service | Default address | Public signet | | --- | --- | --- | | Node, HTTP | `127.0.0.1:8545` (`ksana-node --rpc-addr`) | `https://signet.ksana.network/rpc` | | Node, WebSocket | the same port | `wss://signet.ksana.network/rpc` | | Indexer, HTTP | `127.0.0.1:8546` (`ksana-indexer --rpc-addr`) | `https://signet.ksana.network/indexer` | Calls take positional parameters: `params` is a JSON array, in the order the sections below list them. Send `content-type: application/json`. ### Calls from web pages Browsers call another origin only when the server allows it (CORS). A node allows none by default; start it with `--rpc-cors '*'` to allow every origin, or with a comma-separated list of origins. Command-line tools and servers are not affected. On the public signet, the node’s RPC allows every origin and the indexer allows none. A preflight request shows the difference: ```sh curl -sS -i -X OPTIONS https://signet.ksana.network/rpc -H 'origin: https://example.org' \ -H 'access-control-request-method: POST' -H 'access-control-request-headers: content-type' \ | grep -i -E '^(HTTP/2|access-control)' ``` ```output HTTP/2 200 access-control-allow-headers: content-type access-control-allow-methods: POST,GET,OPTIONS access-control-allow-origin: * ``` The same request to `https://signet.ksana.network/indexer` gets `HTTP/2 405`. Call the indexer from a server or a command line. ### Limits The node and the indexer apply the same limits to every client. They are local policy, not consensus rules, and the server answers what passes one with an error of its own: | Limit | Value | Beyond it | | --- | --- | --- | | Calls in one batch | 64 | The whole batch is refused with one error, `-32010`, whose `id` is `null`; none of its calls runs | | Request body, or one WebSocket message | 1 MiB | `-32007`, with HTTP status 413 | | Response | 10 MiB | `-32008`; for a batch, `-32011` with `id` `null` | | Connections at once, HTTP and WebSocket together | 100 | HTTP status 429 | | Subscriptions on one WebSocket connection | 16 | `-32006` | A batch refused for its size has run nothing: send its calls again in smaller batches. `ksana_submitOp` answers `-32010` and `-32011` too, when the node refuses an operation; an error that answers a whole batch has `id` `null`, one that answers a call has the call's `id`. ## A first call Ask the node for its chain tip: ```sh curl -sS https://signet.ksana.network/rpc -H 'content-type: application/json' \ --data '{"jsonrpc":"2.0","id":1,"method":"ksana_getChainInfo","params":[]}' | jq ``` ```output { "jsonrpc": "2.0", "id": 1, "result": { "chain_id": 1002, "tip": { "height": "61", "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f" }, "daa_score": "1860", "protocol_version": 2, "next_upgrade": null, "max_known_version": 2, "finalized": { "height": "38", "hash": "ab3fe1dcb95f0d76cd171210567f571fcd81cc8f7559d68da7dd38348eec7cf2" } } } ``` The other examples use a small shell function and print only `result`. It needs `curl` and `jq`: ```sh NODE=https://signet.ksana.network/rpc INDEXER=https://signet.ksana.network/indexer rpc() { # rpc [params as a JSON array] curl -sS "$1" -H 'content-type: application/json' \ --data "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"$2\",\"params\":${3:-[]}}" } ACCOUNT=b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d KSA=0000000000000000000000000000000000000000000000000000000000000000 ``` `ACCOUNT` is the account of the [token and pool tutorial](https://ksana.network/docs/token-and-pool/), and `KSA` is the asset ID of KSA. ## JSON conventions - **Bytes** (hashes, accounts, asset and contract IDs, Borsh encodings) are lowercase hex strings without `0x`. - **`u64` and `u128` values** (heights, nonces, amounts, gas) are decimal strings, because JavaScript numbers hold only 53 bits. `u8` and `u32` values (decimals, BTC heights, counts) are JSON numbers. - **Block identifiers** are `"latest"`, a decimal height such as `"33"`, or a 64-digit block hash. A height names a block of the main chain; a hash can name any block the node knows. - **Bitcoin IDs** (`txid`, BTC block hashes) are in Bitcoin’s internal byte order, the reverse of what explorers show. Fields that end in `_rpc` give the explorer order. - **Protocol types** (block headers, entries, VmOps) use the JSON form of the repository’s test vectors: an enum is an object with one key, its variant, such as `{"Token": {"amount": "1"}}`. ## Methods at a glance | Method | Parameters | Result | | --- | --- | --- | | [`ksana_getChainInfo`](#ksana_getchaininfo) | none | chain ID, tip, DAA score, versions, finalized tip | | [`ksana_estimateFee`](#ksana_estimatefee) | none | suggested path B fee and the node’s BTC fee rate | | [`ksana_getAccount`](#ksana_getaccount) | account | nonce, balances, locked fees | | [`ksana_getAsset`](#ksana_getasset) | asset ID | name, symbol, decimals, total supply, issuer, capabilities | | [`ksana_getAssetStatus`](#ksana_getassetstatus) | asset ID, account | the account’s flags, whether it can send and receive the asset | | [`ksana_getContract`](#ksana_getcontract) | contract ID | code hash, deployer, declared standards | | [`ksana_getAccountAssets`](#ksana_getaccountassets) | account, `after`, `limit` | a page of an account’s assets, tokens and NFTs | | [`ksana_getToken`](#ksana_gettoken) | contract ID | a token’s standard, metadata, supply and holder count | | [`ksana_getTokenHolders`](#ksana_gettokenholders) | contract ID, `after`, `limit` | a page of a token’s holders, the largest first | | [`ksana_getNfts`](#ksana_getnfts) | account, `contract`, `after`, `limit` | a page of an account’s NFTs | | [`ksana_getApprovals`](#ksana_getapprovals) | account, `after`, `limit` | a page of the approvals an account gave | | [`ksana_submitOp`](#ksana_submitop) | VmOp (Borsh, hex) | op ID | | [`ksana_getOpStatus`](#ksana_getopstatus) | op ID | status, block, receipt | | [`ksana_getAccountOps`](#ksana_getaccountops) | account, `before`, `limit` | a page of an account’s ops | | [`ksana_getLatestOps`](#ksana_getlatestops) | `before`, `limit` | a page of the chain’s ops | | [`ksana_getBlock`](#ksana_getblock) | block identifier | header, entries, receipts | | [`ksana_getSettlement`](#ksana_getsettlement) | block identifier | the settlement and its Bitcoin status | | [`ksana_call`](#ksana_call) | call request | receipt of a read-only call | | [`ksana_subscribeBlocks`](#ksana_subscribeblocks) | none (WebSocket) | a notification per new block | | [`indexer_status`](#indexer_status) | none | the indexer’s verified tip | | [`indexer_stateRoot`](#indexer_stateroot) | block identifier | a verified block’s state root | ## Chain and fees ### `ksana_getChainInfo` No parameters. The result, shown in [A first call](#a-first-call): | Field | Meaning | | --- | --- | | `chain_id` | 1002 on the signet, 1001 on devnet, 1000 on mainnet | | `tip` | the main chain’s tip, `{ "height", "hash" }` | | `daa_score` | the tip’s DAA score; each block adds its weight (an empty block weighs more) | | `protocol_version` | the tip’s block header version | | `next_upgrade` | the next scheduled upgrade, `{ "version", "daa_score" }`, or `null` | | `max_known_version` | the highest protocol version this node’s software supports | | `finalized` | the BTC-final tip: the newest block decided final at a Bitcoin block that now has 6 confirmations; the main chain passes through it, and only a Bitcoin reorganization of at least 6 blocks can take it back | When the network’s `protocol_version` passes `max_known_version`, the node’s software needs an upgrade. Before any block is final, `finalized` is the genesis block. ### `ksana_estimateFee` No parameters. It suggests fees; it does not change what the node accepts. ```sh rpc $NODE ksana_estimateFee | jq .result ``` ```output { "feerate_sat_vb": "2", "path_b": { "amount": "1", "per_kib": "4" }, "at": { "height": "61", "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f" } } ``` - `feerate_sat_vb` is the fee rate, in sat/vB, at which this node pays for its settlements now. Use it as a reference for path C transactions and top-ups. - `path_b.per_kib` is a suggested fee rate for path B: base units of KSA per KiB of cost. The cost of an op is the larger of its encoded size and its `max_gas` converted to bytes (`max_gas × 81,920 / 100,000,000`). The node takes the median, over its last 20 main-chain blocks, of each block’s lowest path B fee rate, and never goes below its own `--min-fee-per-kib`. - `path_b.per_kib_data` is present only on a node run with `--ksa-price-sat`: base units of KSA per KiB of the op’s encoded size, whatever its `max_gas`. It is the KSA worth 128 vB at `feerate_sat_vb` and the operator’s price, which is what the node’s producer asks for carrying the op’s bytes to Bitcoin. When the field is absent, take it as 0. - `path_b.amount` is the suggested fee of an ordinary KSA transfer: the larger of its cost at `per_kib` and its size at `per_kib_data`, never below the node’s `--min-token-fee`. For another op, take the larger of its cost multiplied by `per_kib` and its size multiplied by `per_kib_data`, each divided by 1,024 and rounded up, and not less than `amount`. - `at` is the tip the estimate was read at. [Operations and fees](https://ksana.network/docs/submitting-ops/) explains the fee rules. ## Accounts and assets ### `ksana_getAccount` Parameter: the account, as 64 hex digits (the Taproot output key, not the `tb1p` address). ```sh rpc $NODE ksana_getAccount "[\"$ACCOUNT\"]" | jq .result ``` ```output { "account": "b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d", "nonce": "9", "balances": [ { "asset": "0000000000000000000000000000000000000000000000000000000000000000", "amount": "6975669407" } ], "locked_fees": [], "at": { "height": "61", "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f" } } ``` - `nonce` is the account’s next nonce on the main chain. Ops still waiting in the entry pool are not counted. - `balances` lists the available balance of each built-in asset, in base units. A token kept in a contract’s storage, such as the `token` example, does not appear here: [`ksana_getAccountAssets`](#ksana_getaccountassets) lists the KS-20 tokens and KS-721 NFTs an account holds, and the contract answers how much. - `locked_fees` lists what the account is owed by blocks that are not unlocked yet, one entry per block, `[{ "block_hash", "amount" }]`: its reward and path B fees as the block’s producer, its part as the block’s carrier, and the block share for the block share account. It is empty for an account owed nothing. - `at` is the block the answer was read at. ### `ksana_getAsset` Parameter: the asset ID. KSA’s ID is 64 zeros. ```sh rpc $NODE ksana_getAsset "[\"$KSA\"]" | jq .result ``` ```output { "asset": "0000000000000000000000000000000000000000000000000000000000000000", "name": "KSA", "symbol": "KSA", "decimals": 8, "total_supply": "11001412730000000", "issuer": "0000000000000000000000000000000000000000000000000000000000000000", "capabilities": [], "paused": false, "at": { "height": "61", "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f" } } ``` `total_supply` is in base units: the genesis allocation plus the block rewards issued so far, minus burns. `issuer` is the contract that issued the asset, or zeros for KSA. An unknown asset returns `-32004`. `capabilities` lists what the issuing contract can still do to the asset, in the order `mint`, `freeze`, `allowlist`, `pause`: issue more, freeze an account, admit only the accounts it allows, pause every account but its own. It is empty for KSA and for an asset with a fixed supply that nobody can stop. Capabilities are only ever given up, and none moves a balance. `paused` is `true` while the issuing contract has paused the asset. [Host functions](https://ksana.network/docs/host-functions/#assets) explains the rules. ### `ksana_getAssetStatus` Parameters: the asset ID and the account. ```sh rpc $NODE ksana_getAssetStatus "[\"$KSA\", \"$ACCOUNT\"]" | jq .result ``` ```output { "asset": "0000000000000000000000000000000000000000000000000000000000000000", "account": "b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d", "status": [], "can_send": true, "can_receive": true, "at": { "height": "61", "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f" } } ``` - `status` lists the account’s flags for the asset, `frozen` and `allowed`. A flag counts only while the asset still has the matching capability. - `can_send` is whether the asset’s rules let the account send it now: it is not frozen, it is allowed when the asset has an allowlist, and the asset is not paused, unless the account is the issuing contract. Its balance is not considered. - `can_receive` is whether the rules let the account receive the asset now. - Check both before sending an asset with capabilities: an op the rules refuse still pays its fee. An unknown asset returns `-32004`. ## Tokens and NFTs A node indexes the events of KS-20 tokens and KS-721 collections, the contracts that follow the [token standards](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/STANDARDS.md), from the receipts of the operations its main chain executes. The methods of this section read that index. It is the node’s own bookkeeping, not part of consensus, and the node keeps it in step with its main chain, reorganizations included. - **What counts.** A contract’s first `standards` event is its declaration, and from then on the index counts the events of the standard it names first. An event that breaks the standard, such as a transfer of more than the sender holds by the token’s own events, is left out, and the token is marked `irregular`. - **The index and the contract.** The index tells what an account holds; the contract tells how much. Read `balance_of`, `allowance` or `owner_of` with [`ksana_call`](#ksana_call) before you act on an amount. An allowance is listed as its latest `approve` event set it: spending it emits no new event, so `amount` stays what was approved while the token’s `allowance` gives what is left. Approvals stay listed after they expire, until a new event changes them. - **Pages.** Pass the previous page’s `next` as `after` to continue, and `null` (or nothing) for the first page. `limit` is 1 to 500, 50 by default, and `next` is `null` at the end. `at` is the tip the page was read at; an item that moved between two pages, such as a holder whose balance changed, can be missed or listed twice. - **Older nodes.** A node from before the index, or one whose index is not built, returns `-32601`, as it does for the op listings. A malformed ID or `after`, or a `limit` out of range, returns `-32602`. ### `ksana_getContract` Parameter: a contract ID. It answers for any contract, standard or not: | Field | Meaning | | --- | --- | | `contract` | the contract ID | | `code_hash` | the SHA-256 of the contract’s code: compare it with a known build | | `deployer` | the account that deployed it | | `standards` | its declaration, the standard first and then its extensions, such as `["KS-20", "KS-20-burnable"]`; empty when it declared nothing | | `declared` | the [position](#ksana_getaccountops) of the operation that made the declaration, or `null` | | `at` | the block the answer was read at | An ID that is not a contract returns `-32004`. A token or a collection that keeps its standard declares itself in its `init`, so `declared` is the position of its deployment, the op whose events also hold its first `metadata`. [`ksana_getAccountOps`](#ksana_getaccountops) never lists a deployment under the contract it deploys: to read the deployment, call [`ksana_getLatestOps`](#ksana_getlatestops) with `limit` 1 and `before` one entry past it (for `"412:1:3"`, pass `"412:1:4"`). ### `ksana_getAccountAssets` Parameters: `account`, `after` (optional), `limit` (optional). Everything the account holds, in one list: its built-in assets by asset ID, then its KS-20 tokens and KS-721 collections by contract ID. Each item has a `kind`: | `kind` | Fields | Meaning | | --- | --- | --- | | `asset` | `asset`, `balance` | a built-in asset, with the balance [`ksana_getAccount`](#ksana_getaccount) shows | | `token` | `contract`, `balance` | a KS-20 token, with the balance its events add up to | | `nft` | `contract`, `count` | a KS-721 collection, with how many of its NFTs the account holds | Amounts are base units, in decimal strings. A token or a collection is listed while the account holds some of it. ### `ksana_getToken` Parameter: the contract ID of a token or a collection. | Field | Meaning | | --- | --- | | `contract` | the contract ID | | `standard` | `KS-20` or `KS-721` | | `extensions` | the extensions it declared, such as `KS-20-mintable` | | `name`, `symbol` | from its latest `metadata` event, or `null` before one | | `decimals` | a token’s decimals, a number; `null` for a collection | | `supply` | the token’s supply in base units, or how many NFTs of the collection exist | | `holders` | how many accounts hold some | | `declared` | the position of the operation that made its declaration | | `irregular` | `true` once the index left out one of its events: its balances may then differ from what the contract says | | `at` | the block the answer was read at | A contract that declared neither standard, or an ID that is not a contract, returns `-32004`. ### `ksana_getTokenHolders` Parameters: the contract ID, `after` (optional), `limit` (optional). The holders of a token or a collection, the largest first, each `{ "account", "balance" }`; for a collection, `balance` is a number of NFTs. Holders with the same balance come by account, the highest first. A contract `ksana_getToken` does not know returns `-32004`. ### `ksana_getNfts` Parameters: `account`, `contract` (optional), `after` (optional), `limit` (optional). The NFTs the account holds, each `{ "contract", "token_id" }`, by collection and then token ID; with `contract`, only that collection’s. A token ID is 32 bytes, and the [SDK](https://ksana.network/docs/sdk/#use-ks-20-and-ks-721-tokens) turns serial numbers into IDs and back. ### `ksana_getApprovals` Parameters: `account`, `after` (optional), `limit` (optional). The approvals the account gave, by contract and then kind: | `kind` | Fields | Meaning | | --- | --- | --- | | `allowance` | `contract`, `spender`, `amount`, `expires_at` | a KS-20 allowance, as its latest `approve` event set it | | `operator` | `contract`, `operator`, `expires_at` | a KS-721 operator, who may move all of the account’s NFTs in the collection | | `token` | `contract`, `token_id`, `spender` | the account approved to move one NFT; the approval goes when the NFT changes owner | `expires_at` is a block timestamp in seconds, as a decimal string, from which the approval no longer counts, or `null` when it has no end. To revoke an approval, send the standard’s call that clears it: `approve` with an amount of 0 for an allowance, `set_operator` with `approved` false for an operator, `approve` with no spender for one NFT. ## Operations ### `ksana_submitOp` Parameter: a path B VmOp with its whole signature, Borsh-encoded, in hex. Result: `{ "op_id" }`, the hash of the op with half its signature, which is how a block holds it. The node checks the op against the consensus rules (version, chain ID, size, signature, a nonce not below the account’s) and against its own policy (minimum fee, capacity). A producing node answers once the op is in its next block template, or after 5 seconds at most. - A path C op does not go through this method: it travels in a Bitcoin transaction, and `ksana_submitOp` refuses it with `-32010`. - An op that breaks a consensus rule returns `-32010`; an op the node’s policy refuses (fee too low, pool full, a replacement that does not raise the fee enough) returns `-32011`. - Bytes that do not decode return `-32602`: ```sh rpc $NODE ksana_submitOp '["00"]' | jq .error ``` ```output { "code": -32602, "message": "VmOp decode failed: Borsh decode failed: Unexpected length of input" } ``` The [TypeScript SDK](https://ksana.network/docs/sdk/) and [ksana-cli](https://ksana.network/docs/cli/) build, sign and encode ops for you. ### `ksana_getOpStatus` Parameter: the op ID. The example asks for a faucet transfer: ```sh OP=a91054efcbde256b412d0d5286d922ce5377ac6a3ea0941a2eabe41cbaaf090e rpc $NODE ksana_getOpStatus "[\"$OP\"]" | jq .result ``` ```output { "status": "btc_final", "block": { "height": "30", "hash": "f564dcd99ab57f8cc2a38e76232a717a2b4a0a3cc2707fcb55ca22e04c687e01" }, "index": 0, "receipt": { "op_id": "a91054efcbde256b412d0d5286d922ce5377ac6a3ea0941a2eabe41cbaaf090e", "success": true, "error": null, "gas_used": "10000", "output": "", "events": [], "asset_changes": [ { "kind": "transfer", "asset": "0000000000000000000000000000000000000000000000000000000000000000", "from": "de6603f052fd5bfaae5678a2a20ae6ae4fe4ae00c89db70a2efea7429851afc0", "to": "b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d", "amount": "10000000000", "events": 0 } ] } } ``` | `status` | Meaning | | --- | --- | | `pending` | in the entry pool, not yet in a block | | `fast_confirmed` | in a block of the main chain and executed successfully | | `failed` | in a block, but its execution failed: the state is rolled back and the fee is charged | | `skipped` | included only by a merged block and could not be executed; no fee is charged, and the op can return to the entry pool | | `btc_final` | executed successfully, and the block that accepted it is BTC-final | `block.hash` is the block that included the op. `block.height` is the height of the main-chain block that accepted it: an op in a merged block takes effect at the height of the block that merges it. `index` is the entry’s place in its block. An unknown op returns `-32004`, and [Confirmations](https://ksana.network/docs/confirmations/) explains the marks behind these statuses. `receipt.asset_changes` lists what the op did to built-in assets, in the order it did it: here the transfer itself. Each change has a `kind` and an `asset`, and `events` counts the op’s events before it, so that the two lists read in the op’s order: | `kind` | Fields | The change | | --- | --- | --- | | `transfer` | `from`, `to`, `amount` | an `AssetTransfer` op, from its signer | | `funds` | `from`, `to`, `amount` | assets attached to a call or a deployment, by the op’s signer or by a contract to a contract it calls or creates | | `payout` | `from`, `to`, `amount` | a contract paying from its own balance | | `issue` | `to`, `amount` | the issuing contract issuing more | | `burn` | `from`, `amount` | a burn | | `create` | `capabilities` | the asset’s creation, its capabilities named as [`ksana_getAsset`](#ksana_getasset) names them; the issuance follows as an `issue`, unless it is of 0 | | `freeze` | `account`, `frozen` | the issuing contract freezing an account, or unfreezing it | | `allow` | `account`, `allowed` | the issuing contract putting an account on its allowlist, or taking it off | | `pause` | `paused` | the issuing contract pausing the asset, or resuming it | | `renounce` | `capabilities` | the capabilities the issuing contract gave up, none if the asset no longer had them | A failed op has no changes, and neither fees nor movements of 0 are changes. `asset_changes` is `null` in the receipts a node stored before it recorded them, and a node from before has no such field. ### `ksana_getAccountOps` Parameters: `account`, `before` (optional), `limit` (optional). It lists the ops of one account on the main chain, newest first: the ops it signed, the transfers to it, the calls to it as a contract, the ops whose [token events](#tokens-and-nfts) name it or were emitted by it, and the ops whose [changes to built-in assets](#ksana_getopstatus) name it, other than its own deployment. Given the ID of an asset other than KSA, it lists the ops that changed that asset. ```sh rpc $NODE ksana_getAccountOps "[\"$ACCOUNT\", null, 2]" | jq .result ``` ```output { "ops": [ { "op_id": "85aa965def12e9cc329dc120f9fcabf2ad165b70731917fc47158e0b87b42f0d", "status": "fast_confirmed", "block": { "height": "39", "hash": "7a485752fb81319c9d454215968acb3010139cc79f52457feff6d8f25653c5c6" }, "index": 0, "position": "39:0:0" }, { "op_id": "797d9dc411ae59e79ce0aa8a369ec151f9416f7afb18569c0181fe81ebecc2e0", "status": "btc_final", "block": { "height": "38", "hash": "ab3fe1dcb95f0d76cd171210567f571fcd81cc8f7559d68da7dd38348eec7cf2" }, "index": 0, "position": "38:0:0" } ], "next": "38:0:0", "at": { "height": "61", "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f" } } ``` - `position` is an op’s place on the main chain, `"height:slot:entry"`: the height of the main-chain block that accepted it, the place of its block among the blocks that one accepted, and the entry’s index. Listings run from the highest position down. - `before` is a position: the page lists the ops below it. Pass the previous page’s `next` to continue, and `null` (or nothing) for the newest ops. - `limit` is 1 to 500, 50 by default. - `next` is `null` once the listing reaches the genesis block. A page can hold fewer ops than `limit`, even none, while `next` is not `null`: keep following `next`. The next page continues below `38:0:0`: ```sh rpc $NODE ksana_getAccountOps "[\"$ACCOUNT\", \"38:0:0\", 2]" \ | jq -c '.result.ops[].position, .result.next' ``` ```output "37:0:0" "36:0:0" "36:0:0" ``` Listings include path B and path C ops, not unlock entries. A node from before these methods existed, or one whose op index is not built, returns `-32601`. A malformed account or position, or a `limit` out of range, returns `-32602`. ### `ksana_getLatestOps` Parameters: `before` (optional), `limit` (optional). The same listing as `ksana_getAccountOps`, for every account: ```sh rpc $NODE ksana_getLatestOps '[null, 1]' | jq .result ``` ```output { "ops": [ { "op_id": "54dfe7da3eccfadafdaf89422d718ead59ee35a7100fa1c96553b38c2ca230bb", "status": "fast_confirmed", "block": { "height": "49", "hash": "ce36e3736a66c3773ed309cae018dd6e51fe2e4ad1e11b7d46893238026882a6" }, "index": 0, "position": "49:0:0" } ], "next": "49:0:0", "at": { "height": "61", "hash": "d436b257794aeaec071c01a339dd61d175e9959ce4d837ef5151a49e34ae434f" } } ``` ## Blocks and settlements ### `ksana_getBlock` Parameter: a block identifier. The result holds `hash`, `header`, `entries`, `settlement`, `receipts`, `accepted_height` and `merged`. The example leaves out `entries` and `receipts` to stay short: ```sh rpc $NODE ksana_getBlock '["33"]' | jq '.result | del(.entries, .receipts)' ``` ```output { "hash": "8f3d978dd672b44bf040d325af63e4701a00d9e04e620178480a5b36b636b593", "header": { "version": 2, "height": "33", "parents": [ "5131d895b03d85d20262c6bc70417a36bb3d8c46c03059167d29267e7118a1b4" ], "btc_anchor": { "height": 327279, "hash": "c770c385e86ae4792f479f8a8c0fd3fde68b3fb604d47911afa42c5103000000" }, "entries_root": "418ccbe2a7af7e2dd1e10948e51a1558358ac3b3f20fdc3efd09e5351bba20d1", "state_root": "bcd3279d347647192768169d53610bb36fe0681b0213e46a3e8193fae792f8ad", "producer": "b40c816d58ee2578da0118a9c6feeca74b80280f92030bdfa510821ae2887954", "timestamp": "1792558601", "bits": 520499867, "nonce": "371" }, "settlement": null, "accepted_height": "33", "merged": [] } ``` - `header.parents` lists the block’s parents in the block DAG; `btc_anchor` is the Bitcoin block it anchors to; `producer` is the account that made it. - `entries` lists the block’s entries, each an object with one key: `Sponsored` (a path B op), `Forced` (a path C op with the `btc_txid` that carried it), `Unlock`, or `Aggregate`, `{ "s": "<32 bytes>" }`: the last entry of a block that has a path B op, which stands for the second halves of their signatures ([Signatures in a block](https://ksana.network/docs/submitting-ops/#signatures-in-a-block)). - `receipts` holds one receipt per entry, from when the main chain accepted the block; the aggregate entry’s is a success without an `op_id`. An entry whose `error` starts with `skipped` was not executed. - `settlement` holds the block’s own commit and reveal transactions, `{ "commit", "reveal" }`, as hex, or `null` when it carries none. - `accepted_height` is the height of the main-chain block that accepted this one: its own height on the main chain, the merging block’s height for a merged block, `null` while no main-chain block has accepted it. - `merged` lists the blocks it merges, in the order their entries run. The entry of block 33, without its signature: ```sh rpc $NODE ksana_getBlock '["33"]' | jq '.result.entries[0].Sponsored.op | del(.sig)' ``` ```output { "version": 2, "chain_id": 1002, "account": "b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d", "nonce": "2", "fee": { "Token": { "amount": "1" } }, "max_gas": "1000000", "action": { "Call": { "contract": "6569e81e9aa68a0ae8058c3f749de4b0f13d2f3448f12831d8ccf0960c329658", "method": "transfer_and_call", "args": "eb5ca55289984d64598a12303a0638ee9dd6edc50f4bebe6d43a7a46121fc74500a0724e180900000000000000000000210000000100f2052a01000000000000000000000001000000000000000000000000000000", "funds": [ { "asset": "0000000000000000000000000000000000000000000000000000000000000000", "amount": "5000000000" } ] } } } ``` `sig` is `{"Bip340": "<64 bytes>"}` for a key signature or `{"Bip322Simple": ""}` for a wallet signature. Those are the whole signatures, as an op is submitted and as a path C op stays; a path B op in a block has the first half of its signature, `{"HalfBip340": "<32 bytes>"}` for a key signature, `{"HalfBip322": "<32 bytes>"}` or `{"HalfBip322All": "<32 bytes>"}` for a wallet signature. `fee` is `{"Token": {"amount"}}` for path B and `"BtcNative"` for path C. `action` is `Deploy`, `Call` or `AssetTransfer`. ### `ksana_getSettlement` Parameter: a block identifier. It tells you whether the block’s data is on Bitcoin. The example leaves out `txs`, the two raw transactions (`{ "commit", "reveal" }` in hex): ```sh rpc $NODE ksana_getSettlement '["38"]' | jq '.result | del(.txs)' ``` ```output { "block": { "height": "38", "hash": "ab3fe1dcb95f0d76cd171210567f571fcd81cc8f7559d68da7dd38348eec7cf2" }, "txid": "a31ec70b067407708454acf3cea6af68851c4e2cea4d682c737dc76003943921", "txid_rpc": "2139940360c77d732c684dea2c4e1c8568afa6cef3ac5484700774060bc71ea3", "commit_txid": "97080af7841e539719cb93c78562f11d9f9e4f155930785224c460f32e99f702", "commit_txid_rpc": "02f7992ef360c42452783059154f9e9f1df16285c793cb1997531e84f70a0897", "carrier_account": "ccc06c3ce8d176b3c10138dd4e70873939a9c6dc05597f45aace147ef2c07d3d", "carrier": null, "status": "confirmed", "confirmed": { "txid": "a31ec70b067407708454acf3cea6af68851c4e2cea4d682c737dc76003943921", "height": 327281, "block": "c2d6d161fdef456778a3df4f2ffe65a4627ad100ccbd24122d78fd5006000000", "confirmations": 11 }, "settled": true, "btc_final": true } ``` - `txid` is the reveal transaction, which carries the payload in its Taproot witness; `commit_txid` is the commit transaction it spends. The `_rpc` fields give them in explorer order. - `status` is `pending` (not broadcast yet: a settlement waits until the block has 2 fast-lane confirmations), `broadcast`, or `confirmed` once the block’s data is on Bitcoin. A settlement that confirmed before the headers it needs from earlier blocks had counted put nothing on Bitcoin, so the status stays `broadcast` until the same payload is sent again and lands. - `confirmed` describes the first confirmed Bitcoin transaction that put the block’s data on Bitcoin, `{ "txid", "height", "block", "confirmations" }`. That can be the block’s own settlement, a later block’s, or a republish. For a block with no body to land, such as an empty block carrying a batch’s settlement, it is the first transaction carrying the block’s header at the height where the header counts, so its `txid` can differ from the block’s own. - `settled` is `true` once the data of the block that accepted it, and of every main-chain block before that one, is on Bitcoin; `btc_final` is `true` once the block that accepted it is final. - `carrier_account` is the account paid as the block’s carrier, or `null` when the producer keeps the reward. It is answered from the current Bitcoin chain and main chain. A block can have its body carried by a later block’s settlement (batching). Its `carrier` then names that block, and the transaction fields describe that block’s settlement; while no block carries it yet, they are `null` and `status` is `pending`. An empty block, or one holding only path C operations, has no body to land, so it returns `-32004` when it carries no settlement itself. ## Read-only calls ### `ksana_call` Parameter: one call request object. It runs a contract method on the latest state without a fee, without a nonce, and without writing anything: | Field | Required | Meaning | | --- | --- | --- | | `contract` | yes | the contract ID | | `method` | yes | the method name | | `args` | yes | the arguments, Borsh-encoded, in hex (`""` for none) | | `funds` | no | attached assets, `[{ "asset", "amount" }]`, moved from `caller` in the simulation | | `caller` | no | the simulated caller, 32 zero bytes by default | | `max_gas` | no | a decimal string, at most `BLOCK_GAS_LIMIT` (100,000,000, also the default) | Read a pool’s reserves (the tutorial’s pool, `(u128, u128)` little-endian): ```sh POOL=eb5ca55289984d64598a12303a0638ee9dd6edc50f4bebe6d43a7a46121fc745 rpc $NODE ksana_call "[{\"contract\": \"$POOL\", \"method\": \"reserves\", \"args\": \"\"}]" \ | jq .result ``` ```output { "op_id": null, "success": true, "error": null, "gas_used": "50570", "output": "be310d09810400000000000000000000583a7696000000000000000000000000", "events": [], "asset_changes": [] } ``` Attached funds come out of `caller`’s balance, so a simulation that attaches funds needs a funded `caller`. Here a quote for swapping 1 KSA in that pool, without `caller`, fails, and a failed call reports all of `max_gas` as used: ```sh ARGS=${KSA}00e1f50500000000000000000000000001000000000000000000000000000000 rpc $NODE ksana_call "[{\"contract\": \"$POOL\", \"method\": \"swap\", \"args\": \"$ARGS\", \"funds\": [{\"asset\": \"$KSA\", \"amount\": \"100000000\"}], \"max_gas\": \"500000\"}]" \ | jq .result ``` ```output { "op_id": null, "success": false, "error": "attached funds transfer failed: insufficient balance", "gas_used": "500000", "output": "", "events": [], "asset_changes": [] } ``` With `"caller": "$ACCOUNT"` added, the call succeeds and returns the quote: ```output { "op_id": null, "success": true, "error": null, "gas_used": "169247", "output": "f4513fcf2b0000000000000000000000" } ``` (That output leaves out `events` and `asset_changes`.) The receipt is `{ "op_id", "success", "error", "gas_used", "output", "events", "asset_changes" }`, the same shape as an op’s receipt with `op_id` set to `null`, and `asset_changes` lists the changes the call would make to built-in assets, the attached funds first. `output` is the hex of the bytes the method returned, and each event is `{ "contract", "data" }`. The call sees the environment of the next block: its height is the tip’s plus one, with the tip’s timestamp and Bitcoin anchor. `native_tx()` returns nothing. A `max_gas` above the limit returns `-32602`. A node runs at most 4 calls at a time; further calls return `-32009` until one finishes. ## Subscriptions ### `ksana_subscribeBlocks` Over WebSocket only. The answer is a subscription ID. Then every block that joins the main chain, including the blocks a reorganization connects, arrives as a `ksana_block` notification. To stop, call `ksana_unsubscribeBlocks` with the subscription ID. This JavaScript runs in a browser or in Node.js 22 and later (`node subscribe.mjs`). It subscribes, prints the first notification, and unsubscribes: ```javascript title="subscribe.mjs" const ws = new WebSocket("wss://signet.ksana.network/rpc"); const send = (id, method, params) => ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params })); ws.onopen = () => send(1, "ksana_subscribeBlocks", []); ws.onmessage = (event) => { const message = JSON.parse(event.data); console.log(JSON.stringify(message, null, 2)); if (message.method === "ksana_block") { // One block is enough here: unsubscribe, then close once the node confirms send(2, "ksana_unsubscribeBlocks", [message.params.subscription]); } if (message.id === 2) ws.close(); }; ws.onclose = (event) => console.log("closed", event.code); ``` ```output { "jsonrpc": "2.0", "id": 1, "result": 8723730946419982 } { "jsonrpc": "2.0", "method": "ksana_block", "params": { "subscription": 8723730946419982, "result": { "height": "63", "hash": "8f9221ec3639c5f48bf56afed0a2e8b692d5a229470ca108f8137c37e8b3202b", "entries": 0, "timestamp": "1792562771" } } } { "jsonrpc": "2.0", "id": 2, "result": true } closed 1005 ``` Each notification is `{ "height", "hash", "entries", "timestamp" }`: `entries` is the block’s number of entries and `timestamp` is in seconds. A subscriber that falls behind skips the notifications it missed and continues with later blocks. Nothing reconnects for you: when the connection closes, open a new one, subscribe again, and read the blocks you missed with `ksana_getBlock`. On an idle signet, blocks can be minutes apart. ## Indexer methods The [indexer](https://ksana.network/docs/run-an-indexer/) rebuilds the chain from bitcoind alone and checks every state root. Its two methods follow the same conventions. ### `indexer_status` No parameters. ```sh rpc $INDEXER indexer_status | jq .result ``` ```output { "height": "51", "hash": "5b69b10223571ab01bdee3080d8e1ed25c8ace4fc420f744d23b7d8d5db15981", "state_root": "bd7ad23935fc366400a48eb8591696171be864520fd981c3204f9d5e64cc0963", "btc_height": 327291, "finalized": { "height": "38", "hash": "ab3fe1dcb95f0d76cd171210567f571fcd81cc8f7559d68da7dd38348eec7cf2" }, "halted": null } ``` - `height`, `hash` and `state_root` describe the highest block the indexer has executed and verified. It verifies a block once the block’s data is on Bitcoin and the block has 2 confirmations on the indexer’s main chain, or once it is decided final, so it trails the node. - `btc_height` is the Bitcoin tip it has scanned, `null` before it has synced with bitcoind. - `finalized` is the BTC-final tip, by the same rule as the node’s. - `halted` is `null` in normal operation. The indexer stops, and `halted` gives the reason, only when a block that Bitcoin made final turns out invalid; an invalid block that is not final is left out, and the indexer chooses its main chain again ([alarms](https://ksana.network/docs/run-an-indexer/#alarms)). ### `indexer_stateRoot` Parameter: a block identifier. It answers only for blocks the indexer has verified; others return `-32004`, and a malformed identifier returns `-32602`. ```sh rpc $INDEXER indexer_stateRoot '["51"]' | jq .result rpc $NODE ksana_getBlock '["51"]' | jq -r .result.header.state_root ``` ```output { "height": "51", "hash": "5b69b10223571ab01bdee3080d8e1ed25c8ace4fc420f744d23b7d8d5db15981", "state_root": "bd7ad23935fc366400a48eb8591696171be864520fd981c3204f9d5e64cc0963" } bd7ad23935fc366400a48eb8591696171be864520fd981c3204f9d5e64cc0963 ``` The two state roots match: the node’s block 51 is the block the indexer rebuilt from Bitcoin alone. ## Errors An error answer has an `error` object instead of `result`, with `code` and `message`, sometimes `data`: ```sh rpc $NODE ksana_getOpStatus "[\"$KSA\"]" | jq .error rpc $NODE ksana_getBlock '["0x10"]' | jq .error rpc $NODE ksana_getBlockCount | jq .error ``` ```output { "code": -32004, "message": "unknown op" } { "code": -32602, "message": "block identifier must be \"latest\", a decimal height or a 64-digit hex hash" } { "code": -32601, "message": "Method not found" } ``` | Code | Meaning | | --- | --- | | `-32601` | no such method, or not available on this node (the op listings and the token methods without their index) | | `-32602` | a malformed parameter: hex, decoding, length, range | | `-32010` | the op breaks a consensus rule, or is a path C op; with `id` `null`, a batch of more than 64 calls ([limits](#limits)) | | `-32011` | the node’s policy refuses the op: fee too low, pool full, replacement fee not high enough; with `id` `null`, a batch whose answers would pass 10 MiB | | `-32004` | the object does not exist: op, block, asset, settlement, unverified block | | `-32009` | the node is busy: too many `ksana_call` requests at once; try again later | | `-32603` | an internal error of the node | | `-32006` | too many subscriptions on one WebSocket connection ([limits](#limits)) | | `-32007` | the request is longer than 1 MiB | | `-32008` | the answer would be longer than 10 MiB | --- # Your first contract URL: https://ksana.network/docs/first-contract/ > Write a poll in Rust, compile it and deploy it on the public signet, all in the browser with the contract playground, then vote on it from your wallet. This tutorial writes a poll. The account that deploys it asks a question with 2 to 8 options, every account votes once while the poll is open, and the creator closes it. You write, compile and deploy it in the [contract playground](https://playground.ksana.network/), with nothing to install: every operation is signed in your own wallet and pays its fee in test KSA. The poll is `contracts/examples/poll` in the [repository](https://github.com/ksana-in-bitcoin/ksana), with its tests. [Write a contract](https://ksana.network/docs/contracts/) goes through the same steps on your own machine, with `cargo` and [ksana-cli](https://ksana.network/docs/cli/). ## Before you start - A wallet: Unisat, OneKey or Xverse, with a Taproot (`tb1p…`) account on Bitcoin signet, as for [the signet wallet](https://ksana.network/docs/wallet/#connect). The playground asks it for signatures only and never sees your keys. - Test KSA: the playground’s **Get test KSA** asks the faucet for 100 KSA, once a day for each account, enough for many deployments and calls. ## The contract ```rust title="src/lib.rs" //! Tutorial contract: a poll. The account that deploys it asks a question with 2 to 8 options; every account votes //! once while the poll is open, and the creator closes it. It takes no funds. //! //! The contract of the docs' tutorial "Your first contract", which builds it in the playground in place of the //! counter's source, so it needs nothing but the contract SDK. It keeps its state under a few storage keys and one key //! per voter, refuses with a reason what it does not allow, knows its creator and its voters by `caller()`, and emits //! an event for every change. //! //! Arguments and return values are Borsh-encoded; the options are numbered from 0 in the order `init` takes them. //! //! ```abi //! init(question: String, options: Vec) // a question of 1 to 200 bytes; 2 to 8 options of 1 to 64 bytes //! call vote(option: u32) -> u64 // one vote per account while the poll is open; returns the option's votes //! call close() // the creator only: ends the voting for good //! view poll() -> (String, Vec, bool) // the question, the options, whether voting is open //! view results() -> Vec // the votes for each option, in order //! view voted(account: Account) -> Option // the option the account voted for; None before it votes //! event voted(voter: Account, option: u32) //! event closed(total: u64) //! ``` #![cfg_attr(target_arch = "wasm32", no_std)] extern crate alloc; use alloc::string::String; use alloc::vec::Vec; use ksana_contract_sdk::{self as sdk, storage, CallResult, Decode}; sdk::entry!(dispatch); /// The longest question, in bytes. pub const MAX_QUESTION: usize = 200; /// The longest option, in bytes. pub const MAX_OPTION: usize = 64; /// The most options a poll has; it has at least 2. pub const MAX_OPTIONS: usize = 8; const KEY_QUESTION: &[u8] = b"question"; const KEY_OPTIONS: &[u8] = b"options"; const KEY_CREATOR: &[u8] = b"creator"; const KEY_OPEN: &[u8] = b"open"; const KEY_TALLY: &[u8] = b"tally"; /// Followed by a voter's account: the option it voted for. const PREFIX_VOTE: &[u8] = b"vote:"; /// Dispatches the poll's methods; storage belongs to this contract instance. pub fn dispatch(method: &str, args: &[u8]) -> CallResult { if !sdk::call_funds().is_empty() { return sdk::revert("unexpected attached funds"); } match method { "init" => { let (question, options): (String, Vec) = sdk::decode(args)?; init(question, options) } "vote" => vote(sdk::decode(args)?), "close" => { sdk::decode::<()>(args)?; close() } "poll" => { sdk::decode::<()>(args)?; let question: String = load(KEY_QUESTION)?; let options: Vec = load(KEY_OPTIONS)?; let open: bool = load(KEY_OPEN)?; sdk::ok(&(question, options, open)) } "results" => { sdk::decode::<()>(args)?; sdk::ok(&load::>(KEY_TALLY)?) } "voted" => { let account: [u8; 32] = sdk::decode(args)?; sdk::ok(&storage::read::(&vote_key(&account))?) } _ => sdk::revert("unknown method"), } } /// Keeps the question and the options and opens the poll with no votes; the deploying account is its creator. fn init(question: String, options: Vec) -> CallResult { if question.is_empty() || question.len() > MAX_QUESTION { return sdk::revert("the question must be 1 to 200 bytes"); } if options.len() < 2 || options.len() > MAX_OPTIONS { return sdk::revert("a poll has 2 to 8 options"); } if options.iter().any(|o| o.is_empty() || o.len() > MAX_OPTION) { return sdk::revert("an option must be 1 to 64 bytes"); } storage::write(KEY_TALLY, &alloc::vec![0u64; options.len()]); storage::write(KEY_QUESTION, &question); storage::write(KEY_OPTIONS, &options); storage::write(KEY_CREATOR, &sdk::caller()); storage::write(KEY_OPEN, &true); sdk::ok(&()) } /// Counts the caller's vote for `option`, once per account while the poll is open. fn vote(option: u32) -> CallResult { if !load::(KEY_OPEN)? { return sdk::revert("voting is closed"); } let voter = sdk::caller(); let key = vote_key(&voter); if storage::get(&key).is_some() { return sdk::revert("already voted"); } let mut tally: Vec = load(KEY_TALLY)?; let Some(count) = usize::try_from(option).ok().and_then(|i| tally.get_mut(i)) else { return sdk::revert("unknown option"); }; let Some(votes) = count.checked_add(1) else { return sdk::revert("too many votes"); }; *count = votes; storage::write(KEY_TALLY, &tally); storage::write(&key, &option); sdk::emit(&("voted", voter, option)); sdk::ok(&votes) } /// Ends the voting; only the creator may, once. fn close() -> CallResult { if load::<[u8; 32]>(KEY_CREATOR)? != sdk::caller() { return sdk::revert("only the creator"); } if !load::(KEY_OPEN)? { return sdk::revert("voting is closed"); } let tally: Vec = load(KEY_TALLY)?; let Some(total) = tally.iter().try_fold(0u64, |sum, n| sum.checked_add(*n)) else { return sdk::revert("too many votes"); }; storage::write(KEY_OPEN, &false); sdk::emit(&("closed", total)); sdk::ok(&()) } /// Reads a value `init` stored. fn load(key: &[u8]) -> Result> { storage::read(key)?.ok_or_else(|| b"not initialized".to_vec()) } /// The storage key of `account`'s vote. fn vote_key(account: &[u8; 32]) -> Vec { [PREFIX_VOTE, account.as_slice()].concat() } ``` ## How it works ### The ABI block The block marked `abi` in the `//!` comment at the top describes the poll to the playground. `init` takes the question and the options at deployment; each `call` is an operation you sign; each `view` only reads, so it needs no signature and no fee; and the events are what the poll records. The playground builds a form for every method from this block and decodes results and events with it. [The ABI block](https://ksana.network/docs/playground/#the-abi-block) lists its types. ### Dispatch `sdk::entry!(dispatch)` makes `dispatch` the contract’s entry point: it gets each call’s method name and its arguments, encoded with Borsh, and returns `sdk::ok(&value)` or a revert. The poll first refuses attached funds, since KSA attached to a call it does not expect would stay in the contract for good, and then matches the method’s name. `sdk::decode` reads the arguments and fails the call with `malformed arguments` when they do not fit. ### Storage A call’s memory is gone when it returns: each call runs in a fresh instance. What lasts goes into storage, a key-value store only this contract can write. The poll keeps the question, the options, the creator, whether voting is open and the tally under one key each, and each voter’s choice under `vote:` followed by the voter’s account. That key is how `vote` refuses a second vote, and what `voted` reads. ### Checks and reverts Every method checks before it writes and refuses with a reason: `init` checks the lengths, `vote` that the poll is open, that the account has not voted and that the option exists, and `close` that the caller is the creator. A revert undoes everything the operation did, and its reason is what the wallet and the playground show. The poll never panics either: it uses `get_mut` rather than indexing and `checked_add` rather than `+`, because a panic fails the operation without a reason anyone can read. ### Callers and events `sdk::caller()` is the account that signed the operation, so `init` records the deployer as the creator and `vote` knows who voted. `sdk::emit` records an event in the operation’s receipt: `voted` with the voter and the option, `closed` with the total number of votes. ## Compile it ### Open the counter’s Code tab The playground compiles a source as the `src/lib.rs` of one of its examples. The poll needs nothing but the contract SDK, so it builds as the counter does: open the [Counter page’s Code tab](https://playground.ksana.network/#/counter/code) and connect your wallet. ### Paste the poll Select the whole source in the editor and paste the poll over it. The page keeps your edit in this browser, and **Back to the example** brings the counter back. ### Compile Press **Compile**. The build takes a few seconds, and the line under the button counts what your ABI block declares: `ABI: 6 methods, 2 events`, counting `init`. A mistake comes back from the compiler on its line and in a list beside the editor. To see one, delete the `?` after `sdk::decode(args)` in the `"vote"` arm and compile again: ```output error[E0308]: mismatched types --> src/lib.rs:57:24 | 57 | "vote" => vote(sdk::decode(args)), | ---- ^^^^^^^^^^^^^^^^^ expected `u32`, found `Result<_, Vec>` ``` The compiler suggests the fix itself: put the `?` back, which turns arguments that do not decode into a revert. ## Deploy it Press **Deploy this build**. The dialog asks for `init`’s arguments in a form built from the ABI block: type a question, such as `Which fruit?`, and add two or more options. Review the operation and sign it in your wallet. The page shows the new contract’s ID, predicted until a block includes the deployment. The poll is now a contract of its own on the signet. The Counter page’s **App** tab is made for the counter and says that it may not match your contract, so use the **Methods** tab, whose forms follow your ABI block. ## Use it ### Vote In the **Methods** tab, open `vote`, enter the option `1`, press **Review** and sign the operation in your wallet. Once a block includes it, the result is `1`, the option’s votes so far, with the `voted` event below it. ### Try to vote again Press **Try read-only** on `vote`. It runs the operation against the latest state without signing or sending anything, and shows that it would fail with `already voted`. The review before every signature runs the same check, because a failed operation still pays its fee. ### Read the results `results`, `poll` and `voted` are views: **Read** runs them read-only, with no signature and no fee. `results` gives the votes of each option, and `voted` with your account the option you chose. ### Close the poll Send `close` the same way. From then on `vote` fails with `voting is closed`, and `poll` reports voting closed. From any account but the creator’s, `close` fails with `only the creator`. The **Activity** tab lists the operations this browser sent, with their receipts. Others can vote too: on the playground’s home, **Any contract** opens the poll by its ID and builds its forms from the poll’s source, or just its ABI block, pasted there. ## Test it on your machine The repository builds the poll as `contracts/examples/poll` and tests it natively on the SDK’s mock host, which runs a contract without a node. A test deploys the poll, calls it as different accounts, and checks what it returns, what it refuses and what it emits: ```rust title="tests/one_vote.rs" //! A native test of the poll on the contract SDK's mock host. #![cfg(not(target_arch = "wasm32"))] #![allow(missing_docs, clippy::unwrap_used)] use ksana_contract_sdk::mock::{self, Failure}; use ksana_contract_sdk::{decode, encode}; #[test] fn every_account_votes_once() { mock::reset(); let creator = [1; 32]; let init = encode(&( "Which fruit?", vec!["apple".to_string(), "pear".to_string()], )); let contract = mock::deploy(creator, 0, b"poll", poll::dispatch, &init).unwrap(); let votes: u64 = decode(&mock::call([2; 32], contract, "vote", &encode(&1u32)).unwrap()).unwrap(); assert_eq!(votes, 1); assert_eq!( mock::call([2; 32], contract, "vote", &encode(&0u32)), Err(Failure::Revert { contract, reason: b"already voted".to_vec() }) ); let results: Vec = decode(&mock::call([9; 32], contract, "results", &[]).unwrap()).unwrap(); assert_eq!(results, vec![0, 1]); assert_eq!(mock::events().len(), 1); } ``` Run the poll’s tests from a clone of the repository, with Rust 1.98.1: ```sh git clone https://github.com/ksana-in-bitcoin/ksana cd ksana/contracts cargo test -p poll ``` [Write a contract](https://ksana.network/docs/contracts/#test-it-natively) explains the mock host, and [The contract SDK](https://ksana.network/docs/contract-sdk/#mock) lists its functions. ## With an AI assistant An AI assistant writes and changes contracts like this one well once it knows Ksana. The playground’s [AI assistants](https://playground.ksana.network/#/ai) page copies a reference written for them, also published at [https://ksana.network/llms-contracts.txt](https://ksana.network/llms-contracts.txt), and the Code tab’s **Copy for an AI assistant** copies it together with your contract and the compiler’s last messages. Paste it into ChatGPT, Claude or another assistant, then ask, for example: ```text Change the poll so that voting ends by itself at a block height that init takes, and let the creator add options until the first vote. ``` Paste the answer into the Code tab, compile it, and deploy it as a new contract. ## Next - [Write a contract](https://ksana.network/docs/contracts/) The same steps on your own machine, with cargo and ksana-cli. - [The contract SDK](https://ksana.network/docs/contract-sdk/) Every function, type and constant a contract uses. - [Host functions and gas](https://ksana.network/docs/host-functions/) What each call costs, and the limits. - [Example contracts](https://ksana.network/docs/example-contracts/) Tokens, an AMM, lending, a multisig and more, each tested. --- # Write a contract URL: https://ksana.network/docs/contracts/ > Ksana contracts are Rust compiled to WebAssembly. Build a small one from an empty directory, test it on your machine, then deploy and call it on the public signet. A contract is a WebAssembly module with its own storage and its own balances. An op deploys it; ops and other contracts call its methods. Every node and every indexer runs each call the same way, so the results are part of the chain’s state root. This page builds a tip jar: anyone can leave a note with KSA attached, and the owner can withdraw the tips. To start in the browser instead, [Your first contract](https://ksana.network/docs/first-contract/) writes a poll in the playground with nothing to install. [The contract SDK](https://ksana.network/docs/contract-sdk/) lists every function this page uses, and the [example contracts](https://ksana.network/docs/example-contracts/) are larger, tested models to read next. ## How contracts work - **Language and target.** You write the contract in Rust, against `ksana-contract-sdk` from the repository, and compile it to `wasm32-unknown-unknown`. On that target the crate is `no_std`: the SDK supplies the allocator and the panic handler. - **One call, one instance.** Each call runs in a fresh instance, so memory does not survive between calls. Data that must persist goes into the contract’s storage, a key-value store that only the contract itself can write. - **Methods.** The node passes a method name and argument bytes. The contract returns `Ok(bytes)`, or `Err(reason)` to revert. - **All or nothing.** A revert, a trap or running out of gas, at any level of nested calls, fails the whole op: every change is rolled back, and only the fee and the nonce increment remain. The one exception is `try_call`, below. - **Determinism.** The host functions are a contract’s only view of the world: there is no clock but the block’s timestamp and no source of randomness. Floating point is rejected at deployment, gas is counted exactly, and the stack is metered by a fixed estimate, so every machine gets the same result. ### Checks at deployment The node checks the module when the deploy op executes: a module that fails makes the op fail with `deployment rejected: `, and the op’s fee and nonce are spent all the same. The module must: - use WebAssembly 1.0 plus mutable globals, sign extension, bulk memory, multi-value and `funcref` tables, and no floating point, SIMD, threads or other proposals; - define exactly one memory of at most 256 pages (16 MiB) at the start, and at most one table of at most 4,096 entries; - import functions only from the module `ksana` (the [host functions](https://ksana.network/docs/host-functions/)), and export `memory`, `ksana_alloc` and `ksana_call`. Rust 1.98.1 with the SDK produces such a module without extra flags. The [ABI](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/ABI.md) is the full specification. ## Set up a project You need Rust 1.98.1 or later with the `wasm32-unknown-unknown` target, and a clone of the repository: the SDK is not published on crates.io. Put your project next to the clone, not inside it, so that Cargo does not take it for a member of the repository’s workspace: ```text work/ ksana/ git clone https://github.com/ksana-in-bitcoin/ksana tip-jar/ Cargo.toml rust-toolchain.toml src/lib.rs tests/tip_jar.rs ``` ```toml title="Cargo.toml" [package] name = "tip-jar" version = "0.1.0" edition = "2021" rust-version = "1.98.1" publish = false [lib] crate-type = ["cdylib", "rlib"] [dependencies] ksana-contract-sdk = { path = "../ksana/crates/ksana-contract-sdk" } [profile.release] opt-level = "z" lto = true codegen-units = 1 panic = "abort" strip = true ``` ```toml title="rust-toolchain.toml" [toolchain] channel = "1.98.1" targets = ["wasm32-unknown-unknown"] ``` `cdylib` is the WebAssembly module, and `rlib` lets your native tests link the contract. The release profile keeps the module small: the deployment fee, the deployment gas and the gas of every call grow with its size. ## Write the contract ```rust title="src/lib.rs" //! A tip jar: anyone leaves a note with KSA attached, and the owner withdraws the tips. #![cfg_attr(target_arch = "wasm32", no_std)] extern crate alloc; use alloc::string::String; use alloc::vec::Vec; use ksana_contract_sdk::{self as sdk, storage, CallResult, KSA_ASSET_ID}; sdk::entry!(dispatch); const OWNER: &[u8] = b"owner"; const TOTAL: &[u8] = b"total"; /// Routes a call to its method. Deployment always calls `init`. pub fn dispatch(method: &str, args: &[u8]) -> CallResult { match method { "init" => init(args), "tip" => tip(args), "withdraw" => withdraw(args), "total" => { sdk::decode::<()>(args)?; sdk::ok(&total()?) } _ => sdk::revert("unknown method"), } } /// `init()`: the deployer becomes the owner. fn init(args: &[u8]) -> CallResult { sdk::decode::<()>(args)?; if !sdk::call_funds().is_empty() { return sdk::revert("init takes no funds"); } storage::write(OWNER, &sdk::caller()); sdk::ok(&()) } /// `tip(note: String) -> u128`: keeps the KSA attached to the call; returns the new total. fn tip(args: &[u8]) -> CallResult { let note: String = sdk::decode(args)?; if note.len() > 140 { return sdk::revert("the note is longer than 140 bytes"); } let amount = match sdk::call_funds().as_slice() { [funds] if funds.asset == KSA_ASSET_ID => funds.amount, _ => return sdk::revert("attach KSA and nothing else"), }; let total = total()?.checked_add(amount).ok_or(b"overflow".to_vec())?; storage::write(TOTAL, &total); sdk::emit(&("tip", sdk::caller(), amount, note)); sdk::ok(&total) } /// `withdraw(to: [u8; 32], amount: u128)`: the owner sends tips out of the jar. fn withdraw(args: &[u8]) -> CallResult { let (to, amount): ([u8; 32], u128) = sdk::decode(args)?; let owner: [u8; 32] = storage::read(OWNER)?.ok_or(b"not initialized".to_vec())?; if sdk::caller() != owner { return sdk::revert("only the owner can withdraw"); } // asset_transfer traps on a short balance; check first to revert with a reason if sdk::asset_balance(&KSA_ASSET_ID, &sdk::self_id()) < amount { return sdk::revert("not enough KSA in the jar"); } sdk::asset_transfer(&KSA_ASSET_ID, &to, amount); sdk::emit(&("withdraw", to, amount)); sdk::ok(&()) } fn total() -> Result> { Ok(storage::read(TOTAL)?.unwrap_or(0)) } ``` ### Entry point and dispatch `sdk::entry!(dispatch)` generates the two exports the node calls, `ksana_alloc` and `ksana_call`. It decodes the method name and the argument bytes and hands them to your `dispatch` function, which returns a `CallResult`, that is `Result, Vec>`. Deployment always calls `init`, so every contract handles it, even with no arguments: an `unknown method` revert there fails the deployment. After deployment, any call to `init` fails. ### Arguments and return values Arguments and return values are plain bytes. The convention, used by every example and by `ksana-cli`, is Borsh: the arguments of a method are a tuple encoded back to back, a single argument is encoded as itself, and no arguments is empty bytes. - `sdk::decode::(args)` decodes and requires every byte to be used. On bad input it returns `Err(b"malformed arguments")`, so `?` turns it into a revert. It handles integers, `bool`, `[u8; N]`, `Vec`, `String`, `Option`, `Result`, `()` and tuples of up to 8 elements; decode your own structs field by field. - `sdk::ok(&value)` encodes a return value, and `sdk::revert("reason")` reverts with a message. ### Storage `storage::read` and `storage::write` keep Borsh values under byte keys; `storage::get`, `set` and `remove` work on raw bytes. A key can be up to 256 bytes and a value up to 65,536 bytes. A write is visible at once to every level of the same op. Writes cost far more gas than reads (10,000 plus 10 per byte, against 2,000 plus 1 per byte), so store what you need and no more. The examples delete a key when its value drops to zero. ### Callers and attached funds `sdk::caller()` is the account that signed the op when an op calls the contract, or the calling contract’s ID when another contract calls it. `init` sees the deployer, which is how the tip jar learns its owner. An op or a contract can attach built-in assets, such as KSA, to a call. The node moves them to the contract before the contract runs, and `sdk::call_funds()` lists them. Funds that a contract does not account for stay in its balance for good, so check what arrives, as `tip` and `init` do. The contract’s own balance works like an account’s: `sdk::asset_balance` reads it and `sdk::asset_transfer` pays out of it. A transfer the balance cannot cover traps: the contract cannot catch it, and the op fails with the bare error `insufficient balance`. So `withdraw` checks first and reverts with its own message. ### Events `sdk::emit(&value)` records an event in the op’s receipt. By convention, an event is a Borsh tuple whose first element is its name, such as `("tip", caller, amount, note)`. Events are not part of the state, cost 1,000 gas plus 5 per byte, hold at most 16,384 bytes, and disappear when the op fails. ## Test it natively On your own machine, the SDK replaces the host functions with an in-memory mock, so ordinary `cargo test` runs the contract without a node: ```rust title="tests/tip_jar.rs" #![cfg(not(target_arch = "wasm32"))] use ksana_contract_sdk::mock::{self, Failure}; use ksana_contract_sdk::{encode, Funds, KSA_ASSET_ID}; const OWNER: [u8; 32] = [1; 32]; const FAN: [u8; 32] = [2; 32]; /// Deploys a fresh jar and gives FAN 1,000 base units of KSA. fn setup() -> [u8; 32] { mock::reset(); mock::register_asset(KSA_ASSET_ID, "KSA", 8, [0; 32]); mock::mint(KSA_ASSET_ID, FAN, 1_000).unwrap(); mock::deploy(OWNER, 0, b"tip-jar", tip_jar::dispatch, &[]).unwrap() } fn ksa(amount: u128) -> [Funds; 1] { [Funds { asset: KSA_ASSET_ID, amount, }] } #[test] fn tips_add_up_and_the_owner_withdraws() { let jar = setup(); let out = mock::call_with_funds(FAN, jar, "tip", &encode("gm"), &ksa(250)).unwrap(); assert_eq!(out, encode(&250u128)); assert_eq!(mock::balance(&KSA_ASSET_ID, &jar), 250); assert_eq!(mock::events().len(), 1); mock::call(OWNER, jar, "withdraw", &encode(&(OWNER, 100u128))).unwrap(); assert_eq!(mock::balance(&KSA_ASSET_ID, &OWNER), 100); assert_eq!(mock::balance(&KSA_ASSET_ID, &jar), 150); } #[test] fn only_the_owner_withdraws() { let jar = setup(); mock::call_with_funds(FAN, jar, "tip", &encode("gm"), &ksa(250)).unwrap(); let failure = mock::call(FAN, jar, "withdraw", &encode(&(FAN, 250u128))).unwrap_err(); assert_eq!( failure, Failure::Revert { contract: jar, reason: b"only the owner can withdraw".to_vec() } ); } ``` ```sh cargo test ``` ```output running 2 tests test tips_add_up_and_the_owner_withdraws ... ok test only_the_owner_withdraws ... ok test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` The mock follows the ABI: a failure at any level rolls back the whole op, and the limits, the call depth and the funds rules apply. It differs from a node in three ways that matter in tests: - KSA does not exist until you call `mock::register_asset` and `mock::mint`. - There is no gas metering, so a test cannot tell you what a call costs. - The `code` you pass to `mock::deploy` is a label, not your module, so contract IDs in tests differ from those on chain. ## Build the module Build the release module as a `cdylib` alone: ```sh cargo rustc --release --target wasm32-unknown-unknown --crate-type cdylib wc -c target/wasm32-unknown-unknown/release/tip_jar.wasm ``` ```output 9081 target/wasm32-unknown-unknown/release/tip_jar.wasm ``` `cargo build` also produces the `rlib`, and the module it leaves behind is larger, because link-time optimization cannot drop as much. The module’s bytes depend on the absolute path of your SDK checkout, so build the file you deploy once and compute its ID from that file. **The lints the example contracts use** The repository’s contracts deny the constructs that panic or overflow. Add the same table to your `Cargo.toml` and run `cargo clippy -- -D warnings`, natively and with `--target wasm32-unknown-unknown`; the tip jar passes both. ```toml [lints.rust] unsafe_code = "deny" missing_docs = "warn" [lints.clippy] unwrap_used = "deny" expect_used = "deny" panic = "deny" unreachable = "deny" todo = "deny" unimplemented = "deny" indexing_slicing = "deny" arithmetic_side_effects = "deny" float_arithmetic = "deny" cast_possible_truncation = "deny" cast_possible_wrap = "deny" cast_sign_loss = "deny" ``` Tests usually allow `unwrap_used` and `panic` again at the top of each test file. ## Deploy and call it To try a contract from the browser, the [contract playground](https://ksana.network/docs/playground/) deploys modules on the signet and calls them through forms that follow the [ABI block](https://ksana.network/docs/playground/#the-abi-block) of their source, signed in your wallet. Its examples can also be edited and compiled there. Deploy with [ksana-cli](https://ksana.network/docs/cli/) on the public signet. These commands use the `contract_id`, `enc_string` and `enc_u128` shell functions of the [token and pool tutorial](https://ksana.network/docs/token-and-pool/#load-the-helpers), which runs the same commands, with real output, on three example contracts. The tip jar’s `init` takes no arguments, so the deployment has no `--init-args`. The output gives the op’s `account`, `nonce` and status, but not the new contract’s ID: you compute it from the deploying account, the deploy op’s nonce and the SHA-256 of the module. ```sh export KSANA_RPC=https://signet.ksana.network/rpc ACCOUNT=$(ksana-cli --chain signet key alice.key | jq -r .account) WASM=target/wasm32-unknown-unknown/release/tip_jar.wasm ksana-cli deploy --key alice.key --code $WASM --fee-token 1 --wait > deploy.json JAR=$(contract_id $ACCOUNT $(jq -r .nonce deploy.json) $WASM) ``` Leave a tip of 1 KSA with a note, read the total, then withdraw half of it to your own account. `--args` takes the Borsh bytes in hex, and `--fund` attaches KSA in base units: ```sh ksana-cli call --key alice.key --contract $JAR --method tip --args $(enc_string "gm") \ --fund 100000000 --fee-token 1 --wait ksana-cli query --contract $JAR --method total ksana-cli call --key alice.key --contract $JAR --method withdraw \ --args $ACCOUNT$(enc_u128 50000000) --fee-token 1 --wait ``` `query` runs a method without sending an op, so it costs nothing and changes nothing. From a web app or a script, use the [TypeScript SDK](https://ksana.network/docs/sdk/) instead. The default `--max-gas` of `ksana-cli` is 1,000,000. A deployment costs 100,000 gas plus 20 per byte of code, plus its `init`; the 28,720-byte token of the tutorial used 776,169 gas. A call costs 20,000 plus 1 per byte of the contract’s code, plus 10,000 per attached asset, plus what the method uses. ## Call other contracts A contract calls another with `sdk::call`, which returns the bytes inside the callee’s `Ok`. Any failure of the callee fails the whole op: ```rust /// Reads `account`'s balance in a contract with the token example's interface. pub fn token_balance(token: &[u8; 32], account: &[u8; 32]) -> Result> { sdk::decode(&sdk::call(token, "balance_of", account)) } ``` `sdk::call_with_funds` attaches assets from the calling contract’s own balance. List them in ascending order of asset ID, at most 16: ```rust /// Swaps `amount` of this contract's KSA in a pool of the amm example; returns what it got. pub fn swap_ksa(pool: &[u8; 32], amount: u128, min_out: u128) -> Result> { let args = sdk::encode(&(KSA_ASSET_ID, amount, min_out)); let funds = [sdk::Funds { asset: KSA_ASSET_ID, amount, }]; sdk::decode(&sdk::call_with_funds(pool, "swap", &args, &funds)) } ``` `sdk::try_call` catches the callee’s failure instead: only the callee’s changes roll back, and the caller continues with `CallError::Revert(reason)` or `CallError::Failed`. Use it where a failure elsewhere must not undo your own work: ```rust /// Sends `amount` of a token this contract holds to `to`; reports a refusal instead of failing. pub fn try_pay(token: &[u8; 32], to: &[u8; 32], amount: u128) -> CallResult { match sdk::try_call(token, "transfer", &sdk::encode(&(to, amount))) { Ok(_) => sdk::ok(&true), Err(sdk::CallError::Revert(reason)) => { sdk::emit(&("payment_refused", reason)); sdk::ok(&false) } Err(sdk::CallError::Failed) => sdk::ok(&false), } } ``` `try_call_with` adds funds and a gas limit for the callee. `delegate_call` runs another contract’s code inside your own context (your storage, your balances, your caller), for proxy patterns with code you trust. Calls can nest 8 levels deep, counting the op’s own call as the first, and a contract can be re-entered. ## Create contracts A contract can create another from code that is already on chain, that is, code some account stored with an earlier deployment. The new contract’s ID is the SHA-256 of the creating contract’s ID, a 32-byte salt and the code hash, so it is known in advance: ```rust /// Creates a contract from code already on chain; the salt makes one contract per `init_args`. pub fn create(code_hash: &[u8; 32], init_args: &[u8]) -> [u8; 32] { let salt = sdk::sha256(init_args); sdk::create_contract(code_hash, &salt, init_args, &[]) } /// The ID that `create` gives for these arguments, known before the contract exists. pub fn created_id(code_hash: &[u8; 32], init_args: &[u8]) -> [u8; 32] { sdk::created_contract_id(&sdk::self_id(), &sdk::sha256(init_args), code_hash) } ``` The new contract’s `init` runs at once, with the creating contract as its caller. `create_contract` traps when the code is not on chain, when the ID is taken (the same salt twice), or when `init` fails. The `amm-factory` example creates one pool per pair of assets this way. ## Limits | Limit | Value | | --- | --- | | Storage key / value | 256 / 65,536 bytes | | Event | 16,384 bytes | | Call input / return value | 65,536 bytes each | | Assets attached to one call | 16 | | Nested calls | 8 levels | | Instances / memory in one op | 64 / 256 MiB | | Memory of one instance | 16 MiB | | Stack of one instance | 262,144 bytes, by the node’s estimate | | Op size, code included | 65,536 bytes | | Gas of one op | `max_gas`, at most 100,000,000; 1,000,000 for a path C op | These limits are the same on devnet, the signet and mainnet. [Host functions and gas](https://ksana.network/docs/host-functions/) lists the gas of every operation, and [Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/) shows how a contract reads Bitcoin. To write contracts with an AI assistant, give it the [reference for AI assistants](https://ksana.network/llms-contracts.txt) first: everything on this page and the SDK’s, gas, limits and complete contracts in one file, which the playground’s [AI assistants](https://playground.ksana.network/#/ai) page copies in one click. --- # The contract SDK URL: https://ksana.network/docs/contract-sdk/ > Every function, type and constant of ksana-contract-sdk, the Rust crate Ksana contracts are written with, as its signatures with a line on what each does. `ksana-contract-sdk` is the crate in `crates/ksana-contract-sdk` of the [repository](https://github.com/ksana-in-bitcoin/ksana). On `wasm32-unknown-unknown` it is `no_std`, and its functions call the node’s [host functions](https://ksana.network/docs/host-functions/); on any other target the same functions run on an in-memory mock host, so `cargo test` runs a contract without a node. The SDK is not published on crates.io: [Write a contract](https://ksana.network/docs/contracts/#set-up-a-project) adds it by path, and the [playground](https://ksana.network/docs/playground/) builds against it in the browser. This page lists everything the SDK exports, as Rust signatures without their bodies, each with the line that says what it does. [Host functions and gas](https://ksana.network/docs/host-functions/) gives the gas of every call that reaches the node, and [Your first contract](https://ksana.network/docs/first-contract/) uses the most common ones. **For AI assistants.** The same listing, with the rules a contract follows, gas, limits and complete contracts, is one Markdown file: [https://ksana.network/llms-contracts.txt](https://ksana.network/llms-contracts.txt). Give it to ChatGPT, Claude or any other assistant before you ask it for a contract. The playground’s [AI assistants](https://playground.ksana.network/#/ai) page copies it in one click. ## A contract’s frame Every contract has the same frame: no standard library on WebAssembly, one exported entry point, and a `dispatch` function that answers each method by its name. ```rust title="src/lib.rs" #![cfg_attr(target_arch = "wasm32", no_std)] extern crate alloc; use ksana_contract_sdk::{self as sdk, CallResult}; sdk::entry!(dispatch); pub fn dispatch(method: &str, args: &[u8]) -> CallResult { match method { "init" => { sdk::decode::<()>(args)?; sdk::ok(&()) } _ => sdk::revert("unknown method"), } } ``` - `sdk::entry!(dispatch)` generates the module’s exports, `ksana_alloc` and `ksana_call`, on WebAssembly only: they decode the method’s name and its arguments and hand them to `dispatch`. - Deployment always calls `init`, so `dispatch` answers it even when it takes no arguments. After deployment, a call to `init` fails. - `sdk::ok(&value)` returns a value, and `sdk::revert("reason")` reverts: everything the operation did is undone, at every level, and the reason is what the user sees. - A host function traps when it is misused: a key that is too long, a transfer the balance cannot cover, an asset that does not exist, a movement the asset’s rules refuse. So does a panic, such as an `unwrap` of `None` or an index out of bounds. A trap fails the operation without a reason a user can read, so check first and revert with one. ## Call context and encoding Arguments and return values are Borsh: a method’s arguments are a tuple encoded back to back, one argument is encoded as itself, and none is empty bytes. `decode` requires every byte to be used and returns `Err(b"malformed arguments")` otherwise, so `?` turns bad input into a revert. ```rust // ksana_contract_sdk /// What a method returns: `Ok(data)`, or `Err(reason)` to revert. pub type CallResult = Result, Vec>; /// Decodes all of `bytes` as `T`; `Err(ERR_MALFORMED_ARGS)` when they do not fit, for `?`. pub fn decode(bytes: &[u8]) -> Result>; /// Borsh-encodes `value`. pub fn encode(value: &T) -> Vec; /// `Ok(encode(value))`. pub fn ok(value: &T) -> CallResult; /// `Err(reason)`: reverts the whole operation with `reason`. pub fn revert(reason: &str) -> Result>; pub const ERR_MALFORMED_ARGS: &[u8] = b"malformed arguments"; /// Borsh decoding without `core::fmt`; implemented for the integers, `bool` (0 or 1), `[u8; N]`, `Vec`, `String`, /// `Option`, `Result`, `()`, tuples of up to 8 elements, `Funds`, `AssetMetaInput`, `NativeTx`, /// `NativeOutput` and `standard::AssetRef`. pub trait Decode: Sized { fn decode(input: &mut &[u8]) -> Option; } /// The caller: the signing account at the top level, the calling contract in a call from a contract. pub fn caller() -> [u8; 32]; /// This contract's ID. pub fn self_id() -> [u8; 32]; /// The height of the block running the operation. pub fn block_height() -> u64; /// The block's timestamp in Unix seconds, set by its producer within the consensus rules: not a precise time. pub fn block_timestamp() -> u64; /// 1001 devnet, 1002 signet, 1000 mainnet. pub fn chain_id() -> u32; /// The gas left to this call. pub fn gas_left() -> u64; /// Aborts the operation (a trap, without a reason); revert instead whenever there is one. pub fn trap() -> !; /// Records an event (raw bytes); events are rolled back with a failed operation. pub fn emit_event(data: &[u8]); /// Records the Borsh encoding of `event`, by convention a tuple whose first element is the event's name. pub fn emit(event: &T); pub fn sha256(data: &[u8]) -> [u8; 32]; /// `sha256(sha256(data))`, as Bitcoin hashes. pub fn sha256d(data: &[u8]) -> [u8; 32]; /// BIP340: a 32-byte x-only key, a 32-byte message digest, a 64-byte signature. pub fn verify_schnorr(pubkey: &[u8; 32], msg: &[u8; 32], sig: &[u8; 64]) -> bool; /// `sha256(deployer ‖ nonce as u64 little-endian ‖ code_hash)`: the ID of a contract an account deployed. pub fn contract_id(deployer: &[u8; 32], nonce: u64, code_hash: &[u8; 32]) -> [u8; 32]; ``` A struct of your own encodes with Borsh’s derive, which the SDK re-exports, and decodes with a `Decode` implementation that reads its fields in the same order: ```rust use ksana_contract_sdk::borsh::BorshSerialize; use ksana_contract_sdk::Decode; /// A listing, as methods take and return it: Borsh lays out its fields in order. #[derive(BorshSerialize)] #[borsh(crate = "ksana_contract_sdk::borsh")] pub struct Listing { pub price: u128, pub seller: [u8; 32], } impl Decode for Listing { fn decode(input: &mut &[u8]) -> Option { Some(Self { price: u128::decode(input)?, seller: <[u8; 32]>::decode(input)?, }) } } ``` ## Built-in assets and attached funds KSA and the assets contracts issue live in one balance table, which accounts and contracts share. The funds an operation or another contract attaches to a call are in the contract’s balance before it runs: a method that takes none refuses them, or they stay in the contract for good. [Assets and tokens](https://ksana.network/docs/tokens/) explains when to issue a built-in asset and when to write a token contract, and [Host functions](https://ksana.network/docs/host-functions/#assets) the rules every movement of an asset obeys. ```rust // ksana_contract_sdk /// KSA's asset ID: 32 zero bytes. pub const KSA_ASSET_ID: [u8; 32] = [0u8; 32]; /// An asset and an amount attached to a call; Borsh-encodable, `Decode`. pub struct Funds { pub asset: [u8; 32], pub amount: u128 } /// The most assets one call attaches. pub const MAX_CALL_FUNDS: usize = 16; /// The funds attached to this call, already in this contract's balance, in ascending asset ID order. pub fn call_funds() -> Vec; /// The amount of `asset` attached to this call; 0 when none. pub fn received(asset: &[u8; 32]) -> u128; pub fn asset_balance(asset: &[u8; 32], account: &[u8; 32]) -> u128; /// Pays `amount` of `asset` from this contract's balance to `to`; traps when the balance is short. pub fn asset_transfer(asset: &[u8; 32], to: &[u8; 32], amount: u128); /// Burns `amount` of this contract's own balance of `asset`, KSA included. pub fn asset_burn(asset: &[u8; 32], amount: u128); /// A new asset's name (1 to 64 bytes), symbol (1 to 16 bytes) and decimals (at most 18); Borsh-encodable, `Decode`. pub struct AssetMetaInput { pub name: String, pub symbol: String, pub decimals: u8 } /// Issues `amount` of this contract's asset `sub_id` to `to` and returns its ID. The first issue creates the asset with /// `CAP_MINT` alone and records `meta`; every later one passes the same `meta` and needs `CAP_MINT` still. pub fn asset_issue(sub_id: &[u8; 32], meta: &AssetMetaInput, to: &[u8; 32], amount: u128) -> [u8; 32]; /// Creates this contract's asset `sub_id` with the issuer capabilities `capabilities` (`CAP_*` bits) and issues /// `amount` of it (0 for none) to `to`; traps when the asset exists. Without `CAP_MINT` the supply stays `amount` for /// good; with `CAP_ALLOWLIST`, `to` must be this contract until it allows an account. pub fn asset_create(sub_id: &[u8; 32], meta: &AssetMetaInput, capabilities: u8, to: &[u8; 32], amount: u128) -> [u8; 32]; /// `sha256(issuer ‖ sub_id)`: the ID of the asset a contract issues. pub fn asset_id(issuer: &[u8; 32], sub_id: &[u8; 32]) -> [u8; 32]; /// Issuer capabilities, declared by `asset_create` and only ever given up. pub const CAP_MINT: u8 = 1; pub const CAP_FREEZE: u8 = 2; pub const CAP_ALLOWLIST: u8 = 4; pub const CAP_PAUSE: u8 = 8; /// Freezes or unfreezes `account` for this contract's asset, never this contract itself (freezing needs `CAP_FREEZE`): /// a frozen account can neither send, receive nor burn it. pub fn asset_freeze(sub_id: &[u8; 32], account: &[u8; 32], frozen: bool); /// Puts `account` on or off the allowlist of this contract's asset (putting it on needs `CAP_ALLOWLIST`). pub fn asset_allow(sub_id: &[u8; 32], account: &[u8; 32], allowed: bool); /// Pauses or resumes this contract's asset (pausing needs `CAP_PAUSE`). pub fn asset_pause(sub_id: &[u8; 32], paused: bool); /// Gives up capabilities of this contract's asset for good. pub fn asset_renounce(sub_id: &[u8; 32], capabilities: u8); /// The capabilities an asset's issuer still holds and whether it is paused. pub struct AssetPolicy { pub capabilities: u8, pub paused: bool } /// `None` when the asset does not exist; KSA has no capabilities. pub fn asset_policy(asset: &[u8; 32]) -> Option; /// An account's `STATUS_*` flags for an asset. pub fn asset_status(asset: &[u8; 32], account: &[u8; 32]) -> u8; pub const STATUS_FROZEN: u8 = 1; pub const STATUS_ALLOWED: u8 = 2; ``` ## Calling and creating contracts A call to another contract runs it at once, inside the same operation, and its failure fails the whole operation unless `try_call` catches it. Calls nest 8 levels deep and may re-enter the caller, so write your storage before you call out. [Write a contract](https://ksana.network/docs/contracts/#call-other-contracts) shows each of these in use. ```rust // ksana_contract_sdk /// Calls `method` of `contract` and returns the bytes in its `Ok`; any failure of the callee fails the operation. /// The method name `init` is refused. pub fn call(contract: &[u8; 32], method: &str, args: &[u8]) -> Vec; /// As `call`, attaching `funds` from this contract's balance (strictly ascending asset IDs, amounts above 0). pub fn call_with_funds(contract: &[u8; 32], method: &str, args: &[u8], funds: &[Funds]) -> Vec; /// How a caught call failed: the callee's revert reason, or any other failure. pub enum CallError { Revert(Vec), Failed } /// As `call`, but a failure undoes only the callee's level and comes back as `Err`. The callee gets at most 63/64 of /// the gas left, and a failure other than a revert uses up what it got. pub fn try_call(contract: &[u8; 32], method: &str, args: &[u8]) -> Result, CallError>; /// `try_call` with attached funds and a gas limit for the callee (0: no limit beyond 63/64). pub fn try_call_with(contract: &[u8; 32], method: &str, args: &[u8], funds: &[Funds], gas: u64) -> Result, CallError>; /// Runs `contract`'s code in this contract's context (its storage, balances, caller and funds): trusted code only. pub fn delegate_call(contract: &[u8; 32], method: &str, args: &[u8]) -> Vec; /// Creates a contract from code already on chain (`code_hash = sha256(code)`, stored by an earlier deployment) and runs /// its `init(init_args)` with this contract as the caller, `funds` moved to it first; returns /// `created_contract_id(self_id(), salt, code_hash)`. Fails the operation when the code is unknown, the ID is taken or /// `init` fails. pub fn create_contract(code_hash: &[u8; 32], salt: &[u8; 32], init_args: &[u8], funds: &[Funds]) -> [u8; 32]; /// `sha256(creator ‖ salt ‖ code_hash)`. pub fn created_contract_id(creator: &[u8; 32], salt: &[u8; 32], code_hash: &[u8; 32]) -> [u8; 32]; ``` ## Bitcoin A contract reads the headers of Bitcoin blocks at least 6 below the block it anchors to, and the Bitcoin transaction that carried a path C operation. The `btc` module parses headers and transactions and checks Merkle proofs inside the contract; [Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/) builds a payment check with it. ```rust // ksana_contract_sdk /// The Bitcoin height the current block anchors to. pub fn btc_anchor_height() -> u32; /// The 80-byte Bitcoin header at `height`, which must be at most `btc_anchor_height() - 6`; traps otherwise. pub fn btc_header(height: u32) -> [u8; 80]; /// An output of the Bitcoin transaction carrying a path C operation. pub struct NativeOutput { pub value: u64, pub script: Vec } /// That transaction: its ID (internal byte order) and every output. pub struct NativeTx { pub txid: [u8; 32], pub outputs: Vec } /// The transaction carrying this operation when it came by path C; `None` for path B and read-only calls. Every level /// of one operation reads the same transaction, so record what it paid for to credit it once. pub fn native_tx() -> Option; ``` ```rust // ksana_contract_sdk::btc pub const HEADER_LEN: usize = 80; pub const MAX_MONEY: u64 = 21_000_000 * 100_000_000; pub const MAX_COMPACT_SIZE: u64 = 0x0200_0000; pub const MAX_MERKLE_DEPTH: usize = 32; /// A parsed block header; hashes in Bitcoin's internal byte order. pub struct BlockHeader { pub version: i32, pub prev_blockhash: [u8; 32], pub merkle_root: [u8; 32], pub time: u32, pub bits: u32, pub nonce: u32 } impl BlockHeader { pub fn parse(bytes: &[u8]) -> Option; pub fn to_bytes(&self) -> [u8; HEADER_LEN]; pub fn block_hash(&self) -> [u8; 32]; } /// An output of a parsed transaction. pub struct TxOut<'a> { pub value: u64, pub script_pubkey: &'a [u8] } /// `sha256d` of a transaction serialized without witness data. pub fn txid(raw_tx: &[u8]) -> [u8; 32]; /// The outputs of a transaction serialized without witness data; `None` when it is malformed. pub fn parse_outputs(raw_tx: &[u8]) -> Option>>; pub fn merkle_root_from_branch(leaf: &[u8; 32], index: u32, branch: &[[u8; 32]]) -> Option<[u8; 32]>; pub fn verify_merkle_branch(leaf: &[u8; 32], index: u32, branch: &[[u8; 32]], root: &[u8; 32]) -> bool; pub fn is_coinbase(raw_tx: &[u8]) -> bool; /// Proves `raw_tx` is transaction `index` of the block `header` and returns its ID; the same block's coinbase and its /// branch pin the tree's depth. A transaction is proven at its own `index` only. Guard replays by the returned ID. pub fn verify_tx_inclusion(header: &BlockHeader, raw_tx: &[u8], index: u32, branch: &[[u8; 32]], coinbase_tx: &[u8], coinbase_branch: &[[u8; 32]]) -> Option<[u8; 32]>; ``` ## Storage Each contract has its own key-value storage, which only it can write. A key is at most 256 bytes and a value at most 65,536. Storage cannot be listed or iterated, so keep counts and index keys yourself. A write costs 10,000 gas plus 10 per byte, a read 2,000 plus 1 per byte: store little, and remove a key whose value goes back to nothing. ```rust // ksana_contract_sdk::storage /// The raw value of `key`, `None` when absent. pub fn get(key: &[u8]) -> Option>; pub fn set(key: &[u8], value: &[u8]); pub fn remove(key: &[u8]); /// Reads and Borsh-decodes `key`: `Ok(None)` when absent, `Err(ERR_MALFORMED_STORAGE)` when it does not decode. pub fn read(key: &[u8]) -> Result, Vec>; /// Borsh-encodes `value` under `key`. pub fn write(key: &[u8], value: &T); pub const ERR_MALFORMED_STORAGE: &[u8] = b"malformed storage value"; ``` ## The mock host On any target but WebAssembly, the SDK runs contracts on an in-memory host, for `cargo test`. It follows the ABI: a failure at any level rolls the whole operation back, and the limits, the call depth and the rules of attached funds apply. It has no gas metering, KSA does not exist until `register_asset` and `mint` create it, and the `code` you pass to `deploy` is a label rather than your module, so contract IDs differ from those on chain. [Write a contract](https://ksana.network/docs/contracts/#test-it-natively) has complete tests. ```rust // ksana_contract_sdk::mock /// Clears everything. pub fn reset(); /// Deploys: the ID from `deployer`, `nonce` and `sha256(code)` (`code` is a label, not the module), then `init` as /// `deployer`; a failed `init` deploys nothing. pub fn deploy(deployer: [u8; 32], nonce: u64, code: &[u8], dispatch: impl Fn(&str, &[u8]) -> CallResult + 'static, init_args: &[u8]) -> Result<[u8; 32], Failure>; pub fn deploy_with_funds(deployer: [u8; 32], nonce: u64, code: &[u8], dispatch: impl Fn(&str, &[u8]) -> CallResult + 'static, init_args: &[u8], funds: &[Funds]) -> Result<[u8; 32], Failure>; /// An operation of `caller` calling `contract`; a failure at any level rolls everything back. pub fn call(caller: [u8; 32], contract: [u8; 32], method: &str, args: &[u8]) -> Result, Failure>; pub fn call_with_funds(caller: [u8; 32], contract: [u8; 32], method: &str, args: &[u8], funds: &[Funds]) -> Result, Failure>; /// Why an operation failed. pub enum Failure { Revert { contract: [u8; 32], reason: Vec }, Trap(String) } /// A dispatch function for `contract` without `init`, such as a stub of another contract. pub fn register(contract: [u8; 32], dispatch: impl Fn(&str, &[u8]) -> CallResult + 'static); /// Code that `create_contract` can create from; returns its hash. pub fn register_code(code: &[u8], dispatch: impl Fn(&str, &[u8]) -> CallResult + 'static) -> [u8; 32]; pub type Dispatch = Rc CallResult>; /// Runs `f` as `caller` calling `self_id`, without rollback, to test a contract's internals. pub fn with_context(caller: [u8; 32], self_id: [u8; 32], f: impl FnOnce() -> R) -> R; pub fn contract_exists(contract: &[u8; 32]) -> bool; pub fn storage_value(contract: &[u8; 32], key: &[u8]) -> Option>; /// An event a successful operation emitted. pub struct Event { pub contract: [u8; 32], pub data: Vec } pub fn events() -> Vec; pub fn clear_events(); /// Registers an asset with no supply (an issuer of 32 zero bytes, as KSA's, gets no capabilities, any other `CAP_MINT`). pub fn register_asset(asset: [u8; 32], name: &str, decimals: u8, issuer: [u8; 32]); /// Gives `account` `amount` of a registered asset. pub fn mint(asset: [u8; 32], account: [u8; 32], amount: u128) -> Result<(), Failure>; pub fn balance(asset: &[u8; 32], account: &[u8; 32]) -> u128; pub struct AssetInfo { pub name: String, pub symbol: String, pub decimals: u8, pub total_supply: u128, pub issuer: [u8; 32], pub capabilities: u8, pub paused: bool } pub fn asset_info(asset: &[u8; 32]) -> Option; pub fn set_asset_policy(asset: [u8; 32], capabilities: u8, paused: bool); pub fn set_account_status(asset: [u8; 32], account: [u8; 32], status: u8); pub fn account_status(asset: &[u8; 32], account: &[u8; 32]) -> u8; pub fn set_block_height(height: u64); pub fn set_block_timestamp(timestamp: u64); pub fn set_chain_id(chain_id: u32); pub fn set_gas_left(gas: u64); pub fn set_btc_anchor_height(height: u32); pub fn set_btc_header(height: u32, header: [u8; 80]); pub fn set_btc_query_depth(depth: u32); pub fn set_max_call_depth(depth: usize); /// `Some` makes the following operations path C operations carried by `tx`. pub fn set_native_tx(tx: Option); pub const DEFAULT_CHAIN_ID: u32 = 1001; pub const DEFAULT_GAS_LEFT: u64 = 1_000_000_000; pub const DEFAULT_BTC_QUERY_DEPTH: u32 = 6; pub const DEFAULT_MAX_CALL_DEPTH: usize = 8; pub const MAX_STORAGE_KEY_BYTES: usize = 256; pub const MAX_STORAGE_VALUE_BYTES: usize = 65_536; pub const MAX_EVENT_BYTES: usize = 16_384; pub const MAX_OUTPUT_BYTES: usize = 65_536; pub const MAX_OP_BYTES: usize = 65_536; pub const MAX_ASSET_META_BYTES: usize = 1_024; pub const MAX_ASSET_NAME_BYTES: usize = 64; pub const MAX_ASSET_SYMBOL_BYTES: usize = 16; pub const MAX_ASSET_DECIMALS: u8 = 18; ``` ## Token standards With the feature `standards`, the SDK holds the reference implementations of [KS-20](https://ksana.network/docs/ks-20/) tokens and [KS-721](https://ksana.network/docs/ks-721/) collections: a contract answers every standard method by calling `dispatch`, and `conformance` tests it against the standard on the mock host. The feature is off by default, since it changes the module even of a contract that does not use it. Turn it on in `Cargo.toml`: ```toml ksana-contract-sdk = { path = "../ksana/crates/ksana-contract-sdk", features = ["standards"] } ``` In the playground, the KS-20 token, KS-721 NFT and AMM pages build with it, and the others without. ### `standard` What both standards share: the zero account, the revert reasons, the capabilities a token lists, the answer of a receiving contract, and `AssetRef`, which names a token contract or a built-in asset in one argument. ```rust // ksana_contract_sdk::standard /// The zero account: the `from` of a mint and the `to` of a burn. pub const ZERO_ACCOUNT: [u8; 32] = [0u8; 32]; pub const STANDARDS: &str = "standards"; pub const METADATA: &str = "metadata"; pub const CAPABILITIES_VIEW: &str = "capabilities"; pub const ERR_UNKNOWN_METHOD: &[u8] = b"unknown method"; pub const ERR_UNEXPECTED_FUNDS: &[u8] = b"unexpected attached funds"; pub const ERR_ZERO_ACCOUNT: &[u8] = b"zero account"; pub const ERR_SELF_RECIPIENT: &[u8] = b"recipient is this contract"; pub const ERR_NOT_THE_MINTER: &[u8] = b"not the minter"; pub const ERR_MINTING_ENDED: &[u8] = b"minting has ended"; pub const ERR_ALREADY_INITIALIZED: &[u8] = b"already initialized"; pub const ERR_NOT_INITIALIZED: &[u8] = b"not initialized"; pub const ERR_NAME: &[u8] = b"name must be 1 to 64 bytes"; pub const ERR_SYMBOL: &[u8] = b"symbol must be 1 to 16 bytes"; pub const ERR_MALFORMED_RETURN: &[u8] = b"malformed return value"; pub const ERR_MISSING_INDEX: &[u8] = b"missing index entry"; pub const ERR_OVERFLOW: &[u8] = b"arithmetic overflow"; pub const REJECTED: &str = "rejected: "; pub const MAX_NAME_BYTES: usize = 64; pub const MAX_SYMBOL_BYTES: usize = 16; pub const CAP_MINT: &str = "mint"; pub const CAP_FREEZE: &str = "freeze"; pub const CAP_ALLOWLIST: &str = "allowlist"; pub const CAP_PAUSE: &str = "pause"; pub const CAP_CLAWBACK: &str = "clawback"; pub const CAP_FEE: &str = "fee"; pub const CAP_UPGRADE: &str = "upgrade"; /// The order a `capabilities()` view lists them in. pub const CAPABILITIES: [&str; 7] = [CAP_MINT, CAP_FREEZE, CAP_ALLOWLIST, CAP_PAUSE, CAP_CLAWBACK, CAP_FEE, CAP_UPGRADE]; /// `rejected: `: a refusal by the contract's own rules. pub fn rejected(reason: &str) -> Vec; pub fn is_rejection(reason: &[u8]) -> bool; /// Reverts with `unexpected attached funds` when funds are attached. pub fn no_funds() -> Result<(), Vec>; /// Reverts unless `to` is neither the zero account nor this contract. pub fn check_recipient(to: &[u8; 32]) -> Result<(), Vec>; pub fn check_name(name: &str) -> Result<(), Vec>; pub fn check_symbol(symbol: &str) -> Result<(), Vec>; /// The answer of `on_token_received` or `on_nft_received`: `value`'s Borsh bytes as `Bytes`. pub fn reply(value: &T) -> CallResult; /// Whether an allowance or operator expiring at `expires_at` has expired at this block's timestamp. pub fn expired(expires_at: Option) -> bool; /// The standards `contract` declares, `None` when it answers no list (a caught call). pub fn standards_of(contract: &[u8; 32]) -> Option>; pub fn declares(contract: &[u8; 32], id: &str) -> bool; /// A fungible asset of either kind in one argument: Borsh tag 0 and a token contract's ID, or tag 1 and a built-in /// asset's ID (KSA: 1 and 32 zero bytes). pub enum AssetRef { Token([u8; 32]), Asset([u8; 32]) } impl AssetRef { pub fn id(&self) -> [u8; 32]; /// The token's `balance_of`, or the built-in balance. pub fn balance_of(&self, account: &[u8; 32]) -> Result>; /// Pays from this contract's balance: the token's `transfer`, or `asset_transfer`. pub fn pay(&self, to: &[u8; 32], amount: u128); } ``` ### `ks20` A KS-20 token in one constant, `const TOKEN: Ks20 = Ks20::new().burnable();`, and `Token`, for calling any KS-20 token from another contract. ```rust // ksana_contract_sdk::ks20 pub const ID: &str = "KS-20"; pub const BURNABLE: &str = "KS-20-burnable"; pub const MINTABLE: &str = "KS-20-mintable"; pub const ON_RECEIVED: &str = "on_token_received"; pub const MAX_DECIMALS: u8 = 18; /// An allowance that never goes down. pub const UNLIMITED: u128 = u128::MAX; pub const ERR_ZERO_AMOUNT: &[u8] = b"zero amount"; pub const ERR_INSUFFICIENT_BALANCE: &[u8] = b"insufficient balance"; pub const ERR_INSUFFICIENT_ALLOWANCE: &[u8] = b"insufficient allowance"; pub const ERR_ALLOWANCE_EXPIRED: &[u8] = b"allowance expired"; pub const ERR_SPENDER_IS_CALLER: &[u8] = b"spender is the caller"; pub const ERR_DECIMALS: &[u8] = b"decimals must be at most 18"; pub const ERR_CAP_EXCEEDED: &[u8] = b"cap exceeded"; pub const ERR_SUPPLY_OVERFLOW: &[u8] = b"supply overflow"; pub const REASON_FEE: &str = "the fee takes the whole amount"; /// A KS-20 token to call from another contract: `Token(id).balance_of(&account)?`. pub struct Token(pub [u8; 32]); impl Token { pub fn standards(&self) -> Result, Vec>; pub fn metadata(&self) -> Result<(String, String, u8), Vec>; pub fn total_supply(&self) -> Result>; pub fn balance_of(&self, account: &[u8; 32]) -> Result>; pub fn allowance(&self, owner: &[u8; 32], spender: &[u8; 32]) -> Result>; /// Sends this contract's tokens. pub fn transfer(&self, to: &[u8; 32], amount: u128); /// Takes tokens with the allowance `from` gave this contract. pub fn transfer_from(&self, from: &[u8; 32], to: &[u8; 32], amount: u128); pub fn approve(&self, spender: &[u8; 32], amount: u128, expires_at: Option); pub fn transfer_and_call(&self, to: &[u8; 32], amount: u128, data: &[u8], funds: &[Funds]) -> Result, Vec>; /// `transfer` that returns the token's refusal instead of failing the operation. pub fn try_transfer(&self, to: &[u8; 32], amount: u128) -> Result<(), CallError>; pub fn try_transfer_from(&self, from: &[u8; 32], to: &[u8; 32], amount: u128) -> Result<(), CallError>; } /// What `on_token_received` got: `token` is its caller, and `from` and `amount` are true only when that is a token /// this contract accepts. pub struct Received { pub token: [u8; 32], pub from: [u8; 32], pub amount: u128, pub data: Vec } /// Decodes the arguments of `on_token_received`. pub fn received(args: &[u8]) -> Result>; pub enum Event { Standards(Vec), Metadata { name: String, symbol: String, decimals: u8 }, Transfer { from: [u8; 32], to: [u8; 32], amount: u128 }, Approve { owner: [u8; 32], spender: [u8; 32], amount: u128, expires_at: Option }, Minter { previous: Option<[u8; 32]>, minter: Option<[u8; 32]> }, } impl Event { pub fn parse(data: &[u8]) -> Option; pub fn encode(&self) -> Vec; pub fn emit(&self); } /// A token's own rules; every method has a default of none. pub trait Policy { /// Before every change of a balance (a mint is from the zero account, a burn to it); refuse with `rejected(…)`. fn check(&self, from: &[u8; 32], to: &[u8; 32], amount: u128) -> Result<(), Vec>; /// `Some((account, fee))` takes `fee` out of a transfer's amount for `account`. fn fee(&self, from: &[u8; 32], to: &[u8; 32], amount: u128) -> Result, Vec>; /// The capabilities these rules give someone now, such as `freeze`. fn capabilities(&self) -> Result, Vec>; } pub struct NoPolicy; /// The reference implementation, as a `const` of the token: `const TOKEN: Ks20 = Ks20::new().burnable();`. pub struct Ks20

{ .. } impl Ks20 { pub const fn new() -> Self; pub const fn burnable(self) -> Self; pub const fn mintable(self) -> Self; pub const fn with_policy(self, policy: Q) -> Ks20; } impl Ks20

{ /// Answers every standard method the token has; `None` for the others, `init` included. pub fn dispatch(&self, method: &str, args: &[u8]) -> Option; /// Records the metadata and emits the declaration, in `init` before any mint. pub fn init(&self, name: &str, symbol: &str, decimals: u8) -> Result<(), Vec>; /// `KS-20-mintable`: the first minter and the cap, in `init` after `init`. pub fn init_minter(&self, minter: Option<[u8; 32]>, cap: Option) -> Result<(), Vec>; pub fn policy(&self) -> &P; pub fn standards(&self) -> Vec; pub fn metadata(&self) -> Result<(String, String, u8), Vec>; pub fn set_metadata(&self, name: &str, symbol: &str) -> Result<(), Vec>; pub fn capabilities(&self) -> Result, Vec>; pub fn total_supply(&self) -> Result>; pub fn balance_of(&self, account: &[u8; 32]) -> Result>; pub fn allowance(&self, owner: &[u8; 32], spender: &[u8; 32]) -> Result>; pub fn allowance_info(&self, owner: &[u8; 32], spender: &[u8; 32]) -> Result<(u128, Option), Vec>; pub fn minter(&self) -> Result, Vec>; pub fn cap(&self) -> Result, Vec>; /// Sets the minter (the method checks the caller first); `None` ends minting. pub fn set_minter(&self, minter: Option<[u8; 32]>) -> Result<(), Vec>; /// Moves `amount` from `from` to `to` by the token's rules; returns what `to` received. pub fn transfer(&self, from: &[u8; 32], to: &[u8; 32], amount: u128) -> Result>; pub fn transfer_from(&self, spender: &[u8; 32], from: &[u8; 32], to: &[u8; 32], amount: u128) -> Result>; pub fn transfer_and_call(&self, from: &[u8; 32], to: &[u8; 32], amount: u128, data: &[u8]) -> Result, Vec>; pub fn approve(&self, owner: &[u8; 32], spender: &[u8; 32], amount: u128, expires_at: Option) -> Result<(), Vec>; pub fn spend_allowance(&self, owner: &[u8; 32], spender: &[u8; 32], amount: u128) -> Result<(), Vec>; /// Creates tokens for `to`, up to the cap; the token's own minting method checks the caller first. pub fn mint(&self, to: &[u8; 32], amount: u128) -> Result<(), Vec>; pub fn burn(&self, from: &[u8; 32], amount: u128) -> Result<(), Vec>; pub fn burn_from(&self, spender: &[u8; 32], from: &[u8; 32], amount: u128) -> Result<(), Vec>; } ``` ### `ks721` A KS-721 collection in one constant, `const NFT: Ks721 = Ks721::new().burnable().enumerable();`, and `Collection`, for calling any collection from another contract. The collection writes its own `init` and its own minting method. ```rust // ksana_contract_sdk::ks721 pub const ID: &str = "KS-721"; pub const BURNABLE: &str = "KS-721-burnable"; pub const ENUMERABLE: &str = "KS-721-enumerable"; pub const ON_RECEIVED: &str = "on_nft_received"; pub const MAX_URI_BYTES: usize = 2_048; pub const MAX_PAGE: u32 = 100; pub type TokenId = [u8; 32]; pub const ERR_UNKNOWN_TOKEN: &[u8] = b"unknown token"; pub const ERR_NOT_THE_OWNER: &[u8] = b"not the owner"; pub const ERR_NOT_AUTHORIZED: &[u8] = b"not authorized"; pub const ERR_WRONG_OWNER: &[u8] = b"wrong owner"; pub const ERR_ALREADY_THE_OWNER: &[u8] = b"already the owner"; pub const ERR_SPENDER_IS_OWNER: &[u8] = b"spender is the owner"; pub const ERR_OPERATOR_IS_CALLER: &[u8] = b"operator is the caller"; pub const ERR_TOKEN_EXISTS: &[u8] = b"token exists"; pub const ERR_TOKEN_BURNED: &[u8] = b"token was burned"; pub const ERR_URI_TOO_LONG: &[u8] = b"uri too long"; /// The ID of serial number `n`: `n` big-endian in the last 16 bytes. pub fn id(n: u128) -> TokenId; /// The serial number of an ID whose first 16 bytes are zero. pub fn serial(token_id: &TokenId) -> Option; /// A KS-721 collection to call from another contract. pub struct Collection(pub [u8; 32]); impl Collection { pub fn standards(&self) -> Result, Vec>; pub fn metadata(&self) -> Result<(String, String), Vec>; pub fn owner_of(&self, token_id: &TokenId) -> Result, Vec>; pub fn balance_of(&self, owner: &[u8; 32]) -> Result>; pub fn token_uri(&self, token_id: &TokenId) -> Result, Vec>; pub fn transfer(&self, to: &[u8; 32], token_id: &TokenId); pub fn transfer_from(&self, from: &[u8; 32], to: &[u8; 32], token_id: &TokenId); pub fn approve(&self, spender: Option<&[u8; 32]>, token_id: &TokenId); pub fn set_operator(&self, operator: &[u8; 32], approved: bool, expires_at: Option); pub fn transfer_and_call(&self, to: &[u8; 32], token_id: &TokenId, data: &[u8], funds: &[Funds]) -> Result, Vec>; pub fn try_transfer(&self, to: &[u8; 32], token_id: &TokenId) -> Result<(), CallError>; pub fn try_transfer_from(&self, from: &[u8; 32], to: &[u8; 32], token_id: &TokenId) -> Result<(), CallError>; } /// What `on_nft_received` got; `collection` is its caller. pub struct Received { pub collection: [u8; 32], pub from: [u8; 32], pub token_id: TokenId, pub data: Vec } pub fn received(args: &[u8]) -> Result>; pub enum Event { Standards(Vec), Metadata { name: String, symbol: String }, Transfer { from: [u8; 32], to: [u8; 32], token_id: TokenId }, Approve { owner: [u8; 32], spender: Option<[u8; 32]>, token_id: TokenId }, Operator { owner: [u8; 32], operator: [u8; 32], approved: bool, expires_at: Option }, Uri(Option), } impl Event { pub fn parse(data: &[u8]) -> Option; pub fn encode(&self) -> Vec; pub fn emit(&self); } /// A collection's own rules; every method has a default of none. pub trait Policy { /// Before every change of owner (a mint is from the zero account, a burn to it). fn check(&self, from: &[u8; 32], to: &[u8; 32], token_id: &TokenId) -> Result<(), Vec>; fn capabilities(&self) -> Result, Vec>; } pub struct NoPolicy; /// The reference implementation: `const NFT: Ks721 = Ks721::new().burnable().enumerable();`. pub struct Ks721

{ .. } impl Ks721 { pub const fn new() -> Self; pub const fn burnable(self) -> Self; pub const fn enumerable(self) -> Self; pub const fn with_policy(self, policy: Q) -> Ks721; } impl Ks721

{ /// Answers every standard method the collection has; `None` for the others, `init` and minting included. pub fn dispatch(&self, method: &str, args: &[u8]) -> Option; pub fn init(&self, name: &str, symbol: &str) -> Result<(), Vec>; pub fn policy(&self) -> &P; pub fn standards(&self) -> Vec; pub fn metadata(&self) -> Result<(String, String), Vec>; pub fn set_metadata(&self, name: &str, symbol: &str) -> Result<(), Vec>; pub fn capabilities(&self) -> Result, Vec>; pub fn owner_of(&self, token_id: &TokenId) -> Result, Vec>; pub fn balance_of(&self, owner: &[u8; 32]) -> Result>; pub fn token_uri(&self, token_id: &TokenId) -> Result, Vec>; pub fn approved(&self, token_id: &TokenId) -> Result, Vec>; pub fn operator_info(&self, owner: &[u8; 32], operator: &[u8; 32]) -> Result<(bool, Option), Vec>; pub fn is_operator(&self, owner: &[u8; 32], operator: &[u8; 32]) -> Result>; pub fn is_burned(&self, token_id: &TokenId) -> bool; /// Whether `account` may move `owner`'s token: the owner, the approved account or an operator. pub fn may_move(&self, account: &[u8; 32], owner: &[u8; 32], token_id: &TokenId) -> Result>; pub fn transfer(&self, caller: &[u8; 32], to: &[u8; 32], token_id: &TokenId) -> Result<(), Vec>; pub fn transfer_from(&self, caller: &[u8; 32], from: &[u8; 32], to: &[u8; 32], token_id: &TokenId) -> Result<(), Vec>; pub fn transfer_and_call(&self, caller: &[u8; 32], to: &[u8; 32], token_id: &TokenId, data: &[u8]) -> Result, Vec>; pub fn approve(&self, caller: &[u8; 32], spender: Option<&[u8; 32]>, token_id: &TokenId) -> Result<(), Vec>; pub fn set_operator(&self, owner: &[u8; 32], operator: &[u8; 32], approved: bool, expires_at: Option) -> Result<(), Vec>; /// Mints a new ID to `to`; an ID minted before, even burned, is refused. pub fn mint(&self, to: &[u8; 32], token_id: &TokenId, uri: Option<&str>) -> Result<(), Vec>; pub fn burn(&self, token_id: &TokenId) -> Result<(), Vec>; pub fn set_token_uri(&self, token_id: &TokenId, uri: Option<&str>) -> Result<(), Vec>; pub fn total_supply(&self) -> Result>; pub fn tokens(&self, start: u64, limit: u32) -> Result, Vec>; pub fn tokens_of(&self, owner: &[u8; 32], start: u64, limit: u32) -> Result, Vec>; } ``` ### `conformance` Native tests of a token or a collection against the standard, on the mock host: `conformance::ks20(setup)` returns `Ok(())` or the first check that failed. ```rust // ksana_contract_sdk::conformance /// Runs the KS-20 checks against the token `setup` deploys on the freshly reset mock host. pub fn ks20(setup: impl Fn() -> Ks20Subject) -> Outcome; pub fn ks721(setup: impl Fn() -> Ks721Subject) -> Outcome; pub type Outcome = Result<(), String>; /// The token and an account holding at least `MIN_BALANCE` that may send to the kit's accounts. pub struct Ks20Subject { pub token: [u8; 32], pub holder: [u8; 32] } /// The collection, an account owning at least `MIN_TOKENS`, and those tokens. pub struct Ks721Subject { pub collection: [u8; 32], pub holder: [u8; 32], pub tokens: Vec } pub const MIN_BALANCE: u128 = 100; pub const MIN_TOKENS: usize = 2; pub const ALICE: [u8; 32] = [0xA1; 32]; pub const BOB: [u8; 32] = [0xB2; 32]; pub const RECEIVER: [u8; 32] = [0xC3; 32]; pub const FUNDS_ASSET: [u8; 32] = [0xF4; 32]; pub const UNKNOWN_TOKEN: TokenId = [0xE5; 32]; ``` --- # Contract playground URL: https://ksana.network/docs/playground/ > Eight example contracts with a page each, on the public signet. Use them, edit their Rust source, compile it in the browser and deploy your version. The [contract playground](https://playground.ksana.network/) is a page of its own, beside the [signet wallet](https://ksana.network/docs/wallet/). It runs on the [public signet](https://ksana.network/docs/signet/), signs every operation in your own wallet and pays the fees in test KSA. The wallet links it from its top bar, its footer and its home, and from a contract's page. ## The examples | Example | What it shows | Crate | | --- | --- | --- | | Counter | the smallest contract: one number anyone can increase | `playground-counter` | | Built-in asset | a built-in asset that wallets list: mint up to a cap, burn, send | `mintable-token` | | KS-20 token | a [KS-20](https://ksana.network/docs/ks-20/) token: send, approve with an expiry, take with an allowance, burn, mint up to a cap | `token` | | KS-721 NFT | a [KS-721](https://ksana.network/docs/ks-721/) collection: mint, send, approve and sell for a fixed price | `nft` | | AMM | swaps between two assets, and liquidity shares that earn the fees | `amm` | | Lending | supply to earn interest, borrow against collateral, liquidations | `lending` | | Multisig | a wallet whose owners approve and run proposals together | `multisig` | | Vesting | tokens that release over time to a beneficiary | `vesting` | The built-in asset, KS-20 token and KS-721 NFT pages sit under one **Tokens** heading in the top bar, with a switch between the three standards. A contract opened by its ID on one of them moves to the page of its own standard, or to the page that already keeps it, and every asset ID and token contract ID links to its page in the explorer. Each example has four tabs: **App**, a page made for it; **Code**, its Rust source; **Methods**, a form for every method; and **Activity**, the operations this browser sent. The examples build on each other: the AMM, lending and vesting pages offer to deploy an asset first, the asset page starts a pool or a lending market with its asset filled in and links to vesting, and the KS-20 token page starts a pool with the token as a side. [Assets and tokens](https://ksana.network/docs/tokens/) explains when to use which. The crates live in `contracts/examples/` of the repository with their native tests; [Example contracts](https://ksana.network/docs/example-contracts/#playground-examples) lists them with the others. ## Start ### Connect a wallet Use Unisat, OneKey or Xverse with a Taproot (`tb1p…`) account on Bitcoin signet, as for [the signet wallet](https://ksana.network/docs/wallet/#connect). The playground asks the wallet for signatures only and never sees your keys. ### Get test KSA **Get test KSA** asks the faucet for 100 KSA, once a day for each account. Deployments and calls are path B operations that pay their fee in KSA, and a deployment's fee grows with the module's size. ### Deploy an example **Deploy new** fills in the example's `init` arguments, which you can change. Asset IDs and contract IDs look alike, so before anything is sent the page checks that each asset ID names an asset and that each of the AMM's token sides names a token contract, and offers the asset to use instead when an ID leads to one. Review the operation, then sign it in the wallet; the page shows the predicted contract ID until a block includes the deployment. To use a contract someone else deployed, open their link or **Open by ID**. ### Use it The **App** tab is the example's own page: swaps and liquidity for the AMM, supply, borrow and repay for lending, proposals for the multisig. A KS-20 side pays the pool with the token's own `transfer_and_call`, so a swap or a deposit is one operation with nothing to approve; a token written before KS-20 is pulled with its `transfer_from`, so the AMM page asks you to approve the amount for the pool first, with a button of its own. Every write goes through the same review, which runs the operation read-only against the latest state first and warns you when it would fail. ## Edit and compile The **Code** tab holds the example's `src/lib.rs`. The editor builds that one file against `ksana-contract-sdk`, as the repository builds the examples. [Your first contract](https://ksana.network/docs/first-contract/) writes a contract of your own here, step by step. - **Compile** sends the source to the compile service. Errors and warnings come back on their lines. - **Deploy this build** deploys your module as a new contract, and the forms of the **Methods** tab follow the ABI block of your source. The example's own **App** page may not match edited code, and says so. - The example's source, unchanged, compiles to the very module the playground ships, byte for byte (`playground/src/examples/wasm/builds.json` holds the hashes). An example's deployment can be checked against the source the page shows. - A copy of the playground without a compile service still deploys the published modules. Build a module yourself as [Example contracts](https://ksana.network/docs/example-contracts/#build-and-test-them) shows, and upload the `.wasm` on the **Code** tab. ### Limits of the compile service - One source of at most 128 KiB, built as one of the eight example crates, with that crate's dependencies and no others. The build runs without network access and stops after 120 seconds. - The module may be at most 1 MiB, but one operation carries at most 64 KiB, so a module that deploys stays below that. - Six builds a minute from one address. Builds wait in a short queue, and a full queue answers that the service is busy. ## With an AI assistant The playground’s **AI assistants** page ([`#/ai`](https://playground.ksana.network/#/ai)) holds a reference for ChatGPT, Claude, Gemini and other AI assistants: how Ksana contracts run, every function of the [contract SDK](https://ksana.network/docs/contract-sdk/), gas, limits, the token standards, the ABI block and complete contracts, in one Markdown file that the repository’s tests hold to the code. Copy it, download it, or open it as text at [https://ksana.network/llms-contracts.txt](https://ksana.network/llms-contracts.txt), and give it to the assistant before you ask for a contract. The page has prompts to start from. On an example’s **Code** tab, **Copy for an AI assistant** copies the reference together with the source in the editor, the page and the crate it builds as, and the compiler’s messages about that source, ending with what the assistant is to do: fix the errors, or what you ask next. **Only the code and errors** leaves the reference out, for a conversation that already has it. The text is English, which assistants follow best; copied from the Chinese page, it asks for answers in Chinese. The assistant answers with a whole `src/lib.rs` and the page that builds it: the Counter page for a contract on the plain SDK, the KS-20 token, KS-721 NFT or AMM page for one that uses the token standards. Paste it into that page’s **Code** tab and compile it before you deploy. ## The ABI block A contract describes its methods to the playground in its own documentation: a fenced block marked `abi` in the `//!` comment at the top of `src/lib.rs`, one declaration per line, with an optional `//` description. The counter's: ````rust //! ```abi //! init() // starts the count at 0 //! call increment() -> u64 // adds one; returns the new count //! call add(amount: u64) -> u64 // adds 1 to 1000 at a time; returns the new count //! view get() -> u64 // the count //! event changed(by: Account, value: u64) //! ``` ```` - `init` runs once, at deployment; `call` declares a method that changes state, sent as an operation; `view` one that only reads, run without a signature. `payable` before `init` or `call` means the method takes attached funds. - `struct` and `enum` declare the types the methods use, and `event` the events the contract emits. - Types: the integers `u8` to `u128` and `i8` to `i128`, `bool`, `String`, `Bytes`, `[u8; N]`, `Account`, `ContractId`, `AssetId`, `Hash`, `TokenId` (32 bytes each), `Option`, `Vec`, tuples, `()`, and the declared structs and enums; not an `Option` directly inside an `Option`, whose `Some(None)` would read as `None`. Arguments and results are Borsh, as for every Ksana contract ([Contracts](https://ksana.network/docs/contracts/)). The block is documentation for people as well: rustdoc shows it as a code block. A source without one still compiles and deploys, but gets no forms. ## Open a contract A contract's page in the [wallet's explorer](https://ksana.network/docs/wallet/#history-and-the-explorer) offers **Open in the playground**. A deployment of an example opens on that example's page; any other contract gets forms once you paste its source, or just its ABI block. On the playground's home, **Any contract** does the same with a contract ID. ## Things to know - The playground runs on the signet only. Signet KSA has no value, and the examples are for learning, not audited software. - A failed operation still pays its fee and uses its nonce. - The page remembers the contracts you deployed or opened, and the operations it sent, for each chain, which it names by its genesis block: after a network starts again from genesis, it lists none of the contracts from before. - Each write is recorded in this browser before it is sent. An operation whose answer was lost keeps its nonce reserved until the node shows it; **Release this nonce** removes only that local reservation and cancels nothing, since another node may still include the old operation. Clearing the site's data loses this protection. --- # Host functions and gas URL: https://ksana.network/docs/host-functions/ > The interface between a contract and the node that runs it: how a call enters the module, every host function with its SDK wrapper and its gas, and the limits. A contract talks to the node only through host functions: the functions of the WebAssembly import module `ksana`. With `ksana-contract-sdk` you call them through Rust wrappers and never touch pointers; this page also gives the raw interface, for tools and for contracts written without the SDK. [The contract SDK](https://ksana.network/docs/contract-sdk/) lists every wrapper with its Rust signature, and the rest of the SDK. The gas costs and limits on this page are consensus rules. They are the same on devnet, the signet and mainnet, and they change only through a protocol upgrade. The [ABI](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/ABI.md) in the repository is the full specification. ## How a call enters a contract Every call creates a new instance of the module, so linear memory never carries over from one call to the next. A call runs in three steps: 1. The node calls the export `ksana_alloc(len: i32) -> i32` to get a buffer, and writes the input into it: the Borsh encoding of `(method: String, args: Vec)`. 2. The node calls `ksana_call(ptr: i32, len: i32) -> i64`. 3. The returned `i64`, read as unsigned, is `(out_ptr << 32) | out_len`. It points at the Borsh encoding of `Result, Vec>`, whose tag is `0` for `Err` and `1` for `Ok`: `Ok(data)` returns `data`, and `Err(reason)` reverts. These all fail the call: a trap (including `unreachable`, an access out of bounds and division by zero), running out of gas, output that is not a valid `Result` encoding, output longer than 65,536 bytes, and `Err`. A failure at any level fails the whole op, except under `try_call_contract`. Host functions take pointers as `i32` offsets into the contract’s own memory, and an offset out of bounds traps. Functions that write a fixed-size result take a destination pointer `dst`. Functions that return data of variable length allocate it by calling the contract’s `ksana_alloc` and return it packed the same way, `(ptr << 32) | len`, or `-1` when there is nothing. `entry!` in the SDK generates the two exports and does this decoding for you. ## Host functions The tables group the 31 functions by purpose. “/B” means per byte. ### Storage | Host function | SDK | Gas | Notes | | --- | --- | --- | --- | | `storage_get` | `storage::get`, `storage::read` | 2,000 + 1/B of key and value | reads this contract’s storage; `None` when absent | | `storage_set` | `storage::set`, `storage::write` | 10,000 + 10/B of key and value | keys up to 256 bytes, values up to 65,536 | | `storage_remove` | `storage::remove` | 5,000 + 1/B of key | | Storage is private: a contract reads and writes only its own keys. A write is visible at once to every level of the same op, re-entrant calls included. ### Context | Host function | SDK | Gas | Notes | | --- | --- | --- | --- | | `caller` | `caller()` | 100 | the op’s account at the top level; the calling contract inside a call | | `self_id` | `self_id()` | 100 | this contract’s ID | | `block_height` | `block_height()` | 100 | height of the main-chain block executing the op | | `block_timestamp` | `block_timestamp()` | 100 | that block’s timestamp, in seconds | | `chain_id` | `chain_id()` | 100 | 1001 devnet, 1002 signet, 1000 mainnet | | `gas_left` | `gas_left()` | 100 | gas left after this function’s own cost | An op in a merged block runs with the height and timestamp of the main-chain block that merges it. The producer sets the timestamp within loose bounds, so it is not a precise clock. A read-only call (the RPC method `ksana_call`) runs as if in the next block: the tip’s height plus one, with the tip’s timestamp. ```rust /// `env() -> (u64, u64, u32, u32)`: the block a call runs in, as the contract sees it. pub fn env() -> CallResult { let height = sdk::block_height(); // the main-chain block executing the op let time = sdk::block_timestamp(); // seconds, set by the producer: not a precise clock sdk::ok(&(height, time, sdk::chain_id(), sdk::btc_anchor_height())) } ``` ### Events | Host function | SDK | Gas | Notes | | --- | --- | --- | --- | | `emit_event` | `emit_event(&[u8])`, `emit(&T)` | 1,000 + 5/B | at most 16,384 bytes | Events appear in the op’s receipt as `{ "contract", "data" }`. They are not part of the state root, and they are dropped when the op fails. ### Assets | Host function | SDK | Gas | Notes | | --- | --- | --- | --- | | `asset_balance` | `asset_balance(asset, account)` | 2,000 | any account’s or contract’s balance, as a u128 | | `asset_transfer` | `asset_transfer(asset, to, amount)` | 10,000 | pays out of this contract’s balance; traps when it is short or the asset’s rules refuse the transfer | | `asset_issue` | `asset_issue(sub_id, meta, to, amount)` | 20,000 + 1/B of `meta` | issues this contract’s own asset; returns its ID. The first issue creates the asset with the capability to mint alone | | `asset_create` | `asset_create(sub_id, meta, capabilities, to, amount)` | 20,000 + 1/B of `meta` | creates this contract’s own asset with the capabilities it declares, and issues `amount` to `to`; returns its ID | | `asset_freeze` | `asset_freeze(sub_id, account, frozen)` | 10,000 | freezes or unfreezes an account for this contract’s asset | | `asset_allow` | `asset_allow(sub_id, account, allowed)` | 10,000 | puts an account on or off this contract’s asset’s allowlist | | `asset_pause` | `asset_pause(sub_id, paused)` | 10,000 | pauses or resumes this contract’s asset | | `asset_renounce` | `asset_renounce(sub_id, capabilities)` | 10,000 | gives up capabilities of this contract’s asset for good | | `asset_policy` | `asset_policy(asset)` | 2,000 | any asset’s capabilities and whether it is paused; `None` when it does not exist | | `asset_status` | `asset_status(asset, account)` | 2,000 | an account’s status flags for an asset: `STATUS_FROZEN`, `STATUS_ALLOWED` | | `asset_burn` | `asset_burn(asset, amount)` | 10,000 | burns from this contract’s balance, KSA included | | `call_funds` | `call_funds()`, `received(asset)` | 100 + 1/B returned | the assets attached to the current call | Accounts and contracts share one balance table for built-in assets: KSA (ID: 32 zero bytes, 8 decimals) and the assets contracts issue. An issued asset’s ID is `sha256(issuing contract ‖ sub_id)`, which `asset_id(issuer, sub_id)` computes. The first issue, or `asset_create`, records `meta`: a name of 1 to 64 bytes, a symbol of 1 to 16 bytes (such as `USDX`) and at most 18 decimals. Every later issue must pass the same `meta`, or it traps. An asset’s issuing contract holds the capabilities it declared when it created the asset, and nothing else: `CAP_MINT` issues more, `CAP_FREEZE` freezes accounts, `CAP_ALLOWLIST` admits only the accounts it allows, `CAP_PAUSE` pauses the asset. `asset_create` declares any of them (0 for none, a fixed supply), and `asset_issue` creates an asset with `CAP_MINT` alone. A capability can be given up with `asset_renounce` and never gained, and the functions that manage an asset name it by this contract’s `sub_id`, so only its issuing contract manages it. KSA has no capabilities. Wallets read an asset’s capabilities with [`ksana_getAsset`](https://ksana.network/docs/rpc/#ksana_getasset) and an account’s standing with [`ksana_getAssetStatus`](https://ksana.network/docs/rpc/#ksana_getassetstatus). Every movement of the asset obeys them: the transfer action, attached funds, `asset_transfer`, `asset_issue`, `asset_create` and `asset_burn`. The issuing contract is exempt. - A frozen account can neither send, receive nor burn the asset. - With an allowlist, only the allowed accounts send, receive or burn it. - While the asset is paused, no account but the issuing contract sends or burns it. - Setting a flag or pausing needs the capability; clearing a flag or resuming never does, and a flag stops counting once its capability is given up. - No capability moves a balance: an issuer can stop an account’s asset, never take it. A refused movement fails the op, and its message starts with `rejected:`, such as `rejected: sender is frozen for this asset` or `rejected: asset is paused`. `try_call_contract` catches a refusal of the funds it attaches as status `2`. Attached funds move to the contract before it runs. They must be in strictly ascending order of asset ID, each above zero, at most 16 items. ### Calls | Host function | SDK | Gas | Notes | | --- | --- | --- | --- | | `call_contract` | `call`, `call_with_funds` | 20,000 + 1/B of input + 1/B of callee code + 10,000 per asset | a failure of the callee fails the op | | `try_call_contract` | `try_call`, `try_call_with` | as `call_contract` | a failure rolls back only the callee | | `delegate_call` | `delegate_call` | as `call_contract`, no assets | runs another contract’s code in this contract’s context | | `create_contract` | `create_contract` | 100,000 + 1/B of args + 1/B of code + 10,000 per asset | creates a contract from code on chain | - **`try_call_contract`** returns `(status: u8, data)`: `0` with the callee’s output, `1` with its revert reason, `2` for any other failure (the SDK maps these to `Ok`, `CallError::Revert` and `CallError::Failed`). The callee gets at most `min(gas, remaining − remaining / 64)`, where a `gas` of 0 sets no separate limit. The caller’s own mistakes still fail the op: the method name `init`, an input that is too long, a malformed funds list. - **`delegate_call`** runs the other code with this contract’s storage, balances, `self_id`, `caller` and `call_funds`. Use it only with code you trust. - **`create_contract`** gives the new contract the ID `sha256(this contract ‖ salt ‖ code_hash)` (`created_contract_id` computes it), then runs its `init` with this contract as the caller. It traps when the code is not on chain, the ID is taken, or `init` fails. The op’s own call counts as level 1, and calls nest at most 8 levels. `try_call_contract` and `delegate_call` take a level too. Re-entry (A calls B calls A) is allowed. ### Bitcoin | Host function | SDK | Gas | Notes | | --- | --- | --- | --- | | `btc_anchor_height` | `btc_anchor_height()` | 100 | the Bitcoin height the executing block anchors to | | `btc_header` | `btc_header(height)` | 2,000 | the 80-byte header; traps unless `height` ≤ anchor − 6 | | `native_tx` | `native_tx()` | 2,000 + 1/B returned | the Bitcoin transaction that carried this path C op | `native_tx` returns `None` for path B ops and for read-only calls. Every level of one op reads the same transaction, so a contract must make sure it counts a payment once. [Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/) shows how to use these three, and the SDK’s `btc` module parses headers and transactions and checks Merkle proofs inside the contract. ### Crypto | Host function | SDK | Gas | Notes | | --- | --- | --- | --- | | `sha256` | `sha256(data)`, `sha256d(data)` | 500 + 1/B | `sha256d` is two calls | | `verify_schnorr` | `verify_schnorr(pubkey, digest, sig)` | 50,000 | BIP340 over a 32-byte digest | `verify_schnorr` checks a signature of a 32-byte digest, not of a message: hash the message first. A Ksana account is an x-only key, so a contract can check a signature by an account: ```rust /// Whether `sig` is a BIP340 signature by `signer` of `message`; the host checks a 32-byte digest. pub fn signed_by(signer: &[u8; 32], message: &[u8], sig: &[u8; 64]) -> bool { sdk::verify_schnorr(signer, &sdk::sha256(message), sig) } ``` The SDK’s `contract_id`, `created_contract_id` and `asset_id` compute identifiers with `sha256` inside the contract, at its gas. `trap()` executes `unreachable`, for cases that cannot happen. ## Raw signatures The node accepts these imports, with exactly these types, and no others: ```text storage_get(key_ptr: i32, key_len: i32) -> i64 storage_set(key_ptr: i32, key_len: i32, val_ptr: i32, val_len: i32) storage_remove(key_ptr: i32, key_len: i32) caller(dst: i32) self_id(dst: i32) block_height() -> i64 block_timestamp() -> i64 chain_id() -> i64 gas_left() -> i64 btc_anchor_height() -> i64 btc_header(height: i64, dst: i32) asset_balance(asset_ptr: i32, account_ptr: i32, dst: i32) asset_transfer(asset_ptr: i32, to_ptr: i32, amount_ptr: i32) asset_issue(sub_id_ptr: i32, meta_ptr: i32, meta_len: i32, to_ptr: i32, amount_ptr: i32, dst: i32) asset_create(sub_id_ptr: i32, meta_ptr: i32, meta_len: i32, capabilities: i32, to_ptr: i32, amount_ptr: i32, dst: i32) asset_freeze(sub_id_ptr: i32, account_ptr: i32, frozen: i32) asset_allow(sub_id_ptr: i32, account_ptr: i32, allowed: i32) asset_pause(sub_id_ptr: i32, paused: i32) asset_renounce(sub_id_ptr: i32, capabilities: i32) asset_policy(asset_ptr: i32) -> i64 asset_status(asset_ptr: i32, account_ptr: i32) -> i32 asset_burn(asset_ptr: i32, amount_ptr: i32) create_contract(code_hash_ptr: i32, salt_ptr: i32, args_ptr: i32, args_len: i32, funds_ptr: i32, funds_len: i32, dst: i32) call_contract(contract_ptr: i32, input_ptr: i32, input_len: i32, funds_ptr: i32, funds_len: i32) -> i64 call_funds() -> i64 native_tx() -> i64 try_call_contract(contract_ptr: i32, input_ptr: i32, input_len: i32, funds_ptr: i32, funds_len: i32, gas: i64) -> i64 delegate_call(contract_ptr: i32, input_ptr: i32, input_len: i32) -> i64 emit_event(ptr: i32, len: i32) sha256(ptr: i32, len: i32, dst: i32) verify_schnorr(pubkey_ptr: i32, msg_ptr: i32, sig_ptr: i32) -> i32 ``` Amounts are 16-byte little-endian u128 values in memory. `funds` is a Borsh `Vec`, at most 772 bytes, with `funds_len = 0` for none. The input of a call is encoded as in [How a call enters a contract](#abi). `verify_schnorr` returns `1` for a valid signature and `0` otherwise. `meta` is the Borsh encoding of `(name: String, symbol: String, decimals: u8)`. Capabilities are bits: `1` mint, `2` freeze, `4` allowlist, `8` pause, and a higher bit traps. `frozen`, `allowed` and `paused` are `1` or `0`, and any other value traps. `asset_policy` returns the capabilities in bits 0 to 7 with `0x100` added while the asset is paused, or `-1` when it does not exist; `asset_status` returns the flags, `1` frozen and `2` allowed. ## Gas Gas is wasmtime fuel: ordinary instructions cost 1, while `nop`, `drop` and the structured control instructions cost 0. `memory.copy`, `memory.fill` and `memory.init` cost 1 more per byte, `memory.grow` 1 per page, and table operations 1 per element. Host functions add the costs in the tables above. Each op also pays a fixed cost for its action: | Action | Gas | | --- | --- | | `AssetTransfer` | 10,000 | | `Deploy` | 100,000 + 20/B of code + 10,000 per attached asset + `init`, which includes loading the code at 1/B | | `Call` | 20,000 + 1/B of the contract’s code + 10,000 per attached asset + the method | The op’s `max_gas` is a hard limit: an op that needs more fails, even when the excess comes at the very end. A failed op’s receipt reports all of `max_gas` as used. The `max_gas` values of a block’s path B ops add up to at most 100,000,000, so no op can ask for more; a path C op with a `max_gas` above 1,000,000 uses its nonce but fails. These ops of the [token and pool tutorial](https://ksana.network/docs/token-and-pool/) used: | Op | Gas | | --- | --- | | Deploy the 28,720-byte token | 776,169 | | Deploy the 25,427-byte pool | 672,844 | | `transfer_and_call` on the token, a deposit in the pool with KSA attached | 214,928 | | `swap` on the pool, KSA attached | 169,247 | | `transfer_and_call` on the token, a swap in the pool | 172,426 | Gas sets the limit of an op’s work; it is not its price. A path B fee is paid in KSA and rated by the op’s cost in bytes, where `max_gas` counts as `max_gas × 81,920 / 100,000,000` bytes. [Operations and fees](https://ksana.network/docs/submitting-ops/) explains how producers choose. ## Limits | Limit | Value | | --- | --- | | Storage key / value | 256 / 65,536 bytes | | Event | 16,384 bytes | | `asset_issue` / `asset_create` meta | 1,024 bytes; a name of 1 to 64 bytes, a symbol of 1 to 16, at most 18 decimals | | Call input / output | 65,536 / 65,536 bytes | | Attached funds | 16 items, 772 bytes encoded | | Call depth (`MAX_CALL_DEPTH`) | 8 | | Instances / total memory in one op | 64 / 256 MiB | | Linear memory of an instance (`MAX_WASM_MEMORY`) | 16 MiB, at most 256 pages at the start | | Table | 4,096 entries | | Stack of an instance (`STACK_BUDGET`) | 262,144 bytes, estimated | | Whole op, code included (`MAX_OP_BYTES`) | 65,536 bytes | | `max_gas` of a block’s path B ops (`BLOCK_GAS_LIMIT`) | 100,000,000 in total | | `max_gas` of a path C op (`NATIVE_MAX_GAS`) | 1,000,000 | | Header depth (`BTC_QUERY_DEPTH`) | 6 Bitcoin blocks below the anchor | When `memory.grow` would pass 16 MiB it returns −1, and the SDK’s allocator then traps. Breaking any other limit fails the call or the op. ### Stack metering The native stack depth of WebAssembly differs between machines, so the node meters the stack with an estimate that is the same everywhere. A function’s frame counts as 64 + 16 × (parameters + locals + the deepest operand stack) bytes, and an instance that goes past 262,144 bytes traps. Each contract call is a new instance with its own budget. Recursion, function pointers, trait objects and `core::fmt` all work within it. --- # Bitcoin in contracts URL: https://ksana.network/docs/bitcoin-in-contracts/ > A contract can read Bitcoin block headers, check a proof that a Bitcoin transaction paid a script, and read the Bitcoin transaction that carried its own op. Every Ksana block anchors to a Bitcoin block, and every node executes it against the Bitcoin chain up to that anchor. Contracts share that view of Bitcoin through three host functions: | Function | Returns | Gas | | --- | --- | --- | | `btc_anchor_height()` | the Bitcoin height that the block executing the op anchors to | 100 | | `btc_header(height)` | the 80-byte header of a Bitcoin block at least 6 blocks below the anchor | 2,000 | | `native_tx()` | for a path C op, the Bitcoin transaction that carried it | 2,000 + 1 per byte | A contract sees nothing else of Bitcoin: no transaction by ID, no address, no balance. To use any other transaction, the caller passes it in with a Merkle proof, and the contract checks the proof against a header. The SDK’s `btc` module parses headers and transactions and checks the proofs. The contract code on this page starts from `use ksana_contract_sdk::{self as sdk, btc, storage};`, as in [Write a contract](https://ksana.network/docs/contracts/). ## What a contract can see A producer anchors each block `ANCHOR_DEPTH` blocks below the Bitcoin tip it sees: 0 on devnet, 1 on the signet and 2 on mainnet. A contract can read the headers at least `BTC_QUERY_DEPTH` blocks below that anchor, and `BTC_QUERY_DEPTH` is 6 on every network. So a Bitcoin block’s header becomes readable once the block has 7 + `ANCHOR_DEPTH` confirmations: 8 on the signet and 9 on mainnet, or more when a producer’s view of Bitcoin lags. `btc_header` traps for a block that is not deep enough, and the op fails with the error `insufficient BTC block header depth`. Check the depth first, so that your contract decides what happens; here it reverts with its own reason: ```rust /// A contract reads BTC headers at least this far below the anchor: 6 on every network. const BTC_QUERY_DEPTH: u32 = 6; /// The header of BTC block `height`, or a revert when it is not yet deep enough to read. pub fn header_at(height: u32) -> Result> { // btc_header traps when the block is too shallow, so check first and revert with a reason let deepest = sdk::btc_anchor_height().checked_sub(BTC_QUERY_DEPTH); if deepest.is_none_or(|deepest| height > deepest) { return Err(b"the block is not deep enough yet".to_vec()); } btc::BlockHeader::parse(&sdk::btc_header(height)).ok_or(b"malformed header".to_vec()) } ``` The header comes from the node’s own view of the anchor chain, so the contract needs no proof-of-work check. `BlockHeader` has the fields `version`, `prev_blockhash`, `merkle_root`, `time`, `bits` and `nonce`, and `block_hash()` computes its hash. **Byte order.** Contracts see txids, block hashes and Merkle branches in Bitcoin’s internal byte order. Block explorers and bitcoind’s RPC show txids and block hashes reversed. Reverse a txid copied from an explorer before you compare it with one a contract computed. ## Prove a payment To show a contract that a Bitcoin transaction paid a script, the caller passes: - the height of the block that holds the transaction; - the transaction, serialized without witness data (without the marker, the flag and the witnesses of a segwit transaction); - its position in the block and its Merkle branch, from the leaf up; - the block’s coinbase transaction, also without witness data, and the coinbase’s Merkle branch. Bitcoin’s Merkle tree allows three known forgeries, and `btc::verify_tx_inclusion` blocks all of them. It rejects a transaction of exactly 64 bytes, so an inner node of the tree cannot pass as a transaction. The coinbase proof pins the depth of the tree: the coinbase is always the first transaction, and the transaction’s branch must be as long as the coinbase’s. A forged transaction therefore cannot hang below a real 64-byte one. Bitcoin also pairs the last node of an odd level with a copy of itself, so the last of 3 transactions would verify at index 2 and at index 3; the function rejects a position below such a copy, and a transaction verifies at its own index only. ```rust /// A transaction and the Merkle proofs that place it in a BTC block. pub struct Proof<'a> { /// Height of the BTC block. pub height: u32, /// The transaction, serialized without witness data. pub raw_tx: &'a [u8], /// Its position in the block. pub index: u32, /// Its Merkle branch, from the leaf up. pub branch: &'a [[u8; 32]], /// The block's coinbase transaction, without witness data. pub coinbase_tx: &'a [u8], /// The coinbase's Merkle branch: as long as `branch`. pub coinbase_branch: &'a [[u8; 32]], } /// Checks that output `vout` of a proven transaction pays `script`; returns the txid and the sats. pub fn proven_payment( proof: &Proof<'_>, vout: u32, script: &[u8], ) -> Result<([u8; 32], u64), Vec> { let header = header_at(proof.height)?; let txid = btc::verify_tx_inclusion( &header, proof.raw_tx, proof.index, proof.branch, proof.coinbase_tx, proof.coinbase_branch, ) .ok_or(b"the transaction is not in that block".to_vec())?; let outputs = btc::parse_outputs(proof.raw_tx).ok_or(b"malformed transaction".to_vec())?; let output = usize::try_from(vout) .ok() .and_then(|i| outputs.get(i)) .ok_or(b"no such output".to_vec())?; if output.script_pubkey != script { return Err(b"the output pays another script".to_vec()); } Ok((txid, output.value)) } ``` The position does not identify a transaction. When a level of the tree has an odd number of nodes, Bitcoin pairs the last node with itself, so the last transactions of a block also verify at a position past the end. Key replay protection on the txid and the output, never on the position: ```rust /// Marks output (txid, vout) as used; a second claim of the same output reverts. pub fn use_once(txid: &[u8; 32], vout: u32) -> Result<(), Vec> { let key = [b"used".as_slice(), txid, &vout.to_le_bytes()].concat(); if storage::get(&key).is_some() { return Err(b"already claimed".to_vec()); } storage::set(&key, &[1]); Ok(()) } ``` A proof does not say who may use the payment: anyone who sees the transaction on Bitcoin, the producer included, could submit it first. The `btc-payment-trigger` example requires the paying transaction to commit to the beneficiary in an output `OP_RETURN <32-byte account>`, so a claim for anyone else fails. The whole proof travels in the op, and an op is at most 65,536 bytes, so a very large transaction cannot be proven this way. ### Build the proof Your app builds the proof from the whole block. The signet’s public Bitcoin endpoint does not serve blocks, so read the block from your own bitcoind with `bitcoin-cli -signet getblock 0`, which prints it in hex. These functions use the [rust-bitcoin](https://crates.io/crates/bitcoin) crate: ```toml [dependencies] bitcoin = "0.32" borsh = "1" hex = "0.4" ``` ```rust title="src/lib.rs" //! Builds the proofs that `btc::verify_tx_inclusion` checks, from a block read from bitcoind. use bitcoin::consensus::serialize; use bitcoin::hashes::{sha256d, Hash}; use bitcoin::{Block, Transaction}; /// The parts of a proof that place a transaction in its block. pub struct InclusionProof { /// The transaction, without witness data. pub raw_tx: Vec, /// Its Merkle branch, from the leaf up. pub branch: Vec<[u8; 32]>, /// The block's coinbase transaction, without witness data. pub coinbase_tx: Vec, /// The coinbase's Merkle branch. pub coinbase_branch: Vec<[u8; 32]>, } /// The transaction without witness data: the bytes its txid hashes. pub fn without_witness(tx: &Transaction) -> Vec { let mut stripped = tx.clone(); for input in &mut stripped.input { input.witness.clear(); } serialize(&stripped) } /// The Merkle branch of transaction `index`, from the leaf up, in internal byte order. pub fn merkle_branch(txids: &[[u8; 32]], mut index: usize) -> Vec<[u8; 32]> { let mut level = txids.to_vec(); let mut branch = Vec::new(); while level.len() > 1 { if level.len() % 2 == 1 { level.push(level[level.len() - 1]); // an odd level pairs its last node with itself } branch.push(level[index ^ 1]); level = level .chunks(2) .map(|pair| sha256d::Hash::hash(&[pair[0], pair[1]].concat()).to_byte_array()) .collect(); index /= 2; } branch } /// The proof of transaction `index` of `block`. pub fn inclusion_proof(block: &Block, index: usize) -> InclusionProof { let txids: Vec<[u8; 32]> = block .txdata .iter() .map(|tx| tx.compute_txid().to_byte_array()) .collect(); InclusionProof { raw_tx: without_witness(&block.txdata[index]), branch: merkle_branch(&txids, index), coinbase_tx: without_witness(&block.txdata[0]), coinbase_branch: merkle_branch(&txids, 0), } } /// The Borsh arguments of `claim` in the btc-payment-trigger example, in hex for `--args`. pub fn claim_args( block: &Block, height: u32, index: usize, vout: u32, beneficiary: [u8; 32], ) -> String { let p = inclusion_proof(block, index); let index = u32::try_from(index).expect("a block holds fewer than 2^32 transactions"); let args = ( height, p.raw_tx, index, p.branch, p.coinbase_tx, p.coinbase_branch, vout, beneficiary, ); hex::encode(borsh::to_vec(&args).expect("encoding plain values cannot fail")) } ``` Decode the hex with `bitcoin::consensus::encode::deserialize_hex::(hex.trim())`. rust-bitcoin’s `to_byte_array()` gives a hash in internal byte order, the order contracts use, and `to_string()` gives the reversed order that explorers show. `claim_args` produces the `--args` of a [ksana-cli](https://ksana.network/docs/cli/) call to the `btc-payment-trigger` example. ## Read the op’s own transaction A path C op travels inside a Bitcoin transaction, in a KSN1 data output. Every producer must include it once that transaction has `NATIVE_CONFIRMATIONS` + `ANCHOR_DEPTH` confirmations: 2 on the signet and 5 on mainnet. The op’s signature covers the transaction’s first input, so a copy of the op in another transaction fails authentication. While the op runs, `native_tx()` returns the transaction’s txid and all its outputs, the KSN1 output included; for a path B op, and in a read-only call (the RPC method `ksana_call`), it returns `None`. That lets one Bitcoin transaction both pay and ask a contract to act on the payment, with no proof to build. This function adds up what the transaction pays to a script: ```rust /// What the BTC transaction carrying this op pays to `script`, in sats, and its txid. pub fn paid_by_this_op(script: &[u8]) -> Result<([u8; 32], u64), Vec> { let tx = sdk::native_tx().ok_or(b"send this op through path C".to_vec())?; let mut paid = 0u64; for output in tx.outputs.iter().filter(|o| o.script == script) { paid = paid.checked_add(output.value).ok_or(b"overflow".to_vec())?; } Ok((tx.txid, paid)) } ``` Every level of the op reads the same transaction: calls to other contracts, `try_call`, `delegate_call` and the `init` of created contracts. A contract that a path C op calls twice sees the payment twice, so record each txid you credit. A path C op’s `max_gas` cannot exceed 1,000,000: above that, the op uses its nonce and fails. [Operations and fees](https://ksana.network/docs/submitting-ops/) explains how to send a path C op, and the [TypeScript SDK](https://ksana.network/docs/sdk/) builds the transaction for a browser wallet. ## Test it natively The SDK’s mock host plays the anchor chain in native tests. `mock::set_btc_header` stores a header, and `mock::set_btc_anchor_height` moves the anchor. `mock::set_native_tx` sets the transaction that carries the op, and `None`, the default, means a path B op. `mock::with_context(caller, contract, f)` runs `f` as if `contract` were executing a call from `caller`: ```rust title="tests/path_c.rs" //! Native tests of the path C payment check, against the mock host. #![cfg(not(target_arch = "wasm32"))] use ksana_contract_sdk::{mock, NativeOutput, NativeTx}; const ALICE: [u8; 32] = [0xa1; 32]; const CONTRACT: [u8; 32] = [0xc0; 32]; #[test] fn counts_what_the_carrying_transaction_pays() { mock::reset(); let script = [&[0x51, 0x20][..], &[7; 32]].concat(); // a P2TR output script let pay = |value| NativeOutput { value, script: script.clone(), }; let outputs = vec![pay(700), pay(300)]; mock::set_native_tx(Some(NativeTx { txid: [3; 32], outputs, })); let paid = mock::with_context(ALICE, CONTRACT, || snippets::paid_by_this_op(&script)); assert_eq!(paid, Ok(([3; 32], 1_000))); mock::set_native_tx(None); // a path B op from here on let paid = mock::with_context(ALICE, CONTRACT, || snippets::paid_by_this_op(&script)); assert_eq!(paid, Err(b"send this op through path C".to_vec())); } ``` Here the contract’s crate is named `snippets`; use your crate’s name. Like a node, the mock traps on `btc_header` for a block less than 6 blocks below the anchor, and for a header you did not set. ## The examples Two of the [example contracts](https://ksana.network/docs/example-contracts/) use Bitcoin: - **`btc-payment-trigger`** issues its own asset to whoever proves a payment to a watched script. `claim` reads the header, checks the proof, requires the commitment to the beneficiary, accepts each output once, and issues the output’s value in sats times `units_per_sat`. - **`ksa-exchange`** sells KSA for bitcoin, and top-ups use it. A seller locks KSA at a price for a buyer’s account. The buyer pays the lock’s script in the Bitcoin transaction that carries a path C `claim`. `claim` reads `native_tx()`, adds up the payment, records the txid against the lock, and pays the KSA it buys to the buyer. Both are tested in the repository against the mock host, and the regtest end-to-end tests run them against a real bitcoind. --- # Assets and tokens URL: https://ksana.network/docs/tokens/ > Ksana has built-in assets, which the VM keeps, and tokens, which contracts keep under two standards, KS-20 for fungible tokens and KS-721 for unique ones. How they differ, which to choose, and what every KS-20 token and KS-721 collection has in common. ## Three kinds | | Built-in asset | KS-20 token | KS-721 collection | | --- | --- | --- | --- | | What it is | KSA, or an asset a contract creates with `asset_issue` or `asset_create` | a contract that keeps a ledger of amounts | a contract that keeps the owner of each unique token | | Where balances live | the VM's balance table, beside each account's KSA | the token's storage | the collection's storage | | How it moves | an `AssetTransfer` operation, or attached to a call | a call of the token: `transfer`, `transfer_and_call` | a call of the collection | | Who reads it | the node's [`ksana_getAccount`](https://ksana.network/docs/rpc/) lists it | a read-only call of the token's `balance_of` | a read-only call of `owner_of` | | Rules of its own | only the capabilities its issuer declared when it created it, among `mint`, `freeze`, `allowlist` and `pause` | any, which the token reports in `capabilities()` | any, reported the same way | | A transfer costs | 10,000 gas | about 84,000 gas for the reference token | about 176,000 gas for the test collection | Every built-in asset has a name, a symbol, decimals and an ID of 32 bytes: KSA's ID is 32 zero bytes, and an issued asset's the SHA-256 of its contract's ID and a sub-ID ([Accounts](https://ksana.network/docs/accounts/) explains balances). A token is named by its contract's ID. The two kinds of ID look alike, so a contract that takes either asks for an [`AssetRef`](#asset-ref), and the playground checks every ID before it deploys anything. ## Choosing a kind | Need | Use | | --- | --- | | A currency, a points balance, an item counted by quantity | a built-in asset: the protocol itself knows it, so every node answers for it without an index, it can be attached to calls, and a transfer costs 10,000 gas | | A currency whose issuer must be able to freeze an account, admit only the accounts it allows or pause every transfer, such as a payment stablecoin | a built-in asset created with those capabilities by `asset_create`: wallets show them, and the issuer can give them up but never gain one or take a balance | | Balances with logic of their own: a fee on transfers, shares that earn, vote snapshots, vesting, dividends, data per holder, transfers that read or write other contracts | a [KS-20 token](https://ksana.network/docs/ks-20/), which the web wallet and the explorer list beside built-in assets from a node’s index of the standards’ events | | Items each unique: collectibles, tickets, names, position receipts | a [KS-721 collection](https://ksana.network/docs/ks-721/) | | Many fungible items from one contract | built-in assets: one contract issues any number of them, each with its own sub-ID | Issue one kind for one brand. When it has to reach contracts that take only the other kind, such as a KS-20 token in a market that takes built-in assets alone, a wrapper contract locks the token one for one and issues a built-in asset whose name says so, such as `wXYZ`. ## How a contract declares a standard A token or a collection declares its standard itself. Its `init` emits the event `standards(ids)` and then `metadata`, before any `transfer`, and its view `standards()` returns the same list for its whole life: the standard first (`"KS-20"` or `"KS-721"`), then the extensions it implements. An indexer takes a contract's first `standards` event as its declaration, so tokens can be indexed from receipts alone, and wallets and other contracts ask the view at any time; in a contract, the SDK's `standard::standards_of(contract)` and `standard::declares(contract, id)` ask it. A declaration is a claim, not a guarantee: a contract can declare KS-20 and break its rules, emit false events and answer false balances, though only its own. What a wallet trusts is the contract's identity, its ID and the hash of its code, which cannot change unless the contract delegates its code. A wallet can mark a contract whose code hash is that of a known build: the [playground's compile service](https://ksana.network/docs/playground/) builds the same source into the same module on any machine. ## Capabilities `capabilities() -> Vec` reports what a contract's rules let someone do now, so that a wallet can mark the token: | Name | Someone can | | --- | --- | | `mint` | create more tokens: a minter is set, or the collection can still mint | | `freeze` | stop an account's tokens from moving | | `allowlist` | limit who may hold or receive the tokens | | `pause` | stop every transfer | | `clawback` | take tokens from a holder without the holder's approval | | `fee` | charge a fee on transfers | | `upgrade` | change the contract's code, by delegating it | The list holds each name once, in this order, with names the standards do not define after them. A capability that has ended is no longer reported: a token whose minter gave minting up reports no `mint`. Built-in assets use the first four names for their issuer capabilities, which the issuing contract declares when it creates the asset and can only give up. [`ksana_getAsset`](https://ksana.network/docs/rpc/#ksana_getasset) lists them in the same order, so a wallet marks both kinds alike. A built-in asset never has `clawback`, `fee` or `upgrade`, and none of its capabilities moves a balance ([Host functions](https://ksana.network/docs/host-functions/#assets) gives the rules). ## Either kind in one argument A contract that takes any fungible asset in one argument, such as a pool or a market, uses the SDK's `standard::AssetRef`: ```abi title="AssetRef" enum AssetRef { Token(ContractId), Asset([u8; 32]) } // a KS-20 token; a built-in asset (KSA is 32 zero bytes) ``` Its Borsh encoding is one byte for the variant, `00` for `Token` and `01` for `Asset`, then the 32-byte ID: `01` and 32 zero bytes is KSA. The [example AMM](https://ksana.network/docs/example-contracts/#amm) takes its two sides this way. In a contract, `AssetRef::balance_of` reads the token's `balance_of` or the built-in balance, and `AssetRef::pay` pays from the contract's own balance with the token's `transfer` or with `asset_transfer`. ## Revert reasons A refusal is the text of the method's error, which the receipt shows as `revert: `. The standards fix these reasons as English phrases, so that wallets can translate them and contracts can compare them: | Case | Reason | | --- | --- | | A method the contract does not have | `unknown method` | | Arguments that do not decode, or bytes left after them | `malformed arguments` | | Funds attached to a method that takes none | `unexpected attached funds` | | An amount of 0 (KS-20) | `zero amount` | | The zero account as recipient, spender, operator or minter | `zero account` | | The token or the collection itself as recipient | `recipient is this contract` | | Too small a balance (KS-20) | `insufficient balance` | | Too small an allowance (KS-20) | `insufficient allowance` | | An expired allowance (KS-20) | `allowance expired` | | `approve` for oneself (KS-20) | `spender is the caller` | | A token that does not exist (KS-721) | `unknown token` | | `transfer` or `transfer_and_call` by anyone but the owner (KS-721) | `not the owner` | | `transfer_from`, `approve` or `burn` by an account that may not (KS-721) | `not authorized` | | `transfer_from` naming another `from` than the owner (KS-721) | `wrong owner` | | A transfer to the owner (KS-721) | `already the owner` | | The owner as the approved account (KS-721) | `spender is the owner` | | `set_operator` for oneself (KS-721) | `operator is the caller` | | A mint of an ID a token has, or had (KS-721) | `token exists`, `token was burned` | | A recipient's answer that is not `Bytes` | `malformed return value` | | `mint` or `set_minter` by anyone but the minter (KS-20-mintable) | `not the minter`, or `minting has ended` once there is none | | A mint past the cap (KS-20-mintable) | `cap exceeded` | | A refusal by the contract's own rules | `rejected: ` | When the recipient of `transfer_and_call` refuses, the receipt shows the recipient's reason. A contract's own `init` and limits may use other reasons. ## Security - **Impersonation**: anyone can deploy a token named KSA. Wallets clean names and symbols, compare them with KSA and BTC, show an unverified token's whole ID, and fold away tokens nobody asked for. - **Allowances**: an allowance lets the spender take up to its amount at any time. Approve the amount one operation needs, with an expiry, revoke what you no longer use, and prefer `transfer_and_call`, which needs none. - **Callbacks**: a contract that receives tokens checks `caller()`, since anyone can call `on_token_received` or `on_nft_received` directly. The token moves before it calls, and calls nest at most 8 deep. - **Stuck tokens**: tokens never go to the zero account or to the contract itself, and methods that take no funds refuse them. A plain `transfer` to a contract that cannot move tokens strands them, so wallets suggest `transfer_and_call` when the recipient is a contract. - **Spam**: transfers of 0 are refused, so nobody can fill an account's history with them. - **Upgradeable tokens**: a contract that delegates its code can change what it does; it reports `upgrade`, and the reference implementations delegate nothing. - **Rules that refuse**: a token's own rules, and a built-in asset's capabilities, may refuse a transfer with a reason that starts with `rejected: `. A pool or a market treats it as it treats too small a balance. - **NFT media**: wallets show a token's image with `` only, never as a document that runs scripts, and load remote media through a proxy or on demand. ## Next steps - [KS-20 tokens](https://ksana.network/docs/ks-20/) The interface, rules and extensions of fungible tokens, and how to build one. - [KS-721 collections](https://ksana.network/docs/ks-721/) Unique tokens: IDs, URIs, approvals and operators. - [Token and pool tutorial](https://ksana.network/docs/token-and-pool/) Deploy a KS-20 token and trade it in a pool, one operation at a time. --- # KS-20: fungible tokens URL: https://ksana.network/docs/ks-20/ > The standard for fungible tokens whose balances a contract keeps. Wallets, pools and other contracts read and move every KS-20 token the same way, and `transfer_and_call` pays a contract and calls it in one operation. A KS-20 token is a contract that keeps a ledger of balances in its own storage. The standard fixes its methods, events and refusals, so that a wallet lists any KS-20 token, a pool trades any of them and an indexer counts their transfers from receipts alone. It is a convention between contracts, wallets and indexers, not a consensus rule: the node runs a token like any other contract. The specification is [`docs/STANDARDS.md`](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/STANDARDS.md) in the repository; this page restates it. [Assets and tokens](https://ksana.network/docs/tokens/) compares KS-20 with built-in assets and covers what KS-20 and KS-721 share. ## Interface Arguments and return values are Borsh, in the notation of the playground's [ABI block](https://ksana.network/docs/playground/#the-abi-block): `view` methods change nothing, `call` methods may, and `payable` marks the one method that takes attached funds. An `Account` is 32 bytes, a user's Taproot output key or a contract ID, and a `ContractId` is an account that must be a contract. ```abi title="KS-20" view standards() -> Vec // ["KS-20", extensions...] view metadata() -> (String, String, u8) // (name, symbol, decimals) view capabilities() -> Vec // what the token's rules let someone do now view total_supply() -> u128 view balance_of(account: Account) -> u128 view allowance(owner: Account, spender: Account) -> u128 // what spender may take now: 0 once expired view allowance_info(owner: Account, spender: Account) -> (u128, Option) // (amount, expires_at) as set call transfer(to: Account, amount: u128) call transfer_from(from: Account, to: Account, amount: u128) call approve(spender: Account, amount: u128, expires_at: Option) payable call transfer_and_call(to: ContractId, amount: u128, data: Bytes) -> Bytes // returns the recipient's answer event standards(ids: Vec) event metadata(name: String, symbol: String, decimals: u8) event transfer(from: Account, to: Account, amount: u128) event approve(owner: Account, spender: Account, amount: u128, expires_at: Option) ``` A contract that takes tokens in one step adds `payable call on_token_received(from: Account, amount: u128, data: Bytes) -> Bytes`. `init` is not part of the standard: each token takes the arguments it needs. ## How a token declares itself `init` emits `standards`, then `metadata`, before any `transfer`, and the view `standards()` returns the same list for the token's whole life: `"KS-20"` first, then the extensions it implements, such as `"KS-20-burnable"`. A wallet asks the view; an indexer takes the contract's first `standards` event as its declaration and counts its standard events from there on. A declaration is a claim, not a guarantee, so wallets go by a token's ID and code hash, as [Assets and tokens](https://ksana.network/docs/tokens/#declare) explains. ## Rules 1. **Metadata**: `decimals` is at most 18 and never changes; `name` is 1 to 64 bytes and `symbol` 1 to 16 bytes of UTF-8. A token that changes its name or symbol emits `metadata` again. 2. **Every change is an event**: every change of a balance comes with a `transfer` event in the same operation, for the amount that changed. A mint is a transfer from the zero account (32 zero bytes) and a burn a transfer to it, and `total_supply` is the sum of all balances. 3. **Fees come out of the amount**: a transfer of `amount` lowers the sender's balance by exactly `amount`. A token that charges a fee credits the recipient with `amount − fee` and emits two `transfer` events, to the recipient and to its fee account (the zero account when the fee is burned), and reports `fee` in `capabilities()`. 4. **No zero amounts**: moving 0 reverts with `zero amount`; `approve` with 0 revokes. 5. **Recipients**: never the zero account (`zero account`) nor the token itself (`recipient is this contract`). 6. **Attached funds**: every method but `transfer_and_call` reverts with `unexpected attached funds`, so nothing gets stuck in the token's account. 7. **Allowances**: `approve` sets the allowance, it does not add to it. `transfer_from` by `from` itself needs none; anyone else takes `amount` of the allowance `from` gave them, which must not have expired (`allowance expired`) and must cover it (`insufficient allowance`). `u128::MAX` is unlimited and never goes down. 8. **A token's own rules**: a transfer they refuse (a frozen account, a pause, an allowlist) reverts with a reason that starts with `rejected: `. 9. **Effects before the call**: `transfer_and_call` moves the tokens and emits the events before it calls the recipient. A transfer beyond the balance reverts with `insufficient balance`. [Assets and tokens](https://ksana.network/docs/tokens/#revert-reasons) lists every reason. ## Pay a contract in one operation `transfer_and_call(to, amount, data)` sends tokens to a contract and calls it in the same operation. When an account U calls it on the token T and attaches built-in assets F: 1. The VM moves F from U to T before T runs. 2. T moves `amount` from U to the contract R by the rules above and emits the events. 3. T calls `R.on_token_received(U, received, data)` with F attached, where `received` is what R was credited. 4. R acts on `data` (a swap, a deposit) and answers `Bytes` of its own content, which T returns unchanged: a wallet can show what a swap paid out. 5. When R is no contract, has no `on_token_received`, refuses or fails, the whole operation fails, and the tokens and F stay with U. So a swap of a token is one operation with one fee and nothing to approve, and a pool of a token and KSA takes liquidity in one operation, the KSA attached to `transfer_and_call` and passed on by the token. The [token and pool tutorial](https://ksana.network/docs/token-and-pool/) does both. A receiving contract checks that `caller()` is a token it accepts: anyone can call `on_token_received` directly with a made-up `from` and `amount`, and only the token itself makes them true. The attached funds are always real, whoever the caller. A contract without `on_token_received` refuses the call, so tokens sent to it with `transfer_and_call` stay with the sender, while a plain `transfer` to a contract that cannot move tokens strands them: wallets suggest `transfer_and_call` when the recipient is a contract. ## Allowances An allowance with `expires_at` of `None` never expires; otherwise it counts while the block timestamp, in seconds, is below `expires_at`. `allowance` is what the spender may take now, and `allowance_info` the amount and the expiry as set, so a wallet can list them and warn. A spender can take up to the amount at any time, so an allowance to a contract that turns out broken can empty the account: wallets approve the amount one operation needs, with an expiry of about a week, ask separately for an unlimited amount or none, and revoke with `approve(spender, 0, None)`. With `transfer_and_call`, most uses need no allowance at all. ## Events | Event | Fields | When | | --- | --- | --- | | `standards` | `ids: Vec` | in `init`, once | | `metadata` | `name: String, symbol: String, decimals: u8` | in `init`, and again when the name or the symbol changes | | `transfer` | `from: Account, to: Account, amount: u128` | every change of a balance: mints from the zero account, burns to it, a fee as a transfer of its own | | `approve` | `owner: Account, spender: Account, amount: u128, expires_at: Option` | every `approve`; `expires_at` is `None` when `amount` is 0 | An event is the Borsh encoding of a tuple whose first element is its name, and the receipt names the contract that emitted it. A `transfer` event is 92 bytes: the name (4 bytes of length and 8 of text), then 32, 32 and 16. ## Extensions A token lists the extensions it implements after `"KS-20"` in `standards()`. ```abi title="KS-20-burnable" call burn(amount: u128) // burns the caller's tokens call burn_from(from: Account, amount: u128) // with the allowance from gave the caller ``` ```abi title="KS-20-mintable" view minter() -> Option // None once minting ended for good view cap() -> Option // the most total_supply can reach; None for no cap call mint(to: Account, amount: u128) // the minter only, up to the cap call set_minter(minter: Option) // the minter only; None ends minting for good event minter(previous: Option, minter: Option) ``` A mintable token emits `minter` in `init` and whenever the minter changes, and reports `mint` in `capabilities()` while it has a minter. `mint` and `set_minter` by anyone else revert with `not the minter`, or `minting has ended` once there is none, and a mint past the cap with `cap exceeded`. ## Tokens written before KS-20 The example token took `approve(spender, amount)` and `init(name, symbol, decimals, supply)` before KS-20, and the reference token still takes both: an `approve` of two arguments has no expiry, and an `init` of four has no minter and no cap. A pool that pulls tokens with `transfer_from` after an `approve`, as the example AMM still can, works with any KS-20 token. ## Build a token The contract SDK implements KS-20 in its `ks20` module, behind the `standards` feature: ```toml title="Cargo.toml" [dependencies] ksana-contract-sdk = { workspace = true, features = ["standards"] } ``` `Ks20::new()` is a plain token; `.burnable()` and `.mintable()` add the extensions, and `.with_policy(rules)` the token's own rules (a check before every movement, a fee, the capabilities it reports). `Ks20::dispatch` answers every standard method and `None` for the others, so the token's own methods go beside it. A burnable token with a fixed supply: ```rust title="src/lib.rs" #![cfg_attr(target_arch = "wasm32", no_std)] extern crate alloc; use alloc::string::String; use ksana_contract_sdk::{self as sdk, ks20::Ks20, standard, CallResult}; sdk::entry!(dispatch); const TOKEN: Ks20 = Ks20::new().burnable(); pub fn dispatch(method: &str, args: &[u8]) -> CallResult { if method == "init" { standard::no_funds()?; let (name, symbol, decimals, supply): (String, String, u8, u128) = sdk::decode(args)?; TOKEN.init(&name, &symbol, decimals)?; TOKEN.mint(&sdk::caller(), supply)?; return sdk::ok(&()); } TOKEN.dispatch(method, args).unwrap_or_else(|| sdk::revert("unknown method")) } ``` The implementation keeps its state under storage keys that start with `KS20:`, so the token's own state goes under any other key. The example `contracts/examples/token` is the reference KS-20 token, burnable and mintable, and the playground's [KS-20 token page](https://playground.ksana.network/#/ks20) deploys it. A contract that receives tokens decodes `on_token_received` with `ks20::received`, checks the caller, and answers with `standard::reply(&value)`; `ks20::Token` calls a token from another contract. The SDK's `conformance::ks20(setup)` checks a token on the mock host, whatever its own rules: the declaration, events for every change, the refusals and their reasons, allowances and their expiry, attached funds, `transfer_and_call` with a receiving contract the kit registers, and the extensions it declares. Call it from the token's native tests. ## What it costs Measured with the gas table every network uses, in `crates/ksana-execution/tests/contracts.rs`: | Operation on the reference token | Gas | | --- | --- | | Deploy (28.7 KB of code) | about 780,000 | | `transfer` | about 84,000 | | `approve` | about 68,000 | | `transfer_from` | about 99,000 | | `transfer_and_call` to a test receiver | about 157,000 | | A built-in asset's transfer, for comparison | 10,000 | The deployment fits within the default `--max-gas` of [ksana-cli](https://ksana.network/docs/cli/), 1,000,000. A swap or a deposit through `transfer_and_call` also pays for the pool's work: the [tutorial](https://ksana.network/docs/token-and-pool/) shows each one's gas. --- # KS-721: non-fungible tokens URL: https://ksana.network/docs/ks-721/ > The standard for collections of unique tokens, each with a 32-byte ID and an owner. Wallets, markets and other contracts read and move every KS-721 token the same way. Built-in assets are fungible amounts, so the VM cannot say who holds a given item: a collection is a contract that keeps the owner of each token in its own storage. KS-721 fixes its methods, events and refusals, so that a wallet shows any collection's tokens and a market sells any of them. Like [KS-20](https://ksana.network/docs/ks-20/), it is a convention between contracts, wallets and indexers, not a consensus rule, specified in [`docs/STANDARDS.md`](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/STANDARDS.md); [Assets and tokens](https://ksana.network/docs/tokens/) covers what the two share. ## Interface ```abi title="KS-721" view standards() -> Vec // ["KS-721", extensions...] view metadata() -> (String, String) // (name, symbol) view capabilities() -> Vec view owner_of(token_id: [u8; 32]) -> Option // None for a token that does not exist, or was burned view balance_of(owner: Account) -> u64 // how many tokens owner holds view token_uri(token_id: [u8; 32]) -> Option view approved(token_id: [u8; 32]) -> Option view is_operator(owner: Account, operator: Account) -> bool // now: false once expired view operator_info(owner: Account, operator: Account) -> (bool, Option) // (approved, expires_at) as set call transfer(to: Account, token_id: [u8; 32]) // the owner only call transfer_from(from: Account, to: Account, token_id: [u8; 32]) // the owner, the approved account or an operator call approve(spender: Option, token_id: [u8; 32]) // the owner or an operator; None clears call set_operator(operator: Account, approved: bool, expires_at: Option) payable call transfer_and_call(to: ContractId, token_id: [u8; 32], data: Bytes) -> Bytes // the owner only event standards(ids: Vec) event metadata(name: String, symbol: String) event transfer(from: Account, to: Account, token_id: [u8; 32]) event approve(owner: Account, spender: Option, token_id: [u8; 32]) event operator(owner: Account, operator: Account, approved: bool, expires_at: Option) event uri(token_id: Option<[u8; 32]>) ``` A contract that takes tokens in one step adds `payable call on_nft_received(from: Account, token_id: [u8; 32], data: Bytes) -> Bytes`. Minting is the collection's own method, as is `init`: collections number their tokens in different ways, so the standard leaves it out, and a collection that can still mint reports `mint` in `capabilities()`. ## Rules 1. **Declaration**: `init` emits `standards`, then `metadata`, before any `transfer`, and `standards()` starts with `"KS-721"`. A contract never declares both KS-20 and KS-721. 2. **Every change of owner is an event**: every mint, transfer and burn emits `transfer`, a mint from the zero account and a burn to it, and `balance_of` is the number of tokens an account holds. 3. **Approvals end with the owner**: a change of owner clears the token's approved account, with no event of its own. 4. **Who moves a token**: `transfer` and `transfer_and_call` are the owner's alone (`not the owner`). `transfer_from` is the owner's, the approved account's or an operator's (`not authorized`), and `from` must own the token now (`wrong owner`), so a market's old listing cannot sell a token its owner moved to another wallet. 5. **Recipients**: neither the zero account (`zero account`) nor the collection itself (`recipient is this contract`), nor the token's owner (`already the owner`). 6. **IDs are minted once**: an ID that a token has (`token exists`) or had before it was burned (`token was burned`) is never minted again. 7. **Attached funds**: every method but `transfer_and_call` reverts with `unexpected attached funds`. 8. **Approvals and operators**: the approved account is never the zero account nor the owner (`spender is the owner`). An operator moves, approves and burns every token of the owner, present and future, while the block timestamp is below `expires_at` (always for `None`); `set_operator` with `approved` false takes it back. 9. **Unknown tokens**: a method naming a token that does not exist reverts with `unknown token`; the views answer `None`. 10. **A collection's own rules** refuse with a reason that starts with `rejected: `. 11. **URIs**: a change of a token's URI after its mint emits `uri(Some(token_id))`, and a change of every token's (a new base URI) `uri(None)`, so wallets read them again. `transfer_and_call` works as KS-20's: the owner calls it on the collection, which moves the token to the contract `to`, calls its `on_nft_received(owner, token_id, data)` with the attached funds, and returns its answer; when the recipient refuses or fails, the whole operation fails and the token stays with its owner. The recipient checks that `caller()` is a collection it accepts. ## Token IDs and URIs A token ID is 32 bytes, as long as an account or a transaction ID, so it can hold a hash: a name service can use the SHA-256 of a name, a collection that follows Bitcoin transactions their IDs. A serial number `n` is written big-endian in the last 16 bytes, so storage keys sort by serial number, and wallets show an ID whose first 16 bytes are zero as `#n`. `token_uri` points to a JSON document in ERC-721's metadata format (`name`, `description`, `image`, `attributes`), by a `data:`, `https:`, `ipfs:` or `ar:` URI; a wallet that finds no JSON there shows the URI as an image or as text. A `data:` URI stored on chain is bound by the 64 KiB limit of a storage value, and the reference implementation takes URIs of up to 2,048 bytes. Wallets show images with `` only, SVG included, and load remote ones through a proxy or when you open them. ## Events | Event | Fields | When | | --- | --- | --- | | `standards` | `ids: Vec` | in `init`, once | | `metadata` | `name: String, symbol: String` | in `init`, and again when the name or the symbol changes | | `transfer` | `from: Account, to: Account, token_id: [u8; 32]` | every mint, transfer and burn | | `approve` | `owner: Account, spender: Option, token_id: [u8; 32]` | every `approve`; `None` clears | | `operator` | `owner: Account, operator: Account, approved: bool, expires_at: Option` | every `set_operator` | | `uri` | `token_id: Option<[u8; 32]>` | a token's URI changed after its mint (`None`: every token's) | ## Extensions ```abi title="KS-721-burnable" call burn(token_id: [u8; 32]) // the owner, the approved account or an operator ``` ```abi title="KS-721-enumerable" view total_supply() -> u64 // how many tokens exist view tokens(start: u64, limit: u32) -> Vec<[u8; 32]> // every token, a page from position start view tokens_of(owner: Account, start: u64, limit: u32) -> Vec<[u8; 32]> // owner's tokens, a page ``` A page holds at most 100 IDs, and a `start` past the end gives an empty page. Keeping the lists costs gas at every mint, transfer and burn, which is why the extension is optional: wallets can list a holder's tokens from a node's index without it. ## Build a collection The contract SDK implements KS-721 in its `ks721` module, behind the same `standards` feature as [KS-20](https://ksana.network/docs/ks-20/#build-a-token). `Ks721::new()` with `.burnable()` and `.enumerable()` answers every standard method in `Ks721::dispatch`; the collection adds its own `init` and `mint`, and `ks721::id(n)` makes the ID of serial number `n`: ```rust title="src/lib.rs" #![cfg_attr(target_arch = "wasm32", no_std)] extern crate alloc; use alloc::string::String; use ksana_contract_sdk::{self as sdk, ks721::{self, Ks721}, standard, storage, CallResult}; sdk::entry!(dispatch); const NFT: Ks721 = Ks721::new().burnable().enumerable(); pub fn dispatch(method: &str, args: &[u8]) -> CallResult { match method { "init" => { standard::no_funds()?; let (name, symbol): (String, String) = sdk::decode(args)?; NFT.init(&name, &symbol)?; storage::write(b"minter", &sdk::caller()); sdk::ok(&()) } "mint" => { standard::no_funds()?; let (to, serial, uri): ([u8; 32], u128, Option) = sdk::decode(args)?; if storage::read::<[u8; 32]>(b"minter")? != Some(sdk::caller()) { return sdk::revert("not the minter"); } NFT.mint(&to, &ks721::id(serial), uri.as_deref())?; sdk::ok(&()) } _ => NFT.dispatch(method, args).unwrap_or_else(|| sdk::revert("unknown method")), } } ``` The implementation keeps its state under keys that start with `KS721:`. A `Policy` adds the collection's own rules, a check before every change of owner that can also keep the collection's records, and `conformance::ks721(setup)` checks a collection on the mock host as the KS-20 kit checks a token. The example `contracts/examples/nft` is a KS-721 collection built this way, burnable and enumerable, with a market of its own: owners list tokens at a fixed price in any built-in asset, and a buyer pays it attached to `buy`. The playground's [KS-721 NFT page](https://playground.ksana.network/#/nft) deploys it. The test collection `contracts/testing/collection`, burnable and enumerable, deploys for about 842,000 gas (33.6 KB of code), and a mint takes about 169,000, a transfer 176,000 and a `transfer_and_call` 218,000, measured as KS-20's are. --- # Example contracts URL: https://ksana.network/docs/example-contracts/ > The repository ships example contracts, from the reference KS-20 token to a market that sells KSA for bitcoin, the poll of the first tutorial, six more written for the contract playground, and one test contract. Each is a tested model to read, build and deploy. The contracts live in `contracts/` of the repository, a Cargo workspace of their own. The comment at the top of each crate’s `src/lib.rs` documents every method, event and rule; this page summarizes them. | Contract | What it shows | Directory | | --- | --- | --- | | [`token`](#token) | the reference [KS-20](https://ksana.network/docs/ks-20/) token: storage, events, allowances | `contracts/examples/token` | | [`amm`](#amm) | calls to other contracts, attached funds, tokens paid in one step | `contracts/examples/amm` | | [`amm-factory`](#amm-factory) | contracts that create contracts | `contracts/examples/amm-factory` | | [`btc-payment-trigger`](#btc-payment-trigger) | Bitcoin headers and payment proofs | `contracts/examples/btc-payment-trigger` | | [`ksa-exchange`](#ksa-exchange) | `native_tx` and path C | `contracts/examples/ksa-exchange` | | [`poll`](#poll) | a first contract: a storage key per account, checks with reasons, events | `contracts/examples/poll` | | [`probe`](#probe) | every host function, for tests | `contracts/testing/probe` | ## Build and test them The native tests run each contract against the SDK’s mock host, with no node. Run them from the workspace: ```sh git clone https://github.com/ksana-in-bitcoin/ksana cd ksana/contracts cargo test --workspace ``` Build a module from inside `contracts/`, as a `cdylib` alone, so that `contracts/.cargo/config.toml` applies and the module stays small: ```sh cargo rustc --release --locked --target wasm32-unknown-unknown \ --package ksa-exchange --crate-type cdylib ``` The module lands in `contracts/target/wasm32-unknown-unknown/release/`, named after the package with underscores: `ksa_exchange.wasm`, `amm_factory.wasm`. Its bytes depend on the absolute path of your checkout, so build the file you deploy once and compute IDs from that file. ## Deploy one Deploy with `ksana-cli deploy`, which takes the module and the Borsh bytes of the `init` arguments in hex. The output does not give the new contract’s ID: compute it from your account, the deploy op’s nonce and the SHA-256 of the module, with the `contract_id` helper of the [token and pool tutorial](https://ksana.network/docs/token-and-pool/#load-the-helpers), and your account in `ACCOUNT` as there. `ksa-exchange` takes no `init` arguments: ```sh export KSANA_RPC=https://signet.ksana.network/rpc W=target/wasm32-unknown-unknown/release ksana-cli deploy --key alice.key --code $W/ksa_exchange.wasm --fee-token 1 --wait > exchange.json EXCHANGE=$(contract_id $ACCOUNT $(jq -r .nonce exchange.json) $W/ksa_exchange.wasm) ``` The [tutorial](https://ksana.network/docs/token-and-pool/) deploys `token`, `amm` and `amm-factory`, with real output. Mainnet has not launched, so deploy on the signet. ## `token` The reference [KS-20](https://ksana.network/docs/ks-20/) token: the contract SDK's implementation with the extensions `KS-20-burnable` and `KS-20-mintable`, and no rules of its own. Its balances live in the contract’s storage, not in the node’s balance table like KSA’s, and you move them by calling the contract. `init` gives the supply to the deployer; a minter, when `init` names one, can mint more up to the cap, hand the role over or end minting for good. `approve(spender, amount, expires_at)` lets a contract take your tokens with `transfer_from` until `expires_at`, a block timestamp in seconds (`None` never expires); it sets the allowance, it does not add to it. `transfer_and_call` pays a contract and calls its `on_token_received` in the same operation, so a pool needs no allowance at all. | Method | Arguments | Returns | | --- | --- | --- | | `init` | `(name: String, symbol: String, decimals: u8, supply: u128, minter: Option<[u8; 32]>, cap: Option)` | `()` | | `transfer` | `(to: [u8; 32], amount: u128)` | `()` | | `transfer_from` | `(from: [u8; 32], to: [u8; 32], amount: u128)` | `()` | | `approve` | `(spender: [u8; 32], amount: u128, expires_at: Option)` | `()` | | `transfer_and_call` | `(to: [u8; 32], amount: u128, data: Vec)`, funds attached for the recipient | `Vec`, the recipient’s answer | | `burn` | `amount: u128` | `()` | | `burn_from` | `(from: [u8; 32], amount: u128)` | `()` | | `mint` | `(to: [u8; 32], amount: u128)`, the minter only | `()` | | `set_minter` | `minter: Option<[u8; 32]>`, the minter only | `()` | | `balance_of` | `account: [u8; 32]` | `u128` | | `allowance` | `(owner: [u8; 32], spender: [u8; 32])` | `u128`, 0 once expired | | `allowance_info` | `(owner: [u8; 32], spender: [u8; 32])` | `(u128, Option)` | | `total_supply` | none | `u128` | | `metadata` | none | `(name, symbol, decimals)` | | `standards` | none | `Vec`: `KS-20`, `KS-20-burnable`, `KS-20-mintable` | | `capabilities` | none | `Vec`: `mint` while there is a minter | | `minter`, `cap` | none | `Option<[u8; 32]>`, `Option` | Events: `standards`, `metadata` and `minter` in `init`, then `("transfer", from, to, amount)` for every change of a balance, with `from` all zeros for a mint and `to` all zeros for a burn, and `("approve", owner, spender, amount, expires_at)`. The token written before KS-20 took `init` without the minter and the cap and `approve` without the expiry, and the reference token still takes both forms. ## `amm` A constant-product pool of two sides. A side is an [`AssetRef`](https://ksana.network/docs/tokens/#asset-ref): a KS-20 token or a built-in asset such as KSA, encoded as one byte (`0` token, `1` asset) and the 32-byte ID. A token side comes in one of two ways: in one step, with the token’s own `transfer_and_call(pool, amount, action)`, where `action` is a `PoolAction`, a swap or a deposit; or pulled by `swap` and `add_liquidity` with the token’s `transfer_from`, after you approve the pool. An asset side arrives attached to the call, in exactly the amount the arguments name, and with `transfer_and_call` the token passes it on. The first deposit gets `isqrt(amount_a × amount_b)` shares. Later deposits get shares at the smaller of the two ratios of amount to reserve, and the pool takes only the amounts that ratio needs, refunding the excess of an asset side. A swap keeps a 0.3% fee: `out = in × 997 × R_out / (R_in × 1000 + in × 997)`, rounded down, and it reverts when `out` is below `min_out`. The pool keeps its reserves in storage, so assets sent to it directly do not move the price. `add_liquidity` reverts when the shares fall below `min_shares`, and `remove_liquidity` when either amount falls below its minimum. A swap just before a deposit moves the ratio the deposit enters at. Amounts in the pool’s ratio get fewer shares whichever way the ratio moves, so offer amounts in that ratio, with `min_shares` a little below the shares a `query` of the same deposit returns. Callers written before the minimums can leave them out: `(amount_a, amount_b)` and a bare `shares` mean minimums of 0. | Method | Arguments | Returns | | --- | --- | --- | | `init` | `(side_a: Side, side_b: Side)` | `()` | | `add_liquidity` | `(amount_a: u128, amount_b: u128, min_shares: u128)` | `u128`, the shares | | `remove_liquidity` | `(shares: u128, min_a: u128, min_b: u128)` | `(u128, u128)`, the amounts of A and B | | `swap` | `(id_in: [u8; 32], amount_in: u128, min_out: u128)` | `u128`, the amount out | | `reserves` | none | `(u128, u128)` | | `shares_of` | `account: [u8; 32]` | `u128` | | `total_shares` | none | `u128` | | `on_token_received` | `(from: [u8; 32], amount: u128, data: Vec)`, called by a token side | `Vec`: the Borsh `u128` paid out, or the shares | | `tokens` | none | `(AssetRef, AssetRef)` | `data` of `on_token_received` is a `PoolAction`: `00` and `min_out: u128` for `Swap(min_out)`, which swaps the tokens received and pays the other side to the sender, or `01`, `amount_other: u128` and `min_shares: u128` for `AddLiquidity`, which deposits them with up to `amount_other` of the other side (attached when it is an asset) and sends back what the ratio does not use. Only a token side of the pool may call it. Events: `("add_liquidity", provider, amount_a, amount_b, shares)`, `("remove_liquidity", provider, shares, amount_a, amount_b)` and `("swap", trader, id_in, amount_in, amount_out)`; through `transfer_and_call`, the provider or the trader is the account that sent the tokens. ## `amm-factory` Creates `amm` pools with `create_contract`, from the `amm` code already on chain: someone must have deployed `amm` once. `init` takes the code’s hash, the SHA-256 of the module. A `Side` here is encoded as the pool’s `AssetRef`. `create_pair` sorts the two sides by ID, then by kind, and uses the SHA-256 of their Borsh encoding as the salt. So each pair of sides gets one pool, at an ID you can compute in advance from the factory’s ID, the salt and the code hash. The pool’s `init` receives the sides in that order: in a pool of KSA and a token, KSA is side A, because its ID is all zeros. | Method | Arguments | Returns | | --- | --- | --- | | `init` | `amm_code_hash: [u8; 32]` | `()` | | `create_pair` | `(side_a: Side, side_b: Side)` | `[u8; 32]`, the pool’s ID | | `get_pair` | `(side_a: Side, side_b: Side)`, in either order | `Option<[u8; 32]>` | | `pair_count` | none | `u64` | | `pair_at` | `index: u64` | `Option<[u8; 32]>` | | `amm_code_hash` | none | `[u8; 32]` | Event: `("pair_created", side_a, side_b, pair)`. ## `btc-payment-trigger` Issues the contract’s own asset to whoever proves a Bitcoin payment to a watched script. `init` takes the script, the asset’s `sub_id`, its metadata `(name: String, symbol: String, decimals: u8)` and `units_per_sat`. It reverts on an empty script, a rate of 0 or metadata the host would refuse: a name of 1 to 64 bytes, a symbol of 1 to 16 bytes and at most 18 decimals pass. `claim` checks the proof against a Bitcoin header and checks that output `vout` pays the watched script. The transaction must also have an output `OP_RETURN ` (`6a20` and the 32-byte account), so nobody else can claim the payment first. Each `(txid, vout)` is claimed once, for `value × units_per_sat` of the asset, issued to the beneficiary. | Method | Arguments | Returns | | --- | --- | --- | | `init` | `(watch_script: Vec, sub_id: [u8; 32], meta, units_per_sat: u128)` | `()` | | `claim` | the proof, then `vout: u32` and `beneficiary: [u8; 32]` | `u128`, the amount issued | | `asset_id` | none | `[u8; 32]` | | `is_claimed` | `(txid: [u8; 32], vout: u32)` | `bool` | The proof is `height: u32`, `raw_tx: Vec`, `tx_index: u32`, `branch: Vec<[u8; 32]>`, `coinbase_tx: Vec` and `coinbase_branch: Vec<[u8; 32]>`, in that order. [Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/#proof) explains each part and builds the arguments of `claim` from a block. The event is `("claim", txid, vout, beneficiary, asset_id, amount)`, and the asset’s ID is the SHA-256 of the contract’s ID and `sub_id`. ## `ksa-exchange` Sells KSA for bitcoin. Top-ups use it: a buyer with sats and no KSA pays a seller on Bitcoin and receives KSA on Ksana, in one Bitcoin transaction. 1. The seller deposits KSA, with `deposit` or attached to `lock`, and calls `lock`. The lock reserves `ksa` base units for the buyer’s account at `price` base units per sat, payable to a Bitcoin script no other lock has used, until Bitcoin height `expiry`. 2. The buyer sends one Bitcoin transaction that pays the lock’s script and carries a path C op calling `claim(lock)`. When the op runs, `claim` reads [`native_tx()`](https://ksana.network/docs/bitcoin-in-contracts/#native-tx), adds up what the transaction pays to the script, and pays the KSA it buys to the buyer’s account, at most the KSA still locked. 3. A partial payment leaves the rest locked for the same buyer. Once the anchor reaches `expiry` + 6, the seller can `release` an open lock, and the KSA still in it returns to the seller’s free balance; `withdraw` takes KSA out of that balance. The beneficiary is fixed in the lock, so whoever submits a claim, the KSA goes to the buyer. The op’s signature covers the transaction’s first input, so a copied claim fails. Paying more than the lock holds buys nothing more, and paying a lock that is no longer open loses the bitcoin: read the lock before you pay. | Method | Arguments | Returns | | --- | --- | --- | | `init` | none, with no funds | `()` | | `deposit` | none, with KSA attached | `u128`, the free balance | | `withdraw` | `amount: u128` | `u128`, the free balance | | `lock` | `(ksa: u128, price: u128, script: Vec, beneficiary: [u8; 32], expiry: u32)` | `u64`, the lock’s number | | `claim` | `lock: u64`, from a path C op only | `(paid_sats: u64, ksa_paid: u128)` | | `release` | `lock: u64` | `u128`, the KSA taken back | | `get_lock` | `lock: u64` | `Lock` | | `lock_of_script` | `script: Vec` | `Option` | | `balance` | `seller: [u8; 32]` | `u128`, the free balance | | `lock_count` | `seller: [u8; 32]` | `u64` | | `locks_of` | `(seller: [u8; 32], start: u64, limit: u32)`, `limit` 1 to 256 | `Vec` | A `Lock` is `(seller, beneficiary, script, price, ksa, expiry, state)`, where `ksa` is what is still locked. `state` is `0` (open), `1` with the totals `paid_sats: u64` and `ksa_paid: u128` (claimed), or `2` (released). A lock’s script is at most 64 bytes and cannot start with `OP_RETURN`. [ksana-cli](https://ksana.network/docs/cli/) has `exchange` commands for sellers and a `top-up` command for buyers, and the [TypeScript SDK](https://ksana.network/docs/sdk/) builds a top-up for a browser wallet. ## `poll` The contract of the tutorial [Your first contract](https://ksana.network/docs/first-contract/), which writes, compiles and deploys it in the playground. The account that deploys it asks a question with 2 to 8 options, every account votes once while the poll is open, and the creator closes it. It is a contract’s basics at their smallest: a storage key for each voter, a check with a reason before every write, the caller as identity, and an event for every change. It needs nothing but the contract SDK, so the playground builds it on the Counter page. | Method | Arguments | Returns | | --- | --- | --- | | `init` | `(question: String, options: Vec)`: a question of 1 to 200 bytes, 2 to 8 options of 1 to 64 bytes | `()` | | `vote` | `option: u32`, once per account while the poll is open | `u64`, the option’s votes | | `close` | none, the creator only | `()` | | `poll` | none | `(String, Vec, bool)`: the question, the options, whether voting is open | | `results` | none | `Vec`, the votes of each option | | `voted` | `account: [u8; 32]` | `Option`, the option it voted for | Events: `("voted", voter, option)` and `("closed", total)`. Every method refuses attached funds. ## `probe` A test contract, not an example: it exposes the host functions as methods, so that the node’s execution and determinism tests can drive each one. Its methods include `send`, `issue`, `burn`, `forward`, `try_forward`, `delegate`, `create`, `set`, `get`, `env`, `recurse`, `spin`, `trap` and `revert`. Read it to see a host function used in isolation, and do not deploy it for real use. Its method table is at the top of `contracts/testing/probe/src/lib.rs`. ## Playground examples Six more examples were written for the [contract playground](https://ksana.network/docs/playground/), which has a page for each. Their `src/lib.rs` opens with the rules of every method and an [ABI block](https://ksana.network/docs/playground/#the-abi-block), from which the playground builds its forms. The playground's KS-20 token page uses the [`token`](#token) above, and its AMM page the [`amm`](#amm). | Contract | What it shows | Directory | | --- | --- | --- | | `playground-counter` | the smallest contract that keeps state: `init`, `increment`, `add`, `get` and a `changed` event | `contracts/examples/playground-counter` | | `mintable-token` | a built-in asset whose owner mints up to an optional cap; any holder burns, `set_owner` hands the minting over | `contracts/examples/mintable-token` | | `nft` | a [KS-721](https://ksana.network/docs/ks-721/) collection with URIs, approvals and operators, and fixed-price listings paid in any asset | `contracts/examples/nft` | | `lending` | one market: supply for shares, borrow against collateral at a price its admin sets, interest on a rate curve with a kink, liquidations | `contracts/examples/lending` | | `multisig` | owners and a threshold, and proposals to transfer, call another contract or change the owners | `contracts/examples/multisig` | | `vesting` | schedules with a cliff and a linear release, which their creator may revoke | `contracts/examples/vesting` | --- # Tutorial: a token and a pool URL: https://ksana.network/docs/token-and-pool/ > Deploy the reference KS-20 token on the public signet, open a pool that trades it against KSA, add liquidity and swap both ways in one operation each, all with `ksana-cli`. In this tutorial you deploy three of the [example contracts](https://ksana.network/docs/example-contracts/) and use them from the command line: - `token`, the reference [KS-20](https://ksana.network/docs/ks-20/) token, whose balances live in the contract’s own storage; - `amm`, a constant-product pool with your token on one side and KSA on the other; - `amm-factory`, a contract that creates pools at IDs you can compute in advance. A KS-20 token pays a contract with `transfer_and_call`, which moves the tokens and calls the contract in the same operation, so every deposit and swap below is one operation, with nothing to approve. Every command and output on this page comes from one run on 21 October 2026 on the public signet. Your IDs, hashes, heights and amounts will differ. Signet coins have no value, and mainnet has not launched: run this on the signet. ## Before you start You need: - `ksana-cli` on your `PATH`, built from the repository as in the [quickstart](https://ksana.network/docs/quickstart/) ([ksana-cli](https://ksana.network/docs/cli/) describes every command); - the repository’s Rust toolchain with the `wasm32-unknown-unknown` target: `rustup toolchain install`, run inside the clone, installs both from `rust-toolchain.toml`; - `bash`, `python3` and `jq`, for the helper functions below; - about 51 KSA on the signet. The faucet’s 100 KSA is enough, and the liquidity you remove comes back to you. Run every command from the root of your clone, in one `bash` session: later steps use the shell variables that earlier steps set. Each op costs a fee of 1 base unit here. ### Build the contracts The contracts are a separate Cargo workspace in `contracts/`. Build each one from inside that directory, as a `cdylib` alone, so that `contracts/.cargo/config.toml` applies and the module stays small: ```sh cd contracts for p in token amm amm-factory; do cargo rustc --release --locked --target wasm32-unknown-unknown --package $p --crate-type cdylib done cd .. W=contracts/target/wasm32-unknown-unknown/release wc -c $W/token.wasm $W/amm.wasm $W/amm_factory.wasm ``` ```output 28720 contracts/target/wasm32-unknown-unknown/release/token.wasm 25427 contracts/target/wasm32-unknown-unknown/release/amm.wasm 9598 contracts/target/wasm32-unknown-unknown/release/amm_factory.wasm 63745 total ``` The module bytes depend on the absolute path of your checkout, so your code hashes, and with them your contract IDs, differ from the ones below. ### Load the helpers `ksana-cli` takes contract arguments as the hex of their Borsh encoding and does no encoding for you. Save these functions as `helpers.sh`: ```sh title="helpers.sh" # Borsh values for --args and --init-args, contract IDs, and short receipts (python3, jq) enc_u128() { python3 -c 'import sys; print(int(sys.argv[1]).to_bytes(16, "little").hex())' "$1"; } enc_string() { python3 -c 'import sys; b = sys.argv[1].encode() print(len(b).to_bytes(4, "little").hex() + b.hex())' "$1" } enc_bytes() { # Bytes from hex: a u32 length, then the bytes python3 -c 'import sys; b = bytes.fromhex(sys.argv[1]) print(len(b).to_bytes(4, "little").hex() + b.hex())' "$1" } dec_u128() { # one or more u128 values, back to back python3 -c 'import sys; b = bytes.fromhex(sys.argv[1]) print(*(int.from_bytes(b[i:i + 16], "little") for i in range(0, len(b), 16)))' "$1" } dec_answer() { # the u128 a pool answers through transfer_and_call: Bytes, so skip its u32 length dec_u128 "${1:8}" } dec_strings() { # a Vec: a u32 count, then each string with its u32 length python3 -c 'import sys; b = bytes.fromhex(sys.argv[1]); i = 4; out = [] for _ in range(int.from_bytes(b[:4], "little")): n = int.from_bytes(b[i:i + 4], "little"); out.append(b[i + 4:i + 4 + n].decode()); i += 4 + n print(*out)' "$1" } code_hash() { python3 -c 'import hashlib, sys print(hashlib.sha256(open(sys.argv[1], "rb").read()).hexdigest())' "$1" } contract_id() { # sha256(account + nonce as u64 little-endian + sha256(code)) python3 -c 'import hashlib, sys code = hashlib.sha256(open(sys.argv[3], "rb").read()).digest() seed = bytes.fromhex(sys.argv[1]) + int(sys.argv[2]).to_bytes(8, "little") + code print(hashlib.sha256(seed).hexdigest())' "$@" } brief() { # the parts of a --wait result this tutorial reads jq '{nonce, op_id, status: .status.status, block: .status.block.height, gas_used: .status.receipt.gas_used, error: .status.receipt.error, output: .status.receipt.output}' "$@" } ``` Load them, point the CLI at the signet node, and keep the ID of KSA (32 zero bytes) at hand: ```sh source ./helpers.sh export KSANA_RPC=https://signet.ksana.network/rpc KSA=0000000000000000000000000000000000000000000000000000000000000000 ``` [How arguments are encoded](#encoding), below the steps, explains the bytes the helpers produce. ### Make a key and get KSA Create a key file, keep your account in `ACCOUNT`, and send your address to the faucet: ```sh ksana-cli --chain signet key alice.key ACCOUNT=$(ksana-cli --chain signet key alice.key | jq -r .account) curl -sS https://signet.ksana.network/faucet -H 'content-type: application/json' \ --data '{"to": "tb1pklkarsaaegsk2dxgh4ug9tru6q6x63gge8emdeltt8fpxm6r7zwse04hlm"}' | jq ``` ```output { "account": "b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d", "address": "tb1pklkarsaaegsk2dxgh4ug9tru6q6x63gge8emdeltt8fpxm6r7zwse04hlm", "internal_key": "e8ad3e8fc1e17bc0918445a0973c6111867e7236c025121d2215eb559ea78ccf", "script": "5120b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d" } { "op_id": "a91054efcbde256b412d0d5286d922ce5377ac6a3ea0941a2eabe41cbaaf090e", "to": "b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d", "amount": "10000000000", "nonce": "3" } ``` Put your own `address` in the faucet request. The faucet sends 100 KSA (10,000,000,000 base units) once a day per account; `ksana-cli account @alice.key` shows the balance a few seconds later. If you already hold signet KSA, skip the faucet. ### Deploy the token The token’s `init` takes `(name: String, symbol: String, decimals: u8, supply: u128, minter: Option<[u8; 32]>, cap: Option)` and gives the supply to the deployer. A minter could mint more up to the cap; `00` for each leaves both out, so the supply is fixed. This run creates 1,000,000 TUT with 8 decimals: ```sh INIT=$(enc_string "Tutorial Token")$(enc_string TUT)08$(enc_u128 100000000000000)0000 echo $INIT ksana-cli deploy --key alice.key --code $W/token.wasm --init-args $INIT \ --fee-token 1 --wait | tee token.json | brief ``` ```output 0e0000005475746f7269616c20546f6b656e030000005455540800407a10f35a000000000000000000000000 { "nonce": "0", "op_id": "6e5c44290d388596929b8b9e6f3250d99e0629e7beb1679e2952177144ff8150", "status": "fast_confirmed", "block": "31", "gas_used": "776169", "error": null, "output": "" } ``` `--fee-token 1` sends the op through path B with a fee of 1 base unit, the default packing floor of a node, which the signet’s seed nodes keep. Run `ksana-cli estimate-fee` to see what your node suggests. `--wait` polls until a block includes the op: `fast_confirmed` is the first of its [three marks](https://ksana.network/docs/confirmations/). The whole result, with the receipt’s events, stays in `token.json`. ### Find the token’s ID Nothing reports a new contract’s ID: you compute it. It is the SHA-256 of your account, the nonce of the deploy op as a little-endian u64, and the SHA-256 of the code: ```sh TOKEN=$(contract_id $ACCOUNT $(jq -r .nonce token.json) $W/token.wasm) echo $TOKEN jq -r '.status.receipt.events[0].contract' token.json ``` ```output 6569e81e9aa68a0ae8058c3f749de4b0f13d2f3448f12831d8ccf0960c329658 6569e81e9aa68a0ae8058c3f749de4b0f13d2f3448f12831d8ccf0960c329658 ``` The second line is a cross-check: the token’s `init` emits four events, `standards`, `metadata`, `minter` (none here) and the `transfer` of the supply, and every event names the contract that emitted it. Now read the token back. `query` runs a method on the node without submitting anything, so it costs no fee: ```sh dec_strings $(ksana-cli query --contract $TOKEN --method standards | jq -r .output) ksana-cli query --contract $TOKEN --method metadata ksana-cli query --contract $TOKEN --method balance_of --args $ACCOUNT | jq -r .output ``` ```output KS-20 KS-20-burnable KS-20-mintable { "asset_changes": [], "error": null, "events": [], "gas_used": "56186", "op_id": null, "output": "0e0000005475746f7269616c20546f6b656e0300000054555408", "success": true } 00407a10f35a00000000000000000000 ``` The first line is the token’s declaration: KS-20, and the two extensions the reference token implements. Then come `(name, symbol, decimals)` in Borsh and your balance, a u128: `dec_u128 00407a10f35a00000000000000000000` prints `100000000000000`, the whole supply. ### Deploy a pool A pool’s `init` takes its two sides, each an [`AssetRef`](https://ksana.network/docs/tokens/#asset-ref): one byte for its kind (`00` for a KS-20 token, `01` for a built-in asset such as KSA) followed by a 32-byte ID. Side A is your token and side B is KSA: ```sh ksana-cli deploy --key alice.key --code $W/amm.wasm --init-args 00${TOKEN}01${KSA} \ --fee-token 1 --wait | tee pool.json | brief POOL=$(contract_id $ACCOUNT $(jq -r .nonce pool.json) $W/amm.wasm) echo $POOL ``` ```output { "nonce": "1", "op_id": "b37ca78fd6d0d1a3434c505afd14b766f0a061e1a560b8800c7c050cf7218304", "status": "fast_confirmed", "block": "32", "gas_used": "672844", "error": null, "output": "" } eb5ca55289984d64598a12303a0638ee9dd6edc50f4bebe6d43a7a46121fc745 ``` The pool’s methods take amounts in side order: TUT first, then KSA. ### Add liquidity The token pays the pool: `transfer_and_call(to, amount, data)` moves `amount` of TUT to `to` and calls its `on_token_received` with `data`, in the same operation. For a pool, `data` holds a `PoolAction`: `01`, then `amount_other: u128` and `min_shares: u128`, deposits the tokens with up to `amount_other` of the other side, and `enc_bytes` puts the u32 length of `Bytes` in front. KSA is a built-in asset, so you attach it to the call with `--fund`, and the token passes it on to the pool. This deposit puts 100,000 TUT and 50 KSA into the pool: ```sh ksana-cli call --key alice.key --contract $TOKEN --method transfer_and_call \ --args $POOL$(enc_u128 10000000000000)$(enc_bytes 01$(enc_u128 5000000000)$(enc_u128 1)) \ --fund 5000000000 --fee-token 1 --wait | tee add.json | brief dec_answer $(jq -r .status.receipt.output add.json) ``` ```output { "nonce": "2", "op_id": "314c6927c5e955c040cf1b62018090bc46f42ab31b135cc8bb70afc27b6d033f", "status": "fast_confirmed", "block": "33", "gas_used": "214928", "error": null, "output": "10000000b5f50010340000000000000000000000" } 223606797749 ``` The op called the token, and its output is the pool’s answer, which the token returns unchanged: `Bytes`, a u32 length (`10000000`, 16) and then a u128, your number of pool shares, which `dec_answer` reads. The first deposit receives the integer square root of the product of the two amounts. A later deposit receives shares in proportion to the reserves; the pool takes only what the current ratio needs and sends the rest back. `min_shares`, 1 here, makes the deposit fail below that many shares. You are the only one depositing, so 1 will do; in a pool that others trade in, set it a little below the shares a `query` of the same call returns. Both contracts left their events in the one receipt: ```sh jq -c '.status.receipt.events[] | {contract, data}' add.json ``` ```output {"contract":"6569e81e9aa68a0ae8058c3f749de4b0f13d2f3448f12831d8ccf0960c329658","data":"080000007472616e73666572b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09deb5ca55289984d64598a12303a0638ee9dd6edc50f4bebe6d43a7a46121fc74500a0724e180900000000000000000000"} {"contract":"eb5ca55289984d64598a12303a0638ee9dd6edc50f4bebe6d43a7a46121fc745","data":"0d0000006164645f6c6971756964697479b7edd1c3bdca216534c8bd7882ac7cd0346d4508c9f3b6e7eb59d2136f43f09d00a0724e18090000000000000000000000f2052a010000000000000000000000b5f50010340000000000000000000000"} ``` Each event’s `data` starts with its name as a Borsh `String`, then its fields. The token’s `transfer` of 100,000 TUT from you to the pool comes first, then the pool’s `add_liquidity`, which names you as the provider, the two amounts and your shares. ### Quote a swap The pool’s own `swap` takes `(id_in: [u8; 32], amount_in: u128, min_out: u128)` and keeps a fee of 0.3% for the pool. To see what a swap returns, run it as a `query` with the same funds attached, and with your account as the caller so that the simulated transfer has KSA to move: ```sh QUOTE=$(ksana-cli query --contract $POOL --method swap \ --args $KSA$(enc_u128 100000000)$(enc_u128 1) --fund 100000000 --caller $ACCOUNT \ | jq -r .output) dec_u128 $QUOTE MIN_OUT=$(( $(dec_u128 $QUOTE) * 99 / 100 )) echo $MIN_OUT ``` ```output 195501696178 193546679216 ``` At these reserves, 1 KSA buys about 1,955.02 TUT. `MIN_OUT` accepts up to 1% less, in case another trade moves the price before yours. ### Swap KSA for TUT Send the same swap as an op, with `MIN_OUT` as the limit: ```sh ksana-cli call --key alice.key --contract $POOL --method swap \ --args $KSA$(enc_u128 100000000)$(enc_u128 $MIN_OUT) --fund 100000000 \ --fee-token 1 --wait | tee swap1.json | brief ``` ```output { "nonce": "3", "op_id": "019c46f11df1d8097a2acefe942e78ab1c3c225617b132838ecf2c22ef286b0d", "status": "fast_confirmed", "block": "34", "gas_used": "169247", "error": null, "output": "b224cf842d0000000000000000000000" } ``` The output is the TUT you received, 195,501,696,178 base units: nothing traded in between, so the quote was exact. Had the price moved past `MIN_OUT`, the op would have failed: a failed op keeps its fee and its nonce, and changes nothing else. ### Swap TUT for KSA Selling TUT takes one `transfer_and_call` of the token, whose action is a swap: `00`, then `min_out: u128`. Quote it with a `query` of the same call, which answers what the pool would pay out: ```sh QUOTE=$(ksana-cli query --contract $TOKEN --method transfer_and_call \ --args $POOL$(enc_u128 100000000000)$(enc_bytes 00$(enc_u128 1)) --caller $ACCOUNT | jq -r .output) echo $QUOTE dec_answer $QUOTE MIN_OUT=$(( $(dec_answer $QUOTE) * 99 / 100 )) echo $MIN_OUT ``` ```output 10000000525e0f03000000000000000000000000 51338834 50825445 ``` Then swap: ```sh ksana-cli call --key alice.key --contract $TOKEN --method transfer_and_call \ --args $POOL$(enc_u128 100000000000)$(enc_bytes 00$(enc_u128 $MIN_OUT)) \ --fee-token 1 --wait | tee swap2.json | brief dec_answer $(jq -r .status.receipt.output swap2.json) ``` ```output { "nonce": "4", "op_id": "ea50a2fe329d5c76117afb8d3663971c71514a178db51daa73cb0b22b13a751c", "status": "fast_confirmed", "block": "35", "gas_used": "172426", "error": null, "output": "10000000525e0f03000000000000000000000000" } 51338834 ``` 1,000 TUT bought 51,338,834 base units of KSA, about 0.513 KSA, in one op with nothing to approve. The pool’s `swap` and `add_liquidity` can still take a token side the old way, pulling it with the token’s `transfer_from` after you `approve` the pool, in two ops. ### Remove liquidity `remove_liquidity` takes `(shares: u128, min_a: u128, min_b: u128)` and pays out that fraction of both reserves, rounded down; it fails when either amount falls below its minimum. Read your shares and remove half of them: ```sh SHARES=$(dec_u128 $(ksana-cli query --contract $POOL --method shares_of --args $ACCOUNT | jq -r .output)) echo $SHARES ksana-cli call --key alice.key --contract $POOL --method remove_liquidity \ --args $(enc_u128 $(( SHARES / 2 )))$(enc_u128 1)$(enc_u128 1) --fee-token 1 --wait | tee remove.json | brief dec_u128 $(jq -r .status.receipt.output remove.json) ``` ```output 223606797749 { "nonce": "5", "op_id": "dfb53e962a874922cddff07f2c4fdeccc3aea2b5de555a6ca4db65c0b31b30b2", "status": "fast_confirmed", "block": "36", "gas_used": "195421", "error": null, "output": "90310d09810400000000000000000000563a7696000000000000000000000000" } 4952249151888 2524330582 ``` The output is `(u128, u128)`: 49,522.49151888 TUT and 25.24330582 KSA came back to your account. ### Create a pool with the factory `amm-factory` creates pools with `create_contract`, which instantiates code already stored on chain: the pool you deployed above stored the `amm` code. The factory’s `init` takes the hash of that code: ```sh ksana-cli deploy --key alice.key --code $W/amm_factory.wasm \ --init-args $(code_hash $W/amm.wasm) --fee-token 1 --wait | tee factory.json | brief FACTORY=$(contract_id $ACCOUNT $(jq -r .nonce factory.json) $W/amm_factory.wasm) echo $FACTORY ``` ```output { "nonce": "6", "op_id": "98db7cf37f05452b4f988a54bc3c53589cf44b41daf2c19883a7b02f64fed625", "status": "fast_confirmed", "block": "37", "gas_used": "326178", "error": null, "output": "" } 7ed0c04c348385122cc496d3c67ea4d1c9cc15fadcc66fe3f1fbf499304fd115 ``` `create_pair` takes two sides, creates the pool, and returns its ID. `get_pair` finds it again, with the sides in either order, and returns a Borsh `Option`: `01` and the ID, or `00` when there is no such pool. The new pool’s `tokens` shows its sides: ```sh ksana-cli call --key alice.key --contract $FACTORY --method create_pair \ --args 00${TOKEN}01${KSA} --fee-token 1 --wait | tee pair.json | brief PAIR=$(jq -r .status.receipt.output pair.json) ksana-cli query --contract $FACTORY --method get_pair --args 01${KSA}00${TOKEN} | jq -r .output ksana-cli query --contract $PAIR --method tokens | jq -r .output ``` ```output { "nonce": "7", "op_id": "797d9dc411ae59e79ce0aa8a369ec151f9416f7afb18569c0181fe81ebecc2e0", "status": "fast_confirmed", "block": "38", "gas_used": "243181", "error": null, "output": "2a220d0a8c6910fb557785daf4fdfed5eaea6f4690aeaedd9e0acb0ac008efb6" } 012a220d0a8c6910fb557785daf4fdfed5eaea6f4690aeaedd9e0acb0ac008efb6 010000000000000000000000000000000000000000000000000000000000000000006569e81e9aa68a0ae8058c3f749de4b0f13d2f3448f12831d8ccf0960c329658 ``` The factory sorts the two sides into one order, so each pair of sides gets one pool. KSA’s ID is all zeros, so in this pool side A is KSA and side B is TUT, as `tokens` shows: `01` and KSA’s ID, then `00` and your token’s. The new pool is empty and separate from the one you deployed yourself. Fund it the same way: whichever side the token is, `transfer_and_call` sends it, and `amount_other` is the KSA attached: ```sh ksana-cli call --key alice.key --contract $TOKEN --method transfer_and_call \ --args $PAIR$(enc_u128 1000000000000)$(enc_bytes 01$(enc_u128 500000000)$(enc_u128 1)) \ --fund 500000000 --fee-token 1 --wait | tee pairadd.json | brief dec_answer $(jq -r .status.receipt.output pairadd.json) dec_u128 $(ksana-cli query --contract $PAIR --method reserves | jq -r .output) ``` ```output { "nonce": "8", "op_id": "85aa965def12e9cc329dc120f9fcabf2ad165b70731917fc47158e0b87b42f0d", "status": "fast_confirmed", "block": "39", "gas_used": "215556", "error": null, "output": "100000005ee5cc34050000000000000000000000" } 22360679774 500000000 1000000000000 ``` The reserves are in side order: 5 KSA, then 10,000 TUT. ### Follow an op to final Your ops are fast-confirmed. Each one is on Bitcoin once a settlement carrying its block confirms on Bitcoin, and final once the Bitcoin block that gives that settlement its sixth confirmation, which decides the block final, has six confirmations of its own. Ask for the deploy op and for the settlement of its block, 31: ```sh ksana-cli op $(jq -r .op_id token.json) | jq '{status, block: .block.height}' ksana-cli settlement 31 | jq '{status, txid_rpc, confirmed, settled, btc_final}' ``` ```output { "status": "btc_final", "block": "31" } { "status": "confirmed", "txid_rpc": "5a4f1245b728011d71f732aab68fa34ccb5c6460fc5cc6166f9b7dfadb2f23d2", "confirmed": { "block": "c2d6d161fdef456778a3df4f2ffe65a4627ad100ccbd24122d78fd5006000000", "confirmations": 11, "height": 327281, "txid": "d2232fdbfa7d9b6f16c65cfc60645ccb4ca38fb6aa32f7711d0128b745124f5a" }, "settled": true, "btc_final": true } ``` The op was final about 48 minutes after its block, when the Bitcoin transaction carrying the block’s settlement had 11 confirmations: an op becomes `btc_final` five Bitcoin blocks after that transaction’s sixth confirmation. Signet blocks came about every 4 minutes during this run; at their usual 10 minutes, it takes about two hours after the block. `txid_rpc` is that transaction’s ID as explorers show it, while `confirmed.txid` and `confirmed.block` are in Bitcoin’s internal byte order. Your other ops follow as the settlements of their blocks get there. A failed op never shows `btc_final`: it stays `failed` even once its block is final. ## How arguments are encoded A method’s arguments are a Borsh tuple: the encodings of its parameters, back to back. A method with one parameter takes that parameter’s encoding, and a method with none takes empty bytes. Return values follow the same rules. | Type | Borsh bytes | Helper or example | | --- | --- | --- | | `u8` | 1 byte | `08` | | `u128` | 16 bytes, little-endian | `enc_u128 5000000000`, `dec_u128` | | `String` | u32 length, little-endian, then UTF-8 | `enc_string TUT` gives `03000000545554` | | `Bytes`, `Vec` | u32 length, little-endian, then the bytes | `enc_bytes`; `dec_answer` reads a u128 in it | | `Vec` | u32 count, little-endian, then each `String` | the output of `standards`, read by `dec_strings` | | `[u8; 32]` | the 32 bytes, with no length | an account, a contract ID, `$KSA` | | `Option` | `00`, or `01` then `T` | the minter and the cap of `init`, the output of `get_pair` | | `AssetRef` | `00` (KS-20 token) or `01` (built-in asset), then the ID | `00${TOKEN}`, `01${KSA}` | | `PoolAction` | `00` then `min_out: u128` (a swap), or `01` then `amount_other: u128` and `min_shares: u128` (a deposit) | the `data` of `transfer_and_call` to a pool, in `Bytes` | [Write a contract](https://ksana.network/docs/contracts/) explains the conventions from the contract’s side. ## If something goes wrong - **The status is `failed`.** `error` says why, for example `revert: output below min_out` when the price moved past your limit before your swap; quote again and send it again. A failed op still uses its nonce and pays its fee, and a `query` of the same call shows the error for nothing. - **`revert: insufficient allowance`.** You gave the pool’s own `swap` or `add_liquidity` the TUT side, which the pool pulls with `transfer_from`. Send TUT with the token’s `transfer_and_call` instead, or `approve` the pool first. - **`revert: unexpected attached funds`.** Funds went where nothing takes them, such as KSA attached to a swap of TUT. Attach KSA to a deposit, or to a swap that sells KSA. - **`--wait` times out.** After 120 seconds (`--timeout`) the CLI prints only an error, without the op ID, although the op was sent. Run `ksana-cli account @alice.key`: when `nonce` has gone up, the op is in a block, and `ksana_getAccountOps` in the [JSON-RPC API](https://ksana.network/docs/rpc/) lists it. - **The node refuses the op.** It refuses a fee below its floor. The CLI takes the nonce from the account’s state, so a second op sent before the first is in a block gets the same nonce: the node refuses it, or, when its fee is higher, drops the first op for it. Send ops one at a time with `--wait`, as on this page. ## Next steps - [KS-20 tokens](https://ksana.network/docs/ks-20/) The interface, rules and extensions of fungible tokens, and how to build one. - [Example contracts](https://ksana.network/docs/example-contracts/) Every method of the token, the pool and the factory, and the other examples. - [Write a contract](https://ksana.network/docs/contracts/) Start your own contract, test it, and deploy it. - [TypeScript SDK](https://ksana.network/docs/sdk/) Call the same contracts from a web app or a script. --- # Protocol parameters URL: https://ksana.network/docs/parameters/ > Every protocol parameter of devnet, signet and mainnet, with the name of the constant that holds it, so that you can find each value in the code. Mainnet has not launched; the public signet is the network to use. All protocol parameters live in one file, `crates/ksana-primitives/src/params.rs`: the struct `Params` and one constant for each network, `DEVNET`, `SIGNET` and `MAINNET`. This page names each parameter as the specification and the code comments do (`CHAIN_ID`, `ANCHOR_DEPTH`). The field in `Params` is the same name in lowercase, with a unit suffix on six of them (`target_block_time_secs`, `asert_half_life_secs`, `max_future_block_time_secs`, `max_timestamp_ahead_of_anchor_secs`, `min_settlement_feerate_sat_vb`, `max_wasm_memory_bytes`). Amounts are in base units: KSA has 8 decimals, so 1 KSA is 100,000,000 base units. Times given in seconds or years assume the target of one unit of DAA score every 5 seconds. Mainnet has not launched: its values are the ones the [specification](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md) freezes, and its section 13.1 gives the reason for each and marks the few still to be measured before launch, such as the Argon2id parameters. ## The three networks | Network | `CHAIN_ID` | Runs on | Account addresses | | --- | --- | --- | --- | | devnet | 1001 | Bitcoin regtest, on your machine | Taproot, starting `bcrt1p` | | signet | 1002 | Bitcoin's public signet | Taproot, starting `tb1p` | | mainnet | 1000 | Bitcoin mainnet (Ksana's mainnet has not launched) | Taproot, starting `bc1p` | The project hosts two seed nodes, an indexer and the web wallet of the signet at `signet.ksana.network` (see [Public signet](https://ksana.network/docs/signet/)). The node and the indexer pick the network with `--chain devnet|signet|mainnet` and default to `devnet`. `ksana-cli` takes the network from the chain ID of the node it talks to, and its `--chain` only states the network you expect. The chain ID is written into every VmOp, so an operation signed for one network is invalid on the others. It is also part of the Argon2id salt of the proof of work. ## What differs between networks | Constant | devnet | signet | mainnet | | --- | --- | --- | --- | | `CHAIN_ID` | 1001 | 1002 | 1000 | | `ANCHOR_DEPTH` | 0 | 1 | 2 | | `NATIVE_CONFIRMATIONS` | 1 | 1 | 3 | | `POW_LIMIT_BITS` | `0x207fffff` | `0x1f0fffff` | `0x1f00ffff` | | `BLOCK_REWARD` | 990,000,000 (9.9 KSA) | 990,000,000 (9.9 KSA) | 420,000,000 (4.2 KSA) | | `REWARD_HALVING_INTERVAL` | 25,228,800 | 25,228,800 | 12,500,000 | | `REWARD_INTERVAL_DOUBLINGS` | 0 | 0 | 2 | | `KSA_MAX_SUPPLY` | 1,000,000,000 KSA | 1,000,000,000 KSA | 210,000,000 KSA | Every other parameter on this page has the same value on all three networks. Signet differs from devnet only in `CHAIN_ID` and `ANCHOR_DEPTH`, which a test in `params.rs` checks. A path C transaction is force-included once it has `NATIVE_CONFIRMATIONS` + `ANCHOR_DEPTH` Bitcoin confirmations: 1 on devnet, 2 on signet and 5 on mainnet. A block anchored at Bitcoin height A must include the native transactions up to height A − `NATIVE_CONFIRMATIONS` + 1, and producers anchor `ANCHOR_DEPTH` blocks below their Bitcoin tip (`crates/ksana-btc/src/native.rs`). ## Proof of work and difficulty | Constant | Value | Meaning | | --- | --- | --- | | `TARGET_BLOCK_TIME` | 5 seconds | Target time per unit of DAA score | | `ASERT_HALF_LIFE` | 7,200 seconds | Half-life of the aserti3-2d difficulty adjustment, computed by DAA score with the genesis block as its anchor | | `POW_ALGORITHM` | Argon2id | RFC 9106, version 0x13: the message is the Borsh-encoded block header, the salt is `ksana-pow` followed by the chain ID as 4 little-endian bytes, and the 32-byte output is read as a little-endian number | | `POW_ARGON2_MEMORY` | 2,048 KiB (2 MiB) | Memory of one evaluation (`Argon2Params::memory_kib`) | | `POW_ARGON2_ITERATIONS` | 1 | Passes (`iterations`) | | `POW_ARGON2_LANES` | 1 | Parallelism (`lanes`) | | `POW_LIMIT_BITS` | By network, above | The easiest target, and the genesis block's `bits` when its config gives none | | `EMPTY_BLOCK_DIFFICULTY` | 12 | Weight of the first empty block after a non-empty block | | `MAX_EMPTY_BLOCK_WEIGHT` | 120 | Cap on the weight of consecutive empty blocks | One Argon2id evaluation takes about 1 ms on one core of an ordinary CPU. On mainnet, `0x1f00ffff` is a target of about 2^240: about 65,536 evaluations per block at the limit, so about 13 cores find a block every 5 seconds there. A genesis config can set a harder `bits` to match the hashrate expected at launch. The signet uses `0x1f0fffff`, a target of about 2^244: about 4,096 evaluations per block at the limit, about 3.5 seconds of one core, so that a side branch whose difficulty has fallen to the limit still pays for every header it puts on Bitcoin. Devnet uses `0x207fffff`, the easiest target of Bitcoin regtest. **Two-speed difficulty.** A block with entries has weight 1. The s-th empty block in a row on a selected chain has weight min(N × 2^(s − 1), N_MAX), with N = `EMPTY_BLOCK_DIFFICULTY` and N_MAX = `MAX_EMPTY_BLOCK_WEIGHT`: 12, 24, 48, 96, then 120 for every further one (`Params::empty_block_weight`). The weight divides the block's PoW target, adds to the DAA score and counts the block's reward slots, so an idle chain makes a block about every 1, 2, 4, 8 and then 10 minutes. See [Mining](https://ksana.network/docs/mining/). ## Timestamps | Constant | Value | Meaning | | --- | --- | --- | | `MEDIAN_TIME_SPAN` | 11 | Reception rule: a new block's timestamp must exceed the median of the 11 blocks before it on its selected chain | | `MAX_FUTURE_BLOCK_TIME` | 15 seconds | Reception rule: how far a new block's timestamp may be ahead of the receiving node's clock | | `MAX_TIMESTAMP_AHEAD_OF_ANCHOR` | 14,400 seconds (4 hours) | Consensus rule: how far a timestamp may be ahead of the time of the Bitcoin block its anchor names | A node checks a reception rule only when it receives a new block. A consensus rule holds for every block, including blocks synced from history or rebuilt from Bitcoin. ## Block DAG | Constant | Value | Meaning | | --- | --- | --- | | `GHOSTDAG_K` | 16 | Most blue blocks that a blue block's anticone may hold | | `MAX_BLOCK_PARENTS` | 10 | Most parents of a block | | `MAX_MERGESET_SIZE` | 128 | Largest merge set, the selected parent included | | `MERGE_DEPTH` | 720 blue score (about an hour of 5-second blocks) | A merged block's blue score may be at most this far below the selected parent's, and its selected chain must pass through the merge-depth root | | `REORG_WINDOW` | 1,000 blocks | Deepest switch of the main chain by work; a forced switch to the finalized chain is not bound by it | Pruning keeps a node's memory bounded. The pruning point lies at least `GhostdagParams::min_pruning_depth` = 3 × (`MERGE_DEPTH` + `GHOSTDAG_K`) + 1 = 2,209 blue score below the pruning root (`crates/ksana-consensus/src/ghostdag.rs`). How far back the root is, and how often a node prunes, are local settings, listed under [Local policy defaults](#local-policy-defaults). ## Bitcoin anchoring and finality | Constant | Value | Meaning | | --- | --- | --- | | `ANCHOR_DEPTH` | 0, 1, 2 | How many blocks below its Bitcoin tip a producer anchors a new block (devnet, signet, mainnet) | | `MAX_ANCHOR_LAG` | 1 Bitcoin block | How far a new block's anchor may lag behind the receiving node's Bitcoin tip, beyond `ANCHOR_DEPTH` | | `NATIVE_CONFIRMATIONS` | 1, 1, 3 | Bitcoin confirmations, counted at a block's anchor, after which that block must include a path C transaction (devnet, signet, mainnet) | | `SETTLEMENT_DEPTH` | 2 blocks | Fast-lane confirmations before a block's settlement is broadcast; also what the indexer waits for before it executes a main-chain block that is not final yet | | `SETTLEMENT_TIMEOUT` | 6 Bitcoin blocks | When a block's body has not landed on Bitcoin this many blocks after its anchor, new blocks may hold only forced-inclusion entries until it lands (the settlement backlog limit) | | `BTC_FINALITY_CONFS` | 6 | Bitcoin confirmations that a block's data, and the data of the blocks it merges, needs before the block is decided final; the Bitcoin block of that decision then needs as many before the block is reported final | | `BTC_QUERY_DEPTH` | 6 | A contract reads only the Bitcoin headers at least this many blocks below its block's anchor height | | `MIN_SETTLEMENT_FEERATE` | 1 sat/vB | Lowest fee rate of a commit or reveal transaction (a consensus rule; nodes pay 2 sat/vB or more by default) | | `CARRIER_REPOST_DELAY` | 2 Bitcoin blocks | The payee of a republish payload earns the carrier reward only when the block's data landed more than `ANCHOR_DEPTH` + 2 Bitcoin blocks after its anchor | [Confirmations](https://ksana.network/docs/confirmations/) explains what these numbers mean for the time an operation takes to become final. ## Data limits | Constant | Value | Meaning | | --- | --- | --- | | `MAGIC` | `KSN1` | Marker of KSN1 data outputs and envelopes | | `MAX_OP_BYTES` | 65,536 bytes (64 KiB) | Largest encoded VmOp, contract code included | | `MAX_BLOCK_DATA_BYTES` | 81,920 bytes (80 KiB) | Largest payload, settlement or republish; a block that needs a body is valid only if its body fits in a republish payload of its own | | `MAX_SETTLEMENT_HEADERS` | 500 | Most block headers in one payload, checked before any header is decoded | | `MAX_CHUNK` | 520 bytes | Largest data push in a KSN1 output or envelope (`crates/ksana-btc/src/data.rs`) | | `MAX_SETTLEMENT_TX_BYTES` | 400,000 bytes | Largest commit or reveal transaction; `MAX_SETTLEMENT_WEIGHT` caps its weight at 400,000 WU (`crates/ksana-btc/src/settlement.rs`) | | `PRODUCER_SEQUENCE` | `0xFFFFFFFD` | The `nSequence` that every input of a commit and reveal transaction must have | | `MAX_BIP322_SIG_BYTES` | 1,024 bytes | Largest BIP322 simple signature (`crates/ksana-crypto/src/bip322.rs`) | | `MAX_CALL_FUNDS` | 16 | Most assets attached to one call | | `VMOP_VERSION` | 2 | Version of the VmOp format | | `BLOCK_VERSION` | 2 | Block header version, the protocol version while no upgrade has activated | The last three are in `crates/ksana-primitives/src/lib.rs`. These limits are consensus rules too: changing one is a consensus change, the same as changing a field of `Params`. ## Gas and execution limits | Constant | Value | Meaning | | --- | --- | --- | | `BLOCK_GAS_LIMIT` | 100,000,000 | Most gas in one block, counted as the sum of the entries' `max_gas`; a forced-inclusion entry counts `min(max_gas, NATIVE_MAX_GAS)` and is not bound by the limit, an unlock entry counts 0 | | `NATIVE_MAX_GAS` | 1,000,000 | Most gas a path C operation may ask for; one that passes its checks but asks for more fails, and its nonce is used | | `MAX_WASM_MEMORY` | 16 MiB (16,777,216 bytes) | Linear memory of a contract | | `MAX_CALL_DEPTH` | 8 | Deepest chain of contract-to-contract calls | The virtual machine adds fixed limits in `crates/ksana-vm/src/limits.rs` (and `MAX_CALL_INPUT_BYTES` in `engine.rs`): | Constant | Value | Limits | | --- | --- | --- | | `MAX_STORAGE_KEY_BYTES` | 256 bytes | A storage key | | `MAX_STORAGE_VALUE_BYTES` | 65,536 bytes | A storage value | | `MAX_CALL_INPUT_BYTES` | 65,536 bytes | A call's input, the Borsh-encoded method and arguments | | `MAX_OUTPUT_BYTES` | 65,536 bytes | A contract's return value | | `MAX_EVENT_BYTES` | 16,384 bytes | One event | | `MAX_ASSET_META_BYTES` | 1,024 bytes | The metadata of `asset_issue` and `asset_create` | | `MAX_ASSET_NAME_BYTES` | 64 bytes | An asset's name, at least 1 byte | | `MAX_ASSET_SYMBOL_BYTES` | 16 bytes | An asset's symbol, at least 1 byte | | `MAX_ASSET_DECIMALS` | 18 | An asset's decimals | | `MAX_TABLE_ELEMENTS` | 4,096 | Elements of a WebAssembly table | | `STACK_BUDGET` | 262,144 bytes | Estimated stack of the call chain in one contract instance, metered at run time | | `MAX_INSTANCES_PER_OP` | 64 | Contract instances that one operation creates (every call creates one) | | `MAX_TOTAL_MEMORY_PER_OP` | 268,435,456 bytes (256 MiB) | Linear memory of all instances of one operation | The gas table, which prices every host function, is in [Host functions](https://ksana.network/docs/host-functions/). ## Rewards and supply KSA is issued only as block rewards. Each block takes as many reward slots as its weight, at the DAA scores it covers, and each slot pays the reward of its halving period. Period k lasts `REWARD_HALVING_INTERVAL` × 2^min(k, `REWARD_INTERVAL_DOUBLINGS`) DAA score and pays `BLOCK_REWARD` / 2^k per slot, rounded down to whole base units (`Params::reward_period_at`, `block_reward_at`). | Mainnet period | DAA scores | Reward per slot | About | | --- | --- | --- | --- | | 0 | 0 to 12,499,999 | 4.2 KSA | Years 0 to 2 | | 1 | 12,500,000 to 37,499,999 | 2.1 KSA | Years 2 to 6 | | 2 | 37,500,000 to 87,499,999 | 1.05 KSA | Years 6 to 14 | | 3 | 87,500,000 to 137,499,999 | 0.525 KSA | Years 14 to 22 | | 4 and later | 50,000,000 each | Half the period before | 8 years each | On mainnet the last base unit is paid in period 28, and from DAA score 1,387,500,000 (about year 220) the reward is 0. All of mainnet's slots together pay 20,999,999,600,000,000 base units, 4 KSA short of the cap. The bound `Params::max_total_rewards` = `BLOCK_REWARD` × `REWARD_HALVING_INTERVAL` × (`REWARD_INTERVAL_DOUBLINGS` + 2) is exactly `KSA_MAX_SUPPLY` on mainnet, so mainnet has no genesis allocation. On devnet and signet every period lasts 25,228,800 DAA score (about 4 years) and the first pays 9.9 KSA per slot; the reward is 0 from DAA score 756,864,000 (period 30). The bound on their rewards is 499,530,240 KSA, which leaves at most 500,469,760 KSA for genesis allocations under their 1,000,000,000 KSA cap. | Constant | Value | Meaning | | --- | --- | --- | | `CARRIER_BPS` | 500 (5%) | Share of each reward slot that goes to the block's carrier, taken out of the producer's part | | `CARRIER_FEE_BPS` | 5,000 (50%) | Carrier's share of the block's path B fees; the rest goes to the producer | | `MAX_UNLOCK_BATCH` | 1,024 | Most blocks that one unlock entry pays out, in the order the main chain accepted them | The carrier's part is 0.21 KSA of a 4.2 KSA slot on mainnet and 0.495 KSA of a 9.9 KSA slot on signet; when no carrier qualifies, it stays with the producer. Rewards and fees are paid at unlock, once the data of the block and of every block in its past has landed on Bitcoin. [KSA and rewards](https://ksana.network/docs/ksa/) explains the schedule, the carrier and unlocking. ## Upgrades `Params::upgrades` is empty on all three networks: blocks have protocol version 2 (`BLOCK_VERSION`) and accept VmOp version 2. An upgrade item raises the protocol version from a given DAA score and can set new values for these rules: `BLOCK_GAS_LIMIT`, `NATIVE_MAX_GAS`, the accepted VmOp versions, `BLOCK_SHARE_BPS`, `BLOCK_SHARE_END`, `CARRIER_BPS` and `CARRIER_FEE_BPS`. Other changes, such as new execution rules or encodings, branch on the protocol version in the code and activate with the same item. Some parameters are fixed for the life of a network and stay out of the upgrade table: `ASERT_HALF_LIFE`, `EMPTY_BLOCK_DIFFICULTY`, `MAX_EMPTY_BLOCK_WEIGHT`, the Argon2id parameters, `REWARD_INTERVAL_DOUBLINGS` and `CARRIER_REPOST_DELAY`. A node reports its chain ID, protocol version and next scheduled upgrade with `ksana_getChainInfo`: ```sh title="Read the signet's chain info" curl -s -H 'content-type: application/json' \ --data '{"jsonrpc":"2.0","id":1,"method":"ksana_getChainInfo","params":[]}' \ https://signet.ksana.network/rpc | jq .result ``` ```output { "chain_id": 1002, "tip": { "height": "281", "hash": "d18e91c9383400d27166695177decadb89399456e55d79eb6e6164d625edaf95" }, "daa_score": "12199", "protocol_version": 2, "next_upgrade": null, "max_known_version": 2, "finalized": { "height": "241", "hash": "0cb65c0a51c1200757560f9ed1a2aa28f5a01a236bbdda8005120eb609a8ae6b" } } ``` The DAA score runs far ahead of the height because the signet was mostly idle: its empty blocks weigh 12 to 120 each. ## Genesis configurations Every node and indexer of a network starts from the same genesis config, a JSON file (`crates/ksana-execution/src/genesis_file.rs`). A data directory records the config's fingerprint and refuses to open with another one. | Field | devnet | signet | mainnet | | --- | --- | --- | --- | | `timestamp` | When `devnet/init.sh` ran | 1792553063 (2026-10-21 03:24:23 UTC) | To be filled in at launch | | `btc_anchor` | The regtest tip | Signet height 327,273 | To be filled in, at least 2 blocks below the tip | | `bits` | Not given (`0x207fffff`) | 520523192 (`0x1f068db8`) | Optional, `0x1f00ffff` when not given | | `allocations` | 10,000 KSA to a test account | 110,000,000 KSA to two accounts | None allowed | | `block_share_account` | A generated account | Set, see below | A placeholder that no node accepts | - **devnet** has no committed file: `devnet/init.sh` writes a new one, with new random keys, each time the devnet starts from scratch. - **signet** uses the committed `signet/genesis.json`. Its `bits` expects about 10,000 Argon2id evaluations per block, sized for the two seed nodes that mine on one thread each (`signet/ksana-signet.sh`). The first allocation, 100,000,000 KSA, funds the [faucet](https://ksana.network/docs/signet/); the second, 10,000,000 KSA, belongs to the operator. - **mainnet** has only the template `mainnet/genesis.json`. A node or indexer refuses any config whose block share account is the placeholder `KSANA_BLOCK_SHARE_ACCOUNT_TBD___`, and on mainnet it also requires a block share account, no allocations, and a real anchor and timestamp. Mainnet does not start yet, whatever its config holds: the block share's values are not published, and nodes and indexers refuse mainnet until they are set in the code. ```json title="signet/genesis.json" { "timestamp": "1792553063", "btc_anchor": { "height": 327273, "hash": "41cb1fa60f4a0803b02024c7c0fd9cabb094f2935e7fcc4e7a63f03011000000" }, "bits": 520523192, "allocations": [ { "account": "de6603f052fd5bfaae5678a2a20ae6ae4fe4ae00c89db70a2efea7429851afc0", "amount": "10000000000000000" }, { "account": "6431409abb9b8434defe68b0e066cf76610ac7b1cf49f2d02bc807543877dc0e", "amount": "1000000000000000" } ], "block_share_account": "0073719af1ae0718ca4fde1055e6c5c34157eefd54302c9b19deb28927ce8d8c" } ``` The anchor hash is in Bitcoin's internal byte order, the reverse of what `bitcoin-cli getblockhash` prints. A consensus change before mainnet restarts the signet from a new genesis config, and balances do not carry over. ## Local policy defaults These are a node's own settings, not consensus rules: each operator can change them, and nodes with different settings still agree on the chain. [Run a node](https://ksana.network/docs/run-a-node/) explains the flags. | Setting | Default | Meaning | | --- | --- | --- | | `--min-token-fee` | 1 base unit | Packing floor: the smallest path B fee this node puts in its blocks | | `--min-relay-token-fee` | The packing floor | Relay floor: the smallest fee this node admits and forwards (the lower of the two applies) | | `--min-fee-per-kib` | 0 | Smallest fee rate this node packs, in base units per KiB of cost | | `--ksa-price-sat` | None | What one KSA is worth to the operator, in sat. With it, an op must also pay for its bytes at the Bitcoin fee rate the node pays: a KiB of its encoded size must pay the KSA worth 128 vB, whatever its `max_gas` (only with a funding key) | | Entry pool | 10,000 ops, 32 MiB | At most 64 ops per account, 8 of them behind a nonce gap (no flags) | | `--settlement-feerate` | 2 sat/vB | Floor of this node's Bitcoin fee rate: paid while bitcoind's mempool has room, and when bitcoind has no estimate | | `--max-settlement-feerate` | 1,000 sat/vB | Cap of this node's Bitcoin fee rate, CPFP bumps included; the rate paid at once while a lighter competing chain is on Bitcoin | | `--settlement-conf-target` | 3 Bitcoin blocks | Target of `estimatesmartfee`; not asked while a lighter competing chain is on Bitcoin, when the node pays the cap | | Room in the mempool | 500,000 vB | While bitcoind's mempool holds at most half a block (`ROOMY_MEMPOOL_VSIZE`) and the last Bitcoin block was at most half full, this node's new Bitcoin transactions pay the floor, or the mempool's minimum when that is higher, instead of the estimate; not while a lighter competing chain is on Bitcoin | | `ROOMY_BLOCK_WEIGHT` | 2,000,000 weight units | The most bitcoind's best block may have taken (`getblockstats`) for the next block to count as having room | | `BUMP_AFTER` | 2 Bitcoin blocks | A settlement pair this node sent that waits this long below bitcoind's estimate is bumped to it by a child transaction spending the reveal's change; with or without room in the mempool, one still waiting is bumped to at least twice its own rate, doubling for every further block, up to the cap. A change that cannot pay the rate pays what it can | | `BUMP_GRACE` | 2 minutes | A pair that waited while the next block showed room, and that a Bitcoin block found this long or more after the node first saw it waiting leaves out, is bumped at once to at least the next-block estimate | | `ROOM_DISTRUST_BLOCKS` | 6 Bitcoin blocks | After a Bitcoin block leaves such a pair out, the node's new transactions pay the estimate for this many blocks, whatever room shows; kept in memory only | | `CLAIM_PATIENCE` | 8 Bitcoin blocks | Longest a settlement claim in the Bitcoin mempool holds back a rescue (`RESCUE_ORDER_WINDOW` 6 + `RESCUE_DELAY` 2) | | `REPUBLISH_PATIENCE` | 2 Bitcoin blocks | Longest another sender's republish in the Bitcoin mempool keeps this node from republishing the same headers and bodies; it does so only while it pays at least this node's fee rate and everything it relies on has counted or is in the mempool as well | | `REPUBLISH_YIELD` | 10 seconds | Before it starts republishing a run whose first block it did not produce, a node waits one to six times this long, by that block's hash and the node's funding script, and then sends what the republishes that arrived meanwhile leave; not while a lighter competing chain is on Bitcoin | | `--hot-wallet-cap-sat` | 1,000,000 sats | With `--revenue-address`: what the funding wallet holds above this much (once the excess reaches 100,000 sats and a tenth of the cap) is moved to the revenue address by a separate sweep transaction | | `--funding-pool-target` | 64 | Confirmed funding outputs to keep, by splitting the largest into pieces of at least 100,000 sats | | Settlement batching | On | While a settlement is in flight (carried by a block anchored at most 2 Bitcoin blocks below the tip, `IN_FLIGHT_BTC_BLOCKS`, and not landed yet), new blocks leave their bodies for the next settlement, unless the bodies waiting, or a block's own, pass 10 KiB (`MAX_BLOCK_DATA_BYTES` / `PAYLOAD_BODY_TRIGGER` 8); `--no-settlement-batching` makes every block that needs a body carry its own settlement | | Pruning | On | The pruning root is the highest block decided final at least 144 Bitcoin blocks below the tip (`PRUNE_BTC_MARGIN`), and a node prunes again once the pruning point can advance 1,000 blue score (`PRUNE_STEP`); `--no-pruning` keeps everything | | Compiled contract code | 16,384 MiB on disk | Kept in `vm-cache` under the data directory and read back instead of compiled again; `--vm-code-cache-mib`, `0` keeps none | | Contract memory pool | 1 call | Contract calls that take their memory from a pool kept resident, up to 1 GiB each; `--vm-pooled-calls`, `0` turns it off | | Orphan pool | 256 blocks, 32 MiB | `MAX_ORPHANS`, `MAX_ORPHAN_BYTES` | | P2P connections | 100 inbound, 32 in the handshake | At most 4 inbound from one address (an IPv6 address by its /64) and 2 with one peer; loopback and private addresses count only in the totals (no flags) | | P2P quotas | Blocks 20/s, ops 1,000/s, sync requests 50/s | Token buckets of the address a peer connects from, with bursts of 100, 5,000 and 200, kept across reconnections; a peer banned by score (3 points, for 60 seconds) bans its address too | | Gossip awaiting validation | 256 MiB of blocks, 32 MiB of ops | At most a quarter of each from one address; an op longer than `MAX_OP_BYTES` is refused before it is decoded | | Sync serving | 4 requests at a time | At most 16 in flight from one address, and 256 MiB of responses being sent, a quarter of it from one address; a `GetMempool` response holds at most 4 MiB | | RPC limits | Batches of 64 calls, bodies of 1 MiB | Responses of 10 MiB, 100 connections and 16 subscriptions per WebSocket connection, for the node and the indexer ([JSON-RPC limits](https://ksana.network/docs/rpc/#limits)) | | `--btc-poll-ms` | 500 | Interval between syncs with bitcoind | | `--min-block-interval-ms` | 0 | Smallest gap between this node's own blocks | A read-only `ksana_call` runs with at most `BLOCK_GAS_LIMIT` gas, and a node runs at most 4 of them at a time. ## Default ports | Service | Default | Set with | | --- | --- | --- | | Node JSON-RPC, HTTP and WebSocket | `127.0.0.1:8545` | `--rpc-addr` | | Indexer JSON-RPC | `127.0.0.1:8546` | `--rpc-addr` | | Node P2P | Off; port 9000 by convention | `--p2p-listen /ip4/0.0.0.0/tcp/9000` | | bitcoind RPC (node, indexer, `ksana-cli`) | `http://127.0.0.1:18443` (regtest) | `--btc-rpc-url`; signet's bitcoind listens on 38332, mainnet's on 8332 | | Node URL of `ksana-cli` | `http://127.0.0.1:8545` | `--rpc` or `KSANA_RPC` | The devnet in Docker Compose publishes bitcoind on 18443 (P2P on 18444), its three nodes on 18545 to 18547 and its indexer on 18548. The signet's first seed node is `{{signet.p2p}}`, and its other endpoints are listed on [Public signet](https://ksana.network/docs/signet/). --- # Glossary URL: https://ksana.network/docs/glossary/ > Short definitions of the terms these docs use, in alphabetical order, each with a link to the page that explains it. ## A ### ABI The binary interface between a contract and the node: the module's exports `ksana_alloc` and `ksana_call`, the Borsh-encoded input and result of a call, and the host functions of the import module `ksana`. See [Host functions](https://ksana.network/docs/host-functions/). ### Account The 32-byte output key (BIP86) of a Taproot address, written as that address (`tb1p` on signet, `bc1p` on mainnet) or as 64 hex digits. The key that holds your bitcoin also controls your KSA, and each stays on its own chain. See [Accounts](https://ksana.network/docs/accounts/). ### Anchor The Bitcoin block, by height and hash, that every Ksana block names in its header (`btc_anchor`). Producers anchor `ANCHOR_DEPTH` blocks below their Bitcoin tip (1 on signet, 2 on mainnet), and everything a block's execution reads from Bitcoin lies at or below its anchor. See [How it works](https://ksana.network/docs/how-it-works/). ### Anchor-invalid block A block anchored, or merging a block anchored, on a Bitcoin block that is not on the Bitcoin best chain, usually after a Bitcoin reorg. Nodes still accept it as history, but it can never become final, so producers never merge it and the main chain never takes it. See [Security](https://ksana.network/docs/security/#unanchored-blocks). ### Argon2id The memory-hard function (RFC 9106) that Ksana's proof of work evaluates on each block header: 2 MiB of memory, one pass and one lane, about 1 ms per evaluation on one CPU core. A browser can verify a header too. See [Mining](https://ksana.network/docs/mining/). ### ASERT The difficulty adjustment (aserti3-2d). It sets each block's target from how far the chain runs ahead of or behind a schedule of one unit of DAA score every 5 seconds, with a half-life of 7,200 seconds. See [Mining](https://ksana.network/docs/mining/). ### Asset What an account holds in its balances: KSA, whose asset ID is 32 zero bytes, or an asset that a contract issues, whose ID is the SHA-256 hash of the contract's ID and a sub-ID. A token contract, such as a KS-20 token, is something else: it keeps its balances in its own storage. See [Assets and tokens](https://ksana.network/docs/tokens/). ### Attached funds Built-in assets that an operation or a contract call sends along to the contract it calls or deploys: at most 16 (`MAX_CALL_FUNDS`), in strictly ascending order of asset ID, each above zero. They move to the contract before it runs, and a list that breaks these rules fails the operation. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ## B ### Base unit The smallest amount of KSA: 1 KSA is 100,000,000 base units. The RPC, `ksana-cli` and genesis configs write every amount as a whole number of base units. See [KSA and rewards](https://ksana.network/docs/ksa/). ### BIP322 Bitcoin's standard for signing a message with an address. Browser wallets such as Unisat and Xverse sign an operation as a BIP322 simple signature of your Taproot address, and the message is the operation's signature hash in hex. See [Accounts](https://ksana.network/docs/accounts/). ### BIP340 The Schnorr signature scheme of Taproot. `ksana-cli` and the TypeScript SDK sign operations with BIP340 directly, using the tweaked key of your account's Taproot address. See [Accounts](https://ksana.network/docs/accounts/). ### Block A fast-lane block: a header (version, height, parents, anchor, entries root, state root, producer, timestamp, difficulty bits and nonce) and its list of entries. A producer finds it by proof of work, and GHOSTDAG gives it its place in the order. See [How it works](https://ksana.network/docs/how-it-works/). ### Block DAG The graph that Ksana's blocks form: a block can have up to 10 parents, so blocks found at the same time are merged rather than thrown away. GHOSTDAG orders it. See [Mining](https://ksana.network/docs/mining/). ### Block share The part of a reward slot paid to the block share account that the genesis config names, before the carrier and the producer, while the protocol's rules set one. See [KSA and rewards](https://ksana.network/docs/ksa/#who-gets-each-slot). ### Blue and red blocks GHOSTDAG colors the blocks that a block merges: blue when they fit a well-connected set (a blue block has at most `GHOSTDAG_K`, 16, blue blocks in its anticone), red otherwise. The entries of both execute, but only main-chain and blue blocks earn block rewards. See [Mining](https://ksana.network/docs/mining/). ### Blue score and blue work A block's blue score counts the blue blocks in its past, and its blue work sums their proof of work. `MERGE_DEPTH` and the pruning depth are measured in blue score. See [Mining](https://ksana.network/docs/mining/). ### Borsh The binary encoding of Ksana's operations, block headers and contract calls: fields in a fixed order, integers little-endian, and a 4-byte length before each list or string. The field order is the format, so changing it is a consensus change. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### BTC-final The RPC's name (`btc_final`) for the third mark of an operation or a block. See [Final](#final). ## C ### Carrier The account credited for landing a block's data on Bitcoin: the producer of the block whose settlement first carried it, or the payee of a republish payload that landed it more than `ANCHOR_DEPTH` + 2 Bitcoin blocks above the block's anchor. The carrier receives 5% of the block's reward slots and half of its path B fees. See [KSA and rewards](https://ksana.network/docs/ksa/). ### Chain ID The number of a network: 1001 for devnet, 1002 for signet and 1000 for mainnet. Every VmOp carries it, so an operation signed for one network is invalid on another. See [Parameters](https://ksana.network/docs/parameters/). ### Chain work A block's blue work plus its own work. The fork choice and the selected parent go by it, so a heavy block counts as soon as it is published, not only once a block is built on it. See [Security](https://ksana.network/docs/security/). ### Checkpoint The file `pruning.ckpt` in a node's or indexer's data directory: what pruning keeps in memory (the block DAG, the finality state, the bodies and the Bitcoin view), so that a restart continues from it. See [Run a node](https://ksana.network/docs/run-a-node/). ### Coinbase The first transaction of every Bitcoin block, which pays its miner. A coinbase never carries a path C operation, and a contract that checks a payment asks for the coinbase's Merkle proof too, because it pins the depth of the block's transaction tree. See [Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/). ### Commit and reveal transactions The two Bitcoin transactions of a settlement. The commit transaction spends the producer's funding and creates an output that commits to a Taproot script; the reveal transaction spends that output and shows the script, the envelope holding the payload, in its witness. See [How it works](https://ksana.network/docs/how-it-works/). ### Compact encoding How payloads stay small: each header is written relative to the ones before it, and the entries of a payload share one dictionary of keys. In a run of empty blocks, each header after the first takes 14 bytes. See [How it works](https://ksana.network/docs/how-it-works/). ### Competing chain A fork that is lighter than a node's main chain but has put more chain work on Bitcoin than the node's own chain has so far. If that is still so one Bitcoin block after it appeared, the node republishes its own headers up to its tip at its highest fee rate (`--max-settlement-feerate`), so that the heavier chain lands in time to become final. See [Security](https://ksana.network/docs/security/#competing-chains). ### Contract A WebAssembly program stored on Ksana by a deploy operation and run by calls. It has a contract ID, its own storage and balances, and it can call other contracts and read Bitcoin data. See [Write a contract](https://ksana.network/docs/contracts/). ### Contract ID The 32-byte ID of a contract, written as 64 hex digits; a contract has no address. A deployed contract's ID is the SHA-256 hash of the deploying account, that operation's nonce and the code's hash; one that a contract creates with `create_contract` gets the hash of the creating contract's ID, a 32-byte salt and the code's hash. See [Accounts](https://ksana.network/docs/accounts/). ### Counted header A block header that a payload on Bitcoin has added to the header DAG. It counts at the payload's Bitcoin height once its anchor is on Bitcoin's best chain and its parents have counted; a header whose parents have not counted leaves no trace and has to be carried again. A block's body lands only with its counted header. See [How it works](https://ksana.network/docs/how-it-works/). ### CPFP bump Child pays for parent: a node raises the fee of a settlement it sent that waits in the Bitcoin mempool, by spending the reveal transaction's change output in a child transaction with a higher fee. See [Mining](https://ksana.network/docs/mining/). ## D ### DAA score A block's measure of time for difficulty, rewards and upgrades: the weights of all the blocks in its past (the genesis block aside) plus its own. A block with entries weighs 1 and an empty block 12 to 120, and the target is one unit of DAA score every 5 seconds. See [Mining](https://ksana.network/docs/mining/). ### Determinism Every node and indexer computes the same state from the same blocks: consensus code uses no floating point, no system time and no unordered iteration. A test runs the same chain in two processes, on x86_64 and on aarch64, and compares each block's state root with fixed values. See [How it works](https://ksana.network/docs/how-it-works/). ### devnet A local network on Bitcoin regtest (chain ID 1001) for development; `devnet/docker-compose.yml` starts its bitcoind, and with `--profile nodes` three nodes and an indexer. See [Parameters](https://ksana.network/docs/parameters/). ### Disqualified block A block that breaks a rule only its execution can check, such as a state root that does not match or an entry that fails in strict mode. It and every block whose selected chain passes through it are kept off the main chain, but it stays in the block DAG and other blocks can merge it. See [Security](https://ksana.network/docs/security/#invalid-blocks). ## E ### Empty block A block with no entries. It needs 12 times the work of a block with entries, and each further empty block in a row doubles that, up to 120 times, so an idle chain makes a block about every 1 to 10 minutes. See [Mining](https://ksana.network/docs/mining/). ### Empty-block streak The number of empty blocks in a row on the selected chain, up to and including a block: 0 for a block with entries. It sets an empty block's weight: 12 for the first, doubling with each one after it, at most 120. See [Mining](https://ksana.network/docs/mining/). ### Entry One item of a block's list: a forced-inclusion entry (a path C operation), an unlock entry or a path B entry, in that order. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Entry pool A node's pool of path B operations waiting for a block, its mempool. By default it holds up to 10,000 operations, 64 per account, and admits only fees at or above the node's relay floor. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Envelope The Taproot script in a reveal transaction's witness that carries a payload: ` OP_CHECKSIG OP_FALSE OP_IF KSN1 OP_ENDIF`. The commit transaction's output commits to it, so nobody can swap the payload. See [How it works](https://ksana.network/docs/how-it-works/). ### Event A record that a contract emits while it runs (`emit_event`). Events appear in the operation's receipt, not in the state root, and are dropped when the operation fails. See [Host functions](https://ksana.network/docs/host-functions/). ### Exchange contract A contract that sells KSA for BTC, such as the example `ksa-exchange`. A seller locks KSA for a buyer at a price, and the buyer's Bitcoin transaction pays the seller and claims the KSA (a top-up). See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Excluded block A block that the finality rule passes over at some Bitcoin height, because it is anchored off the Bitcoin best chain or its execution is invalid. Every block whose selected chain passes through it is excluded with it, and a Bitcoin reorg can revoke the exclusion. See [Security](https://ksana.network/docs/security/#invalid-blocks). ## F ### Failed operation An included operation that did not take effect, while its block stays valid. When its action fails (it runs out of gas, a contract reverts or a balance is short), the action's changes are rolled back but its nonce is used, and a path B operation still pays its fee. A path C operation that fails its checks (version, chain ID, length, fee mode, signature or nonce) is recorded as failed without using its nonce. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Fast lane Ksana's own proof-of-work chain, which orders and executes operations in about 5 seconds, while Bitcoin stores its data and decides its finality. See [How it works](https://ksana.network/docs/how-it-works/). ### Fast-confirmed The first mark of an operation, about 5 seconds after you submit it on path B: a main-chain block included and executed it (`fast_confirmed` in the RPC). It rests on the fast lane's hashrate alone. See [Confirmations](https://ksana.network/docs/confirmations/). ### Faucet The signet service at `https://signet.ksana.network/faucet` that sends 100 test KSA to an account once a day. See [Public signet](https://ksana.network/docs/signet/). ### Fee rate For a path B operation, its fee per KiB of cost, where cost is the larger of its encoded size and its `max_gas` converted to bytes; producers pack operations by fee rate. For a Bitcoin transaction, sats per virtual byte. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Final The third mark of an operation (BTC-final, `btc_final` in the RPC): the block that accepted it is on the finalized chain. Its data, and the data of every block in its past, had 6 Bitcoin confirmations at the Bitcoin block that decided it final, which has 6 confirmations of its own, and its execution is valid. Fast-lane hashrate alone cannot undo it: that takes a Bitcoin reorg of at least 6 blocks. See [Confirmations](https://ksana.network/docs/confirmations/). ### Finality The rule that decides, from Bitcoin data alone and one Bitcoin block at a time, which Ksana blocks are final. Every node and indexer reaches the same answer, and a heavier chain that lands on Bitcoin too late cannot replace a final block. See [How it works](https://ksana.network/docs/how-it-works/). ### Finalized tip The newest block decided final; the main chain must pass through it. The `finalized` that `ksana_getChainInfo` and `indexer_status` report is the BTC-final tip instead: the newest block reported final, once the Bitcoin block of its decision has 6 confirmations. See [Confirmations](https://ksana.network/docs/confirmations/). ### Forced inclusion The rule that every block must begin with the path C transactions that confirmed on Bitcoin within its window, in Bitcoin order; a block that leaves one out is invalid. A transaction is due once it has `NATIVE_CONFIRMATIONS` plus `ANCHOR_DEPTH` confirmations: 2 on signet, 5 on mainnet. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Fork choice The rule that picks the main chain: the eligible tip with the most chain work, the larger hash winning a tie. A block is not eligible when it, or a block it merges, is anchored off the Bitcoin best chain. See [Security](https://ksana.network/docs/security/). ### Funding key The Bitcoin key (`--btc-funding-key-file`) whose coins pay for a producer's settlements; its Taproot address must hold confirmed bitcoin. On signet and mainnet the node finds those coins through a watch-only wallet of its bitcoind (`--btc-funding-wallet`). See [Run a node](https://ksana.network/docs/run-a-node/). ## G ### Gas The unit of execution cost: 1 gas is one unit of wasmtime fuel, and host functions and built-in actions add fixed prices. Each operation sets its `max_gas`, and a block's entries may add up to 100,000,000 gas (`BLOCK_GAS_LIMIT`), which only forced-inclusion entries can exceed. See [Host functions](https://ksana.network/docs/host-functions/). ### Genesis config The JSON file that every node and indexer of a network starts from: start time, Bitcoin anchor, difficulty, allocations and block share account. The signet's is `signet/genesis.json`. See [Parameters](https://ksana.network/docs/parameters/#genesis-configurations). ### GHOSTDAG The protocol that orders the block DAG, with the definitions and algorithms Kaspa uses: it picks each block's selected parent, colors merged blocks blue or red, and puts every block in one order. Ksana uses K = 16. See [Mining](https://ksana.network/docs/mining/). ## H ### Half-aggregation How a block holds its path B signatures: the first half of each (32 bytes) in the operation's entry, and one aggregate entry of 32 bytes at the block's end that stands for all the second halves. The block is valid only when the aggregate verifies against all of them together. See [Signatures in a block](https://ksana.network/docs/submitting-ops/#signatures-in-a-block). ### Halving period A stretch of DAA score during which each reward slot pays the same; the reward halves with each new period. On mainnet the periods last about 2, 4 and then 8 years each, and on signet about 4 years each. See [KSA and rewards](https://ksana.network/docs/ksa/). ### Height A block's height is its selected parent's height plus one. An operation in a merged block takes effect at the height of the main-chain block that merges it, and the RPC reports that height. See [JSON-RPC](https://ksana.network/docs/rpc/). ### Host function A function that the virtual machine offers contracts, such as `storage_get`, `call_contract`, `asset_transfer`, `emit_event`, `btc_header` and `native_tx`. Each has a price in gas, some per byte. See [Host functions](https://ksana.network/docs/host-functions/). ## I ### Idle header interval The time between blocks while there is nothing to include: about 1 minute for the first empty block, doubling with each further one up to about 10 minutes. The first operation that arrives brings the chain back to blocks about 5 seconds apart. See [Mining](https://ksana.network/docs/mining/). ### Indexer `ksana-indexer`, which rebuilds the Ksana chain and its state from bitcoind alone, without talking to any node, and checks every block's state root. See [Run an indexer](https://ksana.network/docs/run-an-indexer/). ### Invalid block A block that breaks a consensus rule, for example with bad proof of work, a missing forced inclusion or a body too large for a payload. Nodes reject it and every block built on it, whereas a failed operation leaves its block valid. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ## K ### KS-20 The standard for fungible tokens whose balances a contract keeps: its methods, events and refusals, allowances with an expiry, and `transfer_and_call`, which pays a contract and calls it in one operation. See [KS-20](https://ksana.network/docs/ks-20/). ### KS-721 The standard for collections of unique tokens, each with a 32-byte ID and an owner the collection keeps. See [KS-721](https://ksana.network/docs/ks-721/). ### KSA Ksana's native asset, with 8 decimals and an asset ID of 32 zero bytes. Path B fees are paid in it and producers earn it as block rewards; mainnet's cap is 210,000,000 KSA. See [KSA and rewards](https://ksana.network/docs/ksa/). ### ksana-cli The command-line client: it makes keys, queries a node, and submits operations on path B or, through a bitcoind wallet, on path C. See [ksana-cli](https://ksana.network/docs/cli/). ### ksana-keytool A small tool that creates or reads a key file and prints its account and its addresses, for a producer's `--producer` account and funding key. See [Run a node](https://ksana.network/docs/run-a-node/). ### ksana-node The node: it follows the chain over P2P, checks every block against Bitcoin and serves JSON-RPC. With `--producer` it also mines blocks, and with a funding key it settles them. See [Run a node](https://ksana.network/docs/run-a-node/). ### KSN1 The marker (`MAGIC`) that starts Ksana data on Bitcoin, both in the `OP_RETURN` output of a path C transaction and in the envelope of a settlement or republish payload. See [How it works](https://ksana.network/docs/how-it-works/). ## L ### Lenient and strict execution A main-chain block first executes the other blocks of its merge set in lenient mode, where an entry that conflicts with earlier ones is skipped, then its own entries in strict mode, where such an entry disqualifies the block. See [How it works](https://ksana.network/docs/how-it-works/). ### Local fault An error of one node's own, such as a failure of its storage or of its bitcoind, as opposed to a fault in a block or an operation. A node never judges a block invalid because of a local fault. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Lock An offer in an exchange contract: KSA that a seller sets aside for one buyer, the beneficiary, at a price per sat, payable to a Bitcoin payment script the seller names, which no other lock has ever used. The buyer claims it with a top-up; from 6 Bitcoin blocks after the lock's expiry height, the seller can release whatever is left. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Locked fees What an account is owed by blocks that are not unlocked yet, listed per block as `locked_fees` by `ksana_getAccount`: a producer's block rewards and path B fees, a carrier's part, and the block share for the block share account. They move to the balance when an unlock entry pays the block out, once it is settled. See [KSA and rewards](https://ksana.network/docs/ksa/). ## M ### Main chain The chain from the best eligible tip back to the genesis block along selected parents. It fixes the order in which blocks execute, and it must pass through the finalized tip. See [How it works](https://ksana.network/docs/how-it-works/). ### mainnet The network on Bitcoin mainnet (chain ID 1000). It has not launched: its parameters are set, and its genesis config is a template. See [Parameters](https://ksana.network/docs/parameters/). ### Mark One of the three stages an operation passes: fast-confirmed, on Bitcoin and final. Each rests on something different, so an application chooses by amount which one to wait for. See [Confirmations](https://ksana.network/docs/confirmations/). ### Merge depth `MERGE_DEPTH`, 720 blue score: an hour of blocks at one every 5 seconds. A block may merge only blocks whose blue score is within that distance of its selected parent's, and whose selected chain passes through its merge-depth root. See [Mining](https://ksana.network/docs/mining/). ### Merge set The blocks a block adds to its past beyond its selected parent's past: the selected parent itself and the parallel blocks it merges, at most 128. The merged blocks execute in GHOSTDAG order before the block's own entries. See [Mining](https://ksana.network/docs/mining/). ### Merkle proof Proof that a transaction is in a Bitcoin block: the hashes on the path from its txid up to the Merkle root in the block's header, also called a Merkle branch. A contract checks one with the SDK's `btc::verify_tx_inclusion` against a header from `btc_header`, together with the proof of the same block's coinbase, which pins the depth of the tree. See [Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/). ### Mock host The in-memory stand-in for the host functions that `ksana-contract-sdk` uses when you build a contract for your own machine instead of WebAssembly, so that `cargo test` runs it without a node. See [Write a contract](https://ksana.network/docs/contracts/). ## N ### Native transaction A Bitcoin transaction whose one KSN1 `OP_RETURN` output carries a signed operation: how path C travels. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Nonce A counter per account. Each operation carries the account's next nonce, so it cannot be replayed, and a node's entry pool keeps an account's operations in nonce order. See [Accounts](https://ksana.network/docs/accounts/). ## O ### On Bitcoin The second mark of an operation: the data of its block, and of every block in that block's past, has landed in Bitcoin blocks (`settled` in `ksana_getSettlement`). Anyone can now check the operation from Bitcoin, but it is not final yet. See [Confirmations](https://ksana.network/docs/confirmations/). ### One-time key A key made for a single top-up. It signs only the claim operation, at nonce 0, so the claim uses none of your account's nonces and several top-ups can confirm in any order. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Op ID The SHA-256 hash of an operation's encoding (`op_id`): for path C the full encoding, signature included; for path B the encoding with the first half of the signature, the form a block holds, so the ID is the same before and after inclusion. You track an operation by it. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Operation A signed instruction to Ksana (an op), encoded as a VmOp: a transfer of an asset, a contract call or a contract deployment. You submit it on path B or path C. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Operation status What `ksana_getOpStatus` reports: `pending` (in the entry pool), `fast_confirmed`, `failed` (included, execution failed, fee paid), `skipped` and `btc_final`. See [Confirmations](https://ksana.network/docs/confirmations/). ### Outpoint A reference to one output of a Bitcoin transaction: the transaction's ID and the output's index. A path C signature covers the outpoint that the carrying transaction's first input spends, so a copy of the operation in any other transaction fails. See [Accounts](https://ksana.network/docs/accounts/). ### Output key The 32-byte key that a Taproot address encodes: its internal key tweaked as BIP86 describes. A Ksana account is an output key, which is why your account and your Taproot address are the same bytes. See [Accounts](https://ksana.network/docs/accounts/). ## P ### Packing floor The smallest path B fee (`--min-token-fee`, 1 base unit by default) and fee rate (`--min-fee-per-kib`, 0 by default) that a producer puts in its own blocks. A producer given a KSA price (`--ksa-price-sat`) also asks each op to pay for its bytes at the Bitcoin fee rate it pays. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Parallel block A block found at about the same time as another, so that neither is in the other's past. A later block merges it instead of discarding it, and its operations still execute unless they conflict with earlier ones. See [Mining](https://ksana.network/docs/mining/). ### Path B (sponsored) Submitting an operation to a node with a fee in KSA. You sign one message, a producer includes the operation within seconds, and producers pay the Bitcoin fees that settle it. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Path C (native) Submitting an operation in your own Bitcoin transaction, through a KSN1 `OP_RETURN` output. You pay only the Bitcoin fee, every producer must include the operation once the transaction confirms, and its signature binds the transaction's first input so that nobody can copy it. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Payload The data that a settlement or republish transaction carries in its envelope: compact block headers and the bodies of the blocks that need them, at most 81,920 bytes and 500 headers. Its headers count only where their parents have counted ([Counted header](#counted-header)). A path C transaction's payload is one operation. See [How it works](https://ksana.network/docs/how-it-works/). ### Producer A node that mines blocks: it evaluates Argon2id on block templates and is paid in KSA at the account given by `--producer`. Anyone can produce. See [Mining](https://ksana.network/docs/mining/). ### Pruning Keeping in memory only the block DAG from the pruning point on and answering older history from disk, so that memory stays bounded. The pruning point lies at least 2,209 blue score below the pruning root, the highest block decided final at least 144 Bitcoin blocks ago. See [Run a node](https://ksana.network/docs/run-a-node/). ### PSBT A partially signed Bitcoin transaction (BIP174). For path C and top-ups, the web wallet and the TypeScript SDK build one for your browser wallet to sign. See [Signet wallet](https://ksana.network/docs/wallet/). ## R ### Read-only call A contract call made with the RPC method `ksana_call` instead of an operation. It runs on the latest state as if in the next block, pays no fee, uses no nonce and changes nothing on chain. See [JSON-RPC](https://ksana.network/docs/rpc/). ### Receipt The result of executing an operation: success or failure, gas used, return value, events and the changes it made to built-in assets. A failed operation's receipt records its whole `max_gas` as used. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Relay floor The smallest path B fee that a node admits to its entry pool and forwards to its peers (`--min-relay-token-fee`, the packing floor by default; the lower of the two applies). See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Reorg A reorganization: part of a chain replaced by a heavier branch. A Bitcoin reorg of at most `ANCHOR_DEPTH` blocks leaves every Ksana block in place, and a deeper one takes the blocks anchored on the orphaned Bitcoin blocks off the main chain. Only a Bitcoin reorg of at least 6 blocks can undo a final block. See [Security](https://ksana.network/docs/security/#bitcoin-reorgs). ### Republish Writing block headers, and bodies where needed, to Bitcoin again in a new payload: to land data that no settlement carried, or to put a node's own chain ahead of a competing chain on Bitcoin. Any node can do it, and the payload names a payee who can earn the carrier reward. See [How it works](https://ksana.network/docs/how-it-works/). ### Rescue A node rebuilding a stuck settlement with its own funding: the same payload in a new commit and reveal pair. A settlement is stuck when it cannot confirm, or when it confirmed before the headers it needs from earlier blocks had counted and so landed nothing. The block's producer goes first, then the producers of the main-chain blocks after it, one Bitcoin block apart, then any other node. See [How it works](https://ksana.network/docs/how-it-works/). ### Revert and trap Two of the ways a contract call fails. A method reverts when it returns an error, whose reason the receipt's `error` shows; it traps on a WebAssembly fault such as `unreachable`, an access out of bounds or a division by zero. Either fails the whole operation, unless the call was made with `try_call_contract`, which rolls back only the callee. See [Host functions](https://ksana.network/docs/host-functions/). ### Reward slot A unit of block reward: a block of weight w takes the w slots that end at its DAA score, and each slot pays the reward of its halving period (4.2 KSA in mainnet's first period). See [KSA and rewards](https://ksana.network/docs/ksa/). ## S ### Seed node One of the two signet nodes that the project hosts, which produce and settle blocks. A new node joins the network by passing the first, `{{signet.p2p}}`, with `--peer`. See [Run a node](https://ksana.network/docs/run-a-node/). ### Selected parent The parent with the most chain work. Following selected parents from a tip gives its selected chain, and the main chain is the selected chain of the best tip. See [Mining](https://ksana.network/docs/mining/). ### Settled A block is settled once its data and the data of every block in its past have landed on Bitcoin: the [On Bitcoin](#on-bitcoin) mark. Its rewards and fees can then unlock, and the indexer can execute it. See [KSA and rewards](https://ksana.network/docs/ksa/). ### Settlement The commit and reveal transactions through which a producer writes a block's data to Bitcoin, often with the headers and bodies of earlier blocks, and pays their Bitcoin fee. A block with no body to land, an empty block or one holding only path C operations, has a settlement of its own only when it carries other blocks' bodies; otherwise a later settlement lands its header. See [How it works](https://ksana.network/docs/how-it-works/). ### Settlement backlog limit A safety rule: once a block's body has waited 6 Bitcoin blocks after its anchor (`SETTLEMENT_TIMEOUT`) without landing, new blocks may hold only forced-inclusion entries, which pauses path B until the data lands. See [Security](https://ksana.network/docs/security/#unsettled-data). ### Settlement batching While a settlement is in flight, producers keep the new blocks' bodies back and carry them all in the next settlement once it confirms. When the bodies waiting, or a new block's own, pass 10 KiB (an eighth of the payload limit), the new block carries a settlement at once. It is on by default. See [Mining](https://ksana.network/docs/mining/). ### signet Ksana's public test network (chain ID 1002) on Bitcoin's public signet, with two seed nodes, an indexer, a web wallet and a faucet hosted at `signet.ksana.network`. Its coins have no value. See [Public signet](https://ksana.network/docs/signet/). ### Signet BTC The coins of Bitcoin's public signet (sBTC), free from any signet faucet and worth nothing. You need a little for path C, top-ups and producing settlements. See [Public signet](https://ksana.network/docs/signet/). ### Skipped The status of an operation that only merged blocks included and that could not execute when they were merged, for example because it had already run elsewhere. It pays no fee and, while still valid, goes back to the entry pool. See [Confirmations](https://ksana.network/docs/confirmations/). ### Soak test A long devnet run (5 hours by default) that keeps submitting random path B and path C operations, optionally with random Bitcoin reorgs, and checks the indexer against the nodes block by block. See [Security](https://ksana.network/docs/security/#testing). ### State root The root of the Merkle tree of the whole state after a block, written in the block's header. The indexer recomputes it from Bitcoin data to check every block. See [Run an indexer](https://ksana.network/docs/run-an-indexer/). ## T ### Taproot Bitcoin's output type defined by BIP341, with addresses that start `bc1p` (`tb1p` on signet). A Ksana account is a Taproot output key, and the envelope is a Taproot script. See [Accounts](https://ksana.network/docs/accounts/). ### Tip The newest block of a chain: the main chain's tip is its highest block, and the Bitcoin tip is the newest block of the Bitcoin best chain. A block DAG can have several tips at once, and the fork choice picks one. See [How it works](https://ksana.network/docs/how-it-works/). ### Top-up Buying KSA with BTC from a seller's lock in an exchange contract: one Bitcoin transaction of yours pays the seller and carries a path C claim that credits the KSA to you. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Two-speed difficulty Empty blocks need more work than blocks with entries: 12 times at first, doubling with each further empty block up to 120 times. A busy chain makes a block about every 5 seconds and an idle one about every 1 to 10 minutes, with the same reward per unit of time. See [Mining](https://ksana.network/docs/mining/). ### Txid A Bitcoin transaction's ID: the double SHA-256 of the transaction without its witness. Ksana stores txids and Bitcoin block hashes in Bitcoin's internal byte order, the reverse of the hex that bitcoind and block explorers show, so the RPC also gives settlement txids in display order (`txid_rpc`). See [JSON-RPC](https://ksana.network/docs/rpc/). ## U ### Unlock Paying out locked rewards and path B fees once their blocks are settled. A block holds at most one unlock entry, which pays out up to 1,024 blocks (`MAX_UNLOCK_BATCH`) in the order the main chain accepted them. See [KSA and rewards](https://ksana.network/docs/ksa/). ### Upgrade A new protocol version from a set DAA score, taken from the upgrade table in `params.rs`. None is scheduled on any network, so the protocol version is 2. See [Parameters](https://ksana.network/docs/parameters/#upgrades). ### UTXO An unspent transaction output: a Bitcoin coin, named by its outpoint, that a new transaction can spend. Path C transactions, top-ups and settlements are paid from UTXOs; the TypeScript SDK takes the ones to spend as `Utxo` values and does not list them for you. See [TypeScript SDK](https://ksana.network/docs/sdk/). ## V ### Verdict The result of executing a candidate for finality as a main-chain block on the finalized tip: valid, or invalid and excluded. Every node and indexer on the same Bitcoin chain reaches the same verdict. See [Security](https://ksana.network/docs/security/#invalid-blocks). ### Virtual byte (vB) Bitcoin's measure of a transaction's size for fees: a byte outside the witness counts as one, a witness byte as a quarter. Bitcoin fee rates are given in sats (hundred-millionths of a bitcoin) per virtual byte, sat/vB. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### VmOp The encoded form of an operation: version, chain ID, account, nonce, fee (a KSA amount for path B, native for path C), `max_gas`, the action and a BIP340 or BIP322 signature, at most 65,536 bytes. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ## W ### Wallet adapter The TypeScript SDK's interface to a browser wallet, `WalletAdapter`: it reads the wallet's Taproot account, has the wallet sign PSBTs and BIP322 messages, and can ask which Bitcoin network the wallet is set to. `UnisatAdapter` and `XverseAdapter` wrap the two extensions, and you can implement it for another wallet. See [TypeScript SDK](https://ksana.network/docs/sdk/). ### Web wallet The signet wallet and explorer at `https://signet.ksana.network/`: connect Unisat or Xverse, get test KSA, send operations on path B or C, top up, and follow operations and blocks to Bitcoin. See [Signet wallet](https://ksana.network/docs/wallet/). ### WebAssembly The format of Ksana contracts: Rust compiled to `wasm32` without the standard library, run by wasmtime with exact gas metering and no floating point. See [Write a contract](https://ksana.network/docs/contracts/). ### Weight A block's weight: 1 for a block with entries, 12 to 120 for an empty block. It divides the block's proof-of-work target, adds to the DAA score and sets the number of reward slots. See [Mining](https://ksana.network/docs/mining/). ### Withholding Mining blocks in private and publishing them later (selfish mining), to turn honest blocks red and take their rewards, or to reverse a payment. Counting a block's own work in the fork choice, and `GHOSTDAG_K` 16, limit what it gains. See [Security](https://ksana.network/docs/security/#withholding). --- # Frequently asked questions URL: https://ksana.network/docs/faq/ > Short answers to the questions people ask most about Ksana, each with a link to the page that explains more. ## About Ksana ### What is Ksana? Ksana runs WebAssembly contracts on its own proof-of-work chain, the fast lane, and uses Bitcoin to store that chain's data and to decide when its blocks are final. Operations are fast-confirmed in about 5 seconds, every block's data is written to Bitcoin, and anyone can rebuild the whole state from a Bitcoin node alone. See [How it works](https://ksana.network/docs/how-it-works/). ### Is Ksana an L2? Not in the usual sense, and it is not a sidechain or a rollup either. Unlike a sidechain, it has no peg: your bitcoin never moves to Ksana, and Ksana's blocks become final only through data on Bitcoin. Unlike a rollup, no operator or sequencer orders operations: producers compete by proof of work, and Bitcoin stores and orders the data without executing it, while every Ksana node and indexer applies the rules itself. See [How it works](https://ksana.network/docs/how-it-works/). ### Is there a bridge for BTC? No. Ksana holds no one's bitcoin: BTC stays on Bitcoin, and a BTC transfer is an ordinary Bitcoin transaction. Contracts can read Bitcoin headers and transactions instead, so a contract can act on a payment made on Bitcoin, as the exchange contract does for top-ups. See [Bitcoin in contracts](https://ksana.network/docs/bitcoin-in-contracts/). ### Is mainnet live? No. Mainnet has not launched, and the public signet is the network to use. Most mainnet parameters are fixed and a few wait on measurements, and before a launch the signet runs for at least four weeks without a consensus change. The work that remains includes the mainnet genesis config, runs of paths B and C with real wallets on the signet, those measurements, and an independent security audit. See [Public signet](https://ksana.network/docs/signet/). ### Will the signet be reset? It can be. A consensus change before mainnet restarts the signet from a new genesis config, and every balance starts over; its coins have no value in any case. See [Public signet](https://ksana.network/docs/signet/). ## Using Ksana ### Which wallets work? Unisat and Xverse, switched to Bitcoin Signet, with a Taproot address (in Xverse, the Ordinals address). Your account is that address, so other address types cannot hold KSA. On the command line, `ksana-cli` keeps its own key files, and the TypeScript SDK signs with a key or through a wallet. See [Signet wallet](https://ksana.network/docs/wallet/). ### Do I need KSA? No. On path C you submit an operation in your own Bitcoin transaction and pay only its Bitcoin fee, and every producer must include it once your transaction has its confirmations (2 on the signet). KSA lets you use path B, which confirms in seconds; you can buy KSA with BTC in a top-up, and on the signet the faucet gives you some for free. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### How do I get test coins? Test KSA comes from the faucet, in the web wallet or at `https://signet.ksana.network/faucet`: 100 KSA per account once a day. Signet BTC comes free from any Bitcoin signet faucet, and you need a little of it for path C, top-ups and settling blocks you produce. See [Public signet](https://ksana.network/docs/signet/). ### What does an operation cost? On path B you set a fee in KSA: a producer includes the operation when the fee reaches its packing floor (1 base unit by default), producers fill blocks by fee rate, and `ksana-cli estimate-fee` (`ksana_estimateFee`) suggests an amount. On path C you pay your transaction's Bitcoin fee: a plain transfer is about 330 virtual bytes, about 660 sats at 2 sat/vB, and a top-up about 381 virtual bytes. See [Operations and fees](https://ksana.network/docs/submitting-ops/). ### Who pays the Bitcoin fees? For path B, producers do. A settlement is a commit and reveal pair of about 300 to 360 virtual bytes, about 700 sats at 2 sat/vB, and producers are paid in KSA: path B fees and block rewards, which unlock once the data is on Bitcoin, with a share for the block's carrier, usually the producer whose settlement lands the data. For path C and top-ups, you pay the fee of your own transaction. See [KSA and rewards](https://ksana.network/docs/ksa/). ### When is my operation final? On path B it is fast-confirmed in about 5 seconds, and on Bitcoin once the Bitcoin block that confirms its settlement is mined. Once that data has 6 Bitcoin confirmations, about an hour after you send, every node decides the block final, and reports it final five Bitcoin blocks later, once the Bitcoin block of that decision has 6 confirmations of its own: about 110 minutes in all on signet and mainnet, whose Bitcoin blocks come about every 10 minutes. A path C operation first waits for its own transaction's confirmations (2 on signet, 5 on mainnet) before a block includes it. See [Confirmations](https://ksana.network/docs/confirmations/). ### Do BTC and KSA share addresses? Yes. Your Ksana account is your Taproot address, so the same key holds your bitcoin on Bitcoin and your KSA on Ksana, each on its own chain. KSA sent to your address arrives in your Ksana account, and BTC sent to it arrives on Bitcoin. See [Accounts](https://ksana.network/docs/accounts/). ## Blocks and mining ### Why are idle blocks minutes apart? Because of two-speed difficulty: a block with no entries needs 12 times the usual work, and each further empty block in a row doubles that, up to 120 times. While nothing happens, blocks come about 1, 2, 4, 8 and then 10 minutes apart, which keeps the number of headers written to Bitcoin low, and the reward per unit of time stays the same. The first operation that arrives brings blocks back to about 5 seconds apart. See [Mining](https://ksana.network/docs/mining/). ### Why Argon2id and not SHA-256? Merged mining with Bitcoin was ruled out, because its proof of work would have to land on Bitcoin with every header. On a chain of its own, SHA-256 would let rented Bitcoin mining hardware overwhelm the fast lane and would shut ordinary computers out. Argon2id with 2 MiB of memory lets CPUs mine and browsers verify; GPUs keep an advantage, estimated at 10 to 30 times but not yet measured, far smaller than that of SHA-256 ASICs. See [Mining](https://ksana.network/docs/mining/). ### Can I mine on my computer? Yes. A node mines on one CPU thread when you give it `--producer` and your account, and the blocks it finds pay their rewards to that account once their data is on Bitcoin. To settle your own blocks you also need a funding key holding a little signet BTC; without one, other producers carry your blocks' data and take the carrier's share. See [Mining](https://ksana.network/docs/mining/). ### Can I run a node myself? Yes. A node needs its own bitcoind on the same Bitcoin network, with `-txindex`; on signet its first sync takes a few hours and about 30 GB of disk. The project develops on Ubuntu 22.04, and in its latest 10-hour devnet soak tests each node ended at about 130 to 150 MiB of memory. Open TCP port 9000 if you want other nodes to connect to yours. See [Run a node](https://ksana.network/docs/run-a-node/). ## Safety ### Can producers censor me? A producer can leave your path B operation out of its blocks, but any other producer can include it. Path C cannot be left out: once your Bitcoin transaction has its confirmations, every block must include it, and a block that does not is invalid. Bitcoin miners still decide when your transaction confirms, as for any Bitcoin transaction. See [Security](https://ksana.network/docs/security/#censorship). ### Can a payment be reversed? Before it is final, yes: an attacker with a share of the fast lane's hashrate can reverse a fast-confirmed payment, with a chance that falls with every minute you wait and is higher while the chain is idle. Rely on a fast confirmation only for small amounts, wait about 5 minutes on a busy chain for moderate ones, and wait until final for large amounts or on an idle chain. Undoing a final payment takes a reorganization of at least 6 Bitcoin blocks, which grows harder with every Bitcoin block after it. See [Security](https://ksana.network/docs/security/#payment-reversal). ### What if Bitcoin reorganizes? A Bitcoin reorg of at most `ANCHOR_DEPTH` blocks (1 on signet, 2 on mainnet) leaves every Ksana block in place. A deeper one takes the Ksana blocks anchored on the orphaned Bitcoin blocks off the main chain, and their operations are included again on the new branch. A final block can be undone only by a Bitcoin reorg of at least 6 blocks, and each Bitcoin block mined after it became final makes that harder. See [Security](https://ksana.network/docs/security/#bitcoin-reorgs). ### What if a block never settles? Other nodes land it for the producer: any node can broadcast the settlement the block carries, rebuild it with its own funding if it is stuck, or republish the block's data, and later producers carry the data of blocks without a settlement. Until it lands, the rewards and fees of that block and of every block after it stay locked, and after 6 Bitcoin blocks new blocks may hold only path C operations. A block whose data could not fit in a payload is invalid in the first place. See [Security](https://ksana.network/docs/security/#unsettled-data). ### What if every node vanished? The chain's data stays on Bitcoin. An indexer rebuilds the whole state from a Bitcoin node alone, a new node with no peers follows the finalized chain by rebuilding its blocks from Bitcoin data, and producers can mine on from there. Only blocks whose data never reached Bitcoin would be lost, and none of them was final. See [Run an indexer](https://ksana.network/docs/run-an-indexer/). ### Has Ksana been audited? Two internal security audits reviewed the code in October 2026, and their consensus fixes are now rules; the second report is in the repository. They do not replace the independent audit that is listed before mainnet. Simulations, fuzzing and long soak tests run alongside them. See [Security](https://ksana.network/docs/security/#testing). ## KSA ### Is there a premine or sale? Not in the protocol. Mainnet has no genesis allocation (a mainnet genesis config with one cannot start), and KSA comes into existence only as block rewards. The signet's genesis allocation of 110,000,000 test KSA funds its faucet and its operator, and is worth nothing. See [KSA and rewards](https://ksana.network/docs/ksa/). --- # Security model URL: https://ksana.network/docs/security/ > What each mark of an operation relies on, the attacks Ksana is built to resist and how, what has been tested, and what is still open. Ksana has not launched on mainnet. The public signet and devnet restart from genesis whenever a consensus change needs it, and nothing on them holds value. This page describes what the code does today; the full threat table is §16 of the [specification](https://github.com/ksana-in-bitcoin/ksana/blob/main/docs/SPEC.md). ## What each mark relies on An operation passes three marks, and each one rests on something different. Choose by amount which mark to wait for. *Figure: An operation is fast-confirmed after about 5 seconds, on Bitcoin once the Bitcoin block that confirms its settlement is mined, and final after six Bitcoin confirmations and five more blocks that secure the decision.* | Mark | What it rests on | What can still undo it | | --- | --- | --- | | Fast-confirmed (`fast_confirmed`) | The fast lane's proof of work: a main-chain block included and executed the operation | A heavier fast-lane branch, from an attacker with a share of the hashrate or after a Bitcoin reorg deeper than `ANCHOR_DEPTH` | | On Bitcoin (`settled` for its block) | The data of the block, and of every block in its past, is in Bitcoin blocks, where anyone can read it and an indexer can execute it | The same as fast-confirmed, since the block is not final yet; a Bitcoin reorg can also take the data out of Bitcoin again | | Final (`btc_final`) | Bitcoin's proof of work: that data had 6 confirmations (`BTC_FINALITY_CONFS`) at the Bitcoin block that decided it, which has 6 confirmations of its own, and the block's execution is valid | Only a Bitcoin reorg of at least 6 blocks, reaching the Bitcoin block that decided it; each Bitcoin block mined after that makes it harder | Bitcoin stores Ksana's data and orders it, but it does not execute Ksana's rules. Every node and every indexer checks every block itself, and the indexer recomputes the whole state from Bitcoin data alone, so a block that breaks a rule cannot become final by landing on Bitcoin. Finality is decided one Bitcoin block at a time, by the same function in every node and indexer. At each Bitcoin height it walks the heaviest chain whose headers are on Bitcoin, starting from the last block decided final: each block whose data has 6 confirmations, whose anchors are on the Bitcoin best chain and whose execution is valid is decided final, and the main chain must pass through it. Nodes and indexers report such a block final (`btc_final`, `finalized`) once the Bitcoin block of that decision has 6 confirmations too. A heavier chain that reaches Bitcoin later cannot replace a final block, so fast-lane hashrate alone cannot undo one. Decisions follow Bitcoin's best chain: after a Bitcoin reorg, every node and indexer decides again on the new branch, from the data that branch holds. Only a Bitcoin reorganization can undo a final block, and it has to reach the Bitcoin block that decided it, which had 6 confirmations when the block was reported final: a reorganization of fewer than 6 blocks never undoes one. With a heavier fast-lane chain on the new Bitcoin branch, a reorganization that deep takes the block off the final chain; without one, the block is decided again on the new branch, and it leaves the final chain only if the reorganization also removes its data, 5 blocks deeper still. Every later Bitcoin block makes that harder, as it does for a Bitcoin transaction, and nodes and indexers raise their highest-level alarm when a block they reported final is taken back. ## Threats and defences ### Reversing a payment An attacker with a share of the fast lane's hashrate can mine a private branch from the parent of the block that holds your payment, with a conflicting operation in it, and publish the branch if it becomes heavier. The chance falls the longer you wait, and it is much higher while the chain is idle. Simulated with the real fork choice (`reorg_race.rs`, below), an attacker with 10% of the hashrate reverses 6.5% of the payments accepted after one minute on a busy chain and 0.91% after five, but 33% and 13% on an idle chain; [Confirmations](https://ksana.network/docs/confirmations/) has the full tables. On an idle chain the honest work arrives in empty blocks that take minutes each, so a payment is protected by little more than its own block for minutes. On a busy chain an attacker's lucky empty block is worth 12 honest blocks and counts as soon as it is found. So treat a fast confirmation as final only for small amounts; on a busy chain, wait about 5 minutes for moderate amounts; on an idle chain, or for large amounts, wait until the operation is final. With most of the hashrate, an attacker can roll back any block that is not final yet, and renting CPU or GPU hashrate against Argon2id costs far less than attacking Bitcoin. Final blocks stay out of its reach unless it can also reorganize Bitcoin, as [What each mark relies on](#model) describes. ### Withholding blocks Withholding, or selfish mining, means mining blocks in private and publishing them later, so that honest blocks turn red and lose their rewards. Two forms matter on Ksana. - **Cheap blocks against a heavy one.** On an idle chain a miner hides more than `GHOSTDAG_K` weight-1 blocks while the honest network finds one heavy empty block. When the fork choice counted only blue work, a 5%, 10% or 20% miner took 30%, 45% or 56% of the honest reward slots this way at no cost. The fork choice now counts a tip's own work, so the heavy block wins as soon as it is published and the withheld blocks turn red: in simulation the honest loss is at most 1.2% (for a 30% miner), and the attacker loses a tenth to almost half of its own income. - **A heavy block against cheap ones.** A miner keeps an empty block private, extends it with weight-1 blocks, and publishes it before the honest blocks found meanwhile outweigh it; honest blocks beyond the first `GHOSTDAG_K` turn red. `GHOSTDAG_K` 16 leaves room for the honest blocks a weight-12 empty block can overtake. Simulated over 2,400 hours per cell, the attacker takes this share of the honest reward slots and loses none of its own: | Attacker's hashrate | Busy chain | Idle chain | | --- | --- | --- | | 5% | 0 | 0.50% | | 10% | 0.02% | 2.9% | | 20% | 1.1% | 9.6% | | 30% | 10% | 16% | The idle-chain figures remain open: there the honest blocks are empty blocks found minutes apart, and a private chain can still put more than `GHOSTDAG_K` blocks in the anticone of one of them. ### Racing a chain onto Bitcoin Finality counts only data that lands on Bitcoin in time. A heavier chain that was withheld and published later cannot replace final blocks, because the main chain must pass through them. The opposite attack lands a lighter chain's headers on Bitcoin first, while the network is idle or while honest settlements wait behind a fee spike, so that the lighter chain's blocks reach 6 confirmations first. When such a chain has been on Bitcoin for one Bitcoin block and a node's own chain there is still lighter, the node republishes its headers up to its tip at its highest fee rate (`--max-settlement-feerate`, 1,000 sat/vB by default) and bumps its own waiting settlements towards that rate with a child transaction spending their reveal’s change; a wallet that cannot pay that much pays what it can. Once the honest chain is connected on Bitcoin, the candidate with more chain work is decided final. What remains is the case where no operator pays to land the honest chain's data for 6 Bitcoin blocks. ### Censorship and path C Producers choose path B operations freely, so one producer can leave yours out, but any other producer can include it, and who produces the next block changes with the hashrate. Path C is the guarantee: once your Bitcoin transaction has `NATIVE_CONFIRMATIONS` plus `ANCHOR_DEPTH` confirmations (2 on signet, 5 on mainnet), every block must include it, in Bitcoin order, and a block that leaves it out is invalid. Forced-inclusion entries are not bound by the block gas limit. Nobody can copy your path C operation into another transaction: its signature commits to the first input of the transaction that carries it, so a copy fails authentication and does not use your nonce. Bitcoin miners still decide when your transaction confirms, as for any Bitcoin transaction, and Bitcoin Core relays its large `OP_RETURN` output by default from version 30. If producers ever became concentrated and censored, the specification names inclusion lists, added through a protocol upgrade, as the answer. ### Data that never lands A producer can mine a block and never put its data on Bitcoin. Ksana answers in four ways: - **Anyone can land it.** Any node can rebuild the settlement with its own funding (a rescue) or republish the data: the block's producer goes first, then the producers of the main-chain blocks after it, then every other node. A settlement claim in the Bitcoin mempool holds a rescue back for at most 8 Bitcoin blocks (`CLAIM_PATIENCE`), and a node bumps a settlement of its own that waits 2 Bitcoin blocks, to bitcoind's fee estimate or to twice its own rate, whichever is higher, and twice as much again for every further block (`BUMP_AFTER`). - **Nobody is paid until it lands.** Rewards and path B fees unlock only once a block and its whole past are settled, so every later producer has a reason to land the missing data. The carrier's share goes to the producer whose settlement first carries the data, or to the payee of a republish that lands it more than `ANCHOR_DEPTH` + 2 Bitcoin blocks above the block's anchor. - **The backlog limit.** When a body has waited 6 Bitcoin blocks after its anchor (`SETTLEMENT_TIMEOUT`), new blocks may hold only forced-inclusion entries until it lands. Path B pauses rather than build on data nobody can check, path C goes on, and the fast lane does not roll back. - **No block that cannot land.** A block whose body would not fit in a payload is invalid, and a settlement transaction must have `nLockTime` 0 and `nSequence` `0xFFFFFFFD` on every input, so it cannot carry a time lock. ### Bitcoin reorgs Producers anchor `ANCHOR_DEPTH` blocks below their Bitcoin tip, so a Bitcoin reorg of at most that depth (1 on signet, 2 on mainnet) moves no Ksana block. A deeper reorg takes the Ksana blocks anchored on the orphaned Bitcoin blocks off the main chain. Their path B operations return to the entry pool, on the nodes that hold [the second halves of their signatures](https://ksana.network/docs/submitting-ops/#signatures-in-a-block), and are included again on the new branch with the same op ID; their path C operations are included again once their transactions confirm on the new chain, or are gone if the reorg double-spent them. A Bitcoin miner able to make reorgs deeper than `ANCHOR_DEPTH` can prepare a double spend in a fast-lane branch anchored on its withheld Bitcoin blocks: against it, a fast confirmation is worth its anchor's Bitcoin confirmations, and reversing a block produced m Bitcoin blocks ago takes a reorg of at least `ANCHOR_DEPTH` + 1 + m blocks. With pruning on, a reorg that reaches below what a node keeps, at least 144 blocks deep, stops the node for a resync and makes an indexer start again from the genesis anchor. Final blocks follow Bitcoin's best chain too (see [What each mark relies on](#model)): only a Bitcoin reorg of at least 6 blocks can undo one, each Bitcoin block mined after it became final makes that harder, and a reorg deep enough to orphan the block's anchor, which lies below its data, takes the block off the main chain like any block anchored there. ### Blocks anchored off Bitcoin A block can name a Bitcoin block that is not on the Bitcoin best chain, because its anchor was forged or because a reorg orphaned it. Such a block, and any block that merges it, is excluded from finality before anything else is asked about it. Producers never merge it, the main chain never takes it, and a node holds back a block from a peer that anchors above the node's own Bitcoin tip less `ANCHOR_DEPTH` (unless its parents already anchor that high) until its Bitcoin view catches up. Its forced-inclusion entries must also be checkable against the current Bitcoin chain, so it cannot carry a body that the indexer could never determine. ### Invalid blocks Every node checks every block: proof of work, anchor, timestamps, forced inclusion, body size, gas and, after executing it, the state root. A block that breaks a rule is rejected together with every block built on it. A block that fails only in execution is disqualified: it stays in the block DAG, other blocks can merge it, but neither it nor any block whose selected chain passes through it can be on the main chain. Bitcoin cannot tell an invalid block from a valid one, so an attacker could land one on Bitcoin first. Before a block is decided final, finality asks for its verdict: the result of executing it on the finalized tip, the same execution the indexer runs. An invalid candidate is excluded, with every block whose selected chain passes through it, and the next best candidate is judged instead. Every node and indexer on the same Bitcoin chain reaches the same verdict, so a final block could be invalid only through a non-determinism bug; the indexer would then stop and every node raise an alert. Determinism has its own guards: consensus code uses no floating point, no system time and no unordered iteration, returns errors instead of panicking, and a two-process test compares every block's state root with fixed values on x86_64 and aarch64. ### Other defences | Threat | Defence | | --- | --- | | Timestamps pushed ahead to lower the difficulty | A timestamp may be at most 4 hours past the anchor's Bitcoin block time (`MAX_TIMESTAMP_AHEAD_OF_ANCHOR`), so one block can raise the next block's target at most 4 times | | Empty blocks spammed onto Bitcoin | An empty block needs 12 to 120 times the work for the same reward per unit of time, and in a run each header takes 14 bytes | | A signature replayed elsewhere | Tagged hashes, the chain ID and the nonce in every VmOp; a path C signature commits to its transaction's first input | | KSA sent to a Bitcoin address, or BTC to a Ksana account | An account is a Taproot address, so both land on the same key, and clients refuse other address types as accounts. A contract ID is not a key: never send bitcoin to one ([Accounts](https://ksana.network/docs/accounts/#contracts-have-ids-not-addresses)) | | Contracts that exhaust a node | Exact gas metering, memory, instance, call depth and stack limits, and the block gas limit; a read-only `ksana_call` gets at most `BLOCK_GAS_LIMIT` gas, 4 at a time per node | | Spam through the entry pool or P2P | Signature, nonce and balance checks on admission, per-account limits, a byte cap with eviction, a capped orphan pool, peer scoring and bans | | A client signing for the wrong network | `ksana-cli` and the web wallet take the network from the node's chain ID before anything is signed, and the TypeScript SDK has no default network | | A producer's hot wallet stolen | The funding key is separate from the `--producer` account, and `--revenue-address` with `--hot-wallet-cap-sat` sweep what exceeds a cap elsewhere | **Signing a hex message.** A browser wallet signs a Ksana operation as a BIP322 message of 64 hex digits, the operation's signature hash. A site that asks you to sign a "random" 64-hex-digit string may be presenting one of your operations, so sign such messages only on pages you trust. ## What has been tested Two internal security audits reviewed the code on 2026-10-06. They do not replace an independent audit, which the specification lists as work to do before mainnet. | Audit | Findings | Outcome | | --- | --- | --- | | First internal audit (`ef07411`) | 42 | Fixed through local hardening (D-098) and new consensus rules (D-100, with devnet and signet restarted from genesis); all three critical findings and four of the five high ones are fixed, and the fifth waits for the gas calibration | | Second internal audit (`11f0576`, re-checked at `5819b26`) | 22 (2 critical, 1 high, 9 medium, 10 low) and 8 notes | The critical and high findings and three medium ones were fixed before the code merged, the four other medium ones later (D-102, D-106, D-130, D-135) and two low ones with them (D-135); 8 are open (all low) and 2 partly fixed | The second report, with the status of every finding of both audits, is [audits/2026-10-06-second-internal-audit.md](https://github.com/ksana-in-bitcoin/ksana/blob/main/audits/2026-10-06-second-internal-audit.md); the first report is not in the repository. Beyond the audits, these checks run: | Check | What it shows | When | | --- | --- | --- | | Unit, property and vector tests | Each rule; the encodings against test vectors shared by Rust and TypeScript | CI | | Determinism test | Two processes reach the same state root for every block of a fixed scenario, against golden values | CI, on x86_64 and aarch64 | | Fuzzing (cargo-fuzz) | Five targets (VmOp decoding, payload decoding, settlement transactions, host function parameters, BIP322 witnesses) never crash, and decoding stays canonical | CI, 60 seconds per target | | Differential fuzzing | The TypeScript SDK and the contract playground's codec read every input as the Rust code does: operations, payloads, Bitcoin transactions and their data carriers, addresses, signatures, PoW, rewards, token events and contract values | CI: 60 seconds of fuzzing, and a sweep of the shared vectors and generated inputs | | Regtest end-to-end tests | Paths B and C, top-ups, settlement and the indexer against a real bitcoind | CI | | Devnet smoke test | Three nodes converge, a transfer goes through, and the indexer's state root matches the node's at every height; then 3 minutes of random operations | CI | | Soak test | Random path B and path C operations for hours, optionally with random Bitcoin reorgs of 1 to 3 blocks, checking the indexer against the nodes throughout | On demand: 5 hours on a GitHub runner, 10 hours on the project owner's Mac | | Adversarial simulations | Payment reversal, withholding, and Bitcoin reorgs of 1 to `ANCHOR_DEPTH` + 2, 6 and 7 blocks against anchor depths 0 to 3 | On demand | Recent 10-hour soak tests on the project owner's Mac ran 4,007 path B and 2,010 path C operations without a failure, ending with the three nodes and the indexer at the same height (7,231); and, with 39 random Bitcoin reorgs, 3,675 path B and 1,863 path C operations, after each of which finality passed the fast-lane tip again. In that run 9 path C operations failed after a reorg, the limitation described below. You can run the simulations yourself from the repository: ```sh title="Adversarial simulations" cargo test -p ksana-consensus --release --test reorg_race -- --ignored --nocapture cargo test -p ksana-consensus --release --test selfish_mining -- --ignored --nocapture cargo test -p ksana-indexer --release --test deep_reorg -- --ignored --nocapture ``` `KSANA_RACE_TRIALS` sets the number of races and `KSANA_SM_HOURS` the simulated hours; `KSANA_SM_K` and `KSANA_SM_N` replay the withholding table with other values of `GHOSTDAG_K` and `EMPTY_BLOCK_DIFFICULTY`. ## Known limitations - **Idle-chain confirmations.** A payment made while the chain is idle is weakly protected for minutes (see [Reversing a payment](#payment-reversal)); wait until it is final. - **Withholding a heavy block on an idle chain.** A 5% to 30% miner can still take 0.50% to 16% of the honest reward slots (see [Withholding blocks](#withholding)). - **Values still to measure.** The GPU advantage on Argon2id (estimated at 10 to 30 times), the propagation delay of a real network (`GHOSTDAG_K` 16 tolerates about 17.6 seconds), the gas table behind `BLOCK_GAS_LIMIT`, and `SETTLEMENT_TIMEOUT` and the carrier reward on a real fee market are to be measured before mainnet. - **Landing races.** A lighter chain can become final if nobody pays to land the honest chain's data for 6 Bitcoin blocks. - **Path C after a deep Bitcoin reorg.** An operation that is included again runs in the new Bitcoin order and fails if its nonce is then out of turn. The account's later operations wait until the gap is filled, a node's entry pool keeps at most 8 of them, and you resubmit the failed one. - **Rescue costs.** A rescue copies the payload, so the carrier reward stays with the block's original producer while the rescuer pays the Bitcoin fee. - **Open audit findings.** Mostly local denial-of-service hardening: valid side-branch headers on Bitcoin, which every node keeps until pruning at the price of their proof of work, the gas price of compiling contract code, and client-side items in `ksana-cli`, the SDK and the web wallet. - **Outside the audits.** wasmtime's own correctness, Bitcoin Core, the browser wallets, performance under real network load, and reward economics beyond the simulations. ## Report a vulnerability Do not describe a vulnerability in an issue, a discussion or a pull request. Report it privately through GitHub's private vulnerability reporting, with [Report a vulnerability](https://github.com/ksana-in-bitcoin/ksana/security/advisories/new) in the repository's Security tab, or send it to a maintainer of the `ksana-in-bitcoin` organization through a private channel you already share with them. Include: - the affected component (crate, SDK, contract or web app) and the commit you looked at; - what an attacker can do, what it costs them, and who is affected (one node, every node, the indexer, users' funds); - the steps or a test that reproduces it. The report and its follow-up stay private until the fix is merged. What counts as a vulnerability (consensus divergence, stopping production, settlement, finality or the indexer, denial of service, funds taken, locked or created outside the rules, crashes from external input) is listed in [SECURITY.md](https://github.com/ksana-in-bitcoin/ksana/blob/main/SECURITY.md).