# Table of Contents - [Introduction | Stacks Documentation](#introduction-stacks-documentation) - [Stacks Brand Kit | Stacks Brand | Stacks Documentation](#stacks-brand-kit-stacks-brand-stacks-documentation) - [Introduction | Learn | Stacks Documentation](#introduction-learn-stacks-documentation) - [Stacks 101 | Learn | Stacks Documentation](#stacks-101-learn-stacks-documentation) - [What Is Stacks? | Learn | Stacks Documentation](#what-is-stacks-learn-stacks-documentation) - [Network Fundamentals | Learn | Stacks Documentation](#network-fundamentals-learn-stacks-documentation) - [Bitcoin Theses | Press & Reports | Stacks Documentation](#bitcoin-theses-press-reports-stacks-documentation) - [Mainnet and Testnets | Learn | Stacks Documentation](#mainnet-and-testnets-learn-stacks-documentation) - [2024 | Press & Reports | Stacks Documentation](#2024-press-reports-stacks-documentation) - [Bitcoin Reports | Press & Reports | Stacks Documentation](#bitcoin-reports-press-reports-stacks-documentation) - [March 2024 | Press & Reports | Stacks Documentation](#march-2024-press-reports-stacks-documentation) - [July 2024 | Press & Reports | Stacks Documentation](#july-2024-press-reports-stacks-documentation) - [June 2024 | Press & Reports | Stacks Documentation](#june-2024-press-reports-stacks-documentation) - [October 2024 | Press & Reports | Stacks Documentation](#october-2024-press-reports-stacks-documentation) - [Tokens | Learn | Stacks Documentation](#tokens-learn-stacks-documentation) - [May 2024 | Press & Reports | Stacks Documentation](#may-2024-press-reports-stacks-documentation) - [November 2024 | Press & Reports | Stacks Documentation](#november-2024-press-reports-stacks-documentation) - [September 2024 | Press & Reports | Stacks Documentation](#september-2024-press-reports-stacks-documentation) - [April 2024 | Press & Reports | Stacks Documentation](#april-2024-press-reports-stacks-documentation) - [February 2024 | Press & Reports | Stacks Documentation](#february-2024-press-reports-stacks-documentation) - [August 2024 | Press & Reports | Stacks Documentation](#august-2024-press-reports-stacks-documentation) - [Proof of Transfer (PoX) | Learn | Stacks Documentation](#proof-of-transfer-pox-learn-stacks-documentation) - [January 2024 | Press & Reports | Stacks Documentation](#january-2024-press-reports-stacks-documentation) - [August 2025 | Press & Reports | Stacks Documentation](#august-2025-press-reports-stacks-documentation) - [2025 | Press & Reports | Stacks Documentation](#2025-press-reports-stacks-documentation) - [April 2025 | Press & Reports | Stacks Documentation](#april-2025-press-reports-stacks-documentation) - [May 2025 | Press & Reports | Stacks Documentation](#may-2025-press-reports-stacks-documentation) - [September 2025 | Press & Reports | Stacks Documentation](#september-2025-press-reports-stacks-documentation) - [February 2025 | Press & Reports | Stacks Documentation](#february-2025-press-reports-stacks-documentation) - [June 2025 | Press & Reports | Stacks Documentation](#june-2025-press-reports-stacks-documentation) - [January 2025 | Press & Reports | Stacks Documentation](#january-2025-press-reports-stacks-documentation) - [December 2024 | Press & Reports | Stacks Documentation](#december-2024-press-reports-stacks-documentation) - [Introduction | Operate | Stacks Documentation](#introduction-operate-stacks-documentation) - [July 2025 | Press & Reports | Stacks Documentation](#july-2025-press-reports-stacks-documentation) - [March 2025 | Press & Reports | Stacks Documentation](#march-2025-press-reports-stacks-documentation) - [November 2025 | Press & Reports | Stacks Documentation](#november-2025-press-reports-stacks-documentation) - [Run a Node | Operate | Stacks Documentation](#run-a-node-operate-stacks-documentation) - [Miner Costs and Fees | Operate | Stacks Documentation](#miner-costs-and-fees-operate-stacks-documentation) - [Run a Node with Quicknode | Operate | Stacks Documentation](#run-a-node-with-quicknode-operate-stacks-documentation) - [Verify Miner | Operate | Stacks Documentation](#verify-miner-operate-stacks-documentation) - [October 2025 | Press & Reports | Stacks Documentation](#october-2025-press-reports-stacks-documentation) - [Run a Miner | Operate | Stacks Documentation](#run-a-miner-operate-stacks-documentation) - [Accounts & Addresses | Cookbook | Stacks Documentation](#accounts-addresses-cookbook-stacks-documentation) - [Transaction Building | Cookbook | Stacks Documentation](#transaction-building-cookbook-stacks-documentation) - [Miner Prerequisites | Operate | Stacks Documentation](#miner-prerequisites-operate-stacks-documentation) - [Run a Node with a Hosted Provider | Operate | Stacks Documentation](#run-a-node-with-a-hosted-provider-operate-stacks-documentation) - [Token Transfers | Cookbook | Stacks Documentation](#token-transfers-cookbook-stacks-documentation) - [Address Utilities | Cookbook | Stacks Documentation](#address-utilities-cookbook-stacks-documentation) - [Data Utility | Cookbook | Stacks Documentation](#data-utility-cookbook-stacks-documentation) - [Generate a wallet | Cookbook | Stacks Documentation](#generate-a-wallet-cookbook-stacks-documentation) - [Derive stacks address from keys | Cookbook | Stacks Documentation](#derive-stacks-address-from-keys-cookbook-stacks-documentation) - [Build an nft pc | Cookbook | Stacks Documentation](#build-an-nft-pc-cookbook-stacks-documentation) - [Filter items from a list | Cookbook | Stacks Documentation](#filter-items-from-a-list-cookbook-stacks-documentation) - [Transfer STX | Cookbook | Stacks Documentation](#transfer-stx-cookbook-stacks-documentation) - [Create a sponsored tx | Cookbook | Stacks Documentation](#create-a-sponsored-tx-cookbook-stacks-documentation) - [Build an ft pc | Cookbook | Stacks Documentation](#build-an-ft-pc-cookbook-stacks-documentation) - [Create sha256 hash clarity | Cookbook | Stacks Documentation](#create-sha256-hash-clarity-cookbook-stacks-documentation) - [How to Read Signer Logs | Operate | Stacks Documentation](#how-to-read-signer-logs-operate-stacks-documentation) - [Cryptography & Security | Cookbook | Stacks Documentation](#cryptography-security-cookbook-stacks-documentation) - [Check for duplicates | Cookbook | Stacks Documentation](#check-for-duplicates-cookbook-stacks-documentation) - [Stacking STX | Operate | Stacks Documentation](#stacking-stx-operate-stacks-documentation) - [Transfer a SIP10 token | Cookbook | Stacks Documentation](#transfer-a-sip10-token-cookbook-stacks-documentation) - [Run a Node with Digital Ocean | Operate | Stacks Documentation](#run-a-node-with-digital-ocean-operate-stacks-documentation) - [Return an entry from a map | Cookbook | Stacks Documentation](#return-an-entry-from-a-map-cookbook-stacks-documentation) - [Generate a secret key | Cookbook | Stacks Documentation](#generate-a-secret-key-cookbook-stacks-documentation) - [Cryptography & Security | Cookbook | Stacks Documentation](#cryptography-security-cookbook-stacks-documentation) - [Convert BTC to STX address | Cookbook | Stacks Documentation](#convert-btc-to-stx-address-cookbook-stacks-documentation) - [Generate random number | Cookbook | Stacks Documentation](#generate-random-number-cookbook-stacks-documentation) - [Integrate api keys | Cookbook | Stacks Documentation](#integrate-api-keys-cookbook-stacks-documentation) - [Create sha256 hash | Cookbook | Stacks Documentation](#create-sha256-hash-cookbook-stacks-documentation) - [Create a random burn address | Cookbook | Stacks Documentation](#create-a-random-burn-address-cookbook-stacks-documentation) - [OpSec Best Practices | Operate | Stacks Documentation](#opsec-best-practices-operate-stacks-documentation) - [Best Practices for Running a sBTC Signer | Operate | Stacks Documentation](#best-practices-for-running-a-sbtc-signer-operate-stacks-documentation) - [Build a STX pc | Cookbook | Stacks Documentation](#build-a-stx-pc-cookbook-stacks-documentation) - [Derive principal addresses between networks | Cookbook | Stacks Documentation](#derive-principal-addresses-between-networks-cookbook-stacks-documentation) - [Helper function to restrict contract calls | Cookbook | Stacks Documentation](#helper-function-to-restrict-contract-calls-cookbook-stacks-documentation) - [Fundamentos de la red | Learn | Stacks Documentation](#fundamentos-de-la-red-learn-stacks-documentation) - [Run a Node with Docker | Operate | Stacks Documentation](#run-a-node-with-docker-operate-stacks-documentation) - [Contract post-conditions | Cookbook | Stacks Documentation](#contract-post-conditions-cookbook-stacks-documentation) - [Run a sBTC Signer | Operate | Stacks Documentation](#run-a-sbtc-signer-operate-stacks-documentation) - [Welcome to the Cookbook | Cookbook | Stacks Documentation](#welcome-to-the-cookbook-cookbook-stacks-documentation) - [Convert string to principal | Cookbook | Stacks Documentation](#convert-string-to-principal-cookbook-stacks-documentation) - [Key and Address Rotation | Operate | Stacks Documentation](#key-and-address-rotation-operate-stacks-documentation) - [Best Practices to Run a Signer | Operate | Stacks Documentation](#best-practices-to-run-a-signer-operate-stacks-documentation) - [Build an unsigned tx | Cookbook | Stacks Documentation](#build-an-unsigned-tx-cookbook-stacks-documentation) - [Snapshot the Chainstate | Operate | Stacks Documentation](#snapshot-the-chainstate-operate-stacks-documentation) - [How to Monitor Signer | Operate | Stacks Documentation](#how-to-monitor-signer-operate-stacks-documentation) - [Run a Pruned Bitcoin Node | Operate | Stacks Documentation](#run-a-pruned-bitcoin-node-operate-stacks-documentation) - [Run a Node Behind a Proxy | Operate | Stacks Documentation](#run-a-node-behind-a-proxy-operate-stacks-documentation) - [Run a Bitcoin Node | Operate | Stacks Documentation](#run-a-bitcoin-node-operate-stacks-documentation) - [Introducción | Learn | Stacks Documentation](#introducci-n-learn-stacks-documentation) - [Stacks 101 | Learn | Stacks Documentation](#stacks-101-learn-stacks-documentation) - [Mine Testnet Stacks Tokens | Operate | Stacks Documentation](#mine-testnet-stacks-tokens-operate-stacks-documentation) - [Stack with a Pool | Operate | Stacks Documentation](#stack-with-a-pool-operate-stacks-documentation) - [Transacciones | Learn | Stacks Documentation](#transacciones-learn-stacks-documentation) - [Counter | Cookbook | Stacks Documentation](#counter-cookbook-stacks-documentation) - [Tokens | Learn | Stacks Documentation](#tokens-learn-stacks-documentation) - [Fungible Token | Cookbook | Stacks Documentation](#fungible-token-cookbook-stacks-documentation) - [Finalidad en Bitcoin | Learn | Stacks Documentation](#finalidad-en-bitcoin-learn-stacks-documentation) - [Solo Stacking | Operate | Stacks Documentation](#solo-stacking-operate-stacks-documentation) - [Send Many | Cookbook | Stacks Documentation](#send-many-cookbook-stacks-documentation) - [Mainnet y Testnets | Learn | Stacks Documentation](#mainnet-y-testnets-learn-stacks-documentation) - [Reorganizaciones de Bitcoin | Learn | Stacks Documentation](#reorganizaciones-de-bitcoin-learn-stacks-documentation) - [Run a Signer | Operate | Stacks Documentation](#run-a-signer-operate-stacks-documentation) - [Mine Mainnet Stacks Tokens | Operate | Stacks Documentation](#mine-mainnet-stacks-tokens-operate-stacks-documentation) - [¿Qué es Stacks? | Learn | Stacks Documentation](#-qu-es-stacks-learn-stacks-documentation) - [Generate a Signer Signature | Operate | Stacks Documentation](#generate-a-signer-signature-operate-stacks-documentation) - [Historia de BNS | Learn | Stacks Documentation](#historia-de-bns-learn-stacks-documentation) - [Non-Fungible token | Cookbook | Stacks Documentation](#non-fungible-token-cookbook-stacks-documentation) - [ExecutorDAO Framework | Cookbook | Stacks Documentation](#executordao-framework-cookbook-stacks-documentation) - [Especificaciones técnicas | Learn | Stacks Documentation](#especificaciones-t-cnicas-learn-stacks-documentation) - [Auditorías | Learn | Stacks Documentation](#auditor-as-learn-stacks-documentation) - [Incentivo financiero y presupuesto de seguridad | Learn | Stacks Documentation](#incentivo-financiero-y-presupuesto-de-seguridad-learn-stacks-documentation) - [The Bitcoin Connection | Learn | Stacks Documentation](#the-bitcoin-connection-learn-stacks-documentation) - [Condiciones posteriores | Learn | Stacks Documentation](#condiciones-posteriores-learn-stacks-documentation) - [Sistema de Nombres de Bitcoin | Learn | Stacks Documentation](#sistema-de-nombres-de-bitcoin-learn-stacks-documentation) - [Producción de bloques | Learn | Stacks Documentation](#producci-n-de-bloques-learn-stacks-documentation) - [Ordinals Swap | Cookbook | Stacks Documentation](#ordinals-swap-cookbook-stacks-documentation) - [Operate a Pool | Operate | Stacks Documentation](#operate-a-pool-operate-stacks-documentation) - [Clarity | Learn | Stacks Documentation](#clarity-learn-stacks-documentation) - [Características principales de sBTC | Learn | Stacks Documentation](#caracter-sticas-principales-de-sbtc-learn-stacks-documentation) - [NFT Marketplace | Cookbook | Stacks Documentation](#nft-marketplace-cookbook-stacks-documentation) - [Operaciones | Learn | Stacks Documentation](#operaciones-learn-stacks-documentation) - [Proof of Transfer (PoX) | Learn | Stacks Documentation](#proof-of-transfer-pox-learn-stacks-documentation) --- # Introduction | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F284917788-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FZz9BLmTU9oydDpL3qiUh%252Fuploads%252FGdHL7viBPTUy5YMx9dxN%252Fbuild-intro.png%3Falt%3Dmedia%26token%3D77008faf-011e-4e21-90f0-f4b108a11598&width=768&dpr=3&quality=100&sign=b2527a2c&sv=2) chevron-right**New to building with Stacks? Check out these weekly virtual meets!**[hashtag](https://docs.stacks.co/#new-to-building-with-stacks-check-out-these-weekly-virtual-meets) * **Clarity Working Group**: An open, developer-focused initiative dedicated to supporting builders across the Stacks ecosystem. The group brings together experienced Clarity engineers (“Clarity giga chads”), auditors, educators, grant project teams, and new developers to collaborate, learn, and advance smart contract development on Bitcoin. Check out the calendar [linkarrow-up-right](https://www.addevent.com/event/yc0x95fky8y4) to join every other Tuesday. * **AI BTC Working Group:** Join the **AI BTC Working Group**'s (WG) weekly meeting on AIBTC's twitter account, where they delve into the exciting intersection of AI and Bitcoin. Check out the calendar [linkarrow-up-right](https://www.addevent.com/event/c3qjy462xr82) to join every Thursday. chevron-right**Join the Stackers community!**[hashtag](https://docs.stacks.co/#join-the-stackers-community) Stackers is a community of people building on Bitcoin with Stacks. The purpose of the Stackers community comes down to guided paths for learning and starting a project on Stacks, developer support from community members, and the best place to hear about new events, initiatives, and opportunities to build. Join the [Stackersarrow-up-right](https://www.skool.com/stackers) ! circle-info Stacks ranks #5 among all crypto ecosystems for new developers in 2025! \[source: [Electric Capitalarrow-up-right](https://x.com/Stacks/status/1978563911948370403)\ \] ### [hashtag](https://docs.stacks.co/#hello-builders) Hello, Builders 👋 Stacks is a fast, low-cost, builder-friendly layer 2 network on Bitcoin. It’s built on Bitcoin, inheriting Bitcoin’s battle-tested security. By jumping into our docs, you’re joining the Stacks builder community that’s bringing a global onchain economy to Bitcoin. If you're here on this page, hopefully you've already gotten a good sense of _what_ Stacks' purpose is, if not, head to the [Learn](https://docs.stacks.co/learn/) section. Or if you're still on the edge of _why_ you should build with Stacks, head to [Why Build with Stacks](https://docs.stacks.co/get-started/readme/why-build-with-stacks) . * * * ### [hashtag](https://docs.stacks.co/#how-to-use-these-docs) How to use these docs The Stacks documentation is organized into a set of top-level sections, each aligned to a distinct stage of a developer’s journey—from learning core concepts to building applications and operating infrastructure. Learn Build Operate Reference Tutorials Cookbook **How does the Stacks network** _**actually**_ **work?** The [Learn](https://docs.stacks.co/learn) section focuses on building a strong academic foundation. It explains how Stacks functions as a Bitcoin layer 2, providing clarity and context around the network’s design and mechanics. Topics include Proof of Transfer (PoX), Bitcoin finality, block production, the transaction lifecycle, and more. If you want a deep understanding of how Stacks anchors to Bitcoin and why it works the way it does, this is the best place to start. **How do you build on Stacks?** This section is for experienced developers, but are new to Stacks, who are in the exploratory phase of understanding the general workflow of building apps on Stacks. These guides focus on accomplishing specific tasks—writing contracts, integrating wallets, working with sBTC or USDC—without extensive explainers. It includes curated quick starts for smart contract development with Clarinet and frontend development with Stacks.js, along with step-by-step guides covering common use cases such as integrating sBTC, onboarding users, working with price oracles, and more. **How do you run Stacks infrastructure?** The [Operate](https://docs.stacks.co/operate/run-a-node) section is designed for node operators and infrastructure providers. It covers how to run and manage Stacks nodes, signers, and miners. If you’re responsible for operating or maintaining Stacks-related infrastructure, this section contains the resources you’ll need. **Where do you look up technical details such as types, definitions, and configuration?** The [Reference](https://docs.stacks.co/reference/node-operations/readme-1) section contains authoritative technical documentation for Stacks devtools and APIs. This includes function and type definitions for Clarity and Stacks.js, API endpoint schemas, and interactive API playgrounds. If you’re an experienced Stacks developer looking to quickly reference a specific method, type, or API response, this section is built for fast lookup and precision. **Looking for a more guided, lesson-oriented experience?** The [Tutorials](https://docs.stacks.co/tutorials) section is designed for complete beginner developers who want structured, long-form lessons rather than quick answers. These tutorials provide step-by-step walkthroughs alongside in-depth explanations of the underlying concepts. The goal isn’t just to help you complete a task, but to help you understand _why_ things work the way they do as you build. If you’re a complete beginner and prefer a classroom-style, concept-driven learning experience—this section is the best place to start. **Looking for a specific code snippet?** The [Cookbook](https://docs.stacks.co/cookbook) section is for developers beyond the exploratory phase who require a specific, concrete code solution quickly for an existing application.This section provides focused, reusable Clarity and Stacks.js code snippets that solve common problems or demonstrate specific patterns—designed to be referenced, copied, and adapted rather than read end-to-end. There is also a subsection of example Clarity contracts where you'll find **starter contracts** that demonstrate common patterns and best practices in Clarity, as well as **notable production contracts** currently used by popular Stacks applications. * * * ### [hashtag](https://docs.stacks.co/#pick-your-learning-path) Pick your learning path We all have different styles of learning. If you've already got a good concept of web3 fundamentals and want to get a quick taste of what the DevEx is like on Stacks, then check out the [Developer Quickstart](https://docs.stacks.co/get-started/developer-quickstart) . Or find the path that clicks for you — and if bandwidth allows, tackle them all! [](https://docs.stacks.co/get-started/developer-quickstart) #### [hashtag](https://docs.stacks.co/#try-the-developer-quickstart) **Try the Developer Quickstart** Your 0→1 guide for building a Clarity contract and app on Stacks. [](https://docs.stacks.co/get-started/clarity-crash-course) #### [hashtag](https://docs.stacks.co/#start-learning-clarity) **Start Learning Clarity** An easy starting point for learning smart contracts. [](https://docs.stacks.co/tutorials/bitcoin-primer/introduction) #### [hashtag](https://docs.stacks.co/#bitcoin-primer-tutorial) **Bitcoin Primer Tutorial** A comprehensive end-to-end experience to building full-stack dApps on Bitcoin. [](https://learnweb3.io/degrees/stacks-developer-degree/) #### [hashtag](https://docs.stacks.co/#earn-a-stacks-developer-degree) **Earn a Stacks Developer Degree** A hands-on Stacks bootcamp by LearnWeb3. [](https://www.youtube.com/@stacks-developers) #### [hashtag](https://docs.stacks.co/#watch-our-hands-on-videos) **Watch Our Hands-On Videos** Developer insights and workshops from the Stacks ecosystem [](https://docs.stacks.co/clarinet/overview) #### [hashtag](https://docs.stacks.co/#clarity-development-using-clarinet) **Clarity Development Using Clarinet** The smart contract toolkit for Stacks * * * ### [hashtag](https://docs.stacks.co/#who-should-use-what) Who should use what If you are… First check out... Completely new to building with Stacks [Developer Quickstart](https://docs.stacks.co/get-started/developer-quickstart) Learning smart contract development [Clarity Crash Course](https://docs.stacks.co/get-started/clarity-crash-course) , [Learn Clarinet](https://docs.stacks.co/clarinet/overview) Preferring a structured, guided course that shows you every step to build full-stack apps [Stacks Developer Degreearrow-up-right](https://learnweb3.io/degrees/stacks-developer-degree/) , [Bitcoin Primer](https://docs.stacks.co/tutorials/bitcoin-primer/introduction) , [EasyAarrow-up-right](https://www.easya.io/challenges/stacks) Wanting to integrate sBTC in your app [sBTC guides](https://docs.stacks.co/more-guides/sbtc) Launching a token [Create Tokens](https://docs.stacks.co/get-started/create-a-token) Interested in security / auditing / grants [Stacks Bug Bountiesarrow-up-right](https://immunefi.com/bug-bounty/stacks/information/) , [Stacks Foundationarrow-up-right](https://stacks.org/grants) Curious about current use cases [Use Cases](https://docs.stacks.co/get-started/use-cases) Searching for a complete list of devtools [Stacks Devtools Catalog](https://docs.stacks.co/stacks-devtools-catalog) * * * ### [hashtag](https://docs.stacks.co/#still-got-questions) Still got questions? We know, it's a lot. But we, along with our large community, are always more than welcome to help you throughout your journey with Stacks. * [**Stacks Discord**arrow-up-right](https://discord.gg/stacks) : Connect with other developers and our team * [**Stacks Forum**arrow-up-right](https://forum.stacks.org/) : Ask questions and share projects * [**Stacks Twitter**arrow-up-right](https://x.com/StacksDevs) **:** Follow us on Twitter and ask us questions there * [**Stackers**arrow-up-right](https://www.skool.com/stackers) : A community to hear about new events, initiatives, and opportunities to build. [NextDeveloper Quickstartchevron-right](https://docs.stacks.co/get-started/developer-quickstart) Last updated 7 days ago Was this helpful? --- # Stacks Brand Kit | Stacks Brand | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close The most current brand resources are always available via [stacks.co/brandarrow-up-right](https://stacks.co/brand) . Stacks brand materials can be found and downloaded (exported) via the linked Figma space. [Stacks Brand Kit](https://stacks.co/brand) Last updated 4 months ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Introduction | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fam7BqpV0sbUexW7Zpqoh%252Fbitcoin-stacks-dark.png%3Falt%3Dmedia%26token%3D28aa61b3-628a-4519-a574-0b5856762626&width=768&dpr=3&quality=100&sign=75f5528d&sv=2)![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fx09gHeYU67yvfXLh7Iis%252Fbitcoin-stacks.png%3Falt%3Dmedia%26token%3D7635e08d-2495-44ed-a93c-68351882fbf3&width=768&dpr=3&quality=100&sign=40475737&sv=2) circle-info For the official Stacks whitepaper: [https://stacks-network.github.io/stacks/stacks.pdfarrow-up-right](https://stacks-network.github.io/stacks/stacks.pdf) ### [hashtag](https://docs.stacks.co/learn#stacks-the-tl-dr) Stacks: The TL;DR Stacks activates the Bitcoin economy. Bitcoin is the most adopted, most valuable, and most decentralized cryptocurrency. The Stacks L2 enables fast, cheap BTC and full-featured smart contracts on the L2 without modifying Bitcoin itself. Users and developers can use BTC in their apps and pay gas fees with BTC. All transactions on Stacks L2 are secured by Bitcoin L1 with 100% finality, enabling you to build apps and digital assets that are integrated with Bitcoin security. The Stacks layer for smart contracts has the following innovations that make it unique: **S**: Secured by the entire hash power of Bitcoin (Bitcoin finality). **T**: Trust-minimized Bitcoin peg mechanism; write to Bitcoin. **A**: Atomic BTC swaps and assets owned by BTC addresses. **C**: Clarity language for safe, decidable smart contracts. **K**: Knowledge of full Bitcoin state; read from Bitcoin. **S**: Scalable, fast transactions that settle on Bitcoin. * * * ### [hashtag](https://docs.stacks.co/learn#why-learn-the-fundamentals-of-stacks) Why learn the fundamentals of Stacks? Stacks fundamentals give you the intuition to build apps that are safer, more Bitcoin-aligned, and more future-proof. A developer who learns the basics doesn’t just write Clarity—they build apps that actually _feel like_ Bitcoin apps. 1. You'll build apps that actually leverage Bitcoin 2. You'll avoid costly design mistakes 3. You'll write better smart contracts 4. You'll use sBTC and Bitcoin writes correctly * * * ### [hashtag](https://docs.stacks.co/learn#what-to-learn-next) What to learn next? [](https://docs.stacks.co/learn/stacks-101) #### [hashtag](https://docs.stacks.co/learn#stacks-101) Stacks 101 Really dive into the nuts and bolts of how Stacks is built on Bitcoin. [](https://docs.stacks.co/learn/network-fundamentals) #### [hashtag](https://docs.stacks.co/learn#network-fundamentals) Network Fundamentals Learn about accounts, testnets, SIPs, authentication, BNS, and more. [](https://docs.stacks.co/learn/block-production) #### [hashtag](https://docs.stacks.co/learn#block-production) Block Production How do Stacks blocks get validated and mined? [](https://docs.stacks.co/learn/transactions) #### [hashtag](https://docs.stacks.co/learn#transactions) Transactions Learn about the lifecycle of a transaction on Stacks. [](https://docs.stacks.co/learn/clarity) #### [hashtag](https://docs.stacks.co/learn#clarity) Clarity Discover the philosophy and design principles of the Clarity smart contract language. [](https://docs.stacks.co/learn/sbtc) #### [hashtag](https://docs.stacks.co/learn#sbtc) sBTC Understand how bitcoin is unwrapped into a productive and programmable asset. [](https://docs.stacks.co/learn/dual-stacking) #### [hashtag](https://docs.stacks.co/learn#dual-stacking) Dual Stacking A financial innovation on top of the core foundation of Stacking. Earn bitcoin with bitcoin. [](https://docs.stacks.co/learn/bridging) #### [hashtag](https://docs.stacks.co/learn#bridging) Bridging Explore how cross-chain interoperability works with Stacks and other major networks. * * * ### [hashtag](https://docs.stacks.co/learn#additional-resources) Additional Resources * \[[Stacks YTarrow-up-right](https://youtu.be/0erpW7IEo6Y?si=Ldu4RlVVnLqOL4eP)\ \] How Stacks Will Grow In 2025 With Stacks Founder Muneeb Ali * \[[Token2049 Dubaiarrow-up-right](https://youtu.be/DFTXAOmi0es?si=sMOO6Yfj_TCVdFTF)\ \] Muneeb Ali - Building Bitcoin’s Future: The Role of Stacks L2 [NextStacks 101chevron-right](https://docs.stacks.co/learn/stacks-101) Last updated 1 month ago Was this helpful? * [Stacks: The TL;DR](https://docs.stacks.co/learn#stacks-the-tl-dr) * [Why learn the fundamentals of Stacks?](https://docs.stacks.co/learn#why-learn-the-fundamentals-of-stacks) * [What to learn next?](https://docs.stacks.co/learn#what-to-learn-next) * [Additional Resources](https://docs.stacks.co/learn#additional-resources) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Stacks 101 | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Stacks has a very unique technical model in the Bitcoin ecosystem. This section will help you get a high-level overview of the essential components to understand how Stacks works. We'll cover the basics of what Stacks is and how it works from both a philosophical and technical level, and you can dive into the further sections for more details. First up, let's get an overview of exactly what Stacks is. [PreviousIntroductionchevron-left](https://docs.stacks.co/learn) [NextWhat Is Stacks?chevron-right](https://docs.stacks.co/learn/stacks-101/what-is-stacks) Last updated 1 month ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # What Is Stacks? | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-273720c2164bb69aeb720d97d2c2bd48c974507d%252FFrame%2520316126258.jpg%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=87c4a0cb&sv=2) Stacks is a Bitcoin layer for smart contracts; it enables smart contracts and decentralized applications to use Bitcoin as an asset in a trust-minimized way and settle transactions on the Bitcoin blockchain. Stacks is a different type of Bitcoin layer for smart contracts than sidechains, with a deeper, ongoing connection to Bitcoin. Stacks enables applications and smart contracts to use BTC as their asset or money and to settle their transactions on the Bitcoin main chain. **The goal of Stacks is to grow the Bitcoin economy, by turning BTC into a productive rather than passive asset, and by enabling various decentralized applications.** The Stacks layer has its own global ledger and execution environment, to support smart contracts and to not overwhelm the Bitcoin blockchain with additional transactions. However, the Stacks layer is unique as it has most of the ideal properties that native Bitcoin smart contracts would have, but it does this without needing to add additional functionality or complexity to Bitcoin. It also provides mechanisms for higher performance and additional functionality, such as fast block times and the decentralized peg. As a Bitcoin layer, Stacks has the following innovations that make it unique: chevron-right**Secured by Bitcoin**[hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#secured-by-bitcoin) Secured by Bitcoin: enables Bitcoin finalization for Stacks transactions; transactions that happen on the Stacks layer are secured by the entire hash power of Bitcoin. Meaning that to reverse these transactions, an attacker will need to reorg Bitcoin. Such transactions settle on Bitcoin and have Bitcoin finality. Further, the Stacks layer forks with Bitcoin, so any state on Stacks automatically follows the Bitcoin forks. chevron-right**Trust-minimized Bitcoin peg**[hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#trust-minimized-bitcoin-peg) Trust-minimized Bitcoin peg: lays the foundation for a novel decentralized, Bitcoin-pegged asset, sBTC, so smart contracts can run much faster and more cheaply using the Bitcoin-pegged asset with minimal counterparty risk. This also enables contracts on the Stacks layer to write to Bitcoin through the peg-out transactions without needing to rely on a centralized, closed set of entities. Atomic swaps and assets: Stacks already has atomic BTC swaps and enables Bitcoin addresses to own and move assets defined on the Stacks layer. Magic swaps and Catamaran swaps are examples of decentralized atomic swaps between BTC on Bitcoin L1 and assets on the Stacks layer that are already live. Further, users can own Stacks layer assets like STX, stablecoins, and NFTs on Bitcoin addresses and transfer them using Bitcoin L1 transactions if they prefer. chevron-right**Clarity language**[hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#clarity-language) Clarity language: supports Clarity, a safe, decidable language for provable smart contracts. With Clarity, developers can know with mathematical certainty what a contract can and cannot do, even before executing it. The decentralized peg contract will benefit from the safety properties of the Clarity language. Of particular note, Clarity WASM is a change being made to the Clarity VM that provides significantly faster execution times, along with creating a potential path to Rust and Solidity developers being able to write smart contracts on Stacks, although this work is not part of the Nakamoto release. chevron-right**Knowledge of Bitcoin state**[hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#knowledge-of-bitcoin-state) Knowledge of Bitcoin state: has knowledge of the full Bitcoin state; it can trustlessly read Bitcoin transactions and state changes and execute smart contracts triggered by Bitcoin transactions. The Bitcoin read functionality helps to keep the decentralized peg state consistent with BTC locked on Bitcoin L1, amongst other things. chevron-right**Scalable, fast transactions**[hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#scalable-fast-transactions) Scalable, fast transactions: will provide high performance and scalability through several mechanisms, including faster Stacks layer blocks. Further, scalability layers like subnets can make different tradeoffs between performance and decentralization than the main Stacks layer. We can get an idea of the goal and ethos behind Stacks by looking at how Satoshi envisioned generalizing Bitcoin back in 2010: > _"...to be a completely separate network and separate block chain, yet share CPU power with Bitcoin...all networks in the world would share combined CPU power, increasing the total strength."_ This is a major theme in the design decisions for Stacks. A bit of a contradiction in the Bitcoin world, the Stacks network is a Bitcoin L2, but it does have its own token. This is an intentional and critical design decision primarily for the purpose of maintaining decentralization, rather than needing to rely on a federation. If that's confusing or you are skeptical, that's understandable — we'll be diving deeper into these ideas as we go through the docs. ### [hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#core-technical-components-of-stacks) Core technical components of Stacks 1 #### [hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#proof-of-transfer) Proof of Transfer Proof of Transfer (PoX) is the block production mechanism of the Stacks chain. Essentially, it attempts to recreate the block production patterns of PoW programmatically. Stacks miners spend BTC for a chance to mine new Stacks blocks. Under the hood, this block production mechanism anchors Stacks blocks to Bitcoin blocks, making it as hard to reverse a Stacks block as it is to reverse a Bitcoin block. That's a big claim, and we unpack it in further detail in the sections on Nakamoto block production. [Learn more about PoX](https://docs.stacks.co/learn/stacks-101/proof-of-transfer) 2 #### [hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#stacks-native-token-stx) Stacks' Native Token: STX The Stacks layer’s native token (STX) is essential to PoX consensus: STX is needed for (a) incentivizing Stacks miners to maintain the Stacks layer global ledger outside the Bitcoin L1, and (b) incentives for threshold signers that participate in the peg mechanism. Existing approaches to Bitcoin pegs, which lack a native token, cannot support a permissionless, open system and fallback to using custodians or trusting known federation members. 3 #### [hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#clarity) Clarity Clarity is the smart contract language that Stacks uses. It has been designed from the ground up to make it easier for developers to write safe, secure smart contracts. Additionally, since it has been purpose-built for Stacks and Bitcoin, there are built-in functions for reading Bitcoin state, which means you can use Bitcoin state to perform actions in Clarity. For example, you could set up a check to make sure a particular Bitcoin transaction has occurred before executing a mint function in Clarity, which just so happens to be what happens with the third component: sBTC. [Learn more about Clarity](https://docs.stacks.co/learn/clarity) 4 #### [hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#sbtc) sBTC sBTC is the trust-minimized 2-way Bitcoin peg on the Stacks layer. sBTC is the key to making Bitcoin programmable and bringing full smart contract functionality to Bitcoin via Stacks. sBTC is not a federation, but operates as an open-network, decentralized 2-way peg solution to bring smart contract functionality to Bitcoin with as little counterparty risk as possible. [Learn more about sBTC](https://docs.stacks.co/learn/sbtc) chevron-right**Stacks and the Purpose of Blockchain Technology**[hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#stacks-and-the-purpose-of-blockchain-technology) When evaluating new blockchain technologies, it's important to keep the original intent and purpose of them intact. If we go back to Bitcoin, it was originally designed to be: * Decentralized * Immutable * Secure You've likely heard of the blockchain trilemma — the problem of trying to balance decentralization, scalability, and security of a blockchain network. Stacks takes the approach of solving this trilemma by separating out chains into layers. So at the bottom, you have the foundational layer: **Bitcoin**. Bitcoin is the most decentralized, most secure, and most immutable blockchain network. However, that comes with a few tradeoffs: * Bitcoin is very slow compared to other networks. Bitcoin only has a new block written once every ~10 minutes, making its throughput negligible compared to networks designed for speed like Solana. * Bitcoin is also "boring". Ethereum came along after Bitcoin and sought to do the same thing for software that Bitcoin did for money. Ethereum's goal is to be a decentralized supercomputer of sorts, serving as a global compute environment for smart contracts (code that is written to a blockchain). * Bitcoin is not scalable. Because every new block must propagate to every node on the network, Bitcoin can only run as fast as the slowest node in the network. Now we are seeing the rise of modular blockchain networks like Cosmos that are designed to make it easy for people to spin up their own blockchain networks. While most new blockchain protocols popping up these days see these properties as negatives and seek to eliminate them, the Stacks community sees things differently. ### [hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#the-stacks-way) The Stacks Way Stacks takes a layered approach: the foundational settlement layer is Bitcoin, and scalability and functionality are added on top of that using layers. There are many different types of L2s and different ways they can be built. They all come with different tradeoffs and have their own way of accomplishing the goals of scalability or functionality. By taking this layered approach, we are able to have all of the same functionality as chains like Ethereum, but built on Bitcoin. So Stacks is a Bitcoin layer 2 with some unique properties, like having its own token, that acts as an incentive mechanism to maintain a historical ledger of all of its transactions and operate with its own security budget (in addition to Bitcoin's security budget — more on this in the next section). This is one of the things that separates Stacks from other Bitcoin layers like Lightning. * Lightning doesn't add any additional functionality to Bitcoin; it simply helps to scale functionality Bitcoin already has and helps it operate faster. Lightning is also ephemeral — it has no permanent state — and so is unsuitable for things like smart contracts that need to keep track of data and maintain state. * Contrast this to Stacks, which adds additional functionality to Bitcoin but still ultimately settles to Bitcoin (we'll cover this in the next section as well). The benefit is that we can maintain a separation of concerns and keep Bitcoin simple and sturdy, chugging along producing blocks, while adding additional layers for functionality and speed. If those other layers were compromised, the foundational layer would remain unaffected. This is important when building systems intended to be a global decentralized money (Bitcoin) and a decentralized economy built on top of that money (Stacks). With that context, let's dive into exactly how Stacks is connected to Bitcoin. * * * ### [hashtag](https://docs.stacks.co/learn/stacks-101/what-is-stacks#additional-resources) Additional Resources * \[[Stacks YTarrow-up-right](https://www.youtube.com/watch?v=BmejRmkLxZU)\ \] Muneeb gives a talk at the Stacks 2.0 Mainnet Launch event on January 14, 2021. [PreviousStacks 101chevron-left](https://docs.stacks.co/learn/stacks-101) [NextThe Bitcoin Connectionchevron-right](https://docs.stacks.co/learn/stacks-101/bitcoin-connection) Last updated 29 days ago Was this helpful? * [Core technical components of Stacks](https://docs.stacks.co/learn/stacks-101/what-is-stacks#core-technical-components-of-stacks) * [The Stacks Way](https://docs.stacks.co/learn/stacks-101/what-is-stacks#the-stacks-way) * [Additional Resources](https://docs.stacks.co/learn/stacks-101/what-is-stacks#additional-resources) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Network Fundamentals | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Mainnet and Testnetschevron-right](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets) [Tokenschevron-right](https://docs.stacks.co/learn/network-fundamentals/network-basics) [Wallets & Accountschevron-right](https://docs.stacks.co/learn/network-fundamentals/wallets-and-accounts) [Bitcoin Name Systemchevron-right](https://docs.stacks.co/learn/network-fundamentals/bitcoin-name-system) [SIPschevron-right](https://docs.stacks.co/learn/network-fundamentals/sips) [Technical Specificationschevron-right](https://docs.stacks.co/learn/network-fundamentals/technical-specifications) [Auditschevron-right](https://docs.stacks.co/learn/network-fundamentals/audits) [PreviousProof of Transfer (PoX)chevron-left](https://docs.stacks.co/learn/stacks-101/proof-of-transfer) [NextMainnet and Testnetschevron-right](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets) Last updated 1 month ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Bitcoin Theses | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![Page cover](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3056062144-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FQp9yDvKWmlMwwZWjUXrn%252Fuploads%252FFndYoAvhUMuKhgEUPo9O%252Ftheses.svg%3Falt%3Dmedia%26token%3D596ff792-8285-4d10-9afc-751996025caf&width=1248&dpr=3&quality=100&sign=b99efa6a&sv=2) Title Outlet / Author Date [TradFi Tomorrow: DeFi and the Rise of Extensible Financearrow-up-right](https://www.paradigm.xyz/2025/03/tradfi-tomorrow-defi-and-the-rise-of-extensible-finance) Paradigm March 2025 💭 [It's time to make your It’s time to make your BTC productive againarrow-up-right](https://medium.com/@aspendigitalAMP/its-time-to-make-your-btc-productive-again-7532ea788a32) Aspen Digital March 2025 💭 [The Bitcoin Renaissance: Unlocking Trillions in Valuearrow-up-right](https://www.forbes.com/sites/leeorshimron/2024/08/13/the-bitcoin-renaissance-unlocking-trillions-in-value/) Leeor Shimron, Forbes August 2024 💭 [My journey with the Blockchain Ecosystem and why do I like Stacks?arrow-up-right](https://www.linkedin.com/pulse/my-journey-blockchain-ecosystem-why-do-i-like-stacks-ali-farid-khwaja-wkybf?ref=stacksblog) Ali Farid Khwaja July 2024 🖋️ [Bitcoin and Future Infracon Highlightsarrow-up-right](https://arkstreamcapital.medium.com/arkstream-capital-bitcoin-and-future-infracon-highlights-b9b3ac4777cd) Arkstream Capital June 2024 📊 [The Build on Bitcoin Era is Herearrow-up-right](https://mythofmoney.substack.com/p/build-on-bitcoin-era-is-here) Myth of Money February 2024 📊 [2024 Bitcoin Halving: This Time It's Differentarrow-up-right](https://www.grayscale.com/research/reports/2024-halving-this-time-its-actually-different) Grayscale February 2024 🌱 [The Year Aheadarrow-up-right](https://panteracapital.com/blockchain-letter/the-year-ahead-2024/) Pantera January 2024 🌱 [State of Bitcoin Q4 2023arrow-up-right](https://messari.io/report/state-of-bitcoin-q4-2023) Messari January 2024 🖋️ [Notable Moments for Bitcoin in 2024arrow-up-right](https://trustmachines.co/blog/notable-moments-for-bitcoin-in-2024/?ref=stacksblog) Trust Machines January 2024 📙 [Bitcoin Layers: Tapestry of a Trustless Financial Eraarrow-up-right](https://bitcoinlayersreport.com/) Spartan Group December 2023 🧪 [A Technical History of Blockchain Design, Innovation, and Narrativesarrow-up-right](https://foundationcapital.com/a-technical-history-of-blockchain-design-innovation-and-narratives-part-i/) Foundation Capital December 2023 📊 [2024 Crypto Market Outlookarrow-up-right](https://www.coinbase.com/nl/institutional/research-insights/research/market-intelligence/2024-crypto-market-outlook) Coinbase December 2023 👀 [STX Thesis Updatearrow-up-right](https://medium.com/@halp1120/stx-thesis-update-cd09b7f2cce8) Hal Press December 2023 [NextBitcoin Reportschevron-right](https://docs.stacks.co/press-and-reports/bitcoin-theses-and-reports/bitcoin-reports) Last updated 5 months ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Mainnet and Testnets | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-b9085514942994a4f51310436d9280ca02b58aca%252Fimage.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=ae28af55&sv=2) Stacks has both a mainnet and a testnet for different purposes. Mainnet and testnet are two completely different public networks and tokens cannot be transferred between one or the other. ### [hashtag](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets#tech-specs-for-mainnet-and-testnet) Tech Specs for Mainnet and Testnet Mainnet Testnet Chain ID `1` `2147483648` Transaction Version `0` `128` Magic Bytes `X2` `T2` Explorer [https://explorer.hiro.so/arrow-up-right](https://explorer.hiro.so/) [https://explorer.hiro.so/?chain=testnetarrow-up-right](https://explorer.hiro.so/?chain=testnet) Stacks API Base URL [https://api.hiro.soarrow-up-right](https://api.hiro.so/) [https://api.testnet.hiro.soarrow-up-right](https://api.hiro.so/) Address Format / Version **SP**3B108...2DNJA0 / `22` **ST**3B108P...EQEZY5 / `26` Multisig Format / Version **SM**3RWH...5X9DXM / `20` **SN**8NKFP...2NAQJA / `21` Genesis Block [Block #1arrow-up-right](https://explorer.hiro.so/block/0x6b2c809627f2fd19991d8eb6ae034cb4cce1e1fc714aa77351506b5af1f8248e?chain=mainnet) [Block #1arrow-up-right](https://explorer.hiro.so/block/0xc9938007fe5f8cc312d782349a6cfbaee7598e08acc4f4da31c876a4b16d4153?chain=testnet) sBTC contract [SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-tokenarrow-up-right](https://explorer.hiro.so/token/SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token?chain=mainnet) [ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-tokenarrow-up-right](https://explorer.hiro.so/txid/ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-token?chain=testnet) ### [hashtag](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets#mainnet) Mainnet Stacks mainnet is directly anchored to the Bitcoin mainnet and its the network where tokens have actual monetary worth. This is the production network and should be treated as such. ### [hashtag](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets#testnet) Testnet The Stacks testnet serves as a live public sandbox for developers, allowing them to build, test, and iterate on apps and smart contracts in an environment that mimics the mainnet. It provides a risk-free space to experiment with changes or new features before deploying them on the Stacks mainnet, ensuring that everything functions correctly without the risk of real financial loss. #### [hashtag](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets#testnet-faucets) Testnet Faucets Testnet faucets provide you with mock Stacks (STX) tokens to test with. These testnet STX have no value and are not the same as STX on mainnet. There are a couple of different options for getting testnet STX. Platform Sandbox LearnWeb3 You can get testnet STX from the [Platformarrow-up-right](https://platform.hiro.so/faucet) , which is the recommended way. To get STX tokens from within the Platform, navigate to the "Faucet" tab at the top. You can then choose either testnet STX or sBTC, and then paste in your desired testnet STX address to receive. ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FjjVK8GVvGbnDTQxzgJ5t%252Fimage.png%3Falt%3Dmedia%26token%3De82a313d-4381-45cc-9a36-ba02a598d9f4&width=768&dpr=3&quality=100&sign=2e526ea2&sv=2) Using the faucet provided by the [Explorer Sandboxarrow-up-right](https://explorer.hiro.so/sandbox/deploy?chain=testnet) is another option. You'll first need to connect your wallet to the Explorer Sandbox and hit 'Request STX'. Be sure your wallet is on the testnet network before requesting. ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FQCTtyAN2r4btyxWOyJs3%252Fsandbox-faucet.png%3Falt%3Dmedia%26token%3Dac55a1c3-fbe8-4424-a513-3074c7befc5d&width=768&dpr=3&quality=100&sign=cf83f7d9&sv=2) Alternatively, you can use the [LearnWeb3 faucetarrow-up-right](https://learnweb3.io/faucets) . ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-6b3929bea804b05efe83f4bb140709378b6024fb%252Fimage.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=87298cb7&sv=2) [PreviousNetwork Fundamentalschevron-left](https://docs.stacks.co/learn/network-fundamentals) [NextTokenschevron-right](https://docs.stacks.co/learn/network-fundamentals/network-basics) Last updated 1 month ago Was this helpful? * [Tech Specs for Mainnet and Testnet](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets#tech-specs-for-mainnet-and-testnet) * [Mainnet](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets#mainnet) * [Testnet](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets#testnet) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close For weekly stories delivered to your inbox, subscribe to [Stacks Snacksarrow-up-right](https://stackssnacks.com/) . For quarterly ecosystem recaps, subscribe to the [Stacks Foundation newsletterarrow-up-right](https://newsletters.stacks.org/) . [PreviousBitcoin Reportschevron-left](https://docs.stacks.co/press-and-reports/bitcoin-theses-and-reports/bitcoin-reports) [NextJanuary 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/january-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Bitcoin Reports | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Title Outlet / Author Date 🧪 [Unlocking Bitcoin \[Presentation\]: The Bitcoin Tipping Pointarrow-up-right](https://syphercapital.substack.com/p/unlocking-bitcoin-presentation-the) Sypher Capital March 2025 📊 [State of Crypto: 2025 Market Outletarrow-up-right](https://www.globalxetfs.com.au/state-of-crypto-2025-market-outlook/) Global X February 2025 🟧 [Stacks Q4 2024 Briefarrow-up-right](https://messari.io/report/stacks-q4-2024-brief) Messari February 2025 📈 [Top 'Made in USA' Coins by MarketCaparrow-up-right](https://x.com/Stacks/status/1881640502149390473?utm_source=stackssnacks.com&utm_medium=newsletter&utm_campaign=stacks-thrives-amid-regulatory-changes-stacking-dao-unveils-sbtc-product&_bhlid=42f17e5c11b1222a7ddd2cf3de42eb1c121496bc) CoinGecko January 2025 📙 [GTM in Asia Report: The Driving Force Behind Crypto Market Growtharrow-up-right](https://www.theblock.co/post/333733/foresight-ventures-and-primitive-ventures-unveil-game-changing-apac-crypto-go-to-market-insights) Primitive Ventures January 2025 📈 [Top 10 Digital Assets Market Predictionsarrow-up-right](https://x.com/AspenDigitalAMP/status/1877289981166731741) Aspen Digital January 2025 📙 [State of Tokenized BTC: A $1 Trillion Opportunity](https://docs.stacks.co/learn/sbtc/sbtc-operations/deposit) Bitcoin Builders Association December 2024 🟧 [Our Thesis on Stacksarrow-up-right](https://candidcontemplation.substack.com/p/our-thesis-on-stx) Portal Ventures December 2024 📊 [Scaling Bitcoinarrow-up-right](https://www.gsr.io/reports/scaling-bitcoin/) GSR November 2024 📊 [Bitcoin L2s: A Modular Futurearrow-up-right](https://www.galaxy.com/insights/research/bitcoin-layer-2-modular-future/) Galaxy Digital November 2024 📊 [Crypto Sectors in Q4 2024arrow-up-right](https://www.grayscale.com/research/market-commentary/grayscale-research-insights-crypto-sectors-in-q4-2024) Grayscale September 2024 📈 [Stacks August 2024 Snapshotarrow-up-right](https://x.com/signal21btc/status/1833117479024963728) Signal21 August 2024 🟧 [Building Block: Stacksarrow-up-right](https://www.grayscale.com/research/reports/building-block-stacks?ref=stacksblog) Grayscale August 2024 📙 [Bitcoin Layer 2 Ecosystemsarrow-up-right](https://unhashed.aarna.ai/p/bitcoin-layer2-ecosystems?ref=stacksblog) Alpha Unhashed June 2024 📙 [Stacks Snapshot June 2024arrow-up-right](https://app.signal21.io/reports/stacks-snapshot-june-2024) Signal21 June 2024 🧪 [The Future of Bitcoin #3: Scaling Bitcoinarrow-up-right](https://www.binance.com/en/research/analysis/the-future-of-bitcoin-3-scaling-bitcoin?ref=stacksblog) Binance Research May 2024 🟧 [Q4 2023: No Denying Demand For Bitcoin L2sarrow-up-right](https://newsletters.stacks.org/p/q4-2023) Stacks Foundation January 2024 📊 [Stacks established developers up 51%arrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL0tlblRoZVJvZ2Vycy9zdGF0dXMvMTc0ODA2MDU5OTcwMjE5MjYyNj9zPTIwJnJlZj1zdGFja3NibG9nJnV0bV9zb3VyY2U9c3RhY2tzc25hY2tzLmNvbSZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1kaXNjb3Zlci1zdGFja3MtaW4tc3BhcnRhbi1ncm91cC1iaXRjb2luLWwyLXJlcG9ydC1lbGVjdHJpYy1jYXBpdGFsLWRldmVsb3Blci1yZXBvcnQiLCJwb3N0X2lkIjoiZTdmYWFkODEtZmI3Ni00MjBmLTk3YWItNGJjMjdmM2RiYjdiIiwicHVibGljYXRpb25faWQiOiIzY2ZhYmZjYy0xNDU5LTQ0NTAtODI3MC1iOGJmM2RkMmFiOTciLCJ2aXNpdF90b2tlbiI6ImQxNDQwNWJiLWMxOWEtNDJiYi05NGQxLTY4MmRiNzZkOWQ3ZSIsImlhdCI6MTcwODA5NzQyMSwiaXNzIjoib3JjaGlkIn0.t0UBYmIXoMyGWCemN_n36kslOn35rIcv2v7LQR3nMLs) Electric Capital January 2024 📙 [Binance Research: Top 10 Narratives to Follow in 2024arrow-up-right](https://public.bnbstatic.com/static/files/research/top-10-narratives.pdf) Binance Research December 2023 📙 [Bitcoin Layers Report: Tapestry of a Trustless Financial Eraarrow-up-right](https://bitcoinlayersreport.com/) Spartan Group December 2023 [PreviousBitcoin Theseschevron-left](https://docs.stacks.co/press-and-reports) [Next2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024) Last updated 5 months ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # March 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close * 🔏 [Bitcoin layer-2 Stacks partners with eight companies ahead of its Nakamoto upgradearrow-up-right](https://cryptobriefing.com/stacks-network-expansion-new-signers/) — Crypto Briefing * 🤝 [Stacks expands with Blockdaemon, Near Foundation amid Bitcoin surgearrow-up-right](https://cointelegraph.com/news/stacks-welcomes-new-signers-blockdaemon-near-foundation-bitcoin-surge) — Cointelegraph * 📈 [More Validation for Bitcoin Builders: Industry Leaders to Integrate Stacks, the Leading Bitcoin L2arrow-up-right](https://www.benzinga.com/pressreleases/24/03/37487866/more-validation-for-bitcoin-builders-industry-leaders-to-integrate-stacks-the-leading-bitcoin-l2) — Benzinga * 💼 [Bitcoin layer-2 Stacks partners with eight companies ahead of its Nakamoto upgradearrow-up-right](https://www.coindesk.com/tech/2024/04/16/og-bitcoin-l2-stacks-is-getting-a-major-overhaul/) — Coindesk * 🔏 [Stacks L2 Bolsters Network Security with 8 New Signersarrow-up-right](https://www.cryptotimes.io/2024/03/06/stacks-l2-bolsters-network-security-with-8-new-signers/) — The Crypto Times * 📈 [Stacks: The Nakamoto Upgradearrow-up-right](https://twitter.com/FTI_DA/status/1771166481880944693?utm_source=stackssnacks.com&utm_medium=referral&utm_campaign=franklin-templeton-highlights-the-nakamoto-release-velar-amm-mainnet) — Franklin Templeton * 🪴 [Stacks reaches 1,000,000 unique walletsarrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL1N0YWNrcy9zdGF0dXMvMTc2NTg2NTQzOTc2OTMwNTU3MT91dG1fc291cmNlPXN0YWNrc3NuYWNrcy5jb20mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249bmFrYW1vdG8tcmVsZWFzZS12b3RpbmctcGVyaW9kLWVuZHMtY2VsZWJyYXRpbmctb25lLW1pbGxpb24tdW5pcXVlLXdhbGxldHMiLCJwb3N0X2lkIjoiYTY0NTBlYTAtY2U4MC00ZjRlLTg0YjMtNjNmNWFhNzRiMTY1IiwicHVibGljYXRpb25faWQiOiIzY2ZhYmZjYy0xNDU5LTQ0NTAtODI3MC1iOGJmM2RkMmFiOTciLCJ2aXNpdF90b2tlbiI6ImRhZTNjOGUxLWVkZTUtNDQxMC1hNWFkLTU3MTc2NmYyMGQ3OSIsImlhdCI6MTcxMzcyNTM5MiwiaXNzIjoib3JjaGlkIn0.allLoCyKRwaGltRK4_zwV80JFbHr6s8SGxr7zPwSZ44) — Signal21 [PreviousFebruary 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/february-2024) [NextApril 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/april-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # July 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Title Outlet / Author 📈 [All Time High in Monthly Active Accounts for Stacksarrow-up-right](https://app.signal21.io/stacks?utm_source=stackssnacks.com&utm_medium=referral&utm_campaign=all-time-high-in-monthly-active-accounts-for-stacks) Signal21 💎 [Bitflow Unveils Liquidity Hub Upgrade, Enabling Functionality Like Ethereum DeFiarrow-up-right](https://blockchainreporter.net/bitflow-unveils-liquidity-hub-upgrade-enabling-functionality-like-ethereum-defi/) Blockchain Reporter 💎 [Bitflow’s Liquidity Hub Elevates Bitcoin DeFi to Ethereum DeFi Ecosystem Standardarrow-up-right](https://coinmarketcap.com/community/articles/667c6188dd97c85264ba1fc1/) CoinMarketCap [Hermetica's Synthetic Dollar Sparks DeFi Revolutionarrow-up-right](https://hackernoon.com/hermeticas-synthetic-dollar-sparks-defi-revolution?ref=stacksblog) Hackernoon 🛡️ [Hypernative Bolsters Bitcoin L2 Security as Stacks Ecosystem Gets Real-Time Protectionarrow-up-right](https://hackernoon.com/hypernative-bolsters-bitcoin-l2-security-as-stacks-ecosystem-gets-real-time-protection) Hackernoon 🎫 [Bitcoin Builders Conference Set to Spotlight Innovation and the Future of the Bitcoin Economyarrow-up-right](https://decrypt.co/239086/bitcoin-builders-conference-set-to-spotlight-innovation-and-the-future-of-the-bitcoin-economy) Decrypt 🪙 [Bitcoin Developers Launch BTC-Backed Stablecoin As Rune Tokenarrow-up-right](https://decrypt.co/239925/bitcoin-developers-launch-btc-backed-stablecoin-as-rune-token) Decrypt 📰 [BitGo integrates Stacks for Bitcoin rewards, following institutional Bitcoin demandarrow-up-right](https://cointelegraph.com/news/bitgo-stacks-bitcoin-rewards-institutional-bitcoin-demand) CoinTelegraph 📰 [BitGo Launches Support for Bitcoin L2 Stacks and sBTCarrow-up-right](https://cryptopotato.com/bitgo-launches-support-for-bitcoin-l2-stacks-and-sbtc/?amp) Crypto Potato 🟧 [Protocol Village: Bitrue Ventures Launches $40M Fund for 'Nascent Web3 Companies'arrow-up-right](https://www.coindesk.com/tech/2024/07/17/protocol-village/) Coindesk [PreviousJune 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/june-2024) [NextAugust 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/august-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # June 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Title Outlet/Author 📊 [Layer-2 Networks Mark The Dawn Of A New Golden Age For Bitcoinarrow-up-right](https://www.analyticsinsight.net/cryptocurrency-analytics-insight/layer-2-networks-mark-the-dawn-of-a-new-golden-age-for-bitcoin?ref=stacksblog) Analytics Insight 📈 [Stacks Layer 2 for Bitcoin already hosts projects, STX token among top gainersarrow-up-right](https://www.cryptopolitan.com/stacks-layer-2-bitcoin-stx-token-top-gainers/?ref=stacksblog) Cryptopolitan 📖 [Top Bitcoin Layer 2 Projects & Coins in 2024arrow-up-right](https://cryptonews.com/cryptocurrency/bitcoin-layer-2-projects/?ref=stacksblog/) Cryptonews 📖 [Layer-2 Networks Mark The Dawn Of A New Golden Age For Bitcoinarrow-up-right](https://www.analyticsinsight.net/cryptocurrency-analytics-insight/layer-2-networks-mark-the-dawn-of-a-new-golden-age-for-bitcoin) Analytics Insight 🧩 [Haruko Integrates Stacks to Deliver Institutional Asset Management on Bitcoin L2arrow-up-right](https://www.financemagnates.com/thought-leadership/haruko-integrates-stacks-to-deliver-institutional-asset-management-on-bitcoin-l2/) Finance Magnates 🧩 [Haruko to enhance digital asset management with Stacks integrationarrow-up-right](https://finbold.com/haruko-to-enhance-digital-asset-management-with-stacks-integration/) Finbold 🧩 [Haruko to Streamline Bitcoin Asset Management With Stacks Integrationarrow-up-right](https://u.today/haruko-to-streamline-bitcoin-asset-management-with-stacks-integration) U Today 💲 [Stacking DAO Bi-Weekly Update: $560k in Stacking rewards over two cyclesarrow-up-right](https://medium.com/@stackingdao/stacking-dao-bi-weekly-update-560k-in-stacking-rewards-over-two-cycles-c012256c1622) Medium 🧩 [Kiln: We're thrilled to unveil our latest integrationarrow-up-right](https://x.com/Kiln_finance/status/1797612820537729354?ref=stacksblog) Kiln [PreviousMay 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/may-2024) [NextJuly 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/july-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # October 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Outlet/Author 🚀 [Stacks fortifies Bitcoin ties with Nakamoto upgradearrow-up-right](https://blockworks.co/news/stacks-sbtc-bitcoin-alignment-nakamoto?ref=stacksblog) Blockworks 🚀 [Stacks, Prominent Bitcoin Layer-2 Project, Activates Long-Awaited 'Nakamoto' Upgradearrow-up-right](https://www.coindesk.com/tech/2024/10/29/stacks-prominent-bitcoin-layer-2-project-activates-long-awaited-nakamoto-upgrade/?ref=stacksblog) Coindesk 🤝 [Asymmetric Research Joins Stacks Ecosystem as Security Contributor to Bitcoin L2arrow-up-right](https://hackernoon.com/asymmetric-research-joins-stacks-ecosystem-as-security-contributor-to-bitcoin-l2) Hackernoon 🟧 [A Beginner's Guide to Bitcoin Layersarrow-up-right](https://www.hiro.so/blog/read-a-beginners-guide-to-bitcoin-layers?ref=stacksblog) Hiro 🌱 [Bitcoin-backed stablecoin developer Hermetica raises $1.7M in seed fundingarrow-up-right](https://www.theblock.co/post/321141/bitcoin-backed-stablecoin-developer-hermetica-raises-1-7-million-in-seed-funding?ref=stacksblog) The Block 🌱 [Blockstream raises $210M to accelerate Bitcoin adoptionarrow-up-right](https://subscribe.bitcoinbuildersassociation.com/p/blockstream-raises-210m-to-accelerate?ref=stacksblog) Bitcoin Builders Association 🟧 [BoostVC, Draper Associates, and Thesis Announce BitcoinFi Acceleratorarrow-up-right](https://subscribe.bitcoinbuildersassociation.com/p/boostvc-draper-associates-and-thesis?ref=stacksblog) Bitcoin Builders Association [PreviousSeptember 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/september-2024) [NextNovember 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/november-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Tokens | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fi9dfCzjxY5JQnXBsDXw4%252Ftokens-network-fundamentals-cover.png%3Falt%3Dmedia%26token%3Df2cf2cd7-128f-4153-844b-57aff84c8179&width=768&dpr=3&quality=100&sign=8a336c7b&sv=2) ### [hashtag](https://docs.stacks.co/learn/network-fundamentals/network-basics#stx) STX Stacks (STX) tokens are the native tokens on the Stacks network. The smallest fraction is one micro-STX: 1,000,000 micro-STX make one Stacks (STX). STX amounts should be stored as integers (8 bytes long), and represent the amount of micro-STX. STX is central to the consensus mechanism of the Stacks Bitcoin layer, discussed below, and is essential for two key goals: (i) it incentivizes mining of Stacks blocks with a “new block subsidy,” which is critical since transaction fees are not enough to sustain a ledger at least in the early days (as is the case with Bitcoin itself), and (ii) it serves as a liveness incentive and the basis for the economically secured decentralized Bitcoin peg. chevron-rightWhy Does Stacks Need a Token?[hashtag](https://docs.stacks.co/learn/network-fundamentals/network-basics#why-does-stacks-need-a-token) This brings us to a central philosophical conversation in the world of crypto and Bitcoin, whether or not blockchains need tokens. Let's start by looking at the fundamental reason why tokens exist: to fund the maintenance and forward progress of a blockchain. Bitcoin is a token. It is a cryptocurrency that is used to incentivize miners to add new blocks to the chain. In Bitcoin's case, mining rewards are set on a predefined schedule, and once those mining rewards run out, the chain will need to survive on transaction fees alone. The purpose of a blockchain is to have a permanent historical record of every transaction that has ever occurred on the chain. Blockchains are basically ledgers. The token aspect is used as an incentive mechanism to secure and maintain the chain. This is why networks like Lightning and other P2P networks don't need tokens, they don't need to maintain a historical record. Channel-based solutions like Lightning rely on users opening 2-of-2 multisigs with each other. Once those channels are closed, the state disappears. When we are talking about a system that is supposed to maintain a global financial system, it is important for the maintenance of that system to be incentivized correctly. Let's look at this concept in the context of Stacks and its goals. Stacks seeks to provide smart contract functionality to Bitcoin, to serve as the programming rails for building a decentralized economy on top of Bitcoin. Many Bitcoin community members are skeptical of new tokens and rightly so. There are countless projects out there that force the use of a token on their project and in many cases a token is actually not needed. The Stacks project was started by Bitcoin builders who have a long history of building apps & protocols on Bitcoin L1 without any token (e.g., BNS launched in 2015 on Bitcoin L1 which was one of the largest protocols using OP\_RETURN on Bitcoin L1). So why did a bunch of Bitcoin builders decide to have a separate token for Stacks L2? Great question! Let's dig into the details. The Stacks token (STX) is primarily meant to be used for two things: 1. **Incentives for Stacks L2 miners**: Newly minted STX are used to incentivize decentralized block production on Stacks L2. 2. **Incentives for peg-out signers**: Signers participating in peg-out operations receive incentives in STX to economically align them with protocol rules. The only way to remove the token is to build Stacks as a federated network like Liquid. In a federation the pre-selected group of companies control the mining and block production and a pre-selected group of companies need to be trusted for peg-out transactions. Stacks developers wanted to design an open and permissionless system. The only way to have a decentralized mining process is through incentives. As mentioned above, this is how Bitcoin works as well, where newly minted BTC are used as incentives to mine new blocks and anyone in the world can decide to become a miner. Anyone with BTC can mine the Stacks L2 chain, it is open and permissionless. Similarly, the way sBTC is designed is that the group of signers is open and permissionless (unlike a federation). These signers have economic incentives to correctly follow the protocol for peg-out requests. In a federation, users need to blindly trust the pre-set federation members to get their BTC out of the federation and back on Bitcoin L1. Stacks developers wanted to have an open, permissionless, and decentralized way to move BTC from Bitcoin L1 to Stacks L2 and back. This is made possible through economic incentives i.e., need for a token. Other than these two reasons, STX is also used to pay gas fees for transactions. However, once the upcoming sBTC peg is live most of the economy of Stacks L2 is expected to follow a Bitcoin standard and work using BTC as the economic unit. It is expected that users will mostly interact just with Bitcoin and use BTC in wallets and apps (gas fees can be paid with BTC using atomic swaps in the background). It is important to note that BTC cannot be used for mining incentives on Stacks L2 because the only way to incentivize decentralized block production is through newly minted assets by the protocol (similar to how Bitcoin works itself) i.e., need for a token. [How to get STX](https://youtu.be/Khfl50J7v6s?si=AkG2x9VIWsrCUoSL) ### [hashtag](https://docs.stacks.co/learn/network-fundamentals/network-basics#sbtc) sBTC sBTC is a decentralized, trust-minimized two-way Bitcoin peg between Bitcoin and the Stacks blockchain. Implemented as a SIP-010 compliant fungible token on Stacks, sBTC enables Bitcoin holders to securely represent their BTC as tokens on the Stacks chain without relying on a single trusted entity. This bridge allows Bitcoin to be seamlessly integrated into the Stacks ecosystem, significantly expanding Bitcoin’s utility through programmable smart contracts while maintaining its fundamental security properties. [Learn more about sBTC](https://docs.stacks.co/learn/sbtc) ### [hashtag](https://docs.stacks.co/learn/network-fundamentals/network-basics#sip-010-fungible-tokens) SIP-010 Fungible Tokens [SIP-010arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) is the standard for defining fungible tokens on Stacks. Defining a common interface (known in Clarity as a "trait") allows different smart contracts, apps, and wallets to interoperate with fungible token contracts in a reusable way. [Create a fungible token](https://docs.stacks.co/get-started/create-a-token/fungible-tokens) ### [hashtag](https://docs.stacks.co/learn/network-fundamentals/network-basics#sip-009-non-fungible-tokens) SIP-009 Non-Fungible Tokens [SIP-009arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) is the standard for defining fungible tokens on Stacks. Defining a common interface (known in Clarity as a "trait") allows different smart contracts, apps, and wallets to interoperate with non-fungible token contracts in a reusable way. Its primary purpose is to ensure that NFTs are composable and different tools know how to interact with them. [Create a non-fungible token](https://docs.stacks.co/get-started/create-a-token/non-fungible-tokens) ### [hashtag](https://docs.stacks.co/learn/network-fundamentals/network-basics#sip-013-semi-fungible-tokens) SIP-013 Semi-Fungible Tokens Semi-fungible tokens (SFTs) are a hybrid token structure that embraces parts of both FTs (fungible tokens) and NFTs. SFTs are interchangeable (like FTs) and can be traded between users like cash—1 SFT has the same value as another SFT in the same collection. But each SFT also has a unique identifier (like NFTs). [SIP-013arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-013/sip-013-semi-fungible-token-standard.md) is the standard for defining semi-fungible tokens on Stacks. Defining a common interface (known in Clarity as a "trait") allows different smart contracts, apps, and wallets to interoperate with semi-fungible token contracts in a reusable, standard way. [Create a semi-fungible token](https://docs.stacks.co/get-started/create-a-token/semi-fungible-tokens) [PreviousMainnet and Testnetschevron-left](https://docs.stacks.co/learn/network-fundamentals/mainnet-and-testnets) [NextWallets & Accountschevron-right](https://docs.stacks.co/learn/network-fundamentals/wallets-and-accounts) Last updated 1 month ago Was this helpful? * [STX](https://docs.stacks.co/learn/network-fundamentals/network-basics#stx) * [sBTC](https://docs.stacks.co/learn/network-fundamentals/network-basics#sbtc) * [SIP-010 Fungible Tokens](https://docs.stacks.co/learn/network-fundamentals/network-basics#sip-010-fungible-tokens) * [SIP-009 Non-Fungible Tokens](https://docs.stacks.co/learn/network-fundamentals/network-basics#sip-009-non-fungible-tokens) * [SIP-013 Semi-Fungible Tokens](https://docs.stacks.co/learn/network-fundamentals/network-basics#sip-013-semi-fungible-tokens) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # May 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Title Outlet/Author [👀 Stacks active accounts reach record high amid growing interest in Bitcoin DeFiarrow-up-right](https://cointelegraph.com/news/bitcoin-defi-surge-stacks-l2-record-users) Cointelegraph [🗞️ Newsletter: BTC’s Streak Is Coming To An Endarrow-up-right](https://milkroad.com/daily/btcs-streak-is-coming-to-an-end-%EF%B8%8F/?ref=stacksblog) Milkroad [📕 The Imperative for Bitcoin Layersarrow-up-right](https://chorus.one/articles/the-imperative-for-bitcoin-layers-2?ref=stacksblog) Chorus One [First Bitcoin-backed synthetic dollar to launch with 25% yieldarrow-up-right](https://cointelegraph.com/news/hermetica-usdh-bitcoin-backed-synthetic-dollar) Cointelegraph [🔗 Stacks, Moonriver, Hedera Network and Iron Fish Join Axelar’s Interchain Amplifierarrow-up-right](https://cryptonews.com/news/stacks-hedera-network-and-iron-fish-join-axelar-interchain.htm) Crypto News [🔗 Axelar Integrates With Stacks To Bridge Bitcoin Across Over 65 Blockchainsarrow-up-right](https://cryptodaily.co.uk/news-in-crypto/coincodex:axelar-integrates-with-stacks-to-bridge-bitcoin-across-over-65-blockchains) Crypto Daily UK 🌱 [LunarCrush Unveils AI-Driven Web3 Platform for Creatorsarrow-up-right](https://www.altcoinbuzz.io/cryptocurrency-news/lunarcrush-unveils-ai-driven-web3-platform-for-creators/) Altcoin Buzz [Despite Bitcoin price volatility, factors point to BTC’s long-term successarrow-up-right](https://cointelegraph.com/news/bitcoin-price-volatility-btc-success) CoinTelegraph [Satoshi’s Vision Or Not, Bitcoin DeFi Is Here To Stayarrow-up-right](https://www.thestreet.com/crypto/markets/satoshis-vision-or-not-bitcoin-defi-is-here-to-stay-) The Street [📣 Stacks Foundation joins Uphold to drive Bitcoin adoptionarrow-up-right](https://www.binance.com/en/square/post/8093584158561) Binance Square [Stacks & Uphold Team Up to Boost Bitcoin Beyond Just a Store of Valuearrow-up-right](https://coinpaper.com/4190/stacks-and-uphold-team-up-to-boost-bitcoin-beyond-just-a-store-of-value) Coinpaper [Stacks and Uphold Partner Up to Boost Bitcoin Adoptionarrow-up-right](https://coinmarketcap.com/community/articles/66437419d7905c7145a4c38e/) CoinMarketCap [Stacks & Uphold Team Up to Boost Bitcoin Beyond Just a Store of Valuearrow-up-right](https://coinstats.app/news/e879f032aa90aad3a51213254a35691ddc897bbfc7200d3d95b95ff87bb4ca0e_Stacks-%26-Uphold-Team-Up-to-Boost-Bitcoin-Beyond-Just-a-Store-of-Value/) CoinStats [Stacks Foundation joins Uphold to drive Bitcoin adoptionarrow-up-right](https://www.coinlive.com/id/news-flash/514530) CoinLive [Stacks Partners With Uphold To Further Increase Bitcoin Adoptionarrow-up-right](https://www.investingcube.com/stacks-partners-with-uphold-to-further-increase-bitcoin-adoption/) InvestingCube [Stacks and Uphold Partner Up to Boost Bitcoin Adoptionarrow-up-right](https://www.cryptotimes.io/2024/05/14/stacks-and-uphold-partner-up-to-boost-bitcoin-adoption/) Crypto Times [PreviousApril 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/april-2024) [NextJune 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/june-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # November 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Outlet / Author 🧡 [CoinFlip, the #1 Global Bitcoin ATM Network Is Making Programmable Bitcoin More Accessible with Stacks, the Leading Bitcoin L2arrow-up-right](https://www.theblock.co/post/327328/coinflip-the-1-global-bitcoin-atm-network-is-making-programmable-bitcoin-more-accessible-with-stacks-the-leading-bitcoin-l2) TheBlock 🧡 [Leading Crowdsourced Security Platform Immunefi Teams Up with Asymmetric Research & Bitcoin L2 Labs to Bolster sBTC Securityarrow-up-right](https://www.theblock.co/post/326835/leading-crowdsourced-security-platform-immunefi-teams-up-with-asymmetric-research-bitcoin-l2-labs-to-bolster-sbtc-security) TheBlock 🧡 [CoinFlip, the #1 Global Bitcoin ATM Network Is Making Programmable Bitcoin More Accessible with Stacks, the Leading Bitcoin L2arrow-up-right](https://coinmarketcap.com/community/articles/673e0069c291c94bd18e68fb/) CoinMarketCap 🧡 [Bitcoin Frontier Fund, Home of the Top Bitcoin Accelerator, To Invest in Teams Built on sBTCarrow-up-right](https://www.theblock.co/post/328240/bitcoin-frontier-fund-home-of-the-top-bitcoin-accelerator-to-invest-in-teams-built-on-sbtc) TheBlock [PreviousOctober 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/october-2024) [NextDecember 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/december-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # September 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Outlet / Author 📈 [New Milestone for Bitcoin DeFi: Over 1,400 Smart Contracts Deployed on Stacksarrow-up-right](https://coinchapter.com/new-milestone-for-bitcoin-defi-over-1400-smart-contracts-deployed-on-stacks-even-before-major-upgrade/) Coin Chapter 📈 [Bitcoin layer-2 Stacks witnessed 1,400 smart contract deployments month over montharrow-up-right](https://www.livebitcoinnews.com/stacks-registers-unseen-smart-contract-deployment-days-away-from-its-nakamoto-upgrade/) Live Bitcoin News 🗞️ [Stacks' smart contracts reach record high ahead of Nakamoto upgradearrow-up-right](https://cointelegraph.com/news/stacks-record-smart-contracts-nakamoto-upgrade?ref=stacksblog) Cointelegraph 🤝🏻 [Anchorage Digital Announces Custody Support for Stacksarrow-up-right](https://x.com/Stacks/status/1831335327300309174?utm_source=stackssnacks.com&utm_medium=referral&utm_campaign=anchorage-digital-supporting-stacks-btc-bash-and-other-highlights) X / Anchorage Digital 🚀 [Hermetica Labs Launches USDh, the first Bitcoin-native synthetic USDarrow-up-right](https://cryptobriefing.com/bitcoin-synthetic-dollar-25-percent-yield/?ref=stacksblog) Crypto Briefing 💡 [What is sBTC? A Guide to the Non-Custodial Native Bitcoin DeFiarrow-up-right](https://www.xverse.app/blog/what-is-sbtc?ref=stacksblog) Xverse ₿ [Over $1.5B worth of BTC is now locked in Bitcoin Layersarrow-up-right](https://subscribe.bitcoinbuildersassociation.com/p/over-15b-worth-of-btc-is-now-locked?ref=stacksblog) Bitcoin Builders Association 🤝 [Stacks x Aptos Foundations Join Forces to Bring Bitcoin to Aptos Network via sBTCarrow-up-right](https://decrypt.co/249825/bitcoin-stacks-l2-brings-its-sbtc-to-the-aptos-network) Decrypt 🖼️ [Gamma's United Bitcoin Ordinals and Stacks Platform Enters Betaarrow-up-right](https://nftinsider.io/gamma-bitcoin-beta/?ref=stacksblog) NFT Insider 🤝 [Tokensoft partners with Stacks Foundation and Bitcoin Frontier Fund to Accelerate Bitcoin Buildersarrow-up-right](https://cryptobriefing.com/bitcoin-builders-acceleration-partnership/?ref=stacksblog) Crypto Briefing 🗞️ [Stacks Asia Foundation Launches with $15M in Funding to Boost Bitcoin Layer-2 Adoptionarrow-up-right](https://coinmarketcap.com/community/articles/66e2998ae0c16b2dea22b4f1/?ref=stacksblog) CoinMarketCap 🚀 [Zest Introduces BTCz, leveraging Babylon and Stacksarrow-up-right](https://subscribe.bitcoinbuildersassociation.com/p/zest-introduces-btcz-leveraging-babylon?ref=stacksblog) Zest [PreviousAugust 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/august-2024) [NextOctober 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/october-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # April 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Title Outlet/Author 👀 [Disruptor To Disruptee: Bitcoin Institutionalization Needs L2 Shakeuparrow-up-right](https://www.forbes.com/sites/nimrodlehavi/2024/04/11/disruptor-to-disruptee-bitcoin-institutionalization-needs-l2-shakeup/?sh=1745f76c629b) Forbes 🟪 [Q&A: What will the Bitcoin halving mean for Bitcoin L2s?arrow-up-right](https://blockworks.co/news/bitcoin-halving-layer-2-impact-stacks) Blockworks [Bitcoin Layer 2 Stacks Prepares for Nakamoto Upgrade, its Largest Hard-Fork Everarrow-up-right](https://thedefiant.io/news/blockchains/bitcoin-layer-2-stacks-prepares-for-nakamoto-upgrade-its-largest-hard-fork-ever) The Defiant 🟧 [Stacks, Bitcoin Layers, and the Nakamoto Upgrade: Here’s What’s Going Onarrow-up-right](https://decrypt.co/225801/stacks-stx-nakamoto-upgrade-bitvm-rollups-defi) Decrypt 📈 [BTCFi is an ‘enormous opportunity’ to make Bitcoin a productive asset — Stacksarrow-up-right](https://cointelegraph.com/news/btcfi-opportunity-make-bitcoin-productive-asset) Cointelegraph ₿ [‘Real opportunity’ for Bitcoin Runes will come after first wave of investor hypearrow-up-right](https://cointelegraph.com/news/real-opportunity-bitcoin-runes-after-first-wave-investor-hype) Cointelegraph 🟧 [OG Bitcoin L2 Stacks Is Getting a Major Overhaularrow-up-right](https://www.coindesk.com/tech/2024/04/16/og-bitcoin-l2-stacks-is-getting-a-major-overhaul/) Coindesk 📻 [Bitcoin L2 with Muneeb Ali of Stacks and Andy Fajar Handika of Loka Miningarrow-up-right](https://www.charlieshrem.com/bitcoin-l2-with-muneeb-ali-of-stacks-and-andy-fajar-handika-of-loka-mining/) Charlie Shrem Show 📧 [April 15th Newsletterarrow-up-right](https://milkroad.com/daily/what-happened-to-prices-this-weekend/?ref=stacksblog) Milroad 🗞️ [TEAMZ Web3/AI Summit2024 Day 1 has ended successfully!arrow-up-right](https://prtimes.jp/main/html/rd/p/000000143.000031083.html?ref=stacksblog) PR Times (Japan) 👀 [The Bitcoin Halving's Degen Betsarrow-up-right](https://www.bankless.com/the-bitcoin-halvings-degen-bets) Bankless 🌱 [Top 5 Pioneering Bitcoin Projects Poised For Growth Post-2024 Halvingarrow-up-right](https://cryptodaily.co.uk/2024/04/top-5-pioneering-bitcoin-projects-poised-for-growth-post-2024-halving) Crypto Daily UK 💰 [Spartan Capital leads $10 million strategic funding round for Bitcoin DeFi developer ALEXarrow-up-right](https://www.theblock.co/post/284556/spartan-capital-leads-10-million-funding-round-for-bitcoin-defi-developer-alex) The Block ₿ [‘Bitcoin has as many functionalities as other blockchains’: Trust Machines member weighs in Bitcoin DeFiarrow-up-right](https://cryptobriefing.com/bitcoin-functionality-other-blockchains/?ref=stacksblog) Crypto Briefing 🗞️ [A Look into The Upcoming Bitcoin Halving & Bitcoin Layer 2sarrow-up-right](https://figment.io/insights/a-look-into-the-upcoming-bitcoin-halving-bitcoin-layer-2s/?ref=stacksblog) Figment 📕 [Bitcoin could gain new smart-contract superpowersarrow-up-right](https://links.coinbase.com/e/evib?_t=3aca56371967418192255878e9689713&_m=fde47e8c40c24182b7cab3a6b10c9d3a&_e=DT1gXnNeiWLsEoKsYDSIAUCWVJr21XSvYbLTlg_uJ63W2CLdvG0Q8MPxsoVG5vCKM9SLV_5n-owzOqH_yPS9iQ%3D%3D&utm_source=stackssnacks.com&utm_medium=referral&utm_campaign=stacks-apps-celebrate-all-time-tvl-high-as-new-defi-protocols-emerge) with the Lightning Network and Stacks. Coinbase Bytes [PreviousMarch 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/march-2024) [NextMay 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/may-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # February 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close _For weekly stories delivered to your inbox, subscribe to_ [Stacks Snacksarrow-up-right](https://stackssnacks.com/) . _For quarterly ecosystem recaps, subscribe to the_ [Stacks Foundation newsletterarrow-up-right](https://newsletters.stacks.org/) . chevron-right📊 [Messari's Q4 2023 'State of Stacks' Reportarrow-up-right](https://messari.io/report/state-of-stacks-q4-2023) [hashtag](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/february-2024#messaris-q4-2023-state-of-stacks-report) [https://messari.io/report/state-of-stacks-q4-2023arrow-up-right](https://messari.io/report/state-of-stacks-q4-2023) **Key Insights** * **Stacks revenue (USD) increased 3,386% QoQ and 3,028% YoY to $637,000.** Much of this revenue was driven by inscription protocol STX20. * **STX’s market cap increased 203% QoQ and 598% YoY to $2.0 billion.** STX’s growth outpaced BTC and the overall crypto market. * **DeFi TVL (USD) increased 363% QoQ and 763% YoY to $61 million.** ALEX firmly remained the leader in TVL, but Arkadiko and StackingDAO considerably increased their own TVL dominance in Q3 and Q4. * **Average daily miner revenue increased 1,015% YoY to $78,000.** STX’s price increase and Stacks’ increased revenue made it significantly more profitable for Bitcoin miners to participate in Stacks’ consensus. * **The Nakamoto upgrade is expected in April 2024.** This update will enable faster blocks, give transactions 100% Bitcoin finality, reduce MEV, and eliminate forking on the Stacks layer to set the stage for the upcoming sBTC release. Title Outlet/Author 🌱 [The Year Aheadarrow-up-right](https://panteracapital.com/blockchain-letter/the-year-ahead-2024/) Pantera Blockchain Letter 📊 [Q1 2024 Bitcoin ecosystem maparrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL3NvcmFfdmVudHVyZXMvc3RhdHVzLzE3NTQ2ODc4ODg3NTgwODM5MjI_dXRtX3NvdXJjZT1zdGFja3NzbmFja3MuY29tJnV0bV9tZWRpdW09cmVmZXJyYWwmdXRtX2NhbXBhaWduPWFsZXgtZ292ZXJuYW5jZS1wcm9wb3NhbC1mb3IteGxuay1zdGFja2luZy1kYW8taGl0cy0zNW0taW4tdHZsIiwicG9zdF9pZCI6IjQ1NTY3YzAzLWFkZDUtNGQzNi1iZGM2LTk4Y2YwYzkyMDA5YyIsInB1YmxpY2F0aW9uX2lkIjoiM2NmYWJmY2MtMTQ1OS00NDUwLTgyNzAtYjhiZjNkZDJhYjk3IiwidmlzaXRfdG9rZW4iOiJkMTQ0MDViYi1jMTlhLTQyYmItOTRkMS02ODJkYjc2ZDlkN2UiLCJpYXQiOjE3MDgwOTcxMjksImlzcyI6Im9yY2hpZCJ9.Ga_H469MIGKuovy5WVHfd3Fit9x6IiqAr0qhNCW575E) Sora Ventures 🪴 [Peak Total Value Locked (TVL) and Rising Developer Engagement on Stacksarrow-up-right](https://twitter.com/HouseofChimera/status/1757792122692911207?ref=stacksblog) House of Chimera 📊 [40% of Bitcoin developers are working on Bitcoin L2sarrow-up-right](https://twitter.com/MohamedFFouda/status/1752407779640295480?s=20&utm_source=stackssnacks.com&utm_medium=referral&utm_campaign=nakamoto-release-launch-date-velar-raises-3-5m-in-funding-round) Mohamed Fouda 📈 [Bitcoin is 25% below its record high -- but Layer 2 Stacks is even closerarrow-up-right](https://blockworks.co/news/layer-2-stacks-approaching-bitcoin?ref=stacksblog) Blockworks 👛 Stacks L2 DeFi protocol [Velar raises $3.5Marrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3d3dy5jb2luZGVzay5jb20vYnVzaW5lc3MvMjAyNC8wMi8wMS9jcnlwdG8tc3RhcnR1cC12ZWxhci1wbGFucy1wZXJwZXR1YWwtc3dhcHMtZXhjaGFuZ2UtZm9yLWJpdGNvaW4tZGVmaS1hZnRlci1yYWlzaW5nLTMtNW0vPXR1dG1fc291cmNlPXN0YWNrc3NuYWNrcy5jb20mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249bmFrYW1vdG8tcmVsZWFzZS1sYXVuY2gtZGF0ZS12ZWxhci1yYWlzZXMtMy01bS1pbi1mdW5kaW5nLXJvdW5kIiwicG9zdF9pZCI6ImYxODVmMmM4LTM0ZTQtNDM0My1hMWFkLTM4YmRlODAyYzY0OCIsInB1YmxpY2F0aW9uX2lkIjoiM2NmYWJmY2MtMTQ1OS00NDUwLTgyNzAtYjhiZjNkZDJhYjk3IiwidmlzaXRfdG9rZW4iOiJkMTQ0MDViYi1jMTlhLTQyYmItOTRkMS02ODJkYjc2ZDlkN2UiLCJpYXQiOjE3MDgwOTcyNDUsImlzcyI6Im9yY2hpZCJ9.FjGMmkbPat9qWNoUR5SJsfnwDWqfUQutXW-ScvveCjc) Coindesk 📊 Report: [Stacks could present a $90 Billion opportunityarrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL1RhbmdDaGFuMHgvc3RhdHVzLzE3NTM0MTcyNDMxMzUwMTMwMTA_dD05N19DMkItaTJqZi11OGgwZEpWV2NBJnM9MzMmdXRtX3NvdXJjZT1zdGFja3NzbmFja3MuY29tJnV0bV9tZWRpdW09cmVmZXJyYWwmdXRtX2NhbXBhaWduPW5ha2Ftb3RvLXJlbGVhc2UtbGF1bmNoLWRhdGUtdmVsYXItcmFpc2VzLTMtNW0taW4tZnVuZGluZy1yb3VuZCIsInBvc3RfaWQiOiJmMTg1ZjJjOC0zNGU0LTQzNDMtYTFhZC0zOGJkZTgwMmM2NDgiLCJwdWJsaWNhdGlvbl9pZCI6IjNjZmFiZmNjLTE0NTktNDQ1MC04MjcwLWI4YmYzZGQyYWI5NyIsInZpc2l0X3Rva2VuIjoiZDE0NDA1YmItYzE5YS00MmJiLTk0ZDEtNjgyZGI3NmQ5ZDdlIiwiaWF0IjoxNzA4MDk3MjQ1LCJpc3MiOiJvcmNoaWQifQ.dons_3VaS_GyWvr5OZs-StFlDP-PX2ToMqIVB9pGVCQ) Tang Chan 📊 [ABCDE 2024 BTC Recaparrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL0FCQ0RFTGFicy9zdGF0dXMvMTc0MDYyNzc3NTg2MDcyNzkxOT90PUo1ODlrWGtMNGlOblFJRXZyRW55TXcmcz0zMyZ1dG1fc291cmNlPXN0YWNrc3NuYWNrcy5jb20mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249bmFrYW1vdG8tcmVsZWFzZS1sYXVuY2gtZGF0ZS12ZWxhci1yYWlzZXMtMy01bS1pbi1mdW5kaW5nLXJvdW5kIiwicG9zdF9pZCI6ImYxODVmMmM4LTM0ZTQtNDM0My1hMWFkLTM4YmRlODAyYzY0OCIsInB1YmxpY2F0aW9uX2lkIjoiM2NmYWJmY2MtMTQ1OS00NDUwLTgyNzAtYjhiZjNkZDJhYjk3IiwidmlzaXRfdG9rZW4iOiJkMTQ0MDViYi1jMTlhLTQyYmItOTRkMS02ODJkYjc2ZDlkN2UiLCJpYXQiOjE3MDgwOTcyNDUsImlzcyI6Im9yY2hpZCJ9.qhu0w9pHUMhY5ASnL74i7ixBbVw7LRrF3MJGJDbcoAs) ABCDE Labs 👀 [2024 Halving: This Time It’s Actually Differentarrow-up-right](https://www.grayscale.com/research/reports/2024-halving-this-time-its-actually-different?ref=stacksblog) Grayscale 📈 [While everyone theorizes about when $BTC will make new highs, $STX...arrow-up-right](https://x.com/cburniske/status/1757951005654978872?t=_cLI0sby6lmp9V1Yj6-6kQ&s=33&ref=stacksblog) Chris Burniske [What Are Bitcoin Layer 2 Networks?arrow-up-right](https://academy.binance.com/en/articles/what-are-bitcoin-layer-2-networks?viastacksblog&ref=stacksblog) Binance Academy [PreviousJanuary 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/january-2024) [NextMarch 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/march-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # August 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Title Outlet/Author 🧩 [Deploy Stacks nodes on AWS with the AWS Blockchain Node Runnersarrow-up-right](https://aws.amazon.com/blogs/database/how-to-deploy-stacks-blockchain-nodes-on-aws-with-the-aws-blockchain-node-runners-stacks-blueprint/?ref=stacksblog) Amazon Web Services 🗞️ [Bitflow and Leather Wallet Join Forces to Simplify Bitcoin L2 Asset Swapsarrow-up-right](https://hackernoon.com/bitflow-and-leather-wallet-join-forces-to-simplify-bitcoin-l2-asset-swaps) Hackernoon 🤝 [Aptos and Stacks Forge New Partnership for Bitcoin Innovationarrow-up-right](https://www.altcoinbuzz.io/cryptocurrency-news/aptos-and-stacks-forge-new-partnership-for-bitcoin-innovation/) Altcoin Buzz 🖊 [Millions of Dollars Worth of BTC Earned by New Institutional Signers Since Nakamoto Instantiationarrow-up-right](https://stacks.org/institutional-signers-earn-millions) Stacks Foundation 💲[Liquidium Raises $2.5M, Accelerating L1 Borrowing and Lendingarrow-up-right](https://subscribe.bitcoinbuildersassociation.com/p/liquidium-raises-25m-accelerating?ref=stacksblog) Bitcoin Builders Association 🧡[Bitcoin Network Stacks Begins Rollout of Speed-Boosting Nakamoto Upgradearrow-up-right](https://decrypt.co/246543/bitcoin-stacks-rollout-speed-boosting-nakamoto-upgrade) Decrypt 📙[Bitcoin Network Stacks Devs 'Can See the Finish Line' With Nakamoto Upgradearrow-up-right](https://decrypt.co/247247/bitcoin-network-stacks-devs-see-finish-line-nakamoto-upgrade) Decrypt 📙[Stacks co-creator on how the Nakamoto upgrade will drive a $70bn market for Bitcoin DeFiarrow-up-right](https://www.dlnews.com/articles/defi/stacks-nakamoto-upgrade-brings-bitcoin-defi-with-sbtc-token/?utm_source=telegram&utm_medium=organic_social&utm_campaign=) DL News 🗞️[Bitcoin Layer-2 Network Stacks Begins Nakamoto Upgradearrow-up-right](https://www.coindesk.com/tech/2024/08/28/bitcoin-layer-2-network-stacks-begins-nakamoto-upgrade/amp/) Coindesk 🗞️[Bitcoin Layer 2 Stacks readies for Nakamoto upgrade activationarrow-up-right](https://crypto.news/bitcoin-layer-2-stacks-readies-for-nakamoto-upgrade-activation/) Crypto News [Stacks (STX) prepares for Nakamoto upgrade: here’s what to expectarrow-up-right](https://coinjournal.net/news/stacks-stx-prepares-for-nakamoto-upgrade-heres-what-to-expect/) 🗞️ Coin Journal 🗞️[Stacks (STX) poised for recovery as game-changer Nakamoto upgrade approachesarrow-up-right](https://invezz.com/news/2024/08/26/stacks-stx-poised-for-recovery-as-game-changer-nakamoto-upgrade-approaches/) Invezz 🗞️[Bitcoin Layer-2 Stacks Set to Receive Its Nakamoto Upgrade, Will Enhance DeFi on Bitcoinarrow-up-right](https://www.livebitcoinnews.com/bitcoin-layer-2-stacks-set-to-receive-its-nakamoto-upgrade-will-enhance-defi-on-bitcoin/) Live Bitcoin News 🗞️[Nakamoto Activation Begins: Leading L2 Stacks Sets the Stage for a Bitcoin-Led Futurearrow-up-right](https://markets.businessinsider.com/news/currencies/nakamoto-activation-begins-leading-l2-stacks-sets-the-stage-for-a-bitcoin-led-future-1033729689) Markets Insider 🧡 [Bitcoin L2s Are Eating the Worldarrow-up-right](https://hackernoon.com/bitcoin-l2s-are-eating-the-world) Hackernoon 💰 [The Bitcoin Renaissance: Unlocking Trillions in Valuearrow-up-right](https://www.forbes.com/sites/leeorshimron/2024/08/13/the-bitcoin-renaissance-unlocking-trillions-in-value/?ref=stacksblog) Forbes [PreviousJuly 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/july-2024) [NextSeptember 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/september-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Proof of Transfer (PoX) | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FEUW1W0NPEuoCYBtienyL%252Fpox.png%3Falt%3Dmedia%26token%3D2edba99c-91f7-4df2-8ea1-aceb9f3bb712&width=768&dpr=3&quality=100&sign=1a571d27&sv=2)![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FqhGYp66lKo0jjZ57rDpy%252Fpox-light.png%3Falt%3Dmedia%26token%3D0d44f0ac-4595-40b4-b554-a510af89fea4&width=768&dpr=3&quality=100&sign=db17af17&sv=2) In the previous sections, we took a look at the vision and ethos of Stacks and talked a lot about it being connected to Bitcoin and how it enables expanding functionality without modifying Bitcoin itself. In this section, we'll run through the block production mechanism that makes that happen, Proof of Transfer. circle-info This section will be a conceptual overview of Proof of Transfer. For more details on exactly how block production happens at a technical level, check out the section on [Block Production](https://docs.stacks.co/learn/block-production) . ### [hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#what-is-proof-of-transfer) What is Proof of Transfer? The Stacks layer relies on STX and on BTC for its novel consensus mechanism, called Proof of Transfer (PoX), that utilizes both the Stacks and Bitcoin layers. PoX is similar in spirit to Bitcoin’s Proof of Work (PoW) consensus: Like how Bitcoin PoW miners spend electricity and are rewarded in BTC, Stacks PoX miners spend (already mined) BTC and are rewarded in STX. Like PoW, PoX uses a single-leader election: PoX miners bid by simply spending BTC, and they have a bid-weighted random probability of becoming a leader. Leader election happens on the Bitcoin chain and new blocks are written on the Stacks layer. In this way, PoX reuses work already done by Bitcoin miners, and does not consume any significant amount of additional electricity: only the cost of running normal laptops/computers for Stacks nodes to bid using BTC. Like PoW, PoX is permissionless: Anyone can be a Stacks miner, as long as they are willing to spend BTC. Also, any STX holder can lock their STX (called “stacking”) to participate in PoX consensus, and earn Bitcoin rewards for doing useful work for the system, i.e., for being a signatory for the decentralized Bitcoin peg. In keeping with Bitcoin ethos, Stackers are rewarded for their positive contributions to the system and inhibited by economic disincentives from behaving poorly (but unlike in bonded Proof of Stake systems, they are not "slashed"). Finally, the nature of PoX consensus is such that the price ratio between BTC and STX is continually recorded and available on-chain, serving as an on-chain Bitcoin price oracle. This is valuable for the decentralized peg, removing the need for an external oracle, as described in the companion paper about the peg. The below diagram flowcharts the PoX consensus mechanism amongst its relevant participants. ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FDdAEe8T2U2HNgOsnAaFb%252FStacks_graphic%2520-%252067.png%3Falt%3Dmedia%26token%3D2a4344b9-c8e8-4ab1-990d-2d2ab61d3932&width=768&dpr=3&quality=100&sign=d10d65f2&sv=2) As depicted in the flowchart, Proof of Transfer also provides two critical dynamics that work together to secure and operate the network. 1. **Economic** – BTC is transferred from miners to stackers, creating a bidirectional incentive structure rooted in Bitcoin itself. Miners commit BTC to participate in block production, effectively competing for the right to produce the next Stacks block. In return, successful miners earn newly minted STX and transaction fees. Stackers, on the other hand, lock their STX to support consensus and receive the BTC committed by miners as a reward. This mechanism ties the Stacks economy directly to Bitcoin, aligning incentives across participants and anchoring security in a real, external asset rather than relying solely on inflation or internal token mechanics. 2. **Programmatic** – Beyond economic incentives, PoX provides the technical coordination layer that determines how blocks are produced, validated, and finalized. Miner BTC commitments on Bitcoin serve as inputs into leader selection, which determines who can construct the next Stacks block. Once produced, blocks are cryptographically linked and anchored to Bitcoin, inheriting its settlement assurances. In this way, PoX is not just an economic exchange mechanism — it is the consensus engine that orchestrates block construction, ordering, and finality while maintaining a verifiable connection to Bitcoin L1. ### [hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#who-are-the-participants-in-proof-of-transfer) Who are the participants in Proof of Transfer? ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fjt1GkSXIb4cL4d1e4SDo%252FStacks_graphic%2520-%252080.png%3Falt%3Dmedia%26token%3D6ba8fe68-ad75-4178-9ebc-51ee2b2f7b7b&width=768&dpr=3&quality=100&sign=247e9ca&sv=2) * * * ### [hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#breakdown-of-poxs-core-components) Breakdown of PoX's Core Components chevron-rightLeader Election (Miners)[hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#leader-election-miners) **Who gets to mine the next tenure of Stacks blocks?** **Participants: Miners** * Idea: Spend BTC to win a chance at producing blocks * Single-leader election through _cryptographic sortition_ * Embed _verifiable random function_ (VRF) state in Bitcoin transactions * Deterministic but unpredictable winner at each Bitcoin block * Mining through block commits: (block hash, VRF seed) pair * VRF seed = hash(VRF proof) chevron-rightReward Set (Stackers)[hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#reward-set-stackers) **But where does the BTC spent by miners go?** **Participants: Stackers that are either solo stacking or pool stacking** * Idea: Spent BTC (from miners) are sent to STX holders * Expected BTC payout is a function of your-lockup over total-lockup * Locked STX never leave your account, and will unlock automatically * Takes unproductive STX our of circulation * Reward Cycle: 2100 Bitcoin blocks * Reward Phase: first 2000 Bitcoin blocks * Prepare Phase: last 100 Bitcoin blocks * Anchor block: first Stacks block confirmed in prepare phase * Reward Set: snapshot of locked STX in anchor block ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FDgyyRS5GoHb0mngC9e8t%252Fimage.png%3Falt%3Dmedia%26token%3D14ee55c5-b165-4207-b1a4-5fde4c74cc57&width=768&dpr=3&quality=100&sign=d2bb9f66&sv=2) ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fvi7Wwp15343yA7F3zySH%252Fimage.png%3Falt%3Dmedia%26token%3D654594ac-4812-48fc-ab3b-524c5b4be519&width=768&dpr=3&quality=100&sign=85cf2e5e&sv=2) chevron-rightBlock Signers (Signers)[hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#block-signers-signers) **Can locked STX secure the network as well?** **Participants: Stackers that are taking on the role of a Signer** * Idea: Use PoX yield to incentivize good chain QoS * PoX yield as a salary to replicate and sequence blocks * Stacks select Signer public key when they stack * Signers sign blocks from miner with weighted signature (by # reward slots) * Once 70%+ of reward slots sign off, block is appended * Block signer set changes once per reward cycle * 70%+ or more signers assumed to be online and honest * Honest Signers vote to withhold (burn) faulty Stackers' subsequent BTC ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FVUFPxnqlCxwtVL1i37fx%252Fimage.png%3Falt%3Dmedia%26token%3Df31b7c0d-4be9-4b83-802c-d1f78be88da8&width=768&dpr=3&quality=100&sign=1bb75ff8&sv=2) * * * ### [hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#technical-implementation-details) Technical Implementation Details The Proof of Transfer functionality is implemented on the Stacks network as a Clarity smart contract. Proof of Transfer has went through multiple iterations over the years. Below lists the different smart contract implementations of Proof of Transfer. Version Date Mainnet Contract SIP PoX 4 2024-04-22 [SP000000000000000000002Q6VF78.pox-4arrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-4) [https://github.com/stacksgov/sips/blob/main/sips/sip-021/sip-021-nakamoto.md](https://github.com/stacksgov/sips/blob/main/sips/sip-021/sip-021-nakamoto.md) PoX 3 2023-05-27 [SP000000000000000000002Q6VF78.pox-3arrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-3) [https://github.com/stacksgov/sips/blob/main/sips/sip-022/sip-022-emergency-pox-fix.md](https://github.com/stacksgov/sips/blob/main/sips/sip-022/sip-022-emergency-pox-fix.md) PoX 2 2023-03-20 [SP000000000000000000002Q6VF78.pox-2arrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-2) [https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) PoX 1 2021-01-15 [SP000000000000000000002Q6VF78.poxarrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox) [https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) A walkthrough of the current PoX 4 contract is available in the [Example Contracts](https://docs.stacks.co/cookbook/clarity/example-contracts) section. * * * ### [hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#wrapping-it-up-pox-in-a-nutshell) Wrapping it up: PoX in a nutshell • PoX selects a randomized single-leader block miner once per BTC block • PoX incentivizes miners to make STX blocks and earn STX coinbase + tx fees • PoX incentivizes STX holders to lock up STX to get BTC yield from miners • PoX disincentivizes BTC L1 miners from interfering • PoX incentivizes Stackers, as a Signer, to keep the network healthy * * * ### [hashtag](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#additional-resources) Additional Resources * \[[SIP-001arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md)\ \] SIP-001 provides a full list of reasons why Bitcoin was chosen to secure Stacks. * \[[SIP-007arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md)\ \] Details of the original design for stacking and Proof of Transfer. * \[[SIP-021arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-021/sip-021-nakamoto.md)\ \] Nakamoto Upgrade: Fast and reliable blocks * \[[Stacks Developers YTarrow-up-right](https://youtu.be/YynwIJIXJWw?si=9DXsd9PzMN14xt-L)\ \] PoX: Under the Hood * \[[Stacks Developers YTarrow-up-right](https://youtu.be/4UJ3ZK8JsrI?si=m8VSVIuCwIyOe3pe)\ \] How Do Developers Test the Stacks Network? * \[[Hiro YTarrow-up-right](https://youtu.be/2Bmo1cK0C8k?si=uiYaXudIhjxkNaS6)\ \] A Breakdown of Stacks' Proof of Transfer Smart Contract [PreviousThe Bitcoin Connectionchevron-left](https://docs.stacks.co/learn/stacks-101/bitcoin-connection) [NextNetwork Fundamentalschevron-right](https://docs.stacks.co/learn/network-fundamentals) Last updated 1 month ago Was this helpful? * [What is Proof of Transfer?](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#what-is-proof-of-transfer) * [Who are the participants in Proof of Transfer?](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#who-are-the-participants-in-proof-of-transfer) * [Breakdown of PoX's Core Components](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#breakdown-of-poxs-core-components) * [Technical Implementation Details](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#technical-implementation-details) * [Wrapping it up: PoX in a nutshell](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#wrapping-it-up-pox-in-a-nutshell) * [Additional Resources](https://docs.stacks.co/learn/stacks-101/proof-of-transfer#additional-resources) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # January 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close For weekly stories delivered to your inbox, subscribe to [Stacks Snacksarrow-up-right](https://stackssnacks.com/) . For quarterly ecosystem recaps, subscribe to the [Stacks Foundation newsletterarrow-up-right](https://newsletters.stacks.org/) . chevron-right**📙 Bitcoin Layers Report by Spartan Group**[hashtag](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/january-2024#bitcoin-layers-report-by-spartan-group) **Tapestry of a Trustless Financial Era** Diving deep into the layers of Bitcoin's blossoming ecosystem, the first edition of the Bitcoin Layers Report unveils the emerging reality of a financial world where trust is embedded in technology rather than institutions. As Bitcoin evolves beyond a Store of Value, we stand on the cusp of a revolution in trustless finance and a new era of economic possibilities. [https://bitcoinlayersreport.com/arrow-up-right](https://bitcoinlayersreport.com/) Title Outlet/Author 🌱 [The Year Ahead | Pantera Blockchain Letterarrow-up-right](https://panteracapital.com/blockchain-letter/the-year-ahead-2024/) Pantera 🟧 [Q4 2023: No Denying Demand For Bitcoin L2sarrow-up-right](https://newsletters.stacks.org/p/q4-2023) Stacks Foundation 📙 [Binance Research: Top 10 Narratives to Follow in 2024arrow-up-right](https://public.bnbstatic.com/static/files/research/top-10-narratives.pdf) Binance Research 📕 [The Bankless Guide to Stacksarrow-up-right](https://www.bankless.com/the-bankless-guide-to-stacks) Bankless 📊 Electric Capital Report: [Stacks established developers up 51%arrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL0tlblRoZVJvZ2Vycy9zdGF0dXMvMTc0ODA2MDU5OTcwMjE5MjYyNj9zPTIwJnJlZj1zdGFja3NibG9nJnV0bV9zb3VyY2U9c3RhY2tzc25hY2tzLmNvbSZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1kaXNjb3Zlci1zdGFja3MtaW4tc3BhcnRhbi1ncm91cC1iaXRjb2luLWwyLXJlcG9ydC1lbGVjdHJpYy1jYXBpdGFsLWRldmVsb3Blci1yZXBvcnQiLCJwb3N0X2lkIjoiZTdmYWFkODEtZmI3Ni00MjBmLTk3YWItNGJjMjdmM2RiYjdiIiwicHVibGljYXRpb25faWQiOiIzY2ZhYmZjYy0xNDU5LTQ0NTAtODI3MC1iOGJmM2RkMmFiOTciLCJ2aXNpdF90b2tlbiI6ImQxNDQwNWJiLWMxOWEtNDJiYi05NGQxLTY4MmRiNzZkOWQ3ZSIsImlhdCI6MTcwODA5NzQyMSwiaXNzIjoib3JjaGlkIn0.t0UBYmIXoMyGWCemN_n36kslOn35rIcv2v7LQR3nMLs) Electric Capital 📰 [Bitcoin Could See Growth in Layer-2 Ecosystem, Drawing on Ethereum's Experiencearrow-up-right](https://www.coindesk.com/tech/2024/01/18/bitcoin-could-see-growth-in-layer-2-ecosystem-drawing-on-ethereums-experience/) Coindesk, Yahoo Finance 🔮 [Paul Veradittakit of Pantera Capital Lists Stacks In 6 Predictions Crypto 2024arrow-up-right](https://www.coindesk.com/consensus-magazine/2023/12/20/6-predictions-for-crypto-in-2024-panteras-paul-veradittakit) Coindesk 🏛️ [Franklin Templeton: Ordinals & Layer 2 solutions on Bitcoin shouldn’t be ignoredarrow-up-right](https://x.com/fti_us/status/1747708193378025475?s=46) Franklin Templeton 🔉 [Podcast: Muneeb Ali joins us in The Blueprintarrow-up-right](https://twitter.com/TheSpartanGroup/status/1747546980321304629) The Blueprint 🎨 [Jack Butcher: Onboarding to Bitcoinarrow-up-right](https://x.com/jackbutcher/status/1745557822203470022?t=ps-Sn2Ohh0TWBR4ptywL-Q&s=33) Jack Butcher 👀 [2024 Bitcoin Outlook: Ecosystem Beyond ETFsarrow-up-right](https://4pillars.io/en/articles/2024-Bitcoin-Outlook-Ecosystem-Beyond-ETFs/public) Four Pillars Ⓜ️ [This Bitcoin ecosystem is having its momentarrow-up-right](https://x.com/cosmo_jiang/status/1752870233231212747?s=20) Cosmo Jiang, Pantera Capital 🧪 [MT Capital Research Report: Stacks Nakamoto is about to be upgraded to inject new impetus into the Bitcoin ecosystemarrow-up-right](https://www.gate.io/learn/articles/stacks-nakamoto-is-about-to-be-upgraded-to-inject-new-impetus-into-the-bitcoin-ecosystem/1211) MT Capital via Gate.io 📊 [House of Chimera Analyzes Rapid Growth in Stacks Transactionsarrow-up-right](https://twitter.com/HouseofChimera/status/1745452755681218792) House of Chimera 👛 [Ryder to operate FAST Pool, become signer in Stacks’ Nakamoto upgradearrow-up-right](https://crypto.news/ryder-to-operate-fast-pool-become-signer-in-stacks-nakamoto-upgrade/) Crypto.news 🔶 [Bitcoin 2024 Outlookarrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3d3dy5va3guY29tL25sL2xlYXJuL3ZlbnR1cmVzLTIwMjQtYml0Y29pbi1vdXRsb29rP3V0bV9zb3VyY2U9c3RhY2tzc25hY2tzLmNvbSZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1iaXRjb2luLWwyLWRleC1yYWlzZXMtMS0zbS1pbi1wcmUtc2VlZC1mdW5kaW5nLXRoZS1sYXVuY2gtb2YtbjIxIiwicG9zdF9pZCI6IjU5MjAwM2Q5LTI0YjktNGMxOS1hNDc0LWYwNDRkYzlhMWUxNCIsInB1YmxpY2F0aW9uX2lkIjoiM2NmYWJmY2MtMTQ1OS00NDUwLTgyNzAtYjhiZjNkZDJhYjk3IiwidmlzaXRfdG9rZW4iOiJkMTQ0MDViYi1jMTlhLTQyYmItOTRkMS02ODJkYjc2ZDlkN2UiLCJpYXQiOjE3MDgwOTczNDAsImlzcyI6Im9yY2hpZCJ9.ZpuDlatRCYz537iRKwlGojFXDCZWCxl1NAGfCYZ_S7Y) (featuring Stacks and ALEX) OKX 💰 Bitcoin DEX Bitflow raises [$1.3M in pre-seed fundingarrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL0JpdGZsb3dfRmluYW5jZS9zdGF0dXMvMTc1MDQ5NDc0MDc0NTc5MzkxMD91dG1fc291cmNlPXN0YWNrc3NuYWNrcy5jb20mdXRtX21lZGl1bT1yZWZlcnJhbCZ1dG1fY2FtcGFpZ249Yml0Y29pbi1sMi1kZXgtcmFpc2VzLTEtM20taW4tcHJlLXNlZWQtZnVuZGluZy10aGUtbGF1bmNoLW9mLW4yMSIsInBvc3RfaWQiOiI1OTIwMDNkOS0yNGI5LTRjMTktYTQ3NC1mMDQ0ZGM5YTFlMTQiLCJwdWJsaWNhdGlvbl9pZCI6IjNjZmFiZmNjLTE0NTktNDQ1MC04MjcwLWI4YmYzZGQyYWI5NyIsInZpc2l0X3Rva2VuIjoiZDE0NDA1YmItYzE5YS00MmJiLTk0ZDEtNjgyZGI3NmQ5ZDdlIiwiaWF0IjoxNzA4MDk3MzQwLCJpc3MiOiJvcmNoaWQifQ.gAwmYWnQwFlQhmA3A__Mu0CGlhS7riNoZbzOefU-c2U) Bitflow 😈 DeFi Researcher Ignas: [“Degen Playbook for Stacks”arrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL2RlZmlpZ25hcy9zdGF0dXMvMTc0NDY5MDQyNzczNzgyMTQxMT9zPTQ2JnV0bV9zb3VyY2U9c3RhY2tzc25hY2tzLmNvbSZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1wb3RlbnRpYWwtc2NhbGluZy1zb2x1dGlvbi1mb3Itb3JkaW5hbHMtb24tbDItc3RhY2tzLWV0Zi1hcHByb3ZhbCIsInBvc3RfaWQiOiJkMmIzNjMxMi1jMTNhLTQyNDctODRiZS1mNzIzOTMxOTIyMzQiLCJwdWJsaWNhdGlvbl9pZCI6IjNjZmFiZmNjLTE0NTktNDQ1MC04MjcwLWI4YmYzZGQyYWI5NyIsInZpc2l0X3Rva2VuIjoiZDE0NDA1YmItYzE5YS00MmJiLTk0ZDEtNjgyZGI3NmQ5ZDdlIiwiaWF0IjoxNzA4MDk3NTM2LCJpc3MiOiJvcmNoaWQifQ.wYm07ZsU_dzCGsvPc2IuHoYLwRXFXQtRnQkJcIAr1KM) [Ignasarrow-up-right](https://twitter.com/DefiIgnas) via [TLDRarrow-up-right](https://tldr.tech/crypto/2024-01-10) 📺 [Why DeFi on Stacks is the Next Bitcoin Bullarrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL3R3aXR0ZXIuY29tL2hlcm9nYW1lcjIxYnRjL3N0YXR1cy8xNzQyOTY0MDgzNjQzNTY0MTczP3V0bV9zb3VyY2U9c3RhY2tzc25hY2tzLmNvbSZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1zdGFja3MtYXBwcy1jZWxlYnJhdGUtYWxsLXRpbWUtdHZsLWhpZ2gtYXMtbmV3LWRlZmktcHJvdG9jb2xzLWVtZXJnZSIsInBvc3RfaWQiOiJmYTkyOTQ4YS0xNDU2LTRlOTktYjBmOS1hNWYyMTczY2I4YjQiLCJwdWJsaWNhdGlvbl9pZCI6IjNjZmFiZmNjLTE0NTktNDQ1MC04MjcwLWI4YmYzZGQyYWI5NyIsInZpc2l0X3Rva2VuIjoiZDE0NDA1YmItYzE5YS00MmJiLTk0ZDEtNjgyZGI3NmQ5ZDdlIiwiaWF0IjoxNzA4MDk3NjA3LCJpc3MiOiJvcmNoaWQifQ.hHQdRz61DrxCRXTRuv7vGEyvuh2gTFl2Mc4u2EG6ks4) Block Runner 📊 [All time high Total Value Locked (TVL) for Bitcoin L2 Stacksarrow-up-right](https://flight.beehiiv.net/v2/clicks/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1cmwiOiJodHRwczovL2RlZmlsbGFtYS5jb20vY2hhaW4vU3RhY2tzP3V0bV9zb3VyY2U9c3RhY2tzc25hY2tzLmNvbSZ1dG1fbWVkaXVtPXJlZmVycmFsJnV0bV9jYW1wYWlnbj1zdGFja3MtYXBwcy1jZWxlYnJhdGUtYWxsLXRpbWUtdHZsLWhpZ2gtYXMtbmV3LWRlZmktcHJvdG9jb2xzLWVtZXJnZSIsInBvc3RfaWQiOiJmYTkyOTQ4YS0xNDU2LTRlOTktYjBmOS1hNWYyMTczY2I4YjQiLCJwdWJsaWNhdGlvbl9pZCI6IjNjZmFiZmNjLTE0NTktNDQ1MC04MjcwLWI4YmYzZGQyYWI5NyIsInZpc2l0X3Rva2VuIjoiZDE0NDA1YmItYzE5YS00MmJiLTk0ZDEtNjgyZGI3NmQ5ZDdlIiwiaWF0IjoxNzA4MDk3NjA3LCJpc3MiOiJvcmNoaWQifQ.f6dic2OuZV_EPpARzcBBfeH11hoE8SL9xXyXAgXprac) DefiLlama 📊 [sOrdinals: 100k Inscriptions in less than 24 hoursarrow-up-right](https://twitter.com/StxOrds/status/1745882592430215626) sOrdinals 📊 [STX20 Protocol Surpasses 1M Transactions in 1 Montharrow-up-right](https://twitter.com/stx20stacks/status/1747684225074053606) STX20 📊 [StackingDAO celebrates $20M in TVL one month inarrow-up-right](https://twitter.com/StackingDao/status/1751684775797002269) StackingDAO 📙 [Bitcoin Layers Report: Tapestry of a Trustless Financial Eraarrow-up-right](https://bitcoinlayersreport.com/) Spartan Group [Previous2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024) [NextFebruary 2024chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/february-2024) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # August 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Title & Link Outlet [BTCFi #2: Inside the Infrastructure Layer of BTCFiarrow-up-right](https://x.com/Tiger_Research_/status/1957703731308556340?ref=stacksblog) Tiger Research [PreviousJuly 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/july-2025) [NextSeptember 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/september-2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close For weekly stories delivered to your inbox, subscribe to [Stacks Snacksarrow-up-right](https://stackssnacks.com/) . For quarterly ecosystem recaps, subscribe to the [Stacks Foundation newsletterarrow-up-right](https://newsletters.stacks.org/) . Issue january-2024.md Target Issue february-2025.md Target Issue march-2025.md Target Issue march-2025-1.md Target Issue march-2025-2.md Target Issue june-2025.md Target Issue june-2025-1.md Target Issue june-2025-2.md Target Issue june-2025-2-1.md Target [PreviousDecember 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/december-2024) [NextJanuary 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/january-2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # April 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Title & Link Media Outlet [🧡 Experts: Gold’s Rise Doesn’t Undermine Bitcoin’s Digital Gold Statusarrow-up-right](https://news.bitcoin.com/experts-golds-rise-doesnt-undermine-bitcoins-digital-gold-status/) Bitcoin.com [🗞️ Veteran crypto exchange Bitfinex bets big on Bitcoin-based DeFi, deepens integration with Stacksarrow-up-right](https://u.today/bitfinex-lists-stx-token-by-stacks-becomes-network-signer) U Today [🟧 Bitfinex Throws Its Full Weight Behind Bitcoin’s Leading Layer-2 Stacksarrow-up-right](https://www.coincarp.com/learn/bitfinex-throws-its-full-weight-behind-bitcoins-leading-layer-2-stacks/) Coincarp [🚀 Hex Trust Expands Institutional Support for Stacks (STX) and sBTC Amid Growing Adoptionarrow-up-right](https://www.dlnews.com/research/external/hex-trust-expands-institutional-support-for-stacks-stx-and-sbtc-amid-growing-adoption/) DL News [🟧 Hermetica brings 5% yield to Bitcoin traders on Velar PerpDEXarrow-up-right](https://crypto.news/hermetica-brings-5-yield-to-bitcoin-traders-on-velar-perpdex/) Crypto.News [🗞️ BitGo Launches Institutional Support for SBTC, Expanding Bitcoin DeFi Accessibility (22 Apr)arrow-up-right](https://www.binance.com/en/square/post/23264351434353) Binance [🪙 Stacks' STX Is Week's Best Performer as Bitgo Link Seen Boosting Institutional Usearrow-up-right](https://www.coindesk.com/markets/2025/04/25/stacks-stx-is-week-s-best-performer-as-bitgo-link-seen-boosting-institutional-use) Coindesk [🚀 Stacks Asia bets big on Middle East Bitcoin boom with Abu Dhabi partnershiparrow-up-right](https://cointelegraph.com/news/stacks-asia-adgm-partnership-boosts-bitcoin-adoption-middle-east) Cointelegraph [PreviousMarch 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/march-2025) [NextMay 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/may-2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # May 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Title & Link Media Outlet 🚀 [Stacks roadmap update and STX surgearrow-up-right](https://blockchain.news/flashnews/stacks-announces-new-roadmap-after-nakamoto-and-sbtc-launch-key-updates-for-crypto-traders-in-2025) Blockchain News 🤝 [Stacks Asia partners with HEX Trustarrow-up-right](https://cointelegraph.com/news/stacks-asia-hex-trust-bitcoin-defi-opportunity) Cointelegraph 📈 [STX rallies 30% ahead of mainnet upgradearrow-up-right](https://cointelegraph.com/news/stacks-stx-makes-30-gain-as-mainnet-upgrade-and-stablecoin-launch-approach) Cointelegraph 💡 [Tech Expert Predicts $1 Million Bitcoin — 'Only One More 10x Left'arrow-up-right](https://www.binance.com/en-IN/square/post/24043258936257) Binance [PreviousApril 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/april-2025) [NextJune 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/june-2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # September 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Title & Link Outlet [LAB: Africa’s First Bitcoin Layer 2 Development Hub & Incubatorarrow-up-right](https://stacks.org/let-africa-build?ref=stacksblog) Stacks Foundation Blog [Unlocking Bitcoin's value - Will the BTCFi narrative push Stacks to $20?arrow-up-right](https://eng.ambcrypto.com/unlocking-bitcoins-value-will-the-btcfi-narrative-push-stacks-stx-to-20/) AMB Crypto [PreviousAugust 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/august-2025) [NextOctober 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/september-2025-1) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # February 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Publication / Link 🧡 Bitcoin's Correlation With Markets Grows, Challenging 'Safe Haven' Narrative [Bitcoin.comarrow-up-right](http://bitcoin.com/) 🪙 How sBTC Unlocks Bitcoin DeFi – And Why It Matters [Coincu.comarrow-up-right](http://coincu.com/) 🟧 sBTC Is Fast Emerging As The Missing Link In Bitcoin’s Cross-Chain Evolution [Bitcoinistarrow-up-right](https://bitcoinist.com/sbtc-is-fast-emerging-as-the-missing-link-in-bitcoins-cross-chain-evolution/) 🧡 The Overlooked Bitcoin Layer-2 Sector: Why and What to Expect Moving Forward [Binancearrow-up-right](https://www.binance.com/en-IN/square/post/20381520919281) 🟧 Bitcoin L2 ‘honeymoon phase’ is over, most projects will fail — Muneeb Ali [CoinTelegrapharrow-up-right](https://cointelegraph.com/news/bitcoin-layer2-projects-fade-stacks-muneeb-ali) 🗞️ Blockchair Launches Stacks Explorer, Enhancing Bitcoin Layer 2 Visibility and sBTC Support [DL Newsarrow-up-right](https://www.dlnews.com/research/external/blockchair-launches-stacks-explorer-enhancing-bitcoin-layer-2-visibility-and-sbtc-support/) 🗞️ Blockchair Launches Stacks Explorer, Enhancing Bitcoin Layer 2 Visibility and sBTC Support [CoinMarketCaparrow-up-right](https://coinmarketcap.com/community/articles/67bf2560ae03156d954313b6/) 🟧 SNZ, UTXO Capital, Jump Crypto Among Leaders to Deposit Early in sBTC, Unlocking Bitcoin DeFi Utility [Decryptarrow-up-right](https://decrypt.co/307910/snz-utxo-capital-jump-crypto-among-leaders-to-deposit-early-in-sbtc-unlocking-bitcoin-defi-utility) 🚀 Stacks’ sBTC Sees Rapid Adoption as Second Cap Hits 3,000 BTC Limit [Bitcoinistarrow-up-right](https://bitcoinist.com/stacks-sbtc-sees-rapid-adoption-as-second-cap-hits-3000-btc-limit/) 🚀 SNZ, UTXO Capital, Jump Crypto Among Leaders to Deposit Early in sBTC, Unlocking Bitcoin DeFi Utility [DL Newsarrow-up-right](https://www.dlnews.com/research/external/snz-utxo-capital-jump-crypto-among-leaders-to-deposit-early-in-sbtc-unlocking-bitcoin-defi-utility/) [PreviousJanuary 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/january-2025) [NextMarch 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/march-2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # June 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Title & Link Outlet 📰 [Stacks to be Showcased at Blockchain and Digital Assets Virtual Investor Conference on June 5arrow-up-right](https://www.globenewswire.com/news-release/2025/06/04/3093569/0/en/Stacks-to-be-Showcased-at-Blockchain-and-Digital-Assets-Virtual-Investor-Conference-on-June-5th.html) Globe Newswire 🤝 [Copper Launches Support for sBTCarrow-up-right](https://www.crowdfundinsider.com/2025/06/241658-digital-assets-copper-introduces-sbtc-stacking-functionality/) Crowdfund Insider 🧩 [Hex Trust Adds sBTC Support and SIP-010 Integrationarrow-up-right](https://bitcolumnist.com/release/hex-trust-integrates-sbtc-via-sip-010-to-enable-institutional-bitcoin-defi-access/) BitColumnist [PreviousMay 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/may-2025) [NextJuly 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/july-2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # January 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close For weekly stories delivered to your inbox, subscribe to [Stacks Snacksarrow-up-right](https://stackssnacks.com/) . For quarterly ecosystem recaps, subscribe to the [Stacks Foundation newsletterarrow-up-right](https://newsletters.stacks.org/) . Article Outlet/Publication [🧡 Stacks’ Muneeb Ali: Let the Bitcoin L2s Bloomarrow-up-right](https://www.coindesk.com/consensus-hong-kong-2025-coverage/2025/01/13/stacks-muneeb-ali-let-the-bitcoin-l2s-bloom) Coindesk [🚀 Why Stacks Is Leading the Bitcoin Layer 2 Revolutionarrow-up-right](https://www.crypto-news-flash.com/why-stacks-is-leading-the-bitcoin-layer-2-revolution/) Crypto News Flash [🗞️ Bitcoin-Based Stablecoin USDh Secures $3M in Liquidityarrow-up-right](https://www.coindesk.com/tech/2025/01/22/bitcoin-based-stablecoin-usdh-secures-usd3m-in-liquidity) Coindesk [🗞️ Hermetica's Bold Move to Dominate Stacks DeFi With its USDh Stablecoin and sBTC Yield Trade Programarrow-up-right](https://hackernoon.com/hermeticas-bold-move-to-dominate-stacks-defi-with-its-usdh-stablecoin-and-sbtc-yield-trade-program) Hackernoon [🪙 Hermetica Launches New sBTC Yield Product, USDh Liquidity Faces Boostarrow-up-right](https://u.today/hermetica-launches-new-sbtc-yield-product-usdh-liquidity-faces-boost) U Today [🪙 Hermetica Unveils $sBTC for Yield-Bearing $USDh in Partnership with Zest Protocolarrow-up-right](https://blockchainreporter.net/hermetica-unveils-sbtc-for-yield-bearing-usdh-in-partnership-with-zest-protocol/) Blockchain Reporter [🪙 USDh set to become the leading stablecoin on Stacks as Hermetica introduces sBTC yield productarrow-up-right](https://invezz.com/news/2025/01/23/usdh-set-to-become-the-leading-stablecoin-on-stacks-as-hermetica-introduces-sbtc-yield-product/) Invezz [🧡 Making Bitcoin Go Further: How sBTC Is Expanding the Possibilities of DeFiarrow-up-right](https://bitcoinist.com/making-bitcoin-go-further-how-sbtc-is-expanding-the-possibilities-of-defi/) Bitcoinist [🚀 Bitcoin DeFi: The Most Pivotal Innovation On Bitcoin’s Evolutionary Patharrow-up-right](https://www.cryptopolitan.com/bitcoin-defi-the-most-pivotal-innovation-on-bitcoins-evolutionary-path/) Cryptopolitan [🟧 Stacks Bridges the Gap to Bitcoin as Strategic US Reserve Materializesarrow-up-right](https://www.financemagnates.com/thought-leadership/stacks-bridges-the-gap-to-bitcoin-as-strategic-us-reserve-materializes/) Finance Magnates [🗞️ Bitcoin DeFi Protocol Velar Unveils .BTC Name Grant Program for Unified Identities on Stacksarrow-up-right](https://cryptopotato.com/bitcoin-defi-protocol-velar-unveils-btc-name-grant-program-for-unified-identities-on-stacks/) CryptoPotato [🚀arrow-up-right](https://www.crypto-news-flash.com/why-stacks-is-leading-the-bitcoin-layer-2-revolution/) [Bitcoin DeFi: The Most Pivotal Innovation On Bitcoin’s Evolutionary Patharrow-up-right](https://www.cryptopolitan.com/bitcoin-defi-the-most-pivotal-innovation-on-bitcoins-evolutionary-path/?ref=stacksblog) Cryptopolitan [Previous2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025) [NextFebruary 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/february-2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # December 2024 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Outlet / Author 🧡 [Portal Ventures, the Leading Pre-seed VC Firm and the First to Call the Bitcoin Thesis, to Back sBTCarrow-up-right](https://www.theblock.co/post/329292/portal-ventures-the-leading-pre-seed-vc-firm-and-the-first-to-call-the-bitcoin-thesis-to-back-sbtc?ref=stacksblog) The Block 🧡 [LearnWeb3, the Largest Educational Platform for Web3, Set to Onboard New Wave of sBTC Developersarrow-up-right](https://www.theblock.co/post/330037/learnweb3-the-largest-educational-platform-for-web3-set-to-onboard-new-wave-of-sbtc-developers) The Block 🧡 [Xverse, Leading Bitcoin Ecosystem Wallet, Adopts sBTC as Preferred Scaling Solution for the Bitcoin Economyarrow-up-right](https://www.theblock.co/post/330649/xverse-leading-bitcoin-ecosystem-wallet-adopts-sbtc-as-preferred-scaling-solution-for-the-bitcoin-economy) The Block 🧡 [Hex Trust Expands Collaboration with Stacks Asia Foundation to Bolster sBTC Adoptionarrow-up-right](https://blockchainreporter.net/hex-trust-expands-collaboration-with-stacks-asia-foundation-to-bolster-sbtc-adoption/) Blockchain Reporter 🧡 [Fordefi, the First MPC Wallet to Fully Support Bitcoin DeFi, Joins Cohort of sBTC Backersarrow-up-right](https://www.theblock.co/post/331016/fordefi-the-first-mpc-wallet-to-fully-support-bitcoin-defi-joins-cohort-of-sbtc-backers) The Block 🧡 [Travala, The #1 Bitcoin and Crypto Travel Booking Portal, Announces Support for sBTC and STXarrow-up-right](https://www.theblock.co/post/331020/travala-the-1-bitcoin-and-crypto-travel-booking-portal-announces-support-for-sbtc-and-stx) The Block 🚀 [Double-dipping with sBTC on Stacksarrow-up-right](https://blockworks.co/news/stacks-sbtc-double-dipping) Blockworks 🚀 [Bitcoin Gets DeFi Upgrade: Stacks Launches Bitcoin-Backed sBTC for Smart Contractsarrow-up-right](https://hackernoon.com/bitcoin-gets-defi-upgrade-stacks-launches-bitcoin-backed-sbtc-for-smart-contracts) Hackernoon 🚀 [sBTC Launches on Stacks Mainnet, Bringing Bitcoin DeFi to Lifearrow-up-right](https://beincrypto.com/sbtc-launches-on-stacks-mainnet/) BeInCrypto 🚀 [sBTC Launches on Stacks Mainnet With Deposit-Only Functionalityarrow-up-right](https://cryptopotato.com/sbtc-launches-on-stacks-mainnet-with-deposit-only-functionality/?amp) Crypto Potato 🚀 [Stacks Launches sBTC on Mainnet with 1,000 BTC Cap, Offering 5% Yield and Up to 60% APY Stakingarrow-up-right](https://thedefiant.io/news/blockchains/stacks-launches-sbtc-on-mainnet-1000-btc-cap-offering-5-yield-up-to-60-apy-b70deae1) The Defiant 🚀 [sBTC Kicks Off on Stacks Mainnet: Detailsarrow-up-right](https://u.today/sbtc-kicks-off-on-stacks-mainnet-details) Crypto Economy 🟧 [Bitcoin's Memecoin-Like 'Runes' Get a Boost With AMM Launch on Stacksarrow-up-right](https://www.coindesk.com/tech/2024/12/18/bitcoins-memecoin-like-runes-get-a-boost-with-amm-launch-on-stacks) Coindesk 🧡 [Ankr, the #1 Provider of Bitcoin-Secured, Physical Infrastructure, Becomes Signer for Stacks as sBTC Launchesarrow-up-right](https://www.theblock.co/post/331411/ankr-the-1-provider-of-bitcoin-secured-physical-infrastructure-becomes-signer-for-stacks-as-sbtc-launches) The Block 📙 [New Report Finds Tokenized BTC Landscape Worth $1T (18 Dec)arrow-up-right](https://coinmarketcap.com/community/articles/6762f62b09984e48933a1ec1/) CoinMarketCap 📙 [New Report Finds Tokenized BTC Landscape Worth $1T (18 Dec)arrow-up-right](https://www.binance.com/en/square/post/17739664161346) Binance [PreviousNovember 2024chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2024/november-2024) [Next2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Introduction | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F4065274862-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F4cpTb2lbw0LAOuMHrvhA%252Fuploads%252FcUxcqYg3XzKCiV6CEyuQ%252Foperate-cover.png%3Falt%3Dmedia%26token%3Da99becb4-6e7d-4018-a809-1c9f5f30abda&width=768&dpr=3&quality=100&sign=911f22c0&sv=2) This section covers the infrastructure needed to participate in the Stacks network. It includes setup guides for running Stacks nodes, miners, and signers, along with instructions for operating a Bitcoin node for those contributing to both networks. It also provides configuration steps for sBTC Signers to enable secure transactions between Bitcoin and Stacks. * * * ### [hashtag](https://docs.stacks.co/operate#learn-to-operate) Learn to operate... [](https://docs.stacks.co/operate/run-a-node) #### [hashtag](https://docs.stacks.co/operate#stacks-node) Stacks Node [](https://docs.stacks.co/operate/run-a-miner) #### [hashtag](https://docs.stacks.co/operate#stacks-miner) Stacks Miner [](https://docs.stacks.co/operate/run-a-signer) #### [hashtag](https://docs.stacks.co/operate#stacks-signer) Stacks Signer [](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node) #### [hashtag](https://docs.stacks.co/operate#bitcoin-node) Bitcoin Node [](https://docs.stacks.co/operate/run-a-sbtc-signer) #### [hashtag](https://docs.stacks.co/operate#sbtc-signer) sBTC Signer [](https://docs.stacks.co/operate/snapshot-the-chainstate) #### [hashtag](https://docs.stacks.co/operate#snapshot-the-chainstate) Snapshot the chainstate [](https://docs.stacks.co/operate/stacking-stx) #### [hashtag](https://docs.stacks.co/operate#stacking-stx) Stacking STX [NextRun a Nodechevron-right](https://docs.stacks.co/operate/run-a-node) Last updated 1 month ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # July 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Title & Link Outlet 📰 [$1.5B Stacks sBTC and STX Adopt Wormhole NTT Standard to Expand Multichainarrow-up-right](https://wormhole.com/blog/usd1-5b-stacks-sbtc-and-stx-adopt-wormhole-ntt-standard-to-expand-multichain?ref=stacksblog) Wormhole Blog [Top Interop Protocol Wormhole Adds Stacks to Bridge Bitcoin to Multi-Chain DeFiarrow-up-right](https://thedefiant.io/news/defi/wormhole-integrates-stacks-tokens-for-multi-chain-bitcoin-defi) The Defiant [PreviousJune 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/june-2025) [NextAugust 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/august-2025) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # March 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close * 🟧 [America’s Crypto Renaissance: Why Stacks and Bitcoin Layers Are Poised for Growtharrow-up-right](https://www.cryptopolitan.com/americas-crypto-renaissance-why-stacks-and-bitcoin-layers-are-poised-for-growth/) — Cryptopolitan * 🧡 [Bitcoin Layers and the Path to Universal Utilityarrow-up-right](https://www.google.com/url?q=https://cfc-stmoritz.com/industry-insights/bitcoin-layers-and-the-path-to-universal-utility?utm_source%3DCfC%2BSt.%2BMoritz%2B-%2BGlobal%2BMailing%2BList%26utm_campaign%3D61bc405f9f-EMAIL_CAMPAIGN_2024_04_03_02_27_COPY_01%26utm_medium%3Demail%26utm_term%3D0_-4a9e5b2e5d-296312470&sa=D&source=editors&ust=1743526707117175&usg=AOvVaw2GQInrk1FYUbGiwB0hw6Jt) — Cfc Moritz (Kyle Ellicott) * 🚀 [Velar PerpDex Launches on Stacks as First Bitcoin-Native Perpetual DEXarrow-up-right](https://www.dlnews.com/research/external/velar-perpdex-launches-on-stacks-as-first-bitcoin-native-perpetual-dex/) — DL News * 🧡 [Stacks Reaches New All-Time High TVLarrow-up-right](https://x.com/signal21btc/status/1902742256068514010) — Signal21 [PreviousFebruary 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/february-2025) [NextApril 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/april-2025) Last updated 5 months ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # November 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Title & Link Outlet [Stacks to integrate Circle xReserve for USDC interoperabilityarrow-up-right](https://www.stacks.co/blog/stacks-circle-xreserve-usdc?ref=stacksblog) Stacks Labs [PreviousOctober 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/september-2025-1) Last updated 4 months ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Run a Node | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F4065274862-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F4cpTb2lbw0LAOuMHrvhA%252Fuploads%252FFTemmfAy773rwMGUSyGc%252Frun-a-stacks-node-cover.png%3Falt%3Dmedia%26token%3Dd237f0aa-0d46-4be1-8763-1986ec311c30&width=768&dpr=3&quality=100&sign=c9340837&sv=2) This section walks through the technical setup steps required to run Stacks network nodes and miners. There are multiple options available for running a node, including Docker, Digital Ocean, and Render. Running your own Stacks node is a great way to increase the decentralization of the ecosystem and avoid relying on third-party centralized providers. [hashtag](https://docs.stacks.co/operate/run-a-node#minimum-viable-requirements) Minimum viable requirements ----------------------------------------------------------------------------------------------------------------- While you can run a node using these specs, it's recommended to assign more than the minimum for better performance. circle-exclamation * ⚠️ docker-compose version `2.2.2` or greater is **required** — https://docs.docker.com/compose/install/ * **8 GB memory** if running only a Stacks node * **16 GB memory** if running Stacks + Bitcoin node * **2 vCPU** * **1 TB disk** for Stacks node * **1 TB disk** for Bitcoin node [PreviousIntroductionchevron-left](https://docs.stacks.co/operate) [NextRun a Node with Dockerchevron-right](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker) Last updated 1 month ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Miner Costs and Fees | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-costs-and-fees#configuring-cost-and-fee-estimation) Configuring Cost and Fee Estimation config.toml Copy [fee_estimation] cost_estimator = naive_pessimistic fee_estimator = fuzzed_weighted_median_fee_rate fee_rate_fuzzer_fraction = 0.1 fee_rate_window_size = 5 cost_metric = proportion_dot_product log_error = true enabled = true Fee and cost estimators observe transactions on the network and use the observed costs of those transactions to build estimates for viable fee rates and expected execution costs. Estimators and metrics can be selected using the configuration fields above (the defaults shown are currently the only options). `log_error` controls whether the INFO logger will display information about cost estimator accuracy as new costs are observed. Setting `enabled = false` turns off the cost estimators. circle-info Cost estimators are not consensus-critical components — they are intended for miners to rank mempool transactions or for clients to pick appropriate fee rates before broadcasting. The `fuzzed_weighted_median_fee_rate` estimator: * uses a median estimate from a window of the fees paid in the last `fee_rate_window_size` blocks, and * then applies a uniform random "fuzz" up to `fee_rate_fuzzer_fraction` of the base estimate. chevron-rightMining calculator (external)[hashtag](https://docs.stacks.co/operate/run-a-miner/miner-costs-and-fees#mining-calculator-external) There is a mining calculator that can help with this process: https://friedger.github.io/mining-calculator/ Source code: https://github.com/friedger/mining-calculator [PreviousMiner Prerequisiteschevron-left](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites) [NextMine Testnet Stacks Tokenschevron-right](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Run a Node with Quicknode | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [QuickNodearrow-up-right](https://www.quicknode.com/) is a service for rapidly getting set up with a Stacks node. As an easy and fast alternative to running your own node, you can utilize QuickNode to serve as an API. 1 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-quicknode#create-a-quicknode-account) Create a QuickNode account Sign up on QuickNode: https://www.quicknode.com/signup 2 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-quicknode#create-an-endpoint) Create an endpoint Once signed in, click "Create an endpoint". Select: * Stacks * your desired network (e.g., mainnet or testnet) * your desired QuickNode plan level After that you'll have an API endpoint URL you can use to connect to Stacks. 3 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-quicknode#install-the-stacks-network-package) Install the Stacks network package Install the `@stacks/network` package in your frontend project. 4 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-quicknode#import-the-network-class) Import the network class In your frontend code, import the network class: example.js Copy import { StacksTestnet } from "@stacks/network"; 5 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-quicknode#configure-the-network-with-your-quicknode-endpoint) Configure the network with your QuickNode endpoint Create the network instance using your QuickNode endpoint URL: example.js Copy const network = new StacksTestnet({ url: "" }); Replace with the full endpoint URL provided by QuickNode. 6 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-quicknode#use-with-stacks-transactions) Use with @stacks/transactions You can now call transactions and other Stacks RPC methods as you normally would using the `@stacks/transactions` library, passing the `network` instance where required. For an example integration and walkthrough, refer to the Hello Stacks tutorial. [PreviousRun a Node with a Hosted Providerchevron-left](https://docs.stacks.co/operate/run-a-node/run-a-node-with-a-hosted-provider) [NextRun a Bitcoin Nodechevron-right](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Verify Miner | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [hashtag](https://docs.stacks.co/operate/run-a-miner/verify-miner#verify-configuration) Verify Configuration ----------------------------------------------------------------------------------------------------------------- You can verify that your node is operating as a miner by checking its log output to verify that it was able to find its Bitcoin UTXOs: logs Copy $ head -n 1000 /path/to/your/node/logs | grep -i utxo INFO [1630127492.031042] [testnet/stacks-node/src/run_loop/neon.rs:146] [main] Miner node: checking UTXOs at address: INFO [1630127492.062652] [testnet/stacks-node/src/run_loop/neon.rs:164] [main] UTXOs found - will run as a Miner node [hashtag](https://docs.stacks.co/operate/run-a-miner/verify-miner#verify-operations) Verify Operations ----------------------------------------------------------------------------------------------------------- The first transaction of the miner is a registration transaction on Bitcoin. It just contains an `OP_RETURN` utxo. Thereafter, the miner creates for each block one transaction on Bitcoin with one data output, and two commit outputs to the stackers. The amount is half the value of the configured `burn_fee_cap` property. If the miner won a sortition, the corresponding Stacks address will create a tenure change transaction and a coinbase transaction. The block rewards will be awarded 100 blocks later if mining was successful. [PreviousMine Mainnet Stacks Tokenschevron-left](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens) [NextRun a Signerchevron-right](https://docs.stacks.co/operate/run-a-signer) Was this helpful? * [Verify Configuration](https://docs.stacks.co/operate/run-a-miner/verify-miner#verify-configuration) * [Verify Operations](https://docs.stacks.co/operate/run-a-miner/verify-miner#verify-operations) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # October 2025 | Press & Reports | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Article Title & Link Outlet [Dual Stacking: What It Means for Stackers and the Broader Ecosystemarrow-up-right](https://stacks.org/dual-stacking-overview?ref=stacksblog) Stacks Foundation Blog [PreviousSeptember 2025chevron-left](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/september-2025) [NextNovember 2025chevron-right](https://docs.stacks.co/press-and-reports/press-and-top-links/2025/september-2025-2) Last updated 4 months ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Run a Miner | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F4065274862-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F4cpTb2lbw0LAOuMHrvhA%252Fuploads%252F3IItqP16x3XffXnx6PgR%252Frun-a-miner-cover.png%3Falt%3Dmedia%26token%3D89a6cc96-1b14-4508-a321-238e73c56bdd&width=768&dpr=3&quality=100&sign=9e6c10b1&sv=2) If you are interested in running a Stacks miner, there are a few things you'll need to understand. Running a miner is similar to running a node, but you'll need to set up some additional configuration. These guides will help you get up and running with both a testnet and mainnet Stacks miner. [PreviousRun a Node Behind a Proxychevron-left](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy) [NextMiner Prerequisiteschevron-right](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites) Last updated 1 month ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Accounts & Addresses | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Generate a walletchevron-right](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet) [Generate a secret keychevron-right](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key) [Derive stacks address from keyschevron-right](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys) [PreviousTransfer a SIP10 tokenchevron-left](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token) [NextGenerate a walletchevron-right](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Transaction Building | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Build an unsigned txchevron-right](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx) [Create a sponsored txchevron-right](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx) [PreviousWelcome to the Cookbookchevron-left](https://docs.stacks.co/cookbook) [NextBuild an unsigned txchevron-right](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Miner Prerequisites | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#prerequisites) Prerequisites ---------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#vm-setup) VM setup The VM will not need a lot of resources to run a miner - the most resources will be consumed during the blockchain syncs (for both Bitcoin and Stacks). For this example, we'll assume a [**Debian**arrow-up-right](https://www.debian.org/) host with `x86_64` architecture (_commands may also work on any Debian-derived distribution_). A single CPU system with at least 4GB of memory and 1TB of disk space should be considered the minimum required specs to run the miner. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#vm-specs) VM Specs * Minimum CPU: `1 vCPU` * Minimum Memory: `4GB` * Minimum Storage: `1TB Disk` to allow for chainstate growth * as of **July 2022**: * Bitcoin chainstate is roughly `420GB` * Stacks chainstate is roughly `45GB` #### [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#disk-configuration) Disk Configuration Two options here — either are fine but it's recommended to mount the chainstate from a separate disk that only contains the chainstate (see the first option). 1 #### [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#separate-disks-for-chainstate-s-and-os) Separate disks for chainstate(s) and OS * mount a dedicated disk for bitcoin at `/bitcoin` of 1TB * mount a dedicated disk for stacks-blockchain at `/stacks-blockchain` of at least 100GB * root volume `/` of at least 25GB 2 #### [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#combined-disk-for-all-data) Combined Disk for all data * root volume `/` of at least 1TB Create the required directories: If using mounted disks: mount the disks to each filesystem created above — edit `/etc/fstab` to automount these disks at boot. Example `/etc/fstab` entries: Mount the disks: ### [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#scripted-install) Scripted install You can use the scripts/prerequisites.sh to install everything: ### [hashtag](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#install-required-packages) Install required packages The following packages are required and used by the rest of these docs: [PreviousRun a Minerchevron-left](https://docs.stacks.co/operate/run-a-miner) [NextMiner Costs and Feeschevron-right](https://docs.stacks.co/operate/run-a-miner/miner-costs-and-fees) Was this helpful? * [Prerequisites](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#prerequisites) * [VM setup](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#vm-setup) * [Scripted install](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#scripted-install) * [Install required packages](https://docs.stacks.co/operate/run-a-miner/miner-prerequisites#install-required-packages) Was this helpful? sun-brightdesktopmoon Create directories Copy $ sudo mkdir -p /bitcoin $ sudo mkdir -p /stacks-blockchain $ sudo mkdir -p /etc/bitcoin $ sudo mkdir -p /etc/stacks-blockchain Copy /dev/xvdb1 /bitcoin xfs rw,relatime,attr2,inode64,noquota /dev/xvdc1 /stacks-blockchain xfs rw,relatime,attr2,inode64,noquota Copy sudo mount -a Copy curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/stacksfoundation/miner-docs/main/scripts/prerequisites.sh | bash Install packages Copy $ 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 sun-brightdesktopmoon --- # Run a Node with a Hosted Provider | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close We're always looking for new hosting providers that enable anyone to run the Stacks Blockchain. Below, you'll find some examples of the current providers that are known to support running a node. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-a-hosted-provider#quicknode) Quicknode Please refer to the Quicknode Section for instructions on launching an instance with Quicknode. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-a-hosted-provider#stacks-on-render) Stacks on Render The [render-stacksarrow-up-right](https://github.com/stacksfoundation/render-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Renderarrow-up-right](https://render.com/) service in one click. circle-exclamation While it is possible to use the free plan with some modifications, it is recommended to run this on a paid plan. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-a-hosted-provider#stacks-on-fly) Stacks on Fly The [fly-stacksarrow-up-right](https://github.com/stacksfoundation/fly-stacks) GitHub repo has instructions so anyone can deploy a Stacks node to the hosted [Flyarrow-up-right](https://fly.io/) service. [PreviousRun a Node with Digital Oceanchevron-left](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean) [NextRun a Node with Quicknodechevron-right](https://docs.stacks.co/operate/run-a-node/run-a-node-with-quicknode) Was this helpful? * [Quicknode](https://docs.stacks.co/operate/run-a-node/run-a-node-with-a-hosted-provider#quicknode) * [Stacks on Render](https://docs.stacks.co/operate/run-a-node/run-a-node-with-a-hosted-provider#stacks-on-render) * [Stacks on Fly](https://docs.stacks.co/operate/run-a-node/run-a-node-with-a-hosted-provider#stacks-on-fly) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Token Transfers | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Transfer STXchevron-right](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx) [Transfer a SIP10 tokenchevron-right](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token) [PreviousCreate a sponsored txchevron-left](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx) [NextTransfer STXchevron-right](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Address Utilities | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Convert BTC to STX addresschevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address) [Convert string to principalchevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal) [Derive principal addresses between networkschevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks) [Create a random burn addresschevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address) [PreviousBuild a STX pcchevron-left](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc) [NextConvert BTC to STX addresschevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Data Utility | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Filter items from a listchevron-right](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list) [Check for duplicateschevron-right](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates) [Return an entry from a mapchevron-right](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map) [PreviousCreate a random burn addresschevron-left](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address) [NextFilter items from a listchevron-right](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Generate a wallet | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet#description) Description Create a new wallet with mnemonic phrase or restore from existing seed ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet#use-cases) Use Cases * Creating new wallets for users * Restoring wallets from seed phrases * Generating deterministic wallet addresses * Building wallet applications ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet#key-concepts) Key Concepts * **Secret key** - Can be a mnemonic phrase or private key * **Password** - Encrypts the wallet (different from mnemonic passphrase) * **Accounts** - Multiple accounts can be derived from one seed * Wallet SDK generates hierarchical deterministic (HD) wallets following BIP32/BIP39 standards [PreviousAccounts & Addresseschevron-left](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses) [NextGenerate a secret keychevron-right](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key) Last updated 2 months ago Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { generateWallet, generateSecretKey } from '@stacks/wallet-sdk'; import { privateKeyToAddress } from '@stacks/transactions' // Generate a new wallet with a new 24-word seed phrase const secretKey = generateSecretKey(256); // 256 bits = 24 words const wallet = await generateWallet({ secretKey, password: 'your-secure-password', }); // Access the first account const account = wallet.accounts[0]; const mainnetAddress = privateKeyToAddress(account.stxPrivateKey, 'mainnet'); console.log('Mnemonic:', secretKey); console.log('Address:', mainnetAddress chevron-downShow all 15 lines sun-brightdesktopmoon --- # Derive stacks address from keys | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys#description) Description Generate Stacks addresses from private or public keys using multiple methods ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys#use-cases) Use Cases * Wallet address generation * Key pair validation * Address recovery from backup keys * Multi-signature wallet setup ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys#key-concepts) Key Concepts * **Private key** - 32-byte random number (keep secret!) * **Public key** - Derived from private key using ECDSA * **Address** - Base58check-encoded hash of public key * **Network** - Different prefixes for mainnet (SP/SM) vs testnet (ST/SN) [PreviousGenerate a secret keychevron-left](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key) [NextCryptography & Securitychevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security) Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { getPublicKeyFromPrivate } from "@stacks/encryption"; import { getAddressFromPrivateKey, getAddressFromPublicKey } from "@stacks/transactions"; // Derive address from private key const privateKey = process.env.PRIVATE_KEY; // Keep this secret! const addressFromPrivate = getAddressFromPrivateKey(privateKey, "testnet"); // Derive public key and address const publicKey = getPublicKeyFromPrivate(privateKey); const addressFromPublic = getAddressFromPublicKey(publicKey, "testnet"); console.log("Address:", addressFromPrivate); console.log("Public key:", publicKey); console.log("Same address:", addressFromPrivate === addressFromPublic); // true chevron-downShow all 17 lines sun-brightdesktopmoon --- # Build an nft pc | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc#description) Description Create post-conditions for NFT transfers to ensure specific tokens are or aren't transferred ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc#use-cases) Use Cases * Protecting valuable NFTs from accidental transfers * Ensuring specific NFTs are transferred in marketplace transactions * Safeguarding NFT collections during contract interactions ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc#key-concepts) Key Concepts * **Asset identifier** - Contract address + asset name with `::` separator * **Token ID** - The specific NFT ID as a Clarity value (using `Cl.uint()`) * NFT post-conditions use the `.nft()` method [PreviousBuild an ft pcchevron-left](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc) [NextBuild a STX pcchevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc) Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { Pc, Cl } from '@stacks/transactions'; // Ensure a specific NFT will be sent const sendPC = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") .willSendAsset() .nft('ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.cool-nfts::nft-token', Cl.uint(42)); // Ensure a specific NFT will NOT be sent const keepPC = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") .willNotSendAsset() .nft('ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.cool-nfts::nft-token', Cl.uint(1)); chevron-downShow all 11 lines sun-brightdesktopmoon --- # Filter items from a list | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list#description) Description Remove specific items from lists using fold in Clarity ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list#use-cases) Use Cases * Removing blacklisted addresses from access lists * Filtering out completed tasks from todo lists * Excluding specific tokens from portfolios * Data cleanup in smart contracts ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list#key-concepts) Key Concepts * **Accumulator** - Tracks the value to remove and builds the new list * **Conditional append** - Only adds items that don't match the filter * **Type safety** - Maintains list type and maximum length * This pattern uses `fold` to iterate through a list and build a new list [PreviousData Utilitychevron-left](https://docs.stacks.co/cookbook/clarity/data-utility) [NextCheck for duplicateschevron-right](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list#key-concepts) Was this helpful? sun-brightdesktopmoon Copy (define-read-only (filter-item (l (list 100 uint)) (remove uint)) (get newList (fold remove-value l { compareTo: remove, newList: (list) })) ) (define-private (remove-value (listValue uint) (trackerTuple { compareTo: uint, newList: (list 100 uint) })) (merge trackerTuple {newList: (if (is-eq listValue (get compareTo trackerTuple)) (get newList trackerTuple) (unwrap-panic (as-max-len? (append (get newList trackerTuple) listValue) u100)) ) }) ) ;; Example usage (filter-item (list u1 u2 u3 u2 u4) u2) ;; Returns (u1 u3 u4) chevron-downShow all 15 lines sun-brightdesktopmoon --- # Transfer STX | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx#description) Description Send STX tokens between addresses with post-conditions for secure transfers ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx#use-cases) Use Cases * Transferring STX tokens securely between addresses * Validating transaction amounts for secure transfers ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx#key-concepts) Key Concepts * **Post-conditions** - Ensure the exact amount of STX is transferred [PreviousToken Transferschevron-left](https://docs.stacks.co/cookbook/stacks.js/token-transfers) [NextTransfer a SIP10 tokenchevron-right](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token) Last updated 2 months ago Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { broadcastTransaction, makeSTXTokenTransfer, Pc, PostConditionMode, } from "@stacks/transactions"; // Define sender and recipient const senderAddress = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM"; const recipientAddress = "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5"; // Create post-condition to ensure exact amount is sent const postConditions = Pc.principal(senderAddress) .willSendEq(1000000) // 1 STX in micro-STX .ustx(); // Configure transaction options const txOptions = { recipient: recipientAddress, amount: 1000000, // 1 STX in micro-STX senderKey: "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", network: 'testnet', memo: "Transfer memo", // Optional memo field postConditions: [postConditions], postConditionMode: PostConditionMode.Deny, }; // Create and broadcast the transaction const transaction = await makeSTXTokenTransfer(txOptions); const broadcastResponse = await broadcastTransaction({ transaction }); console.log("Transaction ID:", broadcastResponse.txid); chevron-downShow all 31 lines sun-brightdesktopmoon --- # Create a sponsored tx | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx#description) Description Build transactions where a sponsor pays the fees on behalf of users ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx#use-cases) Use Cases * Onboarding new users without STX for fees * Subsidizing transaction costs for dApp users * Enterprise applications paying for user transactions * Gaming applications with seamless user experience ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx#key-concepts) Key Concepts * **User** - Creates and signs the transaction with `sponsored: true` * **Sponsor** - Pays the fees and broadcasts the transaction * Sponsored transactions have two parties [PreviousBuild an unsigned txchevron-left](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx) [NextToken Transferschevron-right](https://docs.stacks.co/cookbook/stacks.js/token-transfers) Last updated 2 months ago Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { bytesToHex } from "@stacks/common"; import { broadcastTransaction, deserializeTransaction, makeContractCall, sponsorTransaction, BufferReader, AnchorMode, Cl, } from "@stacks/transactions"; // Step 1: User creates the transaction with sponsored flag const userTxOptions = { contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM", contractName: "my-contract", functionName: "my-function", functionArgs: [Cl.uint(123)], fee: 0, // User doesn't pay fees senderKey: "b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01", network: 'testnet', sponsored: true, // Mark as sponsored }; const transaction = await makeContractCall(userTxOptions); const serializedTx = bytesToHex(transaction.serialize()); // Step 2: Send serialized transaction to sponsor // (In practice, this would be sent to a sponsorship service) // Step 3: Sponsor signs and pays fees const sponsorKey = "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601"; const deserializedTx = deserializeTransaction(serializedTx); const sponsoredTx = await sponsorTransaction({ transaction: deserializedTx, sponsorPrivateKey: sponsorKey, fee: 1000, // Sponsor pays the fee sponsorNonce: 0, }); // Step 4: Broadcast the sponsored transaction const broadcastResponse = await broadcastTransaction({ transaction: sponsoredTx, network: STACKS_TESTNET, }); console.log("Sponsored transaction ID:", broadcastResponse.txid); chevron-downShow all 46 lines sun-brightdesktopmoon --- # Build an ft pc | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc#description) Description Create post-conditions for fungible token transfers to ensure exact amounts are transferred as expected ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc#use-cases) Use Cases * Securing fungible token transfers with amount validation * Protecting users from unexpected token transfers in DeFi protocols * Ensuring token swaps happen with expected amounts ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc#key-concepts) Key Concepts * `.ft()` - Takes two parameters: contract address with asset name and token name as defined in the contract * The `Pc` builder for fungible tokens provides a fluent interface for creating post-conditions [PreviousIntegrate api keyschevron-left](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys) [NextBuild an nft pcchevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc) Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { Pc } from '@stacks/transactions'; // Create a post-condition for fungible token transfers const postCondition = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") .willSendGte(500) // Amount in token's smallest unit .ft("ST1HTBVD3JG9C05J7HBJTHGR0GGW7KXW28M5JS8QE.token-ft", "my-token"); // Use in transaction options const txOptions = { // ... other transaction options postConditions: [postCondition], postConditionMode: PostConditionMode.Deny, }; chevron-downShow all 13 lines sun-brightdesktopmoon --- # Create sha256 hash clarity | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity#description) Description Generate SHA-256 hashes from buffer data in Clarity smart contracts ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity#use-cases) Use Cases * Creating unique identifiers from data * Verifying data integrity in contracts * Implementing commit-reveal schemes * Building merkle trees for proofs ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity#key-concepts) Key Concepts * Takes a buffer as input (max 1MB) * Returns a 32-byte buffer hash * Uses `to-consensus-buff?` to ensure consistent encoding * Produces the same hash as off-chain implementations [PreviousCryptography & Securitychevron-left](https://docs.stacks.co/cookbook/clarity/cryptography-and-security) [NextContract post-conditionschevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity#key-concepts) Was this helpful? sun-brightdesktopmoon Copy (define-read-only (create-sha256-hash (data (buff 4096))) (sha256 (unwrap-panic (to-consensus-buff? data))) ) ;; Example usage (define-read-only (hash-message (message (string-utf8 200))) (create-sha256-hash (unwrap-panic (to-consensus-buff? message))) ) ;; Hash a simple string (print (hash-message u"Hello World")) chevron-downShow all 11 lines sun-brightdesktopmoon --- # How to Read Signer Logs | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close There are a lot of different messages you can get in the logs when running a signer. Getting a good grasp on what some of these logs mean can help you troubleshoot effectively and determine if your signer is running successfully or not. There are three types of log messages you should be aware of: * Successful * Informational * Errors Successful log messages indicate that you are on track and everything is working as expected. However, there are various success stages depending on several factors including your stacking status and the timing of the current reward cycle. There are also several informational/warning logs that you don't necessarily need to take action on, but they provide useful context about the network or the signer. Finally, error logs indicate something has gone wrong and you need to take action. Below are some common log messages you might see, what they mean, and what action (if any) you should take. circle-info Successful / informational / error categories — general guidance: * Successful: nothing to do unless the message indicates a different stage of operation that requires action (e.g., registration needed). * Informational: often safe to ignore, but useful for context. * Errors: require investigation and remediation. [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs#successful) Successful --------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs#signer-uninitialized-or-not-registered) Signer uninitialized or not registered If you get a message saying your signer is uninitialized, it means your signer is not registered for the current or upcoming reward cycle (or the burnchain block height is not yet at the second block in the prepare phase) so the signer cannot determine registration status yet. This does not mean the signer process itself has failed — it is running successfully, but the signer cannot act until registration/delegation occurs. Example log: `Signer spawned successfully. Waiting for messages to process... INFO [1711088054.872542] [stacks-signer/src/runloop.rs:278] [signer_runloop] Running one pass for signer ID# 0. Current state: Uninitialized` You may also see a warning like: Action: * If you want the signer to participate, either delegate to it or stack on your own for an upcoming reward cycle. * For more details on stacking and registration, see the [Stacking STX](https://docs.stacks.co/operate/stacking-stx) guide. [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs#informational) Informational --------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs#peer-not-connecting) Peer not connecting If you see a message about a peer not connecting, for example: This means your node attempted to connect to another node on the network but was unable to. This can happen for many reasons (network connectivity, remote node offline, NAT/firewall, etc.). Action: * Usually not a cause for concern and does not impact whether your signer is running correctly. * If you see many such messages or persistent connectivity issues, investigate network connectivity, firewall/NAT rules, or peer configuration. [PreviousSigner Quickstartchevron-left](https://docs.stacks.co/operate/run-a-signer/signer-quickstart) [NextHow to Monitor Signerchevron-right](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer) Last updated 12 days ago Was this helpful? * [Successful](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs#successful) * [Signer uninitialized or not registered](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs#signer-uninitialized-or-not-registered) * [Informational](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs#informational) * [Peer not connecting](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs#peer-not-connecting) Was this helpful? sun-brightdesktopmoon Copy WARN [1712003997.160121] [stacks-signer/src/runloop.rs:247] [signer_runloop] Signer is not registered for reward cycle 556. Waiting for confirmed registration... Copy INFO [1711988555.021567] [stackslib/src/net/neighbors/walk.rs:1015] [p2p-(0.0.0.0:20444,0.0.0.0:20443)] local.80000000://(bind=0.0.0.0:20444)(pub=Some(10.0.19.16:20444)): Failed to connect to facade0b+80000000://172.16.60.18:20444: PeerNotConnected sun-brightdesktopmoon --- # Cryptography & Security | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Create sha256 hash claritychevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity) [Contract post-conditionschevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions) [Generate random numberchevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number) [Helper function to restrict contract callschevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/helper-function-to-restrict-contract-calls) [PreviousReturn an entry from a mapchevron-left](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map) [NextCreate sha256 hash claritychevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Check for duplicates | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates#description) Description Detect duplicate characters in strings and duplicate items in lists using Clarity ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates#use-cases) Use Cases * Validating usernames for uniqueness of characters * Checking NFT trait uniqueness in collections * Preventing duplicate entries in voting systems * Ensuring unique identifiers in lists ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates#key-concepts) Key Concepts * **Strings** - Uses `fold` with `index-of?` to find repeated characters * **Lists** - Checks if elements appear again in the remaining list * **Optimization** - Early exit on first duplicate found [PreviousFilter items from a listchevron-left](https://docs.stacks.co/cookbook/clarity/data-utility/filter-items-from-a-list) [NextReturn an entry from a mapchevron-right](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates#key-concepts) Was this helpful? sun-brightdesktopmoon Copy ;; Check for duplicate characters in a string (define-read-only (has-duplicate-chars? (input (string-ascii 200))) (is-none (fold dup input (slice? (concat input "|END") u1 (+ (len input) u4)))) ) (define-private (dup (ch (string-ascii 1)) (out (optional (string-ascii 204)))) (match out out_some (match (index-of? (unwrap-panic (slice? out_some u0 (- (len out_some) u4))) ch) found none (slice? out_some u1 (len out_some)) ) out ) ) ;; Example usage (has-duplicate-chars? "hello") ;; Returns true (duplicate 'l') (has-duplicate-chars? "world") ;; Returns false (no duplicates) chevron-downShow all 18 lines sun-brightdesktopmoon --- # Stacking STX | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Stacking is the process of locking STX tokens to support the network's consensus and earn BTC rewards. If you aren't familiar with how stacking works, read the [Stackingarrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/learn/block-production/stacking.md) and [Stackers and Signingarrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/learn/block-production/signing.md) concept guides first. Stacking utilizes the `pox-4` contract. You can view it on the [Explorerarrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-4?chain=mainnet) and review the detailed [stacking contract walkthrougharrow-up-right](https://app.gitbook.com/s/GVj1Z9vMuEOMe7oH7Wnq) to understand what each function does. ### [hashtag](https://docs.stacks.co/operate/stacking-stx#definitions-and-roles) Definitions and Roles * **Stacker**: an entity locking their STX to earn PoX rewards. This is a broad term including solo stackers and delegators. * **Solo stacker**: an entity that locks their own STX and runs a signer (or collaborates with one). They don't receive delegation. * **Delegator**: a stacker who delegates their STX to a pool operator. They don't run a signer. * **Pool operator**: an entity that accepts delegated STX and manages the stacking process. A pool operator runs a signer (or collaborates with one). The pool operator and signer address may be different. * **Signer**: an entity running the stacks-signer software that participates in block validation. circle-info The pool operator and signer are often the same entity but may use different Stacks addresses. This distinction is covered in the [Key and Address Rotation](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation) guide. ### [hashtag](https://docs.stacks.co/operate/stacking-stx#guides) Guides 1 [**Solo Stacking**](https://docs.stacks.co/operate/stacking-stx/solo-stacking) If you meet the minimum STX threshold and want to stack independently. Covers how to start stacking, extend your lock period, increase your position, and stop. 2 [**Stack with a Pool**](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool) If you want to delegate your STX to a pool operator. Covers how to delegate, increase your delegation, revoke, and stop stacking. 3 [**Operate a Pool**](https://docs.stacks.co/operate/stacking-stx/operate-a-pool) If you want to accept delegated STX and manage the stacking process. Covers how to accept delegations, commit aggregated STX, and increase committed amounts. 4 [**Generate a Signer Signature**](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) Both solo stacking and delegated stacking require signer signatures. This guide covers all signature generation methods: stacks-signer CLI, stacks.js, Leather Earn, Degen Lab's stacking.tools, and hardware wallets. 5 [**Key and Address Rotation**](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation) How to rotate your signer key, Bitcoin reward address, and pool operator key. Includes recommendations for key separation and security. If you do not meet the minimum amount of STX to solo stack, you can [delegate your STX to a pool operator](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool) and have them stack on your behalf. This is the most common stacking scenario. circle-info The minimum stacking threshold is dynamic and can be found at the [pox endpointarrow-up-right](https://api.mainnet.hiro.so/v2/pox) under `min_threshold_ustx` (1 STX = 1,000,000 uSTX). [PreviousSnapshot the Chainstatechevron-left](https://docs.stacks.co/operate/snapshot-the-chainstate) [NextSolo Stackingchevron-right](https://docs.stacks.co/operate/stacking-stx/solo-stacking) Last updated 12 days ago Was this helpful? * [Definitions and Roles](https://docs.stacks.co/operate/stacking-stx#definitions-and-roles) * [Guides](https://docs.stacks.co/operate/stacking-stx#guides) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Transfer a SIP10 token | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token#description) Description Transfer fungible tokens using the SIP-10 standard with post-conditions ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token#use-cases) Use Cases * Transferring fungible tokens between wallets * Integrating token transfers in dApps * Building DEX or swap functionality * Implementing payment systems with custom tokens ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token#key-concepts) Key Concepts * **Standard interface** - All SIP-10 tokens implement `transfer`, `get-balance`, etc. * **Post-conditions** - Protect users by ensuring exact amounts are transferred * **Memos** - Optional field for including transfer notes * SIP-10 is the fungible token standard on Stacks, similar to ERC-20 [PreviousTransfer STXchevron-left](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-stx) [NextAccounts & Addresseschevron-right](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses) Last updated 2 months ago Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/token-transfers/transfer-a-sip10-token#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { broadcastTransaction, Cl, makeContractCall, Pc, PostConditionMode, } from "@stacks/transactions"; // Token contract details const tokenAddress = "SP3K8BC0PPEVCV7NZ6QSRWPQ2JE9E5B6N3PA0KBR9"; const tokenName = "wrapped-bitcoin"; const contractIdentifier = `${tokenAddress}.${tokenName}`; // Create post-condition to ensure exact amount is transferred const postConditions = [\ Pc.principal("SP2C20XGZBAYFZ1NYNHT1J6MGBGVX9X7X3P7LAX7K")\ .willSendEq(100000000) // 1 wBTC (8 decimals)\ .ft(contractIdentifier, tokenName)\ ]; const txOptions = { contractAddress: tokenAddress, contractName: tokenName, functionName: "transfer", functionArgs: [\ Cl.uint(100000000), // amount (with decimals)\ Cl.principal("SP2C20XGZBAYFZ1NYNHT1J6MGBGVX9X7X3P7LAX7K"), // sender\ Cl.principal("SP31DA84DWTF6510EW6DCTC3GB3XH1EEBGP7MYT2"), // recipient\ Cl.none(), // optional memo\ ], senderKey: "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", validateWithAbi: true, network: 'mainnet, postConditions, postConditionMode: PostConditionMode.Deny, }; const transaction = await makeContractCall(txOptions); const broadcastResponse = await broadcastTransaction({ transaction, network: STACKS_MAINNET, }); console.log("Transaction ID:", broadcastResponse.txid); chevron-downShow all 44 lines sun-brightdesktopmoon --- # Run a Node with Digital Ocean | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#introduction) Introduction This is a step by step guide to deploy the [Stacks Blockchainarrow-up-right](https://github.com/stacks-network/stacks-blockchain) on [DigitalOceanarrow-up-right](https://digitalocean.com/) . Build code is hosted on this [Github repositoryarrow-up-right](https://github.com/stacksfoundation/stacks-machine-images) using the [methods from herearrow-up-right](https://github.com/stacks-network/stacks-blockchain-docker) . ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#steps) Steps 1 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#create-the-droplet-from-the-marketplace) Create the Droplet from the Marketplace Go to the [Stacks Blockchain pagearrow-up-right](https://marketplace.digitalocean.com/apps/stacks-blockchain) in DigitalOcean's marketplace. Click on `Create Stacks Blockchain Droplet`. 2 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#choose-plan-and-region) Choose plan and region Choose a plan (it will only allow you to select a droplet that meets the minimum requirements) and your preferred datacenter region. 3 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#authentication) Authentication Enter a root password or [enable SSH keysarrow-up-right](https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/) if you prefer. 4 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#create-the-droplet) Create the Droplet You can leave the rest of the options as they are and click on `Create Droplet`. 5 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#wait-for-creation) Wait for creation You will need to wait a few seconds for the droplet to get created. Once created click on it to see more information. 6 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#access-the-droplet) Access the Droplet Congratulations! You are now running the Stacks Blockchain. You can click on `Console` for a terminal window to open or login using SSH to the public IP you've been assigned to with user `root`. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#getting-started-after-deploying-stacks-blockchain) Getting started after deploying Stacks Blockchain Once the droplet is launched, the initial startup can take several minutes while BNS data is imported (this is a one time operation) and the Bitcoin headers are synced. To keep track of the progress, you can SSH to the host and view logs: Copy ssh root@your_droplet_public_ipv4 /opt/stacks-blockchain-docker/manage.sh -n mainnet -a logs After the stacks blockchain finishes the initial header sync and starts to sync with its peers, the application ports will open (`20443` and `3999`) and HTTP port `80` will now start proxying requests. Use `http://your_droplet_public_ipv4` to access the data directly, with output being similar to: Copy { "server_version": "stacks-blockchain-api v6.2.3 (master:77ab3ae2)", "status": "ready", "chain_tip": { "block_height": 91820, "block_hash": "0x06b276e85f238151414616618ae0adaf5eeda4eac6cad5bbefceeb37948ab275", "index_block_hash": "0x4d7c075d7ab0f90b1dbc175f5c42b7344265d00cfef202dd9681d95388eeed8c", "microblock_hash": "0xcf4f9037cc10696b2812b617ca105885be625c6acf8ad67e71bb4c09fa6ebb21", "microblock_sequence": 4 } } circle-info For the full list of API endpoints for the Stacks Blockchain, consult the [Hiro API Docsarrow-up-right](https://docs.hiro.so/api) All services are managed by a [systemd unit filearrow-up-right](https://github.com/stacksfoundation/stacks-machine-images/blob/master/files/etc/systemd/system/stacks.service) that is set to start on boot. Manual control is also possible via the [manage.sh scriptarrow-up-right](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/manage.sh) at `/opt/stacks-blockchain-docker/manage.sh` on the host. Full details on how to use the manage.sh script is [available herearrow-up-right](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/usage.md) . ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#launching-a-droplet-using-the-digitalocean-api) Launching a Droplet using the DigitalOcean API In addition to creating a Droplet from the Stacks Blockchain 1-Click App via the control panel, you can also use the [DigitalOcean APIarrow-up-right](https://digitalocean.com/docs/api) . As an example, to create a 4GB Stacks Blockchain Droplet in the SFO2 region, you can use the following curl command. You’ll need to either save your [API access tokenarrow-up-right](https://docs.digitalocean.com/reference/api/create-personal-access-token/) to an environment variable or substitute it into the command below. circle-info The `name`, `region` and `size` values below are hardcoded, so adjust as desired. [PreviousRun a Node with Dockerchevron-left](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker) [NextRun a Node with a Hosted Providerchevron-right](https://docs.stacks.co/operate/run-a-node/run-a-node-with-a-hosted-provider) Was this helpful? * [Introduction](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#introduction) * [Steps](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#steps) * [Getting started after deploying Stacks Blockchain](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#getting-started-after-deploying-stacks-blockchain) * [Launching a Droplet using the DigitalOcean API](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean#launching-a-droplet-using-the-digitalocean-api) Was this helpful? sun-brightdesktopmoon Copy $ export TOKEN= $ curl -X POST -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '$TOKEN'' -d \ '{"name":"stacks-blockchain","region":"sfo2","size":"s-2vcpu-4gb","image":"stacksfoundation-stacksblockchain"}' \ "https://api.digitalocean.com/v2/droplets" sun-brightdesktopmoon --- # Return an entry from a map | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map#description) Description Query contract map data using the Stacks API map\_entry endpoint ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map#use-cases) Use Cases * Reading user balances from token contracts * Checking NFT ownership records * Retrieving configuration values from contracts * Monitoring contract state without transactions ### [hashtag](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map#key-concepts) Key Concepts * **POST request** - Send the serialized map key * **Hex encoding** - Keys must be hex-encoded Clarity values * **Response format** - Returns hex-encoded Clarity value or null [PreviousCheck for duplicateschevron-left](https://docs.stacks.co/cookbook/clarity/data-utility/check-for-duplicates) [NextCryptography & Securitychevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/data-utility/return-an-entry-from-a-map#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { Cl, cvToHex } from "@stacks/transactions"; // Query a map entry from a contract const contractAddress = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM"; const contractName = "my-contract"; const mapName = "user-balances"; // Create the map key (e.g., a principal) const mapKey = Cl.standardPrincipal("ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5"); const response = await fetch( `https://api.hiro.so/v2/map_entry/${contractAddress}/${contractName}/${mapName}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(cvToHex(mapKey)), } ); const result = await response.json(); const data = result.data ? Cl.deserialize(result.data) : null; console.log("Map value:", data); chevron-downShow all 25 lines sun-brightdesktopmoon --- # Generate a secret key | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key#description) Description Create mnemonic seed phrases for wallet generation ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key#use-cases) Use Cases * Creating new wallet seed phrases * Generating secure entropy for applications * Building wallet creation flows * Testing wallet functionality ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key#key-concepts) Key Concepts * **Entropy** - Random data used to generate the phrase * **Word count** - 12 words (128 bits) or 24 words (256 bits) * **Word list** - Standardized list of 2048 words * **Checksum** - Built-in error detection * Mnemonic seed phrases follow the BIP39 standard [PreviousGenerate a walletchevron-left](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-wallet) [NextDerive stacks address from keyschevron-right](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys) Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/generate-a-secret-key#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { generateSecretKey } from '@stacks/wallet-sdk'; // Generate a 24-word mnemonic (256 bits of entropy) const mnemonic24 = generateSecretKey(); // Example: "aunt birth lounge misery utility blind holiday walnut fuel make gift parent gap picnic exact various express sphere family nerve oil drill engage youth" // Generate a 12-word mnemonic (128 bits of entropy) const mnemonic12 = generateSecretKey(128); // Example: "winter crash infant long upset beauty cram tank short remain obtain sauce" sun-brightdesktopmoon --- # Cryptography & Security | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Create sha256 hashchevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash) [Integrate api keyschevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys) [Build an ft pcchevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc) [Build an nft pcchevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc) [Build a STX pcchevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc) [PreviousDerive stacks address from keyschevron-left](https://docs.stacks.co/cookbook/stacks.js/accounts-and-addresses/derive-stacks-address-from-keys) [NextCreate sha256 hashchevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash) Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Convert BTC to STX address | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address#description) Description Convert Bitcoin addresses to their corresponding Stacks addresses using base58 decoding in Clarity ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address#use-cases) Use Cases * Cross-chain address mapping for Bitcoin-Stacks bridges * Verifying ownership across both chains * Converting legacy Bitcoin addresses to Stacks format * Building cross-chain authentication systems ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address#key-concepts) Key Concepts * **Base58 decoding** - Bitcoin addresses use base58 encoding * **Checksum verification** - Last 4 bytes are a double SHA-256 checksum * **Version mapping** - Bitcoin version bytes map to Stacks version bytes * **Principal construction** - Build Stacks principal from decoded data [PreviousAddress Utilitieschevron-left](https://docs.stacks.co/cookbook/clarity/address-utilities) [NextConvert string to principalchevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address#key-concepts) Was this helpful? sun-brightdesktopmoon Copy (define-read-only (btc-to-stx (input (string-ascii 60))) (let ( ;; Decode base58 string to numbers (b58-numbers (map unwrap-uint (filter is-some-uint (map b58-to-uint input)))) ;; Validate all characters are valid base58 (t1 (asserts! (>= (len b58-numbers) (len input)) ERR_INVALID_CHAR)) ;; Count leading '1's (zeros in base58) (leading-ones-count (default-to (len input) (index-of? (map is-zero b58-numbers) false))) ;; Convert to bytes (decoded (concat (fold decode-outer to-decode LST) leading-zeros)) (decoded-hex (fold to-hex-rev decoded 0x)) ;; Verify checksum (actual-checksum (unwrap-panic (slice? (sha256 (sha256 (unwrap-panic (slice? decoded-hex u0 (- decoded-hex-len u4))))) u0 u4))) (expected-checksum (unwrap-panic (slice? decoded-hex (- decoded-hex-len u4) decoded-hex-len))) (t3 (asserts! (is-eq actual-checksum expected-checksum) ERR_BAD_CHECKSUM)) ;; Extract version and construct principal (version (unwrap-panic (element-at? STX_VER (unwrap! (index-of? BTC_VER (unwrap-panic (element-at? decoded-hex u0))) ERR_INVALID_VERSION)))) ) (principal-construct? version (unwrap-panic (as-max-len? (unwrap-panic (slice? decoded-hex u1 (- decoded-hex-len u4))) u20))) ) ) ;; Example usage (btc-to-stx "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa") ;; Returns Stacks address chevron-downShow all 24 lines sun-brightdesktopmoon --- # Generate random number | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number#description) Description Create pseudo-random numbers using block hashes for randomness in smart contracts ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number#use-cases) Use Cases * Lottery and gaming contracts * Random NFT trait generation * Fair distribution mechanisms * Random selection from lists ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number#key-concepts) Key Concepts * **Block hashes** - Use historical block data as entropy source * **Future blocks** - Cannot predict future block hashes * **Commitment schemes** - Combine with commit-reveal for fairness * Blockchain randomness is deterministic but unpredictable [PreviousContract post-conditionschevron-left](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions) [NextHelper function to restrict contract callschevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/helper-function-to-restrict-contract-calls) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number#key-concepts) Was this helpful? sun-brightdesktopmoon Copy (define-read-only (generate-random (block-height uint)) (let ( ;; Get block header hash (block-hash (unwrap! (get-stacks-block-info? id-header-hash block-height) (err u1001))) ;; Take a slice of the hash for randomness (hash-slice (unwrap-panic (slice? block-hash u16 u32))) ;; Convert to uint (random-value (buff-to-uint-be (unwrap-panic (as-max-len? hash-slice u16)))) ) (ok random-value) ) ) ;; Generate random number in range (define-read-only (random-in-range (block-height uint) (min uint) (max uint)) (let ( (random (try! (generate-random block-height))) (range (- max min)) ) (ok (+ min (mod random (+ u1 range)))) ) ) ;; Example: Random between 1-100 (random-in-range block-height u1 u100) chevron-downShow all 25 lines sun-brightdesktopmoon --- # Integrate api keys | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys#description) Description Configure Stacks.js to use API keys for enhanced rate limits and monitoring ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys#use-cases) Use Cases * Increased API rate limits for production applications * API usage monitoring and analytics * Priority access during high traffic periods * Custom enterprise support features ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys#key-concepts) Key Concepts * **Higher rate limits** - 500 requests/minute vs 50 for anonymous * **Usage tracking** - Monitor your API consumption * **Priority queue** - Better performance during peak times * **Support** - Access to dedicated support channels [PreviousCreate sha256 hashchevron-left](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash) [NextBuild an ft pcchevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-ft-pc) Last updated 2 months ago Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { createNetwork } from '@stacks/network' // Create a network with options object const network = createNetwork({ network: 'mainnet', apiKey: 'my-api-key', }); sun-brightdesktopmoon --- # Create sha256 hash | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash#description) Description Generate SHA-256 hashes that match Clarity's hashing output ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash#use-cases) Use Cases * Creating deterministic identifiers * Verifying data integrity between on-chain and off-chain * Implementing commit-reveal schemes off-chain * Building merkle trees compatible with Clarity ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash#key-concepts) Key Concepts * **Convert to Clarity value** - Use appropriate CV type (`stringUtf8CV`, `bufferCV`, etc.) * **Serialize** - Use `serializeCV` to match Clarity's encoding * **Hash** - Apply SHA-256 to the serialized bytes [PreviousCryptography & Securitychevron-left](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security) [NextIntegrate api keyschevron-right](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/integrate-api-keys) Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/create-sha256-hash#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { sha256 } from "@noble/hashes/sha256"; import { bytesToHex, hexToBytes, utf8ToBytes } from "@stacks/common"; import { bufferCV, stringUtf8CV, serializeCV } from "@stacks/transactions"; // Hash a string (matching Clarity's sha256 output) function hashString(text: string) { const clarityValue = stringUtf8CV(text); const serialized = serializeCV(clarityValue); return bytesToHex(sha256(serialized)); } // Hash hex data (matching Clarity's sha256 output) function hashHexData(hexData: string) { const clarityValue = bufferCV(hexToBytes(hexData)); const serialized = serializeCV(clarityValue); return bytesToHex(sha256(serialized)); } // Example usage const hash1 = hashString("Hello World"); console.log("String hash:", hash1); const hash2 = hashHexData("0x1234567890abcdef"); console.log("Hex hash:", hash2); chevron-downShow all 24 lines sun-brightdesktopmoon --- # Create a random burn address | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address#description) Description Generate burn addresses for permanently removing tokens from circulation ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address#use-cases) Use Cases * Token burning mechanisms * Proof-of-burn implementations * Creating unspendable addresses for protocol fees * Deflationary token economics ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address#key-concepts) Key Concepts * **No private key** - Generated from arbitrary data, not a key pair * **Verifiable** - Anyone can verify tokens sent to these addresses * **Unique** - Different entropy creates different addresses * **Permanent** - Funds sent are irretrievably lost [PreviousDerive principal addresses between networkschevron-left](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks) [NextData Utilitychevron-right](https://docs.stacks.co/cookbook/clarity/data-utility) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address#key-concepts) Was this helpful? sun-brightdesktopmoon Copy (define-read-only (generate-burn-address (entropy (string-ascii 40))) (let ( ;; Hash the entropy to create address bytes (hash-bytes (hash160 (unwrap-panic (to-consensus-buff? entropy)))) ;; Use version byte for current network (version-byte (if is-in-mainnet 0x16 0x1a)) ) ;; Construct a valid principal that no one controls (principal-construct? version-byte hash-bytes) ) ) ;; Example: Generate unique burn address (generate-burn-address "BURN-2024-01-15-PROJECT-XYZ") ;; Returns: (ok SP1FJPSG7V4QMA7D4XVPZ3B2HQ8GY3EK8GC0NGNT3) chevron-downShow all 15 lines sun-brightdesktopmoon --- # OpSec Best Practices | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close #### [hashtag](https://docs.stacks.co/operate/run-a-signer/opsec-best-practices#threat-modeling) Threat Modeling A threat actor that is able to compromise > 70% of Signers (by stake weight) would be able to successfully propose Stacks blocks that would otherwise be considered invalid. Some potential vectors for signer key compromise are as follows: * stacks-signer node is compromised and key is exfiltrated from the filesystem * Signer key is compromised during generation or deployment * Signer key is accidentally checked into SCM (eg Github or Gitlab) * Social engineering attack against Signer community: eg a malicious link is posted to social media that harvests key material * An undisclosed backdoor is discovered in the Signer binary. * Supply chain attack against stacks-signer source code: threat actor compromises upstream dependencies of stacks-signer #### [hashtag](https://docs.stacks.co/operate/run-a-signer/opsec-best-practices#countermeasures) Countermeasures What can Signers do to mitigate the threat vectors identified above? Let's identify countermeasures in response to each of the threats identified above, starting with the first vector: stacks-signer node compromise and key exfiltration. 1 **Run the stacks-signer on a separate system from the stacks-node** This reduces discoverability of the signer. Systems running the stacks-node participate in the peer-to-peer network and are more easily enumerated. If an attacker can't find your stacks-signer, they can't attack it directly. Best practice: ensure stacks-node and stacks-signer communicate only over trusted networks, ideally using localhost (127.0.0.1) or a secure private subnet. Note: Running the stacks-signer on a separate system is an option, but not strictly necessary. Running both on the same virtual machine within a private network, with traffic firewalled to allow only incoming P2P connections (port 20444), provides a secure and easier setup while minimizing exposure. 2 **Run the stacks-signer as a separate user from the stacks-node** When resource constraints prevent separate workloads, run the stacks-signer under a distinct unprivileged user account from the stacks-node. Ensure exclusive ownership and restrictive permissions for each user's configuration files. Example: the user running the signer binary (e.g., signer) should own the signer’s config file and set permissions to prevent other users from reading it. The same principle applies to the stacks-node user. This ensures only appropriate processes can access sensitive configuration details. 3 **Harden the systemd configuration for the stacks-signer** Hardening systemd can reduce blast radius if an attacker gains control of the stacks-signer process. An example stacks-signer.service systemd unit is shown below. This unit prevents certain filesystem writes and otherwise restricts the process. stacks-signer.service Copy [Unit] Description=Stacks Signer After=network.target StartLimitBurst=3 StartLimitIntervalSec=300 ConditionFileIsExecutable=/usr/local/bin/stacks-signer ConditionPathExists=/etc/stacks/signer ConditionFileNotEmpty=/etc/stacks/signer/signer-config.toml [Service] ExecStart=/usr/local/bin/stacks-signer run --config /etc/stacks/signer/signer-config.toml User={{ svc_user }} Group={{ svc_user }} Type=simple Restart=on-failure TimeoutStopSec=600 KillSignal=SIGTERM #KillSignal=SIGINT # Provide a private /tmp and /var/tmp. PrivateTmp=true # Mount /usr, /boot/ and /etc read-only for the process. ProtectSystem=full # Deny access to /home, /root and /run/user ProtectHome=true # Disallow the process and all of its children to gain # new privileges through execve(). NoNewPrivileges=true # Use a new /dev namespace only populated with API pseudo devices # such as /dev/null, /dev/zero and /dev/random. PrivateDevices=true [Install] WantedBy=multi-user.target Read more about systemd hardening: https://www.ctrl.blog/entry/systemd-service-hardening.html 4 **Restrict access to unnecessary ports and protocols** The stacks-signer requires outbound TCP access to the stacks-node, but typically no other inbound network exposure is needed (except for OS updates and administrative access). Restrict network access to the minimum required for operation. 5 **Harden the operating system** A few practical OS hardening measures: * Run stacks-signer as an unprivileged user (not root). * Set permissions on the stacks-signer key/config to be readable only by the user running the stacks-signer process, e.g.: * sudo chmod 600 signer/signer-config.toml * Require public-key authentication for SSH and disable SSH root login. * Consider running sshd on a non-standard port to reduce noise from port scanners and credential-stuffing attacks. This post outlines essential operational security best practices for Stacks Signers, key actors in the Nakamoto architecture. By implementing these strategies, signer operators can effectively mitigate risks and maintain the security and reliability of the Stacks network. [PreviousBest Practices to Run a Signerchevron-left](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer) [NextRun a sBTC Signerchevron-right](https://docs.stacks.co/operate/run-a-sbtc-signer) Last updated 12 days ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Best Practices for Running a sBTC Signer | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close The following best practices suggest how to create a resilient setup for running your sBTC Signer. [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#protect-your-private-key-and-have-a-cold-storage-backup) Protect your private key and have a cold-storage backup -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Prevent unauthorised access to the sBTC Signer private key. * Keep an offline, secure backup of your sBTC Signer private key (e.g., hardware security modules or encrypted storage devices). [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#backup-your-sbtc-signer-postgresql-db) Backup your sBTC Signer PostgreSQL DB -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Perform daily backups of the sBTC Signer PostgreSQL DB. * Periodically verify the integrity of backups (see steps below). ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#verifying-integrity-of-postgresql-db-backups) Verifying integrity of PostgreSQL DB backups 1 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#import-the-backup) Import the backup Import the backup into a fresh PostgreSQL instance. The database alone is sufficient — you do not need to spin up a Stacks or Bitcoin node or the sBTC signer. 2 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#run-the-verification-query) Run the verification query Execute the following query: PostgreSQL Copy Copy SELECT aggregate_key FROM sbtc_signer.dkg_shares WHERE dkg_shares_status = 'verified' ORDER BY created_at DESC; This returns rows like: Copy aggregate_key ---------------------------------------------------------------------- \x03d8c4344861fc7590fd812c24884a3bfd9374d8ba865a787ff53c9060020aa967 \x03f898f8a6ddb86dd4608dd168355ec6135fe2839222240c01942e8e7e50dd4c89 (2 rows) The most recent `aggregate_key` is the first row. 3 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#compare-with-the-on-chain-aggregate-key) Compare with the on-chain aggregate key Fetch the current aggregate pubkey from the sbtc-registry contract and compare it to the most recent `aggregate_key` from the DB query: Copy curl -s 'https://api.hiro.so/v2/contracts/call-read/SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4/sbtc-registry/get-current-aggregate-pubkey' \ -H 'content-type: application/json' --data-raw '{"sender":"SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4","arguments":[]}' | jq .result Example output: Copy "0x020000002103d8c4344861fc7590fd812c24884a3bfd9374d8ba865a787ff53c9060020aa967" Discard the prefix `0x02000000210` (Clarity encoding). The remaining hex `3d8c4344861fc7590fd812c24884a3bfd9374d8ba865a787ff53c9060020aa967` should match the first row of the PostgreSQL query (excluding `\x0` which indicates hex encoding). [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#setup-proper-access-control) Setup proper access control ------------------------------------------------------------------------------------------------------------------------------------------------------------------ * Require hardware 2FA keys for access control (e.g., YubiKey) to connect through SSH, to authenticate to AWS, and for every other relevant action. * Follow the principle of least privilege: if you don’t need access, you don’t get access; if you get access, it expires after the action is taken. circle-info Optional, but strongly recommended: Implement a "4-eyes" process (require that any activity by an individual must be reviewed or approved by a second individual) to access critical resources (e.g., deploying a new version of the sBTC signer). [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#maintain-a-strict-firewall-configuration) Maintain a strict firewall configuration -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Allow connections to your sBTC signer `listen_on` address (used for P2P communication). * Do not expose any non-essential service to the internet: use a DEFAULT DENY policy with explicit ALLOWs for necessary network traffic (such as sBTC signer P2P and SSH). [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#maintain-a-robust-secrets-management-program) Maintain a robust secrets management program ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Ensure all relevant secrets are safely managed and rotated (where possible), e.g., if someone leaves the team. [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#monitor-and-observe-your-sbtc-signer) Monitor and observe your sBTC Signer ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ * Retain at least 90 days of logs for the sBTC Signer, the Stacks node, and the Bitcoin node. * The sBTC signer can optionally expose Prometheus metrics (see `prometheus_exporter_endpoint` configuration option). circle-info You can use Prometheus metrics to monitor signer health. For example, see how Alloy can be configured to collect metrics on Grafana Cloud: ../running-a-signer/how-to-monitor-signer.md [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#provision-dedicated-downstream-components) Provision dedicated downstream components ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Run a dedicated Bitcoin node and Stacks node for your sBTC Signer. * Ensure the nodes are provisioned with the minimum hardware requirements described here: https://docs.stacks.co/guides-and-tutorials/running-a-signer#minimum-system-requirements * Nodes should be exclusively dedicated to serve the sBTC Signer. Avoid re-using them to serve other clients as that may negatively affect performance (no mock-signing, no Stacks API nodes). [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#monitor-new-software-releases) Monitor new software releases ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Stay up-to-date with new releases, patches, and security advisories for all used operating systems, software and packages. * https://www.cve.org/ is a useful resource for popular software packages. * Subscribe to security notifications from your vendors. * Join relevant messaging channels as applicable (Discord, Slack, etc.). * Exercise vulnerability management for all packages. * Apply updates promptly, especially those addressing security vulnerabilities. * Use inventory and patch management software, if available. [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#ensure-redundancy-in-operations) Ensure redundancy in operations -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Ensure that multiple, trusted system administrators can manage and maintain your sBTC Signer instance. * Where feasible, system administrators should span different time zones. * Document your operations procedures and ensure that relevant personnel have access to them. [PreviousRun a sBTC Signerchevron-left](https://docs.stacks.co/operate/run-a-sbtc-signer) [NextSnapshot the Chainstatechevron-right](https://docs.stacks.co/operate/snapshot-the-chainstate) Last updated 5 months ago Was this helpful? * [Protect your private key and have a cold-storage backup](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#protect-your-private-key-and-have-a-cold-storage-backup) * [Backup your sBTC Signer PostgreSQL DB](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#backup-your-sbtc-signer-postgresql-db) * [Verifying integrity of PostgreSQL DB backups](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#verifying-integrity-of-postgresql-db-backups) * [Setup proper access control](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#setup-proper-access-control) * [Maintain a strict firewall configuration](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#maintain-a-strict-firewall-configuration) * [Maintain a robust secrets management program](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#maintain-a-robust-secrets-management-program) * [Monitor and observe your sBTC Signer](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#monitor-and-observe-your-sbtc-signer) * [Provision dedicated downstream components](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#provision-dedicated-downstream-components) * [Monitor new software releases](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#monitor-new-software-releases) * [Ensure redundancy in operations](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer#ensure-redundancy-in-operations) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Build a STX pc | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc#description) Description A helper function that creates a post-condition for STX token transfers using the Pc builder class, ensuring exact amounts are transferred as expected. ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc#use-cases) Use Cases * Securing STX token transfers with transfer amount validation * Protecting users from unexpected token transfers * Ensuring contract interactions behave as expected ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc#key-concepts) Key Concepts * `Pc.principal()` - Specify the principal that will send tokens * `.willSendEq()` - Ensure exactly this amount is sent (also supports `willSendGte`, `willSendLte`, `willSendGt`, `willSendLt`) * `.ustx()` - Specify the token type (micro-STX) [PreviousBuild an nft pcchevron-left](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-an-nft-pc) [NextAddress Utilitieschevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities) Last updated 2 months ago Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/cryptography-and-security/build-a-stx-pc#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { broadcastTransaction, makeSTXTokenTransfer, Pc, PostConditionMode, } from "@stacks/transactions"; // Create a post-condition that ensures exactly 10 STX is sent const pc = Pc.principal("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") .willSendEq(10000000) // 10 STX in micro-STX .ustx(); const txOptions = { recipient: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5", amount: 10000000, senderKey: "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", network: "testnet", postConditions: [pc], postConditionMode: PostConditionMode.Deny, }; const transaction = await makeSTXTokenTransfer(txOptions); const broadcastResponse = await broadcastTransaction(transaction); console.log("Transaction ID:", broadcastResponse.txid); chevron-downShow all 24 lines sun-brightdesktopmoon --- # Derive principal addresses between networks | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks#description) Description Convert addresses between mainnet and testnet by extracting and reconstructing with different version bytes ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks#use-cases) Use Cases * Cross-network address verification * Building multi-network dApps * Address validation tools * Network migration utilities ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks#key-concepts) Key Concepts * **Version byte** - Indicates network and address type * **Hash bytes** - 20-byte hash of the public key * **Checksum** - Built into the c32 encoding * Version bytes: 0x16 (Mainnet SP), 0x17 (Mainnet SM), 0x1a (Testnet ST), 0x1b (Testnet SN) [PreviousConvert string to principalchevron-left](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal) [NextCreate a random burn addresschevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities/create-a-random-burn-address) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks#key-concepts) Was this helpful? sun-brightdesktopmoon Copy ;; Extract hash bytes from an address (define-read-only (get-address-hash-bytes (address principal)) (get hash-bytes (unwrap-panic (principal-destruct? address))) ) ;; Convert testnet address to mainnet (define-read-only (testnet-to-mainnet (testnet-address principal)) (let ( ;; Extract the hash bytes from testnet address (hash-bytes (get-address-hash-bytes testnet-address)) ;; Mainnet version byte (mainnet-version 0x16) ) ;; Reconstruct with mainnet version (principal-construct? mainnet-version hash-bytes) ) ) ;; Convert mainnet address to testnet (define-read-only (mainnet-to-testnet (mainnet-address principal)) (let ( ;; Extract the hash bytes from mainnet address (hash-bytes (get-address-hash-bytes mainnet-address)) ;; Testnet version byte (testnet-version 0x1a) ) ;; Reconstruct with testnet version (principal-construct? testnet-version hash-bytes) ) ) ;; Example usage (testnet-to-mainnet 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM) ;; Returns: (ok SP1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R) chevron-downShow all 34 lines sun-brightdesktopmoon --- # Helper function to restrict contract calls | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/helper-function-to-restrict-contract-calls#description) Description Implement access control to ensure functions can only be called by users, not other contracts ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/helper-function-to-restrict-contract-calls#use-cases) Use Cases * Preventing contract-to-contract reentrancy attacks * Ensuring human-initiated transactions for governance * Restricting token minting to direct user actions * Protecting admin functions from automated calls ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/helper-function-to-restrict-contract-calls#key-concepts) Key Concepts * **Standard principals** - User wallets (SP/ST addresses) * **Contract principals** - Deployed contracts (address.contract-name) * **contract-caller** - The immediate caller of the current function * **tx-sender** - The original transaction initiator [PreviousGenerate random numberchevron-left](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number) [NextExample Contractschevron-right](https://docs.stacks.co/cookbook/clarity/example-contracts) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/helper-function-to-restrict-contract-calls#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/helper-function-to-restrict-contract-calls#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/helper-function-to-restrict-contract-calls#key-concepts) Was this helpful? sun-brightdesktopmoon Copy ;; Check if caller is a standard principal (user wallet) (define-private (is-standard-principal-call) (is-none (get name (unwrap! (principal-destruct? contract-caller) false))) ) ;; Public function restricted to direct user calls (define-public (user-only-function (amount uint)) (begin (asserts! (is-standard-principal-call) (err u401)) ;; Function logic here (ok true) ) ) chevron-downShow all 13 lines sun-brightdesktopmoon --- # Fundamentos de la red | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [Mainnet y Testnetschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets) [Tokenschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/network-basics) [Billeteras y cuentaschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/wallets-and-accounts) [Sistema de Nombres de Bitcoinchevron-right](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system) [SIPschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/sips) [Especificaciones técnicaschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications) [Auditoríaschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/audits) [AnteriorProof of Transfer (PoX)chevron-left](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer) [SiguienteMainnet y Testnetschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets) Última actualización hace 1 mes ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Run a Node with Docker | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#stacks-blockchain-with-docker) Stacks Blockchain with Docker Run your own Stacks Blockchain node using [docker-composearrow-up-right](https://docs.docker.com/compose/) with just a few commands using [stacks-blockchain-dockerarrow-up-right](https://github.com/stacks-network/stacks-blockchain-docker) ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#requirements) Requirements The minimum viable requirements are listed below. While you _can_ run a node using these specs, it's _recommended_ to assign more than the minimum for better performance. * ⚠️ [docker-composearrow-up-right](https://docs.docker.com/compose/install/) version `2.2.2` or greater is **required** * **8GB memory if running only a Stacks node** * **16 GB memory if running Stacks + Bitcoin node** * **1 Vcpu** ( _minimum of 2 Vcpu is recommended_ ) * **500GB disk for Stacks node** * **1TB disk space for Bitcoin node** circle-exclamation MacOS with an ARM (M-series chip) processor is NOT recommended The way Docker for Mac on an Arm CPU is designed makes the I/O incredibly slow, and blockchains are _**very**_ heavy on I/O. This only seems to affect MacOS with the M-series chip, other Arm based systems like Raspberry Pi work as expected. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#storage) Storage A fully synced Stacks node can use significant disk space and will continue to grow. If your boot drive doesn't have enough room, mount a dedicated disk and symlink the `persistent-data` directory before starting the node: The Docker volumes write to `persistent-data//`, so the symlink redirects all chainstate, database, and event data to the external disk transparently. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#quickstart) Quickstart The `` placeholder used below can be replaced with one of: * mainnet * testnet * mocknet 1 **Clone the repository** Clone the stacks-blockchain-docker repository locally and change into the directory: 2 **Start the services** Start the docker-compose services for the chosen network: circle-info With an optional HTTP proxy on port 80: ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#accessing-the-services) Accessing the services circle-info For networks other than `mocknet`, downloading the initial headers can take several minutes. Until the headers are downloaded, the `/v2/info` endpoints won't return any data. Follow the logs to track the sync progress: stacks-blockchain: * Ports `20443-20444` are exposed on `localhost` stacks-blockchain-api: * Port `3999` is exposed on `localhost` proxy: * Port `80` is exposed on `localhost` ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#upgrades) Upgrades circle-exclamation For schema-breaking upgrades to running instances of this repo, you'll need to [run an event-replayarrow-up-right](https://github.com/stacks-network/stacks-blockchain-docker/blob/master/docs/upgrade.md) . [PreviousRun a Nodechevron-left](https://docs.stacks.co/operate/run-a-node) [NextRun a Node with Digital Oceanchevron-right](https://docs.stacks.co/operate/run-a-node/run-a-node-with-digital-ocean) Last updated 1 month ago Was this helpful? * [Stacks Blockchain with Docker](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#stacks-blockchain-with-docker) * [Requirements](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#requirements) * [Storage](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#storage) * [Quickstart](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#quickstart) * [Accessing the services](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#accessing-the-services) * [Upgrades](https://docs.stacks.co/operate/run-a-node/run-a-node-with-docker#upgrades) Was this helpful? sun-brightdesktopmoon Point persistent-data to an external disk Copy # If persistent-data already exists, move its contents first mv persistent-data/mainnet /mnt/stacks-data/mainnet rmdir persistent-data # Create the symlink ln -s /mnt/stacks-data persistent-data Clone repository Copy git clone https://github.com/stacks-network/stacks-blockchain-docker && cd stacks-blockchain-docker Start services Copy ./manage.sh -n -a start Start with proxy Copy ./manage.sh -n -a start -f proxy Follow logs Copy ./manage.sh -n -a logs Check stacks-blockchain /v2/info Copy curl -sL localhost:20443/v2/info | jq -r Check stacks-blockchain-api Copy curl -sL localhost:3999 | jq -r Check proxy Copy curl -sL localhost/v2/info | jq -r curl -sL localhost | jq -r sun-brightdesktopmoon --- # Contract post-conditions | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Source: [SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.xbtc-sbtc-swap-v2arrow-up-right](https://explorer.hiro.so/txid/SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.xbtc-sbtc-swap-v2) ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions#description) Description The `as-contract?` function resolves the expression caller to the principal of the current contract. Most importantly it allows a contract to protect its own assets during the execution of the expression with a set of specified allowances. ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions#use-cases) Use Cases * A contract invoking a body expression that potentially may have unwanted and unexpected asset transfers. * Protecting a contract invoking another external contract's function. ### [hashtag](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions#key-concepts) Key Concepts * **Contract caller context -** Switches the current context's `tx-sender` and `contract-caller` values to the contract's principal and executes the body expressions within that context, then checks the asset outflows from the contract against the granted allowances, in declaration order. * **Clarity post-conditions** - Accepts a set of allowances, defined using `with-stx`, `with-ft`, `with-nft`, and `with-stacking`, which selectively grant outflow allowances from the contract's assets. [PreviousCreate sha256 hash claritychevron-left](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/create-sha256-hash-clarity) [NextGenerate random numberchevron-right](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number) Last updated 2 months ago Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/contract-post-conditions#key-concepts) Was this helpful? sun-brightdesktopmoon .xbtc-sbtc-swap-v2 Copy ;; --snip-- (define-private (transfer-sbtc-to (amount uint) (sbtc-recipient principal) ) (as-contract? ((with-ft 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token "sbtc-token" amount )) (try! (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token transfer amount current-contract sbtc-recipient none )) ) ) ;; --snip-- chevron-downShow all 17 lines sun-brightdesktopmoon --- # Run a sBTC Signer | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F4065274862-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F4cpTb2lbw0LAOuMHrvhA%252Fuploads%252FbNxUw0dx5PbQ03RJvvXU%252Fsbtc-signers-cover.png%3Falt%3Dmedia%26token%3Da5bbf286-de5b-49ef-a1d9-7d2ae61755a7&width=768&dpr=3&quality=100&sign=c294e6ae&sv=2) circle-info This documentation provides guidelines, best-practices and recommendations for running an sBTC Signer. Review it and adapt it to your infrastructure policy before deploying it. circle-exclamation Each sBTC signer will control a set of signing shares used to sign transactions on both Bitcoin and Stacks. Such shares will be encrypted by using the `private_key` specified in the Signer's config and stored in the PostgreSQL database attached to each signer. It is of the utmost importance to follow the recommendations below. 1 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#prevent-unauthorized-access-to-signer-infrastructure) Prevent unauthorized access to signer infrastructure Prevent unauthorized access to the sBTC Signer infrastructure (the signer itself, its private key, and the associated PostgreSQL database). 2 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#keep-an-offline-secure-backup-of-the-signer-private-key) Keep an offline, secure backup of the Signer private key Keep an offline, secure backup of the sBTC Signer private key. 3 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#regularly-backup-postgresql-database) Regularly backup PostgreSQL database Regularly backup the PostgreSQL database and store it in a secure location. See [here](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer) for additional best practices to run an sBTC signer. [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#minimum-system-requirements) Minimum System Requirements ------------------------------------------------------------------------------------------------------------------------ Below are the **minimum required specs** to be able to run a sBTC signer. * 2 CPU * 4GB memory * 50GB storage Note that these are in _addition_ to the hardware requirements for running a Stacks node and Bitcoin node outlined in the [How to Run a Signer doc](https://docs.stacks.co/operate/run-a-signer) . [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#connection-diagram) Connection diagram ------------------------------------------------------------------------------------------------------ ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fstacks-network%2Fdocs%2Fblob%2Fmaster%2Fdocs%2Foperate%2F.gitbook%2Fassets%2Fimage%2520%288%29.png&width=768&dpr=3&quality=100&sign=dbb4ff62&sv=2) [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#configure-your-bitcoin-node) Configure your Bitcoin node ------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#minimum-version) Minimum version You will need `bitcoind` version 25 or higher. ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#settings) Settings Your Bitcoin node must include these settings for sBTC signer operation: * `txindex=1`: Transaction indexing must be enabled * `server=1`: RPC server must be enabled ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#rpc-based-block-detection) RPC-Based Block Detection Starting with sBTC v1.1.0, the signer uses RPC polling instead of ZeroMQ for block detection. The signer connects to Bitcoin Core via RPC and polls for new bitcoin blocks. This process works as follows: 1 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#bitcoin-core-validates-a-new-block) Bitcoin Core validates a new block Bitcoin Core validates a new block. 2 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#signer-detects-the-block-via-rpc-polling) Signer detects the block via RPC polling Signer detects the block via RPC polling. 3 #### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#signer-processes-relevant-sbtc-transactions) Signer processes relevant sBTC transactions Signer processes relevant sBTC transactions. ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#example) Example [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#configure-your-stacks-node) Configure your Stacks node ---------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#minimum-version-1) Minimum version Please ensure your Stacks version is up-to-date (using the latest release). ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#event-observer) Event observer You will need to add a _new_ event observer that relays information from the sBTC smart contracts to the sBTC signer: ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#reference-configuration) Reference configuration See [herearrow-up-right](https://github.com/stacks-network/sbtc/blob/main/docker/mainnet/nodes/stacks/Config.toml.in) . [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#configure-your-sbtc-signer) Configure your sBTC Signer ---------------------------------------------------------------------------------------------------------------------- The signer configuration file (`signer-config.toml`) defines the signer's operation parameters. The configuration sections include: ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#blocklist-client-settings) Blocklist Client Settings ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#bitcoin-connection-settings) Bitcoin Connection Settings Defines how the signer connects to Bitcoin Core: ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#core-signer-parameters) Core Signer Parameters Defines the signer's identity and network participation: ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#p2p-network-configuration) P2P Network Configuration Controls how the signer communicates with other network participants: The signer operates on port 4122 by default and supports both TCP and QUIC protocols for peer communication. The signer will attempt QUIC connections first for improved performance, automatically falling back to TCP if QUIC is unavailable or blocked on the network. ### [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#reference-configuration-1) Reference configuration See [herearrow-up-right](https://github.com/stacks-network/sbtc/blob/main/docker/mainnet/sbtc-signer/signer-config.toml.in) . [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#set-up-your-containers) Set up your containers -------------------------------------------------------------------------------------------------------------- See [herearrow-up-right](https://github.com/stacks-network/sbtc/blob/main/docker/mainnet/docker-compose.yml) for a Docker Compose including all the required components. circle-exclamation When deploying with Docker, always use [immutable image tagsarrow-up-right](https://docs.docker.com/reference/cli/docker/image/pull/#pull-an-image-by-digest-immutable-identifier) - the image digests are provided below. Verify the attestation of these images using this [guidearrow-up-right](https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations/using-artifact-attestations-to-establish-provenance-for-builds#verifying-artifact-attestations-with-the-github-cli) . We publish our images on [GitHub Container Registryarrow-up-right](https://github.com/stacks-sbtc/sbtc/pkgs/container/sbtc) . [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#monitoring) Monitoring -------------------------------------------------------------------------------------- Monitoring Details TBD [hashtag](https://docs.stacks.co/operate/run-a-sbtc-signer#troubleshooting) Troubleshooting ------------------------------------------------------------------------------------------------ Troubleshooting Guide TBD [PreviousOpSec Best Practiceschevron-left](https://docs.stacks.co/operate/run-a-signer/opsec-best-practices) [NextBest Practices for Running a sBTC Signerchevron-right](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer) Last updated 1 month ago Was this helpful? * [Minimum System Requirements](https://docs.stacks.co/operate/run-a-sbtc-signer#minimum-system-requirements) * [Connection diagram](https://docs.stacks.co/operate/run-a-sbtc-signer#connection-diagram) * [Configure your Bitcoin node](https://docs.stacks.co/operate/run-a-sbtc-signer#configure-your-bitcoin-node) * [Minimum version](https://docs.stacks.co/operate/run-a-sbtc-signer#minimum-version) * [Settings](https://docs.stacks.co/operate/run-a-sbtc-signer#settings) * [RPC-Based Block Detection](https://docs.stacks.co/operate/run-a-sbtc-signer#rpc-based-block-detection) * [Example](https://docs.stacks.co/operate/run-a-sbtc-signer#example) * [Configure your Stacks node](https://docs.stacks.co/operate/run-a-sbtc-signer#configure-your-stacks-node) * [Minimum version](https://docs.stacks.co/operate/run-a-sbtc-signer#minimum-version-1) * [Event observer](https://docs.stacks.co/operate/run-a-sbtc-signer#event-observer) * [Reference configuration](https://docs.stacks.co/operate/run-a-sbtc-signer#reference-configuration) * [Configure your sBTC Signer](https://docs.stacks.co/operate/run-a-sbtc-signer#configure-your-sbtc-signer) * [Blocklist Client Settings](https://docs.stacks.co/operate/run-a-sbtc-signer#blocklist-client-settings) * [Bitcoin Connection Settings](https://docs.stacks.co/operate/run-a-sbtc-signer#bitcoin-connection-settings) * [Core Signer Parameters](https://docs.stacks.co/operate/run-a-sbtc-signer#core-signer-parameters) * [P2P Network Configuration](https://docs.stacks.co/operate/run-a-sbtc-signer#p2p-network-configuration) * [Reference configuration](https://docs.stacks.co/operate/run-a-sbtc-signer#reference-configuration-1) * [Set up your containers](https://docs.stacks.co/operate/run-a-sbtc-signer#set-up-your-containers) * [Monitoring](https://docs.stacks.co/operate/run-a-sbtc-signer#monitoring) * [Troubleshooting](https://docs.stacks.co/operate/run-a-sbtc-signer#troubleshooting) Was this helpful? sun-brightdesktopmoon Copy bitcoind \ -server \ -datadir=${BITCOIN_DATA} \ -rpcbind=0.0.0.0 \ -rpcuser=${BITCOIN_RPC_USERNAME} \ -rpcpassword=${BITCOIN_RPC_PASSWORD} \ -rpcport=${BITCOIN_RPC_PORT} \ -rpcallowip=0.0.0.0/0 \ -rpcallowip=::/0 \ -txindex Copy [[events_observer]] endpoint = "sbtc-signer:8801" events_keys = [\ "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-registry::print",\ ] Copy [blocklist_client] endpoint = "http://blocklist-client:3032" Copy [bitcoin] rpc_endpoints = ["http://user:pass@your-bitcoin-node:8332"] # Note: block_hash_stream_endpoints are no longer used as of v1.1.0 # The signer now uses RPC polling for block detection Copy [signer] private_key = "your-private-key" # 32 or 33-byte hex format network = "mainnet" deployer = "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4" Copy [signer.p2p] listen_on = ["tcp://0.0.0.0:4122"] sun-brightdesktopmoon --- # Welcome to the Cookbook | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2420193188-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FuholC0CdufHxYs050O3V%252Fuploads%252FNKfYBS961GghukK4UJEh%252Fstacksdocs-cookbook.png%3Falt%3Dmedia%26token%3De728dd97-738d-4b12-a89b-0f89d7a4f60f&width=768&dpr=3&quality=100&sign=5ebeb7e3&sv=2) The Cookbook contains detailed coding snippets known as recipes. Recipes are focused and reusable. They are designed to be referenced, copied, and adapted. They are not meant to be read end-to-end. > _Prepped snippets for when you just need the ingredients._ chevron-right**Who is the Cookbook for?**[hashtag](https://docs.stacks.co/cookbook#who-is-the-cookbook-for) For developers beyond the exploratory phase who require a specific, concrete code solution quickly for an existing application.This section provides focused, reusable Clarity and Stacks.js code snippets that solve common problems or demonstrate specific patterns—designed to be referenced, copied, and adapted rather than read end-to-end. circle-info If you’re still learning core concepts, start with the main guides in the Build section. Come back here when you know what you’re trying to build. ### [hashtag](https://docs.stacks.co/cookbook#what-youll-find-here) What you’ll find here * Minimal, working **Clarity** snippets. * Minimal, working **Stacks.js** snippets. * Small patterns you can reuse across apps and contracts. * Notes on gotchas, tradeoffs, and safe defaults. ### [hashtag](https://docs.stacks.co/cookbook#how-to-use-the-recipes) How to use the recipes 1. Pick the closest recipe to your goal. 2. Copy the snippet into your project. 3. Replace placeholders like `SP…`, contract names, and network settings. 4. Add your app’s error handling and UX. circle-exclamation Recipes optimize for clarity and speed. They may omit production concerns like retries, logging, and input validation. ### [hashtag](https://docs.stacks.co/cookbook#jump-right-in) Jump right in [](https://docs.stacks.co/cookbook/stacks.js/transaction-building) Recipes **Stacks.js** Transactions, reads, auth, and app integration. Browse [Stacks.js](https://docs.stacks.co/cookbook/stacks.js/transaction-building) [](https://docs.stacks.co/cookbook/clarity/address-utilities) Recipes **Clarity** Common contract patterns and implementation snippets. Browse [Clarity](https://docs.stacks.co/cookbook/clarity/address-utilities) [](https://docs.stacks.co/cookbook/clarity/example-contracts) Recipes **Example Contracts** Curated examples of notable mainnet contracts and reference implementations. Browse [Example Contracts](https://docs.stacks.co/cookbook/clarity/example-contracts) ### [hashtag](https://docs.stacks.co/cookbook#conventions-and-placeholders) Conventions and placeholders * Addresses use `SP…` (mainnet) and `ST…` (testnet) unless noted. * Contract identifiers use `SP….contract-name`. * Replace `NETWORK` / `STACKS_API_URL` with your environment. * Prefer explicit versions in your app. chevron-rightWant to contribute a recipe?[hashtag](https://docs.stacks.co/cookbook#want-to-contribute-a-recipe) Head to the [Stacks Docs Github repoarrow-up-right](https://github.com/stacks-network/docs) and submit a PR. Add a new page under the closest section. Keep it short and sweet. Use the same structure: **Title**, **Byline**, **Code**, **Description**, **Use Cases**, **Key Concepts**. Be sure to also include a byline of your Github or Twitter handle at the top of the page. [NextTransaction Buildingchevron-right](https://docs.stacks.co/cookbook/stacks.js/transaction-building) Last updated 2 months ago Was this helpful? * [What you’ll find here](https://docs.stacks.co/cookbook#what-youll-find-here) * [How to use the recipes](https://docs.stacks.co/cookbook#how-to-use-the-recipes) * [Jump right in](https://docs.stacks.co/cookbook#jump-right-in) * [Conventions and placeholders](https://docs.stacks.co/cookbook#conventions-and-placeholders) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Convert string to principal | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal#description) Description Parse string addresses into principal types using c32 decoding in Clarity ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal#use-cases) Use Cases * Parsing user input addresses in contracts * Converting stored string addresses to principals * Validating address formats before use * Building dynamic contract calls with string inputs ### [hashtag](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal#key-concepts) Key Concepts * **c32 alphabet** - `0123456789ABCDEFGHJKMNPQRSTVWXYZ` (no I, L, O, U) * **Checksum** - Last 4 bytes verify address integrity * **Version byte** - First character indicates address type * **Contract addresses** - Include `.contract-name` suffix [PreviousConvert BTC to STX addresschevron-left](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-btc-to-stx-address) [NextDerive principal addresses between networkschevron-right](https://docs.stacks.co/cookbook/clarity/address-utilities/derive-principal-addresses-between-networks) Was this helpful? * [Description](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal#description) * [Use Cases](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/address-utilities/convert-string-to-principal#key-concepts) Was this helpful? sun-brightdesktopmoon Copy (define-read-only (string-to-principal? (input (string-ascii 82))) (let ( ;; Find the dot separator for contract addresses (dot (default-to (len input) (index-of? input "."))) ;; Extract address part (skip first char which is version) (addr (unwrap! (slice? input u1 dot) ERR_INVALID_LENGTH)) ;; Decode c32 characters to numbers (addressc32 (map unwrap-panic-uint (filter is-some-uint (map c32-index addr)))) ;; Validate all characters are valid c32 (isValidChars (asserts! (is-eq (len addr) (len addressc32)) ERR_INVALID_CHAR)) ;; Extract version and decode address data (version (unwrap-panic (element-at? addressc32 u0))) (decoded (decode-address addressc32)) ;; Verify checksum (checksum (verify-checksum decoded version)) ) ;; Construct principal with or without contract name (match (slice? input (+ u1 dot) (len input)) contract (principal-construct? (to-byte version) (get-address-bytes decoded) contract) (principal-construct? (to-byte version) (get-address-bytes decoded)) ) ) ) ;; Example usage (string-to-principal? "SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7") ;; Returns (some SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7) (string-to-principal? "SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7.my-contract") ;; Returns (some SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7.my-contract) chevron-downShow all 30 lines sun-brightdesktopmoon --- # Key and Address Rotation | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close This guide covers how and when to rotate your signer key, Bitcoin reward address, and pool operator key. Understanding the differences between these keys and the constraints around rotating them is important for long-term operations. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#definitions) Definitions ------------------------------------------------------------------------------------------------------------ * **Signer key**: the cryptographic key used by the signer software to participate in block validation and DKG. Configured as `stacks_private_key` in the signer configuration. * **Bitcoin reward address (PoX address)**: the BTC address where stacking rewards are sent. * **Pool operator key**: the STX address used by a pool operator to make stacking transactions (`delegate-stack-stx`, `stack-aggregation-commit-indexed`, etc.). This is separate from the signer key. circle-info The signer key and pool operator key may belong to the same entity, but they should be **separate keys**. See the pool operator key section below for why. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#rotate-a-signer-key) Rotate a Signer Key ---------------------------------------------------------------------------------------------------------------------------- You can rotate your signer key without needing to stop stacking. This is done through specific stacking function calls that accept a new signer key as a parameter. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#solo-stackers) Solo stackers When calling `stack-extend`, you can pass a new `signer-key`. The new key will be used for the extended cycles. You will also need a new [signer signature](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) generated with the new key. When calling `stack-increase`, you can also pass a new `signer-key`. circle-exclamation You cannot rotate your signer key mid-cycle. The rotation takes effect in the next cycle when the new stacking parameters are applied. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#pool-operators) Pool operators When calling `stack-aggregation-commit-indexed` for a new reward cycle, you can pass a new `signer-key`. This associates the new key with the pool for that cycle. circle-info The pox-4 contract is designed to support rotating the signer key without needing your stackers to un-stack and re-stack. This is one of the key advantages of keeping the signer key separate from the pool operator key. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#after-rotating) After rotating After rotating your signer key, you must also update your signer software configuration to use the new `stacks_private_key`. Restart the signer software to apply the change. Make sure the new signer is running before the prepare phase of the cycle where the new key takes effect. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#rotate-a-bitcoin-reward-address) Rotate a Bitcoin Reward Address ---------------------------------------------------------------------------------------------------------------------------------------------------- You can change the Bitcoin address where you receive stacking rewards when making certain stacking function calls. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#solo-stackers-1) Solo stackers * `**stack-extend**`: accepts a `pox-addr` parameter. You can pass a new BTC address, and rewards for the extended cycles will be sent there. * `**stack-stx**`: when starting a new stacking position (after a previous one has unlocked), you can specify any BTC address. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#pool-operators-1) Pool operators * `**stack-aggregation-commit-indexed**`: accepts a `pox-addr` parameter. You can use a different BTC address for each reward cycle you commit to. * `**delegate-stack-stx**`: accepts a `pox-addr` parameter. If the delegator specified a required BTC address in their `delegate-stx` call, you must use that address. circle-info Changing the BTC address does not affect previously committed reward cycles. The new address only applies to newly committed cycles. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#pool-operator-key) Pool Operator Key ------------------------------------------------------------------------------------------------------------------------ The pool operator key (the STX address used for making stacking transactions) **cannot be rotated** without delegators needing to un-stack and re-delegate to the new address. This is because the `delegate-stx` function records the specific pool operator address that the delegator authorizes. If the pool operator changes their address, all existing delegations are no longer valid for the new address. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#why-this-matters) Why this matters If your pool operator key is compromised, every delegator must: 1. Wait for their current lock period to expire 2. Call `revoke-delegate-stx` to cancel the old delegation 3. Call `delegate-stx` with the new pool operator address This is disruptive and time-consuming, which is why it is **strongly recommended** to keep the pool operator key separate from the signer key. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#recommendations) Recommendations 1 **Use separate keys** Keep your signer key and pool operator key separate. The signer key can be rotated through stacking transactions, while the pool operator key should be treated as a long-lived identity. 2 **Secure the pool operator key** Since the pool operator key is harder to rotate, secure it with a hardware wallet or other cold-storage mechanism. The benefit of a separate pool operator key is that it can easily be used in existing wallets, including hardware wallets like Ledger. 3 **Limit signer key exposure** The signer key is stored on a server running the signer software. Rotate it periodically and follow the [OpSec Best Practices](https://docs.stacks.co/operate/run-a-signer/opsec-best-practices) to minimize the risk of compromise. [PreviousGenerate a Signer Signaturechevron-left](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) Last updated 12 days ago Was this helpful? * [Definitions](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#definitions) * [Rotate a Signer Key](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#rotate-a-signer-key) * [Solo stackers](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#solo-stackers) * [Pool operators](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#pool-operators) * [After rotating](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#after-rotating) * [Rotate a Bitcoin Reward Address](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#rotate-a-bitcoin-reward-address) * [Solo stackers](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#solo-stackers-1) * [Pool operators](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#pool-operators-1) * [Pool Operator Key](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#pool-operator-key) * [Why this matters](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#why-this-matters) * [Recommendations](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation#recommendations) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Best Practices to Run a Signer | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close circle-info **Intended audience**: solo Stackers or Stacking pool operators. The following best practices suggest how to create a resilient setup for running your Signer. circle-info tl;dr: avoid single point of failures, introduce redundancy, monitor things. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#monitor-your-signer-and-collect-logs) Monitor your Signer and collect logs * See [here](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer) on how to set up monitoring. * Retain at least 1 week of logs for both the Signer and the Stacks node. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#downstream-components) Downstream components * Run a dedicated Bitcoin node and Stacks node per Signer. * Ensure the nodes are provisioned with the minimum hardware requirements described [herearrow-up-right](https://docs.stacks.co/guides-and-tutorials/running-a-signer#minimum-system-requirements) . * Nodes should be exclusively dedicated to serve the Signer. Avoid re-using them to serve other clients as that may negatively affect performance (no mock-signing, no Stacks API nodes). * If running dedicated nodes is not possible, then ensure that the Bitcoin / Stacks nodes do not become single points of failure for multiple signers depending on them. * Introduce redundancy, load balancing, rely on a robust Bitcoin RPC provider, etc. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#split-voting-power-across-multiple-signers) Split voting power across multiple Signers * Distribute your voting power across multiple, distinct Signer public keys to mitigate the risk of loss or downtime from a single compromised key. * Each Signer should also limit voting power to a maximum amount and invite Stackers to use a different Signer when the limit is reached. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#monitor-new-software-releases) Monitor new software releases * Stay up-to-date with new releases, patches, and security advisories (e.g., GitHub, mailing lists, Discord). * Apply updates as quickly as possible, especially those addressing a security vulnerability. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#upgrade-procedures) Upgrade procedures 1 **Test one instance first** Upgrade one Signer instance at a time. Test the update on a single instance and verify functionality before proceeding to others. 2 **Roll out gradually** If the test is successful, proceed to upgrade the remaining instances one-by-one. 3 **Minimize downtime** While a Signer is offline for upgrades, it won't sign any blocks. Ensure that the downtime is as short as possible. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#diversified-hosting) Diversified hosting * Use different provider / configuration where feasible (e.g., a self-hosted instance and one in the cloud, or in two different data center regions, etc.). * Ensure each host has redundant power supply and network connectivity. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#fall-back-deployments) Fall-back deployments * Deploy additional Stacks nodes and Bitcoin nodes to be used as fall-back. * Use the same configuration as your active instances. * For the Stacks node, comment out the `event_observer` section. * Prepare a backup Signer (same configuration) to be quickly activated, but do not run it. * At all times, there should be exactly one Signer instance running for each Signer private key. * These fall-back instances should be hosted on separate physical hosts (see diversified hosting) from the instances usually active in operations (serving each Signer). To switch to the fall-back configuration quickly if an active instance fails, follow these steps: 1 **Run the backup Signer** Start the prepared backup Signer instance. 2 **Enable event observer** Enable the `event_observer` section of the Stacks node configuration. 3 **Restart the node** Restart the Stacks node so it runs with the enabled `event_observer`. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#redundancy-in-operations) Redundancy in operations * Ensure that multiple, trusted users can manage and maintain signer instances. * Where feasible, users should span different timezones. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#auto-restart-configuration) Auto-restart configuration Configure your signer and Stacks node to automatically restart on failure to minimize downtime. #### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#docker) Docker Use the `--restart` flag when running containers to enable automatic restarts: The `unless-stopped` policy restarts the container automatically if it crashes or the host reboots, but not if you explicitly stop it. Apply the same policy to your Stacks node container. #### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#systemd) systemd If running as a binary, create a systemd service unit to handle automatic restarts. Example for the signer: Example for the Stacks node: Enable and start the services: Check their status at any time: View logs with: ### [hashtag](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#backup-signer-keys-in-cold-storage) Backup signer keys in cold-storage * Keep an offline, secure backup of all Signer private keys (e.g., hardware security modules or encrypted storage devices). [PreviousHow to Monitor Signerchevron-left](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer) [NextOpSec Best Practiceschevron-right](https://docs.stacks.co/operate/run-a-signer/opsec-best-practices) Last updated 12 days ago Was this helpful? * [Monitor your Signer and collect logs](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#monitor-your-signer-and-collect-logs) * [Downstream components](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#downstream-components) * [Split voting power across multiple Signers](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#split-voting-power-across-multiple-signers) * [Monitor new software releases](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#monitor-new-software-releases) * [Upgrade procedures](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#upgrade-procedures) * [Diversified hosting](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#diversified-hosting) * [Fall-back deployments](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#fall-back-deployments) * [Redundancy in operations](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#redundancy-in-operations) * [Auto-restart configuration](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#auto-restart-configuration) * [Backup signer keys in cold-storage](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer#backup-signer-keys-in-cold-storage) Was this helpful? sun-brightdesktopmoon Copy docker run -d \ --restart unless-stopped \ -v $STX_SIGNER_CONFIG:/config.toml \ -v $STX_SIGNER_DATA:/var/stacks \ -p 30000:30000 \ -e RUST_BACKTRACE=full \ -e BLOCKSTACK_DEBUG=0 \ --name stacks-signer \ $IMG:$VER \ stacks-signer run \ --config /config.toml /etc/systemd/system/stacks-signer.service Copy [Unit] Description=Stacks Signer After=network.target StartLimitBurst=3 StartLimitIntervalSec=300 ConditionFileIsExecutable=/usr/local/bin/stacks-signer ConditionPathExists=/etc/stacks/signer ConditionFileNotEmpty=/etc/stacks/signer/signer-config.toml [Service] ExecStart=/usr/local/bin/stacks-signer run --config /etc/stacks/signer/signer-config.toml User=stacks-signer Group=stacks-signer Type=simple Restart=on-failure RestartSec=10 TimeoutStopSec=600 KillSignal=SIGTERM [Install] WantedBy=multi-user.target /etc/systemd/system/stacks-node.service Copy [Unit] Description=Stacks Node After=network.target StartLimitBurst=3 StartLimitIntervalSec=300 ConditionFileIsExecutable=/usr/local/bin/stacks-node ConditionFileNotEmpty=/etc/stacks/node/node-config.toml [Service] ExecStart=/usr/local/bin/stacks-node start --config /etc/stacks/node/node-config.toml User=stacks-node Group=stacks-node Type=simple Restart=on-failure RestartSec=10 TimeoutStopSec=600 KillSignal=SIGTERM [Install] WantedBy=multi-user.target Copy 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 Copy sudo systemctl status stacks-signer.service sudo systemctl status stacks-node.service Copy journalctl -xefu stacks-signer journalctl -xefu stacks-node sun-brightdesktopmoon --- # Build an unsigned tx | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx#description) Description Create unsigned transactions for hardware wallets or multi-signature scenarios ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx#use-cases) Use Cases * Hardware wallet integration (Ledger, Trezor) * Multi-signature wallet transactions * Offline transaction signing * Secure key management systems ### [hashtag](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx#key-concepts) Key Concepts * **Public key only** - No private key needed for creation * **External signing** - Sign with hardware wallet or secure enclave * **Serialization** - Can be transported and signed elsewhere * Unsigned transactions separate transaction creation from signing [PreviousTransaction Buildingchevron-left](https://docs.stacks.co/cookbook/stacks.js/transaction-building) [NextCreate a sponsored txchevron-right](https://docs.stacks.co/cookbook/stacks.js/transaction-building/create-a-sponsored-tx) Last updated 2 months ago Was this helpful? * [Description](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx#description) * [Use Cases](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx#use-cases) * [Key Concepts](https://docs.stacks.co/cookbook/stacks.js/transaction-building/build-an-unsigned-tx#key-concepts) Was this helpful? sun-brightdesktopmoon Copy import { getPublicKeyFromPrivate } from "@stacks/encryption"; import { makeUnsignedSTXTokenTransfer, type StacksTransactionWire, type SingleSigSpendingCondition, createMessageSignature } from "@stacks/transactions"; // Get public key from private key const privateKey = "753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601"; const publicKey = getPublicKeyFromPrivate(privateKey); const recipient = process.env.STACKS_RECIPIENT_ADDRESS!; // Build unsigned STX transfer let transaction: StacksTransactionWire = await makeUnsignedSTXTokenTransfer({ recipient, amount: 300, publicKey: pubKey, numSignatures: 1, network: "mainnet", }); let sighash = transaction.signBegin() let preSignSigHash: string = sigHashPreSign( sigHash, transaction.auth.authType, transaction.auth.spendingCondition.fee, transaction.auth.spendingCondition.nonce, ); // Unsigned transaction payload ready for external signing ECDSA over secp256k1 console.log("Unsigned transaction payload to sign:", preSignSigHash); // Signing should return a recoverable signature (in VRS order). // let signature // r and s values to be returned in hex format, may need to padStart r and s values // v should be "00" for Stacks but a returned "01" also works const nextSig = `${signature!.v}${signature!.r.padStart(64, "0")}${signature!.s.padStart(64, "0")}`; // Reassign signature field in transaction with `nextSig` let spendingCondition = transaction.auth.spendingCondition as SingleSigSpendingCondition; spendingCondition.signature = createMessageSignature(nextSig); // `transaction` is now ready to be broadcasted console.log(transaction) chevron-downShow all 47 lines sun-brightdesktopmoon --- # Snapshot the Chainstate | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F4065274862-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F4cpTb2lbw0LAOuMHrvhA%252Fuploads%252F7WUPnrF9zKU02dQ07DHW%252Fsnapshot-chainstate.png%3Falt%3Dmedia%26token%3D73664b09-a386-4cbc-98c6-6f9ccbbf7e3f&width=768&dpr=3&quality=100&sign=ebbd745f&sv=2) circle-info **Intended audience**: Solo Stackers, Stacking pool operators, and node operators who need to create reliable chainstate backups. Regular snapshots of your Stacks chainstate help you recover quickly when things go wrong. This guide shows you how to create and manage chainstate snapshots properly. circle-exclamation **Critical**: Always shut down your Stacks node properly before creating a snapshot. Creating snapshots while the node is running will result in corrupted chainstate data. ### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#shutdown-procedure) Shutdown Procedure To produce a valid chainstate backup, the node should be stopped gracefully before making a copy. The following steps will correctly shutdown the Stacks node: 1 #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#check-node-status-before-shutdown) Check node status before shutdown 2 #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#initiate-graceful-shutdown) Initiate graceful shutdown * For Docker: `docker stop stacks-node` (allows at least 10 seconds for graceful shutdown) * For systemd: `systemctl stop stacks-node` * For manual processes: 3 #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#verify-complete-shutdown) Verify complete shutdown ### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#overview-of-snapshot-methods) Overview of Snapshot Methods There are two primary approaches for creating Stacks chainstate snapshots: 1. **File-based snapshots** - compress up the chainstate folder 2. **Volume snapshots** - snapshot the entire disk/volume Each method has its advantages depending on your infrastructure setup and recovery requirements. ### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#file-based-snapshots) File-Based Snapshots This method involves compressing the chainstate directory and storing it locally, or uploading to a cloud storage service. #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#steps-see-example-automation-code-section-below) Steps (see [Example Automation Code section](https://docs.stacks.co/operate/snapshot-the-chainstate#example-automation-code) below) 1. **Stop the Stacks node gracefully** 2. **Create compressed archive** 3. **Upload to cloud storage or save it locally** 4. **Restart the Stacks node** ### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#volume-based-snapshots) Volume-Based Snapshots This method creates block-level snapshots of the entire storage volume containing the chainstate. Different filesystems have different tools: * **ZFS**: Use `zfs snapshot` - [OpenZFS documentationarrow-up-right](https://openzfs.github.io/openzfs-docs/man/v2.3/8/zfs-snapshot.8.html) * **XFS**: Use `xfsdump` - [XFS documentationarrow-up-right](https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/storage_administration_guide/xfsbackuprestore) * **ext4**: Use LVM snapshots - [LVM guidearrow-up-right](https://kerneltalks.com/disk-management/how-to-guide-lvm-snapshot/) You can also use cloud provider snapshot tools (AWS EBS, Azure Disk, GCP Persistent Disk). #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#steps) Steps 1. **Stop the Stacks node gracefully** 2. **Create volume snapshot** using ZFS or cloud provider tools 3. **Restart the Stacks node** ### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#how-to-restore) How to Restore After restoring the chainstate, you can check for corruption by waiting for a few blocks to download and ensuring the node syncs correctly. #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#from-file-snapshots) From File Snapshots 1. Stop the Stacks node 2. Download and extract the snapshot 3. Replace the chainstate directory 4. Restart the node #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#from-volume-snapshots) From Volume Snapshots 1. Stop the Stacks node 2. Create a new volume from the snapshot 3. Attach the volume to your instance 4. Update mount points if necessary 5. Restart the node ### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#example-automation-code) Example Automation Code Here's a simple script that handles both file and volume snapshots on AWS. #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#how-to-use) How to Use 1. **Edit the variables** at the top of the script for your setup 2. **Make it executable**: `chmod +x snapshot.sh` 3. **Run it**: `./snapshot.sh` 4. **Schedule it with cron** for daily backups: #### [hashtag](https://docs.stacks.co/operate/snapshot-the-chainstate#what-you-need) What You Need * AWS CLI set up with the right permissions * `pzstd` installed (comes with the zstd package) [PreviousBest Practices for Running a sBTC Signerchevron-left](https://docs.stacks.co/operate/run-a-sbtc-signer/best-practices-for-running-an-sbtc-signer) [NextStacking STXchevron-right](https://docs.stacks.co/operate/stacking-stx) Last updated 2 months ago Was this helpful? * [Shutdown Procedure](https://docs.stacks.co/operate/snapshot-the-chainstate#shutdown-procedure) * [Overview of Snapshot Methods](https://docs.stacks.co/operate/snapshot-the-chainstate#overview-of-snapshot-methods) * [File-Based Snapshots](https://docs.stacks.co/operate/snapshot-the-chainstate#file-based-snapshots) * [Volume-Based Snapshots](https://docs.stacks.co/operate/snapshot-the-chainstate#volume-based-snapshots) * [How to Restore](https://docs.stacks.co/operate/snapshot-the-chainstate#how-to-restore) * [Example Automation Code](https://docs.stacks.co/operate/snapshot-the-chainstate#example-automation-code) Was this helpful? sun-brightdesktopmoon Copy # Verify if the node is responsive curl http://localhost:20443/v2/info Copy kill $(ps aux | grep stacks-node | grep -v grep | awk '{print $2}') Copy # Ensure no stacks-node processes are running ps aux | grep stacks-node snapshot.sh Copy #!/bin/bash set -euo pipefail # Configuration variables - modify these for your setup SERVICE_NAME="stacks-node" # systemd service name SNAPSHOT_DIR="/var/stacks/mainnet" # path to chainstate directory SNAPSHOT_BASE="/tmp" # temporary directory for archives EBS_VOLUME_ID="vol-1234567890abcdef0" # EBS volume ID containing chainstate S3_BUCKET="s3://my-stacks-snapshots" # S3 bucket for archive storage SNAPSHOT_TYPE="archive" # Options: ebs, archive, or both # Stop the Stacks node service gracefully stop_service() { echo "Stopping $SERVICE_NAME..." sudo systemctl stop "$SERVICE_NAME" } # Start the Stacks node service start_service() { echo "Starting $SERVICE_NAME..." sudo systemctl start "$SERVICE_NAME" } # Create compressed archive and upload to S3 snapshot_archive() { echo "Creating archive snapshot..." # Generate timestamp and version info for filename TIMESTAMP=$(date +"%Y%m%d") DIR_NAME=$(basename "$SNAPSHOT_DIR") VERSION=$(stacks-node version 2>&1 | tail -n 1 | awk '{print $2}') DEST="$SNAPSHOT_BASE/$DIR_NAME-$VERSION-$TIMESTAMP.tar.zst" # Create compressed archive (using zstd for better compression) tar -cf - -C "$(dirname $SNAPSHOT_DIR)" "$(basename $SNAPSHOT_DIR)" | pzstd -o "$DEST" echo "Archive created at: $DEST" # Upload to S3 echo "Uploading to S3..." aws s3 cp "$DEST" "$S3_BUCKET/" echo "S3 upload complete: $S3_BUCKET/$(basename "$DEST")" # Clean up local archive rm "$DEST" } # Create EBS volume snapshot snapshot_ebs() { echo "Creating EBS snapshot of $EBS_VOLUME_ID..." # Generate description with timestamp TIMESTAMP=$(date +"%Y%m%d") DESC="Stacks Node Snapshot - $TIMESTAMP" # Create snapshot with tags SNAPSHOT_ID=$(aws ec2 create-snapshot \ --volume-id "$EBS_VOLUME_ID" \ --description "$DESC" \ --tag-specifications "ResourceType=snapshot,Tags=[{Key=Name,Value=Stacks Snapshot},{Key=type,Value=chainstate}]" \ --query 'SnapshotId' --output text) echo "EBS Snapshot ID: $SNAPSHOT_ID" } # Main execution function main() { case "$SNAPSHOT_TYPE" in ebs) stop_service snapshot_ebs start_service ;; archive) stop_service snapshot_archive start_service ;; both) stop_service snapshot_archive # Create archive first snapshot_ebs # Then EBS snapshot start_service ;; *) echo "Invalid snapshot type: $SNAPSHOT_TYPE. Available options: ebs, archive, or both." exit 1 ;; esac echo "Snapshot process completed successfully!" } # Execute main function main Copy # Daily snapshot at 2 AM 0 2 * * * /path/to/snapshot.sh sun-brightdesktopmoon --- # How to Monitor Signer | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close We will use [Grafana Cloudarrow-up-right](https://grafana.com/) to observe and monitor both the Signer and its corresponding Stacks node. [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#requirements) Requirements ----------------------------------------------------------------------------------------------------------- Grafana's application observability docs have a [great quick-startarrow-up-right](https://grafana.com/docs/grafana-cloud/monitor-applications/application-observability/) . We will use: * Grafana Cloud to collect metrics and visualize them. * Grafana Alloy, on the Signer host, to push the metrics. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#creating-a-grafana-cloud-account) Creating a Grafana Cloud account Before we begin, create a [Grafana Cloudarrow-up-right](https://grafana.com/docs/grafana-cloud/monitor-applications/application-observability/grafana-cloud/) account (they offer a free tier that you can use). Once done, access your dashboard and follow these steps: 1 #### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#add-a-new-connection) Add a new connection Click on "Connections", then "Add new connection". 2 #### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#select-hosted-prometheus-metrics) Select Hosted Prometheus metrics Select "Hosted Prometheus metrics". 3 #### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#choose-via-grafana-alloy) Choose via Grafana Alloy Select "Via Grafana Alloy", then on step 2 choose "Run Grafana Alloy" to generate an API token. Note the token `GCLOUD_RW_API_KEY` and the parameters `GCLOUD_HOSTED_METRICS_URL` and `GCLOUD_HOSTED_METRICS_ID`; we will use them later. ### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#configuring-the-signer-and-the-stacks-node) Configuring the Signer and the Stacks node Ensure both your Signer configuration and your node configuration include the following lines: Copy # signer-config.toml # ... # Adjust to 0.0.0.0:30001 if running in Docker. metrics_endpoint = "127.0.0.1:30001" The pre-compiled binaries already include the monitoring feature. However, if you are compiling the application binaries yourself, remember to enable the Cargo feature `monitoring_prom` while building them, for example: Once both binaries are running with the updated configuration, you can peek at the metrics being exposed: Also, you'll have a `/info` endpoint on the same port: ### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#install-alloy) Install Alloy Follow these instructions to install [Grafana Alloyarrow-up-right](https://grafana.com/docs/alloy/latest/set-up/install/linux/) . On Debian-based distributions: ### [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#configure-alloy) Configure Alloy Edit the file `/etc/alloy/config.alloy` as follows, replacing the placeholders related to the `prometheus` endpoint with the parameters obtained when creating a Grafana Cloud account: * `GCLOUD_HOSTED_METRICS_URL` * `GCLOUD_HOSTED_METRICS_ID` * `GCLOUD_RW_API_KEY` Enable and start Alloy: Metrics from your Signer and node will now start being pushed to Grafana Cloud. [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#visualizing-the-metrics) Visualizing the metrics --------------------------------------------------------------------------------------------------------------------------------- You can now start building a dashboard to visualize the metrics. 1. Log in to Grafana Cloud and create a new Dashboard. 2. Pick the Prometheus instance you created before as the data source. 3. Create a new panel and pick `stacks_signer_current_reward_cycle` from the metrics. You should now be able to see Stacks' current reward cycle, as measured by the Signer, in the dashboard. Grafana comes with powerful data visualization tools. You can read about how to query and transform data [herearrow-up-right](https://grafana.com/docs/grafana-cloud/visualizations/panels-visualizations/query-transform-data/) , and find examples on how to build [Prometheus queriesarrow-up-right](https://prometheus.io/docs/prometheus/latest/querying/basics/) . [This templatearrow-up-right](https://grafana.com/grafana/dashboards/22137-stacks-signer-template/) will kick-start your dashboard. ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2Fgrafana.com%2Fapi%2Fdashboards%2F22137%2Fimages%2F17368%2Fimage&width=768&dpr=3&quality=100&sign=eacd19b3&sv=2) A screenshot of the Grafana dashboard instantiated from the template [hashtag](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#bonus-monitoring-the-host) Bonus: monitoring the host -------------------------------------------------------------------------------------------------------------------------------------- Since we are here, we can also monitor the host itself. Debian-based distributions make it very easy for us by using [`node_exporter`arrow-up-right](https://github.com/prometheus/node_exporter/tree/master) . This will expose metrics on port `9100` of `localhost`. We can now configure `alloy` to push them to Grafana. Edit your `/etc/alloy/config.alloy` file and add the following scrape target to the `prometheus.scrape "default"` targets list: Now reload `alloy` and check its status: `node_exporter` provides a lot of metrics. Explore them through the Grafana Explorer or use one of the many prepared dashboards (e.g., [this onearrow-up-right](https://grafana.com/grafana/dashboards/1860-node-exporter-full/) ) to see comprehensive information. Once you have a dashboard ready, you can also use it to configure alerts (e.g., on disk space, etc.). [PreviousHow to Read Signer Logschevron-left](https://docs.stacks.co/operate/run-a-signer/how-to-read-signer-logs) [NextBest Practices to Run a Signerchevron-right](https://docs.stacks.co/operate/run-a-signer/best-practices-to-run-a-signer) Was this helpful? * [Requirements](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#requirements) * [Creating a Grafana Cloud account](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#creating-a-grafana-cloud-account) * [Configuring the Signer and the Stacks node](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#configuring-the-signer-and-the-stacks-node) * [Install Alloy](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#install-alloy) * [Configure Alloy](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#configure-alloy) * [Visualizing the metrics](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#visualizing-the-metrics) * [Bonus: monitoring the host](https://docs.stacks.co/operate/run-a-signer/how-to-monitor-signer#bonus-monitoring-the-host) Was this helpful? sun-brightdesktopmoon Copy # node-config.toml [node] # ... # Adjust to 0.0.0.0:9153 if running in Docker. prometheus_bind = "127.0.0.1:9153" Copy cargo build --features monitoring_prom,slog_json --release Copy curl 127.0.0.1:30001/metrics # HELP stacks_signer_current_reward_cycle The current reward cycle # TYPE stacks_signer_current_reward_cycle gauge stacks_signer_current_reward_cycle 95 # HELP stacks_signer_node_rpc_call_latencies_histogram Time (seconds) measuring round-trip RPC call latency to the Stacks node # TYPE stacks_signer_node_rpc_call_latencies_histogram histogram ... stacks_signer_node_rpc_call_latencies_histogram_bucket{path="/v2/info",le="0.005"} 0 stacks_signer_node_rpc_call_latencies_histogram_bucket{path="/v2/info",le="0.01"} 0 stacks_signer_node_rpc_call_latencies_histogram_bucket{path="/v2/info",le="0.025"} 0 stacks_signer_node_rpc_call_latencies_histogram_bucket{path="/v2/info",le="0.05"} 985 stacks_signer_node_rpc_call_latencies_histogram_bucket{path="/v2/info",le="0.1"} 1194 ... Copy curl 127.0.0.1:30001/info Copy sudo apt install gpg sudo mkdir -p /etc/apt/keyrings/ wget -q -O - https://apt.grafana.com/gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/grafana.gpg > /dev/null echo "deb [signed-by=/etc/apt/keyrings/grafana.gpg] https://apt.grafana.com stable main" | sudo tee /etc/apt/sources.list.d/grafana.list sudo apt-get update sudo apt-get install alloy Copy // For a full configuration reference, see https://grafana.com/docs/alloy // For a default configuration, integrating all environmental variables from Grafana Cloud // see https://storage.googleapis.com/cloud-onboarding/alloy/config/config.alloy logging { level = "warn" } prometheus.exporter.unix "default" { include_exporter_metrics = true disable_collectors = ["mdadm"] } prometheus.scrape "default" { targets = array.concat( prometheus.exporter.unix.default.targets, [\ {\ // Self-collect metrics\ job = "alloy",\ __address__ = "127.0.0.1:12345",\ },\ {\ // stacks-signer\ job = "stacks-signer",\ __address__ = "127.0.0.1:30001",\ },\ {\ // stacks-node\ job = "stacks-node",\ __address__ = "127.0.0.1:9153",\ },\ ], ) forward_to = [prometheus.remote_write.metrics_service.receiver] } prometheus.remote_write "metrics_service" { external_labels = {"instance" = constants.hostname} endpoint { # TODO: Edit the URL below with your Grafana production URL. # should end with /api/prom/push url = "" # TODO: Edit with your Grafana Cloud ID and Token basic_auth { username = "" password = "" } } } Copy sudo systemctl daemon-reload sudo systemctl enable alloy.service sudo systemctl start alloy.service Copy sudo apt install prometheus-node-exporter sudo systemctl enable prometheus-node-exporter sudo systemctl start prometheus-node-exporter Copy { job = "node_exporter", __address__ = "127.0.0.1:9100", } Copy sudo systemctl reload alloy sudo systemctl status alloy sun-brightdesktopmoon --- # Run a Pruned Bitcoin Node | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close This guide is written for a Unix based system. It's reasonable to expect some modifications will be required for other operating systems. When started, the pruned Bitcoin node will take roughly ~24 hours to reach chain tip. circle-exclamation While bitcoin is syncing, it's recommended to keep a stacks-blockchain node at chain tip, or [use a stacks chainstate archivearrow-up-right](https://docs.hiro.so/stacks/archive/guides/stacks-blockchain) . Requirements: * Bitcoin Core >= v25.0 * https://github.com/bitcoin/bitcoin * https://bitcoincore.org/en/download/ * Host with a minimum of: * 2 vCPU (a single dedicated cpu for the bitcoind process) * 4GB Memory (during sync, more available memory will improve sync time) * 50GB free disk space (actual usage is closer to 20GB) * User account: `bitcoin:bitcoin` * Chainstate directory located at: `/bitcoin/mainnet` * `bitcoin` user must have read/write access. * Config directory located at: `/etc/bitcoin` * `bitcoin` user must have at least read access Caveats [BIP-0159arrow-up-right](https://github.com/bitcoin/bips/blob/master/bip-0159.mediawiki) In short, this BIP specifies that pruned nodes will advertise the service bit `NODE_NETWORK_LIMITED`, which restricts syncing blocks older than 288 blocks (~2 days). What this means is that in practice, a stacks-blockchain node: * Cannot sync from genesis using a pruned node. * Must not be offline or otherwise down for longer than ~2 days (or 288 Bitcoin blocks). 1 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-pruned-bitcoin-node#add-bitcoin-user-and-set-file-ownership) Add bitcoin user and set file ownership 2 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-pruned-bitcoin-node#bitcoin-config) Bitcoin Config Below is a sample config used to sync a pruned bitcoin node - feel free to adjust as needed. circle-info If using the [systemd unit below](https://docs.stacks.co/operate/run-a-node/run-a-pruned-bitcoin-node#systemd-unit-file) , save this file as `/etc/bitcoin/bitcoin.conf` Notes: * `btuser:btcpass` is hardcoded as an rpcauth user/password ([generated using this scriptarrow-up-right](https://github.com/bitcoin/bitcoin/tree/master/share/rpcauth) ). * Only localhost access is allowed (`127.0.0.1`) on the standard mainnet ports. * Pruning is set to be small, storing only the last 1GB of blocks (for p2p traffic, this is more than enough). * `dbcache` is set to the maximum of 16GB. * Wallet (and wallet rpc calls) are disabled. 3 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-pruned-bitcoin-node#systemd-unit-file) Systemd unit file ref: https://github.com/bitcoin/bitcoin/blob/master/contrib/init/bitcoind.service 4 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-pruned-bitcoin-node#enable-and-start-the-bitcoin-service) Enable and start the Bitcoin service 5 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-pruned-bitcoin-node#track-sync-progress) Track sync progress circle-info Once started, you may track the sync progress: [PreviousRun a Bitcoin Nodechevron-left](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node) [NextRun a Node Behind a Proxychevron-right](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy) Was this helpful? Was this helpful? sun-brightdesktopmoon Copy $ sudo mkdir -p /bitcoin/mainnet $ sudo mkdir /etc/bitcoin $ sudo useradd bitcoin -d /bitcoin $ sudo chown -R bitcoin:bitcoin /bitcoin /etc/bitcoin/ Copy ## [rpc] # Accept command line and JSON-RPC commands. server=1 # Allow JSON-RPC connections from specified source. rpcallowip=127.0.0.1/0 # Bind to given address to listen for JSON-RPC connections. rpcbind=127.0.0.1:8332 # Username and HMAC-SHA-256 hashed password for JSON-RPC connections. # Use the script at https://github.com/bitcoin/bitcoin/tree/master/share/rpcauth to generate # Note: may be specified multiple times for different users. rpcauth=btcuser:18857b4df4b1f0f5e6b1d7884617ab39$de6e02e1da8ee138ee702e13e0637e24679d844756216b066c3aeac4bcac5e10 # btuser:btcpass # Optional: rpcwhitelist can restrict listed RPC calls to specific rpcauth users. # Uncomment the below the restrict the `limited` user to a small subset of `get` commands # rpcauth=limited:350c91a60895b567c4662c27e63e9a41$25188b0f51f2f974dcdc75c1e0d41174e8f7ae19fb96927abf68ac5bc1e8897b # limited:limited # rpcwhitelist=limited:getblockchaininfo,getblock,getblockcount,getblockhash,getblockheader,getnetworkinfo # rpcwhitelistdefault=0 ## [core] # Specify data directory datadir=/bitcoin/mainnet # Do not keep transactions in the mempool longer than hours (default: 336) mempoolexpiry=24 # Bind to given address and always listen on it (default: 0.0.0.0) bind=127.0.0.1:8333 # Maximum database cache size MiB (4 to 16384, default: 450). In addition, unused mempool memory is shared for this cache dbcache=16384 # Maintain a full transaction index, used by the getrawtransaction rpc call (**Running a pruned node requires that this option is disabled**) txindex=0 # Reduce storage requirements by enabling pruning (deleting) of old # blocks. This allows the pruneblockchain RPC to be called to # delete specific blocks and enables automatic pruning of old # blocks if a target size in MiB is provided. This mode is # incompatible with -txindex. Warning: Reverting this setting # requires re-downloading the entire blockchain. (default: 0 = # disable pruning blocks, 1 = allow manual pruning via RPC, >=550 = # automatically prune block files to stay under the specified # target size in MiB) prune=1024 # 1GB of chainstate is enough for p2p block data (if using the RPC,this can be adjusted higher to store more blocks) ## [wallet] # Do not load the wallet and disable wallet RPC calls disablewallet=1 Copy [Unit] Description=Bitcoin daemon Documentation=https://github.com/bitcoin/bitcoin/blob/master/doc/init.md # https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/ After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/bin/bitcoind -pid=/run/bitcoind/bitcoind.pid \ -conf=/etc/bitcoin/bitcoin.conf \ -startupnotify='systemd-notify --ready' \ -shutdownnotify='systemd-notify --stopping' # Make sure the config directory is readable by the service user PermissionsStartOnly=true ExecStartPre=/bin/chgrp bitcoin /etc/bitcoin # Process management #################### Type=notify NotifyAccess=all PIDFile=/run/bitcoind/bitcoind.pid Restart=on-failure TimeoutStartSec=infinity TimeoutStopSec=600 # Directory creation and permissions #################################### # Run as bitcoin:bitcoin User=bitcoin Group=bitcoin # /run/bitcoind RuntimeDirectory=bitcoind RuntimeDirectoryMode=0710 # /etc/bitcoin ConfigurationDirectory=bitcoin ConfigurationDirectoryMode=0710 # /var/lib/bitcoind StateDirectory=bitcoind StateDirectoryMode=0710 # Hardening measures #################### # Provide a private /tmp and /var/tmp. PrivateTmp=true # Mount /usr, /boot/ and /etc read-only for the process. ProtectSystem=full # Deny access to /home, /root and /run/user ProtectHome=true # Disallow the process and all of its children to gain # new privileges through execve(). NoNewPrivileges=true # Use a new /dev namespace only populated with API pseudo devices # such as /dev/null, /dev/zero and /dev/random. PrivateDevices=true # Deny the creation of writable and executable memory mappings. MemoryDenyWriteExecute=true # Restrict ABIs to help ensure MemoryDenyWriteExecute is enforced SystemCallArchitectures=native [Install] WantedBy=multi-user.target Copy $ sudo systemctl daemon-reload $ sudo systemctl enable bitcoin.service $ sudo systemctl start bitcoin.service Copy $ sudo tail -f /bitcoin/mainnet/debug.log 2024-12-05T19:35:31Z UpdateTip: new best=00000000000000000058990a84cc8f8eab25dbbd572f123f9190cea7256d7349 height=509258 version=0x20000000 log2_work=88.128280 tx=299522737 date='2018-02-15T03:42:14Z' progress=0.295203 cache=43.5MiB(172740txo) ... $ bitcoin-cli \ -rpcconnect=127.0.0.1 \ -rpcport=8332 \ -rpcuser=btcuser \ -rpcpassword=btcpass \ getblockcount 509016 sun-brightdesktopmoon --- # Run a Node Behind a Proxy | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close circle-exclamation Running a publicly accessible node exposes your infrastructure to the open internet. The proxy configurations below are starting points, not complete security solutions. **Do this at your own risk.** You are responsible for securing and maintaining your own infrastructure. If you plan to run a Stacks node with publicly accessible RPC endpoints, it is strongly recommended at a minimum to place the node behind a reverse proxy with rate limiting. Without rate limiting, a public node can be overwhelmed by excessive requests, leading to degraded performance or denial of service. This guide provides minimal, production-tested configurations for two popular reverse proxies. **Choose one — you do not need both:** * [**Nginx**](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#nginx) — simpler configuration, widely used, good baseline rate limiting. * [**HAProxy**](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#haproxy) — more advanced abuse detection via stick tables, HTTP proxying with automatic IP blocking. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#ports-overview) Ports overview A Stacks node deployment typically exposes the following services: Service Default Port Protocol Proxy? Stacks RPC 20443 HTTP Yes Stacks P2P 20444 TCP No Stacks API 3999 HTTP Yes, if running Bitcoin RPC 8332 HTTP Yes, if exposed Bitcoin P2P 8333 TCP No circle-info The **P2P ports** (20444, 8333) use custom binary protocols for peer-to-peer communication, not HTTP. You can leave them open directly to the network. The proxy configurations below focus on the **RPC/API ports** which serve HTTP traffic and are the primary target for abuse. **Optional:** P2P ports can also benefit from rate-limiting. While unlikely, a denial-of-service attack could flood the P2P port so the node only communicates with malicious peers. Adding connection-rate limits on P2P ports won't hurt and provides an extra layer of protection. [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#configure-the-stacks-node) Configure the Stacks node --------------------------------------------------------------------------------------------------------------------------------------- Before setting up the proxy, configure your Stacks node so its RPC endpoint is not directly reachable from the public internet (i.e. for stacks-node configuration -`rpc_bind = "127.0.0.1:30443"`). The proxy will be the only public-facing service. Since the proxy needs to listen on the standard public ports (e.g. `20443`), the node itself must bind to **different** ports to avoid conflicts. The examples below use offset ports (`30443`, `33999`) for the node's RPC and API, while the proxy owns the public-facing ports (`20443`, `3999`). P2P stays on its standard port and is not proxied. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#bare-metal) Bare metal In your node's configuration file (e.g. `Stacks.toml`), bind the RPC to a localhost address on an offset port: The proxy will listen on port `20443` and forward RPC traffic to the offset port. P2P binds directly on the standard port `20444` and does not go through the proxy. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#docker-stacks-blockchain-docker) Docker (stacks-blockchain-docker) When running with [stacks-blockchain-dockerarrow-up-right](https://github.com/stacks-network/stacks-blockchain-docker) , the node's ports are controlled by the Docker Compose configuration. By default, ports are exposed on all interfaces (`0.0.0.0`). To restrict the RPC and API to localhost (so only the proxy can reach them), edit `compose-files/common.yaml` and change the port mappings. P2P is published directly on the standard port: The format is `host_ip:host_port:container_port`. The node inside the container keeps its default ports — only the **host** side changes. Offset host ports (`30443`, `33999`) are necessary because the proxy already occupies the standard ports (`20443`, `3999`) on the host. Binding to `127.0.0.1` ensures the container ports are only reachable from the host (where the proxy runs), not from the public internet. P2P is published directly on the standard port `20444`. circle-info Inter-container communication (e.g. the API receiving events from the blockchain node) uses Docker's internal network and service names, not published host ports. These port mapping changes do not affect container-to-container traffic. [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#nginx) Nginx ----------------------------------------------------------------------------------------------- Nginx can serve as a reverse proxy with rate limiting using the `limit_req` module. The configuration below rate-limits the Stacks RPC and Stacks API endpoints. **Rate limit parameters explained:** * `**rate=5r/s**` — allows a sustained average of 5 requests per second per client IP. Requests beyond this rate are delayed or rejected. * `**burst=20**` — permits up to 20 requests to queue above the base rate before Nginx starts rejecting. This absorbs short traffic spikes without immediately dropping legitimate requests. * `**nodelay**` — queued burst requests are forwarded immediately rather than being spaced out over time. Without `nodelay`, excess requests would be throttled to match the base rate. The Stacks API zone uses a higher rate (`10r/s`) and larger burst (`40`) because API endpoints typically see more traffic than the node RPC. Enable the site and restart Nginx: ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#verify) Verify [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#haproxy) HAProxy --------------------------------------------------------------------------------------------------- HAProxy provides fine-grained connection tracking and abuse detection via [stick tablesarrow-up-right](https://www.haproxy.com/blog/introduction-to-haproxy-stick-tables) . The configuration below proxies Stacks RPC and API traffic over HTTP, automatically rejecting clients that exceed request rate thresholds. circle-info Adjust `maxconn`, rate thresholds (`ge 25`), stick-table sizes, and expiry times to suit your traffic patterns. The values below are conservative defaults. ### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#verify-1) Verify circle-info **How the abuse table works:** HAProxy tracks each client IP's HTTP request rate. When a client exceeds the threshold (e.g. 25 HTTP requests in 10 seconds), its `gpc0` counter is incremented and all subsequent requests from that IP are denied with HTTP 429. The stick-table entry expires after 30 minutes, lifting the block automatically. [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#firewall-considerations) Firewall considerations ----------------------------------------------------------------------------------------------------------------------------------- Additionally, a host-level firewall adds defense in depth: only the proxy's listening ports and the P2P ports should be reachable from the public internet, while the node's RPC stays accessible only via the proxy (localhost). How you configure this depends on your environment — cloud providers, bare-metal hosts, and container setups all handle firewalling differently. circle-info Refer to your provider's or operating system's firewall documentation for specifics: * **AWS** — [Security Groupsarrow-up-right](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html) * **GCP** — [VPC Firewall Rulesarrow-up-right](https://cloud.google.com/firewall/docs/firewalls) * **Azure** — [Network Security Groupsarrow-up-right](https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview) * **Digital Ocean** — [Cloud Firewallsarrow-up-right](https://docs.digitalocean.com/products/networking/firewalls/) * **Linux (bare metal)** — [UFWarrow-up-right](https://help.ubuntu.com/community/UFW) , [iptablesarrow-up-right](https://wiki.archlinux.org/title/Iptables) , or [nftablesarrow-up-right](https://wiki.nftables.org/) * **Docker** — Docker manipulates `iptables` directly and can bypass host firewall rules. See the [Docker packet filtering docsarrow-up-right](https://docs.docker.com/engine/network/packet-filtering-firewalls/) for how to enforce restrictions. [PreviousRun a Pruned Bitcoin Nodechevron-left](https://docs.stacks.co/operate/run-a-node/run-a-pruned-bitcoin-node) [NextRun a Minerchevron-right](https://docs.stacks.co/operate/run-a-miner) Last updated 1 month ago Was this helpful? * [Ports overview](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#ports-overview) * [Configure the Stacks node](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#configure-the-stacks-node) * [Bare metal](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#bare-metal) * [Docker (stacks-blockchain-docker)](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#docker-stacks-blockchain-docker) * [Nginx](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#nginx) * [Verify](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#verify) * [HAProxy](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#haproxy) * [Verify](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#verify-1) * [Firewall considerations](https://docs.stacks.co/operate/run-a-node/run-a-node-behind-a-proxy#firewall-considerations) Was this helpful? sun-brightdesktopmoon Stacks.toml Copy [node] rpc_bind = "127.0.0.1:30443" # Only accessible from localhost, offset port p2p_bind = "0.0.0.0:20444" # Standard port, open directly to the network # data_url = "http://:20443" # Uncomment if peers need to reach your RPC compose-files/common.yaml (port changes) Copy services: stacks-blockchain: ports: - 127.0.0.1:30443:20443 # RPC: only localhost, host port 30443 - 0.0.0.0:20444:20444 # P2P: open directly, standard port - 127.0.0.1:9153:9153 # Metrics: only localhost stacks-blockchain-api: ports: - 127.0.0.1:33999:3999 # API: only localhost, host port 33999 Install Nginx Copy sudo apt-get update sudo apt-get install -y nginx /etc/nginx/sites-available/stacks-node Copy limit_req_zone $binary_remote_addr zone=stacks_rpc:10m rate=5r/s; limit_req_zone $binary_remote_addr zone=stacks_api:10m rate=10r/s; server { listen 20443; # Stacks RPC location / { limit_req zone=stacks_rpc burst=20 nodelay; proxy_pass http://127.0.0.1:30443; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } server { listen 3999; # Stacks API (if running) location / { limit_req zone=stacks_api burst=40 nodelay; proxy_pass http://127.0.0.1:33999; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Enable and start Nginx Copy sudo ln -s /etc/nginx/sites-available/stacks-node /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl restart nginx Test the RPC endpoint through the proxy Copy curl -s localhost:20443/v2/info | jq Install HAProxy Copy sudo apt-get update sudo apt-get install -y haproxy /etc/haproxy/haproxy.cfg Copy global log /dev/log local0 log /dev/log local1 notice maxconn 512 chroot /var/lib/haproxy stats socket /run/haproxy/admin.sock mode 660 level admin stats timeout 30s user haproxy group haproxy daemon defaults log global mode http option httplog option dontlognull timeout connect 5000 timeout client 50000 timeout server 50000 timeout http-request 10s # ------------------------------------------- # Abuse tracking table (shared across all frontends) # Keeps 100k entries, each expiring after 30m. # All frontends share this table, so a client that # exceeds the rate limit on any service is blocked # from all services. To isolate rate limits per # service, create separate stick-table backends. # ------------------------------------------- backend Abuse stick-table type ip size 100K expire 30m store gpc0,http_req_rate(10s) # ------------------------------------------- # Stacks RPC (public: 20443 -> node: 30443) # ------------------------------------------- frontend stacks_rpc bind *:20443 http-request track-sc0 src table Abuse http-request deny deny_status 429 if { src_get_gpc0(Abuse) gt 0 } http-request deny deny_status 429 if { src_http_req_rate(Abuse) ge 25 } { src_inc_gpc0(Abuse) ge 0 } default_backend stacks_rpc_back backend stacks_rpc_back server stacks-node 127.0.0.1:30443 maxconn 100 check inter 10s # ------------------------------------------- # Stacks API (public: 3999 -> node: 33999) # ------------------------------------------- frontend stacks_api bind *:3999 http-request track-sc0 src table Abuse http-request deny deny_status 429 if { src_get_gpc0(Abuse) gt 0 } http-request deny deny_status 429 if { src_http_req_rate(Abuse) ge 25 } { src_inc_gpc0(Abuse) ge 0 } default_backend stacks_api_back backend stacks_api_back server stacks-api 127.0.0.1:33999 maxconn 100 check inter 10s # ------------------------------------------- # Bitcoin RPC (optional, if you expose it) # ------------------------------------------- frontend btc_rpc bind *:8332 http-request track-sc0 src table Abuse http-request deny deny_status 429 if { src_get_gpc0(Abuse) gt 0 } http-request deny deny_status 429 if { src_http_req_rate(Abuse) ge 25 } { src_inc_gpc0(Abuse) ge 0 } default_backend btc_rpc_back backend btc_rpc_back server bitcoin 127.0.0.1:8332 maxconn 100 check inter 10s Enable and start HAProxy Copy sudo systemctl enable haproxy sudo systemctl start haproxy Test the RPC endpoint through the proxy Copy curl -s localhost:20443/v2/info | jq sun-brightdesktopmoon --- # Run a Bitcoin Node | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F4065274862-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F4cpTb2lbw0LAOuMHrvhA%252Fuploads%252FpfzonQkQOzLcDyVSmIoW%252Frun-a-bitcoin-node.png%3Falt%3Dmedia%26token%3D1456af17-ba92-4764-b1c6-87118876de32&width=768&dpr=3&quality=100&sign=c1a200a9&sv=2) 1 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node#requirements) Requirements This guide is written for a Unix based system. It's reasonable to expect some modifications will be required for other operating systems. When started, the Bitcoin node will take several days to reach chain tip. * Bitcoin Core >= v25.0 * https://github.com/bitcoin/bitcoin * https://bitcoincore.org/en/download/ * Host with a minimum of: * 2 vCPU (a single dedicated cpu for the bitcoind process) * 4GB Memory (during sync, more available memory will improve sync time) * 1TB free disk space * User account: `bitcoin:bitcoin` * Chainstate directory located at: `/bitcoin/mainnet` * `bitcoin` user must have read/write access. * Config directory located at: `/etc/bitcoin` * `bitcoin` user must have at least read access 2 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node#add-bitcoin-user-and-set-file-ownership) Add bitcoin user and set file ownership Run the following commands: Create directories and add user Copy $ sudo mkdir -p /bitcoin/mainnet $ sudo mkdir /etc/bitcoin $ sudo useradd bitcoin -d /bitcoin $ sudo chown -R bitcoin:bitcoin /bitcoin /etc/bitcoin/ 3 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node#bitcoin-config) Bitcoin config Below is a sample config used to sync a bitcoin node - feel free to adjust as needed. circle-info If using the [systemd unit below](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node#systemd-unit-file) , save this file as `/etc/bitcoin/bitcoin.conf` * `btuser:btcpass` is hardcoded as an rpcauth user/password ([generated using this scriptarrow-up-right](https://github.com/bitcoin/bitcoin/tree/master/share/rpcauth) ). * Only localhost access is allowed (`127.0.0.1`) on the standard mainnet ports. * `dbcache` is set to the maximum of 16GB. * Wallet (and wallet rpc calls) are disabled. Sample /etc/bitcoin/bitcoin.conf Copy ## [rpc] # Accept command line and JSON-RPC commands. server=1 # Allow JSON-RPC connections from specified source. rpcallowip=127.0.0.1/0 # Bind to given address to listen for JSON-RPC connections. rpcbind=127.0.0.1:8332 # Username and HMAC-SHA-256 hashed password for JSON-RPC connections. # Use the script at https://github.com/bitcoin/bitcoin/tree/master/share/rpcauth to generate # Note: may be specified multiple times for different users. rpcauth=btcuser:18857b4df4b1f0f5e6b1d7884617ab39$de6e02e1da8ee138ee702e13e0637e24679d844756216b066c3aeac4bcac5e10 # btuser:btcpass # Optional: rpcwhitelist can restrict listed RPC calls to specific rpcauth users. # Uncomment the below the restrict the `limited` user to a small subset of `get` commands # rpcauth=limited:350c91a60895b567c4662c27e63e9a41$25188b0f51f2f974dcdc75c1e0d41174e8f7ae19fb96927abf68ac5bc1e8897b # limited:limited # rpcwhitelist=limited:getblockchaininfo,getblock,getblockcount,getblockhash,getblockheader,getnetworkinfo # rpcwhitelistdefault=0 ## [core] # Specify data directory datadir=/bitcoin/mainnet # Do not keep transactions in the mempool longer than hours (default: 336) mempoolexpiry=24 # Bind to given address and always listen on it (default: 0.0.0.0) bind=127.0.0.1:8333 # Maximum database cache size MiB (4 to 16384, default: 450). In addition, unused mempool memory is shared for this cache dbcache=16384 # Maintain a full transaction index, used by the getrawtransaction rpc call txindex=1 ## [wallet] # Do not load the wallet and disable wallet RPC calls disablewallet=1 4 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node#systemd-unit-file) Systemd unit file Reference: https://github.com/bitcoin/bitcoin/blob/master/contrib/init/bitcoind.service Save the following as your systemd unit (for example `/etc/systemd/system/bitcoin.service`): bitcoind.service Copy [Unit] Description=Bitcoin daemon Documentation=https://github.com/bitcoin/bitcoin/blob/master/doc/init.md # https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/ After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/bin/bitcoind -pid=/run/bitcoind/bitcoind.pid \ -conf=/etc/bitcoin/bitcoin.conf \ -startupnotify='systemd-notify --ready' \ -shutdownnotify='systemd-notify --stopping' # Make sure the config directory is readable by the service user PermissionsStartOnly=true ExecStartPre=/bin/chgrp bitcoin /etc/bitcoin # Process management #################### Type=notify NotifyAccess=all PIDFile=/run/bitcoind/bitcoind.pid Restart=on-failure TimeoutStartSec=infinity TimeoutStopSec=600 # Directory creation and permissions #################################### # Run as bitcoin:bitcoin User=bitcoin Group=bitcoin # /run/bitcoind RuntimeDirectory=bitcoind RuntimeDirectoryMode=0710 # /etc/bitcoin ConfigurationDirectory=bitcoin ConfigurationDirectoryMode=0710 # /var/lib/bitcoind StateDirectory=bitcoind StateDirectoryMode=0710 # Hardening measures #################### # Provide a private /tmp and /var/tmp. PrivateTmp=true # Mount /usr, /boot/ and /etc read-only for the process. ProtectSystem=full # Deny access to /home, /root and /run/user ProtectHome=true # Disallow the process and all of its children to gain # new privileges through execve(). NoNewPrivileges=true # Use a new /dev namespace only populated with API pseudo devices # such as /dev/null, /dev/zero and /dev/random. PrivateDevices=true # Deny the creation of writable and executable memory mappings. MemoryDenyWriteExecute=true # Restrict ABIs to help ensure MemoryDenyWriteExecute is enforced SystemCallArchitectures=native [Install] WantedBy=multi-user.target 5 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node#enable-and-start-the-bitcoin-service) Enable and start the Bitcoin service Run: Enable and start service Copy $ sudo systemctl daemon-reload $ sudo systemctl enable bitcoin.service $ sudo systemctl start bitcoin.service 6 #### [hashtag](https://docs.stacks.co/operate/run-a-node/run-a-bitcoin-node#track-sync-progress) Track sync progress circle-info Once started, you may track the sync progress: Tail debug log and query RPC Copy $ sudo tail -f /bitcoin/mainnet/debug.log 2024-12-05T19:35:31Z UpdateTip: new best=00000000000000000058990a84cc8f8eab25dbbd572f123f9190cea7256d7349 height=509258 version=0x20000000 log2_work=88.128280 tx=299522737 date='2018-02-15T03:42:14Z' progress=0.295203 cache=43.5MiB(172740txo) ... $ bitcoin-cli \ -rpcconnect=127.0.0.1 \ -rpcport=8332 \ -rpcuser=btcuser \ -rpcpassword=btcpass \ getblockcount 509016 [PreviousRun a Node with Quicknodechevron-left](https://docs.stacks.co/operate/run-a-node/run-a-node-with-quicknode) [NextRun a Pruned Bitcoin Nodechevron-right](https://docs.stacks.co/operate/run-a-node/run-a-pruned-bitcoin-node) Last updated 2 months ago Was this helpful? Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Introducción | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fam7BqpV0sbUexW7Zpqoh%252Fbitcoin-stacks-dark.png%3Falt%3Dmedia%26token%3D28aa61b3-628a-4519-a574-0b5856762626&width=768&dpr=3&quality=100&sign=8872fbcd&sv=2)![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fx09gHeYU67yvfXLh7Iis%252Fbitcoin-stacks.png%3Falt%3Dmedia%26token%3D7635e08d-2495-44ed-a93c-68351882fbf3&width=768&dpr=3&quality=100&sign=16aee377&sv=2) circle-info Para el whitepaper oficial de Stacks: [https://stacks-network.github.io/stacks/stacks.pdfarrow-up-right](https://stacks-network.github.io/stacks/stacks.pdf) ### [hashtag](https://docs.stacks.co/learn/es#stacks-el-tl-dr) Stacks: El TL;DR Stacks activa la economía de Bitcoin. Bitcoin es la criptomoneda más adoptada, más valiosa y más descentralizada. La L2 de Stacks permite BTC rápidos y baratos y contratos inteligentes completos en la L2 sin modificar el propio Bitcoin. Los usuarios y desarrolladores pueden usar BTC en sus aplicaciones y pagar tarifas de gas con BTC. Todas las transacciones en la L2 de Stacks están aseguradas por Bitcoin L1 con finalización al 100%, lo que te permite construir aplicaciones y activos digitales que están integrados con la seguridad de Bitcoin. La capa de Stacks para contratos inteligentes tiene las siguientes innovaciones que la hacen única: **S**: Asegurada por todo el poder de hash de Bitcoin (finalidad de Bitcoin). **T**: Mecanismo de peg con Bitcoin minimizando la confianza; escribir en Bitcoin. **A**: Intercambios atómicos de BTC y activos propiedad de direcciones BTC. **C**: Lenguaje Clarity para contratos inteligentes seguros y decidibles. **K**: Conocimiento del estado completo de Bitcoin; leer desde Bitcoin. **S**: Transacciones escalables y rápidas que se liquidan en Bitcoin. * * * ### [hashtag](https://docs.stacks.co/learn/es#por-que-aprender-los-fundamentos-de-stacks) ¿Por qué aprender los fundamentos de Stacks? Los fundamentos de Stacks te dan la intuición para construir aplicaciones que sean más seguras, más alineadas con Bitcoin y más a prueba de futuro. Un desarrollador que aprende lo básico no solo escribe en Clarity—construye aplicaciones que en realidad _se sienten como_ aplicaciones de Bitcoin. 1. Construirás aplicaciones que realmente aprovechen Bitcoin 2. Evitarás costosos errores de diseño 3. Escribirás mejores contratos inteligentes 4. Usarás sBTC y las escrituras en Bitcoin correctamente * * * ### [hashtag](https://docs.stacks.co/learn/es#que-aprender-a-continuacion) ¿Qué aprender a continuación? [](https://docs.stacks.co/learn/es/stacks-101) #### [hashtag](https://docs.stacks.co/learn/es#stacks-101) Stacks 101 Profundiza realmente en los detalles de cómo Stacks se construye sobre Bitcoin. [](https://docs.stacks.co/learn/es/network-fundamentals) #### [hashtag](https://docs.stacks.co/learn/es#fundamentos-de-la-red) Fundamentos de la red Aprende sobre cuentas, testnets, SIPs, autenticación, BNS y más. [](https://docs.stacks.co/learn/es/block-production) #### [hashtag](https://docs.stacks.co/learn/es#produccion-de-bloques) Producción de Bloques ¿Cómo se validan y minan los bloques de Stacks? [](https://docs.stacks.co/learn/es/transactions) #### [hashtag](https://docs.stacks.co/learn/es#transacciones) Transacciones Aprende sobre el ciclo de vida de una transacción en Stacks. [](https://docs.stacks.co/learn/es/clarity) #### [hashtag](https://docs.stacks.co/learn/es#clarity) Clarity Descubre la filosofía y los principios de diseño del lenguaje de contratos inteligentes Clarity. [](https://docs.stacks.co/learn/es/sbtc) #### [hashtag](https://docs.stacks.co/learn/es#sbtc) sBTC Entiende cómo el bitcoin se desencapsula en un activo productivo y programable. [](https://docs.stacks.co/learn/es/dual-stacking) #### [hashtag](https://docs.stacks.co/learn/es#dual-stacking) Dual Stacking Una innovación financiera encima de la base central del Stacking. Gana bitcoin con bitcoin. [](https://docs.stacks.co/learn/es/bridging) #### [hashtag](https://docs.stacks.co/learn/es#puentes) Puentes Explora cómo funciona la interoperabilidad entre cadenas con Stacks y otras redes principales. * * * ### [hashtag](https://docs.stacks.co/learn/es#recursos-adicionales) Recursos Adicionales * \[[Stacks YTarrow-up-right](https://youtu.be/0erpW7IEo6Y?si=Ldu4RlVVnLqOL4eP)\ \] Cómo crecerá Stacks en 2025 con el creador de Stacks Muneeb Ali * \[[Token2049 Dubáiarrow-up-right](https://youtu.be/DFTXAOmi0es?si=sMOO6Yfj_TCVdFTF)\ \] Muneeb Ali - Construyendo el futuro de Bitcoin: El papel de Stacks L2 [SiguienteStacks 101chevron-right](https://docs.stacks.co/learn/es/stacks-101) Última actualización hace 1 mes ¿Te fue útil? * [Stacks: El TL;DR](https://docs.stacks.co/learn/es#stacks-el-tl-dr) * [¿Por qué aprender los fundamentos de Stacks?](https://docs.stacks.co/learn/es#por-que-aprender-los-fundamentos-de-stacks) * [¿Qué aprender a continuación?](https://docs.stacks.co/learn/es#que-aprender-a-continuacion) * [Recursos Adicionales](https://docs.stacks.co/learn/es#recursos-adicionales) ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Stacks 101 | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Stacks tiene un modelo técnico muy único en el ecosistema de Bitcoin. Esta sección te ayudará a obtener una visión general de alto nivel de los componentes esenciales para entender cómo funciona Stacks. Cubriremos los fundamentos de qué es Stacks y cómo funciona tanto a nivel filosófico como técnico, y puedes profundizar en las secciones posteriores para más detalles. Primero, obtengamos una visión general de exactamente qué es Stacks. [AnteriorIntroducciónchevron-left](https://docs.stacks.co/learn/es) [Siguiente¿Qué es Stacks?chevron-right](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks) Última actualización hace 1 mes ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Mine Testnet Stacks Tokens | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#introduction) Introduction For more on the technical details of mining, please review the mining guide. The following is an abridged version of the [walkthrough herearrow-up-right](https://github.com/stacksfoundation/miner-docs/tree/testnet) , written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed (PR's welcome!). If you're interested in mining on the Stacks testnet, you can find instructions on how to do that here: ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#running-a-bitcoin-testnet-full-node) Running a Bitcoin Testnet Full Node To participate as a miner on testnet, you must have access to a testnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. * [Ensure your computer meets the minimum hardware requirements before continuing.arrow-up-right](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) First, download a [bitcoin binaryarrow-up-right](https://bitcoin.org/en/download) , or [build from sourcearrow-up-right](https://github.com/stacksfoundation/miner-docs/blob/testnet/bitcoin.md#source-install) (_there may be some extra requirements to building,_ [_defined here_arrow-up-right](https://github.com/stacksfoundation/miner-docs/blob/testnet/prerequisites.md#install-required-packages) ). circle-info Tip: It is recommended to use a persistent location for the chainstate, in the steps below we're using `/bitcoin`. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#update-the-bitcoin-configuration-file) Update the Bitcoin Configuration File Next, update the bitcoin configuration: * Optional, but recommended: Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin`. * Optional, but recommended: Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4. * Modify the `rpcuser` and `rpcpassword` values from the defaults below. * Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`). Copy server=1 testnet=1 disablewallet=0 datadir=/bitcoin rpcuser=btcuser rpcpassword=btcpass rpcallowip=0.0.0.0/0 dbcache=512 banscore=1 rpcthreads=256 rpcworkqueue=256 rpctimeout=100 txindex=1 [test] bind=0.0.0.0:18333 rpcbind=0.0.0.0:18332 rpcport=18332 #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#start-bitcoin) Start Bitcoin Finally, start `bitcoind` as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): circle-info Note: It will take a few hours for the node to synchronize with Bitcoin Testnet. While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/testnet3/debug.log`): * * * ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#running-a-stacks-blockchain-miner) Running a Stacks Blockchain miner First, download the latest tagged [stacks blockchain binaryarrow-up-right](https://github.com/stacks-network/stacks-blockchain/releases/latest) , or [build from sourcearrow-up-right](https://github.com/stacksfoundation/miner-docs/blob/testnet/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) (_there may be some extra requirements to building,_ [_defined here_arrow-up-right](https://github.com/stacksfoundation/miner-docs/blob/testnet/prerequisites.md#install-required-packages) ). circle-info Tip: It is recommended to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain`. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#generate-a-keychain) Generate a keychain First, a keychain needs to be generated. With this keychain, we'll get some testnet BTC from a faucet, and then use that BTC to start mining. To create a keychain, the simplest way is to use the [stacks-cliarrow-up-right](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. After this runs, you should see some JSON printed to the screen that looks like this: triangle-exclamation Do not lose this information - we'll need to use the `privateKey`, `btcAddress` and `wif` fields in later steps. The above `wif` (`cPdTdMgww2njhnekUZmHmFNKsWAjVdCR4cfvD2Y4UQhFzMmwoW33`) will then need to be imported into the bitcoin testnet network. Next, a bitcoin wallet is created: Now, import your wif (bitcoin private key) inside the newly created wallet. circle-info Note: Be sure to replace `` with the wif value in the `Generate a keychain` step. circle-info Note: The import may take a while, because a wallet rescan is triggered. After the import has completed successfully, you can check that the address is imported with `getaddressinfo`. Once imported, we need to get some testnet BTC to that address. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucetarrow-up-right](https://tbtc.bitaps.com/) . You'll be sent `0.01` testnet BTC to that address. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#update-the-stacks-blockchain-configuration-file) Update the Stacks Blockchain Configuration File Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample testnet miner configarrow-up-right](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/testnet-miner-conf.toml) to your local machine in a memorable location like `$HOME/testnet-miner-conf.toml`. Next, update the stacks configuration: * Optional, but recommended: Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` * From the `make_keychain` step, modify the `seed` value with `privatekey` * Store the following configuration somewhere on your filesystem (ex: `$HOME/testnet-miner-conf.toml`) #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#start-the-stacks-blockchain) Start the Stacks Blockchain To run your miner, run this in the command line: Your node should start. It will take some time to sync, and then your miner will be running. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#enable-debug-logging) Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: * * * ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#optional-running-a-stacks-blockchain-miner-with-docker) Optional: Running a Stacks Blockchain miner with Docker Alternatively, you can run a Stacks testnet miner with Docker. circle-exclamation Ensure you have [Dockerarrow-up-right](https://docs.docker.com/get-docker/) installed. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#generate-a-keychain-and-get-some-tokens) Generate a Keychain and Get Some Tokens Generate a keychain: Now, we need to get some tBTC. Grab the `btcAddress` field, and paste it into [this Bitcoin testnet faucetarrow-up-right](https://tbtc.bitaps.com/) . You'll be sent `0.01` tBTC to that address. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#update-stacks-blockchain-docker-configuration-file) Update Stacks Blockchain Docker Configuration File Use the steps outlined above to create the configuration file. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#start-the-stacks-blockchain-miner-with-docker) Start the Stacks Blockchain miner with Docker circle-info Info: The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled. You can review the node logs with this command: * * * ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#optional-running-in-kubernetes-with-helm) Optional: Running in Kubernetes with Helm In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chartarrow-up-right](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain) . Ensure you have the following prerequisites installed: * [Dockerarrow-up-right](https://docs.docker.com/get-docker/) * [minikubearrow-up-right](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) * [kubectlarrow-up-right](https://kubernetes.io/docs/tasks/tools/install-kubectl/) * [helmarrow-up-right](https://helm.sh/docs/intro/install/) #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#generate-keychain-and-get-some-tokens) Generate keychain and get some tokens Use the steps outlined above #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#install-the-chart-and-run-the-miner) Install the chart and run the miner To install the chart with the release name `my-release` and run the node as a miner: You can review the node logs with this command: For more information on the Helm chart and configuration options, please refer to the [chart's homepagearrow-up-right](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain) . [PreviousMiner Costs and Feeschevron-left](https://docs.stacks.co/operate/run-a-miner/miner-costs-and-fees) [NextMine Mainnet Stacks Tokenschevron-right](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens) Last updated 27 days ago Was this helpful? * [Introduction](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#introduction) * [Running a Bitcoin Testnet Full Node](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#running-a-bitcoin-testnet-full-node) * [Running a Stacks Blockchain miner](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#running-a-stacks-blockchain-miner) * [Optional: Running a Stacks Blockchain miner with Docker](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#optional-running-a-stacks-blockchain-miner-with-docker) * [Optional: Running in Kubernetes with Helm](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens#optional-running-in-kubernetes-with-helm) Was this helpful? sun-brightdesktopmoon Copy bitcoind -conf=$HOME/bitcoin.conf Copy $ bitcoin-cli \ -rpcconnect=127.0.0.1 \ -rpcport=18332 \ -rpcuser=btcuser \ -rpcpassword=btcpass \ getblockchaininfo | jq .blocks 2583513 Copy npx @stacks/cli make_keychain -t 2>/dev/null | jq -r Copy { "mnemonic": "spare decade dog ghost luxury churn flat lizard inch nephew nut drop huge divert mother soccer father zebra resist later twin vocal slender detail", "keyInfo": { "privateKey": "ooxeemeitar4ahw0ca8anu4thae7aephahshae1pahtae5oocahthahho4ahn7eici", "address": "STTXOG3AIHOHNAEH5AU6IEX9OOTOH8SEIWEI5IJ9", "btcAddress": "Ook6goo1Jee5ZuPualeiqu9RiN8wooshoo", "wif": "rohCie2ein2chaed9kaiyoo6zo1aeQu1yae4phooShov2oosh4ox", "index": 0 } } Copy bitcoin-cli \ -rpcconnect=127.0.0.1 \ -rpcport=18332 \ -rpcuser=btcuser \ -rpcpassword=btcpass \ createwallet "miner" \ false \ false \ "" \ false \ false \ true Copy bitcoin-cli \ -rpcport=18332 \ -rpcuser=btcuser \ -rpcpassword=btcpassword \ importprivkey Copy bitcoin-cli \ -rpcconnect=127.0.0.1 \ -rpcport=18332 \ -rpcuser=btcuser \ -rpcpassword=btcpass \ getaddressinfo Copy [node] working_dir = "/stacks-blockchain" rpc_bind = "0.0.0.0:20443" p2p_bind = "0.0.0.0:20444" seed = "" miner = true bootstrap_node = "029266faff4c8e0ca4f934f34996a96af481df94a89b0c9bd515f3536a95682ddc@seed.testnet.hiro.so:30444" mine_microblocks = false wait_time_for_microblocks = 10000 [burnchain] wallet_name = "miner" chain = "bitcoin" mode = "xenon" peer_host = "127.0.0.1" username = "" password = "" rpc_port = 18332 peer_port = 18333 [[ustx_balance]] address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2" amount = 10000000000000000 [[ustx_balance]] address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF" amount = 10000000000000000 [[ustx_balance]] address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H" amount = 10000000000000000 [[ustx_balance]] address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B" amount = 10000000000000000 Copy stacks-node start --config $HOME/testnet-miner-conf.toml Copy STACKS_LOG_DEBUG=1 stacks-node start --config $HOME/testnet-miner-conf.toml Copy docker run -i node:20-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r Copy docker run -d \ --name stacks_miner \ --rm \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ -v "$HOME/testnet-miner-conf.toml:/src/stacks-node/testnet-miner-conf.toml" \ -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-core:latest \ /bin/stacks-node start --config /src/stacks-node/testnet-miner-conf.toml Copy docker logs -f stacks_miner Copy 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="privateKey-from-generate-keychain-step" \ Copy kubectl logs -l app.kubernetes.io/name=stacks-blockchain sun-brightdesktopmoon --- # Stack with a Pool | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close This guide covers delegated stacking from the **delegator** perspective: how to delegate your STX to a pool, increase your delegation, revoke it, and stop stacking. circle-info This guide assumes you are familiar with stacking at a conceptual level. If not, read the [Stackingarrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/learn/block-production/stacking.md) concept guide first. Delegating is the most common stacking scenario. It applies when you do not meet the minimum STX threshold to solo stack and want a pool operator to stack on your behalf. This is a **non-custodial** delegation. Your STX do not leave your wallet. The minimum stacking amount is dynamic and can be found at the [pox endpointarrow-up-right](https://api.mainnet.hiro.so/v2/pox) under `min_threshold_ustx` (1 STX = 1,000,000 uSTX). circle-info Pool operators have control over how they implement stacking and reward distribution. Usually you will interact with a wrapper contract the pool operator has created. If you want to operate a pool instead, see the [Operate a Pool](https://docs.stacks.co/operate/stacking-stx/operate-a-pool) guide. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#delegate-to-a-pool) Delegate to a Pool ------------------------------------------------------------------------------------------------------------------- 1 **Find a pool** The Stacks website has a [page on stackingarrow-up-right](https://www.stacks.co/learn/stacking) that links to several pool operators. Do your research, as operators differ in reward distribution, fees, and trust models. 2 **Call** `**delegate-stx**` Use your pool operator's UI or call the function directly to delegate. This does not lock your STX. It gives the pool operator **permission** to stack on your behalf. chevron-rightFunction source code[hashtag](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#function-source-code) Copy ;; Delegate to `delegate-to` the ability to stack from a given address. ;; This method _does not_ lock the funds, rather, it allows the delegate ;; to issue the stacking lock. ;; The caller specifies: ;; * amount-ustx: the total amount of ustx the delegate may be allowed to lock ;; * until-burn-ht: an optional burn height at which this delegation expires ;; * pox-addr: an optional address to which any rewards *must* be sent (define-public (delegate-stx (amount-ustx uint) (delegate-to principal) (until-burn-ht (optional uint)) (pox-addr (optional { version: (buff 1), hashbytes: (buff 32) }))) (begin ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) ;; pox-addr, if given, must be valid (match pox-addr address (asserts! (check-pox-addr-version (get version address)) (err ERR_STACKING_INVALID_POX_ADDRESS)) true) ;; tx-sender must not be delegating (asserts! (is-none (get-check-delegation tx-sender)) (err ERR_STACKING_ALREADY_DELEGATED)) ;; add delegation record (map-set delegation-state { stacker: tx-sender } { amount-ustx: amount-ustx, delegated-to: delegate-to, until-burn-ht: until-burn-ht, pox-addr: pox-addr }) (ok true))) The arguments are: * **Amount**: Denoted in uSTX (1 STX = 1,000,000 uSTX). The maximum amount the pool operator is allowed to lock. * **Delegate to**: the STX address of the pool operator. * **Until burn height**: optional BTC block height when the delegation expires. If not set, the delegation permission expires only when explicitly revoked. * **Pox Address**: optional BTC address that, if specified, the pool operator must use when accepting this delegation. 3 **Pool operator stacks your tokens** Once you've delegated, the pool operator takes over. They call `delegate-stack-stx` to lock your STX, and then `stack-aggregation-commit-indexed` to commit the pool's total to the reward cycle. Your STX will be locked at this point. The pool operator may offer the option to automatically continue stacking for up to 12 continuous cycles. 4 **Pool operator distributes rewards** The pool operator tracks the proportion of rewards you've earned and distributes them in BTC or STX, depending on their model. Research your pool's reward distribution mechanism to ensure you understand and trust it. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#increase-your-delegation) Increase Your Delegation ------------------------------------------------------------------------------------------------------------------------------- To increase the amount of STX you've delegated, you need to revoke your current delegation and re-delegate with a higher amount. 1 **Revoke your current delegation** Call `revoke-delegate-stx` to cancel the existing delegation. See [Revoke and Stop Stacking](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#revoke-and-stop-stacking) below for details. 2 **Delegate with a higher amount** After the revocation is confirmed, call `delegate-stx` again with the new, higher amount to the same pool operator. circle-info Make sure the revocation is successful before initiating a new delegation. Otherwise, the `delegate-stx` transaction will fail. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#revoke-and-stop-stacking) Revoke and Stop Stacking ------------------------------------------------------------------------------------------------------------------------------- To stop stacking as a delegator, you must cancel the delegation with the pool operator by calling `revoke-delegate-stx`. chevron-rightFunction source code[hashtag](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#function-source-code-1) You can call this through the pool's interface or directly on the [pox-4arrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-4?chain=mainnet) contract. circle-exclamation Revoking delegation **does not immediately unlock** your STX. Your tokens remain locked until the end of the last stacking cycle chosen by the pool operator (can be at most 12 cycles). Revoking only prevents the pool from stacking your STX in future cycles. Failing to revoke means you continue to allow the pool to stack your STX until the burn block height specified in the `delegate-stx` call. After revoking, wait for the current lock period to expire. The unlock occurs automatically. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#liquid-stacking) Liquid Stacking ------------------------------------------------------------------------------------------------------------- Liquid stacking is when you delegate your STX to a liquid stacking provider who issues you a new token (e.g., stSTX) that you can use in the ecosystem while your STX are locked. This lets you participate in DeFi protocols even while stacking. Links to liquid stacking providers can be found on the [Stacks websitearrow-up-right](https://www.stacks.co/learn/stacking) . * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#considerations) Considerations ----------------------------------------------------------------------------------------------------------- * **Monitor your stacking status**: Use your wallet's interface or the [Hiro Explorerarrow-up-right](https://explorer.hiro.so/?chain=mainnet) to track your lock period. * **Using the API**: Hiro's API offers an endpoint to [Get account STX balancearrow-up-right](https://docs.hiro.so/stacks/api/accounts/stx-balances) , which includes the `burnchain_unlock_height` representing when your STX unlock. * **Plan ahead**: Unlocking is bound to cycle timing. Plan your revocation accordingly to minimize delays in accessing your funds. [PreviousSolo Stackingchevron-left](https://docs.stacks.co/operate/stacking-stx/solo-stacking) [NextOperate a Poolchevron-right](https://docs.stacks.co/operate/stacking-stx/operate-a-pool) Last updated 12 days ago Was this helpful? * [Delegate to a Pool](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#delegate-to-a-pool) * [Increase Your Delegation](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#increase-your-delegation) * [Revoke and Stop Stacking](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#revoke-and-stop-stacking) * [Liquid Stacking](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#liquid-stacking) * [Considerations](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool#considerations) Was this helpful? sun-brightdesktopmoon Copy ;; Revokes the delegation to the current stacking pool. ;; New in pox-4: Fails if the delegation was already revoked. ;; Returns the last delegation state. (define-public (revoke-delegate-stx) (let ((last-delegation-state (get-check-delegation tx-sender))) ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) (asserts! (is-some last-delegation-state) (err ERR_DELEGATION_ALREADY_REVOKED)) (asserts! (map-delete delegation-state { stacker: tx-sender }) (err ERR_DELEGATION_ALREADY_REVOKED)) (ok last-delegation-state))) sun-brightdesktopmoon --- # Transacciones | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Las transacciones son un componente clave de la red Stacks y son la forma principal en que los usuarios interactuarán con ella. En esta sección, explicaremos cómo funcionan las transacciones y ofreceremos una introducción a las condiciones posteriores (post conditions), una característica de seguridad adicional de Stacks que permite a los desarrolladores del lado del cliente imponer ciertas condiciones para proteger a los usuarios de interactuar con contratos maliciosos. [AnteriorIncentivo financiero y presupuesto de seguridadchevron-left](https://docs.stacks.co/learn/es/block-production/financial-incentive-and-security-budget) [SiguienteCómo funcionan las transaccioneschevron-right](https://docs.stacks.co/learn/es/transactions/how-transactions-work) Última actualización hace 2 meses ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Counter | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/counter#contract-summary) Contract Summary ------------------------------------------------------------------------------------------------------------------- The Counter contract is a simple on-chain counter that maintains individual count values for each principal address. This minimalist contract demonstrates fundamental Clarity data structures and state management patterns. **What this contract does:** * Stores a separate counter value for each user (principal) * Provides read-only access to retrieve any user's count * Allows users to increment their own counter by 1 * Initializes counters at 0 for new users automatically **What developers can learn:** * How to use `define-map` to create key-value storage in Clarity * Pattern for per-user state management using principal addresses * Using `default-to` to handle missing map entries gracefully * Simple read-only vs public function distinction * Basic arithmetic operations and map updates with `map-set` * The `tx-sender` context variable for identifying callers [PreviousFungible Tokenchevron-left](https://docs.stacks.co/cookbook/clarity/example-contracts/fungible-token) Was this helpful? Was this helpful? sun-brightdesktopmoon counter.clar Copy ;; An on-chain counter that stores a count for each individual ;; Define a map data structure (define-map counters principal uint ) ;; Function to retrieve the count for a given individual (define-read-only (get-count (who principal)) (default-to u0 (map-get? counters who)) ) ;; Function to increment the count for the caller (define-public (count-up) (ok (map-set counters tx-sender (+ (get-count tx-sender) u1))) ) chevron-downShow all 17 lines sun-brightdesktopmoon --- # Tokens | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fi9dfCzjxY5JQnXBsDXw4%252Ftokens-network-fundamentals-cover.png%3Falt%3Dmedia%26token%3Df2cf2cd7-128f-4153-844b-57aff84c8179&width=768&dpr=3&quality=100&sign=daf14bb&sv=2) ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#stx) STX Los tokens Stacks (STX) son los tokens nativos en la red Stacks. La fracción más pequeña es un micro-STX: 1.000.000 de micro-STX hacen un Stacks (STX). Las cantidades de STX deben almacenarse como enteros (de 8 bytes) y representan la cantidad de micro-STX. STX es central para el mecanismo de consenso de la capa Bitcoin de Stacks, discutido más abajo, y es esencial para dos objetivos clave: (i) incentiva la minería de bloques de Stacks con un “subsidio por nuevo bloque”, lo cual es crítico dado que las comisiones por transacción no son suficientes para sostener un libro mayor, al menos en los primeros días (como ocurre con el propio Bitcoin), y (ii) sirve como incentivo de disponibilidad y la base para el anclaje descentralizado asegurado económicamente con Bitcoin. chevron-right¿Por qué necesita Stacks un token?[hashtag](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#por-que-necesita-stacks-un-token) Esto nos lleva a una conversación filosófica central en el mundo de las criptomonedas y Bitcoin: si las cadenas de bloques necesitan o no tokens. Empecemos mirando la razón fundamental por la que existen los tokens: financiar el mantenimiento y el progreso de una cadena de bloques. Bitcoin es un token. Es una criptomoneda que se usa para incentivar a los mineros a añadir nuevos bloques a la cadena. En el caso de Bitcoin, las recompensas por minería están fijadas en un calendario predefinido, y una vez que esas recompensas se agoten, la cadena tendrá que sobrevivir únicamente con las comisiones por transacción. El propósito de una cadena de bloques es tener un registro histórico permanente de cada transacción que haya ocurrido en la cadena. Las cadenas de bloques son básicamente libros contables. El aspecto del token se usa como un mecanismo de incentivos para asegurar y mantener la cadena. Por eso las redes como Lightning y otras redes P2P no necesitan tokens: no necesitan mantener un registro histórico. Las soluciones basadas en canales como Lightning dependen de que los usuarios abran multisigs 2-de-2 entre sí. Una vez que esos canales se cierran, el estado desaparece. Cuando hablamos de un sistema que se supone que mantenga un sistema financiero global, es importante que el mantenimiento de ese sistema esté incentivado correctamente. Examinemos este concepto en el contexto de Stacks y sus objetivos. Stacks busca proporcionar funcionalidad de contratos inteligentes a Bitcoin, para servir como los rieles de programación para construir una economía descentralizada encima de Bitcoin. Muchos miembros de la comunidad Bitcoin son escépticos respecto a nuevos tokens y con razón. Hay innumerables proyectos que imponen el uso de un token en su proyecto y en muchos casos un token en realidad no es necesario. El proyecto Stacks fue iniciado por desarrolladores de Bitcoin que tienen una larga historia construyendo aplicaciones y protocolos en Bitcoin L1 sin ningún token (p. ej., BNS se lanzó en 2015 en Bitcoin L1 y fue uno de los mayores protocolos que usó OP\_RETURN en Bitcoin L1). Entonces, ¿por qué un grupo de desarrolladores de Bitcoin decidió tener un token separado para Stacks L2? ¡Buena pregunta! Profundicemos en los detalles. El token de Stacks (STX) está pensado principalmente para utilizarse en dos cosas: 1. **Incentivos para los mineros de Stacks L2**: STX recién acuñados se utilizan para incentivar la producción descentralizada de bloques en Stacks L2. 2. **Incentivos para los firmantes de peg-out**: Los firmantes que participan en operaciones de peg-out reciben incentivos en STX para alinearlos económicamente con las reglas del protocolo. La única forma de eliminar el token es construir Stacks como una red federada como Liquid. En una federación, el grupo preseleccionado de empresas controla la minería y la producción de bloques y se necesita confiar en ese grupo preseleccionado de empresas para las transacciones de peg-out. Los desarrolladores de Stacks querían diseñar un sistema abierto y sin permisos. La única forma de tener un proceso de minería descentralizado es mediante incentivos. Como se mencionó arriba, así es como funciona Bitcoin también, donde BTC recién acuñados se usan como incentivos para minar nuevos bloques y cualquier persona en el mundo puede decidir convertirse en minero. Cualquiera con BTC puede minar la cadena Stacks L2; es abierta y sin permisos. De manera similar, el diseño de sBTC hace que el grupo de firmantes sea abierto y sin permisos (a diferencia de una federación). Estos firmantes tienen incentivos económicos para seguir correctamente el protocolo en las solicitudes de peg-out. En una federación, los usuarios deben confiar ciegamente en los miembros preestablecidos de la federación para sacar sus BTC de la federación y devolverlos a Bitcoin L1. Los desarrolladores de Stacks querían tener una forma abierta, sin permisos y descentralizada de mover BTC desde Bitcoin L1 a Stacks L2 y de regreso. Esto es posible mediante incentivos económicos, es decir, la necesidad de un token. Además de estas dos razones, STX también se utiliza para pagar las comisiones de gas por las transacciones. Sin embargo, una vez que el próximo anclaje sBTC esté activo, se espera que gran parte de la economía de Stacks L2 siga un estándar de Bitcoin y funcione usando BTC como unidad económica. Se espera que los usuarios interactúen principalmente solo con Bitcoin y usen BTC en billeteras y aplicaciones (las comisiones de gas pueden pagarse con BTC usando intercambios atómicos en segundo plano). Es importante notar que BTC no puede usarse para incentivos de minería en Stacks L2 porque la única forma de incentivar la producción descentralizada de bloques es mediante activos recién acuñados por el protocolo (similar a cómo funciona el propio Bitcoin), es decir, la necesidad de un token. [Cómo obtener STX](https://youtu.be/Khfl50J7v6s?si=AkG2x9VIWsrCUoSL) ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#sbtc) sBTC sBTC es un anclaje bidireccional descentralizado y con minimización de confianza entre Bitcoin y la blockchain de Stacks. Implementado como un token fungible conforme con SIP-010 en Stacks, sBTC permite a los poseedores de Bitcoin representar de forma segura sus BTC como tokens en la cadena Stacks sin depender de una única entidad de confianza. Este puente permite que Bitcoin se integre sin problemas en el ecosistema Stacks, ampliando significativamente la utilidad de Bitcoin mediante contratos inteligentes programables mientras mantiene sus propiedades fundamentales de seguridad. [Aprende más sobre sBTC](https://docs.stacks.co/learn/es/sbtc) ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#tokens-fungibles-sip-010) Tokens fungibles SIP-010 [SIP-010arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) es el estándar para definir tokens fungibles en Stacks. Definir una interfaz común (conocida en Clarity como un "trait") permite que diferentes contratos inteligentes, aplicaciones y billeteras interoperen con contratos de tokens fungibles de una manera reutilizable. [Crear un token fungible](https://docs.stacks.co/get-started/create-a-token/fungible-tokens) ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#tokens-no-fungibles-sip-009) Tokens no fungibles SIP-009 [SIP-009arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-009/sip-009-nft-standard.md) es el estándar para definir tokens no fungibles en Stacks. Definir una interfaz común (conocida en Clarity como un "trait") permite que diferentes contratos inteligentes, aplicaciones y billeteras interoperen con contratos de tokens no fungibles de una manera reutilizable. Su propósito principal es asegurar que los NFT sean composables y que distintas herramientas sepan cómo interactuar con ellos. [Crear un token no fungible](https://docs.stacks.co/get-started/create-a-token/non-fungible-tokens) ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#tokens-semi-fungibles-sip-013) Tokens semi-fungibles SIP-013 Los tokens semi-fungibles (SFTs) son una estructura de token híbrida que adopta partes tanto de los FT (tokens fungibles) como de los NFT. Los SFT son intercambiables (como los FT) y pueden ser negociados entre usuarios como efectivo: 1 SFT tiene el mismo valor que otro SFT en la misma colección. Pero cada SFT también tiene un identificador único (como los NFT). [SIP-013arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-013/sip-013-semi-fungible-token-standard.md) es el estándar para definir tokens semi-fungibles en Stacks. Definir una interfaz común (conocida en Clarity como un "trait") permite que diferentes contratos inteligentes, aplicaciones y billeteras interoperen con contratos de tokens semi-fungibles de una manera estándar y reutilizable. [Crear un token semi-fungible](https://docs.stacks.co/get-started/create-a-token/semi-fungible-tokens) [AnteriorMainnet y Testnetschevron-left](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets) [SiguienteBilleteras y cuentaschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/wallets-and-accounts) Última actualización hace 1 mes ¿Te fue útil? * [STX](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#stx) * [sBTC](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#sbtc) * [Tokens fungibles SIP-010](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#tokens-fungibles-sip-010) * [Tokens no fungibles SIP-009](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#tokens-no-fungibles-sip-009) * [Tokens semi-fungibles SIP-013](https://docs.stacks.co/learn/es/network-fundamentals/network-basics#tokens-semi-fungibles-sip-013) ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Fungible Token | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/fungible-token#contract-summary) Contract Summary -------------------------------------------------------------------------------------------------------------------------- A complete implementation of a SIP-010 compliant fungible token called "Clarity Coin" with standard transfer, balance query, and minting capabilities. This contract serves as a template for creating custom fungible tokens on the Stacks blockchain. **What this contract does:** * Implements the full SIP-010 fungible token standard trait * Creates a fungible token with no maximum supply * Provides standard token metadata (name, symbol, decimals, URI) * Enables token transfers between principals with optional memo field * Allows the contract owner to mint new tokens * Tracks balances and total supply automatically * Uses 6 decimal places for token precision (micro-units) **What developers can learn:** * How to implement the SIP-010 fungible token trait correctly * Defining and working with fungible tokens using `define-fungible-token` * Built-in Clarity functions for token operations (`ft-mint?`, `ft-transfer?`, `ft-get-balance`, `ft-get-supply`) * Owner-only access control patterns for privileged operations * Handling optional parameters (memo field) with `match` * Token decimal precision and display conventions * Preventing unauthorized transfers with sender validation * Returning standardized responses that comply with trait requirements * Using constants for immutable contract configuration * Filter annotations for security analysis (`#[filter]`) [PreviousNon-Fungible tokenchevron-left](https://docs.stacks.co/cookbook/clarity/example-contracts/non-fungible-token) [NextCounterchevron-right](https://docs.stacks.co/cookbook/clarity/example-contracts/counter) Was this helpful? Was this helpful? sun-brightdesktopmoon fungible-token.clar Copy ;; This contract implements the SIP-010 community-standard Fungible Token trait. (impl-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) ;; Define the FT, with no maximum supply (define-fungible-token clarity-coin) ;; Define errors (define-constant ERR_OWNER_ONLY (err u100)) (define-constant ERR_NOT_TOKEN_OWNER (err u101)) ;; Define constants for contract (define-constant CONTRACT_OWNER tx-sender) (define-constant TOKEN_URI u"https://hiro.so") ;; utf-8 string with token metadata host (define-constant TOKEN_NAME "Clarity Coin") (define-constant TOKEN_SYMBOL "CC") (define-constant TOKEN_DECIMALS u6) ;; 6 units displayed past decimal, e.g. 1.000_000 = 1 token ;; SIP-010 function: Get the token balance of a specified principal (define-read-only (get-balance (who principal)) (ok (ft-get-balance clarity-coin who)) ) ;; SIP-010 function: Returns the total supply of fungible token (define-read-only (get-total-supply) (ok (ft-get-supply clarity-coin)) ) ;; SIP-010 function: Returns the human-readable token name (define-read-only (get-name) (ok TOKEN_NAME) ) ;; SIP-010 function: Returns the symbol or "ticker" for this token (define-read-only (get-symbol) (ok TOKEN_SYMBOL) ) ;; SIP-010 function: Returns number of decimals to display (define-read-only (get-decimals) (ok TOKEN_DECIMALS) ) ;; SIP-010 function: Returns the URI containing token metadata (define-read-only (get-token-uri) (ok (some TOKEN_URI)) ) ;; Mint new tokens and send them to a recipient. ;; Only the contract deployer can perform this operation. (define-public (mint (amount uint) (recipient principal) ) (begin (asserts! (is-eq tx-sender CONTRACT_OWNER) ERR_OWNER_ONLY) (ft-mint? clarity-coin amount recipient) ) ) ;; SIP-010 function: Transfers tokens to a recipient ;; Sender must be the same as the caller to prevent principals from transferring tokens they do not own. (define-public (transfer (amount uint) (sender principal) (recipient principal) (memo (optional (buff 34))) ) (begin ;; #[filter(amount, recipient)] (asserts! (or (is-eq tx-sender sender) (is-eq contract-caller sender)) ERR_NOT_TOKEN_OWNER ) (try! (ft-transfer? clarity-coin amount sender recipient)) (match memo to-print (print to-print) 0x ) (ok true) ) ) chevron-downShow all 80 lines sun-brightdesktopmoon --- # Finalidad en Bitcoin | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FeLcV1YS0P5CjH00KWDDw%252Fbitcoin-finality.png%3Falt%3Dmedia%26token%3D260ac527-3228-4081-955a-f0d2d59ec979&width=768&dpr=3&quality=100&sign=9bed5ab7&sv=2) El concepto de finalización del 100% en Bitcoin es crucial para el diseño de Stacks. Esto es lo que convierte a Stacks en una verdadera capa 2 de Bitcoin y le permite aprovechar toda la seguridad inherente a Bitcoin. La finalización se refiere al punto en el que las transacciones son irreversibles. Una vez que una blockchain alcanza la finalización, es casi imposible cambiar la historia del libro mayor sin emprender medidas extraordinarias que a menudo son prohibitivas tanto computacional como económicamente. Cuando hablamos de que los bloques de Stacks tienen finalización del 100% en Bitcoin, queremos decir que son tan difíciles de revertir como las propias transacciones de Bitcoin. Esa es una afirmación audaz; entonces, ¿cómo logra Stacks eso? Como se comentó anteriormente, los mineros son responsables de producir los bloques de Stacks durante su periodo, que corresponde a un solo bloque de Bitcoin. Como parte de su transacción de confirmación de bloque, que es la transacción que previamente comprometía el hash del siguiente bloque de Stacks en la cadena de Bitcoin, a los mineros se les exigirá en su lugar añadir un hash de bloque indexado. El hash de bloque indexado es el hash del primer bloque producido por el último minero de Stacks en su periodo. Este es el hash SHA512/256 tanto del hash de consenso de todas las transacciones de Bitcoin previamente aceptadas que Stacks reconoce, como del hash del propio bloque. Esto anclará la historia de la cadena de Stacks a Bitcoin hasta el inicio del periodo del minero anterior, así como todo el estado de Bitcoin causalmente dependiente que Stacks haya procesado. Esto garantiza la finalización de Bitcoin, resuelve problemas de conectividad de los mineros al poner la prevención de forks en los stackers, y permite que los nodos con copias actualizadas del estado de la cadena de Stacks identifiquen qué bloques de Stacks se ven afectados por una reorganización de Bitcoin y recuperen las transacciones de Stacks afectadas. Esta relación entre stackers, mineros, bloques de Bitcoin y bloques de Stacks es lo que mantiene la finalización de Bitcoin mientras permite a los mineros producir bloques de Stacks rápidamente. La finalización de Bitcoin se logra porque en cada bloque de Bitcoin N + 1, el estado de la cadena de Stacks al inicio del periodo N se escribe en Bitcoin. Incluso si en una fecha futura todas las claves de firma de los antiguos stackers fueran comprometidas, no podrían reescribir la historia de Stacks para el periodo N sin reescribir la historia de Bitcoin hasta el periodo N + 1. Debido a esto, las transacciones de Stacks pueden considerarse que tienen finalización en Bitcoin después de que concluya el periodo del que forman parte, es decir, el bloque de Bitcoin N + 1. Por ejemplo, si inicio una transacción en Stacks que es confirmada por un minero de Stacks, al concluir el periodo de ese minero (el final del bloque actual de Bitcoin) esa transacción se escribirá en Bitcoin como parte del estado de la cadena de Stacks y todos los mineros futuros estarán obligados a construir sobre esa punta de cadena, haciendo que revertir la transacción sea tan difícil como revertir la transacción correspondiente en Bitcoin. circle-info Punto clave: En cada bloque de Bitcoin N + 1, el estado de la cadena de Stacks al inicio del periodo N queda anclado a Bitcoin. Esto hace que revertir la historia de Stacks para el periodo N sea tan difícil como reescribir la historia de Bitcoin hasta N + 1. [hashtag](https://docs.stacks.co/learn/es/block-production/bitcoin-finality#transacciones-nakamoto-y-reorganizaciones-de-bitcoin) Transacciones Nakamoto y reorganizaciones de Bitcoin ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Si las transacciones Nakamoto siguen la finalización de Bitcoin, ¿qué sucede si Bitcoin hace un fork? Para responder a esta pregunta, necesitamos distinguir entre dos tipos de transacciones de Stacks: dependientes de Bitcoin e internas. circle-info * **Dependientes de Bitcoin** son transacciones que leen el estado de Bitcoin. Si Bitcoin hace un fork, estas transacciones cambiarán. Para estas, no se puede hacer mejor que seguir la finalización de Bitcoin. Por ejemplo, si moviste BTC de L1 a L2, debes esperar la finalización de Bitcoin antes de que tus BTC en L2 puedan usarse (no tienes BTC en L2 si la transacción en L1 queda sin confirmar debido a un fork). * **Internas** las transacciones no dependen del estado de Bitcoin y, por lo tanto, no cambiarán si Bitcoin hace un fork. Estas pueden tener confirmaciones más rápidas porque, incluso si Bitcoin hace un fork, los firmantes pueden asegurarse de que se vuelvan a procesar en el mismo orden. La idea clave es la siguiente: Bajo Nakamoto Stacks, las transacciones no se reorganizarán de forma impactante debido a un fork de Bitcoin. No solo las reorganizaciones son relativamente infrecuentes, sino que las transacciones en Stacks que se reorganizaron debido a un fork de Bitcoin se comportan igual que las transacciones reorganizadas de Bitcoin. Con algún análisis futuro, las transacciones puramente en la cadena L2 podrían algún día quedar totalmente sin afectación. chevron-rightLee más sobre el comportamiento de las reorganizaciones de Bitcoin[hashtag](https://docs.stacks.co/learn/es/block-production/bitcoin-finality#lee-mas-sobre-el-comportamiento-de-las-reorganizaciones-de-bitcoin) Si estás interesado en aprender más sobre cómo funciona esto, consulta la [Reorganizaciones de Bitcoin](https://docs.stacks.co/learn/es/block-production/bitcoin-reorgs) página de la documentación. * * * [AnteriorSigningchevron-left](https://docs.stacks.co/learn/es/block-production/signing) [SiguienteReorganizaciones de Bitcoinchevron-right](https://docs.stacks.co/learn/es/block-production/bitcoin-reorgs) Última actualización hace 1 mes ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Solo Stacking | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close This guide covers everything you need to stack independently as a solo stacker: starting, extending, increasing, and stopping your stacking position. circle-info This guide assumes you are familiar with stacking at a conceptual level. If not, read the [Stackingarrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/learn/block-production/stacking.md) concept guide first. Solo stacking requires meeting the minimum STX threshold and either running a signer or collaborating with one. The minimum amount is dynamic and can be found at the [pox endpointarrow-up-right](https://api.mainnet.hiro.so/v2/pox) under `min_threshold_ustx` (1 STX = 1,000,000 uSTX). circle-info [Degen Labarrow-up-right](https://solo.stacking.tools/) provides a solo stacking dapp that lets you stack without running your own signer, as they operate one on your behalf. This is likely the easiest option for solo stacking. If you don't meet the stacking minimum, see the [Stack with a Pool](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool) guide instead. [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#prerequisites) Prerequisites ----------------------------------------------------------------------------------------------------- Before you begin, make sure you have: 1. **A running signer** or a signer you are collaborating with. See the [Run a Signer](https://docs.stacks.co/operate/run-a-signer) guide. 2. **A signer key signature** for the stacking transaction you want to make. See [Generate a Signer Signature](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) . 3. **Sufficient STX**: at or above the minimum stacking threshold. circle-info There are several ways to make stacking transactions. This guide covers using [Leather Earnarrow-up-right](https://earn.leather.io/) , which is the simplest option. You can also call the stacking functions directly from the [deployed contractarrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-4?chain=mainnet) in the explorer, or use the [@stacks/stackingarrow-up-right](https://github.com/stx-labs/stacks.js/tree/main/packages/stacking) NPM package. The functions and parameters are the same regardless of method. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#start-stacking) Start Stacking ------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#call-stack-stx) Call `stack-stx` chevron-rightFunction source code[hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#function-source-code) The arguments are: * **Amount**: Denoted in uSTX (1 STX = 1,000,000 uSTX) * **PoX Address**: the BTC wallet address where you will receive stacking rewards * **Start burn height**: the current BTC block height * **Lock period**: the number of cycles to lock for (between 1 and 12) * **Signer key**: the public key that your signer is using * **Signer signature**: a signature that proves control of this signer key (see [Generate a Signer Signature](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) ) * **Max Amount**: used to validate the signer signature; represents the maximum number of uSTX that can be stacked in this transaction * **Auth Id**: used to validate the signer signature; a random integer that prevents re-use of this particular signature ### [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#using-leather-earn) Using Leather Earn Visit [Leather Earnarrow-up-right](https://earn.leather.io/) and click the "Stack independently" button on the home page. You will be prompted to enter: * The amount of STX to lock * The duration (number of cycles) to lock for * Your BTC address for stacking rewards * Your signer public key * Your signer key signature * Auth ID * Max amount circle-info When using Leather Earn, you can paste the JSON output from the signature generation step directly into the form. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#acting-as-a-signer-vs.-working-with-one) Acting as a signer vs. working with one **Option 1: Act as a signer.** If you run your own signer, ensure it is running during the prepare phase (last 100 blocks before the next cycle). This is when distributed key generation (DKG) occurs. You don't need to do anything actively during this period other than monitoring your signer. **Option 2: Work with a signer.** If you don't want to run a signer yourself, you can collaborate with an existing one. You'll need their signer key and a signer signature generated for your stacking transaction. [Degen Lab's solo stacking dapparrow-up-right](https://solo.stacking.tools/) simplifies this process by providing their signer for you to use. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#extend-your-lock-period) Extend Your Lock Period ------------------------------------------------------------------------------------------------------------------------- You can extend your lock period while actively stacking by calling `stack-extend`. You can also rotate your signer key and change your Bitcoin reward address as part of this call. chevron-rightFunction source code[hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#function-source-code-1) The arguments are: * **Extend count**: the number of cycles to add to your lock period. The resulting total lock period cannot exceed 12. For example, if you have 6 cycles remaining, the maximum you can extend is 6. * **Pox Address**: the BTC address to receive rewards. This can be changed from your original address. * **Signer public key**: the public key used for signing. This can stay the same, or you can rotate to a new key. See [Key and Address Rotation](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation) . * **Signer signature**: a signature proving control of your signing key (see [Generate a Signer Signature](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) ) * **Max Amount**: used to validate the signer signature * **Auth Id**: used to validate the signer signature ### [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#using-leather-earn-1) Using Leather Earn If you're already stacking, the Leather Earn home page will show a link to "view stacking details". From there, you can choose to extend. The form asks for: * The number of cycles to extend for * Your BTC address for rewards * Signer public key * Signer key signature * Auth ID * Max amount * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#increase-your-stacked-amount) Increase Your Stacked Amount ----------------------------------------------------------------------------------------------------------------------------------- You can increase the amount of STX locked while actively stacking. The increased position takes effect starting with the next stacking cycle. Call the `stack-increase` function. chevron-rightFunction source code[hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#function-source-code-2) The arguments are: * **Increase by**: the amount of uSTX to add to your locked amount * **Signer public key**: the public key used for signing. This can stay the same, or you can use a new key. * **Signer signature**: a signature proving control of your signing key (see [Generate a Signer Signature](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) ) * **Max Amount**: used to validate the signer signature; represents the maximum number of uSTX (1 STX = 1,000,000 uSTX) that can be stacked in this transaction * **Auth Id**: used to validate the signer signature ### [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#using-leather-earn-2) Using Leather Earn If you're already stacking, the home page will show a link to "view stacking details". From there, choose to increase. The form asks for: * The amount of STX to increase by * Signer public key * Signer key signature * Auth ID * Max amount * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#stop-stacking) Stop Stacking ----------------------------------------------------------------------------------------------------- When stacking solo, your STX is locked for a fixed period defined when you initiated stacking or extended the lock period. **No additional action is required to stop stacking.** Your tokens unlock automatically when the lock period expires. circle-info Both the `stack-stx` and `stack-extend` functions emit an event that includes the `unlock-burn-height` field. This is the burn block height at which your tokens will be automatically unlocked. To avoid your position being extended, simply do not call `stack-extend` before the current lock period ends. Once the lock period expires, your STX will be returned to your account. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#monitoring-your-unlock) Monitoring your unlock * Use your wallet's interface or the [Hiro Explorerarrow-up-right](https://explorer.hiro.so/?chain=mainnet) to track the status of your lock period. * Hiro's API offers an endpoint to [Get account STX balancearrow-up-right](https://docs.hiro.so/stacks/api/accounts/stx-balances) , which includes the `burnchain_unlock_height` representing when your STX unlock. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/solo-stacking#how-signer-registration-works) How Signer Registration Works ------------------------------------------------------------------------------------------------------------------------------------- In the prepare phase before the next stacking cycle (last 100 blocks), the signer set is selected based on the amount of STX stacked. For solo stackers, the only transaction needed is `stack-stx`. Once it is confirmed during the first 2000 blocks of the current reward cycle, your signer will be registered in the next cycle's signer set. It is critical that your signer is running during the prepare phase. This is when DKG occurs, and the signer automatically participates. No manual action is required beyond monitoring. [PreviousStacking STXchevron-left](https://docs.stacks.co/operate/stacking-stx) [NextStack with a Poolchevron-right](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool) Last updated 12 days ago Was this helpful? * [Prerequisites](https://docs.stacks.co/operate/stacking-stx/solo-stacking#prerequisites) * [Start Stacking](https://docs.stacks.co/operate/stacking-stx/solo-stacking#start-stacking) * [Call stack-stx](https://docs.stacks.co/operate/stacking-stx/solo-stacking#call-stack-stx) * [Using Leather Earn](https://docs.stacks.co/operate/stacking-stx/solo-stacking#using-leather-earn) * [Acting as a signer vs. working with one](https://docs.stacks.co/operate/stacking-stx/solo-stacking#acting-as-a-signer-vs.-working-with-one) * [Extend Your Lock Period](https://docs.stacks.co/operate/stacking-stx/solo-stacking#extend-your-lock-period) * [Using Leather Earn](https://docs.stacks.co/operate/stacking-stx/solo-stacking#using-leather-earn-1) * [Increase Your Stacked Amount](https://docs.stacks.co/operate/stacking-stx/solo-stacking#increase-your-stacked-amount) * [Using Leather Earn](https://docs.stacks.co/operate/stacking-stx/solo-stacking#using-leather-earn-2) * [Stop Stacking](https://docs.stacks.co/operate/stacking-stx/solo-stacking#stop-stacking) * [Monitoring your unlock](https://docs.stacks.co/operate/stacking-stx/solo-stacking#monitoring-your-unlock) * [How Signer Registration Works](https://docs.stacks.co/operate/stacking-stx/solo-stacking#how-signer-registration-works) Was this helpful? sun-brightdesktopmoon Copy ;; Lock up some uSTX for stacking! Note that the given amount here is in micro-STX (uSTX). ;; The STX will be locked for the given number of reward cycles (lock-period). ;; This is the self-service interface. tx-sender will be the Stacker. ;; ;; * The given stacker cannot currently be stacking. ;; * You will need the minimum uSTX threshold. This will be determined by (get-stacking-minimum) ;; at the time this method is called. ;; * You may need to increase the amount of uSTX locked up later, since the minimum uSTX threshold ;; may increase between reward cycles. ;; * You need to provide a signer key to be used in the signer DKG process. ;; * The Stacker will receive rewards in the reward cycle following `start-burn-ht`. ;; Importantly, `start-burn-ht` may not be further into the future than the next reward cycle, ;; and in most cases should be set to the current burn block height. ;; ;; To ensure that the Stacker is authorized to use the provided `signer-key`, the stacker ;; must provide either a signature have an authorization already saved. Refer to ;; `verify-signer-key-sig` for more information. ;; ;; The tokens will unlock and be returned to the Stacker (tx-sender) automatically. (define-public (stack-stx (amount-ustx uint) (pox-addr (tuple (version (buff 1)) (hashbytes (buff 32)))) (start-burn-ht uint) (lock-period uint) (signer-sig (optional (buff 65))) (signer-key (buff 33)) (max-amount uint) (auth-id uint)) ;; this stacker's first reward cycle is the _next_ reward cycle (let ((first-reward-cycle (+ u1 (current-pox-reward-cycle))) (specified-reward-cycle (+ u1 (burn-height-to-reward-cycle start-burn-ht)))) ;; the start-burn-ht must result in the next reward cycle, do not allow stackers ;; to "post-date" their `stack-stx` transaction (asserts! (is-eq first-reward-cycle specified-reward-cycle) (err ERR_INVALID_START_BURN_HEIGHT)) ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) ;; tx-sender principal must not be stacking (asserts! (is-none (get-stacker-info tx-sender)) (err ERR_STACKING_ALREADY_STACKED)) ;; tx-sender must not be delegating (asserts! (is-none (get-check-delegation tx-sender)) (err ERR_STACKING_ALREADY_DELEGATED)) ;; the Stacker must have sufficient unlocked funds (asserts! (>= (stx-get-balance tx-sender) amount-ustx) (err ERR_STACKING_INSUFFICIENT_FUNDS)) ;; Validate ownership of the given signer key (try! (consume-signer-key-authorization pox-addr (- first-reward-cycle u1) "stack-stx" lock-period signer-sig signer-key amount-ustx max-amount auth-id)) ;; ensure that stacking can be performed (try! (can-stack-stx pox-addr amount-ustx first-reward-cycle lock-period)) ;; register the PoX address with the amount stacked (let ((reward-set-indexes (try! (add-pox-addr-to-reward-cycles pox-addr first-reward-cycle lock-period amount-ustx tx-sender signer-key)))) ;; add stacker record (map-set stacking-state { stacker: tx-sender } { pox-addr: pox-addr, reward-set-indexes: reward-set-indexes, first-reward-cycle: first-reward-cycle, lock-period: lock-period, delegated-to: none }) ;; return the lock-up information, so the node can actually carry out the lock. (ok { stacker: tx-sender, lock-amount: amount-ustx, signer-key: signer-key, unlock-burn-height: (reward-cycle-to-burn-height (+ first-reward-cycle lock-period)) })))) Copy ;; Extend an active Stacking lock. ;; *New in Stacks 2.1* ;; This method extends the `tx-sender`'s current lockup for an additional `extend-count` ;; and associates `pox-addr` with the rewards, The `signer-key` will be the key ;; used for signing. The `tx-sender` can thus decide to change the key when extending. ;; ;; Because no additional STX are locked in this function, the `amount` field used ;; to verify the signer key authorization is zero. Refer to `verify-signer-key-sig` for more information. (define-public (stack-extend (extend-count uint) (pox-addr { version: (buff 1), hashbytes: (buff 32) }) (signer-sig (optional (buff 65))) (signer-key (buff 33)) (max-amount uint) (auth-id uint)) (let ((stacker-info (stx-account tx-sender)) ;; to extend, there must already be an etry in the stacking-state (stacker-state (unwrap! (get-stacker-info tx-sender) (err ERR_STACK_EXTEND_NOT_LOCKED))) (amount-ustx (get locked stacker-info)) (unlock-height (get unlock-height stacker-info)) (cur-cycle (current-pox-reward-cycle)) ;; first-extend-cycle will be the cycle in which tx-sender *would have* unlocked (first-extend-cycle (burn-height-to-reward-cycle unlock-height)) ;; new first cycle should be max(cur-cycle, stacker-state.first-reward-cycle) (cur-first-reward-cycle (get first-reward-cycle stacker-state)) (first-reward-cycle (if (> cur-cycle cur-first-reward-cycle) cur-cycle cur-first-reward-cycle))) ;; must be called with positive extend-count (asserts! (>= extend-count u1) (err ERR_STACKING_INVALID_LOCK_PERIOD)) ;; stacker must be directly stacking (asserts! (> (len (get reward-set-indexes stacker-state)) u0) (err ERR_STACKING_IS_DELEGATED)) ;; stacker must not be delegating (asserts! (is-none (get delegated-to stacker-state)) (err ERR_STACKING_IS_DELEGATED)) ;; Verify signature from delegate that allows this sender for this cycle (try! (consume-signer-key-authorization pox-addr cur-cycle "stack-extend" extend-count signer-sig signer-key u0 max-amount auth-id)) (let ((last-extend-cycle (- (+ first-extend-cycle extend-count) u1)) (lock-period (+ u1 (- last-extend-cycle first-reward-cycle))) (new-unlock-ht (reward-cycle-to-burn-height (+ u1 last-extend-cycle)))) ;; first cycle must be after the current cycle (asserts! (> first-extend-cycle cur-cycle) (err ERR_STACKING_INVALID_LOCK_PERIOD)) ;; lock period must be positive (asserts! (> lock-period u0) (err ERR_STACKING_INVALID_LOCK_PERIOD)) ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) ;; tx-sender must be locked (asserts! (> amount-ustx u0) (err ERR_STACK_EXTEND_NOT_LOCKED)) ;; tx-sender must not be delegating (asserts! (is-none (get-check-delegation tx-sender)) (err ERR_STACKING_ALREADY_DELEGATED)) ;; standard can-stack-stx checks (try! (can-stack-stx pox-addr amount-ustx first-extend-cycle lock-period)) ;; register the PoX address with the amount stacked ;; for the new cycles (let ((extended-reward-set-indexes (try! (add-pox-addr-to-reward-cycles pox-addr first-extend-cycle extend-count amount-ustx tx-sender signer-key))) (reward-set-indexes ;; use the active stacker state and extend the existing reward-set-indexes (let ((cur-cycle-index (- first-reward-cycle (get first-reward-cycle stacker-state))) (old-indexes (get reward-set-indexes stacker-state)) ;; build index list by taking the old-indexes starting from cur cycle ;; and adding the new indexes to it. this way, the index is valid starting from the current cycle (new-list (concat (default-to (list) (slice? old-indexes cur-cycle-index (len old-indexes))) extended-reward-set-indexes))) (unwrap-panic (as-max-len? new-list u12))))) ;; update stacker record (map-set stacking-state { stacker: tx-sender } { pox-addr: pox-addr, reward-set-indexes: reward-set-indexes, first-reward-cycle: first-reward-cycle, lock-period: lock-period, delegated-to: none }) ;; return lock-up information (ok { stacker: tx-sender, unlock-burn-height: new-unlock-ht }))))) Copy ;; Increase the number of STX locked. ;; *New in Stacks 2.1* ;; This method locks up an additional amount of STX from `tx-sender`'s, indicated ;; by `increase-by`. The `tx-sender` must already be Stacking & must not be ;; straddling more than one signer-key for the cycles effected. ;; Refer to `verify-signer-key-sig` for more information on the authorization parameters ;; included here. (define-public (stack-increase (increase-by uint) (signer-sig (optional (buff 65))) (signer-key (buff 33)) (max-amount uint) (auth-id uint)) (let ((stacker-info (stx-account tx-sender)) (amount-stacked (get locked stacker-info)) (amount-unlocked (get unlocked stacker-info)) (unlock-height (get unlock-height stacker-info)) (cur-cycle (current-pox-reward-cycle)) (first-increased-cycle (+ cur-cycle u1)) (stacker-state (unwrap! (map-get? stacking-state { stacker: tx-sender }) (err ERR_STACK_INCREASE_NOT_LOCKED))) (cur-pox-addr (get pox-addr stacker-state)) (cur-period (get lock-period stacker-state))) ;; tx-sender must be currently locked (asserts! (> amount-stacked u0) (err ERR_STACK_INCREASE_NOT_LOCKED)) ;; must be called with positive `increase-by` (asserts! (>= increase-by u1) (err ERR_STACKING_INVALID_AMOUNT)) ;; stacker must have enough stx to lock (asserts! (>= amount-unlocked increase-by) (err ERR_STACKING_INSUFFICIENT_FUNDS)) ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) ;; stacker must be directly stacking (asserts! (> (len (get reward-set-indexes stacker-state)) u0) (err ERR_STACKING_IS_DELEGATED)) ;; stacker must not be delegating (asserts! (is-none (get delegated-to stacker-state)) (err ERR_STACKING_IS_DELEGATED)) ;; Validate that amount is less than or equal to `max-amount` (asserts! (>= max-amount (+ increase-by amount-stacked)) (err ERR_SIGNER_AUTH_AMOUNT_TOO_HIGH)) ;; Verify signature from delegate that allows this sender for this cycle (try! (consume-signer-key-authorization cur-pox-addr cur-cycle "stack-increase" cur-period signer-sig signer-key increase-by max-amount auth-id)) ;; update reward cycle amounts (asserts! (is-some (fold increase-reward-cycle-entry (get reward-set-indexes stacker-state) (some { first-cycle: first-increased-cycle, reward-cycle: (get first-reward-cycle stacker-state), stacker: tx-sender, add-amount: increase-by, signer-key: signer-key }))) (err ERR_INVALID_INCREASE)) ;; NOTE: stacking-state map is unchanged: it does not track amount-stacked in PoX-4 (ok { stacker: tx-sender, total-locked: (+ amount-stacked increase-by)}))) sun-brightdesktopmoon --- # Send Many | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close circle-info Deployed contract page found [herearrow-up-right](https://explorer.hiro.so/txid/0x59665b756dc0fa9efb3fca9e05a28f572c9b14ca894c115fd3e7d81a563e14f8) . [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#contract-summary) Contract Summary --------------------------------------------------------------------------------------------------------------------- The Send Many contract enables efficient batch STX transfers to multiple recipients in a single transaction. This is a simple yet powerful utility contract that demonstrates functional programming patterns in Clarity. **What this contract does:** * Accepts a list of up to 200 recipients with their respective STX amounts * Transfers STX from the transaction sender to each recipient in the list * Uses functional programming (map and fold) to process transfers efficiently * Implements error handling to ensure all transfers succeed or the entire batch fails * Reduces transaction costs by batching multiple transfers into one transaction **What developers can learn:** * How to use Clarity's `map` function to apply operations across a list * How to use `fold` for accumulating results and propagating errors * Pattern for implementing "all-or-nothing" batch operations * Working with tuple types and list structures in Clarity * Efficient error handling in functional programming style * * * [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#function-by-function-breakdown) Function-by-Function Breakdown ------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#transfer-operations) Transfer Operations #### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#send-stx) `**send-stx**` A private helper function that performs a single STX transfer. It extracts the recipient address and amount from the tuple and calls `stx-transfer?` to send STX from the transaction sender to the specified recipient. #### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#send-many) `**send-many**` The main public function that accepts a list of recipients and their amounts. It uses `map` to apply `send-stx` to each recipient, then uses `fold` with `check-err` to ensure all transfers succeed or the entire transaction fails. ### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#error-handling) Error Handling #### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#check-err) `**check-err**` A fold reducer function that propagates errors through the list of transfer results. If any previous transfer failed (`prior` is an error), it returns that error immediately, ensuring the entire batch operation fails if any single transfer fails. * * * [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#key-concepts) Key Concepts ------------------------------------------------------------------------------------------------------------- ### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#batch-processing-pattern) Batch Processing Pattern The contract demonstrates an elegant pattern for batch operations in Clarity. By combining `map` and `fold`, it can process multiple transfers efficiently while maintaining atomic behavior (all succeed or all fail). ### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#functional-programming-in-clarity) Functional Programming in Clarity This contract showcases Clarity's functional programming capabilities: * **map**: Transforms each recipient tuple into a transfer operation * **fold**: Reduces the list of results into a single success/failure response * **Higher-order functions**: Functions that accept other functions as parameters ### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#error-propagation-with-fold) Error Propagation with Fold The `check-err` function implements a critical pattern for error handling in batch operations. It uses `match` to inspect the previous result (`prior`), and if it's an error, propagates it forward regardless of the current result. This ensures the first error encountered stops the entire operation. ### [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#list-size-limits) List Size Limits The contract accepts up to 200 recipients in a single batch. This limit balances efficiency with Clarity's computational constraints, preventing transactions from exceeding block limits while still enabling significant batch processing. [PreviousSemi Fungible Tokenchevron-left](https://docs.stacks.co/cookbook/clarity/example-contracts/semi-fungible-token) [NextExecutorDAO Frameworkchevron-right](https://docs.stacks.co/cookbook/clarity/example-contracts/executordao-framework) Last updated 2 months ago Was this helpful? * [Contract Summary](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#contract-summary) * [Function-by-Function Breakdown](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#function-by-function-breakdown) * [Transfer Operations](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#transfer-operations) * [Error Handling](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#error-handling) * [Key Concepts](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#key-concepts) * [Batch Processing Pattern](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#batch-processing-pattern) * [Functional Programming in Clarity](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#functional-programming-in-clarity) * [Error Propagation with Fold](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#error-propagation-with-fold) * [List Size Limits](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many#list-size-limits) Was this helpful? sun-brightdesktopmoon .send-many Copy (define-private (send-stx (recipient { to: principal, ustx: uint })) (stx-transfer? (get ustx recipient) tx-sender (get to recipient))) (define-private (check-err (result (response bool uint)) (prior (response bool uint))) (match prior ok-value result err-value (err err-value))) (define-public (send-many (recipients (list 200 { to: principal, ustx: uint }))) (fold check-err (map send-stx recipients) (ok true))) sun-brightdesktopmoon --- # Mainnet y Testnets | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-b9085514942994a4f51310436d9280ca02b58aca%252Fimage.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=dffd7115&sv=2) Stacks tiene tanto una mainnet como una testnet para diferentes propósitos. Mainnet y testnet son dos redes públicas completamente diferentes y los tokens no pueden transferirse de una a la otra. ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets#especificaciones-tecnicas-para-mainnet-y-testnet) Especificaciones técnicas para Mainnet y Testnet Mainnet Testnet ID de cadena `1` `2147483648` Versión de transacción `0` `128` Bytes mágicos `X2` `T2` Explorador [https://explorer.hiro.so/arrow-up-right](https://explorer.hiro.so/) [https://explorer.hiro.so/?chain=testnetarrow-up-right](https://explorer.hiro.so/?chain=testnet) URL base de la API de Stacks [https://api.hiro.soarrow-up-right](https://api.hiro.so/) [https://api.testnet.hiro.soarrow-up-right](https://api.hiro.so/) Formato / Versión de dirección **SP**3B108...2DNJA0 / `22` **ST**3B108P...EQEZY5 / `26` Formato / Versión multisig **SM**3RWH...5X9DXM / `20` **SN**8NKFP...2NAQJA / `21` Bloque Génesis [Bloque #1arrow-up-right](https://explorer.hiro.so/block/0x6b2c809627f2fd19991d8eb6ae034cb4cce1e1fc714aa77351506b5af1f8248e?chain=mainnet) [Bloque #1arrow-up-right](https://explorer.hiro.so/block/0xc9938007fe5f8cc312d782349a6cfbaee7598e08acc4f4da31c876a4b16d4153?chain=testnet) contrato sBTC [SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-tokenarrow-up-right](https://explorer.hiro.so/token/SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token?chain=mainnet) [ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-tokenarrow-up-right](https://explorer.hiro.so/txid/ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-token?chain=testnet) ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets#mainnet) Mainnet La mainnet de Stacks está anclada directamente a la mainnet de Bitcoin y es la red donde los tokens tienen valor monetario real. Esta es la red de producción y debe tratarse como tal. ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets#testnet) Testnet La testnet de Stacks sirve como un sandbox público en vivo para desarrolladores, permitiéndoles crear, probar e iterar aplicaciones y contratos inteligentes en un entorno que imita la mainnet. Proporciona un espacio sin riesgo para experimentar con cambios o nuevas funciones antes de desplegarlos en la mainnet de Stacks, asegurando que todo funcione correctamente sin riesgo de pérdida financiera real. #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets#faucets-de-testnet) Faucets de Testnet Los faucets de testnet te proporcionan tokens simulados de Stacks (STX) para probar. Estos STX de testnet no tienen valor y no son los mismos que los STX de la mainnet. Hay un par de opciones diferentes para obtener STX de testnet. Plataforma Sandbox LearnWeb3 Puedes obtener STX de testnet desde la [Plataformaarrow-up-right](https://platform.hiro.so/faucet) , que es la forma recomendada. Para obtener tokens STX desde la Plataforma, navega a la pestaña "Faucet" en la parte superior. Entonces puedes elegir STX de testnet o sBTC, y luego pegar tu dirección STX de testnet deseada para recibirlos. ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FjjVK8GVvGbnDTQxzgJ5t%252Fimage.png%3Falt%3Dmedia%26token%3De82a313d-4381-45cc-9a36-ba02a598d9f4&width=768&dpr=3&quality=100&sign=3b5b2fe2&sv=2) Usar el faucet proporcionado por el [Explorer Sandboxarrow-up-right](https://explorer.hiro.so/sandbox/deploy?chain=testnet) es otra opción. Primero deberás conectar tu wallet al Explorer Sandbox y pulsar 'Request STX'. Asegúrate de que tu wallet esté en la red testnet antes de solicitar. ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FQCTtyAN2r4btyxWOyJs3%252Fsandbox-faucet.png%3Falt%3Dmedia%26token%3Dac55a1c3-fbe8-4424-a513-3074c7befc5d&width=768&dpr=3&quality=100&sign=aa73e499&sv=2) Alternativamente, puedes usar el [faucet de LearnWeb3arrow-up-right](https://learnweb3.io/faucets) . ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-6b3929bea804b05efe83f4bb140709378b6024fb%252Fimage.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=d0179477&sv=2) [AnteriorFundamentos de la redchevron-left](https://docs.stacks.co/learn/es/network-fundamentals) [SiguienteTokenschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/network-basics) Última actualización hace 1 mes ¿Te fue útil? * [Especificaciones técnicas para Mainnet y Testnet](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets#especificaciones-tecnicas-para-mainnet-y-testnet) * [Mainnet](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets#mainnet) * [Testnet](https://docs.stacks.co/learn/es/network-fundamentals/mainnet-and-testnets#testnet) ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Reorganizaciones de Bitcoin | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FB87qRrXxQefRdn8uAP6U%252Fbitcoin-reorgs.png%3Falt%3Dmedia%26token%3D1f5374eb-d020-40c0-8f95-c77ab829328f&width=768&dpr=3&quality=100&sign=909d36d3&sv=2) Las transacciones en Stacks no se reorganizan de forma impactante debido a un fork de Bitcoin. No solo las reorganizaciones son relativamente poco frecuentes, sino que las transacciones en Stacks que se reorganizaron por un fork de Bitcoin se comportan tal como lo hacen las transacciones reorganizadas de Bitcoin. Con algún análisis futuro, las transacciones puramente en la cadena L2 podrían algún día quedar completamente no afectadas. Comprender este concepto se reduce fundamentalmente a entender la finalización en Stacks posterior a Nakamoto. circle-info Stacks no se bifurca por sí solo. Está diseñado para no bifurcarse salvo excepciones especiales, y es completamente inviable que Stacks se bifurque por sí solo si incluso el 31% de los Stackers no quiere que se bifurque, y aun así probablemente solo ocurriría dentro del lapso de una sola tenencia. El único caso en el que Stacks se bifurca es si los forks de Bitcoin lo hacen bifurcarse. En lugar de ganar el derecho a hacer un solo bloque, los mineros ganan el derecho a hacer una gran cantidad de bloques, y durante ese tiempo decimos que están bajo una “tenencia”. Cada bloque de Stacks producido en una tenencia requiere que al menos el 70% de los Stackers lo aprueben (firmen) para que se incluya en la blockchain de Stacks. Los Stackers están observando la blockchain de Bitcoin y solo firmarán bloques del minero que ganó la última sortición. Ahora, imaginemos que Bitcoin se reorganiza y los Stackers estaban observando un fork de Bitcoin que ahora es subóptimo. Los Stackers esencialmente retrocederían en el tiempo hasta la última sortición común entre el fork que estaban observando y el nuevo fork de Bitcoin mejor, y comenzarían a firmar los bloques dentro de las tenencias a partir de allí. Nótese que el 70% de los Stackers hará lo mismo al mismo tiempo, y en el momento en que el 70% esté de acuerdo en comenzar a firmar desde la última tenencia en el nuevo fork de Bitcoin, hay una nueva blockchain de Stacks singularmente óptima. Entonces, ¿qué pasa con las transacciones que se confirmaron en la tenencia que se reorganizó? Nada. Siguen en el mempool como si la tenencia reorganizada no hubiera ocurrido. Para cualquier cosa dentro de la blockchain de Stacks, todo está bien. Esto es 1:1 con un fork de Bitcoin reorganizando una transacción de Bitcoin. No deberías considerar una transacción en Bitcoin como final si está cerca de la punta de la cadena, y no deberías considerar una transacción en Stacks como final si está cerca de la punta de la tenencia. chevron-rightRepetición de transacciones[hashtag](https://docs.stacks.co/learn/es/block-production/bitcoin-reorgs#repeticion-de-transacciones) Dado que el 70% de los firmantes tienen que firmar cualquier bloque de Stacks incluido en la cadena, al menos el 70% de los firmantes conocen el estado de la cadena antes y después de que un fork de Bitcoin cause una reorganización de Stacks. Hay una pega que dificulta su aplicación: si una transacción dependía de algo en la blockchain de Bitcoin que también se reorganizó (un peg-in, por ejemplo), esa transacción ahora sería inválida. El análisis de contaminación (taint analysis) es cuando intentas responder a las preguntas “qué transacción interactuó con la ahora huérfana blockchain de Bitcoin de una manera que las hace inválidas (contaminadas) en la nueva cadena” y luego también “qué transacciones interactuaron con la transacción ahora inválida (contaminada) de modo que ahora también son inválidas”. Hay un efecto en cascada, pero hacer cumplir cualquier tipo de repetición requiere que los Stackers y los Mineros puedan identificar qué transacciones pueden ser repetidas en absoluto. El análisis de contaminación y, posteriormente, la aplicación de la repetición, pueden añadirse en el futuro. Para la primera versión, Nakamoto vincula explícitamente la blockchain de Stacks a la blockchain de Bitcoin de tal manera que solo hay un fork óptimo de Stacks vinculado a Bitcoin en cualquier momento dado. Esto es completamente 1:1 con el comportamiento de la blockchain de Bitcoin, pero a escala de tenencia. [AnteriorFinalidad en Bitcoinchevron-left](https://docs.stacks.co/learn/es/block-production/bitcoin-finality) [SiguienteIncentivo financiero y presupuesto de seguridadchevron-right](https://docs.stacks.co/learn/es/block-production/financial-incentive-and-security-budget) Última actualización hace 2 meses ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Run a Signer | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F4065274862-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F4cpTb2lbw0LAOuMHrvhA%252Fuploads%252Fn6Drb2IOHQHE6IPyghA7%252Frun-a-signer-cover.png%3Falt%3Dmedia%26token%3D8791bf7e-2040-4e81-8cff-9337cdcd4a1b&width=768&dpr=3&quality=100&sign=700a4551&sv=2) ### [hashtag](https://docs.stacks.co/operate/run-a-signer#how-to-use-this-guide) How to Use This Guide This guide is a step-by-step walkthrough for setting up and running a signer. It covers only the signer infrastructure: the signer software and the Stacks node it connects to. If you are not familiar with the concept of signing, be sure to check out the [Stackers and Signing concept guidearrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/learn/block-production/signing.md) . ### [hashtag](https://docs.stacks.co/operate/run-a-signer#background-and-high-level-process) Background and High-Level Process To run a signer you'll run a signer and a Stacks node side-by-side. Specifically, run a follower node. The signer monitors events from the Stacks node and uses the generated account (see Preflight Setup) to sign incoming Stacks blocks sent from the Stacks node. This doc provides instructions to set up both using either Docker or the release binaries available in the [stacks core releasesarrow-up-right](https://github.com/stacks-network/stacks-core/releases/latest) repository, and how to configure them so the signer and Stacks node communicate correctly. ### [hashtag](https://docs.stacks.co/operate/run-a-signer#knowledge-prerequisites) Knowledge Prerequisites * Docker and basic knowledge of pulling and running images * Basic knowledge of [Stacks accountsarrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/learn/network-fundamentals/wallets-and-accounts.md) 1 **Signer Checklist: Pre-Launch Setup** Quick reference of major setup steps prior to launching a signer. * Ensure your system meets the [minimum system requirements](https://docs.stacks.co/operate/run-a-signer#minimum-system-requirements) . * Acquire Docker and basic knowledge of Stacks accounts (links above). 2 **Signer Checklist: Preflight Setup** * Generate a new private key using stacks-cli (see Preflight Setup). * Save the generated account information securely. 3 **Signer Checklist: Configuration Setup** * Create a `signer-config.toml` file with necessary configurations: * node\_host * endpoint * network * db\_path * auth\_password * stacks\_private\_key * Store `signer-config.toml` securely and note down the values used. 4 **Signer Checklist: Running the Signer** * Decide whether to run the signer using Docker (recommended) or as a binary. * If using Docker: * Set up the necessary ports and volumes. * Run the Docker container with the appropriate settings. * If running as a binary: * Build `stacks-core` from source or download the pre-built binary. * Run the signer using: `stacks-signer run --config `. 5 **Signer Checklist: Verify Signer Operation** * Check that the signer is listening on its configured endpoint. * Confirm that there are no errors and that the system is ready for connections. 6 **Signer Checklist: Setting Up the Stacks Node** * Create a `node-config.toml`, include: * connection\_options.sauth\_token * events\_observer.endpoint (matching signer config) * Decide whether to run the Stacks node using Docker or as a binary and follow the respective run steps. 7 **Signer Checklist: Verify Stacks Node Operation** * Check Stacks node logs for successful connection to the signer. * Confirm the node is syncing Bitcoin headers properly. ### [hashtag](https://docs.stacks.co/operate/run-a-signer#minimum-system-requirements) Minimum System Requirements These are the minimum required specs to run a node and signer. More resources are recommended for optimal performance. #### [hashtag](https://docs.stacks.co/operate/run-a-signer#signer-stacks-node-and-bitcoin-node) Signer, Stacks node and Bitcoin node * 4 vCPU * 8 GB memory if running only a Stacks node and signer * 16 GB memory if running Stacks + Bitcoin node + signer * 1.5+ TB storage (1 TB for Bitcoin node, 500 GB for Stacks node, and 50 GB for signer) * * * [hashtag](https://docs.stacks.co/operate/run-a-signer#preflight-setup) Preflight Setup ------------------------------------------------------------------------------------------- Before you get your signer set up, you'll need to [generate a new private keyarrow-up-right](https://docs.stacks.co/stacks-101/accounts#creation) . The `stacks-cli` provides a mechanism for quickly generating a new account keychain via a simple CLI interface. The linked guide shows how to create one of those accounts on testnet. Save the generated account information securely; you'll need it later. circle-info What should the networking setup look like? Signers are intended to work with a local node. The node<->signer connection is not run over SSL, which means you can be exposed to a man-in-the-middle attack if your signer and node are hosted on separate machines. Ensure your signer isn't allowing requests from the public internet. We recommend having the signer and node running locally on the same machine or using internal networking between them. * * * [hashtag](https://docs.stacks.co/operate/run-a-signer#create-a-configuration-file) Create a Configuration File ------------------------------------------------------------------------------------------------------------------- Create a file named `signer-config.toml`. Populate it with the example signer config file contents from the [Sample Configuration Filesarrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/reference/node-operations/signer-configuration.md) page. Each field is described on that page. * * * [hashtag](https://docs.stacks.co/operate/run-a-signer#running-the-signer) Running the Signer ------------------------------------------------------------------------------------------------- Two options: Docker (recommended) or binary. Binaries are available on the [Stacks Core releases pagearrow-up-right](https://github.com/stacks-network/stacks-core/releases/latest) . ### [hashtag](https://docs.stacks.co/operate/run-a-signer#running-the-signer-with-docker) Running the Signer with Docker You can run the signer as a Docker container using the `blockstack/stacks-signer:3.1.0.0.5.0` image. Requirements when running the container: * The port configured as the `endpoint` (example: 30000) must be exposed to your Stacks node (endpoint should not be public). * A volume with at least a few GB available that contains the folder specified by your `db_path` (example: `/var`). * Mount your `signer-config.toml` file as a volume. Example docker run command: circle-info If you get an error about the manifest not found or the image platform not matching the host platform, you probably are running on an architecture other than x64. Add `--platform=linux/amd64` to the command (for example, on M1 Mac). Or, using a custom Dockerfile: ### [hashtag](https://docs.stacks.co/operate/run-a-signer#running-the-signer-as-a-binary) Running the Signer as a Binary Download the pre-built binaries from the [Stacks Core releases page on Githubarrow-up-right](https://github.com/stacks-network/stacks-core/releases/latest) , unzip the archive for your architecture. It includes the `stacks-signer` binary. Run the signer: (Replace `../signer-config.toml` with the actual path to your config.) * * * [hashtag](https://docs.stacks.co/operate/run-a-signer#verify-the-signer-is-running) Verify the Signer is Running --------------------------------------------------------------------------------------------------------------------- List running containers: Check the container logs: You should see: Signer spawned successfully. Waiting for messages to process... You may also see a warning like: This means your signer is running and awaiting registration; proceed to set up the Stacks node and then begin stacking. circle-exclamation You may see messages saying the signer is not registered for the current or next reward cycle. This is normal until the prepare phase for your chosen reward cycle; assuming you meet the stacking minimum, the signer will be registered during that phase. * * * [hashtag](https://docs.stacks.co/operate/run-a-signer#set-up-your-bitcoin-node) Set Up Your Bitcoin Node ------------------------------------------------------------------------------------------------------------- Optional but recommended to improve signer health and performance. Guides: * Run a full Bitcoin node: https://docs.stacks.co/guides-and-tutorials/nodes-and-miners/run-a-bitcoin-node * Run a pruned Bitcoin node: https://docs.stacks.co/guides-and-tutorials/nodes-and-miners/run-a-pruned-bitcoin-node * * * [hashtag](https://docs.stacks.co/operate/run-a-signer#set-up-your-stacks-node) Set Up Your Stacks Node ----------------------------------------------------------------------------------------------------------- Start the Stacks node after the signer is running. The node will not run unless it can send events to the signer. ### [hashtag](https://docs.stacks.co/operate/run-a-signer#stacks-node-configuration) Stacks Node Configuration Create `node-config.toml`. See the [Sample Configuration Filesarrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/reference/node-operations/signer-configuration.md) page for the full contents. Important fields to change: * `working_dir`: directory where the node persists data * `auth_token`: authentication token used by signer (must match signer `auth_password`) * `events_observer.endpoint`: host and port where your signer listens (example: `127.0.0.1:30000` or `stacks-signer.local:30000`) ### [hashtag](https://docs.stacks.co/operate/run-a-signer#start-with-an-archive) Start with an archive Starting from an archive snapshot is much faster than syncing from genesis. Archives are at https://archive.hiro.so. Example to download and extract the latest mainnet snapshot: This creates a `mainnet` folder where downloaded. Set `working_dir` to the parent directory containing `mainnet`. See best practices for snapshots: ../best-practices-to-snapshot-the-chainstate.md ### [hashtag](https://docs.stacks.co/operate/run-a-signer#run-a-stacks-node-with-docker) Run a Stacks Node with Docker Use the `blockstack/stacks-core` image (example tag: `3.1.0.0.13`). When running the container: * Expose the port configured for `p2p_bind` to the internet. * Make the port configured for `rpc_bind` accessible by your signer. * `working_dir` needs 500 GB–1 TB storage. * Include your `node-config.toml`. Example docker run: Or with a custom Dockerfile: If you get connection refused errors, you may need to point `events_observer.endpoint` to the Docker signer container. If using default Docker bridge mode, `localhost` inside the container is not the host. Point the endpoint to the Docker host or the signer container hostname accordingly. ### [hashtag](https://docs.stacks.co/operate/run-a-signer#run-a-stacks-node-with-a-binary) Run a Stacks Node with a Binary Download the pre-built `stacks-node` binary from the [Stacks Core releasesarrow-up-right](https://github.com/stacks-network/stacks-core/releases/latest) . Start the node: ### [hashtag](https://docs.stacks.co/operate/run-a-signer#verify-stacks-node-is-running) Verify Stacks Node is Running Typical startup logs: Ensure you see the `Registering event observer at XXX` log with your signer endpoint. Once Bitcoin headers are synced, you can GET `/v2/info` on the node RPC endpoint (default port 20443). You may see many logs while syncing; refer to How to Read the Signer Logs if concerned. * * * [hashtag](https://docs.stacks.co/operate/run-a-signer#next-steps-stacking) Next Steps: Stacking ---------------------------------------------------------------------------------------------------- Once your signer and Stacks node are running and verified, the next step is to stack STX to register your signer for a reward cycle. See the [Stacking STX](https://docs.stacks.co/operate/stacking-stx) guide for complete instructions on solo stacking, delegated stacking, and managing your keys. You will need to [generate a signer signature](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) before making any stacking transaction. [PreviousVerify Minerchevron-left](https://docs.stacks.co/operate/run-a-miner/verify-miner) [NextSigner Quickstartchevron-right](https://docs.stacks.co/operate/run-a-signer/signer-quickstart) Last updated 12 days ago Was this helpful? * [How to Use This Guide](https://docs.stacks.co/operate/run-a-signer#how-to-use-this-guide) * [Background and High-Level Process](https://docs.stacks.co/operate/run-a-signer#background-and-high-level-process) * [Knowledge Prerequisites](https://docs.stacks.co/operate/run-a-signer#knowledge-prerequisites) * [Minimum System Requirements](https://docs.stacks.co/operate/run-a-signer#minimum-system-requirements) * [Preflight Setup](https://docs.stacks.co/operate/run-a-signer#preflight-setup) * [Create a Configuration File](https://docs.stacks.co/operate/run-a-signer#create-a-configuration-file) * [Running the Signer](https://docs.stacks.co/operate/run-a-signer#running-the-signer) * [Running the Signer with Docker](https://docs.stacks.co/operate/run-a-signer#running-the-signer-with-docker) * [Running the Signer as a Binary](https://docs.stacks.co/operate/run-a-signer#running-the-signer-as-a-binary) * [Verify the Signer is Running](https://docs.stacks.co/operate/run-a-signer#verify-the-signer-is-running) * [Set Up Your Bitcoin Node](https://docs.stacks.co/operate/run-a-signer#set-up-your-bitcoin-node) * [Set Up Your Stacks Node](https://docs.stacks.co/operate/run-a-signer#set-up-your-stacks-node) * [Stacks Node Configuration](https://docs.stacks.co/operate/run-a-signer#stacks-node-configuration) * [Start with an archive](https://docs.stacks.co/operate/run-a-signer#start-with-an-archive) * [Run a Stacks Node with Docker](https://docs.stacks.co/operate/run-a-signer#run-a-stacks-node-with-docker) * [Run a Stacks Node with a Binary](https://docs.stacks.co/operate/run-a-signer#run-a-stacks-node-with-a-binary) * [Verify Stacks Node is Running](https://docs.stacks.co/operate/run-a-signer#verify-stacks-node-is-running) * [Next Steps: Stacking](https://docs.stacks.co/operate/run-a-signer#next-steps-stacking) Was this helpful? sun-brightdesktopmoon Copy IMG="blockstack/stacks-signer" VER="3.1.0.0.5.0" STX_SIGNER_PATH="./" STX_SIGNER_DATA="$STX_SIGNER_PATH/data" STX_SIGNER_CONFIG="$STX_SIGNER_PATH/signer-config.toml" docker run -d \ -v $STX_SIGNER_CONFIG:/config.toml \ -v $STX_SIGNER_DATA:/var/stacks \ -p 30000:30000 \ -e RUST_BACKTRACE=full \ -e BLOCKSTACK_DEBUG=0 \ --name stacks-signer \ $IMG:$VER \ stacks-signer run \ --config /config.toml Copy FROM blockstack/stacks-signer:3.1.0.0.5.0 COPY signer-config.toml /config.toml EXPOSE 30000 CMD ["stacks-signer", "run", "--config", "/config.toml"] Copy stacks-signer run --config ../signer-config.toml Copy docker ps Copy docker logs Copy WARN [1712003997.160121] [stacks-signer/src/runloop.rs:247] [signer_runloop] Signer is not registered for reward cycle 556. Waiting for confirmed registration... Copy curl -# https://archive.hiro.so/mainnet/stacks-blockchain/mainnet-stacks-blockchain-latest.tar.gz -o stacks-snapshot.tar.gz tar -zxvf stacks-snapshot.tar.gz Copy IMG="blockstack/stacks-core" VER="3.1.0.0.13" STX_NODE_CONFIG="./node-config.toml" docker run -d \ -v $STX_NODE_CONFIG:/config.toml \ -v /var/stacks \ -p 20443:20443 \ -p 20444:20444 \ -e RUST_BACKTRACE=full \ --name stacks-node \ $IMG:$VER \ stacks-node start \ --config /config.toml Copy FROM blockstack/stacks-core:3.1.0.0.13 COPY node-config.toml /config.toml EXPOSE 20444 EXPOSE 20443 CMD ["stacks-node", "start", "--config", "/config.toml"] Copy ./stacks-node start --config node-config.toml Copy Mar 6 19:35:08.212848 INFO stacks-node 0.1.0 Mar 6 19:35:08.213084 INFO Loading config at path ./Stacks-config.toml Mar 6 19:35:08.216674 INFO Registering event observer at: localhost:30000 Mar 6 19:35:08.221603 INFO Migrating sortition DB to the latest schema version Mar 6 19:35:08.224082 INFO Migrating chainstate DB to the latest schema version Mar 6 19:35:08.227404 INFO Start syncing Bitcoin headers, feel free to grab a cup of coffee, this can take a while sun-brightdesktopmoon --- # Mine Mainnet Stacks Tokens | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#introduction) Introduction For more on the technical details of mining, please review the mining guide. The following is an abridged version of the [walkthrough herearrow-up-right](https://github.com/stacksfoundation/miner-docs) , written for a Linux system. If you're on Windows or MacOS, there will be some slight modifications needed (PR's welcome!). If you're interested in mining on the Stacks mainnet, you can find instructions on how to do that here: ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#running-a-bitcoin-mainnet-full-node) Running a Bitcoin Mainnet Full Node To participate as a miner on mainnet, you must have access to a mainnet bitcoin node with a wallet (and the wallet's private key). One way to accomplish this is to run bitcoin locally. * [Ensure your computer meets the minimum hardware requirements before continuing.arrow-up-right](https://bitcoin.org/en/bitcoin-core/features/requirements#system-requirements) First, download a [bitcoin binaryarrow-up-right](https://bitcoin.org/en/download) , or [build from sourcearrow-up-right](https://github.com/stacksfoundation/miner-docs/blob/main/bitcoin.md#source-install) (_there may be some extra requirements to building,_ [_defined here_arrow-up-right](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages) ). If you want to learn more about the technical details of mining, please review the mining guide: circle-info **Tip:** It is recommended to use a persistent location for the chainstate, in the steps below we're using `/bitcoin`. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#update-the-bitcoin-configuration-file) Update the Bitcoin Configuration File Next, update the bitcoin configuration: * **Optional, but recommended:** Use a persistent directory to store the Bitcoin chainstate, i.e. `datadir=/bitcoin`. * **Optional, but recommended:** Update the `rpcallowip` value to only allow `127.0.0.1`, or the stacks miner IPv4. * Modify the `rpcuser` and `rpcpassword` values from the defaults below. * Store the following configuration somewhere on your filesystem (ex: `$HOME/bitcoin.conf`). #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#start-bitcoin) Start Bitcoin Finally, start `bitcoind` as follows (adjust the `conf` path to where it was created in the previous step, i.e. `$HOME/bitcoin.conf`): circle-info **Note:** It will take a few hours for the node to synchronize with Bitcoin Mainnet. While it's syncing, you can track the progress with `bitcoin-cli` or the logfile (will be located where the chainstate is stored, i.e. `/bitcoin/debug.log`): ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#running-a-stacks-blockchain-miner) Running a Stacks Blockchain miner First, download the latest tagged [stacks blockchain binaryarrow-up-right](https://github.com/stacks-network/stacks-blockchain/releases/latest) , or [build from sourcearrow-up-right](https://github.com/stacksfoundation/miner-docs/blob/main/stacks-blockchain.md#build-and-install-stacks-blockchain-from-source) (_there may be some extra requirements to building,_ [_defined here_arrow-up-right](https://github.com/stacksfoundation/miner-docs/blob/main/prerequisites.md#install-required-packages) ). circle-info **Tip:** It is recommended to use a persistent location for the chainstate, in the steps below we're using `/stacks-blockchain`. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#generate-a-keychain) Generate a keychain First, a keychain needs to be generated. With this keychain, we'll purchase some BTC from a cryptocurrency exchange, and then use that BTC to start mining. To create a keychain, the simplest way is to use the [stacks-cliarrow-up-right](https://docs.hiro.so/references/stacks-cli) with the `make_keychain` command. After this runs, you should see some JSON printed to the screen that looks like this: triangle-exclamation **Do not lose this information** - we'll need to use the `privateKey`, `btcAddress` and `wif` fields in later steps. The above `wif` (`Kyk49jsPGen5C1ThhyJJH4CndLk8yLESuQJVGsbbTV3FFF9CRTJG`) will then need to be imported into the bitcoin mainnet network. Next, a bitcoin wallet is created: Now, import your wif (bitcoin private key) inside the newly created wallet. circle-info **Note:** Be sure to replace `` with the wif value in the `Generate a keychain` step. circle-info **Note:** The import may take a while, because a wallet rescan is triggered. After the import has completed successfully, you can check that the address is imported with `getaddressinfo`. Once imported, we need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbasearrow-up-right](https://www.coinbase.com/) , [Binancearrow-up-right](https://www.binance.com/) , or [Krakenarrow-up-right](https://www.kraken.com/) . #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#update-the-stacks-blockchain-configuration-file) Update the Stacks Blockchain Configuration File Now, we need to configure our node to use this Bitcoin keychain. Copy the [sample mainnet miner configarrow-up-right](https://raw.githubusercontent.com/stacks-network/stacks-blockchain/master/testnet/stacks-node/conf/mainnet-miner-conf.toml) to your local machine in a _memorable_ location like `$HOME/mainnet-miner-conf.toml`. Next, update the stacks configuration: * **Optional, but recommended:** Use a persistent directory to store the Stacks chainstate, i.e. `working_dir = "/stacks-blockchain"` * From the `make_keychain` step, modify the `seed` and `mining_key` values with `privatekey` * Store the following configuration somewhere on your filesystem (ex: `$HOME/mainnet-miner-conf.toml`) #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#start-the-stacks-blockchain) Start the Stacks Blockchain To run your miner, run this in the command line: Your node should start. It will take some time to sync, and then your miner will be running. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#enable-debug-logging) Enable Debug Logging In case you are running into issues or would like to see verbose logging, you can run your node with debug logging enabled. In the command line, run: ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#optional-running-a-stacks-blockchain-miner-with-docker) Optional: Running a Stacks Blockchain miner with Docker Alternatively, you can run a Stacks mainnet miner with Docker. circle-exclamation Ensure you have [Dockerarrow-up-right](https://docs.docker.com/get-docker/) installed. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#generate-a-keychain-and-get-some-tokens) Generate a Keychain and Get Some Tokens Generate a keychain: We need to get some BTC to that address. You should be able to transfer BTC to this address using a cryptocurrency exchange such as [Coinbasearrow-up-right](https://www.coinbase.com/) , [Binancearrow-up-right](https://www.binance.com/) , or [Krakenarrow-up-right](https://www.kraken.com/) . #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#update-stacks-blockchain-docker-configuration-file) Update Stacks Blockchain Docker Configuration File Use the steps outlined above to create the configuration file. #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#start-the-stacks-blockchain-miner-with-docker) Start the Stacks Blockchain miner with Docker circle-info **Info:** The ENV VARS `RUST_BACKTRACE` and `STACKS_LOG_DEBUG` are optional. If removed, debug logs will be disabled. You can review the node logs with this command: ### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#optional-running-in-kubernetes-with-helm) Optional: Running in Kubernetes with Helm In addition, you're also able to run a Stacks miner in a Kubernetes cluster using the [stacks-blockchain Helm chartarrow-up-right](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain) . Ensure you have the following prerequisites installed: * [Dockerarrow-up-right](https://docs.docker.com/get-docker/) * [minikubearrow-up-right](https://minikube.sigs.k8s.io/docs/start/) (Only needed if standing up a local Kubernetes cluster) * [kubectlarrow-up-right](https://kubernetes.io/docs/tasks/tools/install-kubectl/) * [helmarrow-up-right](https://helm.sh/docs/intro/install/) #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#generate-keychain-and-get-some-tokens) Generate keychain and get some tokens Use the steps outlined above #### [hashtag](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#install-the-chart-and-run-the-miner) Install the chart and run the miner To install the chart with the release name `my-release` and run the node as a miner: You can review the node logs with this command: For more information on the Helm chart and configuration options, please refer to the [chart's homepagearrow-up-right](https://github.com/stacks-network/stacks-blockchain/tree/master/deployment/helm/stacks-blockchain) . [PreviousMine Testnet Stacks Tokenschevron-left](https://docs.stacks.co/operate/run-a-miner/mine-testnet-stacks-tokens) [NextVerify Minerchevron-right](https://docs.stacks.co/operate/run-a-miner/verify-miner) Last updated 27 days ago Was this helpful? * [Introduction](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#introduction) * [Running a Bitcoin Mainnet Full Node](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#running-a-bitcoin-mainnet-full-node) * [Running a Stacks Blockchain miner](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#running-a-stacks-blockchain-miner) * [Optional: Running a Stacks Blockchain miner with Docker](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#optional-running-a-stacks-blockchain-miner-with-docker) * [Optional: Running in Kubernetes with Helm](https://docs.stacks.co/operate/run-a-miner/mine-mainnet-stacks-tokens#optional-running-in-kubernetes-with-helm) Was this helpful? sun-brightdesktopmoon Copy server=1 disablewallet=0 datadir=/bitcoin rpcuser=btcuser rpcpassword=btcpass rpcallowip=0.0.0.0/0 bind=0.0.0.0:8333 rpcbind=0.0.0.0:8332 dbcache=512 banscore=1 rpcthreads=256 rpcworkqueue=256 rpctimeout=100 txindex=1 Copy bitcoind -conf=$HOME/bitcoin.conf Copy $ bitcoin-cli \ -rpcconnect=127.0.0.1 \ -rpcport=8332 \ -rpcuser=btcuser \ -rpcpassword=btcpass \ getblockchaininfo | jq .blocks 836745 Copy npx @stacks/cli make_keychain 2>/dev/null | jq -r Copy { "mnemonic": "spare decade dog ghost luxury churn flat lizard inch nephew nut drop huge divert mother soccer father zebra resist later twin vocal slender detail", "keyInfo": { "privateKey": "ooxeemeitar4ahw0ca8anu4thae7aephahshae1pahtae5oocahthahho4ahn7eici", "address": "SPTXOG3AIHOHNAEH5AU6IEX9OOTOH8SEIWEI5IJ9", "btcAddress": "Ook6goo1Jee5ZuPualeiqu9RiN8wooshoo", "wif": "rohCie2ein2chaed9kaiyoo6zo1aeQu1yae4phooShov2oosh4ox", "index": 0 } } Copy bitcoin-cli \ -rpcconnect=127.0.0.1 \ -rpcport=8332 \ -rpcuser=btcuser \ -rpcpassword=btcpass \ createwallet \ wallet_name="miner" \ disable_private_keys=false \ blank=false \ passphrase="" \ avoid_reuse=false \ descriptors=false \ load_on_startup=true Copy bitcoin-cli \ -rpcport=8332 \ -rpcuser=btcuser \ -rpcpassword=btcpassword \ importprivkey Copy bitcoin-cli \ -rpcconnect=127.0.0.1 \ -rpcport=8332 \ -rpcuser=btcuser \ -rpcpassword=btcpass \ getaddressinfo Copy [node] working_dir = "/stacks-blockchain" rpc_bind = "0.0.0.0:20443" p2p_bind = "0.0.0.0:20444" seed = "" miner = true bootstrap_node = "02196f005965cebe6ddc3901b7b1cc1aa7a88f305bb8c5893456b8f9a605923893@seed.mainnet.hiro.so:20444,02539449ad94e6e6392d8c1deb2b4e61f80ae2a18964349bc14336d8b903c46a8c@cet.stacksnodes.org:20444,02ececc8ce79b8adf813f13a0255f8ae58d4357309ba0cedd523d9f1a306fcfb79@sgt.stacksnodes.org:20444,0303144ba518fe7a0fb56a8a7d488f950307a4330f146e1e1458fc63fb33defe96@est.stacksnodes.org:20444" mine_microblocks = false [burnchain] wallet_name = "miner" chain = "bitcoin" mode = "mainnet" peer_host = "127.0.0.1" username = "" password = "" rpc_port = 8332 peer_port = 8333 satoshis_per_byte = 100 burn_fee_cap = 450000 [miner] mining_key = "" activated_vrf_key_path = "/stacks-blockchain/saved_vrf_key.json" [connection_options] private_neighbors = false Copy stacks-node start --config $HOME/mainnet-miner-conf.toml Copy STACKS_LOG_DEBUG=1 stacks-node start --config $HOME/mainnet-miner-conf.toml Copy docker run -i node:20-alpine npx @stacks/cli make_keychain 2>/dev/null | jq -r Copy docker run -d \ --name stacks_miner \ --rm \ --network host \ -e RUST_BACKTRACE="full" \ -e STACKS_LOG_DEBUG="1" \ -v "$HOME/mainnet-miner-conf.toml:/src/stacks-node/mainnet-miner-conf.toml" \ -v "/stacks-blockchain:/stacks-blockchain" \ -p 20443:20443 \ -p 20444:20444 \ blockstack/stacks-core:latest \ /bin/stacks-node start --config /src/stacks-node/mainnet-miner-conf.toml Copy docker logs -f stacks_miner Copy 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" Copy kubectl logs -l app.kubernetes.io/name=stacks-blockchain sun-brightdesktopmoon --- # ¿Qué es Stacks? | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-273720c2164bb69aeb720d97d2c2bd48c974507d%252FFrame%2520316126258.jpg%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=1369bc0b&sv=2) Stacks es una capa de Bitcoin para contratos inteligentes; permite que los contratos inteligentes y las aplicaciones descentralizadas utilicen Bitcoin como un activo de manera minimizada en cuanto a confianza y liquiden transacciones en la cadena de bloques de Bitcoin. Stacks es un tipo diferente de capa de Bitcoin para contratos inteligentes que las sidechains, con una conexión más profunda y continua con Bitcoin. Stacks permite que las aplicaciones y los contratos inteligentes usen BTC como su activo o dinero y liquiden sus transacciones en la cadena principal de Bitcoin. **El objetivo de Stacks es hacer crecer la economía de Bitcoin, convirtiendo a BTC en un activo productivo en lugar de pasivo, y habilitando diversas aplicaciones descentralizadas.** La capa Stacks tiene su propio libro mayor global y entorno de ejecución para soportar contratos inteligentes y no sobrecargar la cadena de bloques de Bitcoin con transacciones adicionales. Sin embargo, la capa Stacks es única ya que posee la mayoría de las propiedades ideales que tendrían los contratos inteligentes nativos de Bitcoin, pero lo hace sin necesitar añadir funcionalidad o complejidad adicional a Bitcoin. También proporciona mecanismos para mayor rendimiento y funcionalidad adicional, como tiempos de bloque rápidos y el peg descentralizado. Como capa de Bitcoin, Stacks tiene las siguientes innovaciones que la hacen única: chevron-right**Asegurado por Bitcoin**[hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#asegurado-por-bitcoin) Asegurado por Bitcoin: habilita la finalización en Bitcoin para las transacciones de Stacks; las transacciones que ocurren en la capa Stacks están aseguradas por toda la potencia de hash de Bitcoin. Esto significa que para revertir estas transacciones, un atacante necesitaría reorganizar Bitcoin. Tales transacciones se liquidan en Bitcoin y tienen finalización en Bitcoin. Además, la capa Stacks se bifurca con Bitcoin, por lo que cualquier estado en Stacks sigue automáticamente las bifurcaciones de Bitcoin. chevron-right**Peg de Bitcoin minimizado en confianza**[hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#peg-de-bitcoin-minimizado-en-confianza) Peg de Bitcoin minimizado en confianza: sienta las bases para un novedoso activo descentralizado ligado a Bitcoin, sBTC, para que los contratos inteligentes puedan ejecutarse mucho más rápido y de forma más económica usando el activo ligado a Bitcoin con riesgo de contrapartida mínimo. Esto también permite que los contratos en la capa Stacks escriban en Bitcoin a través de las transacciones de peg-out sin necesidad de depender de un conjunto centralizado y cerrado de entidades. Swaps atómicos y activos: Stacks ya tiene swaps atómicos de BTC y permite que direcciones de Bitcoin posean y muevan activos definidos en la capa Stacks. Magic swaps y Catamaran swaps son ejemplos de swaps atómicos descentralizados entre BTC en Bitcoin L1 y activos en la capa Stacks que ya están en funcionamiento. Además, los usuarios pueden poseer activos de la capa Stacks como STX, stablecoins y NFTs en direcciones de Bitcoin y transferirlos usando transacciones de Bitcoin L1 si lo prefieren. chevron-right**Lenguaje Clarity**[hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#lenguaje-clarity) Lenguaje Clarity: soporta Clarity, un lenguaje seguro y decidible para contratos inteligentes demostrables. Con Clarity, los desarrolladores pueden saber con certeza matemática qué puede y qué no puede hacer un contrato, incluso antes de ejecutarlo. El contrato del peg descentralizado se beneficiará de las propiedades de seguridad del lenguaje Clarity. Cabe destacar que Clarity WASM es un cambio que se está haciendo en la VM de Clarity que proporciona tiempos de ejecución significativamente más rápidos, además de crear una posible vía para que desarrolladores de Rust y Solidity puedan escribir contratos inteligentes en Stacks, aunque este trabajo no forma parte del lanzamiento Nakamoto. chevron-right**Conocimiento del estado de Bitcoin**[hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#conocimiento-del-estado-de-bitcoin) Conocimiento del estado de Bitcoin: tiene conocimiento del estado completo de Bitcoin; puede leer de forma confiable las transacciones y cambios de estado de Bitcoin y ejecutar contratos inteligentes desencadenados por transacciones de Bitcoin. La funcionalidad de lectura de Bitcoin ayuda a mantener el estado del peg descentralizado consistente con los BTC bloqueados en Bitcoin L1, entre otras cosas. chevron-right**Transacciones escalables y rápidas**[hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#transacciones-escalables-y-rapidas) Transacciones escalables y rápidas: proporcionará alto rendimiento y escalabilidad a través de varios mecanismos, incluyendo bloques más rápidos en la capa Stacks. Además, capas de escalabilidad como subnets pueden hacer diferentes compensaciones entre rendimiento y descentralización que la capa principal de Stacks. Podemos hacernos una idea del objetivo y la ética detrás de Stacks al observar cómo Satoshi imaginó generalizar Bitcoin en 2010: > _"...ser una red completamente separada y una cadena de bloques separada, pero compartir potencia de CPU con Bitcoin...todas las redes del mundo compartirían la potencia combinada de CPU, aumentando la fuerza total."_ Este es un tema principal en las decisiones de diseño de Stacks. Un poco contradictorio en el mundo de Bitcoin, la red Stacks es una L2 de Bitcoin, pero sí tiene su propio token. Esta es una decisión de diseño intencional y crítica principalmente con el propósito de mantener la descentralización, en lugar de confiar en una federación. Si eso resulta confuso o eres escéptico, es comprensible: profundizaremos en estas ideas a medida que avancemos por la documentación. ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#componentes-tecnicos-centrales-de-stacks) Componentes técnicos centrales de Stacks 1 #### [hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#proof-of-transfer) Proof of Transfer Proof of Transfer (PoX) es el mecanismo de producción de bloques de la cadena Stacks. Esencialmente, intenta recrear los patrones de producción de bloques de PoW de forma programática. Los mineros de Stacks gastan BTC por la oportunidad de minar nuevos bloques de Stacks. Bajo el capó, este mecanismo de producción de bloques ancla los bloques de Stacks a los bloques de Bitcoin, haciendo que sea tan difícil revertir un bloque de Stacks como revertir un bloque de Bitcoin. Es una gran afirmación, y la desglosamos con más detalle en las secciones sobre la producción de bloques Nakamoto. [Aprende más sobre PoX](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer) 2 #### [hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#token-nativo-de-stacks-stx) Token nativo de Stacks: STX El token nativo de la capa Stacks (STX) es esencial para el consenso PoX: STX es necesario para (a) incentivar a los mineros de Stacks a mantener el libro mayor global de la capa Stacks fuera de Bitcoin L1, y (b) los incentivos para los firmantes por umbral que participan en el mecanismo del peg. Los enfoques existentes para los pegs de Bitcoin, que carecen de un token nativo, no pueden soportar un sistema sin permisos y abierto y recurren a usar custodios o confiar en miembros de una federación conocida. 3 #### [hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#clarity) Clarity Clarity es el lenguaje de contratos inteligentes que usa Stacks. Ha sido diseñado desde cero para facilitar a los desarrolladores la escritura de contratos inteligentes seguros y protegidos. Además, dado que se ha construido específicamente para Stacks y Bitcoin, existen funciones integradas para leer el estado de Bitcoin, lo que significa que puedes usar el estado de Bitcoin para realizar acciones en Clarity. Por ejemplo, podrías configurar una verificación para asegurarte de que una transacción de Bitcoin en particular haya ocurrido antes de ejecutar una función de acuñación en Clarity, que precisamente es lo que sucede con el tercer componente: sBTC. [Aprende más sobre Clarity](https://docs.stacks.co/learn/es/clarity) 4 #### [hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#sbtc) sBTC sBTC es el peg bidireccional de Bitcoin minimizado en confianza en la capa Stacks. sBTC es la clave para hacer a Bitcoin programable y llevar la funcionalidad completa de contratos inteligentes a Bitcoin vía Stacks. sBTC no es una federación, sino que opera como una solución de peg descentralizada y de red abierta para llevar la funcionalidad de contratos inteligentes a Bitcoin con el menor riesgo de contrapartida posible. [Aprende más sobre sBTC](https://docs.stacks.co/learn/es/sbtc) chevron-right**Stacks y el propósito de la tecnología blockchain**[hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#stacks-y-el-proposito-de-la-tecnologia-blockchain) Al evaluar nuevas tecnologías blockchain, es importante mantener intacta la intención y el propósito originales de las mismas. Si volvemos a Bitcoin, fue diseñado originalmente para ser: * Descentralizado * Inmutable * Seguro Probablemente hayas oído hablar del trilema de la blockchain: el problema de intentar equilibrar la descentralización, la escalabilidad y la seguridad de una red blockchain. Stacks adopta el enfoque de resolver este trilema separando las cadenas en capas. Así que en la base, tienes la capa fundamental: **Bitcoin**. Bitcoin es la red blockchain más descentralizada, más segura y más inmutable. Sin embargo, eso viene con algunos compromisos: * Bitcoin es muy lento en comparación con otras redes. Bitcoin solo tiene un nuevo bloque escrito aproximadamente cada 10 minutos, lo que hace que su rendimiento sea despreciable en comparación con redes diseñadas para la velocidad como Solana. * Bitcoin también es "aburrido". Ethereum llegó después de Bitcoin e intentó hacer para el software lo que Bitcoin hizo para el dinero. El objetivo de Ethereum es ser una especie de supercomputadora descentralizada, sirviendo como un entorno de cómputo global para contratos inteligentes (código que se escribe en una cadena de bloques). * Bitcoin no es escalable. Debido a que cada nuevo bloque debe propagarse a cada nodo de la red, Bitcoin solo puede funcionar tan rápido como el nodo más lento de la red. Ahora estamos viendo el surgimiento de redes blockchain modulares como Cosmos que están diseñadas para facilitar que las personas desplieguen sus propias redes blockchain. Mientras que la mayoría de los nuevos protocolos blockchain que aparecen hoy en día ven estas propiedades como aspectos negativos y buscan eliminarlas, la comunidad de Stacks ve las cosas de manera diferente. ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#la-forma-stacks) La forma Stacks Stacks adopta un enfoque por capas: la capa fundamental de asentamiento es Bitcoin, y la escalabilidad y la funcionalidad se agregan encima de eso usando capas. Hay muchos tipos diferentes de L2 y diferentes formas en que pueden construirse. Todos vienen con diferentes compensaciones y tienen su propia forma de lograr los objetivos de escalabilidad o funcionalidad. Al adoptar este enfoque por capas, podemos tener toda la misma funcionalidad que cadenas como Ethereum, pero construida sobre Bitcoin. Entonces, Stacks es una capa 2 de Bitcoin con algunas propiedades únicas, como tener su propio token, que actúa como un mecanismo de incentivos para mantener un libro mayor histórico de todas sus transacciones y operar con su propio presupuesto de seguridad (además del presupuesto de seguridad de Bitcoin — más sobre esto en la siguiente sección). Esto es una de las cosas que separa a Stacks de otras capas de Bitcoin como Lightning. * Lightning no agrega funcionalidad adicional a Bitcoin; simplemente ayuda a escalar la funcionalidad que Bitcoin ya tiene y le ayuda a operar más rápido. Lightning también es efímero: no tiene estado permanente, y por lo tanto no es adecuado para cosas como contratos inteligentes que necesitan llevar un registro de datos y mantener estado. * Contrasta esto con Stacks, que añade funcionalidad adicional a Bitcoin pero aun así finalmente se liquida en Bitcoin (cubrirémos esto en la siguiente sección también). El beneficio es que podemos mantener una separación de responsabilidades y mantener a Bitcoin simple y robusto, avanzando en la producción de bloques, mientras añadimos capas adicionales para funcionalidad y velocidad. Si esas otras capas fueran comprometidas, la capa fundamental permanecería sin verse afectada. Esto es importante al construir sistemas destinados a ser un dinero global descentralizado (Bitcoin) y una economía descentralizada construida sobre ese dinero (Stacks). Con ese contexto, profundicemos exactamente en cómo Stacks está conectado a Bitcoin. * * * ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#recursos-adicionales) Recursos adicionales * \[[Stacks YTarrow-up-right](https://www.youtube.com/watch?v=BmejRmkLxZU)\ \] Muneeb da una charla en el evento de lanzamiento de la mainnet Stacks 2.0 el 14 de enero de 2021. [AnteriorStacks 101chevron-left](https://docs.stacks.co/learn/es/stacks-101) [SiguienteLa conexión con Bitcoinchevron-right](https://docs.stacks.co/learn/es/stacks-101/bitcoin-connection) Última actualización hace 29 días ¿Te fue útil? * [Componentes técnicos centrales de Stacks](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#componentes-tecnicos-centrales-de-stacks) * [La forma Stacks](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#la-forma-stacks) * [Recursos adicionales](https://docs.stacks.co/learn/es/stacks-101/what-is-stacks#recursos-adicionales) ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Generate a Signer Signature | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close Stacking transactions require a **signer key signature** to prove that the controller of the signer key authorizes the stacking operation. This page covers what a signer signature is, what data it contains, and all the ways to generate one. Both [solo stacking](https://docs.stacks.co/operate/stacking-stx/solo-stacking) and delegated stacking ([Stack with a Pool](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool) / [Operate a Pool](https://docs.stacks.co/operate/stacking-stx/operate-a-pool) ) reference this page. Generate your signature here before making stacking transactions. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#overview) Overview ------------------------------------------------------------------------------------------------------- Signer signatures are created using your signer key. They demonstrate that the controller of that signer key is allowing a stacker (or pool operator) to use their signing key in a stacking transaction. Because signer keys must be unique across the network, this also prevents other stackers from using someone else's key. circle-info The current pox-4 contract address can be found at [https://api.mainnet.hiro.so/v2/poxarrow-up-right](https://api.mainnet.hiro.so/v2/pox) . You can view the contract in the [Stacks Explorerarrow-up-right](https://explorer.hiro.so/?chain=mainnet) . ### [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#fields-passed-in-stacking-transactions) Fields Passed in Stacking Transactions When making stacking transactions, you need to provide these signature-related fields: 1 **signer-key** The public key that corresponds to the `stacks_private_key` your signer is using. 2 **signer-signature** A signature that demonstrates you actually control your `signer-key`. 3 **max-amount** The maximum amount of uSTX (1 STX = 1,000,000 uSTX) that can be locked in the transaction that uses this signature. For example, if calling `stack-increase`, this dictates the maximum amount of uSTX that can be used to add more locked STX. 4 **auth-id** A random integer that prevents the same signature from being reused, similar to how nonces are used with transactions. Must be less than 14 characters. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#signature-message-contents) Signature Message Contents The signer signature's message hash is created using the following data: * `**method**`: the stacking function that is allowed to use this signature. Valid options: * `stack-stx`: for solo stacking * `stack-extend`: for extending a solo stacking lock * `stack-increase`: for increasing a solo stacking position * `agg-commit`: for `stack-aggregation-commit-indexed` (pool operators) * `agg-increase`: for `stack-aggregation-increase` (pool operators) * `**max-amount**`: the maximum uSTX allowed (described above) * `**auth-id**`: the random integer (described above) * `**period**`: a value between 1 and 12 indicating how many cycles the stacker is allowed to lock for. For `agg-commit`, this must equal 1. * `**reward-cycle**`: the reward cycle in which the stacking transaction can be confirmed. See the important note below about how this differs between solo and delegated stacking. * `**pox-address**`: the Bitcoin address allowed for receiving rewards * `**config**`: the signer configuration file path where the `stacks_private_key` is located (used by the CLI for signing) circle-exclamation **reward-cycle differences:** * For **solo stacking** operations (`stack-stx`, `stack-extend`, `stack-increase`): set this to the **current** reward cycle. * For `**stack-aggregation-commit-indexed**`: set this to the **target** reward cycle (typically current cycle + 1, or a future cycle you are committing to). This is because pool operators can commit for future cycles, not just the next one. circle-exclamation Every field in the signature must **exactly match** the corresponding fields in your stacking transaction. A mismatch will cause the transaction to fail. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#generating-signatures) Generating Signatures --------------------------------------------------------------------------------------------------------------------------------- You have several options for generating signer signatures. Choose the one that best fits your setup. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-the-stacks-signer-cli) Using the stacks-signer CLI If you have your signer configured and running, you can use the `stacks-signer` CLI to generate signatures. You can SSH into your running signer or use the CLI locally with a matching configuration file. circle-info Having a matching configuration file is important to ensure the signer public key in your stacking transactions is the same as in your hosted signer. * `--json` optionally outputs the result in JSON format You can generate a random 32-bit integer for `auth-id` with: The CLI outputs a JSON object: Use this JSON when making stacking transactions. This output can be pasted directly into Leather Earn. circle-info The address you use for stacking transactions may differ from your signer address. See [Key and Address Rotation](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation) for more details on the relationship between signer keys and pool operator keys. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-stacks.js) Using stacks.js The [@stacks/stackingarrow-up-right](https://www.npmjs.com/package/@stacks/stacking) NPM package provides a `signPoxSignature` function to generate signer signatures programmatically. More information and code samples can be found on [Hiro's Nakamoto docsarrow-up-right](https://docs.hiro.so/nakamoto/stacks-js) . ### [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-degen-labs-stacking.tools) Using Degen Lab's stacking.tools Degen Lab provides a [signature generation toolarrow-up-right](https://signature.stacking.tools/) that generates signatures using their signer. This is the quickest and simplest option. Visit the tool and enter the relevant parameters. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-leather-earn) Using Leather Earn circle-info At the time of writing, this has only been tested using the [Leatherarrow-up-right](https://leather.io/) wallet. Visit [earn.leather.ioarrow-up-right](https://earn.leather.io/) to generate a signer key signature. Make sure you're connected to the correct network. To generate a signer key signature, log into Leather with the same secret key used to generate your signer key (not your pool operator address). Then click the "Signer key signature" link at the bottom of the page. The fields are: * **Reward cycle**: * For solo stacking transactions: must equal the current reward cycle. The field defaults to the current cycle. * For `stack-aggregation-commit-indexed`: must equal the cycle used in that function's "reward cycle" argument. Typically current\_cycle + 1. * **Bitcoin address**: the PoX reward address * **Topic**: the stacking function that will use this signature * **Max amount**: max amount of STX that can be used. Defaults to "max possible amount". * **Auth ID**: defaults to a random integer * **Duration**: must match the number of cycles used in the stacking transaction. For `stack-aggregation-commit-indexed`, use "1". Click "generate signature" to popup a Leather signing window. After signing, Leather Earn will display your signer key and signature. You can click the "copy" icon next to "signer details to share with stackers" to copy a JSON string that can be pasted directly into the stacking transaction form. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-a-hardware-or-software-wallet) Using a Hardware or Software Wallet If your signer is configured with a `stacks_private_key`, you can use that key in a wallet to generate stacking signatures. If you used [@stacks/cliarrow-up-right](https://docs.hiro.so/get-started/command-line-interface) to generate the key, the CLI also outputs a mnemonic (seed phrase) that can be imported into a wallet. Because the Stacks CLI uses the standard derivation path, any Stacks wallet will default to the same private key when imported. #### [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#setting-up-a-wallet-for-signature-generation) Setting up a wallet for signature generation 1 **Generate the keypair and configure signer** 1. Use `@stacks/cli` to generate the keychain and private key. * When using a hardware wallet, it's typically better to generate the mnemonic on the device itself. However, the signer software needs the raw private key, which hardware wallets don't export by design. 2. Take the `privateKey` from the CLI output and add it to your signer's configuration. 3. Take the mnemonic (24 words) and either: * Set up a new hardware wallet with this mnemonic, or * Store it securely (e.g., in a password manager). Import it into Leather or XVerse when you need to generate signatures. 2 **Generate signatures when needed** 1. Set up your wallet with your signer key's private key: * Set up Leather with a Ledger hardware wallet, or * Import your mnemonic into Leather, XVerse, or another Stacks wallet 2. Open an app with stacking signature functionality (e.g., Leather Earn) 3. Connect your wallet (sign in) 4. Enter your PoX address and submit. The app will prompt you to sign 5. Confirm the signature (if using a Ledger, confirm on the device) 6. The app displays your signer key and signature 7. Use the signer key and signature in your stacking transaction * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#signature-requirements-by-function) Signature Requirements by Function ----------------------------------------------------------------------------------------------------------------------------------------------------------- Function Method Period Reward Cycle `stack-stx` `stack-stx` Lock period (1–12) Current cycle `stack-extend` `stack-extend` Extend count (1–12) Current cycle `stack-increase` `stack-increase` Current lock period Current cycle `stack-aggregation-commit-indexed` `agg-commit` 1 Target cycle (e.g., current + 1) `stack-aggregation-increase` `agg-increase` 1 Target cycle [PreviousOperate a Poolchevron-left](https://docs.stacks.co/operate/stacking-stx/operate-a-pool) [NextKey and Address Rotationchevron-right](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation) Last updated 12 days ago Was this helpful? * [Overview](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#overview) * [Fields Passed in Stacking Transactions](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#fields-passed-in-stacking-transactions) * [Signature Message Contents](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#signature-message-contents) * [Generating Signatures](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#generating-signatures) * [Using the stacks-signer CLI](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-the-stacks-signer-cli) * [Using stacks.js](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-stacks.js) * [Using Degen Lab's stacking.tools](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-degen-labs-stacking.tools) * [Using Leather Earn](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-leather-earn) * [Using a Hardware or Software Wallet](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#using-a-hardware-or-software-wallet) * [Signature Requirements by Function](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature#signature-requirements-by-function) Was this helpful? sun-brightdesktopmoon Copy stacks-signer generate-stacking-signature \ --method stack-stx \ --max-amount 1000000000000 \ --auth-id 71948271489 \ --period 1 \ --reward-cycle 100 \ --pox-address bc1... \ --config ./config.toml \ --json Copy python3 -c 'import secrets; print(secrets.randbits(32))' Copy { "authId": "71948271489", "maxAmount": "1000000000000", "method": "stack-stx", "period": 1, "poxAddress": "bc1...", "rewardCycle": 100, "signerKey": "03a3...", "signerSignature": "bbbbbbbbbbb" } sun-brightdesktopmoon --- # Historia de BNS | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history#origenes-en-namecoin-2014) Orígenes en Namecoin (2014) El Sistema de Nombres de Bitcoin (BNS) rastrea sus raíces hasta 2014, cuando comenzó como una capa de nombres e identidad construida sobre Namecoin a través del proyecto OneName. ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FueZuLv2az0BtDgwNck8x%252Fonename.png%3Falt%3Dmedia%26token%3D7f22c5a2-3768-4f24-bc42-6530194afa70&width=768&dpr=3&quality=100&sign=fafc9652&sv=2) La idea era simple pero poderosa: permitir a los usuarios registrar nombres únicos a nivel mundial, legibles por humanos y criptográficamente vinculados a claves privadas. Los primeros adoptantes reclamaron nombres en formatos como `u/ryan`, usándolos como identidades digitales portables. Sin embargo, las limitaciones de Namecoin—incluyendo spam, garantías de seguridad más débiles y confirmaciones más lentas—dificultaron la escalabilidad a largo plazo. #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history#migracion-a-bitcoin-2015) Migración a Bitcoin (2015) En 2015, el proyecto migró a la propia cadena de bloques de Bitcoin, anclando el `.id` espacio de nombres al quemar aproximadamente 40 BTC en un compromiso público. Este movimiento aumentó drásticamente el modelo de seguridad al aprovechar la durabilidad y descentralización de Bitcoin. Los registros de nombres se anotaban directamente en transacciones de Bitcoin, a menudo usando `OP_RETURN`, mientras que los datos de estado más ricos vivían fuera de la cadena. Este enfoque híbrido permitió que BNS heredara la seguridad de Bitcoin a la vez que seguía soportando metadatos de identidad flexibles. #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history#era-stacks-2021) Era Stacks (2021) El siguiente capítulo importante comenzó en 2021 con el lanzamiento de Stacks. Con Stacks introduciendo funcionalidad de contratos inteligentes anclada a Bitcoin, BNS se desplegó como un contrato inteligente en el génesis de Stacks 2.0. Todos los nombres BNS previos fueron migrados, preservando el historial de propiedad mientras se habilitaba una lógica en cadena más expresiva. Nombres como `.btc` rápidamente ganaron popularidad, y BNS evolucionó hacia una primitiva de identidad central dentro del ecosistema Stacks. Cada nombre se volvió globalmente único y fuertemente poseído por una clave privada, con archivos de zona que permitían hasta aproximadamente 40 KB de datos fuera de cadena para perfiles, mapeos de direcciones e identificadores descentralizados (ver cambios de BNSv2 abajo). BNS soportó tanto nombres totalmente en cadena como subdominios fuera de cadena anclados al estado de la blockchain, dando a los desarrolladores flexibilidad en cómo estructuraban los sistemas de identidad. #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history#bns-se-ha-convertido-en-una-piedra-angular-del-ecosistema-bitcoin) **BNS se ha convertido en una piedra angular del ecosistema Bitcoin.** Los nombres BNS han generado una actividad sustancial en el mercado, con un volumen de ventas que alcanzó 1.5 millones de STX (unos 2 millones de dólares estimados). El lanzamiento del mercado de BNS en [Gamma.ioarrow-up-right](http://gamma.io/) en octubre de 2022 proporcionó a la comunidad un espacio dedicado para comprar, vender e intercambiar nombres. Esto ha ayudado a consolidar el estatus de BNS como líder en el mercado de dominios descentralizados. En febrero de 2024, BNS celebró su 10.º aniversario, marcando una década de progreso en el nombrado e identidad descentralizados en la cadena de bloques de Bitcoin. #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history#limitaciones-de-bns-v1) Limitaciones de BNS V1 La implementación original de BNS en Stacks, a menudo llamada V1, funcionó de manera fiable pero tenía limitaciones estructurales. Una sola dirección podía mantener solo un nombre primario a la vez, lo que limitaba la composabilidad y hacía que comerciar o coleccionar nombres fuera más engorroso. Además, los nombres no se implementaron como NFTs SIP-09, lo que significaba que no interoperaban automáticamente con el ecosistema más amplio de herramientas NFT. Con el tiempo, a medida que Stacks maduró y los estándares NFT se solidificaron, la comunidad empezó a presionar por un rediseño más flexible e interoperable. #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history#evolucion-hacia-bns-v2) Evolución hacia BNS V2 Ese rediseño se materializó en septiembre de 2024 como BNSv2. La migración de BNSv1 a BNSv2 hizo que los nombres se distribuyeran por airdrop a la cuenta que los poseía en la instantánea de migración del 11 de septiembre de 2024. Los usuarios no necesitaron hacer nada... su nombre BNSv2 simplemente apareció en su cartera. El contrato BNSv1 todavía existe en cadena, pero los cambios en los nombres a través de V1 NO se reflejan en V2 y viceversa. La nueva implementación reestructuró fundamentalmente cómo se representan y gestionan los nombres. Más notablemente, ahora cada nombre de primer nivel es un NFT compatible con SIP-09. Este cambio permite que los nombres BNS se integren directamente en carteras, mercados y contratos inteligentes sin requerir lógica personalizada. También significa que los nombres se comportan como activos digitales estándar: pueden transferirse, listarse, dejarse en custodia o integrarse en protocolos DeFi con fricción mínima. BNSv2 también eliminó la limitación de un solo nombre, permitiendo que las direcciones posean múltiples nombres simultáneamente. Este cambio aparentemente simple mejora drásticamente la usabilidad y desbloquea patrones de aplicación más complejos, desde portafolios de identidad hasta estrategias de marca basadas en espacios de nombres. Los propios espacios de nombres se han vuelto más flexibles bajo V2. Los desarrolladores o comunidades pueden crear espacios de nombres no gestionados que operen sin permisos o espacios de nombres gestionados con autoridades designadas que pueden definir reglas de precios, requisitos de verificación u otras restricciones. Los espacios de nombres gestionados son controlados por un **principal del contrato** (no una cartera estándar), y que este administrador puede ser congelado permanentemente para una descentralización total. Esta flexibilidad abre la puerta a capas de identidad curadas, ecosistemas con marca y economías de nombres experimentales. chevron-right**¿Qué sucede con BNSv1?**[hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history#que-sucede-con-bnsv1) El contrato inteligente BNSv1 continuará existiendo. Pero cualquier cambio realizado en los nombres vía el contrato BNSv1 no se reflejará en BNSv2 y viceversa en adelante. El flujo de registro en BNSv2 continúa utilizando un mecanismo de preordenar-y-revelar para prevenir el front-running, donde se compromete un hash salado del nombre antes de revelar el nombre real. Los archivos de zona siguen siendo parte de la arquitectura, permitiendo que los nombres hagan referencia a datos externos como direcciones de billetera, perfiles o registros de identidad descentralizada. Pero los archivos de zona de V2 son fundamentalmente diferentes a los de V1. En V1, los archivos de zona eran datos fuera de cadena replicados a través de la red Atlas. En V2, los archivos de zona se almacenan en cadena en un contrato separado de resolución de archivos de zona. Debido a que los nombres ahora son NFTs, se integran de forma más natural con mercados e infraestructura en todo el ecosistema Stacks, mientras siguen heredando las garantías de seguridad de Bitcoin a través del modelo de anclaje de Stacks. Hoy, BNSv2 se presenta tanto como un sistema de identidad como un marco de activos digitales construido sobre Stacks. Preserva la visión original de nombres globalmente únicos y propiedad de usuarios asegurados por Bitcoin, al tiempo que moderniza la arquitectura para alinearse con estándares NFT, propiedad múltiple de activos y gestión programable de espacios de nombres. * * * #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history#recursos-adicionales) Recursos adicionales * Un recorrido histórico más profundo de BNS: [https://mythbtc.xyz/bns-history/arrow-up-right](https://mythbtc.xyz/bns-history/) [AnteriorSistema de Nombres de Bitcoinchevron-left](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system) [SiguienteCómo funciona BNSv2chevron-right](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/architecture) Última actualización hace 1 mes ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Non-Fungible token | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/non-fungible-token#contract-summary) Contract Summary ------------------------------------------------------------------------------------------------------------------------------ A complete implementation of a SIP-009 compliant non-fungible token (NFT) contract with minting capabilities and collection limits. This contract serves as a foundational template for creating NFT collections on the Stacks blockchain. **What this contract does:** * Implements the full SIP-009 NFT standard trait * Creates a limited NFT collection (1000 tokens maximum) * Enables the contract owner to mint NFTs to recipients * Tracks the last minted token ID for sequential minting * Provides NFT ownership queries and transfers * Stores metadata URI pointing to off-chain JSON * Prevents minting beyond the collection limit * Restricts minting to the contract deployer only * Ensures only token owners can transfer their NFTs **What developers can learn:** * How to implement the SIP-009 non-fungible token trait correctly * Defining NFTs with `define-non-fungible-token` using uint identifiers * Built-in Clarity functions for NFT operations (`nft-mint?`, `nft-transfer?`, `nft-get-owner?`) * Sequential ID generation pattern for minting * Collection size limits and sold-out prevention * Owner-only minting access control * Token ownership verification before transfers * Metadata URI management for off-chain content * Using data variables to track minting state * Returning standardized responses for trait compliance * Filter annotations for security (`#[filter(sender)]`) [PreviousDeFi Lendingchevron-left](https://docs.stacks.co/cookbook/clarity/example-contracts/defi-lending) [NextFungible Tokenchevron-right](https://docs.stacks.co/cookbook/clarity/example-contracts/fungible-token) Was this helpful? Was this helpful? sun-brightdesktopmoon non-fungible-token.clar Copy ;; This contract implements the SIP-009 community-standard Non-Fungible Token trait (impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) ;; Define the NFT's name (define-non-fungible-token Your-NFT-Name uint) ;; Keep track of the last minted token ID (define-data-var last-token-id uint u0) ;; Define constants (define-constant CONTRACT_OWNER tx-sender) (define-constant COLLECTION_LIMIT u1000) ;; Limit to series of 1000 (define-constant ERR_OWNER_ONLY (err u100)) (define-constant ERR_NOT_TOKEN_OWNER (err u101)) (define-constant ERR_SOLD_OUT (err u300)) (define-data-var base-uri (string-ascii 80) "https://your.api.com/path/to/collection/{id}") ;; SIP-009 function: Get the last minted token ID. (define-read-only (get-last-token-id) (ok (var-get last-token-id)) ) ;; SIP-009 function: Get link where token metadata is hosted (define-read-only (get-token-uri (token-id uint)) (ok (some (var-get base-uri))) ) ;; SIP-009 function: Get the owner of a given token (define-read-only (get-owner (token-id uint)) (ok (nft-get-owner? Your-NFT-Name token-id)) ) ;; SIP-009 function: Transfer NFT token to another owner. (define-public (transfer (token-id uint) (sender principal) (recipient principal) ) (begin ;; #[filter(sender)] (asserts! (is-eq tx-sender sender) ERR_NOT_TOKEN_OWNER) (nft-transfer? Your-NFT-Name token-id sender recipient) ) ) ;; Mint a new NFT. (define-public (mint (recipient principal)) ;; Create the new token ID by incrementing the last minted ID. (let ((token-id (+ (var-get last-token-id) u1))) ;; Ensure the collection stays within the limit. (asserts! (< (var-get last-token-id) COLLECTION_LIMIT) ERR_SOLD_OUT) ;; Only the contract owner can mint. (asserts! (is-eq tx-sender CONTRACT_OWNER) ERR_OWNER_ONLY) ;; Mint the NFT and send it to the given recipient. (try! (nft-mint? Your-NFT-Name token-id recipient)) ;; Update the last minted token ID. (var-set last-token-id token-id) ;; Return a success status and the newly minted NFT ID. (ok token-id) ) ) chevron-downShow all 63 lines sun-brightdesktopmoon --- # ExecutorDAO Framework | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close circle-info For the full framework implementation, check out the [ExecutorDAOarrow-up-right](https://github.com/MarvinJanssen/executor-dao) project repo. [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/executordao-framework#contract-summary) Contract Summary --------------------------------------------------------------------------------------------------------------------------------- ExecutorDAO is a modular, extensible DAO framework that uses a trait-based architecture to enable flexible governance structures. This contract serves as the core execution engine that manages proposals and extensions, providing a foundation for building customizable decentralized autonomous organizations. **What this contract does:** * Acts as the central authority for DAO governance and execution * Manages and validates extensions (modules that add functionality to the DAO) * Executes proposals that have been approved through governance mechanisms * Tracks executed proposals to prevent double-execution * Provides extension authorization checks for secure operations * Supports batch extension management (enable/disable up to 200 extensions) * Implements a bootstrap mechanism for initial DAO setup * Enables callback functionality for extensions to interact with the core * Uses trait-based design for proposal and extension modularity * Transfers executive control from deployer to the DAO itself during construction **What developers can learn:** * Building modular smart contract architectures with trait-based extensions * DAO governance patterns with proposal execution frameworks * Authorization patterns: self-or-extension checks for privileged operations * Using `as-contract` context switching for DAO-initiated actions * Preventing replay attacks by tracking executed proposals * Bootstrap patterns for transitioning control from deployer to contract * Callback mechanisms for cross-contract communication * Batch operations with list iteration using `map` functions * Extension/plugin architecture for composable smart contracts * Event logging with print statements for off-chain indexing * Using `contract-of` to verify trait implementations and prevent impersonation * * * [PreviousSend Manychevron-left](https://docs.stacks.co/cookbook/clarity/example-contracts/send-many) [NextNFT Marketplacechevron-right](https://docs.stacks.co/cookbook/clarity/example-contracts/nft-marketplace) Last updated 2 months ago Was this helpful? Was this helpful? sun-brightdesktopmoon executor-dao.clar Copy ;; ExecutorDAO is the one DAO to rule them all. ;; By Marvin Janssen (use-trait proposal-trait .proposal-trait.proposal-trait) (use-trait extension-trait .extension-trait.extension-trait) (define-constant err-unauthorised (err u1000)) (define-constant err-already-executed (err u1001)) (define-constant err-invalid-extension (err u1002)) (define-data-var executive principal tx-sender) (define-map executed-proposals principal uint) (define-map extensions principal bool) ;; --- Authorisation check (define-private (is-self-or-extension) (ok (asserts! (or (is-eq tx-sender (as-contract tx-sender)) (is-extension contract-caller)) err-unauthorised)) ) ;; --- Extensions (define-read-only (is-extension (extension principal)) (default-to false (map-get? extensions extension)) ) (define-public (set-extension (extension principal) (enabled bool)) (begin (try! (is-self-or-extension)) (print {event: "extension", extension: extension, enabled: enabled}) (ok (map-set extensions extension enabled)) ) ) (define-private (set-extensions-iter (item {extension: principal, enabled: bool})) (begin (print {event: "extension", extension: (get extension item), enabled: (get enabled item)}) (map-set extensions (get extension item) (get enabled item)) ) ) (define-public (set-extensions (extension-list (list 200 {extension: principal, enabled: bool}))) (begin (try! (is-self-or-extension)) (ok (map set-extensions-iter extension-list)) ) ) ;; --- Proposals (define-read-only (executed-at (proposal )) (map-get? executed-proposals (contract-of proposal)) ) (define-public (execute (proposal ) (sender principal)) (begin (try! (is-self-or-extension)) (asserts! (map-insert executed-proposals (contract-of proposal) block-height) err-already-executed) (print {event: "execute", proposal: proposal}) (as-contract (contract-call? proposal execute sender)) ) ) ;; --- Bootstrap (define-public (construct (proposal )) (let ((sender tx-sender)) (asserts! (is-eq sender (var-get executive)) err-unauthorised) (var-set executive (as-contract tx-sender)) (as-contract (execute proposal sender)) ) ) ;; --- Extension requests (define-public (request-extension-callback (extension ) (memo (buff 34))) (let ((sender tx-sender)) (asserts! (is-extension contract-caller) err-invalid-extension) (asserts! (is-eq contract-caller (contract-of extension)) err-invalid-extension) (as-contract (contract-call? extension callback sender memo)) ) ) chevron-downShow all 82 lines sun-brightdesktopmoon --- # Especificaciones técnicas | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#consenso) Consenso * Prueba de Transferencia (PoX) como se describe en [SIP-007arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) * La red hará la transición a Prueba de Quema (PoB) como se describe en [SIP-001arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) después de 10 años. [Aprende más sobre la Prueba-de-Quema en SIP-001arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md) . * Modelo de amenazas * El 51% de la potencia minera maliciosa de Bitcoin puede reorganizar la cadena de Stacks o realizar un ataque de doble gasto * La cadena puede detenerse si los Stackers no pueden alcanzar un consenso del 70% sobre la validez de los bloques * Diferentes actores y sus roles * Los mineros de Stacks empaquetan transacciones en bloques y las proponen a los stackers * Los poseedores de Stacks pueden alterar el cálculo de los límites de bloque (sujeto a un veto del minero) y pueden votar para deshabilitar las recompensas de la Prueba-de-Transferencia durante un ciclo de recompensas. * Los stackers validan y añaden bloques a la cadena y validan las transacciones de depósito y retiro de sBTC ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#mineria-de-prueba-de-transferencia) Minería de Prueba de Transferencia * Calendario de recompensas de coinbase: * 1000 STX/bloque durante los primeros 4 años * 500 STX/bloque durante los siguientes 4 años * 250 STX/bloque durante los 4 años posteriores * 125 STX/bloque en perpetuidad después de eso * Las recompensas de coinbase se acumulan por "sorticiones perdidas": Si un bloque de Bitcoin no tiene sortición (en la altura N), entonces cualquier bloque de Stacks minado en una sortición posterior que se base en cualquier punta de la cadena de Stacks que existiera en la sortición penúltima (en la altura N-1) puede reclamar su coinbase. Esto incentiva a los mineros a seguir minando incluso si las comisiones de Bitcoin son altas. * Bono inicial de minería: Este es un caso especial de lo anterior para incentivar a los primeros mineros. La coinbase de todos los bloques de la cadena de quema entre la primera altura de bloque de quema (a ser elegida por mineros independientes como parte del lanzamiento de Stacks 2.0) y el primer ganador de sortición se acumula y se distribuye a los mineros en una ventana fija (a determinar). Por ejemplo, supongamos que la altura del bloque de quema es 10,000 y la primera sortición está en el bloque 10,500 y la ventana de distribución es de 100 bloques, entonces la coinbase de los primeros 500 bloques (10,500 - 10,000) se distribuirá de manera uniforme a los mineros que ganen sortición durante los 100 bloques subsiguientes. * Ventana de maduración de la recompensa: 100 bloques, lo que significa que los líderes ganarán la recompensa de coinbase 100 bloques después del bloque que minaron con éxito. * Intervalo de bloque: La blockchain de Stacks produce bloques rápidos aproximadamente cada 10 segundos con un cambio de tenencia de minero que ocurre en cada bloque de Bitcoin * Compromiso en BTC: Los mineros deben comprometer al menos 11,000 satoshis (5,500 sats / [salida UTXOarrow-up-right](https://learnmeabitcoin.com/technical/utxo) ); 2 salidas / bloque) para evitar "dust." * Para más detalles, ver Producción de Bloques. ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#stacking) Stacking 1 **Fase de preparación** Se elige un "bloque ancla". El conjunto cualificado de direcciones ("conjunto de recompensas") se determina basándose en la instantánea de la cadena en el bloque ancla. La duración de la fase de preparación es de 100 bloques. Los compromisos de Stacking deben confirmarse antes de que comience esta fase. 2 **Fase de recompensa** Los compromisos de BTC de los mineros se distribuyen entre el conjunto de recompensas. La longitud del ciclo de recompensas es de 2000 bloques de BTC (~2 semanas). * Dos direcciones de recompensa / bloque, para un total de 4000 direcciones por cada ciclo de recompensas. Las direcciones se eligen usando una VRF (función aleatoria verificable), de modo que cada nodo puede llegar de forma determinista a las mismas direcciones de recompensa para un bloque dado. * Umbral de Stacking: 0.025% de la cantidad participante de STX cuando la participación está entre el 25% y el 100% y cuando la participación está por debajo del 25%, el nivel umbral es siempre 0.00625 del suministro líquido de STX. * Delegación: Una dirección STX puede designar otra dirección para participar en Stacking en su nombre. [Sección relevante en SIP-007arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md#stacker-delegation) . * Pooling: Los poseedores de STX que individualmente no alcanzan el umbral de Stacking pueden agrupar sus participaciones para participar en Stacking. Para hacer esto, los poseedores de STX deben establecer la dirección de recompensa (opcional) a la "dirección delegada." Para más detalles, ver [esta referenciaarrow-up-right](https://docs.stacks.co/references/stacking-contract#delegate-stx) . * Se admiten direcciones Legacy, SegWit, Native SegWit y Taproot ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#cuentas-y-direcciones) Cuentas y Direcciones * Las transacciones en la blockchain de Stacks se originan, son pagadas por y se ejecutan bajo la autoridad de cuentas * Una cuenta se especifica completamente por su dirección + nonce + activos * La dirección contiene 2 o 3 campos: 1 byte de versión, 20 bytes de hash de clave pública (RIPEMD160(SHA256(entrada))), nombre opcional (longitud variable, máximo 128 bytes) * Dos tipos de cuentas: las cuentas estándar son propiedad de una o más claves privadas; las cuentas de contrato se materializan cuando se instancia un smart contract (especificado por el campo de nombre opcional arriba) * El nonce cuenta cuántas veces una cuenta ha autorizado una transacción. Comienza en 0, la autorización válida debe incluir el _siguiente_ valor de nonce. * Los activos son un mapa de todos los tipos de activos -- STX, cualquier activo en cadena especificado por un contrato Clarity (por ejemplo NFTs) -- a las cantidades poseídas por esa cuenta. * No es necesario que las cuentas sean explícitamente "creadas" o registradas; todas las cuentas existen implícitamente y se instancian en el primer uso. ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#transacciones) Transacciones * Tipos de transacción: coinbase, transferencia de tokens, despliegue de contrato, llamada de contrato, cambio de tenencia. * Solo las cuentas estándar (no contratos) pueden pagar las tarifas de transacción. * La ejecución de transacciones está gobernada por: 1 **Cuenta originaria** La cuenta que crea, autoriza y envía la transacción. 2 **Cuenta pagadora** La cuenta que factura el líder por el costo de validar y ejecutar la transacción. 3 **Cuenta emisora** La cuenta que identifica quién está ejecutando actualmente la transacción: esto puede cambiar a medida que una transacción se ejecuta mediante el `como-contrato` función de Clarity. * Las transacciones pueden agruparse o transmitirse en bloques. El comportamiento puede controlarse mediante el modo ancla de una transacción. Con streaming (microbloques), es posible un tiempo de confirmación más rápido. * Dos tipos de autorizaciones: la autorización estándar es cuando la cuenta originaria es la misma que la cuenta pagadora. _Patrocinada_ la autorización es cuando la cuenta originaria y la cuenta pagadora son distintas. Por ejemplo, desarrolladores o proveedores de servicios podrían pagar para que los usuarios llamen a sus smart contracts. * Para la autorización patrocinada, primero un usuario firma con la cuenta originaria y luego un patrocinador firma con la cuenta pagadora. * El límite de mempool para transacciones pendientes concurrentes es de 25 por cuenta * Las transacciones pendientes en el mempool serán recolectadas como basura [256 bloques después de la recepciónarrow-up-right](https://github.com/stacks-network/stacks-blockchain/blob/master/src/core/mempool.rs#L62) . Con un tiempo objetivo de bloque de 10 minutos, esto equivaldría a ~42 horas * [Aprende más sobre la codificación de transacciones en SIP-005arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-encoding) * [La firma y verificación de transacciones se describen en SIP-005arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-signing-and-verifying) * Todas las transacciones que impactan el saldo de la cuenta son atómicas, una operación de transferencia no puede incrementar el saldo de una cuenta sin decrementar el de otra. Sin embargo, las transacciones que realizan múltiples acciones sobre cuentas (por ejemplo, transferir desde múltiples cuentas) pueden completarse parcialmente. * Las transacciones pueden incluir una cadena de memo (máx. 34 bytes) [AnteriorSIPschevron-left](https://docs.stacks.co/learn/es/network-fundamentals/sips) [SiguienteAuditoríaschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/audits) Última actualización hace 2 meses ¿Te fue útil? * [Consenso](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#consenso) * [Minería de Prueba de Transferencia](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#mineria-de-prueba-de-transferencia) * [Stacking](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#stacking) * [Cuentas y Direcciones](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#cuentas-y-direcciones) * [Transacciones](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications#transacciones) ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Auditorías | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-5e2e14ea3986509bfcb836fe9be357ca3b56106b%252Fimage.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=b64fc8da&sv=2) #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/audits#las-auditorias-son-solo-una-parte-de-la-historia) Las auditorías son solo una parte de la historia Para cualquier proyecto, las capas de seguridad son cruciales. Las auditorías representan una capa, mientras que los desarrolladores principales y colaboradores colaboran para proporcionar muchas más. Programas, diseños y socios de seguridad notables más allá de las auditorías incluyen: * Investigadores de seguridad integrados [a través de Asymmetric Researcharrow-up-right](https://stacks.org/asymmetric-joins-stacks-ecosystem) * Programas Attackathon en asociación con Immunefi * sBTC descentralizado [red de validadores/firmantesarrow-up-right](https://www.stacks.co/sbtc) (eliminando la necesidad de confiar en una sola entidad y mitigando el riesgo de contraparte) * El diseño subyacente de Stacks que ofrece finalización 100% en Bitcoin, asegurando sBTC a nivel de consenso de una red de $2.5 mil millones. * Soporte a nivel de aplicación a través de [Hypernativearrow-up-right](https://hackernoon.com/hypernative-bolsters-bitcoin-l2-security-as-stacks-ecosystem-gets-real-time-protection) * el programa de [seguridad whitehat de Bitcoin L2 Labsarrow-up-right](https://bitcoinl2-labs.github.io/2024/06/04/orange-hats.html) * La asociación de Stacks Foundation con Staking Defense League * El continuo [programa de recompensas por errores de Immunefiarrow-up-right](https://immunefi.com/bug-bounty/stacks/information/) * Residentes dedicados de Stacks Foundation centrados exclusivamente en fuzzing y pruebas de penetración (creado [Rendezvousarrow-up-right](https://stacks-network.github.io/rendezvous/) ) circle-exclamation _Todos los problemas “altos” o “críticos” enumerados en las auditorías han sido mitigados o, de otro modo, quedaron obsoletos, incluso si el informe indica lo contrario._ #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/audits#stacks-core) Stacks Core Auditorías en Stacks Core file-pdf 4MB [Quantstamp\_Network State Machine.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-150723b09151584d6e0acf37bae5cf3abbaac3f1%2FQuantstamp_Network%20State%20Machine.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-150723b09151584d6e0acf37bae5cf3abbaac3f1%2FQuantstamp_Network%20State%20Machine.pdf?alt=media) file-pdf 1MB [CoinFabrik - Stacks Signer Audit.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-4a733d4e4ff9eb8f4d9e6f09f6f4c644796ff82c%2FCoinFabrik%20-%20Stacks%20Signer%20Audit.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-4a733d4e4ff9eb8f4d9e6f09f6f4c644796ff82c%2FCoinFabrik%20-%20Stacks%20Signer%20Audit.pdf?alt=media) file-pdf 165KB [Coinfabrik - Stacks PoX.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-e9678769eadb5de09cc9a02c006f1fa9109657ad%2FCoinfabrik%20-%20Stacks%20PoX.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-e9678769eadb5de09cc9a02c006f1fa9109657ad%2FCoinfabrik%20-%20Stacks%20PoX.pdf?alt=media) file-pdf 1MB [CoinFabrik - Stacks LibSigner.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-6e1a11c2727047c85a12cc0df3730e665cd3f0e4%2FCoinFabrik%20-%20Stacks%20LibSigner.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-6e1a11c2727047c85a12cc0df3730e665cd3f0e4%2FCoinFabrik%20-%20Stacks%20LibSigner.pdf?alt=media) file-pdf 154KB [CoinFabrik\_StackerDB.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-b0e846fba315845bd8e276bdf347ad90a119f9a0%2FCoinFabrik_StackerDB.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-b0e846fba315845bd8e276bdf347ad90a119f9a0%2FCoinFabrik_StackerDB.pdf?alt=media) file-pdf 153KB [CoinFabrik\_Signer Binary.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-dc059e72dc60cebf121d5e76e2eb926e11d0342d%2FCoinFabrik_Signer%20Binary.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-dc059e72dc60cebf121d5e76e2eb926e11d0342d%2FCoinFabrik_Signer%20Binary.pdf?alt=media) #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/audits#otras-auditorias) Otras auditorías file-pdf 708KB [NCC\_Group\_Stacks\_Wallet\_Report\_2020-11-17\_v1.0.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-cd00d448fac4fb740a472d0ae8264b46395e2afb%2FNCC_Group_Stacks_Wallet_Report_2020-11-17_v1.0.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-cd00d448fac4fb740a472d0ae8264b46395e2afb%2FNCC_Group_Stacks_Wallet_Report_2020-11-17_v1.0.pdf?alt=media) file-pdf 754KB [NCC\_Group\_Stacks\_Blockchain\_Audit\_Report\_2020-11-23\_v1.0.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-bed4f3bd8be8417603de69557d56f833c76466b0%2FNCC_Group_Stacks_Blockchain_Audit_Report_2020-11-23_v1.0.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-bed4f3bd8be8417603de69557d56f833c76466b0%2FNCC_Group_Stacks_Blockchain_Audit_Report_2020-11-23_v1.0.pdf?alt=media) file-pdf 245KB [Blockstack\_Desktop\_Wallet\_Pentest\_Report\_11-12-2020.pdf](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-72b6b717bf79ab81a1223330095de6807ed63efe%2FBlockstack_Desktop_Wallet_Pentest_Report_11-12-2020.pdf?alt=media) PDF downloadDescargar[arrow-up-right-from-squareAbrir](https://3385590278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FH74xqoobupBWwBsVMJhK%2Fuploads%2Fgit-blob-72b6b717bf79ab81a1223330095de6807ed63efe%2FBlockstack_Desktop_Wallet_Pentest_Report_11-12-2020.pdf?alt=media) Informe de Trail of Bits, Stacks Blockchain (sin PDF, [Lista de issues de Github proporcionadaarrow-up-right](https://github.com/diwakergupta/stacks-blockchain-tob-audit/issues) ) [AnteriorEspecificaciones técnicaschevron-left](https://docs.stacks.co/learn/es/network-fundamentals/technical-specifications) [SiguienteProducción de bloqueschevron-right](https://docs.stacks.co/learn/es/block-production) Última actualización hace 2 meses ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Incentivo financiero y presupuesto de seguridad | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FVRhX6bApr6XhhWPVJaNx%252Fsecurity-budget-cover.png%3Falt%3Dmedia%26token%3Dbbe1476d-53e4-4cfa-a8bf-628005b5bd14&width=768&dpr=3&quality=100&sign=dd55fae8&sv=2) Para reorganizar la cadena Stacks, alguien debe tomar el control de al menos el 70% de los STX que actualmente están Stacked y llevar a cabo un ataque del 51% en Bitcoin mismo. Además de esto, debido a cómo Stacks logra la finalización en Bitcoin al no permitir forks, el presupuesto de seguridad de Stacks alcanza el 51% del poder de minado de Bitcoin porque, para revertir el estado de la cadena, también se necesitaría revertir el estado de la cadena de Bitcoin. Los Stackers tienen el recién descubierto poder de firmar bloques para agregarlos a la cadena Stacks. Sin embargo, algunos de ellos podrían negarse a firmar y asegurar que ningún bloque alcance jamás el umbral del 70% de firmas. Si bien esto puede ocurrir por accidente, este no es un comportamiento económicamente racional: si detienen la cadena por demasiado tiempo, sus STX perderán valor y, además, no pueden volver a stackear ni liquidar sus STX ni activar PoX para ganar BTC. Asimismo, los mineros dejarán de minar si no se confirman bloques, lo que elimina sus pagos continuos de PoX. Los detalles técnicos de cómo funciona todo esto se discuten en el [Producción de Bloques](https://docs.stacks.co/learn/es/block-production) sección. * * * ### [hashtag](https://docs.stacks.co/learn/es/block-production/financial-incentive-and-security-budget#recursos-adicionales) Recursos Adicionales * \[[Stacks YTarrow-up-right](https://www.youtube.com/watch?v=HUyFnGnA4FU)\ \] Presupuesto de Seguridad a Largo Plazo e Incentivos para Mineros de Bitcoin [AnteriorReorganizaciones de Bitcoinchevron-left](https://docs.stacks.co/learn/es/block-production/bitcoin-reorgs) [SiguienteTransaccioneschevron-right](https://docs.stacks.co/learn/es/transactions) Última actualización hace 1 mes ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # The Bitcoin Connection | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-dfb22d998899604417b072202f52fa3cdda377ef%252FFrame%2520316126254.jpg%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=7d7c7a5e&sv=2) In the previous section, we described Stacks as bringing smart contract functionality to Bitcoin, without modifying Bitcoin itself, and explained a bit about how the chain works. That's a big promise, but how does Stacks actually deliver on it? And what makes Stacks unique among other Bitcoin layers and other blockchains like Ethereum? Before we get into the technical details of how Stacks works, it's important to get a high-level overview of the problem it's solving and how it actually does that. We'll dive deeper into some of these topics as we go through the docs, but it's good to get a high-level picture to bring everything together. This topic is a bit of a rabbit hole, but it will give you an in-depth understanding of exactly the problem Stacks is looking to solve, and how it solves it. Let's get into it. ### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#whats-the-purpose-of-a-bitcoin-layer) What's the purpose of a Bitcoin layer? The decentralization of trust is the primary innovation and promise of blockchains. Even in the world of cryptocurrencies, recent failures in 2022 have been of centralized entities, further highlighting the importance of systems that don’t rely on “trusted” centralized intermediaries. Bitcoin is the most secure, durable, and valuable blockchain; it is already used as a store of value by millions of people. It is robust, "hard" money, with unprecedented non-custodial ownership and lack of inflation. The Bitcoin blockchain is also the best settlement layer for transactions, as it is the most decentralized, censorship-resistant, and durable blockchain. However, Bitcoin is relatively slow and minimal by design and conservative in its evolution to preserve these powerful properties. It produces blocks on average every 10 minutes, with only 5-7 transactions per second. It does not provide native support for fully-expressive smart contracts and hence for sophisticated applications that can utilize its properties. The result is that Bitcoin has remained a passive rather than a productive asset. Despite its attractive and unique properties, it has not been a platform for applications besides a store of value and infrequent money movement. Bitcoin layers change this. Bitcoin layers extend the functionality and performance of the Bitcoin blockchain without requiring any changes to it. ### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#how-would-we-define-what-a-bitcoin-layer-is) How would we define what a Bitcoin layer is? It is important to define what is meant by a Bitcoin layer. While there are several nuanced opinions on what makes a system a Layer 2 on top of a Layer 1, these are the properties we believe comprise an ideal Bitcoin L2 and the assumptions we make: 1. Open-source and decentralized development process 2. Full VM support and ability to program with expressive, high-level languages 3. Fast transaction and block times (don’t need to wait 10-30 minutes for Bitcoin blocks) 4. A trust-minimized way to move BTC between L1 and L2 5. BTC as the primary asset deployed in L2 apps 6. The ability to pay for L2 transactions in BTC 7. The ability to unilaterally withdraw your BTC back from the L2 with no counterparty risk Stacks V1 had properties 1 and 2, but was missing the rest. The Nakamoto upgrade brings properties 3, 4, and 5, with discussions and work currently underway to accomplish 6. Currently, Lightning is the only L2 that has property 7, and the only way to truly take advantage of this is to run your own Lightning node, a complex undertaking few users engage in. Furthermore, Lightning is missing property 2, which means we cannot unlock any additional functionality beyond what that Bitcoin L1 is already capable of. It’s important to acknowledge that Bitcoin L2s have fundamentally different goals than L2s on other L1s like Ethereum. While the primary motivation for L2s on Ethereum is to enhance scalability, Bitcoin L2s serve the purpose of enhancing both scalability and functionality. This means that the Bitcoin layer cannot verify the validity of transactions that occur on L2s like Stacks. Instead the VM for that layer is responsible for transaction processing and verification, and settling those transactions down to Bitcoin so that they share the same history and finality. ### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#is-stacks-a-bitcoin-l2) Is Stacks a Bitcoin L2? Stacks is a Bitcoin layer for smart contracts. The classification as a layer-1 (L1) or layer-2 (L2) or sidechain really depends on the definition used. With that said, generally speaking L1 chains are sovereign meaning that (a) they have their own security budget, and (b) they can survive without the need for any other L1 chain. L2 chains typically do not have their own security budget and share the security of the underlying L1 chain, and they cannot live without the underlying L1 chain. There are many different design mechanisms that L2s can use. The initial release of Stacks in early 2021 had a separate security budget from Bitcoin L1. Even though the Stacks layer could not function without Bitcoin L1, the developers working on the project described it as a different system that does not fit neatly into existing classifications, sometimes using the term layer 1.5 (see [this Decrypt articlearrow-up-right](https://decrypt.co/82019/bitcoin-defi-thing-says-stacks-founder-muneeb-ali) for example). The Nakamoto release in 2024 enabled Stacks to share the same security budget from Bitcoin. Instead, 100% of Bitcoin hashpower will determine finality on the Stacks layer. To reorg Stacks blocks/transactions the attacker will need to reorg Bitcoin L1 itself (which is very hard to do and therefore a great security property for a Bitcoin layer to have). The definition of L2 used in Ethereum and other newer ecosystems is different and focuses on the ability to withdraw assets using only L1 security and L1 miners. According to that definition Stacks layer is not a clear L2, given the set of peg-out signers determine if users can withdraw sBTC. Bitcoin cannot support such verification without changes to Bitcoin L1 (which may happen in the future). The Ethereum L2 definition also does not apply that cleanly to Bitcoin L2s, given new assets are issued on L2s when it comes to Bitcoin and not issued on L1 (only BTC is the L1 asset). Therefore, using the definition of security of withdrawing assets is not directly applicable given assets are defined and used on L2s and not withdrawn out to Bitcoin L1 anyway (with the exception of BTC itself). Rather, what becomes more important is "settlement on Bitcoin" i.e., is contract data and state secured by 100% of Bitcoin's hashpower or not. Remember that L2s on Bitcoin also have to serve the additional purpose of expanding both functionality and scalability, which means L2s accomplish fundamentally different goals depending on the functionality of the L1. Users and developers organically call Stacks a Bitcoin L2, since it is a simpler concept to understand. There are certain properties of Stacks layer that also help the concept of Stacks as a Bitcoin L2: 1 **Bitcoin finality** 100% of the Bitcoin hashpower decides block ordering and transaction finality. 2 **Consensus runs on Bitcoin** Stacks consensus runs on Bitcoin L1, and Stacks L2 cannot operate or survive without Bitcoin L1. 3 **sBTC and economic unit** With the decentralized Bitcoin peg, sBTC, most of the economy on Stacks layer will use BTC as the unit of economy. It is expected that most users will simply use Bitcoin in wallets and apps and then peg out their BTC to Bitcoin L1. 4 **Data hashed and stored on Bitcoin** All data and transactions on Stacks are automatically hashed and permanently stored on Bitcoin L1 on every Bitcoin block. Anyone can verify that some data on Stacks is valid by checking the corresponding hash on Bitcoin. This compact storage of hashes on the L1 is somewhat similar to rollups (although there are other differences). You can read more about this process in the [Block Production](https://docs.stacks.co/learn/block-production) section. 5 **Contracts can read Bitcoin state** Contracts on Stacks layer can read Bitcoin L1 transactions and respond to them. Assets on Stacks layer can be moved simply through Bitcoin L1 transactions. chevron-right**Addressing the skeptics and critics**[hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#addressing-the-skeptics-and-critics) Given all the details above, why would some people think that Stacks is not a Bitcoin L2? There are a couple of reasons this question comes up often: * **Old security-budget material**: The initial version of Stacks (released early 2021) had a separate security budget which changed to inherit 100% Bitcoin hashpower with the Nakamoto release. * **Ethereum L2 withdrawal definition doesn't map cleanly**: According to the Ethereum definition of L2s a user should be able to withdraw their base-layer assets purely by doing an L1 transaction and relying only on L1 security (this is true for Lightning for example). This definition does not apply cleanly to Bitcoin L2s because assets are not defined at Bitcoin L1 but are defined in L2s instead. The only asset where this matters is the pegged BTC asset from Bitcoin L1, given all other assets are native to L2s anyway. In the upcoming Stacks release, users can withdraw their BTC by sending just a Bitcoin L1 transaction but Bitcoin L1 cannot validate that complex transaction and a majority of peg-out signers will need to sign on the peg-out request. In an ideal world Bitcoin miners can validate such transactions but that would require a change to Bitcoin L1. Therefore, Stacks design optimizes for a method that is decentralized and can be deployed without any changes to Bitcoin L1. If in the future it is possible to make changes to Bitcoin L1 then Stacks layer security can benefit from that as well. * **Healthy Bitcoin skepticism**: Bitcoin community members are generally skeptical of claims and on the lookout for people making any false marketing claims. This is generally a healthy thing for the Bitcoin ecosystem and builds up the immune system. Some such community members might be skeptical about Stacks as a Bitcoin layer or L2 until they fully read the technical details and reasoning. There is a good Twitter thread about this topic as well. Why don't we use the term 'sidechain' for Stacks then? Sidechains in Bitcoin typically have a different security budget from the Bitcoin L1, typically as a subset of Bitcoin miners who participate in the sidechain (they don't follow 100% Bitcoin finality), their consensus runs on the sidechain (vs running on Bitcoin L1), and they don't publish their data/hashes on Bitcoin L1. The Stacks layer does not fit that definition cleanly given the consensus runs on Bitcoin L1, it follows Bitcoin finality, and publishes data/hashes on L1. ### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#the-symbiotic-relationship-between-stacks-and-bitcoin) The Symbiotic Relationship Between Stacks and Bitcoin Stacks and Bitcoin complement each other. Stacks leverages the extreme decentralization of Bitcoin, its PoW consensus mechanism, and its value as a cryptocurrency. But Stacks also complements Bitcoin by unlocking additional use cases, thereby increasing its value over time. This also helps to solve the additional problem of the future maintainability of Bitcoin after the coinbase rewards are gone and Bitcoin has to function on transaction fees alone. If Bitcoin is seen as only a store of value, the economic density, meaning how much value is being exchanged, of each transaction will be minimal. But if Bitcoin is the underlying foundation for an entire decentralized economy, those transactions become much more valuable, increasing transaction fees. This is a crucial incentive for miners to continue securing the network as coinbase rewards drop. ### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#on-crafting-a-bitcoin-first-developer-experience) On Crafting a Bitcoin-First Developer Experience One of the things that gives the Stacks network its superpowers in connecting with Bitcoin is not only how it connects to Bitcoin at a protocol level, discussed above, but also how we can utilize that Bitcoin at a programmatic level. The DevEx for a Bitcoin L2 should abstract away Bitcoin’s complexity but also maintain the _feeling_ of building on Bitcoin. Sounds like a contradiction but here's how Stacks pulls it off: 1 #### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#sustain-bitcoin-movements-with-sbtc) Sustain bitcoin movements with sBTC ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FcEu2zTJAr1gf2DhO0IlF%252Fimage.png%3Falt%3Dmedia%26token%3D0e7b4457-46e4-4804-8715-354c1b231bb8&width=768&dpr=3&quality=100&sign=92ec744a&sv=2) sBTC unlocks Bitcoin’s programmability. You get L2 expressivity without losing Bitcoin’s familiar properties: denomination, representation, and trust model. 2 #### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#plug-directly-into-btcfi) Plug directly into BTCFi ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252F5deRHklyK2MmDdY43npI%252Fimage.png%3Falt%3Dmedia%26token%3D834db26e-3f3d-4a17-9621-94adefa275ee&width=768&dpr=3&quality=100&sign=5f67ae7&sv=2) Zest, Bitflow, StackingDAO, Dual Stacking, and other major DeFi protocols on Stacks offer developer tooling for smart, composable, and Bitcoin-first applications. 3 #### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#one-cryptographic-identity) One cryptographic identity ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FpIxVepsp9Biq2R2nYMcG%252Fimage.png%3Falt%3Dmedia%26token%3D74728d02-14c1-4890-990a-821b1694d5e4&width=768&dpr=3&quality=100&sign=c57c1b0c&sv=2) Stacks uses the _same_ cryptographic primitive — same curve (secp256k1), same `hash160` construction — to derive Stacks addresses. They’re formatted differently (different version bytes / encoding), but underneath: the identity anchor is the same 20-byte public key hash. Different layers. Same cryptographic private key. 4 #### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#react-to-bitcoin-state) React to Bitcoin state ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FKYorxt9fH5tT3QtwZqQH%252Fimage.png%3Falt%3Dmedia%26token%3D6320a719-2c1a-4809-95e2-da076535b848&width=768&dpr=3&quality=100&sign=9547e63f&sv=2) One of the often-touted features of Clarity is that it has access to the state of the Bitcoin chain built in, but how does it actually do that? Because of Stacks' PoX mechanism, every Stacks block is connected to a Bitcoin block, and can query Bitcoin block header hashes with the `get-burn-block-info?` function. Clarity can read Bitcoin state directly. Parse BTC transactions. Trigger logic based on Bitcoin activity. 5 #### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#capture-time-on-the-l2-at-bitcoin-speed) Capture time on the L2 at Bitcoin speed ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F2842511454-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FmhZDcp95zLk3vWKMZGIa%252Fimage.png%3Falt%3Dmedia%26token%3Ded01a9e7-3582-4af0-9547-478d5a224beb&width=768&dpr=3&quality=100&sign=4fdaafae&sv=2) Clarity contracts can measure time by Bitcoin blocks. This is not just technical — it's symbolic: Like tracking time by the sun, we trust Bitcoin’s cadence. * * * ### [hashtag](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#additional-resources) Additional Resources * \[[Hiro Blogarrow-up-right](https://www.hiro.so/blog/building-on-bitcoin-project-comparison)\ \] Building on Bitcoin: a Comparison of Bitcoin Projects * \[[Hiro Booksarrow-up-right](https://www.hiro.so/books/a-beginners-guide-to-bitcoin-layers)\ \] A Beginner's Guide to Bitcoin Layers * \[[Stacks YTarrow-up-right](https://www.youtube.com/watch?v=F31B-my510A)\ \] The Stacks & Bitcoin Miners Relationship [PreviousWhat Is Stacks?chevron-left](https://docs.stacks.co/learn/stacks-101/what-is-stacks) [NextProof of Transfer (PoX)chevron-right](https://docs.stacks.co/learn/stacks-101/proof-of-transfer) Last updated 1 month ago Was this helpful? * [What's the purpose of a Bitcoin layer?](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#whats-the-purpose-of-a-bitcoin-layer) * [How would we define what a Bitcoin layer is?](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#how-would-we-define-what-a-bitcoin-layer-is) * [Is Stacks a Bitcoin L2?](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#is-stacks-a-bitcoin-l2) * [The Symbiotic Relationship Between Stacks and Bitcoin](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#the-symbiotic-relationship-between-stacks-and-bitcoin) * [On Crafting a Bitcoin-First Developer Experience](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#on-crafting-a-bitcoin-first-developer-experience) * [Additional Resources](https://docs.stacks.co/learn/stacks-101/bitcoin-connection#additional-resources) Was this helpful? sun-brightdesktopmoon sun-brightdesktopmoon --- # Condiciones posteriores | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-3716767855649150a8a31e6cedc4c9d4139a7500%252Fimage.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=790302db&sv=2) circle-info **Recursos para desarrolladores** * Para profundizar en el uso de las post-condiciones, [aquí](https://docs.stacks.co/post-conditions/overview) . * Para la especificación técnica de las post-condiciones descrita en SIP-005, [aquíarrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md#transaction-post-conditions) . #### [hashtag](https://docs.stacks.co/learn/es/transactions/post-conditions#la-imagen-general) **La imagen general** * Las post-condiciones son restricciones _que adjuntas a una transacción_ que definen exactamente qué activos (STX, tokens SIP-010, NFT) pueden moverse y en qué cantidad. * Si la ejecución del contrato inteligente subyacente violaría tus límites declarados, toda la transacción se aborta. * Incluso si un contrato inteligente contiene lógica inesperada, no puede mover activos más allá de lo que permiten tus post-condiciones. * Las post-condiciones se construyen del lado del cliente, por lo general por el desarrollador del lado del cliente. Son parte de la transacción firmada. Los contratos no pueden modificarlas. * Las billeteras analizarán la transacción firmada y mostrarán las post-condiciones declaradas al usuario antes de transmitirla. * * * ### [hashtag](https://docs.stacks.co/learn/es/transactions/post-conditions#what-are-post-conditions) ¿Qué son las post-condiciones? Las post-condiciones son afirmaciones sobre una transacción en cadena que deben cumplirse; de lo contrario, la transacción se abortará durante la ejecución. En otras palabras, las post-condiciones actúan como una red de seguridad, permitiéndote especificar qué cambios de estado pueden ocurrir en una transacción. **A veces, el desarrollador del lado del cliente no es la misma persona que escribió el contrato inteligente subyacente y puede no estar familiarizado en profundidad con su lógica interna, llamadas externas anidadas a otros contratos o casos límite.** Esta lógica ayuda a limitar la cantidad de daño que se le puede hacer a un usuario y a sus activos, ya sea por un error o por comportamiento malintencionado. En pocas palabras, las post-condiciones son un conjunto de condiciones que deben cumplirse antes de que se ejecute la transacción de un usuario. El objetivo principal de las post-condiciones es limitar la cantidad de daño que se le puede causar a los activos de un usuario debido a un error, intencional o no. Las post-condiciones son una característica de seguridad adicional incorporada en el propio protocolo Stacks que ayuda a proteger a los usuarios finales. En lugar de ser una característica de los contratos inteligentes Clarity, se implementan en el lado del cliente y están pensadas como una salvaguarda adicional contra contratos maliciosos. Se envían como parte de la transacción cuando el usuario la inicia, por lo que debemos implementar las post-condiciones en el frontend. Siempre que transfieras un activo (fungible o no fungible) de una dirección a otra, deberías aprovechar las post-condiciones. * * * > #### > > [hashtag](https://docs.stacks.co/learn/es/transactions/post-conditions#las-post-condiciones-actuan-como-una-red-de-seguridad-permitiendote-especificar-que-cambios-de-estad) > > _Las post-condiciones actúan como una red de seguridad, permitiéndote especificar qué cambios de estado pueden y deben ocurrir durante la ejecución de una transacción._ [AnteriorCómo funcionan las transaccioneschevron-left](https://docs.stacks.co/learn/es/transactions/how-transactions-work) [SiguienteClaritychevron-right](https://docs.stacks.co/learn/es/clarity) Última actualización hace 1 mes ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Sistema de Nombres de Bitcoin | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fgit-blob-402906fc4f7e845fcfdf66d4752cf3674090b37e%252Fimage.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=12470b0c&sv=2) circle-info **Recursos para desarrolladores** * Sitio oficial de BNSv2 para estadísticas, [aquíarrow-up-right](https://www.bnsv2.com/) . * contrato de BNSv2 en mainnet, [aquíarrow-up-right](https://explorer.hiro.so/txid/SP2QEZ06AGJ3RKJPBV14SY1V5BBFNAW33D96YPGZF.BNS-V2) . * SDK de BNSv2, [aquíarrow-up-right](https://github.com/Strata-Labs/bns-v2-sdk) . * repositorio de contratos de BNSv2, [aquíarrow-up-right](https://github.com/Trust-Machines/BNS-V2) . #### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system#de-un-vistazo) De un vistazo * BNS es el sistema de nombres en vivo en Stacks * Nombres legibles por humanos como `alice.id` o `muneeb.btc` se asignan a datos en cadena * Los nombres son NFT compatibles con SIP-009: transferibles, comerciables, composables * Mercado integrado para listar, comprar y vender nombres * Admite espacios de nombres abiertos (no gestionados) y gobernados (gestionados) * Cada dirección puede poseer múltiples nombres y designar un nombre principal * Totalmente implementado como contratos inteligentes Clarity * La implementación actual de BNS utiliza el contrato BNS V2, desplegado en septiembre de 2024. Sustituyó al contrato V1 del lanzamiento de la mainnet de Stacks en 2021. * * * [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system#que-es-bns) ¿Qué es BNS? ---------------------------------------------------------------------------------------------------------------- El **Sistema de Nombres de Bitcoin (BNS)** es un sistema de nombres descentralizado construido sobre Stacks y asegurado por Bitcoin. Permite nombres legibles por humanos (por ejemplo, `alice.id`) que se asignan a identidades en cadena, direcciones y registros arbitrarios. Bitcoin Name Service (BNS) es un protocolo de identidad descentralizado que originalmente comenzó en Bitcoin como Namecoin en 2014 antes de migrar a Bitcoin en 2015, y finalmente a Stacks cuando su mainnet se lanzó en 2021. ¡Eso significa que BNS es anterior a ENS por varios años! BNS está representado por el popular espacio de nombres .btc pero tiene muchos otros, incluidos .id, .locker, .app y más. Cualquiera puede crear un nuevo espacio de nombres y permitir que los usuarios registren nombres en él. Actualmente hay 97 espacios de nombres y más de 360.000 nombres registrados en BNS \[a marzo de 2026\]! Principales espacios de nombres \[a marzo de 2026\] Nombres registrados bajo el espacio de nombres .btc 302,999 .stx 21,861 .app 12,445 .id 12,053 .stacks 3,961 El beneficio de un nombre BNS es simple: en lugar de enviar cripto a una larga dirección STX o BTC, puedes usar un nombre legible por humanos como muneeb.btc. Los nombres BNS son compatibles con billeteras Stacks como Leather y Xverse y admiten tanto Stacks L2 como Bitcoin L1 para pagos. BNS reemplaza direcciones blockchain complejas por nombres que: * Pueden resolverse a principales de Stacks * Pueden almacenar metadatos estructurados * Los nombres pueden almacenar zonefiles que contienen datos de perfil (biografía, imagen de perfil, enlaces sociales), direcciones de billeteras en distintas cadenas (BTC, ETH, etc.), definiciones de subdominios y metadatos arbitrarios de clave-valor. Todo almacenado on-chain a través del contrato zonefile-resolver. * Pueden integrarse directamente con contratos inteligentes * Son propiedad y se gestionan completamente on-chain Stacks actualmente ejecuta **BNSv2**, una implementación mejorada diseñada para una mayor composabilidad, claridad y ergonomía para desarrolladores. Permite a los usuarios registrar, gestionar y transferir nombres dentro de diferentes espacios de nombres. También introduce un mercado nativo, espacios de nombres gestionados con gobernanza personalizada, propiedad de múltiples nombres por dirección, designación de nombre principal y almacenamiento on-chain de zonefiles desacoplado del contrato principal. * * * * * * [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system#recursos-adicionales) Recursos adicionales ---------------------------------------------------------------------------------------------------------------------------------- * [\[Oficial BNSv2\]arrow-up-right](https://www.bnsv2.com/) Sitio oficial de BNSv2 * [\[BNS One\]arrow-up-right](https://bns.one/) Registrar, comerciar, descubrir espacios de nombres y nombres BNS * \[[Trust Machines Githubarrow-up-right](https://github.com/Trust-Machines/BNS-V2)\ \] repositorio de contratos BNSv2 * [\[Foro Stacks\]arrow-up-right](https://forum.stacks.org/t/megathread-bns-upgrade-discussion/14899) Hilo de discusión sobre la actualización previa * [\[BNSv1\]arrow-up-right](https://explorer.hiro.so/address/SP000000000000000000002Q6VF78.bns?chain=mainnet) El contrato boot de la implementación anterior BNSv1 * [\[Comunidad BNS\]arrow-up-right](https://x.com/bns_community) Página de la comunidad en Twitter sobre todo lo relacionado con BNS * [\[Gamma\]arrow-up-right](https://gamma.io/stacks/collections/bns-v2/items) Mercado para comerciar BNS * [\[BTC US\]arrow-up-right](https://btc.us/) Registrar nombres BNS [AnteriorBilleteras y cuentaschevron-left](https://docs.stacks.co/learn/es/network-fundamentals/wallets-and-accounts) [SiguienteHistoria de BNSchevron-right](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/history) Última actualización hace 1 mes ¿Te fue útil? * [¿Qué es BNS?](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system#que-es-bns) * [Recursos adicionales](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system#recursos-adicionales) ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Producción de bloques | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FAtIlPCw7qrGfrokaExNi%252Fblock-production-cover.png%3Falt%3Dmedia%26token%3Da3179850-9434-42ed-baf4-c64037aa5b03&width=768&dpr=3&quality=100&sign=553cba3d&sv=2) La producción de bloques es un concepto clave para entender cómo funciona Stacks internamente. Esta sección describe las tres acciones principales que deben ocurrir para que la red Stacks opere. 1 **Minería** Los mineros son responsables de construir y proponer nuevos bloques en la cadena Stacks. 2 **Firma** La firma es el proceso utilizado para validar bloques y firmar depósitos y retiros de sBTC. Los stackers participan en la firma una vez que cumplen los requisitos previos de stacking. 3 **Stacking** El stacking es una acción realizada por los stackers que es un requisito necesario para la firma. Permite la participación en la validación y la obtención de recompensas. Hay dos partes principales en la producción de bloques de Stacks: mineros, stackers y firmantes. Los mineros construyen y proponen nuevos bloques, mientras que los stackers validan esos bloques y firman depósitos y retiros de sBTC. El stacking permite a los stackers participar en la firma. * * * ### [hashtag](https://docs.stacks.co/learn/es/block-production#roles-principales-minero-vs-stacker-vs-firmante) Roles principales: Minero vs Stacker vs Firmante Rol Función principal Lo que hacen Recompensas Dónde operan **Minero** Producir bloques de Stacks Envía BTC en PoX para competir por el derecho a escribir el siguiente bloque y ganar STX Gana recompensas de bloque en STX + comisiones Bitcoin (para pujas) + Stacks **Stacker** Asegurar la red mediante PoX Bloquea STX y señala apoyo al consenso Gana BTC de los mineros Stacks (bloquea STX), recompensas en Bitcoin **Firmante** Validar y finalizar bloques Participa en la firma de bloques para confirmar el estado canónico de la cadena; define el conjunto de recompensas Recompensas basadas en acuerdos personalizados con los Stackers Stacks #### [hashtag](https://docs.stacks.co/learn/es/block-production#la-relacion-entre-stackers-y-firmantes) La relación entre Stackers y Firmantes Al leer la sección de Stacking, puede que encuentres que a los Stackers se les denomina indistintamente Firmantes. Es cierto que los Stackers también pueden asumir el rol de Firmante, y viceversa, pero hay algunas matices que deben entenderse: * No todos los stackers son firmantes → porque los stackers pueden **delegar** su participación (incluyendo las responsabilidades de firma) * Todos los firmantes están respaldados por **su propio STX** o **STX delegado** → para estar en el conjunto de firmantes, debe representar **peso de STX stacked** [AnteriorAuditoríaschevron-left](https://docs.stacks.co/learn/es/network-fundamentals/audits) [SiguienteMiningchevron-right](https://docs.stacks.co/learn/es/block-production/mining) Última actualización hace 22 días ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Ordinals Swap | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close circle-info This contract is a part of the [ordyswaparrow-up-right](https://github.com/mechanismHQ/ordyswap) project repo. [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/ordinals-swap#contract-summary) Contract Summary ------------------------------------------------------------------------------------------------------------------------- OrdinalSwap enables trustless peer-to-peer atomic swaps between Bitcoin Ordinals and STX tokens. This contract demonstrates cross-chain verification by validating Bitcoin transactions directly within Clarity, creating a bridge between Bitcoin and Stacks blockchains. **What this contract does:** * Enables users to create STX offers for specific Ordinals (identified by txid and output index) * Escrows STX in the contract until the swap is completed or cancelled * Verifies Bitcoin transaction inclusion using Clarity Bitcoin library * Validates that the correct Ordinal was sent to the correct Bitcoin address * Releases escrowed STX to the seller upon proof of Ordinal transfer * Implements cancellation with a 50-block safety window to prevent front-running * Supports refunds after cancellation period expires * Targets "Genesis" Ordinals (first transfer from coinbase) **What developers can learn:** * Cross-chain atomic swap patterns using hash-time-locked contracts * Bitcoin SPV (Simplified Payment Verification) on Stacks using clarity-bitcoin * Parsing and validating Bitcoin transactions within Clarity * Anti-front-running mechanisms with time-delayed cancellations * Escrow patterns for trustless exchanges * Working with Bitcoin transaction structures (inputs, outputs, txid) * Using block heights for time-based logic and safety windows * State management across multiple maps for complex workflows * Integration with external Clarity libraries (clarity-bitcoin) [PreviousNFT Marketplacechevron-left](https://docs.stacks.co/cookbook/clarity/example-contracts/nft-marketplace) [NextDeFi Lendingchevron-right](https://docs.stacks.co/cookbook/clarity/example-contracts/defi-lending) Was this helpful? Was this helpful? sun-brightdesktopmoon ord-swap.clar Copy ;; OrdinalSwap ;; ;;;; ;; Trustless p2p atomic swaps between Ordinals and STX ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; This code is provided for educational purposes and has not been audited, ;; or thoroughly tested. Use at your own risk. ;; ;; Source: https://github.com/mechanismHQ/ordyswap ;; ;; WARNING ;; This version of ordyswap should only be used with "Genesis" Ordinals, not ;; Ordinals that have already been transferred. ;; ;; DESCRIPTION ;; The basic flow is: ;; ;; - Someone makes an offer on a specific Ordinal. They must know the seller's ;; STX address ahead of time ;; - This contract escrows the STX ;; - Ordinal owner sends the Ordinal to specified BTC address made in the offer ;; - Ordinal owner calls this contract with a transaction inclusion proof to ;; show that they send the right Ordinal to the right address ;; - This contract sends STX to the Ordinal owner ;; Main map for storing offers (define-map offers-map uint { txid: (buff 32), index: uint, amount: uint, output: (buff 128), sender: principal, recipient: principal, } ) (define-map offers-accepted-map uint bool ) ;; mapping of offer -> block height (define-map offers-cancelled-map uint uint ) (define-map offers-refunded-map uint bool ) (define-data-var last-id-var uint u0) (define-constant ERR_TX_NOT_MINED (err u100)) (define-constant ERR_INVALID_TX (err u101)) (define-constant ERR_INVALID_OFFER (err u102)) (define-constant ERR_OFFER_MISMATCH (err u103)) (define-constant ERR_OFFER_ACCEPTED (err u104)) (define-constant ERR_OFFER_CANCELLED (err u105)) (define-public (create-offer (txid (buff 32)) (index uint) (amount uint) (output (buff 128)) (recipient principal) ) (let ((id (make-next-id))) (try! (stx-transfer? amount tx-sender current-contract)) (map-insert offers-map id { txid: txid, index: index, amount: amount, output: output, sender: tx-sender, recipient: recipient, }) (print { topic: "new-offer", offer: { id: id, txid: txid, index: index, amount: amount, output: output, sender: tx-sender, recipient: recipient, }, }) (ok id) ) ) ;; Helper function to validate the transfer of an Ordinal. ;; ;; This function is validating: ;; ;; - The transaction was mined in a BTC block ;; - The transaction was sent to the right address ;; - The transaction includes the right Ordinal as an input ;; - The offer wasn't cancelled ;; - The offer wasn't already accepted (define-read-only (validate-offer-transfer (block { header: (buff 80), height: uint, }) (prev-blocks (list 10 (buff 80))) (tx (buff 1024)) (proof { tx-index: uint, hashes: (list 12 (buff 32)), tree-depth: uint, }) (input-index uint) (output-index uint) (offer-id uint) ) (let ( (was-mined-bool (unwrap! (contract-call? 'SP1WN90HKT0E1FWCJT9JFPMC8YP7XGBGFNZGHRVZX.clarity-bitcoin was-tx-mined-prev? block prev-blocks tx proof ) ERR_TX_NOT_MINED )) (was-mined (asserts! was-mined-bool ERR_TX_NOT_MINED)) (mined-height (get height block)) (parsed-tx (unwrap! (contract-call? 'SP1WN90HKT0E1FWCJT9JFPMC8YP7XGBGFNZGHRVZX.clarity-bitcoin parse-tx tx ) ERR_INVALID_TX )) (output (unwrap! (element-at (get outs parsed-tx) output-index) ERR_INVALID_TX)) (offer (unwrap! (map-get? offers-map offer-id) ERR_INVALID_OFFER)) (input (get outpoint (unwrap! (element-at (get ins parsed-tx) input-index) ERR_INVALID_TX) )) (input-txid (get hash input)) (input-idx (get index input)) ) ;; Ensure that the right ordinal is being sent - based on the `{txid,index}` (asserts! (is-eq input-txid (get txid offer)) ERR_OFFER_MISMATCH) (asserts! (is-eq input-idx (get index offer)) ERR_OFFER_MISMATCH) ;; Ensure it was sent to the right address (asserts! (is-eq (get scriptPubKey output) (get output offer)) ERR_OFFER_MISMATCH ) ;; Ensure it hasn't been accepted (asserts! (is-eq (map-get? offers-accepted-map offer-id) none) ERR_OFFER_ACCEPTED ) ;; Ensure it wasn't cancelled (match (map-get? offers-cancelled-map offer-id) cancelled-at (if (<= burn-block-height cancelled-at) (ok offer) ERR_OFFER_CANCELLED ) (ok offer) ) ) ) (define-public (finalize-offer (block { header: (buff 80), height: uint, }) (prev-blocks (list 10 (buff 80))) (tx (buff 1024)) (proof { tx-index: uint, hashes: (list 12 (buff 32)), tree-depth: uint, }) (output-index uint) (input-index uint) (offer-id uint) ) (let ( (offer (try! (validate-offer-transfer block prev-blocks tx proof input-index output-index offer-id ))) (amount (get amount offer)) ) (try! (as-contract? ((with-stx amount)) (try! (stx-transfer? amount current-contract (get recipient offer))) )) (asserts! (map-insert offers-accepted-map offer-id true) ERR_OFFER_ACCEPTED) (print { topic: "offer-finalized", offer: (merge offer { id: offer-id }), txid: (contract-call? 'SP1WN90HKT0E1FWCJT9JFPMC8YP7XGBGFNZGHRVZX.clarity-bitcoin get-txid tx ), }) (ok offer-id) ) ) ;; Cancel an offer ;; ;; The Ordinal owner still has 50 blocks to send the ordinal. This ;; prevents an attack where an offer is cancelled after the Ordinal transfer ;; hits the mempool. (define-public (cancel-offer (id uint)) (let ((offer (unwrap! (map-get? offers-map id) ERR_INVALID_OFFER))) (asserts! (is-eq (get sender offer) tx-sender) ERR_INVALID_OFFER) (asserts! (map-insert offers-cancelled-map id (+ burn-block-height u50)) ERR_INVALID_OFFER ) (print { topic: "offer-cancelled", offer: (merge offer { id: id }), }) (ok true) ) ) ;; 50+ blocks after cancelling, the offerer can get their STX back (define-public (refund-cancelled-offer (id uint)) (let ( (offer (unwrap! (map-get? offers-map id) ERR_INVALID_OFFER)) (amount (get amount offer)) (cancelled (unwrap! (map-get? offers-cancelled-map id) ERR_INVALID_OFFER)) ) (asserts! (> burn-block-height cancelled) ERR_INVALID_OFFER) (asserts! (map-insert offers-refunded-map id true) ERR_INVALID_OFFER) (try! (as-contract? ((with-stx amount)) (try! (stx-transfer? amount current-contract (get sender offer))) )) (print { topic: "offer-refunded", offer: (merge offer { id: id }), }) (ok id) ) ) ;; Getters (define-read-only (get-offer (id uint)) (map-get? offers-map id) ) (define-read-only (get-offer-accepted (id uint)) (map-get? offers-accepted-map id) ) (define-read-only (get-offer-cancelled (id uint)) (map-get? offers-cancelled-map id) ) (define-read-only (get-offer-refunded (id uint)) (map-get? offers-cancelled-map id) ) (define-read-only (get-last-id) (var-get last-id-var) ) ;; Private (define-private (make-next-id) (let ((last-id (var-get last-id-var))) (var-set last-id-var (+ last-id u1)) last-id ) ) chevron-downShow all 272 lines sun-brightdesktopmoon --- # Operate a Pool | Operate | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close This guide covers how to operate a stacking pool: accepting delegated STX from stackers, committing them to reward cycles, and managing the pool's stacked position. circle-info This guide assumes you are familiar with stacking at a conceptual level. If not, read the [Stackingarrow-up-right](https://github.com/stacks-network/docs/blob/master/docs/learn/block-production/stacking.md) concept guide first. If you want to delegate your STX to a pool instead, see the [Stack with a Pool](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool) guide. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#prerequisites) Prerequisites ------------------------------------------------------------------------------------------------------ 1. **A running signer** or a signer you are collaborating with. See the [Run a Signer](https://docs.stacks.co/operate/run-a-signer) guide. 2. **A pool operator wallet**: a separate STX address used to manage delegations and make stacking transactions. This is different from your signer key. See [Key and Address Rotation](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation) for why this separation matters. 3. **Funding**: your pool operator wallet needs enough STX to cover transaction fees. circle-info As a pool operator, you should have two separate accounts: * **Pool operator account**: used for all stacking operations (`delegate-stack-stx`, `stack-aggregation-commit-indexed`, etc.). * **Signer account**: the key used to configure your signer. The signer public key is what you pass into the aggregation commit function. This separation is recommended because you can rotate a signer key without disrupting delegations, but you cannot rotate a pool operator key without delegators needing to un-stack and re-delegate. See [Key and Address Rotation](https://docs.stacks.co/operate/stacking-stx/key-and-address-rotation) for more details. Set up your pool operator wallet using any Stacks wallet such as [Leatherarrow-up-right](https://leather.io/) or [Xversearrow-up-right](https://www.xverse.app/) . Share this wallet's STX address with parties that will delegate to you. For improved UX, you might use the helper contract [pox4-poolsarrow-up-right](https://explorer.hiro.so/txid/SP001SFSMC2ZY76PD4M68P3WGX154XCH7NE3TYMX.pox4-pools?chain=mainnet) and add your pool to [earn.leather.ioarrow-up-right](https://earn.leather.io/) . circle-info There are several ways to make stacking transactions. This guide covers using [Leather Earnarrow-up-right](https://earn.leather.io/) , which is the simplest option. You can also call the functions directly from the [deployed contractarrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-4?chain=mainnet) , or use the [@stacks/stackingarrow-up-right](https://github.com/stx-labs/stacks.js/tree/main/packages/stacking) NPM package. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#accept-delegations) Accept Delegations ---------------------------------------------------------------------------------------------------------------- After a delegator calls `delegate-stx` (see [Stack with a Pool](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool) ), you as the pool operator call `delegate-stack-stx` to commit each delegator's STX. This must be called for every individual stacker. chevron-rightFunction source code[hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#function-source-code) The arguments are: * **Stacker**: the STX address of the delegator * **Amount**: denoted in uSTX (1 STX = 1,000,000 uSTX) * **Pox Address**: the BTC address where you will receive rewards. If the delegator specified a BTC address in their `delegate-stx` call, you must use that same address. * **Start burn height**: the current BTC block height (add 1 or 2 to the current height when initiating the transaction). The delegation will not actively be stacked at this height, but at whatever reward cycle is committed in the aggregation commit step. * **Lock period**: number of cycles to lock for (maximum 12). If the delegator specified an expiration burn height, the lock period cannot extend past that. This step also lets you choose which stackers to accept. For closed pools, only call this function for approved stackers. You can repeat this for multiple stackers before proceeding to the commit step. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#commit-delegated-stx) Commit Delegated STX -------------------------------------------------------------------------------------------------------------------- Once the total delegated STX exceeds the minimum stacking threshold, call `stack-aggregation-commit-indexed` to commit the pool's aggregate balance to a reward cycle. This is when you provide your signer key and signature. circle-info The minimum stacking threshold can be found at [https://api.hiro.so/v2/poxarrow-up-right](https://api.hiro.so/v2/pox) under `min_threshold_ustx` (1 STX = 1,000,000 uSTX). circle-info Use `stack-aggregation-commit-indexed` instead of the legacy `stack-aggregation-commit`. The indexed version returns the reward index, which is required if you later need to call `stack-aggregation-increase`. chevron-rightFunction source code[hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#function-source-code-1) Note that `stack-aggregation-commit-indexed` wraps `inner-stack-aggregation-commit`. The inner function is shown here. The arguments are: * **Pox Address**: the BTC address to receive rewards * **Reward-cycle**: the future reward cycle to commit for * **Signer public key**: the public key of your signer (this is how you associate your pool operator address with your signer) * **Signer signature**: a signature proving control of your signing key (see [Generate a Signer Signature](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) ) * **Max Amount**: used to validate the signer signature * **Auth Id**: used to validate the signer signature circle-info The `delegate-stack-stx` function sets the stacker's first reward cycle to the _next_ reward cycle. When generating your signature and calling `stack-aggregation-commit-indexed`, make sure the reward cycles match. For example, if you are in cycle 557 when calling `delegate-stack-stx`, pass cycle 558 or higher in both your signature and your `stack-aggregation-commit-indexed` transaction. For solo stacking methods, you use the current reward cycle in the signature. For `stack-aggregation-commit-indexed`, you use the target reward cycle because you can commit for future cycles, not just N+1. Once this succeeds, your pool is eligible for reward slots in that cycle. All steps up to this point must be completed before the prepare phase begins. ### [hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#using-leather-earn) Using Leather Earn Pool operators can log in to Leather Earn and visit [https://earn.leather.io/pool-adminarrow-up-right](https://earn.leather.io/pool-admin) to manage pool operations: * **delegate-stack-stx**: After a user delegates, call this for each individual stacker. * **stack-aggregation-commit**: Enter the reward cycle, BTC address, signer public key, signer key signature, Auth ID, and Max amount. This must be done for every individual reward cycle where the pool will be acting as a signer. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#increase-committed-amount) Increase Committed Amount ------------------------------------------------------------------------------------------------------------------------------ Even after committing, you can increase the total committed STX when new delegations are received. 1 **Update the delegator's locked amount** Call `delegate-stack-increase` for each delegator whose locked amount needs to increase. chevron-rightFunction source code[hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#function-source-code-2) Arguments: * **Stacker**: the STX address of the delegator * **Pox Address**: the BTC address for rewards. Must match the delegator's specified address if one was set. * **Increase by**: the amount of uSTX to add to the delegator's locked amount 2 **Commit or increase the stacked amount** After updating locked amounts, you must commit the change: * **If you have not yet committed** for the given cycle: call `stack-aggregation-commit-indexed` (see above). * **If you have already committed**: call `stack-aggregation-increase` with the index returned from the first commit and a new signature. chevron-rightstack-aggregation-increase source code[hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#stack-aggregation-increase-source-code) Arguments for `stack-aggregation-increase`: * **Pox Address**: the BTC address to receive rewards * **Reward Cycle**: a reward cycle in the future * **Reward Cycle Index**: the index returned by `stack-aggregation-commit-indexed` circle-exclamation This is a sequential process. First call `delegate-stack-increase`, then commit the change: * Use `stack-aggregation-commit-indexed` if this is the first commit for that cycle. * Use `stack-aggregation-increase` if you have already committed. Failing to commit (or properly increase after a commit) will result in the increased delegation not taking effect. * * * [hashtag](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#how-signer-registration-works-for-pools) How Signer Registration Works for Pools ---------------------------------------------------------------------------------------------------------------------------------------------------------- The delegated stacking workflow requires multiple transactions to register a signer: 1 **Stackers delegate their STX** Stackers call `delegate-stx` to give the pool operator permission. 2 **Pool operator accepts delegations** The pool operator calls `delegate-stack-stx` for each individual stacker. 3 **Pool operator commits** The pool operator calls `stack-aggregation-commit-indexed` to commit all delegated STX. This is where the signer key is associated with the pool. All steps must be completed before the prepare phase of the target reward cycle. During the prepare phase, DKG occurs and the signer is automatically registered. No manual action is needed beyond monitoring. [PreviousStack with a Poolchevron-left](https://docs.stacks.co/operate/stacking-stx/stack-with-a-pool) [NextGenerate a Signer Signaturechevron-right](https://docs.stacks.co/operate/stacking-stx/generate-signer-signature) Last updated 12 days ago Was this helpful? * [Prerequisites](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#prerequisites) * [Accept Delegations](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#accept-delegations) * [Commit Delegated STX](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#commit-delegated-stx) * [Using Leather Earn](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#using-leather-earn) * [Increase Committed Amount](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#increase-committed-amount) * [How Signer Registration Works for Pools](https://docs.stacks.co/operate/stacking-stx/operate-a-pool#how-signer-registration-works-for-pools) Was this helpful? sun-brightdesktopmoon Copy ;; As a delegate, stack the given principal's STX using partial-stacked-by-cycle ;; Once the delegate has stacked > minimum, the delegate should call stack-aggregation-commit (define-public (delegate-stack-stx (stacker principal) (amount-ustx uint) (pox-addr { version: (buff 1), hashbytes: (buff 32) }) (start-burn-ht uint) (lock-period uint)) ;; this stacker's first reward cycle is the _next_ reward cycle (let ((first-reward-cycle (+ u1 (current-pox-reward-cycle))) (specified-reward-cycle (+ u1 (burn-height-to-reward-cycle start-burn-ht))) (unlock-burn-height (reward-cycle-to-burn-height (+ (current-pox-reward-cycle) u1 lock-period)))) ;; the start-burn-ht must result in the next reward cycle, do not allow stackers ;; to "post-date" their `stack-stx` transaction (asserts! (is-eq first-reward-cycle specified-reward-cycle) (err ERR_INVALID_START_BURN_HEIGHT)) ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) ;; stacker must have delegated to the caller (let ((delegation-info (unwrap! (get-check-delegation stacker) (err ERR_STACKING_PERMISSION_DENIED)))) ;; must have delegated to tx-sender (asserts! (is-eq (get delegated-to delegation-info) tx-sender) (err ERR_STACKING_PERMISSION_DENIED)) ;; must have delegated enough stx (asserts! (>= (get amount-ustx delegation-info) amount-ustx) (err ERR_DELEGATION_TOO_MUCH_LOCKED)) ;; if pox-addr is set, must be equal to pox-addr (asserts! (match (get pox-addr delegation-info) specified-pox-addr (is-eq pox-addr specified-pox-addr) true) (err ERR_DELEGATION_POX_ADDR_REQUIRED)) ;; delegation must not expire before lock period (asserts! (match (get until-burn-ht delegation-info) until-burn-ht (>= until-burn-ht unlock-burn-height) true) (err ERR_DELEGATION_EXPIRES_DURING_LOCK)) ) ;; stacker principal must not be stacking (asserts! (is-none (get-stacker-info stacker)) (err ERR_STACKING_ALREADY_STACKED)) ;; the Stacker must have sufficient unlocked funds (asserts! (>= (stx-get-balance stacker) amount-ustx) (err ERR_STACKING_INSUFFICIENT_FUNDS)) ;; ensure that stacking can be performed (try! (minimal-can-stack-stx pox-addr amount-ustx first-reward-cycle lock-period)) ;; register the PoX address with the amount stacked via partial stacking ;; before it can be included in the reward set, this must be committed! (add-pox-partial-stacked pox-addr first-reward-cycle lock-period amount-ustx) ;; add stacker record (map-set stacking-state { stacker: stacker } { pox-addr: pox-addr, first-reward-cycle: first-reward-cycle, reward-set-indexes: (list), lock-period: lock-period, delegated-to: (some tx-sender) }) ;; return the lock-up information, so the node can actually carry out the lock. (ok { stacker: stacker, lock-amount: amount-ustx, unlock-burn-height: unlock-burn-height }))) Copy ;; Commit partially stacked STX and allocate a new PoX reward address slot. ;; This allows a stacker/delegate to lock fewer STX than the minimal threshold in multiple transactions, ;; so long as: 1. The pox-addr is the same. ;; 2. This "commit" transaction is called _before_ the PoX anchor block. ;; This ensures that each entry in the reward set returned to the stacks-node is greater than the threshold, ;; but does not require it be all locked up within a single transaction ;; ;; Returns (ok uint) on success, where the given uint is the reward address's index in the list of reward ;; addresses allocated in this reward cycle. This index can then be passed to `stack-aggregation-increase` ;; to later increment the STX this PoX address represents, in amounts less than the stacking minimum. ;; ;; *New in Stacks 2.1.* (define-private (inner-stack-aggregation-commit (pox-addr { version: (buff 1), hashbytes: (buff 32) }) (reward-cycle uint) (signer-sig (optional (buff 65))) (signer-key (buff 33)) (max-amount uint) (auth-id uint)) (let ((partial-stacked ;; fetch the partial commitments (unwrap! (map-get? partial-stacked-by-cycle { pox-addr: pox-addr, sender: tx-sender, reward-cycle: reward-cycle }) (err ERR_STACKING_NO_SUCH_PRINCIPAL)))) ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) (let ((amount-ustx (get stacked-amount partial-stacked))) (try! (consume-signer-key-authorization pox-addr reward-cycle "agg-commit" u1 signer-sig signer-key amount-ustx max-amount auth-id)) (try! (can-stack-stx pox-addr amount-ustx reward-cycle u1)) ;; Add the pox addr to the reward cycle, and extract the index of the PoX address ;; so the delegator can later use it to call stack-aggregation-increase. (let ((add-pox-addr-info (add-pox-addr-to-ith-reward-cycle u0 { pox-addr: pox-addr, first-reward-cycle: reward-cycle, num-cycles: u1, reward-set-indexes: (list), stacker: none, signer: signer-key, amount-ustx: amount-ustx, i: u0 })) (pox-addr-index (unwrap-panic (element-at (get reward-set-indexes add-pox-addr-info) u0)))) ;; don't update the stacking-state map, ;; because it _already has_ this stacker's state ;; don't lock the STX, because the STX is already locked ;; ;; clear the partial-stacked state, and log it (map-delete partial-stacked-by-cycle { pox-addr: pox-addr, sender: tx-sender, reward-cycle: reward-cycle }) (map-set logged-partial-stacked-by-cycle { pox-addr: pox-addr, sender: tx-sender, reward-cycle: reward-cycle } partial-stacked) (ok pox-addr-index))))) Copy ;; As a delegator, increase an active Stacking lock, issuing a "partial commitment" for the ;; increased cycles. ;; *New in Stacks 2.1* ;; This method increases `stacker`'s current lockup and partially commits the additional ;; STX to `pox-addr` (define-public (delegate-stack-increase (stacker principal) (pox-addr { version: (buff 1), hashbytes: (buff 32) }) (increase-by uint)) (let ((stacker-info (stx-account stacker)) (existing-lock (get locked stacker-info)) (available-stx (get unlocked stacker-info)) (unlock-height (get unlock-height stacker-info))) ;; must be called with positive `increase-by` (asserts! (>= increase-by u1) (err ERR_STACKING_INVALID_AMOUNT)) (let ((unlock-in-cycle (burn-height-to-reward-cycle unlock-height)) (cur-cycle (current-pox-reward-cycle)) (first-increase-cycle (+ cur-cycle u1)) (last-increase-cycle (- unlock-in-cycle u1)) (cycle-count (try! (if (<= first-increase-cycle last-increase-cycle) (ok (+ u1 (- last-increase-cycle first-increase-cycle))) (err ERR_STACKING_INVALID_LOCK_PERIOD)))) (new-total-locked (+ increase-by existing-lock)) (stacker-state (unwrap! (map-get? stacking-state { stacker: stacker }) (err ERR_STACK_INCREASE_NOT_LOCKED)))) ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) ;; stacker must not be directly stacking (asserts! (is-eq (len (get reward-set-indexes stacker-state)) u0) (err ERR_STACKING_NOT_DELEGATED)) ;; stacker must be delegated to tx-sender (asserts! (is-eq (unwrap! (get delegated-to stacker-state) (err ERR_STACKING_NOT_DELEGATED)) tx-sender) (err ERR_STACKING_PERMISSION_DENIED)) ;; stacker must be currently locked (asserts! (> existing-lock u0) (err ERR_STACK_INCREASE_NOT_LOCKED)) ;; stacker must have enough stx to lock (asserts! (>= available-stx increase-by) (err ERR_STACKING_INSUFFICIENT_FUNDS)) ;; stacker must have delegated to the caller (let ((delegation-info (unwrap! (get-check-delegation stacker) (err ERR_STACKING_PERMISSION_DENIED))) (delegated-to (get delegated-to delegation-info)) (delegated-amount (get amount-ustx delegation-info)) (delegated-pox-addr (get pox-addr delegation-info)) (delegated-until (get until-burn-ht delegation-info))) ;; must have delegated to tx-sender (asserts! (is-eq delegated-to tx-sender) (err ERR_STACKING_PERMISSION_DENIED)) ;; must have delegated enough stx (asserts! (>= delegated-amount new-total-locked) (err ERR_DELEGATION_TOO_MUCH_LOCKED)) ;; if pox-addr is set, must be equal to pox-addr (asserts! (match delegated-pox-addr specified-pox-addr (is-eq pox-addr specified-pox-addr) true) (err ERR_DELEGATION_POX_ADDR_REQUIRED)) ;; delegation must not expire before lock period (asserts! (match delegated-until until-burn-ht (>= until-burn-ht unlock-height) true) (err ERR_DELEGATION_EXPIRES_DURING_LOCK))) ;; delegate stacking does minimal-can-stack-stx (try! (minimal-can-stack-stx pox-addr new-total-locked first-increase-cycle (+ u1 (- last-increase-cycle first-increase-cycle)))) ;; register the PoX address with the amount stacked via partial stacking ;; before it can be included in the reward set, this must be committed! (add-pox-partial-stacked pox-addr first-increase-cycle cycle-count increase-by) ;; stacking-state is unchanged, so no need to update ;; return the lock-up information, so the node can actually carry out the lock. (ok { stacker: stacker, total-locked: new-total-locked})))) Copy ;; Commit partially stacked STX to a PoX address which has already received some STX (more than the Stacking min). ;; This allows a delegator to lock up marginally more STX from new delegates, even if they collectively do not ;; exceed the Stacking minimum, so long as the target PoX address already represents at least as many STX as the ;; Stacking minimum. ;; ;; The `reward-cycle-index` is emitted as a contract event from `stack-aggregation-commit` when the initial STX are ;; locked up by this delegator. It must be passed here to add more STX behind this PoX address. If the delegator ;; called `stack-aggregation-commit` multiple times for the same PoX address, then any such `reward-cycle-index` will ;; work here. ;; ;; *New in Stacks 2.1* ;; (define-public (stack-aggregation-increase (pox-addr { version: (buff 1), hashbytes: (buff 32) }) (reward-cycle uint) (reward-cycle-index uint)) (let ((partial-stacked ;; fetch the partial commitments (unwrap! (map-get? partial-stacked-by-cycle { pox-addr: pox-addr, sender: tx-sender, reward-cycle: reward-cycle }) (err ERR_STACKING_NO_SUCH_PRINCIPAL)))) ;; must be called directly by the tx-sender or by an allowed contract-caller (asserts! (check-caller-allowed) (err ERR_STACKING_PERMISSION_DENIED)) ;; reward-cycle must be in the future (asserts! (> reward-cycle (current-pox-reward-cycle)) (err ERR_STACKING_INVALID_LOCK_PERIOD)) (let ((amount-ustx (get stacked-amount partial-stacked)) ;; reward-cycle must point to an existing record in reward-cycle-total-stacked ;; infallible; getting something from partial-stacked-by-cycle succeeded so this must succeed (existing-total (unwrap-panic (map-get? reward-cycle-total-stacked { reward-cycle: reward-cycle }))) ;; reward-cycle and reward-cycle-index must point to an existing record in reward-cycle-pox-address-list (existing-entry (unwrap! (map-get? reward-cycle-pox-address-list { reward-cycle: reward-cycle, index: reward-cycle-index }) (err ERR_DELEGATION_NO_REWARD_SLOT))) (increased-ustx (+ (get total-ustx existing-entry) amount-ustx)) (total-ustx (+ (get total-ustx existing-total) amount-ustx))) ;; must be stackable (try! (minimal-can-stack-stx pox-addr total-ustx reward-cycle u1)) ;; new total must exceed the stacking minimum (asserts! (<= (get-stacking-minimum) total-ustx) (err ERR_STACKING_THRESHOLD_NOT_MET)) ;; there must *not* be a stacker entry (since this is a delegator) (asserts! (is-none (get stacker existing-entry)) (err ERR_DELEGATION_WRONG_REWARD_SLOT)) ;; the given PoX address must match the one on record (asserts! (is-eq pox-addr (get pox-addr existing-entry)) (err ERR_DELEGATION_WRONG_REWARD_SLOT)) ;; update the pox-address list -- bump the total-ustx (map-set reward-cycle-pox-address-list { reward-cycle: reward-cycle, index: reward-cycle-index } { pox-addr: pox-addr, total-ustx: increased-ustx, stacker: none, signer: (get signer existing-entry) }) ;; update the total ustx in this cycle (map-set reward-cycle-total-stacked { reward-cycle: reward-cycle } { total-ustx: total-ustx }) ;; clear the partial-stacked state, and log it (map-delete partial-stacked-by-cycle { pox-addr: pox-addr, sender: tx-sender, reward-cycle: reward-cycle }) (map-set logged-partial-stacked-by-cycle { pox-addr: pox-addr, sender: tx-sender, reward-cycle: reward-cycle } partial-stacked) (ok true)))) sun-brightdesktopmoon --- # Clarity | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FhNoJj4p1Tn1ICZ3RHBqb%252Fclarity-cover.png%3Falt%3Dmedia%26token%3Dbfe03cb2-6bc9-4bd7-840c-bd5a5b3d6e84&width=768&dpr=3&quality=100&sign=e9f16630&sv=2) circle-info Dirígete a [Curso intensivo de Clarity](https://docs.stacks.co/get-started/clarity-crash-course) para construir tu primer contrato inteligente en Clarity. Clarity es un **decidible** lenguaje de contratos inteligentes que optimiza la previsibilidad y la seguridad, diseñado para la cadena de bloques Stacks. Ha sido construido desde cero para facilitar a los desarrolladores la escritura de contratos inteligentes seguros y protegidos. Clarity tiene varias características únicas que lo convierten en una opción ideal para escribir contratos inteligentes. Las decisiones de diseño detrás de Clarity se basaron en gran medida en aprender de las explotaciones comunes de Solidity y en crear un lenguaje diseñado específicamente con la seguridad y la protección en mente. ### [hashtag](https://docs.stacks.co/learn/es/clarity#que-hace-a-clarity-diferente) Qué hace a Clarity diferente La siguiente sección es un extracto del [libro de Clarityarrow-up-right](https://book.clarity-lang.org/ch00-00-introduction.html) : El número de lenguajes de contratos inteligentes crece cada año. Elegir un primer lenguaje puede ser un desafío, especialmente para un principiante. La elección está dictada en gran medida por el ecosistema que te interese, aunque algunos lenguajes son aplicables a más de una plataforma. Cada lenguaje tiene sus ventajas y desventajas y está fuera del alcance de este libro analizar todos ellos. En su lugar, nos centraremos en lo que distingue a Clarity y por qué es una elección principal si requieres la máxima seguridad y transparencia. Uno de los preceptos centrales de Clarity es que es seguro por diseño. El proceso de diseño se guió examinando los errores comunes, fallos y vulnerabilidades en el campo de la ingeniería de contratos inteligentes en su conjunto. Existen innumerables ejemplos del mundo real donde la falla del desarrollador condujo a la pérdida o el robo de grandes cantidades de tokens. Para nombrar dos grandes: un problema que se ha conocido como el error de Parity llevó a la pérdida irreparable de millones de dólares en Ethereum. En segundo lugar, el hackeo de The DAO (una "Organización Autónoma Descentralizada") causó un daño financiero tan grande que la Fundación Ethereum decidió emitir un hard fork polémico que deshizo el robo. Estos y muchos otros errores podrían haberse prevenido en el diseño del propio lenguaje. #### [hashtag](https://docs.stacks.co/learn/es/clarity#clarity-es-interpretado-no-compilado) Clarity es interpretado, no compilado El código Clarity se interpreta y se registra en la cadena exactamente como está escrito. Solidity y otros lenguajes se compilan a bytecode antes de enviarse a la cadena. El peligro de los lenguajes de contratos inteligentes compilados es doble: primero, un compilador añade una capa de complejidad. Un error en el compilador puede llevar a un bytecode diferente del intencionado y por tanto conlleva el riesgo de introducir una vulnerabilidad. Segundo, el bytecode no es legible por humanos, lo que hace muy difícil verificar qué está haciendo realmente el contrato inteligente. Pregúntate: ¿firmarías un contrato que no puedes leer? Si tu respuesta es no, entonces ¿por qué debería ser diferente para los contratos inteligentes? Con Clarity, lo que ves es lo que obtienes. #### [hashtag](https://docs.stacks.co/learn/es/clarity#clarity-es-decidible) Clarity es decidible Un lenguaje decidible tiene la propiedad de que, a partir del propio código, puedes saber con certeza qué hará el programa. Esto evita problemas como el problema de la detención. Con Clarity sabes con seguridad que, dado cualquier entrada, el programa se detendrá en un número finito de pasos. En términos simples: se garantiza que la ejecución del programa terminará. La decidibilidad también permite un análisis estático completo del grafo de llamadas para que obtengas una imagen precisa del costo exacto antes de la ejecución. No hay forma de que una llamada en Clarity "se quede sin gas" en medio de la llamada. Exploramos esta idea más a fondo, junto con una discusión sobre la completitud de Turing, en el análisis de seguridad sobre decidibilidad. #### [hashtag](https://docs.stacks.co/learn/es/clarity#clarity-no-permite-reentradas) Clarity no permite reentradas La reentrancia es una situación en la que un contrato inteligente llama a otro, que luego vuelve a llamar al primer contrato—la llamada "reingresa" la misma lógica. Puede permitir que un atacante provoque múltiples retiros de tokens antes de que el contrato tenga la oportunidad de actualizar su contabilidad interna. El diseño de Clarity considera la reentrancia como una anti-característica y la prohíbe a nivel del lenguaje. #### [hashtag](https://docs.stacks.co/learn/es/clarity#clarity-protege-contra-desbordamientos-y-subdesbordamientos) Clarity protege contra desbordamientos y subdesbordamientos Los desbordamientos y subdesbordamientos ocurren cuando un cálculo da como resultado un número que es demasiado grande o demasiado pequeño para ser almacenado, respectivamente. Estos eventos sumen a los contratos inteligentes en el caos y pueden ser desencadenados intencionalmente en contratos mal escritos por atacantes. Normalmente esto conduce a una situación en la que el contrato queda congelado o agotado de tokens. Los desbordamientos y subdesbordamientos de cualquier tipo hacen que la transacción se aborte automáticamente en Clarity. #### [hashtag](https://docs.stacks.co/learn/es/clarity#el-soporte-para-tokens-personalizados-esta-integrado) El soporte para tokens personalizados está integrado La emisión de tokens fungibles y no fungibles personalizados es un caso de uso popular para los contratos inteligentes. Las funcionalidades de tokens personalizados están integradas en el lenguaje Clarity. Los desarrolladores no necesitan preocuparse por crear una contabilidad interna, gestionar la oferta o emitir eventos de tokens. La creación de tokens personalizados se trata en profundidad en capítulos posteriores. #### [hashtag](https://docs.stacks.co/learn/es/clarity#en-stacks-las-transacciones-se-aseguran-mediante-condiciones-posteriores) En Stacks, las transacciones se aseguran mediante condiciones posteriores Para salvaguardar aún más los tokens de los usuarios, se pueden adjuntar condiciones posteriores a las transacciones para afirmar que el estado de la cadena ha cambiado de cierta manera una vez que la transacción ha finalizado. Por ejemplo, un usuario que invoque un contrato inteligente puede adjuntar una condición posterior que indique que, después de que la llamada se complete, exactamente 500 STX deberían haberse transferido de una dirección a otra. Si la verificación de la condición posterior falla, entonces toda la transacción se revierte. Dado que el soporte de tokens personalizados está integrado directamente en Clarity, las condiciones posteriores también pueden usarse para proteger cualquier otro token de la misma manera. #### [hashtag](https://docs.stacks.co/learn/es/clarity#las-respuestas-devueltas-no-pueden-quedar-sin-verificar) Las respuestas devueltas no pueden quedar sin verificar Las llamadas públicas a contratos deben devolver una llamada denominada response que indica éxito o fracaso. Cualquier contrato que llame a otro está obligado a manejar correctamente la respuesta. Los contratos Clarity que no lo hagan son inválidos y no pueden desplegarse en la red. Otros lenguajes como Solidity permiten el uso de llamadas de bajo nivel sin requerir que se compruebe el valor devuelto. Por ejemplo, una transferencia de tokens puede fallar silenciosamente si el desarrollador olvida comprobar el resultado. En Clarity no es posible ignorar errores, aunque eso obviamente previene el manejo de errores con bugs por parte del desarrollador. Las responses y el manejo de errores se tratan extensamente en los capítulos sobre funciones y flujo de control. #### [hashtag](https://docs.stacks.co/learn/es/clarity#composicion-en-lugar-de-herencia) Composición en lugar de herencia Clarity adopta la composición en lugar de la herencia. Esto significa que los contratos inteligentes Clarity no heredan unos de otros como se ve en lenguajes como Solidity. En su lugar, los desarrolladores definen traits que luego son implementados por diferentes contratos inteligentes. Esto permite que los contratos cumplan con distintas interfaces con mayor flexibilidad. No hay necesidad de preocuparse por árboles de clases complejos ni por contratos con comportamientos heredados implícitos. #### [hashtag](https://docs.stacks.co/learn/es/clarity#acceso-a-la-cadena-base-bitcoin) Acceso a la cadena base: Bitcoin Los contratos inteligentes Clarity pueden leer el estado de la cadena base de Bitcoin. Esto significa que puedes usar transacciones de Bitcoin como un disparador en tus contratos inteligentes. Clarity también incluye una serie de funciones integradas para verificar firmas secp256k1 y recuperar claves. [AnteriorCondiciones posterioreschevron-left](https://docs.stacks.co/learn/es/transactions/post-conditions) [SiguienteDecidabilitychevron-right](https://docs.stacks.co/learn/es/clarity/decidability) Última actualización hace 2 meses ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Características principales de sBTC | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close sBTC ofrece varias características principales que lo convierten en un puente de Bitcoin con mínima confianza entre Stacks y Bitcoin: 1 **Respaldo de Bitcoin 1:1** Cada token sBTC está respaldado por una cantidad equivalente de Bitcoin en la billetera de enlace (peg wallet). Esto asegura que sBTC mantenga un valor estable en relación con BTC. 2 **Gestión descentralizada** La peg wallet de sBTC es mantenida y gestionada por un conjunto de firmantes de sBTC. Este enfoque descentralizado mejora la seguridad y reduce los puntos únicos de fallo. 3 **Conversiones rápidas** sBTC facilita el movimiento rápido entre BTC y sBTC: * La conversión de BTC a sBTC puede completarse dentro de 3 bloques de Bitcoin * La conversión de sBTC a BTC puede completarse dentro de 6 bloques de Bitcoin 4 **Compatibilidad con SIP-010** sBTC se adhiere al estándar de token fungible SIP-010 en la blockchain de Stacks. Esto garantiza una amplia compatibilidad con las billeteras y aplicaciones de Stacks. 5 **Gobernanza comunitaria** El conjunto inicial de firmantes de sBTC se determina mediante una votación comunitaria, ponderada por las tenencias de STX. Este enfoque garantiza que la comunidad tenga voz en la gestión del sistema sBTC. 6 **Rotación de claves de firmantes** Los firmantes de sBTC tienen la capacidad de rotar sus claves privadas, mejorando la seguridad a largo plazo del sistema. 7 **Patrocinio de tarifas de transacción** Las transacciones de sBTC en Stacks pueden ser patrocinadas, permitiendo a los usuarios pagar las tarifas de transacción en sBTC en lugar de STX. [AnteriorsBTCchevron-left](https://docs.stacks.co/learn/es/sbtc) [SiguienteOperationschevron-right](https://docs.stacks.co/learn/es/sbtc/sbtc-operations) Última actualización hace 3 meses ¿Te fue útil? ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # NFT Marketplace | Cookbook | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close [hashtag](https://docs.stacks.co/cookbook/clarity/example-contracts/nft-marketplace#contract-summary) Contract Summary --------------------------------------------------------------------------------------------------------------------------- A tiny NFT marketplace contract that enables users to list, buy, and sell NFTs with flexible payment options. This contract demonstrates trait-based programming and comprehensive marketplace mechanics including expiry, whitelisting, and optional buyer targeting. **What this contract does:** * Allows NFT owners to list their tokens for sale with customizable terms * Supports both STX and SIP-010 fungible token payments * Implements listing expiry based on block height * Enables optional buyer restriction (private sales to specific principals) * Requires contract whitelisting for both NFT and payment assets * Escrows NFTs in the marketplace contract until sale or cancellation * Allows sellers to cancel active listings and reclaim their NFTs * Validates all listing parameters before accepting offers * Assigns unique IDs to each listing for tracking **What developers can learn:** * Using Clarity traits (`` and ``) for generic contract interactions * Implementing marketplace escrow patterns with NFT custody * Contract whitelisting pattern for security and quality control * Time-based expiry using block heights * Optional parameters with `(optional principal)` for flexible configurations * Comprehensive input validation and error handling * Using `contract-of` to verify trait implementations * Pattern matching with `match` for optional values * Private helper functions for validation and transfers * Nonce-based unique ID generation with data variables * As-contract context switching for escrowed asset transfers [PreviousExecutorDAO Frameworkchevron-left](https://docs.stacks.co/cookbook/clarity/example-contracts/executordao-framework) [NextOrdinals Swapchevron-right](https://docs.stacks.co/cookbook/clarity/example-contracts/ordinals-swap) Was this helpful? Was this helpful? sun-brightdesktopmoon nft-marketplace Copy ;; A tiny NFT marketplace that allows users to list NFT for sale. They can specify the following: ;; - The NFT token to sell. ;; - Listing expiry in block height. ;; - The payment asset, either STX or a SIP010 fungible token. ;; - The NFT price in said payment asset. ;; - An optional intended taker. If set, only that principal will be able to fulfil the listing. ;; ;; Source: https://github.com/clarity-lang/book/tree/main/projects/tiny-market (use-trait nft-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) (use-trait ft-trait 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sip-010-trait-ft-standard.sip-010-trait) (define-constant contract-owner tx-sender) ;; listing errors (define-constant ERR_EXPIRY_IN_PAST (err u1000)) (define-constant ERR_PRICE_ZERO (err u1001)) ;; cancelling and fulfiling errors (define-constant ERR_UNKNOWN_LISTING (err u2000)) (define-constant ERR_UNAUTHORISED (err u2001)) (define-constant ERR_LISTING_EXPIRED (err u2002)) (define-constant ERR_NFT_ASSET_MISMATCH (err u2003)) (define-constant ERR_PAYMENT_ASSET_MISMATCH (err u2004)) (define-constant ERR_MAKER_TAKER_EQUAL (err u2005)) (define-constant ERR_UNINTENDED_TAKER (err u2006)) (define-constant ERR_ASSET_CONTRACT_NOT_WHITELISTED (err u2007)) (define-constant ERR_PAYMENT_CONTRACT_NOT_WHITELISTED (err u2008)) ;; Define a map data structure for the asset listings (define-map listings uint { maker: principal, taker: (optional principal), token-id: uint, nft-asset-contract: principal, expiry: uint, price: uint, payment-asset-contract: (optional principal), } ) ;; Used for unique IDs for each listing (define-data-var listing-nonce uint u0) ;; This marketplace requires any contracts used for assets or payments to be whitelisted ;; by the contract owner of this (marketplace) contract. (define-map whitelisted-asset-contracts principal bool ) ;; Function that checks if the given contract has been whitelisted. (define-read-only (is-whitelisted (asset-contract principal)) (default-to false (map-get? whitelisted-asset-contracts asset-contract)) ) ;; Only the contract owner of this (marketplace) contract can whitelist an asset contract. (define-public (set-whitelisted (asset-contract principal) (whitelisted bool) ) (begin (asserts! (is-eq contract-owner tx-sender) ERR_UNAUTHORISED) (ok (map-set whitelisted-asset-contracts asset-contract whitelisted)) ) ) ;; Internal function to transfer an NFT asset from a sender to a given recipient. (define-private (transfer-nft (token-contract ) (token-id uint) (sender principal) (recipient principal) ) (contract-call? token-contract transfer token-id sender recipient) ) ;; Internal function to transfer fungible tokens from a sender to a given recipient. (define-private (transfer-ft (token-contract ) (amount uint) (sender principal) (recipient principal) ) (contract-call? token-contract transfer amount sender recipient none) ) ;; Public function to list an asset along with its contract (define-public (list-asset (nft-asset-contract ) (nft-asset { taker: (optional principal), token-id: uint, expiry: uint, price: uint, payment-asset-contract: (optional principal), }) ) (let ((listing-id (var-get listing-nonce))) ;; Verify that the contract of this asset is whitelisted (asserts! (is-whitelisted (contract-of nft-asset-contract)) ERR_ASSET_CONTRACT_NOT_WHITELISTED ) ;; Verify that the asset is not expired (asserts! (> (get expiry nft-asset) burn-block-height) ERR_EXPIRY_IN_PAST) ;; Verify that the asset price is greater than zero (asserts! (> (get price nft-asset) u0) ERR_PRICE_ZERO) ;; Verify that the contract of the payment is whitelisted (asserts! (match (get payment-asset-contract nft-asset) payment-asset (is-whitelisted payment-asset) true ) ERR_PAYMENT_CONTRACT_NOT_WHITELISTED ) ;; Transfer the NFT ownership to this contract's principal (try! (transfer-nft nft-asset-contract (get token-id nft-asset) tx-sender (as-contract tx-sender) )) ;; List the NFT in the listings map (map-set listings listing-id (merge { maker: tx-sender, nft-asset-contract: (contract-of nft-asset-contract), } nft-asset )) ;; Increment the nonce to use for the next unique listing ID (var-set listing-nonce (+ listing-id u1)) ;; Return the created listing ID (ok listing-id) ) ) ;; Public read-only function to retrieve a listing by its ID (define-read-only (get-listing (listing-id uint)) (map-get? listings listing-id) ) ;; Public function to cancel a listing using an asset contract. ;; This function can only be called by the NFT's creator, and must use the same asset contract that ;; the NFT uses. (define-public (cancel-listing (listing-id uint) (nft-asset-contract ) ) (let ( (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING)) (maker (get maker listing)) ) ;; Verify that the caller of the function is the creator of the NFT to be cancelled (asserts! (is-eq maker tx-sender) ERR_UNAUTHORISED) ;; Verify that the asset contract to use is the same one that the NFT uses (asserts! (is-eq (get nft-asset-contract listing) (contract-of nft-asset-contract)) ERR_NFT_ASSET_MISMATCH ) ;; Delete the listing (map-delete listings listing-id) ;; Transfer the NFT from this contract's principal back to the creator's principal (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender maker)) ) ) ;; Private function to validate that a purchase can be fulfilled (define-private (assert-can-fulfil (nft-asset-contract principal) (payment-asset-contract (optional principal)) (listing { maker: principal, taker: (optional principal), token-id: uint, nft-asset-contract: principal, expiry: uint, price: uint, payment-asset-contract: (optional principal), }) ) (begin ;; Verify that the buyer is not the same as the NFT creator (asserts! (not (is-eq (get maker listing) tx-sender)) ERR_MAKER_TAKER_EQUAL) ;; Verify the buyer has been set in the listing metadata as its `taker` (asserts! (match (get taker listing) intended-taker (is-eq intended-taker tx-sender) true ) ERR_UNINTENDED_TAKER ) ;; Verify the listing for purchase is not expired (asserts! (< burn-block-height (get expiry listing)) ERR_LISTING_EXPIRED) ;; Verify the asset contract used to purchase the NFT is the same as the one set on the NFT (asserts! (is-eq (get nft-asset-contract listing) nft-asset-contract) ERR_NFT_ASSET_MISMATCH ) ;; Verify the payment contract used to purchase the NFT is the same as the one set on the NFT (asserts! (is-eq (get payment-asset-contract listing) payment-asset-contract) ERR_PAYMENT_ASSET_MISMATCH ) (ok true) ) ) ;; Public function to purchase a listing using STX as payment (define-public (fulfil-listing-stx (listing-id uint) (nft-asset-contract ) ) (let ( ;; Verify the given listing ID exists (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING)) ;; Set the NFT's taker to the purchaser (caller of the_function) (taker tx-sender) ) ;; Validate that the purchase can be fulfilled (try! (assert-can-fulfil (contract-of nft-asset-contract) none listing)) ;; Transfer the NFT to the purchaser (caller of the function) (try! (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender taker))) ;; Transfer the STX payment from the purchaser to the creator of the NFT (try! (stx-transfer? (get price listing) taker (get maker listing))) ;; Remove the NFT from the marketplace listings (map-delete listings listing-id) ;; Return the listing ID that was just purchased (ok listing-id) ) ) ;; Public function to purchase a listing using another fungible token as payment (define-public (fulfil-listing-ft (listing-id uint) (nft-asset-contract ) (payment-asset-contract ) ) (let ( ;; Verify the given listing ID exists (listing (unwrap! (map-get? listings listing-id) ERR_UNKNOWN_LISTING)) ;; Set the NFT's taker to the purchaser (caller of the_function) (taker tx-sender) ) ;; Validate that the purchase can be fulfilled (try! (assert-can-fulfil (contract-of nft-asset-contract) (some (contract-of payment-asset-contract)) listing )) ;; Transfer the NFT to the purchaser (caller of the function) (try! (as-contract (transfer-nft nft-asset-contract (get token-id listing) tx-sender taker))) ;; Transfer the tokens as payment from the purchaser to the creator of the NFT (try! (transfer-ft payment-asset-contract (get price listing) taker (get maker listing) )) ;; Remove the NFT from the marketplace listings (map-delete listings listing-id) ;; Return the listing ID that was just purchased (ok listing-id) ) ) chevron-downShow all 257 lines sun-brightdesktopmoon --- # Operaciones | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#registrar-un-nombre) Registrar un nombre El registro de nombres se realiza llamando a la función correspondiente del contrato BNSv2. El llamador se convierte en el propietario del nombre. **Flujo de alto nivel:** 1. Comprobar disponibilidad 2. Enviar transacción de registro 3. Pagar la tarifa STX requerida 4. Esperar la confirmación 5. El nombre se asigna al principal que llama **Ruta 1 — Preorder + Registro (seguro, evita el front-running):** 1. Generar un hash salado del nombre totalmente calificado: hash160(name.namespace.salt) 2. Enviar name-preorder con el hash y STX para quemar 3. Esperar al menos 1 bloque 4. Enviar name-register con el nombre real, el namespace y la salt 5. El contrato verifica que los hashes coincidan, quema STX y acuña el NFT al llamador **Ruta 2 — Reclamo rápido (una sola tx, vulnerable al front-running):** 1. Enviar name-claim-fast con nombre, namespace y destinatario 2. STX quemados en un paso, NFT acuñado inmediatamente 3. Riesgo: el nombre es visible en el mempool antes de la confirmación, por lo que puede ser capturado Para namespaces gestionados: usar `mng-name-preorder` + `mng-name-register` (sin quema de STX, el gestor controla los precios). ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#actualizacion-de-registros) Actualización de registros Una vez que un nombre es propiedad de alguien, el propietario puede actualizar registros mediante llamadas al contrato. Las actualizaciones se realizan a través del `zonefile-resolver` contrato vía `update-zonefile(name, namespace, new-zonefile)`. El llamador debe ser o bien el propietario del nombre O el gestor del namespace (para namespaces gestionados). Mencionar el límite de 8KB. Ejemplos de actualizaciones de registros podrían incluir: * Establecer una dirección de Stacks * Actualizar metadatos de perfil * Agregar pares clave-valor personalizados Sólo el propietario actual puede modificar los registros. ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#transferir-un-nombre) Transferir un nombre Los nombres son activos digitales transferibles. `transfer(id, sender, recipient)` en el contrato BNS-V2. Para namespaces gestionados, usar `mng-transfer(id, sender, recipient)`, pero sólo si las transferencias por parte del gestor no han sido desactivadas vía `turn-off-manager-transfers` . El propietario puede: * Transferir la propiedad a otro principal * Usar un nombre dentro de otros contratos * Integrar nombres en mercados o sistemas de identidad Debido a que la propiedad es nativa en Clarity, las transferencias no requieren confianza. ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#resolver-un-nombre) Resolver un nombre La resolución implica consultar los contratos BNSv2 para el registro almacenado de un nombre. `resolve-name(name, namespace)` en `zonefile-resolver` Las funciones correspondientes del SDK de BNSv2: `resolveNameZonefile()`, `getNameInfo()`, `getPrimaryName()`. Las aplicaciones pueden: * Llamar al contrato directamente vía RPC * Usar ayudantes del SDK * Usar indexadores para mayor comodidad La resolución es determinista y no depende de servidores centralizados. ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#precios) **Precios** Los precios de los nombres se calculan en base a: * Longitud del nombre * Presencia de vocales * Presencia de caracteres no alfabéticos * Funciones de fijación de precios específicas del namespace * **Para namespaces gestionados, el precio será gestionado directamente por el contrato del gestor del namespace** ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#integracion-con-nft) **Integración con NFT** Cada nombre se acuña como un NFT, lo que permite: * Transferencias de propiedad sencillas * Integración con mercados de NFT y otras aplicaciones ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#renovaciones) Renovaciones Los nombres en namespaces no gestionados expiran después de bloques de vida. Los propietarios tienen un período de gracia de 5.000 bloques (~34 días) después del vencimiento para renovar vía `name-renewal(namespace, name)`. * La renovación quema STX según el precio actual del nombre. * Si no se renueva dentro del período de gracia, el nombre queda disponible para que cualquiera lo registre. * Los nombres de namespaces gestionados NO expiran (renewal-height = 0). ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#marketplace) Marketplace BNSv2 tiene un marketplace nativo: * `list-in-ustx(id, price, commission-trait)`, listar un nombre para la venta * `unlist-in-ustx(id)`, eliminar el listado * `buy-in-ustx(id, commission-trait)`, comprar un nombre listado La comisión se gestiona mediante el trait de comisión SIP-009. * Para namespaces gestionados, el contrato del gestor debe envolver estas funciones. ### [hashtag](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#establecer-un-nombre-primario) Establecer un nombre primario * `set-primary-name(id)` en BNS-V2 permite a un propietario designar uno de sus nombres como su identidad primaria. * Esto es lo que las billeteras y aplicaciones usan para mostrar. * Sólo un nombre primario por dirección. [AnteriorConceptos clavechevron-left](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/conceptos-clave) [SiguienteSIPschevron-right](https://docs.stacks.co/learn/es/network-fundamentals/sips) Última actualización hace 1 mes ¿Te fue útil? * [Registrar un nombre](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#registrar-un-nombre) * [Actualización de registros](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#actualizacion-de-registros) * [Transferir un nombre](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#transferir-un-nombre) * [Resolver un nombre](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#resolver-un-nombre) * [Precios](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#precios) * [Integración con NFT](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#integracion-con-nft) * [Renovaciones](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#renovaciones) * [Marketplace](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#marketplace) * [Establecer un nombre primario](https://docs.stacks.co/learn/es/network-fundamentals/bitcoin-name-system/operaciones#establecer-un-nombre-primario) ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon --- # Proof of Transfer (PoX) | Learn | Stacks Documentation [circle-info\ \ Chainhooks V2 is now GA. Hosted Chainhooks V1 will deprecate on March 9th\ \ arrow-up-right](https://www.hiro.so/blog/chainhooks-v2-is-now-generally-available) close ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FEUW1W0NPEuoCYBtienyL%252Fpox.png%3Falt%3Dmedia%26token%3D2edba99c-91f7-4df2-8ea1-aceb9f3bb712&width=768&dpr=3&quality=100&sign=de547e67&sv=2)![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FqhGYp66lKo0jjZ57rDpy%252Fpox-light.png%3Falt%3Dmedia%26token%3D0d44f0ac-4595-40b4-b554-a510af89fea4&width=768&dpr=3&quality=100&sign=f821e8d7&sv=2) En las secciones anteriores, analizamos la visión y la ética de Stacks y hablamos mucho sobre su conexión con Bitcoin y cómo permite ampliar la funcionalidad sin modificar Bitcoin en sí. En esta sección, repasaremos el mecanismo de producción de bloques que hace eso posible: Proof of Transfer. circle-info Esta sección será una visión conceptual de Proof of Transfer. Para más detalles sobre exactamente cómo ocurre la producción de bloques a un nivel técnico, consulta la sección sobre [Producción de Bloques](https://docs.stacks.co/learn/es/block-production) . ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#que-es-proof-of-transfer) ¿Qué es Proof of Transfer? La capa Stacks se basa en STX y en BTC para su novedoso mecanismo de consenso, llamado Proof of Transfer (PoX), que utiliza tanto las capas de Stacks como de Bitcoin. PoX es similar en espíritu al consenso Proof of Work (PoW) de Bitcoin: como los mineros PoW de Bitcoin gastan electricidad y son recompensados en BTC, los mineros PoX de Stacks gastan BTC (ya minados) y son recompensados en STX. Como PoW, PoX utiliza una elección de líder único: los mineros PoX pujan simplemente gastando BTC, y tienen una probabilidad aleatoria ponderada por la puja de convertirse en líder. La elección del líder ocurre en la cadena de Bitcoin y los nuevos bloques se escriben en la capa Stacks. De esta manera, PoX reutiliza el trabajo ya realizado por los mineros de Bitcoin, y no consume una cantidad significativa de electricidad adicional: solo el coste de ejecutar ordenadores/portátiles normales para que los nodos Stacks pujen usando BTC. Como PoW, PoX es permisivo: Cualquiera puede ser minero de Stacks, siempre que esté dispuesto a gastar BTC. Además, cualquier poseedor de STX puede bloquear sus STX (llamado “stacking”) para participar en el consenso PoX y ganar recompensas en Bitcoin por realizar trabajo útil para el sistema, es decir, por ser firmante del peg descentralizado con Bitcoin. En consonancia con la ética de Bitcoin, los Stackers son recompensados por sus contribuciones positivas al sistema y desincentivados por incentivos económicos para comportarse mal (pero a diferencia de los sistemas de Proof of Stake con colaterales, no son “slashed”). Finalmente, la naturaleza del consenso PoX es tal que la relación de precios entre BTC y STX se registra continuamente y está disponible on-chain, sirviendo como un oráculo de precio de Bitcoin on-chain. Esto es valioso para el peg descentralizado, eliminando la necesidad de un oráculo externo, como se describe en el documento complementario sobre el peg. El diagrama a continuación representa mediante un diagrama de flujo el mecanismo de consenso PoX entre sus participantes relevantes. ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FDdAEe8T2U2HNgOsnAaFb%252FStacks_graphic%2520-%252067.png%3Falt%3Dmedia%26token%3D2a4344b9-c8e8-4ab1-990d-2d2ab61d3932&width=768&dpr=3&quality=100&sign=182e7132&sv=2) Como se muestra en el diagrama de flujo, Proof of Transfer también proporciona dos dinámicas críticas que trabajan juntas para asegurar y operar la red. 1. **Económico** – BTC se transfiere de los mineros a los stackers, creando una estructura de incentivos bidireccional enraizada en el propio Bitcoin. Los mineros comprometen BTC para participar en la producción de bloques, compitiendo efectivamente por el derecho a producir el siguiente bloque de Stacks. A cambio, los mineros exitosos ganan STX recién acuñados y comisiones por transacción. Los stackers, por otro lado, bloquean sus STX para apoyar el consenso y reciben los BTC comprometidos por los mineros como recompensa. Este mecanismo vincula la economía de Stacks directamente a Bitcoin, alineando los incentivos entre los participantes y anclando la seguridad en un activo externo real en lugar de depender únicamente de la inflación o de mecánicas internas del token. 2. **Programático** – Más allá de los incentivos económicos, PoX proporciona la capa de coordinación técnica que determina cómo se producen, validan y finalizan los bloques. Los compromisos de BTC de los mineros en Bitcoin sirven como entradas para la selección del líder, que determina quién puede construir el siguiente bloque de Stacks. Una vez producidos, los bloques se vinculan criptográficamente y se anclan a Bitcoin, heredando sus garantías de asentamiento. De este modo, PoX no es solo un mecanismo de intercambio económico: es el motor de consenso que orquesta la construcción, el orden y la finalización de los bloques manteniendo una conexión verificable con Bitcoin L1. ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#quienes-son-los-participantes-en-proof-of-transfer) ¿Quiénes son los participantes en Proof of Transfer? ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fjt1GkSXIb4cL4d1e4SDo%252FStacks_graphic%2520-%252080.png%3Falt%3Dmedia%26token%3D6ba8fe68-ad75-4178-9ebc-51ee2b2f7b7b&width=768&dpr=3&quality=100&sign=58d7340a&sv=2) * * * ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#desglose-de-los-componentes-centrales-de-pox) Desglose de los Componentes Centrales de PoX chevron-rightElección de Líder (Mineros)[hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#eleccion-de-lider-mineros) **¿Quién obtiene el derecho a minar la siguiente tanda de bloques de Stacks?** **Participantes: Mineros** * Idea: Gastar BTC para ganar la oportunidad de producir bloques * Elección de líder único a través de _sorteo criptográfico_ * Incrustar _función aleatoria verificable_ (VRF) en el estado de las transacciones de Bitcoin * Ganador determinista pero impredecible en cada bloque de Bitcoin * Minería mediante commits de bloque: par (hash de bloque, semilla VRF) * Semilla VRF = hash(prueba VRF) chevron-rightConjunto de Recompensas (Stackers)[hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#conjunto-de-recompensas-stackers) **¿Pero adónde van los BTC gastados por los mineros?** **Participantes: Stackers que están haciendo stacking en solitario o en pool** * Idea: Los BTC gastados (por los mineros) se envían a los poseedores de STX * El pago de BTC esperado es una función de tu bloqueo sobre el bloqueo total * Los STX bloqueados nunca salen de tu cuenta y se desbloquearán automáticamente * Saca STX improductivos de circulación * Ciclo de Recompensas: 2100 bloques de Bitcoin * Fase de Recompensa: primeros 2000 bloques de Bitcoin * Fase de Preparación: últimos 100 bloques de Bitcoin * Bloque ancla: primer bloque de Stacks confirmado en la fase de preparación * Conjunto de Recompensas: snapshot de STX bloqueados en el bloque ancla ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FDgyyRS5GoHb0mngC9e8t%252Fimage.png%3Falt%3Dmedia%26token%3D14ee55c5-b165-4207-b1a4-5fde4c74cc57&width=768&dpr=3&quality=100&sign=b3212b26&sv=2) ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252Fvi7Wwp15343yA7F3zySH%252Fimage.png%3Falt%3Dmedia%26token%3D654594ac-4812-48fc-ab3b-524c5b4be519&width=768&dpr=3&quality=100&sign=ac1f3a9e&sv=2) chevron-rightFirmantes de Bloque (Signers)[hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#firmantes-de-bloque-signers) **¿Pueden los STX bloqueados asegurar también la red?** **Participantes: Stackers que asumen el rol de Firmante** * Idea: Usar el rendimiento PoX para incentivar una buena QoS de la cadena * Rendimiento PoX como salario para replicar y secuenciar bloques * Stacks selecciona la clave pública del Firmante cuando hacen stacking * Los firmantes firman los bloques del minero con una firma ponderada (por # de ranuras de recompensa) * Una vez que el 70%+ de las ranuras de recompensa firman, el bloque se añade * El conjunto de firmantes de bloque cambia una vez por ciclo de recompensas * Se asume que el 70%+ o más de firmantes están en línea y son honestos * Los Firmantes honestos votan para retener (quemar) los BTC subsecuentes de Stackers defectuosos ![](https://docs.stacks.co/~gitbook/image?url=https%3A%2F%2F3385590278-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FH74xqoobupBWwBsVMJhK%252Fuploads%252FVUFPxnqlCxwtVL1i37fx%252Fimage.png%3Falt%3Dmedia%26token%3Df31b7c0d-4be9-4b83-802c-d1f78be88da8&width=768&dpr=3&quality=100&sign=f5c4d038&sv=2) * * * ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#detalles-de-implementacion-tecnica) Detalles de Implementación Técnica La funcionalidad de Proof of Transfer está implementada en la red Stacks como un contrato inteligente Clarity. Proof of Transfer ha pasado por múltiples iteraciones a lo largo de los años. A continuación se enumeran las diferentes implementaciones del contrato inteligente de Proof of Transfer. Versión Fecha Contrato Mainnet SIP PoX 4 2024-04-22 [SP000000000000000000002Q6VF78.pox-4arrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-4) [https://github.com/stacksgov/sips/blob/main/sips/sip-021/sip-021-nakamoto.md](https://github.com/stacksgov/sips/blob/main/sips/sip-021/sip-021-nakamoto.md) PoX 3 2023-05-27 [SP000000000000000000002Q6VF78.pox-3arrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-3) [https://github.com/stacksgov/sips/blob/main/sips/sip-022/sip-022-emergency-pox-fix.md](https://github.com/stacksgov/sips/blob/main/sips/sip-022/sip-022-emergency-pox-fix.md) PoX 2 2023-03-20 [SP000000000000000000002Q6VF78.pox-2arrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox-2) [https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md](https://github.com/stacksgov/sips/blob/main/sips/sip-015/sip-015-network-upgrade.md) PoX 1 2021-01-15 [SP000000000000000000002Q6VF78.poxarrow-up-right](https://explorer.hiro.so/txid/SP000000000000000000002Q6VF78.pox) [https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md) Un recorrido por el contrato PoX 4 actual está disponible en el [Contratos de Ejemplo](https://docs.stacks.co/cookbook/clarity/example-contracts) sección. * * * ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#en-resumen-pox-en-pocas-palabras) En resumen: PoX en pocas palabras • PoX selecciona un minero de bloques líder aleatorizado una sola vez por cada bloque de BTC • PoX incentiva a los mineros a crear bloques STX y ganar coinbase de STX + comisiones por transacción • PoX incentiva a los poseedores de STX a bloquear STX para obtener rendimiento en BTC de los mineros • PoX desincentiva a los mineros de BTC L1 de interferir • PoX incentiva a los Stackers, como Firmantes, a mantener la red saludable * * * ### [hashtag](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#recursos-adicionales) Recursos Adicionales * \[[SIP-001arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-001/sip-001-burn-election.md)\ \] SIP-001 proporciona una lista completa de razones por las que se eligió Bitcoin para asegurar Stacks. * \[[SIP-007arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-007/sip-007-stacking-consensus.md)\ \] Detalles del diseño original para stacking y Proof of Transfer. * \[[SIP-021arrow-up-right](https://github.com/stacksgov/sips/blob/main/sips/sip-021/sip-021-nakamoto.md)\ \] Actualización Nakamoto: Bloques rápidos y fiables * \[[Stacks Developers YTarrow-up-right](https://youtu.be/YynwIJIXJWw?si=9DXsd9PzMN14xt-L)\ \] PoX: Bajo el Capó * \[[Stacks Developers YTarrow-up-right](https://youtu.be/4UJ3ZK8JsrI?si=m8VSVIuCwIyOe3pe)\ \] ¿Cómo prueban los desarrolladores la red Stacks? * \[[Hiro YTarrow-up-right](https://youtu.be/2Bmo1cK0C8k?si=uiYaXudIhjxkNaS6)\ \] Un desglose del contrato inteligente Proof of Transfer de Stacks [AnteriorLa conexión con Bitcoinchevron-left](https://docs.stacks.co/learn/es/stacks-101/bitcoin-connection) [SiguienteFundamentos de la redchevron-right](https://docs.stacks.co/learn/es/network-fundamentals) Última actualización hace 1 mes ¿Te fue útil? * [¿Qué es Proof of Transfer?](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#que-es-proof-of-transfer) * [¿Quiénes son los participantes en Proof of Transfer?](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#quienes-son-los-participantes-en-proof-of-transfer) * [Desglose de los Componentes Centrales de PoX](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#desglose-de-los-componentes-centrales-de-pox) * [Detalles de Implementación Técnica](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#detalles-de-implementacion-tecnica) * [En resumen: PoX en pocas palabras](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#en-resumen-pox-en-pocas-palabras) * [Recursos Adicionales](https://docs.stacks.co/learn/es/stacks-101/proof-of-transfer#recursos-adicionales) ¿Te fue útil? sun-brightdesktopmoon sun-brightdesktopmoon ---