### Mainnet prerequisites: setup directories, install packages, generate keychain Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Commands for a fresh Ubuntu machine to prepare directories, install required packages (npm, wget, unzip, jq, tar), install the Stacks CLI globally, and generate a new mainnet account keychain saved to ~/stacks-signer/keychain.json. ```bash # Create the required directories mkdir -p ~/stacks-signer/data mkdir -p ~/stacks-node/data # Install needed packages sudo apt install -y npm wget unzip jq tar # Install Stacks CLI globally npm install --global @stacks/cli # Generate a new account and store details in a file stx make_keychain | jq > ~/stacks-signer/keychain.json ``` -------------------------------- ### Return final response Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Returns the message ID wrapped in an ok response, indicating successful execution. ```clarity ;; Return the message ID (ok id) ``` -------------------------------- ### Testnet prerequisites: setup directories, install packages, generate keychain Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Commands for a fresh Ubuntu machine to prepare directories, install required packages (npm, wget, unzip, jq, tar), install the Stacks CLI globally, and generate a new testnet account keychain saved to ~/stacks-signer/keychain.json. Uses the '-t' option to create a testnet account. ```bash # Create the required directories mkdir -p ~/stacks-signer/data mkdir -p ~/stacks-node/data # Install needed packages sudo apt install -y npm wget unzip jq tar # Install Stacks CLI globally npm install --global @stacks/cli # Generate a new account and store details in a file # '-t' option makes this a testnet account stx make_keychain -t | jq > ~/stacks-signer/keychain.json ``` -------------------------------- ### Start the signer (binary) Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Starts the signer using the binary after configuration verification succeeds. ```bash ~/stacks-signer/stacks-signer run -c ~/stacks-signer/signer-config.toml ``` -------------------------------- ### Create a new Clarinet project with clarinet new Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Run this command in your terminal to scaffold a new Clarinet project named 'my-stacks-contracts'. It sets up the project structure, including contracts, settings, tests, and configuration files. ```bash clarinet new my-stacks-contracts ``` -------------------------------- ### Start the node (Binary) Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Start the Stacks node using the binary. The node will not run unless it can reach the endpoint it is configured to send events to, so start the signer first. ```bash ~/stacks-node/stacks-node start --config ~/stacks-node/node-config.toml ``` -------------------------------- ### Deploy contract to testnet with clarinet deployments apply Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Applies the generated deployment plan to deploy the contract to testnet. On success, it broadcasts transactions to https://api.testnet.hiro.so and confirms the transaction. ```bash clarinet deployments apply --testnet ``` ```text Broadcasting transactions to https://api.testnet.hiro.so Publish ST11V9ZN6E6VG72SHMAVM9GDE30VD3VGW5Q1W9WX3.message-board Transaction confirmed ``` -------------------------------- ### Run unit tests with npm run test (terminal output) Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Command to run the unit tests and the expected output showing both tests passing. The output confirms the two scenarios: adding a message and withdrawing funds. ```bash $ npm run test ✓ tests/message-board.test.ts (2 tests) 46ms ✓ message board tests (2) ✓ allows user to add a new message 26ms ✓ allows contract owner to withdraw funds 19ms Test Files 1 passed (1) Tests 2 passed (2) Start at 14:05:07 Duration 886ms (transform 40ms, setup 42ms, collect 8ms, tests 46ms, environment 699ms, prepare 4ms) ``` -------------------------------- ### Example /etc/fstab entries for mounted disks Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-miner/miner-prerequisites.md Example entries to automount dedicated disks for Bitcoin and Stacks chainstate at boot. Edit /etc/fstab accordingly. ```plaintext /dev/xvdb1 /bitcoin xfs rw,relatime,attr2,inode64,noquota /dev/xvdc1 /stacks-blockchain xfs rw,relatime,attr2,inode64,noquota ``` -------------------------------- ### Clarinet project scaffold output Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Expected output after running 'clarinet new my-stacks-contracts'. It lists the created directories and files, and provides hints for next steps, including switching to the project directory and creating new contracts. ```bash Created directory my-stacks-contracts Created directory contracts Created directory settings Created directory tests Created file Clarinet.toml Created file settings/Mainnet.toml Created file settings/Testnet.toml Created file settings/Devnet.toml Created directory .vscode Created file .vscode/settings.json Created file .vscode/tasks.json Created file .gitignore Created file .gitattributes Created file package.json Created file tsconfig.json Created file vitest.config.ts ---------------------------- Hint: what's next? Switch to the newly created directory with: $ cd my-stacks-contracts Once you are ready to write your contracts, run the following commands: $ clarinet contract new Create new contract scaffolding, including test files. $ clarinet check Check contract syntax for all files in ./contracts. ``` -------------------------------- ### Install dependencies and run tests Source: https://github.com/stacks-network/docs/blob/master/docs/build/rendezvous/quickstart.md Run npm install and npm test to install dependencies and execute the unit tests. ```bash npm install npm test ``` -------------------------------- ### Example keychain JSON output Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Example structure of the keychain file generated by the Stacks CLI. Contains mnemonic, keyInfo with privateKey, publicKey, address, btcAddress, wif, and index. The privateKey value is needed for signer configuration. ```json { "mnemonic": "aaa bbb ccc ddd ...", "keyInfo": { "privateKey": "65f3...", "publicKey": "03a3...", "address": "SP1G...", "btcAddress": "19tg...", "wif": "Kzdt...", "index": 0 } } ``` -------------------------------- ### Configure testnet deployment account in settings/Testnet.toml Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Specify the mnemonic seed phrase and account derivation path for the deployer account used to deploy the contract to testnet. The account must be the same one used to request testnet STX. ```TOML [network] name = "testnet" stacks_node_rpc_address = "https://api.testnet.hiro.so" deployment_fee_rate = 10 [accounts.deployer] mnemonic = "<YOUR TESTNET MNEMONIC>" derivation = "m/44'/5757'/0'/0/0" ``` -------------------------------- ### Usage example for fetchEligibleSetupBond Source: https://github.com/stacks-network/docs/blob/master/docs/reference/stacks.js/stacks-bitcoin-staking/eligibility/fetcheligiblesetupbond.md Dry-runs pox-5 setup-bond checks against current chain state. Returns an EligibilityResult with reasons for each failing gate. The caller must be the current bond-admin; the setup window opens two reward cycles before the bond's start height and closes at the start height. Only allowlist[].staker is inspected, not maxSats. Throws on non-2xx read responses or if poxInfo.contractVersions has no pox-5 entry. ```TypeScript import { fetchEligibleSetupBond } from '@stacks/bitcoin-staking'; const result = await fetchEligibleSetupBond({ bondIndex: 0, allowlist: [{ staker: 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE', maxSats: 100_000_000n }], caller: 'SP72DMR3MJKS7RVBY33JVV7EEJSQ1PYDVKDP10FX', // initial mainnet bond-admin in the pox-5 source network: 'mainnet', }); if (!result.ok) console.log(result.reasons); // Pox5ErrorCode values ``` -------------------------------- ### Generate a new contract with clarinet contract new Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Navigate into the project directory and use Clarinet's contract generator to create a new contract named 'message-board'. This command also creates a corresponding test file and updates Clarinet.toml. ```bash $ cd my-stacks-contracts $ clarinet contract new message-board Created file contracts/message-board.clar Created file tests/message-board.test.ts Updated Clarinet.toml with contract message-board ``` -------------------------------- ### Emit an event to the network Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Uses the print function to emit a custom event to the Stacks network. Emitting events provides transparency, notification, state tracking, and efficient data handling for external applications like Chainhooks. ```clarity (print { event: "[Stacks Dev Quickstart] New Message", message: content, id: id, author: contract-caller, time: burn-block-height, }) ``` -------------------------------- ### Verify Rendezvous installation with npx rv --help Source: https://github.com/stacks-network/docs/blob/master/docs/build/rendezvous/quickstart.md Checks that the Rendezvous CLI is installed and displays its help information. Run after installing the package. ```bash npx rv --help ``` -------------------------------- ### Create a new Clarinet project Source: https://github.com/stacks-network/docs/blob/master/docs/build/more-guides/sbtc/sbtc-builder-quickstart.md Creates a new Clarinet project named 'my-sbtc-project' and changes into its directory. Run after installing Clarinet. ```bash clarinet new my-sbtc-project cd my-sbtc-project ``` -------------------------------- ### Enable and start HAProxy Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-node/run-a-node-behind-a-proxy.md Enable HAProxy to start on boot and start the service immediately. ```bash sudo systemctl enable haproxy sudo systemctl start haproxy ``` -------------------------------- ### Implement read-only functions (Clarity) Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Defines three read-only functions: `get-message`, `get-message-author`, and `get-message-count-at-block`. The last uses `at-block` to evaluate the expression as if at a specific Stacks block height. ```clarity ;; Read-only function to get a message by ID (define-read-only (get-message (id uint)) (map-get? messages id) ) ;; Read-only function to get message author (define-read-only (get-message-author (id uint)) (get author (map-get? messages id)) ) ;; Read-only function to get message count at a specific Stacks block height (define-read-only (get-message-count-at-block (block uint)) (ok (at-block (unwrap! (get-stacks-block-info? id-header-hash block) ERR_BLOCK_NOT_FOUND) (var-get message-count) )) ) ``` -------------------------------- ### Download and extract mainnet chainstate archive Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Downloads the latest mainnet chainstate archive from archive.hiro.so, decompresses it, and removes the archive file. Use this to start the node with a data archive instead of syncing from genesis. ```bash # Enter the node's datadir cd ~/stacks-node/data # Download the archive wget https://archive.hiro.so/mainnet/stacks-blockchain/mainnet-stacks-blockchain-latest.tar.gz # Decompress the archive tar -xvf mainnet-stacks-blockchain-latest.tar.gz # Remove the archive rm mainnet-stacks-blockchain-latest.tar.gz ``` -------------------------------- ### Start the signer (Docker) Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Runs the signer in a Docker container with restart policy, volume mounts for config and data, port mapping, and RUST_BACKTRACE. The endpoint port must be reachable by the Stacks node, and the volume needs a few GB free. On non-x64 hosts, add --platform=linux/amd64 to avoid manifest/platform mismatch. ```bash docker run -d \ --restart unless-stopped \ --name stacks-signer \ -v ~/stacks-signer/signer-config.toml:/config.toml \ -v ~/stacks-signer/data:/var/stacks \ -p 30000:30000 \ -e RUST_BACKTRACE=full \ $IMG:$VER \ stacks-signer run --config /config.toml ``` -------------------------------- ### Run prerequisites.sh scripted install Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-miner/miner-prerequisites.md Downloads and runs the prerequisites.sh script from the miner-docs repository to install everything needed. ```bash curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/stacksfoundation/miner-docs/main/scripts/prerequisites.sh | bash ``` -------------------------------- ### Transfer 1 satoshi of sBTC from user to the contract Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Calls the external sbtc-token contract to transfer 1 satoshi of sBTC from the caller to the contract. Uses restrict-assets? as an in-contract post-condition to protect funds, and unwrap! to handle the ERR_NOT_ENOUGH_SBTC error if the transfer fails. ```clarity (try! (restrict-assets? contract-caller ((with-ft 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token "sbtc-token" u1)) (unwrap! ;; Charge 1 satoshi of sBTC from the caller (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token transfer u1 contract-caller current-contract none ) ERR_NOT_ENOUGH_SBTC ) )) ``` -------------------------------- ### Start the node (Docker) Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Start the Stacks node in a Docker container with the given volume mounts and port mappings. Expose p2p_bind to the internet and keep rpc_bind reachable only by your signer. working_dir needs 500 GB to 1 TB. In Docker's default bridge network, localhost inside a container is that container, not the host, so events_observer.endpoint must name the signer container rather than 127.0.0.1; connection refused errors here almost always mean that. ```bash docker run -d \ --restart unless-stopped \ --name stacks-node \ -v ~/stacks-node/node-config.toml:/config.toml \ -v ~/stacks-node/data:/root/stacks-node/data \ -p 20443:20443 \ -p 20444:20444 \ -e RUST_BACKTRACE=full \ $NODE_IMG:$NODE_VER \ stacks-node start --config /config.toml ``` -------------------------------- ### Download and extract testnet chainstate archive Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Downloads the latest testnet chainstate archive from archive.hiro.so, decompresses it, and removes the archive file. Use this to start the node with a data archive instead of syncing from genesis. ```bash # Enter the node's datadir cd ~/stacks-node/data # Download the archive wget https://archive.hiro.so/testnet/stacks-blockchain/testnet-stacks-blockchain-latest.tar.gz # Decompress the archive tar -xvf testnet-stacks-blockchain-latest.tar.gz # Remove the archive rm testnet-stacks-blockchain-latest.tar.gz ``` -------------------------------- ### Install required packages Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-miner/miner-prerequisites.md Installs Node.js, system packages, Rust, and Stacks CLI tools required for the miner setup. Includes build-essential, jq, netcat, nodejs, git, autoconf, boost libraries, libevent, libzmq5, libtool, m4, automake, pkg-config, and more. ```bash $ curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - $ sudo apt-get update -y && sudo apt-get install -y \ build-essential \ jq \ netcat \ nodejs \ git \ autoconf \ libboost-system-dev \ libboost-filesystem-dev \ libboost-thread-dev \ libboost-chrono-dev \ libevent-dev \ libzmq5 \ libtool \ m4 \ automake \ pkg-config \ libtool \ libboost-system-dev \ libboost-filesystem-dev \ libboost-chrono-dev \ libboost-program-options-dev \ libboost-test-dev \ libboost-thread-dev \ libboost-iostreams-dev $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh && source $HOME/.cargo/env $ sudo npm install -g @stacks/cli rimraf shx ``` -------------------------------- ### Install @stacks/connect package Source: https://github.com/stacks-network/docs/blob/master/docs/build/stacks-connect/connect-wallet.md Run this command to add the @stacks/connect package to your project. Required before using any of the other examples on this page. ```bash npm install @stacks/connect ``` -------------------------------- ### Install, build, and run the API locally Source: https://github.com/stacks-network/docs/blob/master/docs/reference/api/stacks-mesh-api/README.md Use these commands to install dependencies, build all packages, start the API in production mode, or run it in watch mode for development. ```bash # Install dependencies npm ci # Build all packages npm run build # Start the API (production) npm start # Or start in watch mode (development) npm run dev ``` -------------------------------- ### Create a new Clarinet project for Rendezvous testing Source: https://github.com/stacks-network/docs/blob/master/docs/build/rendezvous/quickstart.md Initializes a new Clarinet project named 'rendezvous-tutorial' and navigates into it. Requires Node.js >= 20 and Clarinet installed. The resulting directory contains Clarinet.toml, contracts/, settings/Devnet.toml, and tests/. ```bash clarinet new rendezvous-tutorial cd rendezvous-tutorial ``` -------------------------------- ### Install legacy Stacks Connect 7.x.x Source: https://github.com/stacks-network/docs/blob/master/docs/build/stacks-connect/migration-guide.md Legacy install command for Stacks Connect version 7.10.1, which may still be better supported by some wallets. Use this if you need to continue with the older version while things stabilize. ```bash npm install @stacks/connect@7.10.1 ``` -------------------------------- ### Update the message-count variable Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Increments the existing data variable 'message-count' with the let-bound id variable. ```clarity (var-set message-count id) ``` -------------------------------- ### Start Expo development server Source: https://github.com/stacks-network/docs/blob/master/docs/build/stacks.js/react-native-integration.md Runs the development server to test the initial setup. Use the Expo Go app to scan the QR code and verify the base project works. ```bash npm start ``` -------------------------------- ### Install the Helm chart and run the miner Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-miner/mine-mainnet-stacks-tokens.md Starts minikube if needed, adds the Blockstack Helm repository, and installs the stacks-blockchain chart with the release name 'my-release' configured to run as a miner on mainnet. The 'miner' wallet must already exist on the bitcoind instance the chart points at (config.burnchain.peer_host and its RPC credentials). ```bash minikube start # Only run this if standing up a local Kubernetes cluster helm repo add blockstack https://charts.blockstack.xyz helm install my-release blockstack/stacks-blockchain \ --set config.node.miner=true \ --set config.node.seed="your-privateKey-from-generate-keychain-step" \ --set config.burnchain.mode="mainnet" \ --set config.burnchain.wallet_name="miner" ``` -------------------------------- ### Usage: distributionCycleToBurnHeight Source: https://github.com/stacks-network/docs/blob/master/docs/reference/stacks.js/stacks-bitcoin-staking/cycles/distributioncycletoburnheight.md Computes the first Bitcoin block height of a distribution cycle. The example fetches PoxInfo, calculates the next distribution cycle, and gets its start height. The input is not validated. ```ts import { currentDistributionCycle, distributionCycleToBurnHeight, fetchPoxInfo } from '@stacks/bitcoin-staking'; const poxInfo = await fetchPoxInfo({ network: 'mainnet' }); const next = currentDistributionCycle(poxInfo) + 1; const nextStart = distributionCycleToBurnHeight({ distributionCycle: next, poxInfo }); const blocksUntilNext = nextStart - poxInfo.currentBurnchainBlockHeight; ``` -------------------------------- ### Custom Dockerfile for Stacks Node Source: https://github.com/stacks-network/docs/blob/master/docs/reference/nakamoto-upgrade/setting-up-a-primary-post-nakamoto-testnet-node.md Alternative Docker setup using a custom Dockerfile that copies the `node-config.toml` into the image and exposes the required ports (20444 and 20443). The container runs `stacks-node start --config /config.toml`. ```docker FROM blockstack/stacks-core:4.0.2 COPY node-config.toml /config.toml EXPOSE 20444 EXPOSE 20443 CMD ["stacks-node", "start", "--config", "/config.toml"] ``` -------------------------------- ### Enable and start Nginx Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-node/run-a-node-behind-a-proxy.md Creates a symlink to enable the site, tests the configuration, and restarts Nginx. ```bash sudo ln -s /etc/nginx/sites-available/stacks-node /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl restart nginx ``` -------------------------------- ### Define constants in message-board.clar Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Clarity code to define contract constants: the contract owner (using tx-sender) and custom error codes. The tx-sender value is determined at deployment time to point to the deploying principal. ```clarity ;; Simple Message Board Contract ;; This contract allows users to read and post messages for a fee in sBTC. ;; Define contract owner (define-constant CONTRACT_OWNER tx-sender) ;; Define error codes (define-constant ERR_NOT_ENOUGH_SBTC (err u1004)) (define-constant ERR_NOT_CONTRACT_OWNER (err u1005)) (define-constant ERR_BLOCK_NOT_FOUND (err u1003)) ``` -------------------------------- ### Define public function and params Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Shows the skeleton of the public function definition. The define-public function makes the function callable by anyone. The parameter (content (string-utf8 280)) defines a custom parameter name and type. ```clarity (define-public (add-message (content (string-utf8 280))) ;; function body ) ``` -------------------------------- ### Create signer-config.toml for Mainnet Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Creates the signer configuration file for Mainnet using a heredoc. Replace and with your actual values. The file is written to ~/stacks-signer/signer-config.toml. ```bash # Set environment variables AUTH_TOKEN= # Used for signer-node authentication PRIVATE_KEY= # privateKey from Step 1, this is the signer's private key # Create the signer's configuration file cat < ~/stacks-signer/signer-config.toml node_host = "127.0.0.1:20443" endpoint = "127.0.0.1:30000" network = "mainnet" db_path = "$HOME/stacks-signer/data/signer.sqlite" auth_password = "$AUTH_TOKEN" stacks_private_key = "$PRIVATE_KEY" metrics_endpoint = "127.0.0.1:9154" EOF ``` -------------------------------- ### Verify node version and config Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Run these commands to confirm the Stacks node binary works and the configuration file loads correctly. The version command prints the build info, and check-config reports whether the config at the given path is valid. ```bash # Verify the node's version ~/stacks-node/stacks-node version # Output: INFO [1786366428.758607] [stacks-node/src/main.rs:329] [main] stacks-node 4.0.1 (62e03cc, release build, linux [x86_64]) stacks-node 4.0.1 (62e03cc, release build, linux [x86_64]) # Verify the node's config ~/stacks-node/stacks-node check-config --config ~/stacks-node/node-config.toml # Output: INFO [1786366428.987308] [stacks-node/src/main.rs:329] [main] stacks-node 4.0.1 (62e03cc, release build, linux [x86_64]) INFO [1786366428.987352] [stacks-node/src/main.rs:359] [main] Loading config at path /home/user/stacks-node/node-config.toml INFO [1786366429.090617] [stacks-node/src/main.rs:372] [main] Loaded config! ``` -------------------------------- ### Create let variable binding for next message id Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Creates a local variable 'id' that is only accessible within the function body. The id is calculated as the current message-count plus u1, representing the new message id. ```clarity (let ((id (+ (var-get message-count) u1))) ;; body expressions ) ``` -------------------------------- ### Install @stacks/network Source: https://github.com/stacks-network/docs/blob/master/docs/build/stacks.js/overview.md Install the Stacks.js network package for network configuration. ```bash npm install @stacks/network ``` -------------------------------- ### Set up a new Clarinet project Source: https://github.com/stacks-network/docs/blob/master/docs/build/clarinet/testing-with-clarinet-sdk.md Creates a new Clarinet project named stx-defi, changes into its directory, and installs dependencies with npm. ```bash clarinet new stx-defi cd stx-defi npm install ``` -------------------------------- ### Define data storage in message-board.clar Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Clarity code to define a map for storing messages (with ID, content, author, and block height) and a data variable to count total messages. This sets up the contract's state for message storage. ```clarity ;; Define a map to store messages ;; Each message has an ID, content, author, and Bitcoin block height timestamp (define-map messages uint { message: (string-utf8 280), author: principal, time: uint, } ) ;; Counter for total messages (define-data-var message-count uint u0) ``` -------------------------------- ### Create mainnet node configuration file (node-config.toml) Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Creates a mainnet Stacks node configuration file with stacker enabled, an auth token for signer authentication, and an events observer. Replace with your actual token. If running your own bitcoin node, update peer_host and optionally add rpc_port, peer_port, username, and password under [burnchain]. ```bash # Set environment variables AUTH_TOKEN= # Used for signer-node authentication, same token as the one set up in the signer configuration # Create the node's configuration file cat < ~/stacks-node/node-config.toml [node] working_dir = "$HOME/stacks-node/data" rpc_bind = "127.0.0.1:20443" p2p_bind = "0.0.0.0:20444" prometheus_bind = "127.0.0.1:9153" bootstrap_node = "02196f005965cebe6ddc3901b7b1cc1aa7a88f305bb8c5893456b8f9a605923893@seed.mainnet.hiro.so:20444,02539449ad94e6e6392d8c1deb2b4e61f80ae2a18964349bc14336d8b903c46a8c@cet.stacksnodes.org:20444,02ececc8ce79b8adf813f13a0255f8ae58d4357309ba0cedd523d9f1a306fcfb79@sgt.stacksnodes.org:20444,0303144ba518fe7a0fb56a8a7d488f950307a4330f146e1e1458fc63fb33defe96@est.stacksnodes.org:20444" stacker = true [burnchain] chain = "bitcoin" mode = "mainnet" peer_host = "bitcoin.mainnet.stacks.org" [connection_options] auth_token = "$AUTH_TOKEN" [[events_observer]] endpoint = "127.0.0.1:30000" events_keys = ["stackerdb", "block_proposal", "burn_blocks"] EOF ``` -------------------------------- ### Create signer-config.toml for Testnet Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Creates the signer configuration file for Testnet using a heredoc. Replace and with your actual values. The file is written to ~/stacks-signer/signer-config.toml. ```bash # Set environment variables AUTH_TOKEN= # Used for signer-node authentication PRIVATE_KEY= # privateKey from Step 1, this is the signer's private key # Create the signer's configuration file cat < ~/stacks-signer/signer-config.toml node_host = "127.0.0.1:20443" endpoint = "127.0.0.1:30000" network = "testnet" db_path = "$HOME/stacks-signer/data/signer.sqlite" auth_password = "$AUTH_TOKEN" stacks_private_key = "$PRIVATE_KEY" metrics_endpoint = "127.0.0.1:9154" EOF ``` -------------------------------- ### Store message data in mapping Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Uses map-set to add a new key-value pair to the 'messages' mapping. The value includes the message content, author, and the current Bitcoin block height via burn-block-height, which provides read access to Bitcoin state. ```clarity (map-set messages id { message: content, author: contract-caller, time: burn-block-height, }) ``` -------------------------------- ### Enable and start systemd services for signer and node Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/best-practices-to-run-a-signer.md Reloads systemd, enables both services to start at boot, and starts them. Run after creating the unit files. ```bash sudo systemctl daemon-reload sudo systemctl enable stacks-signer.service stacks-node.service sudo systemctl start stacks-signer.service sudo systemctl start stacks-node.service ``` -------------------------------- ### Allow contract owner to withdraw funds (Clarity) Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Defines a public function `withdraw-funds` that lets the contract owner withdraw accumulated sBTC fees. It uses `asserts!` to check `tx-sender` equals `CONTRACT_OWNER` and calls the `.sbtc-token` contract's `transfer` function. ```clarity ;; Withdraw function for contract owner to withdraw accumulated sBTC (define-public (withdraw-funds) (begin (asserts! (is-eq tx-sender CONTRACT_OWNER) (err u1005)) (let ((balance (unwrap-panic (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token get-balance current-contract )))) (if (> balance u0) (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token transfer balance current-contract CONTRACT_OWNER none ) (ok false) ) ) ) ) ``` -------------------------------- ### Vitest configuration with SDK setup file Source: https://github.com/stacks-network/docs/blob/master/docs/build/clarinet/testing-with-clarinet-sdk.md Sets up Vitest to use the SDK's vitestSetupFilePath in setupFiles, which prepares the simnet instance before tests run. ```javascript import { defineConfig } from "vitest/config"; import { vitestSetupFilePath } from "@stacks/clarinet-sdk/vitest"; export default defineConfig({ test: { environment: "node", globals: true, setupFiles: [vitestSetupFilePath], }, }); ``` -------------------------------- ### Install Clarinet from Binary Source: https://github.com/stacks-network/docs/blob/master/docs/build/clarinet/overview.md Download the pre-built Linux binary, extract it, make it executable, and move it to /usr/local/bin. ```bash wget -nv https://github.com/stx-labs/clarinet/releases/latest/download/clarinet-linux-x64-glibc.tar.gz -O clarinet-linux-x64.tar.gz tar -xf clarinet-linux-x64.tar.gz chmod +x ./clarinet mv ./clarinet /usr/local/bin ``` -------------------------------- ### Connect Leather wallet and fetch BNS name in src/App.tsx Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Uses @stacks/connect to authenticate the Leather wallet, disconnect, and retrieve the wallet's BNS name via the BNSv2 API. The connect() method can be configured to show only specific wallets or any SIP-030 compliant wallet. ```TypeScript import { connect, disconnect } from '@stacks/connect' import type { GetAddressesResult } from '@stacks/connect/dist/types/methods' import { useState } from 'react' function App() { let [isConnected, setIsConnected] = useState(false) let [walletInfo, setWalletInfo] = useState(null) let [bns, setBns] = useState('') async function connectWallet() { let connectionResponse: GetAddressesResult = await connect() let bnsName = await getBns(connectionResponse.addresses[2].address) setIsConnected(true) setWalletInfo(connectionResponse) setBns(bnsName) } async function disconnectWallet() { disconnect(); } async function getBns(stxAddress: string) { let response = await fetch(`https://api.bnsv2.com/testnet/names/address/${stxAddress}/valid`) let data = await response.json() return data.names[0].full_name } return ( <>

Stacks Dev Quickstart Message Board

{isConnected ? ( ) : ( )} ) } ``` -------------------------------- ### Download and extract stacks-signer binary (Linux x64 glibc) Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Downloads the latest signer release ZIP for Linux x64 glibc and extracts the stacks-signer binary. Run these commands from the signer directory. ```bash cd ~/stacks-signer wget https://github.com/stacks-network/stacks-core/releases/latest/download/linux-glibc-x64.zip unzip linux-glibc-x64.zip ``` -------------------------------- ### Create a new Clarinet project with `clarinet new counter` Source: https://github.com/stacks-network/docs/blob/master/docs/build/clarinet/quickstart.md Initializes a new Clarinet project named 'counter' with a complete structure including contracts, settings, tests, and configuration files. ```bash clarinet new counter ``` -------------------------------- ### Call get-message-count-at-block read-only function with fetchCallReadOnlyFunction Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Retrieves the current Stacks block height from the Hiro API endpoint and passes it to the contract's get-message-count-at-block read-only function using fetchCallReadOnlyFunction. Requires a Hiro API key for the request; see Hiro docs for available endpoints and rate plans. ```typescript // ... import type { ClarityValue } from '@stacks/connect/dist/types/methods' import { Cl, fetchCallReadOnlyFunction } from '@stacks/transactions' function App() { // ... async function getMessageCountAtBlock() { let response = await fetch('https://api.testnet.hiro.so/v2/info', { headers: { "x-api-key": "" } }) let data = await response.json() let stacksBlockHeight = data.stacks_tip_height let result: ClarityValue = await fetchCallReadOnlyFunction({ contractAddress: 'ST11V9ZN6E6VG72SHMAVM9GDE30VD3VGW5Q1W9WX3', contractName: 'stacks-dev-quickstart-message-board', functionName: 'get-message-count-at-block', functionArgs: [Cl.uint(stacksBlockHeight)], network: 'testnet', senderAddress: 'ST11V9ZN6E6VG72SHMAVM9GDE30VD3VGW5Q1W9WX3', }) } // ... ``` -------------------------------- ### Install and start prometheus-node-exporter Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/how-to-monitor-signer.md Install and enable the Prometheus node exporter on Debian-based systems to expose host metrics on port 9100 of localhost. ```bash sudo apt install prometheus-node-exporter sudo systemctl enable prometheus-node-exporter sudo systemctl start prometheus-node-exporter ``` -------------------------------- ### Unit test for message board contract (tests/message-board.test.ts) Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Vitest unit tests for the message board contract using @stacks/transactions. The first test calls add-message and verifies the response and event tuple; the second mines two empty burn blocks, calls withdraw-funds, and checks the ft_transfer_event. Run with `npm run test`. ```typescript import { Cl, ClarityType } from "@stacks/transactions"; import { describe, expect, it } from "vitest"; const accounts = simnet.getAccounts(); const deployer = accounts.get("deployer")!; const address1 = accounts.get("wallet_1")!; describe("example tests", () => { let content = "Hello Stacks Devs!" it("allows user to add a new message", () => { let currentBurnBlockHeight = simnet.burnBlockHeight; let confirmation = simnet.callPublicFn( "stacks-dev-quickstart-message-board", "add-message", [Cl.stringUtf8(content)], address1 ) const messageCount = simnet.getDataVar("stacks-dev-quickstart-message-board", "message-count"); expect(confirmation.result).toHaveClarityType(ClarityType.ResponseOk); expect(confirmation.result).toBeOk(messageCount); expect(confirmation.events[1].data.value).toBeTuple({ author: Cl.standardPrincipal(address1), event: Cl.stringAscii("[Stacks Dev Quickstart] New Message"), id: messageCount, message: Cl.stringUtf8(content), time: Cl.uint(currentBurnBlockHeight), }); }); it("allows contract owner to withdraw funds", () => { simnet.callPublicFn( "stacks-dev-quickstart-message-board", "add-message", [Cl.stringUtf8(content)], address1 ) simnet.mineEmptyBurnBlocks(2); let confirmation = simnet.callPublicFn( "stacks-dev-quickstart-message-board", "withdraw-funds", [], deployer ) expect(confirmation.result).toBeOk(Cl.bool(true)); expect(confirmation.events[0].event).toBe("ft_transfer_event") expect(confirmation.events[0].data).toMatchObject({ amount: '1', asset_identifier: 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token::sbtc-token', recipient: deployer, sender: `${deployer}${".stacks-dev-quickstart-message-board"}`, }) }) }); ``` -------------------------------- ### Full add-message function in message-board.clar Source: https://github.com/stacks-network/docs/blob/master/docs/build/get-started/developer-quickstart.md Complete public function that adds a message for 1 satoshi of sBTC. It uses in-contract post-conditions, calls the official sBTC token contract, reads Bitcoin state via burn-block-height, emits an event, and returns the message ID. The function is marked with @format-ignore and includes the ERR_NOT_ENOUGH_SBTC error path. ```clarity ;; Public function to add a new message for 1 satoshi of sBTC ;; @format-ignore (define-public (add-message (content (string-utf8 280))) (let ((id (+ (var-get message-count) u1))) (try! (restrict-assets? contract-caller ((with-ft 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token "sbtc-token" u1)) (unwrap! ;; Charge 1 satoshi of sBTC from the caller (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token transfer u1 contract-caller current-contract none ) ERR_NOT_ENOUGH_SBTC ) )) ;; Store the message with current Bitcoin block height (map-set messages id { message: content, author: contract-caller, time: burn-block-height, }) ;; Update message count (var-set message-count id) ;; Emit event for the new message (print { event: "[Stacks Dev Quickstart] New Message", message: content, id: id, author: contract-caller, time: burn-block-height, }) ;; Return the message ID (ok id) ) ) ``` -------------------------------- ### Follow logs Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-node/run-a-node-with-docker.md Follow the logs to track sync progress. For networks other than mocknet, downloading initial headers can take several minutes. ```bash ./manage.sh -n -a logs ``` -------------------------------- ### Download and unzip Stacks node binary (Linux x64 glibc) Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Commands to download and decompress the latest Stacks node release ZIP for a Linux x64 glibc machine. Assumes the node directory is ~/stacks-node and the binary is inside the extracted folder. ```bash # Enter the node directory cd ~/stacks-node # Download the node binary zip wget https://github.com/stacks-network/stacks-core/releases/latest/download/linux-glibc-x64.zip # Unzip the node binary archive unzip linux-glibc-x64.zip ``` -------------------------------- ### Setup wallet and public clients in index.ts Source: https://github.com/stacks-network/docs/blob/master/docs/build/more-guides/bridging-usdcx.md Creates a wallet account from the private key and initializes both a wallet client (for signing transactions) and a public client (for reading blockchain data) connected to the Sepolia testnet. ```typescript // --snip-- // Set up wallet and wallet provider const account = privateKeyToAccount(config.PRIVATE_KEY); const client = createWalletClient({ account, chain: sepolia, transport: http(config.ETH_RPC_URL), }); const publicClient = createPublicClient({ chain: sepolia, transport: http(config.ETH_RPC_URL), }); ``` -------------------------------- ### Usage example for fetchSignerInfo Source: https://github.com/stacks-network/docs/blob/master/docs/reference/stacks.js/stacks-bitcoin-staking/fetch/fetchsignerinfo.md Imports fetchPoxInfo, fetchSignerInfo, and fetchSignerSetFirstItem from '@stacks/bitcoin-staking'. Fetches the current reward cycle, retrieves the first signer-manager, then calls fetchSignerInfo to get its signer key. The returned signerKey is a 33-byte compressed public key in lowercase hex without a 0x prefix. A non-2xx response throws an Error with a message starting with 'Error calling read-only function.'. ```TypeScript import { fetchPoxInfo, fetchSignerInfo, fetchSignerSetFirstItem } from '@stacks/bitcoin-staking'; const { rewardCycleId: rewardCycle } = await fetchPoxInfo({ network: 'mainnet' }); const signerManager = await fetchSignerSetFirstItem({ rewardCycle, network: 'mainnet' }); if (signerManager) { const info = await fetchSignerInfo({ signerManager, network: 'mainnet' }); info?.signerKey; // 33-byte compressed public key, hex } ``` -------------------------------- ### get function examples with tuples and maps Source: https://github.com/stacks-network/docs/blob/master/docs/reference/clarity/functions.md Demonstrates get on a literal tuple, on a map-get? result (returns (some ...) when present), and on a missing key (returns none). Requires a map defined with define-map and inserted data. ```clarity (define-map names-map { name: (string-ascii 12) } { id: int }) (map-insert names-map { name: "blockstack" } { id: 1337 }) ;; Returns true (get id (tuple (name "blockstack") (id 1337))) ;; Returns 1337 (get id (map-get? names-map (tuple (name "blockstack")))) ;; Returns (some 1337) (get id (map-get? names-map (tuple (name "non-existent")))) ;; Returns none ``` -------------------------------- ### Hello World Script: 1 2 OP_ADD Source: https://github.com/stacks-network/docs/blob/master/docs/tutorials/bitcoin-primer/bitcoin-development-basics/bitcoin-script-fundamentals.md Default example in the online Bitcoin IDE. Pushes 1 and 2 onto the stack, then OP_ADD pops the top two items, adds them, and pushes the result (3). Use the Step button to visualize stack operations. ```bitcoin-script 1 2 OP_ADD ``` -------------------------------- ### Verify signer version and configuration Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-signer/signer-quickstart.md Checks the signer version and validates the configuration file. The expected outputs show version 4.0.1 and the resolved configuration values. ```bash # Verify the signer's version ~/stacks-signer/stacks-signer --version # Output: stacks-signer 4.0.1 (62e03cc, release build, linux [x86_64]) # Verify the config file ~/stacks-signer/stacks-signer check-config -c ~/stacks-signer/signer-config.toml # Output: Signer version: stacks-signer 4.0.1 (62e03cc, release build, linux [x86_64]) Config: Stacks node host: 127.0.0.1:20443 Signer endpoint: 127.0.0.1:30000 Stacks address: SP1G... # address from keychain file Public key: 03a3... # publicKey from keychain file Network: mainnet # or testnet Chain ID: 0x1 # or 0x80000000 for testnet Database path: /home/user/stacks-signer/data/signer.sqlite Metrics endpoint: 127.0.0.1:9154 Dry run: false ``` -------------------------------- ### Start services Source: https://github.com/stacks-network/docs/blob/master/docs/operate/run-a-node/run-a-node-with-docker.md Start the docker-compose services for the chosen network. Replace with mainnet, testnet, or mocknet. ```bash ./manage.sh -n -a start ``` -------------------------------- ### View HTML coverage report with genhtml Source: https://github.com/stacks-network/docs/blob/master/docs/build/clarinet/testing-with-clarinet-sdk.md Installs lcov, generates an HTML coverage report from lcov.info with branch coverage, and opens it in the default browser. This is a macOS example. ```Bash brew install lcov genhtml lcov.info --branch-coverage -o coverage open coverage/index.html ``` -------------------------------- ### Use a packaged configuration Source: https://github.com/stacks-network/docs/blob/master/docs/build/clarinet/local-blockchain-development.md Start Devnet using a packaged configuration file with `--package demo-env.json`. ```bash $ clarinet devnet start --package demo-env.json ```