}
- href="/reference/stacks.js"
- title="Stacks.js"
- description="SDK de JavaScript para construir aplicaciones en Stacks con transacciones, utilidades de red e integración de billetera."
+ icon={}
+ href="/resources/guides"
+ title="Guías"
+ description="Instrucciones paso a paso para construir en capas de Bitcoin."
/>
}
- href="/tools/clarinet/sdk-introduction"
- title="SDK de Clarinet JS"
- description="SDK de JavaScript para probar e interactuar con contratos inteligentes de Clarity en entornos simulados."
- />
-
- {/* }
- href="/reference/stacks-blockchain-api"
- title="Stacks Blockchain API Client"
- description="Type-safe JavaScript client library for interacting with the Stacks Blockchain API."
- /> */}
-
-
-
-
- }
- href="/resources/clarity"
- title="Referencia de Claridad"
- description="Guías completas y referencia de funciones para el lenguaje de contratos inteligentes Clarity."
+ icon={}
+ href="/resources/snippets"
+ title="Fragmentos"
+ description="Ejemplos de código reutilizables para tareas comunes en Stacks y Bitcoin."
/>
Libraries & SDKs
-
- }
- href="/reference/stacks.js"
- title="Stacks.js"
- description="JavaScript SDK for building applications on Stacks with transactions, network utilities, and wallet integration."
- />
- }
- href="/tools/clarinet/sdk-introduction"
- title="Clarinet JS SDK"
- description="JavaScript SDK for testing and interacting with Clarity smart contracts in simulated environments."
- />
- }
- href="/tools/clarinet/browser-sdk-reference"
- title="Clarinet JS Browser SDK"
- description="JavaScript SDK for interacting with the simnet in web browsers."
- />
- {/* }
- href="/reference/stacks-blockchain-api"
- title="Stacks Blockchain API Client"
- description="Type-safe JavaScript client library for interacting with the Stacks Blockchain API."
- /> */}
-
+
+ Looking for SDK documentation? Visit{' '}
+
+ docs.stacks.co/reference
+ {' '}
+ for the latest resources.
+
diff --git a/app/[locale]/(home)/reference/_pages/page.es.tsx b/app/[locale]/(home)/reference/_pages/page.es.tsx
index c7a13e3cb..feb4691c4 100644
--- a/app/[locale]/(home)/reference/_pages/page.es.tsx
+++ b/app/[locale]/(home)/reference/_pages/page.es.tsx
@@ -1,5 +1,4 @@
-import { Cards, IndexCard } from '@/components/card';
-import { Js } from '@/components/ui/icon';
+import Link from 'next/link';
export default function ReferencePage() {
return (
@@ -10,35 +9,16 @@ export default function ReferencePage() {
Bibliotecas y SDKs
-
- }
- href="/reference/stacks.js"
- title="Stacks.js"
- description="SDK de JavaScript para construir aplicaciones en Stacks con transacciones, utilidades de red e integración de billetera."
- />
-
- }
- href="/tools/clarinet/sdk-introduction"
- title="SDK de Clarinet JS"
- description="SDK de JavaScript para probar e interactuar con contratos inteligentes de Clarity en entornos simulados."
- />
-
- }
- href="/tools/clarinet/browser-sdk-reference"
- title="Clarinet JS SDK para navegador"
- description="SDK de JavaScript para interactuar con la simnet en navegadores web."
- />
-
- {/* }
- href="/reference/stacks-blockchain-api"
- title="Stacks Blockchain API Client"
- description="Type-safe JavaScript client library for interacting with the Stacks Blockchain API."
- /> */}
-
+
+ ¿Buscas la documentación de SDKs? Visita{' '}
+
+ docs.stacks.co/reference
+ {' '}
+ para acceder a los recursos más recientes.
+
diff --git a/app/[locale]/(home)/resources/_pages/page.en.tsx b/app/[locale]/(home)/resources/_pages/page.en.tsx
index b797eb3c4..b9795efc6 100644
--- a/app/[locale]/(home)/resources/_pages/page.en.tsx
+++ b/app/[locale]/(home)/resources/_pages/page.en.tsx
@@ -1,6 +1,5 @@
import { Code, Database, Terminal } from 'lucide-react';
import { Cards, IndexCard } from '@/components/card';
-import { Clarity } from '@/components/ui/icon';
export default function ResourcesPage() {
return (
@@ -12,12 +11,6 @@ export default function ResourcesPage() {
- }
- href="/resources/clarity"
- title="Clarity Reference"
- description="Comprehensive guides and function reference for the Clarity smart contract language."
- />
}
href="/resources/guides"
diff --git a/app/[locale]/(home)/resources/_pages/page.es.tsx b/app/[locale]/(home)/resources/_pages/page.es.tsx
index a234efd20..c830be6f6 100644
--- a/app/[locale]/(home)/resources/_pages/page.es.tsx
+++ b/app/[locale]/(home)/resources/_pages/page.es.tsx
@@ -1,6 +1,5 @@
import { Code, Database, Terminal } from 'lucide-react';
import { Cards, IndexCard } from '@/components/card';
-import { Clarity } from '@/components/ui/icon';
export default function ResourcesPage() {
return (
@@ -12,13 +11,6 @@ export default function ResourcesPage() {
- }
- href="/resources/clarity"
- title="Referencia de Clarity"
- description="Guías completas y referencia de funciones para el lenguaje de contratos inteligentes Clarity."
- />
-
}
href="/resources/guides"
diff --git a/app/[locale]/(home)/tools/_pages/page.en.tsx b/app/[locale]/(home)/tools/_pages/page.en.tsx
index 480ffccab..98bdf9542 100644
--- a/app/[locale]/(home)/tools/_pages/page.en.tsx
+++ b/app/[locale]/(home)/tools/_pages/page.en.tsx
@@ -1,6 +1,6 @@
import { Brackets, Database } from 'lucide-react';
import { Cards, IndexCard } from '@/components/card';
-import { Chainhook, Clarinet } from '@/components/ui/icon';
+import { Chainhook } from '@/components/ui/icon';
export default function ToolsPage() {
return (
@@ -12,12 +12,6 @@ export default function ToolsPage() {
- }
- description="A comprehensive development environment for building and testing Clarity smart contracts."
- />
- }
- description="Un entorno de desarrollo integral para construir y probar contratos inteligentes de Clarity."
- />
-
{
- if (index === 0 && (segment === 'Libraries & SDKs' || firstSegmentMenu)) {
+ if (index === 0 && firstSegmentMenu) {
return segment;
}
- if (segment.toLowerCase() === 'stacks.js') {
- return 'Stacks.js';
- }
-
if (index === 1 && displaySegments[0].toLowerCase() === 'apis') {
const apiMappings: { [key: string]: string } = {
'stacks-blockchain-api': 'Stacks Blockchain API',
diff --git a/components/search-dialog.tsx b/components/search-dialog.tsx
index 5efcd1a36..e9aef6745 100644
--- a/components/search-dialog.tsx
+++ b/components/search-dialog.tsx
@@ -10,7 +10,6 @@ import {
Layers,
Package,
Search,
- Terminal,
Webhook,
} from 'lucide-react';
import { useRouter } from 'next/navigation';
@@ -221,10 +220,10 @@ interface DocIndexEntry {
}
const predefinedDocQueries = [
- { id: 'q1', text: 'how to set up devnet using clarinet' },
- { id: 'q2', text: 'how to create a chainhook on the hiro platform' },
- { id: 'q3', text: 'how can i connect my wallet to a web app' },
- { id: 'q4', text: 'how can i query a list of the latest transactions' },
+ { id: 'q1', text: 'how to create a chainhook on the hiro platform' },
+ { id: 'q2', text: 'how can i query a list of the latest transactions' },
+ { id: 'q3', text: 'how do i bootstrap the bitcoin indexer' },
+ { id: 'q4', text: 'how do i manage api keys' },
];
const suggestions = [
@@ -246,31 +245,30 @@ function extractSnippet(text: string | undefined, maxLength = 80): string {
}
const navigateItems = [
- {
- id: 'clarinet',
- title: 'Clarinet',
- icon: Terminal,
- href: '/tools/clarinet',
- },
- {
- id: 'stacks.js',
- title: 'Stacks.js',
- icon: Code,
- href: '/reference/stacks.js',
- },
{
id: 'chainhook',
title: 'Chainhook',
icon: Webhook,
href: '/tools/chainhook',
},
+ {
+ id: 'bitcoin-indexer',
+ title: 'Bitcoin Indexer',
+ icon: Layers,
+ href: '/tools/bitcoin-indexer',
+ },
{
id: 'apis',
title: 'APIs',
- icon: Layers,
- href: '/tools/api',
+ icon: Package,
+ href: '/apis/stacks-blockchain-api',
+ },
+ {
+ id: 'guides',
+ title: 'Guides',
+ icon: Code,
+ href: '/resources/guides',
},
- { id: 'sdks', title: 'SDKs', icon: Package, href: '/reference' },
];
const aiItems = [
diff --git a/content/docs/en/reference/stacks.js/(connect)/broadcast-transactions.mdx b/content/docs/en/reference/stacks.js/(connect)/broadcast-transactions.mdx
deleted file mode 100644
index b8fbe4d4c..000000000
--- a/content/docs/en/reference/stacks.js/(connect)/broadcast-transactions.mdx
+++ /dev/null
@@ -1,164 +0,0 @@
----
-title: Broadcast transactions
-description: Prompt users to sign transactions and broadcast them to the Stacks blockchain.
----
-
-import { Badge } from '@/components/ui/badge';
-import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
-
-import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
-import { ChevronRight, Code, Terminal } from 'lucide-react';
-import { File, Folder, Files } from 'fumadocs-ui/components/files';
-
-The process of broadcasting transactions is fundamental for interacting with blockchains, whether you're transferring tokens, deploying contracts, or executing contract functions.
-
-In this guide, you will learn how to:
-
-1. [Install the necessary packages](#setup-and-installation)
-2. [Connect to a user's wallet](#connect-to-a-users-wallet)
-3. [Sign and broadcast transactions](#sign-and-broadcast-transactions)
-4. [Handle transaction results](#handle-transaction-results)
-
----
-
-## Setup and installation
-
-Install the required packages to start building and broadcasting transactions:
-
-```package-install
-@stacks/connect @stacks/transactions
-```
-
-## Connect to a user's wallet
-
-Before signing transactions, users need to connect their wallet to your application. Use the `connect` function to initiate a wallet connection:
-
-```ts
-import { connect, isConnected } from '@stacks/connect';
-
-async function connectWallet() {
- if (!isConnected()) {
- const response = await connect();
- console.log('Connected with addresses:', response);
- }
-}
-```
-
-## Sign and broadcast transactions
-
-There are three types of transactions you can create: STX transfers, contract deployments, and contract calls.
-
-
-
-
- STX transfer
-
-
- Contract deployment
-
-
- Contract execution
-
-
-
- To transfer STX tokens, use the `request` method with `stx_transferStx`:
-
- ```ts
- import { request } from '@stacks/connect';
-
- async function transferStx() {
- const response = await request('stx_transferStx', {
- recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV',
- amount: '100', // in micro-STX (1 STX = 1,000,000 micro-STX)
- memo: 'Reimbursement', // optional
- });
-
- console.log('Transaction ID:', response.txId);
- }
- ```
-
-
- To deploy a smart contract, use the `request` method with `stx_deployContract`:
-
- ```ts
- import { request } from '@stacks/connect';
-
- async function deployContract() {
- const codeBody = '(define-public (say-hi) (ok "hello world"))';
-
- const response = await request('stx_deployContract', {
- name: 'my-contract',
- code: codeBody,
- clarityVersion: 3, // optional, defaults to latest version
- });
-
- console.log('Transaction ID:', response.txId);
- }
- ```
-
- Contracts will deploy to the Stacks address of the connected wallet.
-
-
- To call a contract function, use the `request` method with 'stx_callContract'. Here's an example using a simple contract:
-
- ```clarity
- (define-public (say-hi)
- (print "hi")
- (ok u0)
- )
- ```
-
- Here's how to call this function:
-
- ```ts
- import { request } from '@stacks/connect';
- import { Cl } from '@stacks/transactions';
-
- async function callContract() {
- const response = await request('stx_callContract', {
- contractAddress: 'ST22T6ZS7HVWEMZHHFK77H4GTNDTWNPQAX8WZAKHJ',
- contractName: 'my-contract',
- functionName: 'say-hi',
- functionArgs: [], // array of Clarity values
- });
-
- console.log('Transaction ID:', response.txId);
- }
- ```
-
- For functions that take arguments, you can use the `Cl` namespace to construct Clarity values:
-
- ```ts
- const functionArgs = [
- Cl.uint(123),
- Cl.stringAscii("hello"),
- Cl.standardPrincipalCV("ST1X.."),
- ];
- ```
-
-
-
-## Handle transaction results
-
-When a transaction is signed and broadcast, the `request` method returns a response object containing information about the transaction:
-
-```ts
-interface TransactionResponse {
- txId: string; // The transaction ID
- txRaw: string; // The raw transaction hex
-}
-```
-
-You can use the transaction ID to create a link to view the transaction in the explorer:
-
-```ts
-async function handleTransaction() {
- const response = await request('stx_transferStx', {
- recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV',
- amount: '100',
- });
-
- const explorerUrl = `https://explorer.stacks.co/txid/${response.txId}`;
- console.log('View transaction in explorer:', explorerUrl);
-}
-```
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(connect)/connect-wallet.mdx b/content/docs/en/reference/stacks.js/(connect)/connect-wallet.mdx
deleted file mode 100644
index b7e67650d..000000000
--- a/content/docs/en/reference/stacks.js/(connect)/connect-wallet.mdx
+++ /dev/null
@@ -1,137 +0,0 @@
----
-title: Connect wallet
-description: Learn how to connect to Stacks wallets and authenticate users.
----
-
-Learn how to integrate wallet connections into your Stacks application. Connecting a wallet authenticates users and enables blockchain interactions like transfers and contract calls.
-
-## What you'll learn
-
-:::objectives
-- Install the `@stacks/connect` package
-- Connect to a wallet and authenticate users
-- Manage authentication state
-- Access user account data
-:::
-
-## Prerequisites
-
-:::prerequisites
-- Node.js installed on your machine
-- A web application setup (React, Vue, or vanilla JS)
-- Basic understanding of async/await
-:::
-
-## Quickstart
-
-
-
- ### Install package
-
- Add the Stacks Connect package to your project.
-
- ```package-install
- @stacks/connect
- ```
-
- This package provides all the functions needed for wallet connections and user authentication.
-
-
-
- ### Connect and authenticate
-
- The `connect` function initiates wallet connection and stores user data in local storage for session persistence.
-
- ```ts
- import { connect, isConnected } from '@stacks/connect';
-
- async function connectWallet() {
- // Check if already connected
- if (isConnected()) {
- console.log('Already authenticated');
- return;
- }
-
- // Connect to wallet
- const response = await connect();
- console.log('Connected:', response.addresses);
- }
- ```
-
- Manage the authentication state throughout your app.
-
- ```ts
- import { disconnect, isConnected } from '@stacks/connect';
-
- // Check authentication status
- const authenticated = isConnected();
-
- // Logout function
- function logout() {
- disconnect(); // Clears storage and wallet selection
- console.log('User disconnected');
- }
- ```
-
-
-
- ### Access user data
-
- Retrieve stored addresses and request detailed account information.
-
- ```ts
- import { getLocalStorage, request } from '@stacks/connect';
-
- // Get stored addresses from local storage
- const userData = getLocalStorage();
- if (userData?.addresses) {
- const stxAddress = userData.addresses.stx[0].address;
- const btcAddress = userData.addresses.btc[0].address;
- console.log('STX:', stxAddress);
- console.log('BTC:', btcAddress);
- }
- ```
-
- Get detailed account information including public keys.
-
- ```ts
- // Request full account details
- const accounts = await request('stx_getAccounts');
- const account = accounts.addresses[0];
-
- console.log('Address:', account.address);
- console.log('Public key:', account.publicKey);
- console.log('Gaia URL:', account.gaiaHubUrl);
- ```
-
-
-
- ### Make your first transaction
-
- Use the authenticated connection to send STX tokens.
-
- ```ts
- import { request } from '@stacks/connect';
-
- async function sendTransaction() {
- const response = await request('stx_transferStx', {
- amount: '1000000', // 1 STX in micro-STX
- recipient: 'SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN',
- memo: 'First transfer', // optional
- });
-
- console.log('Transaction ID:', response.txid);
- }
- ```
-
- The wallet will prompt the user to approve the transaction before broadcasting.
-
-
-
-
-## Next steps
-
-:::next-steps
-- [Sign messages](/reference/stacks.js/message-signing): Prove address ownership
-- [Broadcast transactions](/reference/stacks.js/broadcast-transactions): Learn about different transaction types
-:::
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(connect)/message-signing.mdx b/content/docs/en/reference/stacks.js/(connect)/message-signing.mdx
deleted file mode 100644
index 239831879..000000000
--- a/content/docs/en/reference/stacks.js/(connect)/message-signing.mdx
+++ /dev/null
@@ -1,200 +0,0 @@
----
-title: Sign messages
-description: Learn how to sign and verify messages to prove address ownership and authorize actions
----
-
-Learn how to implement message signing in your Stacks application. Message signing allows users to cryptographically prove they control an address without making an on-chain transaction, enabling authentication, authorization, and verifiable statements.
-
-:::objectives
-- Connect to a user's wallet and request message signatures
-- Sign both simple text messages and structured data
-- Verify signatures to ensure authenticity
-:::
-
-:::prerequisites
-- Node.js installed on your machine
-- A code editor like VS Code
-:::
-
-## Installation
-
-Install the required packages for message signing and verification.
-
-```package-install
-@stacks/connect @stacks/encryption
-```
-
-## Connect to wallet
-
-Before signing messages, establish a connection to the user's wallet. The connection persists across page reloads.
-
-```ts
-import { connect, isConnected } from '@stacks/connect';
-
-async function connectWallet() {
- if (!isConnected()) {
- const response = await connect();
- console.log('Connected addresses:', response.addresses);
- }
-}
-```
-
-Call this function when your app loads or when the user clicks a connect button.
-
-## Sign text messages
-
-Request a signature for a simple text message using the `request` method.
-
-```ts
-import { request } from '@stacks/connect';
-
-async function signMessage() {
- const message = 'Hello World';
-
- const response = await request('stx_signMessage', {
- message,
- });
-
- console.log('Signature:', response.signature);
- console.log('Public key:', response.publicKey);
-
- return response;
-}
-```
-
-The wallet will display the message to the user for approval before signing.
-
-## Sign structured data
-
-For more complex data, use structured message signing with Clarity values.
-
-```ts
-import { request } from '@stacks/connect';
-import { Cl } from '@stacks/transactions';
-
-async function signStructuredMessage() {
- const message = Cl.tuple({
- action: Cl.stringAscii('transfer'),
- amount: Cl.uint(1000),
- recipient: Cl.stringAscii('alice.btc')
- });
-
- const domain = Cl.tuple({
- name: Cl.stringAscii('My App'),
- version: Cl.stringAscii('1.0.0'),
- 'chain-id': Cl.uint(1) // 1 for mainnet
- });
-
- const response = await request('stx_signStructuredMessage', {
- message,
- domain
- });
-
- return response;
-}
-```
-
-Structured messages provide better type safety and are easier to parse on-chain.
-
-## Verify signatures
-
-Validate signatures to ensure they match the expected message and public key.
-
-```ts
-import { verifyMessageSignatureRsv } from '@stacks/encryption';
-
-async function verifySignature(
- message: string,
- signature: string,
- publicKey: string
-): Promise {
- const isValid = verifyMessageSignatureRsv({
- message,
- signature,
- publicKey
- });
-
- if (isValid) {
- console.log('✓ Signature verified successfully');
- } else {
- console.log('✗ Invalid signature');
- }
-
- return isValid;
-}
-```
-
-Always verify signatures before trusting the signed data.
-
-### Complete verification flow
-
-```ts
-async function signAndVerify() {
- // Request signature
- const message = 'Authorize login at ' + new Date().toISOString();
- const signResponse = await request('stx_signMessage', { message });
-
- // Verify immediately
- const isValid = await verifySignature(
- message,
- signResponse.signature,
- signResponse.publicKey
- );
-
- if (isValid) {
- // Proceed with authenticated action
- console.log('Authentication successful');
- }
-}
-```
-
-## Try it out
-
-Create a simple authentication system using message signatures.
-
-```ts
-// Generate a unique challenge
-function generateChallenge(): string {
- const nonce = Math.random().toString(36).substring(7);
- const timestamp = Date.now();
- return `Sign this message to authenticate:\nNonce: ${nonce}\nTime: ${timestamp}`;
-}
-
-// Complete auth flow
-async function authenticate() {
- const challenge = generateChallenge();
-
- try {
- const response = await request('stx_signMessage', {
- message: challenge
- });
-
- const isValid = verifyMessageSignatureRsv({
- message: challenge,
- signature: response.signature,
- publicKey: response.publicKey
- });
-
- if (isValid) {
- // Store auth token or session
- localStorage.setItem('auth', JSON.stringify({
- publicKey: response.publicKey,
- timestamp: Date.now()
- }));
-
- return { success: true };
- }
- } catch (error) {
- console.error('Authentication failed:', error);
- }
-
- return { success: false };
-}
-```
-
-## Next steps
-
-:::next-steps
-- [Broadcast transactions](/reference/stacks.js/broadcast-transactions): Learn how to sign and broadcast transactions
-- [Connect API reference](/reference/stacks.js/packages/connect): Explore all available methods
-:::
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(connect)/meta.json b/content/docs/en/reference/stacks.js/(connect)/meta.json
deleted file mode 100644
index 37e59f396..000000000
--- a/content/docs/en/reference/stacks.js/(connect)/meta.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "title": "Stacks Connect",
- "defaultOpen": false,
- "pages": [
- "connect-wallet",
- "broadcast-transactions",
- "message-signing",
- "migration-guide",
- "wallet-support"
- ]
-}
diff --git a/content/docs/en/reference/stacks.js/(connect)/migration-guide.mdx b/content/docs/en/reference/stacks.js/(connect)/migration-guide.mdx
deleted file mode 100644
index ac3e5bfbb..000000000
--- a/content/docs/en/reference/stacks.js/(connect)/migration-guide.mdx
+++ /dev/null
@@ -1,100 +0,0 @@
----
-title: Migration Guide
-description: How to migrate from v7.x.x to v8.x.x of @stacks/connect
----
-
-import { Steps, Step } from 'fumadocs-ui/components/steps'
-
-
-For a while now, the Stacks community has been working on a new standard for wallet-to-dapp communication.
-Stacks Connect and related projects now use standards like [WBIPs](https://wbips.netlify.app/) and [SIP-030](https://github.com/janniks/sips/blob/main/sips/sip-030/sip-030-wallet-interface.md) to allow wallets to communicate with dapps in a more simplified and flexible way.
-
-:::callout
-### Migration Status
-**Feel free to continue using Stacks Connect `7.x.x` while things stabilize.**
-The `7.x.x` version may still be more well supported by some wallets.
-
-For the legacy version of `@stacks/connect` using JWT tokens, you can use:
-
-```sh
-npm install @stacks/connect@7.10.1
-```
-:::
-
-## Deprecations
-
-The following classes, methods, and types are deprecated in favor of the new `request` RPC methods:
-
-- `show...` and `open...` methods
-- `authenticate` method
-- `UserSession` class and related functionality
-- `AppConfig` class
-- `SessionOptions` interface
-- `SessionData` interface
-- `UserData` interface
-- `SessionDataStore` class
-- `InstanceDataStore` class
-- `LocalStorageStore` class
-
-:::callout
-### Backwards Compatibility
-To make migrating easier, the familiar `UserSession` & `AppConfig` class still exists and is semi-backwards compatible for the `8.x.x` release.
-It will "cache" the user's address in local storage and allow access to it via the `loadUserData` method (as previously done).
-:::
-
-## Migration Steps
-
-To update from `<=7.x.x` to latest/`8.x.x`, follow these steps:
-
-
-
- ```sh
- npm install @stacks/connect@latest
- ```
-
-
-
- Switch from `showXyz`, `openXyz`, `doXyz` methods to the `request` method:
-
- - `request` follows the pattern `request(method: string, params: object)`, see [Usage](#usage) for more details
- - `request` is an async function, so replace the `onFinish` and `onCancel` callbacks with `.then().catch()` or `try & await`
-
- Examples:
- - `showConnect()`, `authenticate()` → `connect()`
- - `useConnect().doContractCall({})` → `request("stx_callContract", {})`
- - `openContractDeploy()` → `request("stx_deployContract", {})`
-
-
-
- Switch from `showConnect` or `authenticate` to `connect()` methods:
-
- - `connect()` is an alias for `request({forceWalletSelect: true}, 'getAddresses')`
- - `connect()` by default caches the user's address in local storage
-
-
-
- - Switch from `UserSession.isSignedIn()` to `isConnected()`
- - Switch from `UserSession.signUserOut()` to `disconnect()`
-
-
-
- - Remove code referencing deprecated methods (`AppConfig`, `UserSession`, etc.)
- - Remove the `@stacks/connect-react` package
- - You may need to manually reload a component to see local storage updates
- - No custom hooks are needed to use Stacks Connect anymore
- - We are working on a new `@stacks/react` package that will make usage even easier in the future (e.g., tracking transaction status, reloading components when a connection is established, updating the page when the network changes, and more)
-
-
-
-## Address Access
-
-Previously, the `UserSession` class was used to access the user's addresses and data, which abstracted away the underlying implementation details.
-Now, the `request` method is used to directly interact with the wallet, giving developers more explicit control and clarity over what's happening under the hood.
-This manual approach makes the wallet interaction more transparent and customizable.
-Developers can manually manage the currently connected user's address in e.g. local storage, jotai, etc. or use the `connect()`/`request()` method to cache the address in local storage.
-
-:::callout
-type: warn
-### Security Note
-For security reasons, the `8.x.x` release only returns the current network's address (where previously both mainnet and testnet addresses were returned).
-:::
diff --git a/content/docs/en/reference/stacks.js/(connect)/wallet-support.mdx b/content/docs/en/reference/stacks.js/(connect)/wallet-support.mdx
deleted file mode 100644
index 30214f2b8..000000000
--- a/content/docs/en/reference/stacks.js/(connect)/wallet-support.mdx
+++ /dev/null
@@ -1,57 +0,0 @@
----
-title: Wallet Support
-description: Compatibility information for different wallet providers
----
-
-This page provides detailed information about which methods and events are supported by different wallet providers in the Stacks ecosystem.
-
-## Method Compatibility
-
-- 🔴 No support (yet)
-- 🟡 Partial support
-- 🟢 Supported
-
-| Method | Leather | Xverse-like |
-|-----------------------------|----------------------------------------------|---------------------------------------------------------------|
-| `getAddresses` | 🟡 No support for experimental purposes | 🟡 Use `wallet_connect` instead |
-| `sendTransfer` | 🟡 Expects `amount` as string | 🟡 Expects `amount` as number |
-| `signPsbt` | 🟡 Uses signing index array only | 🟡 Uses `signInputs` record instead of array |
-| `stx_getAddresses` | 🟢 | 🔴 |
-| `stx_getAccounts` | 🔴 | 🟢 |
-| `stx_getNetworks` | 🔴 | 🔴 |
-| `stx_transferStx` | 🟢 | 🟢 |
-| `stx_transferSip10Ft` | 🟢 | 🔴 |
-| `stx_transferSip9Nft` | 🟢 | 🔴 |
-| `stx_callContract` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only, no support for `postConditions` |
-| `stx_deployContract` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only, no support for `postConditions` |
-| `stx_signTransaction` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only |
-| `stx_signMessage` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only |
-| `stx_signStructuredMessage` | 🟡 Hex-encoded Clarity values only | 🟡 Hex-encoded Clarity values only |
-| `stx_updateProfile` | 🔴 | 🔴 |
-
-## Event Compatibility
-
-| Event | Leather | Xverse |
-|---------------------|---------|--------|
-| `stx_accountChange` | 🔴 | 🔴 |
-| `stx_networkChange` | 🔴 | 🔴 |
-
-## Compatibility Layer
-
-The `request` method in `@stacks/connect` adds a layer of auto-compatibility for different wallet providers. This helps unify the interface where wallet providers may implement methods and results differently.
-
-- 🟢 No overrides needed for any wallet
-- 🔵 Has compatibility overrides that maintain functionality
-- 🟡 Has breaking overrides that may lose some information
-
-| Method | Status | Notes |
-| --------------------------- | ------ | ---------------------------------------------------------------------------------------------------- |
-| `getAddresses` | 🔵 | Maps to `wallet_connect` for Xverse-like wallets |
-| `sendTransfer` | 🔵 | Converts `amount` to number for Xverse, string for Leather |
-| `signPsbt` | 🟡 | Transforms PSBT format for Leather (base64 to hex) with lossy restructure of `signInputs` |
-| `stx_getAddresses` | 🔵 | Maps to `wallet_connect` for Xverse-like wallets |
-| `stx_callContract` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility |
-| `stx_deployContract` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility |
-| `stx_signTransaction` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility |
-| `stx_signMessage` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility |
-| `stx_signStructuredMessage` | 🔵 | Transforms Clarity values to hex-encoded format for compatibility |
diff --git a/content/docs/en/reference/stacks.js/(integrations)/meta.json b/content/docs/en/reference/stacks.js/(integrations)/meta.json
deleted file mode 100644
index 4d1f98163..000000000
--- a/content/docs/en/reference/stacks.js/(integrations)/meta.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "title": "Integrations",
- "pages": ["pyth-oracle-integration", "react-native-integration"]
-}
diff --git a/content/docs/en/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx b/content/docs/en/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx
deleted file mode 100644
index 1c591dba6..000000000
--- a/content/docs/en/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx
+++ /dev/null
@@ -1,202 +0,0 @@
----
-title: Pyth oracle integration
-sidebarTitle: Pyth oracle integration
-description: In this guide, you'll learn how to integrate Pyth Network price feeds into your frontend application using Stacks.js.
-isNew: true
----
-
-import { File, Folder, Files } from 'fumadocs-ui/components/files';
-import { Steps, Step } from '@/components/steps';
-import { ArrowRight, Check } from 'lucide-react';
-
-## What you'll learn
-
-:::objectives
-- Install and configure the Pyth SDK
-- Fetch VAA messages from Hermes API
-- Build transactions with oracle data
-- Handle post-conditions for oracle fees
-:::
-
-## Prerequisites
-
-:::prerequisites
-- A React or Node.js application with Stacks.js installed
-- Understanding of [Pyth oracle contracts](/resources/clarity/external-data)
-:::
-
-## Quickstart
-
-
-
- ### Install dependencies
-
- Install the Pyth SDK alongside your existing Stacks.js packages:
-
- ```package-install
- @pythnetwork/price-service-client buffer
- ```
-
- The buffer package is needed for data format conversion in browser environments.
-
-
-
- ### Set up the Pyth client
-
- Create a service to handle Pyth price feed interactions:
-
- ```typescript services/pyth.ts
- import { PriceServiceConnection } from '@pythnetwork/price-service-client';
- import { Buffer } from 'buffer';
-
- // Price feed IDs
- export const PRICE_FEEDS = {
- BTC_USD: '0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
- STX_USD: '0xec7a775f46379b5e943c3526b1c8d54cd49749176b0b98e02dde68d1bd335c17',
- ETH_USD: '0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace',
- USDC_USD: '0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a'
- };
-
- // Initialize Pyth client
- const pythClient = new PriceServiceConnection(
- 'https://hermes.pyth.network',
- {
- priceFeedRequestConfig: {
- binary: true // Request binary format for on-chain use
- }
- }
- );
-
- export async function fetchPriceUpdateVAA(priceFeedId: string): Promise {
- try {
- // Fetch the latest VAA for the price feed
- const vaas = await pythClient.getLatestVaas([priceFeedId]);
-
- if (!vaas || vaas.length === 0) {
- throw new Error('No VAA data received');
- }
-
- // Convert base64 to hex for Clarity
- const messageBuffer = Buffer.from(vaas[0], 'base64');
- const hexString = messageBuffer.toString('hex');
-
- return `0x${hexString}`;
- } catch (error) {
- console.error('Failed to fetch price VAA:', error);
- throw error;
- }
- }
- ```
-
-
-
- ### Build oracle-enabled transactions
-
- Create a transaction that includes fresh price data:
-
- ```typescript components/PythTransaction.tsx
- import { request } from '@stacks/connect';
- import {
- Cl,
- PostConditionMode
- } from '@stacks/transactions';
- import { fetchPriceUpdateVAA, PRICE_FEEDS } from '../services/pyth';
- import { useState } from 'react';
-
- export function MintWithOraclePrice() {
- const [loading, setLoading] = useState(false);
-
- const handleMint = async () => {
- setLoading(true);
- try {
- // Fetch fresh price data
- const priceVAA = await fetchPriceUpdateVAA(PRICE_FEEDS.BTC_USD);
-
- // Convert hex string to buffer Clarity value
- const vaaBuffer = Cl.bufferFromHex(priceVAA.slice(2));
-
- // Call contract with price data using request
- const response = await request('stx_callContract', {
- contract: 'SP1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R.benjamin-club',
- functionName: 'mint-for-hundred-dollars',
- functionArgs: [vaaBuffer],
- postConditionMode: 'deny',
- network: 'mainnet'
- });
-
- console.log('Transaction submitted:', response.txid);
- alert(`NFT minted! Transaction ID: ${response.txid}`);
- } catch (error) {
- console.error('Minting failed:', error);
- alert('Failed to mint NFT');
- } finally {
- setLoading(false);
- }
- };
-
- return (
-
- );
- }
- ```
-
-
-
- ### Add post-conditions for oracle fees
-
- Pyth oracle updates require a small fee. Include post-conditions when calling contracts:
-
- ```typescript components/MintWithPostConditions.tsx
- import { request } from '@stacks/connect';
- import { Cl, Pc } from '@stacks/transactions';
- import { fetchPriceUpdateVAA, PRICE_FEEDS } from '../services/pyth';
-
- export function MintWithPostConditions() {
- const handleMint = async () => {
- const userAddress = 'SP1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R';
-
- // Create post-conditions
- const postConditions = [
- // Oracle fee (1 uSTX)
- Pc.principal(userAddress).willSendLte(1).ustx(),
- // sBTC transfer for $100 worth (example: 100,000 sats)
- Pc.principal(userAddress)
- .willSendEq(100000)
- .ft('SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sbtc-token', 'sbtc')
- ];
-
- try {
- const priceVAA = await fetchPriceUpdateVAA(PRICE_FEEDS.BTC_USD);
-
- const response = await request('stx_callContract', {
- contract: `${userAddress}.benjamin-club`,
- functionName: 'mint-for-hundred-dollars',
- functionArgs: [Cl.bufferFromHex(priceVAA.slice(2))],
- postConditions,
- postConditionMode: 'deny',
- network: 'mainnet'
- });
-
- console.log('Transaction successful:', response.txid);
- } catch (error) {
- console.error('Transaction failed:', error);
- }
- };
-
- return ;
- }
- ```
-
-
-
-## Next steps
-
-:::next-steps
-- [Clarity contracts](/resources/clarity/external-data): Learn how to integrate Pyth oracle with Clarity contracts.
-- [Testing with Clarinet](/tools/clarinet/pyth-oracle-integration): Learn how to test Pyth oracle integration with Clarinet.
-:::
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(integrations)/react-native-integration.mdx b/content/docs/en/reference/stacks.js/(integrations)/react-native-integration.mdx
deleted file mode 100644
index 59700fae5..000000000
--- a/content/docs/en/reference/stacks.js/(integrations)/react-native-integration.mdx
+++ /dev/null
@@ -1,287 +0,0 @@
----
-title: Using Stacks.js with React Native
-sidebarTitle: React Native integration
-description: Learn how to integrate Stacks blockchain functionality into React Native mobile applications
----
-
-Stacks.js can be integrated into React Native applications to bring blockchain functionality to mobile devices. This tutorial walks you through setting up a React Native project with Expo and configuring it to work with Stacks.js libraries.
-
-:::objectives
-- Set up an Expo project configured for Stacks.js
-- Install and configure necessary polyfills for React Native
-- Generate wallets and sign transactions in a mobile app
-- Handle React Native's JavaScript environment limitations
-- Build a working Stacks mobile application
-:::
-
-:::prerequisites
-- Node.js and npm installed on your development machine
-- Basic knowledge of React Native and Expo
-- Familiarity with Stacks.js concepts
-- iOS or Android device/simulator for testing
-:::
-
-## Set up the Expo project
-
-Start by creating a new Expo project. The latest version of Expo provides the best compatibility with Stacks.js polyfills.
-
-```terminal
-$ npx create-expo-app@latest my-stacks-app
-$ cd my-stacks-app
-```
-
-The boilerplate project includes everything needed to start building. Test the initial setup by running the development server.
-
-```terminal
-$ npm start
-```
-
-Connect your mobile device using the Expo Go app and scan the QR code to verify the base project works correctly.
-
-## Install necessary dependencies
-
-React Native's JavaScript environment lacks certain Node.js and browser APIs that Stacks.js requires. Install the core Stacks libraries along with necessary polyfills.
-
-```terminal
-$ npm install @stacks/transactions @stacks/wallet-sdk
-```
-
-Install the polyfill dependencies as dev dependencies to handle missing APIs.
-
-```terminal
-$ npm install --save-dev buffer process react-native-get-random-values \
- text-encoding readable-stream crypto-browserify @peculiar/webcrypto
-```
-
-These polyfills provide:
-- `buffer` and `process` - Node.js globals
-- `react-native-get-random-values` - Crypto random values
-- `text-encoding` - TextEncoder/TextDecoder APIs
-- `crypto-browserify` and `@peculiar/webcrypto` - Cryptographic functions
-
-## Configure Metro bundler
-
-Metro bundler needs configuration to properly resolve Node.js modules. Create a custom Metro configuration file.
-
-```terminal
-$ npx expo customize metro.config.js
-```
-
-Update the configuration to map Node.js modules to their React Native-compatible versions.
-
-```js metro.config.js
-const { getDefaultConfig } = require("expo/metro-config");
-
-const config = getDefaultConfig(__dirname);
-
-config.resolver.extraNodeModules = {
- stream: require.resolve("readable-stream"),
- crypto: require.resolve("crypto-browserify"),
-};
-
-module.exports = config;
-```
-
-This configuration ensures that when Stacks.js requests Node.js modules, Metro provides the appropriate polyfills.
-
-## Set up global polyfills
-
-Create a polyfill system to make browser and Node.js APIs available in React Native. This requires modifying the app's entry point.
-
-### Create the polyfill file
-
-Create a new file to initialize all required global objects.
-
-```js polyfill.js
-import { Buffer } from "buffer/";
-import process from "process";
-import "react-native-get-random-values";
-import { TextDecoder, TextEncoder } from "text-encoding";
-
-global.process = process;
-global.Buffer = Buffer;
-global.TextEncoder = TextEncoder;
-global.TextDecoder = TextDecoder;
-```
-
-### Create custom entry point
-
-Create a new entry point that loads polyfills before the app starts.
-
-```js index.js
-import "./polyfill";
-import { Crypto } from "@peculiar/webcrypto";
-
-Object.assign(global.crypto, new Crypto());
-
-import "expo-router/entry";
-```
-
-### Update package.json
-
-Point the app to use the new entry point.
-
-```json package.json
-{
- "main": "index.js",
- // ... other configuration
-}
-```
-
-:::callout
-type: warn
-### Runtime initialization errors
-Polyfills must be loaded in separate files as shown. Loading them in the same file can cause runtime initialization errors.
-:::
-
-## Implement Stacks functionality
-
-With the environment configured, you can now use Stacks.js in your React Native components. Update the main screen to demonstrate wallet generation and transaction signing.
-
-### Import Stacks.js modules
-
-Edit the main screen component to import necessary Stacks.js functions.
-
-```tsx app/(tabs)/index.tsx
-import {
- TransactionVersion,
- getAddressFromPrivateKey,
- makeSTXTokenTransfer,
-} from "@stacks/transactions";
-import { Wallet, generateSecretKey, generateWallet } from "@stacks/wallet-sdk";
-import { useState } from "react";
-import { Button } from "react-native";
-```
-
-### Set up component state
-
-Create state variables to manage wallet data and user feedback.
-
-```tsx app/(tabs)/index.tsx
-export default function HomeScreen() {
- const [mnemonic, setMnemonic] = useState("Press button to generate");
- const [wallet, setWallet] = useState(null);
- const [log, setLog] = useState("");
-
- // Component implementation continues...
-}
-```
-
-### Generate wallet and sign transaction
-
-Implement the core functionality to create a wallet and sign a transaction.
-
-```tsx app/(tabs)/index.tsx
-const generate = async () => {
- try {
- // Generate a new seed phrase
- const mnemonic = generateSecretKey();
- setMnemonic(mnemonic);
-
- // Create wallet from seed phrase
- const wallet = await generateWallet({
- secretKey: mnemonic,
- password: "",
- });
- setWallet(wallet);
-
- // Create and sign a transaction
- const txOptions = {
- amount: 1000,
- anchorMode: "any" as const,
- recipient: "SP3W993D3BRDYB284CY3SBFDEGTC5XEDJPDEA21CN",
- senderKey: wallet.accounts[0].stxPrivateKey,
- fee: 300,
- network: "testnet" as const,
- nonce: 0,
- };
-
- const transaction = await makeSTXTokenTransfer(txOptions);
- setLog("Transaction signed successfully ✓");
- } catch (error) {
- setLog(`Error: ${error.message}`);
- }
-};
-```
-
-### Build the user interface
-
-Create a simple UI to display wallet information and trigger wallet generation.
-
-```tsx app/(tabs)/index.tsx
-return (
-
- Stacks Wallet Demo
-
-
- Seed Phrase
- {mnemonic}
-
-
-
- {wallet && (
-
- Wallet Address
-
- {getAddressFromPrivateKey(
- wallet.accounts[0].stxPrivateKey,
- TransactionVersion.Testnet
- )}
-
-
- )}
-
- {log && (
-
- Status
- {log}
-
- )}
-
-);
-```
-
-## Test your implementation
-
-Run your app to verify everything works correctly.
-
-```terminal
-$ npm start
-```
-
-When you press "Generate New Wallet":
-1. A new seed phrase appears
-2. The wallet address displays below
-3. A transaction is signed (not broadcast)
-4. Success message confirms signing
-
-:::callout
-type: tip
-### Secure storage
-For production apps, never display seed phrases directly. Implement secure storage using libraries like `react-native-keychain` or `expo-secure-store`.
-:::
-
-## Try it out
-
-Extend the basic implementation with additional features.
-
-```tsx
-// Challenge: Add a function to check STX balance
-const checkBalance = async (address: string) => {
- // Implement balance checking
- // Hint: You'll need to use @stacks/blockchain-api-client
-};
-
-// Challenge: Implement transaction broadcasting
-const broadcastTransaction = async (transaction: StacksTransaction) => {
- // Implement broadcasting logic
- // Remember to handle network selection
-};
-```
-
-## Next steps
-
-:::next-steps
-- [Transactions package](/reference/stacks.js/packages/transactions): Learn about the transactions package.
-- [Network package](/reference/stacks.js/packages/network): Learn about the network package utils.
-:::
diff --git a/content/docs/en/reference/stacks.js/(local-accounts)/build-transactions.mdx b/content/docs/en/reference/stacks.js/(local-accounts)/build-transactions.mdx
deleted file mode 100644
index 509ca7eec..000000000
--- a/content/docs/en/reference/stacks.js/(local-accounts)/build-transactions.mdx
+++ /dev/null
@@ -1,260 +0,0 @@
----
-title: Building transactions
-sidebarTitle: Build transactions
-description: Learn how to build transactions programmatically for complete control over blockchain interactions.
----
-
-:::objectives
-- Build signed transactions for immediate broadcast
-- Create unsigned transactions for multi-signature workflows
-- Implement sponsored transactions to pay fees for users
-:::
-
-## Transaction types
-
-Stacks supports five primary transaction types, each serving a specific purpose.
-
-```typescript
-// STX Transfer - Send native tokens
-const stxTransfer = await makeSTXTokenTransfer(options);
-
-// Contract Deployment - Deploy Clarity contracts
-const deployment = await makeContractDeploy(options);
-
-// Contract Call - Execute contract functions
-const contractCall = await makeContractCall(options);
-
-// Each transaction type accepts similar base options:
-interface TransactionOptions {
- senderKey: string; // Private key for signing
- network: string; // 'mainnet' or 'testnet'
- fee?: bigint; // Manual fee in microSTX
- nonce?: bigint; // Manual nonce
- anchorMode?: AnchorMode; // Block anchoring strategy
-}
-```
-
-## Building signed transactions
-
-Signed transactions are ready to broadcast immediately. The private key signs during creation.
-
-### STX token transfer
-
-```typescript
-import { makeSTXTokenTransfer, broadcastTransaction } from '@stacks/transactions';
-
-const transaction = await makeSTXTokenTransfer({
- recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- amount: 1000000n, // 1 STX = 1,000,000 microSTX
- senderKey: 'your-private-key-hex',
- network: 'testnet',
- memo: 'Payment for services', // Optional memo (max 34 bytes)
-});
-
-const result = await broadcastTransaction({ transaction });
-console.log('Transaction ID:', result.txid);
-```
-
-### Smart contract deployment
-
-```typescript
-import { makeContractDeploy, ClarityVersion } from '@stacks/transactions';
-
-const contractCode = `
-(define-public (say-hello)
- (ok "Hello, Stacks!"))
-`;
-
-const transaction = await makeContractDeploy({
- contractName: 'hello-world',
- codeBody: contractCode,
- senderKey: 'your-private-key-hex',
- network: 'testnet',
- clarityVersion: ClarityVersion.Clarity3,
-});
-
-const result = await broadcastTransaction({ transaction });
-```
-
-### Contract function calls
-
-```typescript
-import { makeContractCall, Cl } from '@stacks/transactions';
-
-const transaction = await makeContractCall({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'counter',
- functionName: 'increment',
- functionArgs: [Cl.uint(1)],
- senderKey: 'your-private-key-hex',
- network: 'testnet',
-});
-```
-
-## Unsigned transactions
-
-Create unsigned transactions for multi-signature workflows or offline signing.
-
-```typescript
-import { makeUnsignedSTXTokenTransfer, TransactionSigner } from '@stacks/transactions';
-import { publicKeyFromPrivate } from '@stacks/encryption';
-
-// Create unsigned transaction
-const publicKey = publicKeyFromPrivate('your-private-key');
-
-const unsignedTx = await makeUnsignedSTXTokenTransfer({
- recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- amount: 1000000n,
- publicKey,
- network: 'testnet',
-});
-
-// Sign separately
-const signer = new TransactionSigner(unsignedTx);
-signer.signOrigin('your-private-key');
-
-const signedTx = signer.transaction;
-```
-
-## Sponsored transactions
-
-Let one account pay fees for another account's transaction.
-
-```typescript
-// User creates sponsored transaction
-const userTx = await makeContractCall({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'my-contract',
- functionName: 'transfer',
- functionArgs: [Cl.principal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG')],
- senderKey: 'user-private-key',
- sponsored: true,
- fee: 0n, // User doesn't pay
- network: 'testnet',
-});
-
-// Sponsor completes and pays
-import { sponsorTransaction } from '@stacks/transactions';
-
-const sponsoredTx = await sponsorTransaction({
- transaction: userTx,
- sponsorPrivateKey: 'sponsor-private-key',
- fee: 2000n, // Sponsor pays the fee
- network: 'testnet',
-});
-
-const result = await broadcastTransaction({ transaction: sponsoredTx });
-```
-
-## Multi-signature transactions
-
-Require multiple signatures for enhanced security.
-
-```typescript
-// Create multi-sig transaction (2-of-3)
-const publicKeys = [publicKey1, publicKey2, publicKey3];
-
-const multiSigTx = await makeUnsignedSTXTokenTransfer({
- recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- amount: 5000000n,
- numSignatures: 2, // Require 2 of 3
- publicKeys,
- network: 'testnet',
-});
-
-// Collect signatures
-const signer = new TransactionSigner(multiSigTx);
-signer.signOrigin(privateKey1); // First signature
-signer.appendOrigin(privateKey2); // Second signature
-
-const signedTx = signer.transaction;
-```
-
-## Working with Clarity values
-
-Use the `Cl` helper for type-safe contract arguments.
-
-```typescript
-import { Cl } from '@stacks/transactions';
-
-const functionArgs = [
- // Primitives
- Cl.uint(42),
- Cl.int(-10),
- Cl.bool(true),
- Cl.stringUtf8('Hello 世界'),
- Cl.stringAscii('Hello World'),
-
- // Principals
- Cl.standardPrincipal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'),
- Cl.contractPrincipal('ST123...', 'my-contract'),
-
- // Composites
- Cl.list([Cl.uint(1), Cl.uint(2), Cl.uint(3)]),
- Cl.tuple({
- name: Cl.stringUtf8('Alice'),
- age: Cl.uint(30)
- }),
-
- // Optionals and responses
- Cl.some(Cl.uint(42)),
- Cl.none(),
- Cl.ok(Cl.uint(200)),
- Cl.err(Cl.uint(404))
-];
-```
-
-## Post-conditions
-
-Add safety constraints to protect users from unexpected transfers.
-
-```typescript
-import { Pc, PostConditionMode } from '@stacks/transactions';
-
-const transaction = await makeContractCall({
- // ... other options
- postConditions: [
- // Sender must send exactly 1 STX
- Pc.principal('ST1ADDRESS...')
- .willSendEq(1000000n)
- .ustx(),
-
- // Contract must transfer tokens
- Pc.principal('ST2CONTRACT...')
- .willSendGte(100n)
- .ft('ST2CONTRACT.token-contract', 'my-token')
- ],
- postConditionMode: PostConditionMode.Deny, // Strict mode
-});
-```
-
-## Fee estimation
-
-Get accurate fee estimates before broadcasting.
-
-```typescript
-import { estimateFee } from '@stacks/transactions';
-
-// Build transaction first
-const tx = await makeSTXTokenTransfer({
- recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- amount: 1000000n,
- senderKey: privateKey,
- network: 'testnet',
- fee: 1n, // Minimal fee for estimation
-});
-
-// Estimate appropriate fee
-const feeRate = await estimateFee(tx);
-tx.setFee(feeRate);
-
-// Now broadcast with accurate fee
-const result = await broadcastTransaction({ transaction: tx });
-```
-
-## Next steps
-
-:::next-steps
-- [Contract calls](/reference/stacks.js/contract-calls): Learn how to call contract functions.
-- [Post-conditions](/reference/stacks.js/post-conditions): Understanding post-conditions.
-:::
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(local-accounts)/contract-calls.mdx b/content/docs/en/reference/stacks.js/(local-accounts)/contract-calls.mdx
deleted file mode 100644
index 3dd551f14..000000000
--- a/content/docs/en/reference/stacks.js/(local-accounts)/contract-calls.mdx
+++ /dev/null
@@ -1,225 +0,0 @@
----
-title: Contract calls
-description: Execute smart contract functions with transactions
----
-
-Contract calls allow you to execute state-changing functions in smart contracts. Unlike read-only calls, these create transactions that must be signed and broadcast to the network.
-
-## Basic contract call
-
-Execute a simple contract function by creating a transaction with the required parameters.
-
-```typescript
-import {
- makeContractCall,
- broadcastTransaction,
- AnchorMode
-} from '@stacks/transactions';
-
-async function callContract() {
- const txOptions = {
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'my-contract',
- functionName: 'transfer',
- functionArgs: [],
- senderKey: 'your-private-key',
- network: 'testnet',
- anchorMode: AnchorMode.Any,
- };
-
- const transaction = await makeContractCall(txOptions);
- const broadcastResponse = await broadcastTransaction({ transaction });
-
- console.log('Transaction ID:', broadcastResponse.txid);
-}
-```
-
-The `makeContractCall` function creates a transaction that will execute the specified function when confirmed on-chain.
-
-## Passing function arguments
-
-Most contract functions require arguments. Use Clarity value constructors to match the expected parameter types.
-
-```typescript
-import {
- Cl,
- makeContractCall,
-} from '@stacks/transactions';
-
-const functionArgs = [
- Cl.principal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'), // recipient
- Cl.uint(1000000), // amount
- Cl.buffer(Buffer.from('Transfer memo', 'utf-8')), // memo
-];
-
-const txOptions = {
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'sip-010-token',
- functionName: 'transfer',
- functionArgs,
- senderKey: 'your-private-key',
- network: "testnet",
-};
-
-const transaction = await makeContractCall(txOptions);
-const result = await broadcastTransaction({ transaction });
-console.log('Transaction ID:', result.txid);
-```
-
-Each Clarity type has a corresponding constructor function that ensures proper encoding for the blockchain.
-
-### Complex argument types
-
-```typescript
-// Tuple arguments
-const userInfo = Cl.tuple({
- name: Cl.string('Alice'),
- age: Cl.uint(30),
- active: Cl.bool(true),
-});
-
-// List arguments
-const addresses = Cl.list([
- Cl.principal('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'),
- Cl.principal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'),
-]);
-
-```
-
-Optional and response values have dedicated constructors for proper type safety.
-
-```typescript
-// Optional values
-const optionalValue = Cl.some(Cl.uint(42)); // (some 42)
-const noValue = Cl.none(); // none
-
-// Response values
-const successResponse = Cl.ok(Cl.uint(100));
-const errorResponse = Cl.err(Cl.uint(404));
-```
-
-## Contract call with STX transfer
-
-Some contracts require STX to be sent along with the function call, such as when minting NFTs or paying for services.
-
-```typescript
-async function mintNFT() {
- const mintPrice = 1000000; // 1 STX
-
- const txOptions = {
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'nft-collection',
- functionName: 'mint',
- functionArgs: [],
- senderKey: 'your-private-key',
- network: new StacksTestnet(),
- anchorMode: AnchorMode.Any,
- // Attach STX to the contract call
- amount: mintPrice,
- };
-
- const transaction = await makeContractCall(txOptions);
- return broadcastTransaction(transaction, network);
-}
-```
-
-## Handling contract responses
-
-Process transaction results and contract responses:
-
-```typescript
-async function executeAndMonitor() {
- // Execute contract call
- const transaction = await makeContractCall({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'my-contract',
- functionName: 'process',
- functionArgs: [uintCV(100)],
- senderKey: 'your-private-key',
- network: new StacksTestnet(),
- anchorMode: AnchorMode.Any,
- });
-
- const broadcastResponse = await broadcastTransaction(transaction, network);
- const txId = broadcastResponse.txid;
-
- // Wait for confirmation
- const txInfo = await waitForConfirmation(txId, network);
-
- // Check transaction result
- if (txInfo.tx_status === 'success') {
- console.log('Contract returned:', txInfo.tx_result);
- // Parse the result based on expected return type
- } else {
- console.error('Transaction failed:', txInfo.tx_result);
- }
-}
-
-async function waitForConfirmation(txId: string, network: StacksNetwork) {
- let attempts = 0;
- const maxAttempts = 30;
-
- while (attempts < maxAttempts) {
- const response = await fetch(
- `${network.coreApiUrl}/extended/v1/tx/${txId}`
- );
- const txInfo = await response.json();
-
- if (txInfo.tx_status === 'success' || txInfo.tx_status === 'abort_by_response') {
- return txInfo;
- }
-
- await new Promise(resolve => setTimeout(resolve, 10000));
- attempts++;
- }
-
- throw new Error('Transaction confirmation timeout');
-}
-```
-
-## Multi-step contract interactions
-
-Chain multiple contract calls:
-
-```typescript
-async function complexWorkflow() {
- // Step 1: Approve spending
- const approveTx = await makeContractCall({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'token',
- functionName: 'approve',
- functionArgs: [
- standardPrincipalCV('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'),
- uintCV(1000000),
- ],
- senderKey: 'your-private-key',
- network: new StacksTestnet(),
- anchorMode: AnchorMode.Any,
- });
-
- const approveResult = await broadcastTransaction(approveTx, network);
- await waitForConfirmation(approveResult.txid, network);
-
- // Step 2: Execute swap after approval
- const swapTx = await makeContractCall({
- contractAddress: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- contractName: 'dex',
- functionName: 'swap-tokens',
- functionArgs: [
- standardPrincipalCV('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'),
- uintCV(1000000),
- ],
- senderKey: 'your-private-key',
- network: new StacksTestnet(),
- anchorMode: AnchorMode.Any,
- });
-
- return broadcastTransaction(swapTx, network);
-}
-```
-
-## Further reading
-
-- [Contract deployment](/reference/stacks.js/contract-deployment)
-- [Read-only calls](/reference/stacks.js/read-only-calls)
-- [Post-conditions](/reference/stacks.js/post-conditions)
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(local-accounts)/contract-deployment.mdx b/content/docs/en/reference/stacks.js/(local-accounts)/contract-deployment.mdx
deleted file mode 100644
index 7fd4cf6f4..000000000
--- a/content/docs/en/reference/stacks.js/(local-accounts)/contract-deployment.mdx
+++ /dev/null
@@ -1,45 +0,0 @@
----
-title: Contract deployment
-description: Deploy smart contracts to the Stacks blockchain
----
-
-## Overview
-
-Contract deployment creates new smart contracts on the blockchain. Stacks.js provides tools to compile, deploy, and verify Clarity contracts programmatically. Deployments can be simple single contracts or complex multi-contract systems with dependencies.
-
-## Basic contract deployment
-
-Deploy a simple smart contract:
-
-```typescript
-import {
- makeContractDeploy,
- broadcastTransaction,
- AnchorMode
-} from '@stacks/transactions';
-import { STACKS_TESTNET } from '@stacks/network';
-import { readFileSync } from 'fs';
-
-async function deployContract() {
- const network = new StacksTestnet();
-
- // Read contract source code
- const contractSource = readFileSync('./contracts/my-contract.clar', 'utf-8');
-
- const txOptions = {
- contractName: 'my-contract',
- codeBody: contractSource,
- senderKey: 'your-private-key',
- network,
- anchorMode: AnchorMode.Any,
- fee: 10000, // Higher fee for deployment
- };
-
- const transaction = await makeContractDeploy(txOptions);
- const broadcastResponse = await broadcastTransaction(transaction, network);
-
- console.log('Contract deployed!');
- console.log('Transaction ID:', broadcastResponse.txid);
- console.log('Contract address:', `${senderAddress}.${txOptions.contractName}`);
-}
-```
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(local-accounts)/meta.json b/content/docs/en/reference/stacks.js/(local-accounts)/meta.json
deleted file mode 100644
index e7843b951..000000000
--- a/content/docs/en/reference/stacks.js/(local-accounts)/meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "title": "Local accounts",
- "defaultOpen": false,
- "pages": ["read-only-calls", "build-transactions", "contract-calls", "contract-deployment"]
-}
diff --git a/content/docs/en/reference/stacks.js/(local-accounts)/read-only-calls.mdx b/content/docs/en/reference/stacks.js/(local-accounts)/read-only-calls.mdx
deleted file mode 100644
index 939140a33..000000000
--- a/content/docs/en/reference/stacks.js/(local-accounts)/read-only-calls.mdx
+++ /dev/null
@@ -1,114 +0,0 @@
----
-title: Read-only calls
-description: Query smart contract state without creating transactions
----
-
-Read-only function calls allow you to query data from smart contracts without creating a transaction. These calls are free, instant, and don't require wallet interaction.
-
-## Basic read-only call
-
-Call a read-only function to get contract data without any transaction fees:
-
-```typescript
-import { fetchCallReadOnlyFunction, cvToValue } from '@stacks/transactions';
-
-const contractAddress = 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM';
-const contractName = 'my-contract';
-const functionName = 'get-balance';
-
-const response = await fetchCallReadOnlyFunction({
- contractAddress,
- contractName,
- functionName,
- functionArgs: [],
- senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
-});
-
-const balance = cvToValue(response);
-console.log('Balance:', balance);
-```
-
-## Passing function arguments
-
-Most read-only functions require arguments. Use Clarity value builders to construct the appropriate types:
-
-```typescript
-import {
- fetchCallReadOnlyFunction,
- principalCV,
- uintCV,
- stringUtf8CV
-} from '@stacks/transactions';
-
-const functionArgs = [
- principalCV('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'),
- stringUtf8CV('admin')
-];
-
-const response = await fetchCallReadOnlyFunction({
- contractAddress: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- contractName: 'access-control',
- functionName: 'has-role',
- functionArgs,
- senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
-});
-
-const hasRole = cvToValue(response);
-console.log('Has admin role:', hasRole);
-```
-
-## Handling response types
-
-Read-only functions can return response types (ok/err). Check the response type to handle both success and error cases:
-
-```typescript
-import {
- fetchCallReadOnlyFunction,
- cvToJSON,
- ResponseOkCV,
- ResponseErrorCV
-} from '@stacks/transactions';
-
-const response = await fetchCallReadOnlyFunction({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'sip-010-token',
- functionName: 'get-token-info',
- functionArgs: [],
- senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
-});
-
-if (response.type === 'ok') {
- const tokenInfo = cvToJSON(response.value);
- console.log('Token info:', tokenInfo);
- // {
- // name: "My Token",
- // symbol: "MTK",
- // decimals: 6,
- // totalSupply: "1000000000000"
- // }
-} else {
- console.error('Error:', cvToValue(response.value));
-}
-```
-
-## Using custom network
-
-Specify a custom network URL for testnet or custom node connections:
-
-```typescript
-import { fetchCallReadOnlyFunction } from '@stacks/transactions';
-
-const response = await fetchCallReadOnlyFunction({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'my-contract',
- functionName: 'get-data',
- functionArgs: [],
- senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- network: 'testnet', // or custom URL like 'http://localhost:3999'
-});
-```
-
-## Further reading
-
-- [Execute state-changing contract functions](/reference/stacks.js/contract-calls)
-- [Work with Clarity values and types](/reference/stacks.js/encoding-decoding)
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(overview)/accounts-and-addresses.mdx b/content/docs/en/reference/stacks.js/(overview)/accounts-and-addresses.mdx
deleted file mode 100644
index fe401dead..000000000
--- a/content/docs/en/reference/stacks.js/(overview)/accounts-and-addresses.mdx
+++ /dev/null
@@ -1,179 +0,0 @@
----
-title: Accounts & addresses
-description: Learn how to get an address from an account
----
-
-Stacks uses the concept of an "account" to represent a user's identity on the blockchain. An account is identified by a unique address derived from the account's public key.
-
-## Address formats
-
-Stacks addresses use different prefixes to indicate the network they belong to, making it easy to distinguish between mainnet and testnet addresses.
-
-```typescript
-// Mainnet address starts with 'SP'
-const mainnetAddress = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
-
-// Testnet address starts with 'ST'
-const testnetAddress = 'ST2F4BK4GZH6YFBNHYDDGN4T1RKBA7DA1BJZPJEJJ';
-```
-
-The address format ensures that tokens on testnet cannot be accidentally sent to mainnet addresses and vice versa.
-
-## Getting an address
-
-There are several ways to obtain a Stacks address depending on your use case and what cryptographic material you have available.
-
-### Using Stacks Connect
-
-When building user-facing applications, you'll typically get addresses from users who connect their wallets through Stacks Connect.
-
-```tsx
-import { connect, getLocalStorage, request } from '@stacks/connect';
-
-async function handleWalletConnection() {
- // Connect to wallet
- const response = await connect();
-
- // Get stored addresses
- const data = getLocalStorage();
- const stxAddresses = data.addresses.stx;
-
- if (stxAddresses && stxAddresses.length > 0) {
- const address = stxAddresses[0].address;
- console.log('STX Address:', address);
- // 'SP1MXSZF4NFC8JQ1TTYGEC2WADMC7Y3GHVZYRX6RF'
- }
-
- // Get detailed account info if needed
- const accounts = await request('stx_getAccounts');
- console.log('Account details:', accounts.addresses[0]);
-}
-```
-
-Stacks Connect stores the connected addresses in local storage, allowing your app to persist the connection across page reloads.
-
-### Using a seed phrase
-
-For programmatic wallet generation or when restoring accounts from backup, you can derive addresses from a seed phrase (also known as a mnemonic).
-
-```typescript
-import { generateWallet, generateSecretKey } from '@stacks/wallet-sdk';
-
-async function createWalletFromSeed() {
- // Generate a new 24-word seed phrase
- const secretKey = generateSecretKey();
-
- // Or use an existing seed phrase
- // const secretKey = 'already owned seed phrase ...';
-
- const wallet = await generateWallet({
- secretKey,
- password: 'optional-encryption-password',
- });
-
- // Get the first account's address
- const account = wallet.accounts[0];
- const mainnetAddress = account.address;
-
- console.log('Address:', mainnetAddress);
- console.log('Private key:', account.stxPrivateKey);
-}
-```
-
-Each wallet can contain multiple accounts, all derived from the same seed phrase using different derivation paths.
-
-### Using a private key
-
-If you already have a private key, you can directly derive the corresponding address without going through the wallet generation process.
-
-```typescript
-import { privateKeyToAddress, TransactionVersion } from '@stacks/transactions';
-
-function getAddressFromPrivateKey() {
- // Compressed private key (64 or 66 characters)
- const privateKey = 'your-private-key-here';
-
- // For mainnet
- const mainnetAddress = privateKeyToAddress(
- privateKey,
- TransactionVersion.Mainnet
- );
-
- // For testnet
- const testnetAddress = privateKeyToAddress(
- privateKey,
- TransactionVersion.Testnet
- );
-
- console.log('Mainnet:', mainnetAddress);
- console.log('Testnet:', testnetAddress);
-}
-```
-
-The same private key will generate different addresses for mainnet and testnet due to the network-specific version bytes.
-
-### Using a public key
-
-When you only have access to a public key (for example, in a watch-only wallet scenario), you can still derive the corresponding address.
-
-```typescript
-import { publicKeyToAddress, TransactionVersion } from '@stacks/transactions';
-
-function getAddressFromPublicKey() {
- // Compressed public key (66 characters starting with 02 or 03)
- const publicKey = '03b3e0a76b292b2c83fc0ac14ae6160d0438ebe94e14bbb7d0ded3c217f3d29ba7';
-
- // For mainnet
- const mainnetAddress = publicKeyToAddress(
- publicKey,
- TransactionVersion.Mainnet
- );
-
- // For testnet
- const testnetAddress = publicKeyToAddress(
- publicKey,
- TransactionVersion.Testnet
- );
-
- console.log('Mainnet:', mainnetAddress);
- // 'SP1MXSZF4NFC8JQ1TTYGEC2WADMC7Y3GHVZYRX6RF'
-}
-```
-
-This is useful for creating watch-only wallets or verifying addresses without access to private keys.
-
-## Address validation
-
-Before sending transactions, it's important to validate that addresses are properly formatted.
-
-```typescript
-import { validateStacksAddress } from '@stacks/transactions';
-
-function isValidAddress(address: string): boolean {
- try {
- // Check if it's a valid mainnet address
- if (address.startsWith('SP')) {
- return validateStacksAddress(address);
- }
-
- // Check if it's a valid testnet address
- if (address.startsWith('ST')) {
- return validateStacksAddress(address);
- }
-
- return false;
- } catch (error) {
- return false;
- }
-}
-
-// Examples
-console.log(isValidAddress('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159')); // true
-console.log(isValidAddress('invalid-address')); // false
-```
-
-Always validate addresses before using them in transactions to prevent loss of funds due to typos or formatting errors.
-
-## Further reading
-
-- [Connect wallet](/reference/stacks.js/connect-wallet)
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(overview)/meta.json b/content/docs/en/reference/stacks.js/(overview)/meta.json
deleted file mode 100644
index 03b0cbfde..000000000
--- a/content/docs/en/reference/stacks.js/(overview)/meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "title": "Overview",
- "defaultOpen": false,
- "pages": ["usage", "accounts-and-addresses", "private-keys", "networks"]
-}
diff --git a/content/docs/en/reference/stacks.js/(overview)/networks.mdx b/content/docs/en/reference/stacks.js/(overview)/networks.mdx
deleted file mode 100644
index 8dd7e9158..000000000
--- a/content/docs/en/reference/stacks.js/(overview)/networks.mdx
+++ /dev/null
@@ -1,49 +0,0 @@
----
-title: Networks
-description: Learn how to use different networks.
----
-
-import { Star } from 'lucide-react';
-
-Typically, we speak of `mainnet` and `testnet` as the networks of Stacks.
-Most wallets are configured to `mainnet` by default—this is the production environment, the actual blockchain that holds real STX tokens.
-
-As the name suggests, `testnet` is a public network for testing.
-It's a separate blockchain state that holds test tokens, which have no value.
-
-For completeness we also mention `devnet`.
-This isn't "one" network, but how developers refer to ephemeral local networks used for testing.
-It is the same as `testnet`, but for local development.
-[Learn more](/tools/clarinet/local-blockchain-development).
-
-## Setting the network
-
-Most Stacks.js functions accept a `network` parameter or an optional last argument.
-
-The `network` type is a string, and can be one of:
-- `'mainnet'` (default)
-- `'testnet'`
-- `'devnet'`
-- `'mocknet'` (alias of `devnet`)
-
-### Examples
-
-Network in transaction signing:
-```ts
-const tx = makeSTXTokenTransfer({
- // ...
- network: 'testnet',
-});
-```
-
-Network in address derivation:
-```ts
-const address = privateKeyToAddress(privateKey, 'devnet');
-// ST3NBRSFKX28FQ2ZJ1MAKX58HKHSDGNV5N7R21XCP
-```
-
-:::callout
-type: tip
-### Advanced usage
-For more advanced uses, you can pass an object of a network configuration. Read more about the network object in the [`@stacks/network`](/reference/stacks.js/packages/network) package.
-:::
diff --git a/content/docs/en/reference/stacks.js/(overview)/private-keys.mdx b/content/docs/en/reference/stacks.js/(overview)/private-keys.mdx
deleted file mode 100644
index f3e282369..000000000
--- a/content/docs/en/reference/stacks.js/(overview)/private-keys.mdx
+++ /dev/null
@@ -1,179 +0,0 @@
----
-title: Private keys
-description: Learn how to manage private keys with Stacks.js
----
-
-Stacks applications can work with two different account types: web wallets (like Hiro Wallet or Xverse) that users control, or local accounts you manage the private keys directly.
-
-## Web wallets (user-controlled)
-
-Most users interact with Stacks apps through web wallets, where the wallet handles all private key management and transaction signing.
-
-```typescript
-import { connect } from '@stacks/connect';
-
-// Users connect their wallet
-const response = await connect();
-console.log('Connected addresses:', response.addresses);
-
-// The wallet handles all cryptographic operations
-// when signing transactions or messages
-```
-
-Use web wallets when building user-facing applications where users should maintain control of their keys.
-
-## Local accounts (application-controlled)
-
-Local accounts give your application direct control over private keys, enabling programmatic transaction signing without user interaction.
-
-```typescript
-import { makeSTXTokenTransfer } from '@stacks/transactions';
-
-// Your application controls the private key
-const privateKey = 'your-private-key-here';
-
-const txOptions = {
- recipient: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- amount: 1000000n,
- senderKey: privateKey, // Direct private key usage
- network: 'testnet',
-};
-
-const transaction = await makeSTXTokenTransfer(txOptions);
-// Transaction is signed programmatically
-```
-
-Use local accounts for backend services, automated systems, or development tools that need to sign transactions without user interaction.
-
-## Working with private keys
-
-When building applications that use local accounts, you'll need to generate and manage private keys securely.
-
-### Generating random private keys
-
-Create a new private key for one-time use or testing purposes.
-
-```typescript
-import { randomPrivateKey } from '@stacks/transactions';
-
-function generateNewAccount() {
- const privateKey = randomPrivateKey();
- console.log('Private key:', privateKey);
- // 'f5a31c1268a1e37d4edaa05c7d11183c5fbf...'
-
- // IMPORTANT: Store this securely!
- // Anyone with this key can control the account
- return privateKey;
-}
-```
-
-Private keys in Stacks are 256-bit numbers, typically represented as 64-character hexadecimal strings.
-
-## Private key formats
-
-Stacks.js supports multiple private key formats for different use cases.
-
-```typescript
-import { PrivateKey } from '@stacks/transactions';
-
-// Hex string format (most common)
-const hexKey = 'f5a31c1268a1e37d4edaa05c7d11183c5fbf...';
-
-// Compressed format with suffix
-const compressedKey = 'f5a31c1268a1e37d4edaa05c7d11183c5fbf...01';
-
-// Create from raw bytes
-const bytes = new Uint8Array(32); // 32 bytes = 256 bits
-crypto.getRandomValues(bytes);
-const privateKeyFromBytes = PrivateKey.fromBytes(bytes);
-```
-
-The compressed format includes a suffix byte (01) that indicates the key should use compressed public key encoding.
-
-## Wallet generation with seed phrases
-
-For better security and recoverability, use hierarchical deterministic (HD) wallets based on seed phrases.
-
-### Generate a seed phrase
-
-Create a new 24-word mnemonic seed phrase that can regenerate all wallet accounts.
-
-```typescript
-import { generateSecretKey } from '@stacks/wallet-sdk';
-
-function createNewWallet() {
- const secretKey = generateSecretKey();
- console.log('Seed phrase:', secretKey);
- // "warrior volume sport ... figure cake since"
-
- // Users should write this down and store it securely
- // This phrase can regenerate all accounts in the wallet
- return secretKey;
-}
-```
-
-Seed phrases provide a human-readable backup that can restore an entire wallet hierarchy.
-
-### Create wallet from seed phrase
-
-Generate a complete wallet structure from a seed phrase, including multiple accounts.
-
-```typescript
-import { generateWallet, generateSecretKey } from '@stacks/wallet-sdk';
-
-async function setupWallet() {
- // Use existing seed phrase or generate new one
- const seedPhrase = generateSecretKey();
-
- const wallet = await generateWallet({
- secretKey: seedPhrase,
- password: 'optional-encryption-password',
- });
-
- // Access the first account
- const account = wallet.accounts[0];
- console.log('STX address:', account.address);
- console.log('STX private key:', account.stxPrivateKey);
- console.log('Data private key:', account.dataPrivateKey);
-
- return wallet;
-}
-```
-
-Each wallet can contain multiple accounts, all derived from the same seed phrase but with different private keys.
-
-### Managing multiple accounts
-
-HD wallets support multiple accounts from a single seed phrase, useful for organizing funds or separating concerns.
-
-```typescript
-import { generateNewAccount, generateWallet, generateSecretKey } from '@stacks/wallet-sdk';
-
-async function createMultipleAccounts() {
- const seedPhrase = generateSecretKey();
-
- let wallet = await generateWallet({
- secretKey: seedPhrase,
- password: 'my-password',
- });
-
- console.log('Accounts:', wallet.accounts.length); // 1 (default)
-
- // Add more accounts
- wallet = generateNewAccount(wallet);
- wallet = generateNewAccount(wallet);
-
- console.log('Accounts:', wallet.accounts.length); // 3
-
- // Each account has its own keys and address
- wallet.accounts.forEach((account, index) => {
- console.log(`Account ${index}:`, account.address);
- });
-}
-```
-
-All accounts can be regenerated from the original seed phrase, making backup simple while maintaining separate addresses.
-
-## Further reading
-
-- [Stacks Connect](/reference/stacks.js/connect-wallet) - Building apps with web wallets
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(post-conditions)/implementing-post-conditions.mdx b/content/docs/en/reference/stacks.js/(post-conditions)/implementing-post-conditions.mdx
deleted file mode 100644
index ad640a320..000000000
--- a/content/docs/en/reference/stacks.js/(post-conditions)/implementing-post-conditions.mdx
+++ /dev/null
@@ -1,243 +0,0 @@
----
-title: Implementing post-conditions
-sidebarTitle: Implement post-conditions
-description: Learn how to add post-conditions to protect your Stacks transactions
----
-
-Post-conditions are a powerful security feature in Stacks that protect users from unexpected transaction outcomes. This tutorial will walk you through implementing post-conditions in your applications to ensure transactions behave exactly as users expect.
-
-## What you'll learn
-
-:::objectives
-- Construct post-conditions using the Pc helper API
-- Add post-conditions to different transaction types
-- Configure post-condition modes for transaction security
-- Implement post-conditions for STX, fungible tokens, and NFTs
-- Handle semi-fungible tokens (SFTs) with post-conditions
-:::
-
-## Prerequisites
-
-:::prerequisites
-- Basic understanding of Stacks transactions
-- Stacks.js library installed (`npm install @stacks/transactions`)
-- A development environment set up for Stacks
-:::
-
-## Constructing post-conditions
-
-The Pc helper in Stacks.js provides a fluent, BDD-inspired API for constructing post-conditions. Start with `Pc.principal()` to specify which address will be verified, then chain methods to define the condition.
-
-```ts
-import { Pc } from '@stacks/transactions';
-
-// Basic structure of a post-condition
-const postCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendEq(1000)
- .ustx();
-```
-
-The Pc helper uses method chaining for intuitive condition building. Your IDE will provide auto-completion for available methods at each step.
-
-## Available transfer methods
-
-Post-conditions support different comparison operators and asset types. Choose the appropriate method based on your security requirements.
-
-### STX and fungible token methods
-
-```ts
-// Exact amount
-Pc.principal(address).willSendEq(1000).ustx();
-
-// Greater than or equal
-Pc.principal(address).willSendGte(500).ustx();
-
-// Less than
-Pc.principal(address).willSendLt(2000).ustx();
-```
-
-Comparison methods available:
-- `.willSendEq(amount)` - Exactly equal to amount
-- `.willSendGte(amount)` - Greater than or equal to amount
-- `.willSendGt(amount)` - Greater than amount
-- `.willSendLte(amount)` - Less than or equal to amount
-- `.willSendLt(amount)` - Less than amount
-
-### Asset type methods
-
-```ts
-// STX transfers
-.ustx()
-
-// Fungible token transfers
-.ft(contractAddress, tokenName)
-
-// NFT transfers
-.nft(assetIdentifier, tokenId)
-```
-
-### NFT-specific methods
-
-```ts
-// Ensure NFT is sent
-Pc.principal(address).willSendAsset().nft(...);
-
-// Ensure NFT is NOT sent
-Pc.principal(address).willNotSendAsset().nft(...);
-```
-
-## Setting the post-condition mode
-
-The post-condition mode determines how the Stacks blockchain handles asset transfers not explicitly covered by your post-conditions. This is a critical security setting.
-
-```ts
-import { PostConditionMode, makeContractCall } from '@stacks/transactions';
-
-const tx = await makeContractCall({
- // ... other transaction properties
- postConditionMode: PostConditionMode.Deny, // Recommended default
- postConditions: [
- // your post-conditions here
- ],
-});
-```
-
-Mode options:
-- **`PostConditionMode.Deny`** (default): Transaction fails if any unspecified transfers occur
-- **`PostConditionMode.Allow`**: Transaction allows transfers beyond specified post-conditions
-
-## Common implementation patterns
-
-### STX transfer post-conditions
-
-Protect STX transfers by specifying exact amounts or ranges.
-
-```ts
-import { Pc, makeSTXTokenTransfer } from '@stacks/transactions';
-
-// Exact amount post-condition
-const exactAmountCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendEq(1000)
- .ustx();
-
-// Use in a transaction
-const tx = await makeSTXTokenTransfer({
- recipient: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- amount: 1000,
- postConditions: [exactAmountCondition],
- postConditionMode: PostConditionMode.Deny,
- // ... other properties
-});
-```
-
-### Fungible token post-conditions
-
-Ensure fungible tokens are transferred as expected in contract calls.
-
-```ts
-import { Pc, makeContractCall } from '@stacks/transactions';
-
-// Minimum amount condition
-const ftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendGte(500)
- .ft('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.token-ft', 'token');
-
-// Use in a contract call
-const tx = await makeContractCall({
- contractAddress: 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6',
- contractName: 'token-transfer',
- functionName: 'transfer',
- functionArgs: [
- // ... function arguments
- ],
- postConditions: [ftCondition],
- // ... other properties
-});
-```
-
-### NFT transfer post-conditions
-
-Control NFT ownership changes with specific post-conditions.
-
-```ts
-import { Pc, Cl } from '@stacks/transactions';
-
-// Ensure NFT is sent
-const sendNftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendAsset()
- .nft('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.nft-contract::nft-name', Cl.uint(1));
-
-// Ensure NFT is NOT sent (protection against unwanted transfers)
-const keepNftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willNotSendAsset()
- .nft('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.nft-contract::nft-name', Cl.uint(1));
-```
-
-Use `willNotSendAsset()` to protect valuable NFTs from being transferred unexpectedly.
-
-### Semi-fungible token (SFT) post-conditions
-
-SFTs require special handling as they have both fungible and non-fungible properties.
-
-```ts
-import { Cl, Pc } from '@stacks/transactions';
-
-// SFT as NFT (specific token ID)
-const sftNftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendAsset()
- .nft(
- 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.sft-contract::sft-id',
- Cl.tuple({
- 'token-id': Cl.uint(1),
- owner: Cl.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- })
- );
-
-// SFT as FT (amount-based)
-const sftFtCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendEq(500)
- .ft('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.sft-contract', 'sft-token');
-```
-
-## Multiple post-conditions
-
-Complex transactions often require multiple post-conditions to fully protect all asset transfers.
-
-```ts
-const tx = await makeContractCall({
- // ... transaction properties
- postConditions: [
- // Sender must send exactly 1000 uSTX
- Pc.principal(senderAddress).willSendEq(1000).ustx(),
-
- // Contract must send at least 100 tokens to user
- Pc.principal(contractAddress).willSendGte(100)
- .ft(contractAddress + '.my-token', 'my-token'),
-
- // User must not lose their NFT
- Pc.principal(senderAddress).willNotSendAsset()
- .nft(nftContract + '::my-nft', Cl.uint(1)),
- ],
- postConditionMode: PostConditionMode.Deny,
-});
-```
-
-:::callout
-type: tip
-### Try it out
-Explore the [Post-conditions template](https://platform.hiro.so) for interactive examples.
-:::
-
-## Next steps
-
-:::next-steps
-- [Contract calling](/reference/stacks.js/contract-calls): Learn how to call contracts in Stacks
-- [Transaction broadcasting](/reference/stacks.js/broadcast-transactions): Learn how to broadcast protected transactions
-:::
diff --git a/content/docs/en/reference/stacks.js/(post-conditions)/meta.json b/content/docs/en/reference/stacks.js/(post-conditions)/meta.json
deleted file mode 100644
index d8ed39ead..000000000
--- a/content/docs/en/reference/stacks.js/(post-conditions)/meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "title": "Security & Post-conditions",
- "defaultOpen": false,
- "pages": ["post-conditions", "implementing-post-conditions"]
-}
diff --git a/content/docs/en/reference/stacks.js/(post-conditions)/post-conditions.mdx b/content/docs/en/reference/stacks.js/(post-conditions)/post-conditions.mdx
deleted file mode 100644
index 72ccd1776..000000000
--- a/content/docs/en/reference/stacks.js/(post-conditions)/post-conditions.mdx
+++ /dev/null
@@ -1,129 +0,0 @@
----
-title: Introduction
-sidebarTitle: Introduction
-description: Learn how post-conditions protect users from unexpected transaction outcomes
----
-
-Post-conditions are security features in Stacks that protect users by ensuring transactions execute exactly as expected. They verify that specific asset transfers occur during a transaction, and if the conditions aren't satisfied, the entire transaction fails with no state changes.
-
-## What are post-conditions?
-
-Post-conditions act as safeguards that verify asset transfers match your expectations. They can check STX transfers, fungible tokens, and non-fungible token ownership changes.
-
-```ts
-import { Pc } from '@stacks/transactions';
-
-const tx = await makeContractCall({
- // ...
- postConditions: [
- Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6').willSendEq(1000).ustx(),
- ],
-});
-```
-
-Post-conditions only verify that assets are sent, not received. They cannot guarantee the final recipient of tokens.
-
-## Using the Pc helper
-
-The `Pc` helper provides a fluent API for creating post-conditions with better type safety and readability.
-
-```ts
-import { Pc } from '@stacks/transactions';
-
-// STX transfer post-condition
-const stxCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendGte(1000)
- .ustx();
-
-// Fungible token post-condition
-const ftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendEq(50)
- .ft('SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-token', 'my-token');
-
-// NFT post-condition
-const nftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendAsset()
- .nft('SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-nft::my-asset', Cl.uint(1));
-```
-
-## Manual creation
-
-Create post-conditions manually using type definitions when building conditions dynamically.
-
-```ts
-import {
- StxPostCondition,
- FungiblePostCondition,
- NonFungiblePostCondition
-} from '@stacks/transactions';
-
-// STX post-condition
-const stxPostCondition: StxPostCondition = {
- type: 'stx-postcondition',
- address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
- condition: 'gte', // 'eq' | 'gt' | 'gte' | 'lt' | 'lte'
- amount: '100',
-};
-```
-
-Available condition types:
-- `eq`: Exactly equal to amount
-- `gt`: Greater than amount
-- `gte`: Greater than or equal to amount
-- `lt`: Less than amount
-- `lte`: Less than or equal to amount
-
-### Fungible tokens
-
-```ts
-const ftPostCondition: FungiblePostCondition = {
- type: 'ft-postcondition',
- address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
- condition: 'eq',
- amount: '100',
- asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-ft-token::my-token',
-};
-```
-
-### Non-fungible tokens
-
-```ts
-const nftPostCondition: NonFungiblePostCondition = {
- type: 'nft-postcondition',
- address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
- condition: 'sent', // 'sent' | 'not-sent'
- asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-nft::my-asset',
- assetId: Cl.uint(602),
-};
-```
-
-## Post-condition mode
-
-Control how unspecified asset transfers are handled with post-condition mode.
-
-```ts
-import { PostConditionMode } from '@stacks/transactions';
-
-const tx = await makeContractCall({
- // ...
- postConditionMode: PostConditionMode.Deny,
- postConditions: [
- // your conditions
- ],
-});
-```
-
-:::callout
-type: warn
-### Post-condition mode
-Always use `Deny` mode unless you have a specific reason to allow additional transfers. This provides maximum security for users.
-:::
-
-## Further reading
-
-- [Implementing post-conditions](/reference/stacks.js/implementing-post-conditions)
-- [Transaction building](/reference/stacks.js/build-transactions)
-- [Contract calls](/reference/stacks.js/contract-calls)
diff --git a/content/docs/en/reference/stacks.js/(utils)/address-validation.mdx b/content/docs/en/reference/stacks.js/(utils)/address-validation.mdx
deleted file mode 100644
index 38b22fd3d..000000000
--- a/content/docs/en/reference/stacks.js/(utils)/address-validation.mdx
+++ /dev/null
@@ -1,562 +0,0 @@
----
-title: Address validation
-description: Validate and format Stacks addresses and principals
----
-
-## Overview
-
-Stacks addresses follow specific formats that differ between mainnet and testnet. Proper validation ensures your application handles addresses correctly, preventing loss of funds and improving user experience. This guide covers address validation, formatting, and conversion utilities.
-
-## Basic address validation
-
-Validate Stacks addresses:
-
-```typescript
-import {
- validateStacksAddress,
- validateContractName
-} from '@stacks/transactions';
-
-// Validate standard addresses
-const isValidMainnet = validateStacksAddress('SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY');
-console.log('Valid mainnet:', isValidMainnet); // true
-
-const isValidTestnet = validateStacksAddress('ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC');
-console.log('Valid testnet:', isValidTestnet); // true
-
-const isInvalid = validateStacksAddress('invalid-address');
-console.log('Valid:', isInvalid); // false
-
-// Validate contract names
-const validContract = validateContractName('my-contract');
-console.log('Valid contract name:', validContract); // true
-
-const invalidContract = validateContractName('My Contract!');
-console.log('Valid contract name:', invalidContract); // false
-```
-
-## Address types and detection
-
-Identify address types and networks:
-
-```typescript
-import {
- getAddressFromPrivateKey,
- getAddressFromPublicKey,
- TransactionVersion
-} from '@stacks/transactions';
-
-// Detect address type from prefix
-function getAddressInfo(address: string): {
- type: 'standard' | 'contract' | 'multisig' | 'invalid';
- network: 'mainnet' | 'testnet' | 'unknown';
-} {
- if (!validateStacksAddress(address)) {
- return { type: 'invalid', network: 'unknown' };
- }
-
- // Mainnet prefixes
- if (address.startsWith('SP')) {
- return { type: 'standard', network: 'mainnet' };
- } else if (address.startsWith('SM')) {
- return { type: 'multisig', network: 'mainnet' };
- }
-
- // Testnet prefixes
- else if (address.startsWith('ST')) {
- return { type: 'standard', network: 'testnet' };
- } else if (address.startsWith('SN')) {
- return { type: 'multisig', network: 'testnet' };
- }
-
- // Contract address (contains .)
- if (address.includes('.')) {
- const [principal] = address.split('.');
- const info = getAddressInfo(principal);
- return { ...info, type: 'contract' };
- }
-
- return { type: 'invalid', network: 'unknown' };
-}
-
-// Usage
-const info = getAddressInfo('SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.my-contract');
-console.log(info); // { type: 'contract', network: 'mainnet' }
-```
-
-## Address generation
-
-Generate addresses from keys:
-
-```typescript
-import {
- makeRandomPrivKey,
- getPublicKey,
- getAddressFromPrivateKey,
- getAddressFromPublicKey,
- TransactionVersion,
- AddressHashMode
-} from '@stacks/transactions';
-
-// Generate new random address
-function generateNewAddress(network: 'mainnet' | 'testnet') {
- const privateKey = makeRandomPrivKey();
- const publicKey = getPublicKey(privateKey);
-
- const version = network === 'mainnet'
- ? TransactionVersion.Mainnet
- : TransactionVersion.Testnet;
-
- const address = getAddressFromPrivateKey(privateKey, version);
-
- return {
- privateKey,
- publicKey,
- address,
- };
-}
-
-// Generate address from existing private key
-function getAddressFromKey(privateKey: string, network: 'mainnet' | 'testnet') {
- const version = network === 'mainnet'
- ? TransactionVersion.Mainnet
- : TransactionVersion.Testnet;
-
- return getAddressFromPrivateKey(privateKey, version);
-}
-
-// Generate multisig address
-function generateMultisigAddress(
- publicKeys: string[],
- signaturesRequired: number,
- network: 'mainnet' | 'testnet'
-) {
- const version = network === 'mainnet'
- ? TransactionVersion.Mainnet
- : TransactionVersion.Testnet;
-
- const hashMode = AddressHashMode.SerializeP2SH;
-
- // Implementation depends on multisig setup
- // This is a simplified example
- return getAddressFromPublicKey(
- publicKeys[0], // Simplified - real implementation needs all keys
- version,
- hashMode
- );
-}
-```
-
-## Contract address handling
-
-Work with contract principals:
-
-```typescript
-// Parse contract address components
-function parseContractAddress(contractAddress: string): {
- principal: string;
- contractName: string;
- isValid: boolean;
-} {
- const parts = contractAddress.split('.');
-
- if (parts.length !== 2) {
- return { principal: '', contractName: '', isValid: false };
- }
-
- const [principal, contractName] = parts;
-
- const isValid = validateStacksAddress(principal) &&
- validateContractName(contractName);
-
- return { principal, contractName, isValid };
-}
-
-// Build contract address
-function buildContractAddress(principal: string, contractName: string): string {
- if (!validateStacksAddress(principal)) {
- throw new Error('Invalid principal address');
- }
-
- if (!validateContractName(contractName)) {
- throw new Error('Invalid contract name');
- }
-
- return `${principal}.${contractName}`;
-}
-
-// Validate full contract identifier
-function validateContractAddress(address: string): boolean {
- const { isValid } = parseContractAddress(address);
- return isValid;
-}
-
-// Usage
-const parsed = parseContractAddress('SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.my-token');
-console.log(parsed);
-// { principal: 'SP2J6...', contractName: 'my-token', isValid: true }
-```
-
-## Address conversion utilities
-
-Convert between formats and networks:
-
-```typescript
-import { c32addressDecode, c32address } from 'c32check';
-
-// Convert between testnet and mainnet addresses
-function convertAddressNetwork(
- address: string,
- toNetwork: 'mainnet' | 'testnet'
-): string {
- try {
- // Decode the address
- const decoded = c32addressDecode(address);
-
- // Determine new version
- let newVersion: number;
- if (toNetwork === 'mainnet') {
- newVersion = decoded[0] === 26 ? 22 : 20; // Multi-sig or standard
- } else {
- newVersion = decoded[0] === 22 ? 26 : 21; // Multi-sig or standard
- }
-
- // Re-encode with new version
- const newAddress = c32address(newVersion, decoded[1]);
- return newAddress;
- } catch (error) {
- throw new Error('Invalid address format');
- }
-}
-
-// Extract address hash
-function getAddressHash(address: string): string {
- const decoded = c32addressDecode(address);
- return Buffer.from(decoded[1]).toString('hex');
-}
-
-// Check if addresses are same (ignoring network)
-function isSameAddress(addr1: string, addr2: string): boolean {
- try {
- const hash1 = getAddressHash(addr1);
- const hash2 = getAddressHash(addr2);
- return hash1 === hash2;
- } catch {
- return false;
- }
-}
-```
-
-## Advanced validation patterns
-
-### Comprehensive address validator
-
-Create a robust validation system:
-
-```typescript
-class AddressValidator {
- private cache = new Map();
-
- validate(address: string, options?: {
- network?: 'mainnet' | 'testnet';
- allowContracts?: boolean;
- allowMultisig?: boolean;
- }): { valid: boolean; reason?: string } {
- // Check cache
- const cacheKey = `${address}-${JSON.stringify(options)}`;
- if (this.cache.has(cacheKey)) {
- return { valid: this.cache.get(cacheKey)! };
- }
-
- // Basic validation
- if (!validateStacksAddress(address)) {
- return { valid: false, reason: 'Invalid address format' };
- }
-
- const info = getAddressInfo(address);
-
- // Check network if specified
- if (options?.network && info.network !== options.network) {
- return {
- valid: false,
- reason: `Address is for ${info.network}, expected ${options.network}`
- };
- }
-
- // Check contract addresses
- if (info.type === 'contract' && !options?.allowContracts) {
- return { valid: false, reason: 'Contract addresses not allowed' };
- }
-
- // Check multisig
- if (info.type === 'multisig' && !options?.allowMultisig) {
- return { valid: false, reason: 'Multisig addresses not allowed' };
- }
-
- // Cache result
- this.cache.set(cacheKey, true);
-
- return { valid: true };
- }
-
- validateBatch(addresses: string[], options?: any): Map {
- const results = new Map();
-
- for (const address of addresses) {
- const { valid } = this.validate(address, options);
- results.set(address, valid);
- }
-
- return results;
- }
-}
-```
-
-### Address formatting
-
-Format addresses for display:
-
-```typescript
-function formatAddress(
- address: string,
- options?: {
- truncate?: boolean;
- length?: number;
- separator?: string;
- }
-): string {
- if (!validateStacksAddress(address)) {
- return 'Invalid Address';
- }
-
- if (options?.truncate) {
- const length = options.length || 8;
- const start = address.slice(0, length);
- const end = address.slice(-length);
- const separator = options.separator || '...';
- return `${start}${separator}${end}`;
- }
-
- return address;
-}
-
-// Format for display with copy functionality
-function AddressDisplay({ address }: { address: string }) {
- const [copied, setCopied] = useState(false);
-
- const formatted = formatAddress(address, {
- truncate: true,
- length: 6
- });
-
- const copyToClipboard = () => {
- navigator.clipboard.writeText(address);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- };
-
- return (
-
- );
-}
-```
-
-## Security considerations
-
-Implement secure address handling:
-
-```typescript
-// Sanitize user input
-function sanitizeAddress(input: string): string {
- // Remove whitespace and common separators
- return input.trim().replace(/[\s\-_]/g, '');
-}
-
-// Verify address ownership
-async function verifyAddressOwnership(
- address: string,
- signature: string,
- message: string
-): Promise {
- try {
- // Verify the signature matches the address
- const verified = verifyMessageSignature({
- message,
- signature,
- publicKey: await getPublicKeyFromAddress(address),
- });
-
- return verified;
- } catch {
- return false;
- }
-}
-
-// Validate address for specific use case
-function validateRecipientAddress(
- address: string,
- options: {
- blockList?: string[];
- allowList?: string[];
- requireMainnet?: boolean;
- }
-): { valid: boolean; reason?: string } {
- // Check blocklist
- if (options.blockList?.includes(address)) {
- return { valid: false, reason: 'Address is blocked' };
- }
-
- // Check allowlist
- if (options.allowList && !options.allowList.includes(address)) {
- return { valid: false, reason: 'Address not in allowlist' };
- }
-
- // Check network
- const info = getAddressInfo(address);
- if (options.requireMainnet && info.network !== 'mainnet') {
- return { valid: false, reason: 'Mainnet address required' };
- }
-
- return { valid: true };
-}
-```
-
-## Testing utilities
-
-Test address validation:
-
-```typescript
-import { describe, it, expect } from 'vitest';
-
-describe('Address validation', () => {
- const validAddresses = [
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY',
- 'ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC',
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.my-contract',
- ];
-
- const invalidAddresses = [
- 'invalid',
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZ', // Too short
- 'XP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY', // Wrong prefix
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.', // Missing contract
- ];
-
- validAddresses.forEach(address => {
- it(`should validate ${address}`, () => {
- expect(validateStacksAddress(address)).toBe(true);
- });
- });
-
- invalidAddresses.forEach(address => {
- it(`should reject ${address}`, () => {
- expect(validateStacksAddress(address)).toBe(false);
- });
- });
-});
-```
-
-## Best practices
-
-- **Always validate user input**: Never trust addresses from users
-- **Check network compatibility**: Ensure addresses match your network
-- **Handle edge cases**: Contract addresses, multisig, etc.
-- **Cache validation results**: Avoid redundant validation
-- **Provide clear error messages**: Help users fix invalid inputs
-
-## Common mistakes
-
-**Not checking network type**
-
-```typescript
-// Bad: Accepting any valid address
-const isValid = validateStacksAddress(userInput);
-
-// Good: Checking network matches
-const info = getAddressInfo(userInput);
-if (info.network !== 'mainnet') {
- throw new Error('Please use a mainnet address');
-}
-```
-
-**Assuming address format**
-
-```typescript
-// Bad: Assuming standard address
-const [principal, contract] = address.split('.');
-
-// Good: Proper validation
-const parsed = parseContractAddress(address);
-if (!parsed.isValid) {
- throw new Error('Invalid contract address');
-}
-```
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(utils)/encoding-decoding.mdx b/content/docs/en/reference/stacks.js/(utils)/encoding-decoding.mdx
deleted file mode 100644
index b05fb7896..000000000
--- a/content/docs/en/reference/stacks.js/(utils)/encoding-decoding.mdx
+++ /dev/null
@@ -1,518 +0,0 @@
----
-title: Encoding & decoding
-description: Convert between Clarity values and JavaScript types
----
-
-## Overview
-
-Stacks uses Clarity values (CVs) to represent data in smart contracts. When building applications, you'll need to encode JavaScript values into CVs for contract calls and decode CVs back to JavaScript for display. This guide covers all CV types and conversion patterns.
-
-## Basic type conversions
-
-### Integers
-
-Convert between JavaScript numbers and Clarity integers:
-
-```typescript
-import {
- intCV,
- uintCV,
- cvToValue,
- cvToJSON
-} from '@stacks/transactions';
-
-// Encoding
-const positiveInt = uintCV(42); // u42
-const negativeInt = intCV(-100); // -100
-const largeUint = uintCV(1000000); // u1000000
-
-// Decoding
-const jsValue = cvToValue(positiveInt); // 42
-const jsonValue = cvToJSON(positiveInt); // { type: 'uint', value: '42' }
-
-// Working with BigInt for large numbers
-const bigNumber = uintCV(BigInt('123456789012345678901234567890'));
-const decoded = cvToValue(bigNumber); // '123456789012345678901234567890'
-```
-
-### Booleans
-
-Simple true/false values:
-
-```typescript
-import { trueCV, falseCV, boolCV } from '@stacks/transactions';
-
-// Encoding
-const clarityTrue = trueCV(); // true
-const clarityFalse = falseCV(); // false
-const fromBoolean = boolCV(true); // true
-
-// Decoding
-const jsBoolean = cvToValue(clarityTrue); // true
-```
-
-### Strings
-
-Handle ASCII and UTF-8 strings:
-
-```typescript
-import {
- stringAsciiCV,
- stringUtf8CV,
- cvToString
-} from '@stacks/transactions';
-
-// ASCII strings (limited character set)
-const asciiString = stringAsciiCV('Hello World');
-const asciiDecoded = cvToValue(asciiString); // 'Hello World'
-
-// UTF-8 strings (full Unicode support)
-const utf8String = stringUtf8CV('Hello 世界! 🌍');
-const utf8Decoded = cvToValue(utf8String); // 'Hello 世界! 🌍'
-
-// Direct string extraction
-const directString = cvToString(utf8String); // 'Hello 世界! 🌍'
-```
-
-### Principals
-
-Encode Stacks addresses and contract principals:
-
-```typescript
-import {
- standardPrincipalCV,
- contractPrincipalCV,
- cvToValue
-} from '@stacks/transactions';
-
-// Standard principal (user address)
-const userPrincipal = standardPrincipalCV('SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY');
-
-// Contract principal
-const contractPrincipal = contractPrincipalCV(
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY',
- 'my-contract'
-);
-
-// Decoding
-const address = cvToValue(userPrincipal);
-// 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY'
-
-const contract = cvToValue(contractPrincipal);
-// 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.my-contract'
-```
-
-## Complex type handling
-
-### Buffers
-
-Work with binary data:
-
-```typescript
-import {
- bufferCV,
- bufferCVFromString,
- cvToValue
-} from '@stacks/transactions';
-
-// From hex string
-const hexBuffer = bufferCV(Buffer.from('deadbeef', 'hex'));
-
-// From UTF-8 string
-const stringBuffer = bufferCVFromString('Hello Buffer');
-
-// From byte array
-const byteBuffer = bufferCV(new Uint8Array([1, 2, 3, 4]));
-
-// Decoding returns hex string
-const decoded = cvToValue(hexBuffer); // '0xdeadbeef'
-
-// Get raw buffer
-const rawBuffer = hexBuffer.buffer; // Buffer instance
-```
-
-### Optional values
-
-Handle Clarity's optional type:
-
-```typescript
-import {
- someCV,
- noneCV,
- cvToValue
-} from '@stacks/transactions';
-
-// Some value (contains a value)
-const someValue = someCV(uintCV(42)); // (some u42)
-const someString = someCV(stringUtf8CV('hi')); // (some u"hi")
-
-// None value (no value)
-const noneValue = noneCV(); // none
-
-// Decoding
-const decodedSome = cvToValue(someValue); // 42
-const decodedNone = cvToValue(noneValue); // null
-
-// Check optional type
-if (someValue.type === ClarityType.OptionalSome) {
- const innerValue = cvToValue(someValue.value);
-}
-```
-
-### Response values
-
-Handle contract response types:
-
-```typescript
-import {
- responseOkCV,
- responseErrorCV,
- cvToValue
-} from '@stacks/transactions';
-
-// Success response
-const okResponse = responseOkCV(uintCV(100)); // (ok u100)
-const okString = responseOkCV(stringUtf8CV('Success')); // (ok u"Success")
-
-// Error response
-const errorResponse = responseErrorCV(uintCV(404)); // (err u404)
-const errorMsg = responseErrorCV(stringUtf8CV('Not found')); // (err u"Not found")
-
-// Decoding and checking
-const result = okResponse;
-if (result.type === ClarityType.ResponseOk) {
- console.log('Success:', cvToValue(result.value));
-} else {
- console.log('Error:', cvToValue(result.value));
-}
-```
-
-### Tuples
-
-Create and decode structured data:
-
-```typescript
-import {
- tupleCV,
- cvToValue,
- cvToJSON
-} from '@stacks/transactions';
-
-// Create tuple
-const userInfo = tupleCV({
- id: uintCV(1),
- name: stringUtf8CV('Alice'),
- balance: uintCV(1000000),
- active: trueCV(),
- metadata: tupleCV({
- created: uintCV(Date.now()),
- tags: listCV([stringAsciiCV('user'), stringAsciiCV('premium')])
- })
-});
-
-// Decode to JavaScript object
-const decoded = cvToValue(userInfo);
-// {
-// id: 1,
-// name: 'Alice',
-// balance: 1000000,
-// active: true,
-// metadata: {
-// created: 1234567890,
-// tags: ['user', 'premium']
-// }
-// }
-
-// Access tuple fields
-const nameCV = userInfo.data.name;
-const name = cvToValue(nameCV); // 'Alice'
-```
-
-### Lists
-
-Work with arrays of values:
-
-```typescript
-import {
- listCV,
- cvToValue
-} from '@stacks/transactions';
-
-// List of same type
-const numbers = listCV([uintCV(1), uintCV(2), uintCV(3)]);
-const strings = listCV([
- stringUtf8CV('apple'),
- stringUtf8CV('banana'),
- stringUtf8CV('cherry')
-]);
-
-// List of tuples (common pattern)
-const users = listCV([
- tupleCV({ id: uintCV(1), name: stringUtf8CV('Alice') }),
- tupleCV({ id: uintCV(2), name: stringUtf8CV('Bob') }),
-]);
-
-// Decoding
-const decodedNumbers = cvToValue(numbers); // [1, 2, 3]
-const decodedUsers = cvToValue(users);
-// [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
-
-// Iterate over list
-numbers.list.forEach((cv, index) => {
- console.log(`Item ${index}:`, cvToValue(cv));
-});
-```
-
-## Advanced encoding patterns
-
-### Dynamic type encoding
-
-Build encoders for runtime values:
-
-```typescript
-function encodeValue(value: any): ClarityValue {
- if (typeof value === 'number') {
- return value >= 0 ? uintCV(value) : intCV(value);
- } else if (typeof value === 'string') {
- // Check if valid ASCII
- if (/^[\x00-\x7F]*$/.test(value)) {
- return stringAsciiCV(value);
- }
- return stringUtf8CV(value);
- } else if (typeof value === 'boolean') {
- return boolCV(value);
- } else if (value === null || value === undefined) {
- return noneCV();
- } else if (Array.isArray(value)) {
- return listCV(value.map(encodeValue));
- } else if (typeof value === 'object') {
- const tupleData: { [key: string]: ClarityValue } = {};
- for (const [key, val] of Object.entries(value)) {
- tupleData[key] = encodeValue(val);
- }
- return tupleCV(tupleData);
- }
-
- throw new Error(`Cannot encode value: ${value}`);
-}
-
-// Usage
-const encoded = encodeValue({
- name: 'Alice',
- age: 30,
- tags: ['user', 'admin'],
- active: true
-});
-```
-
-### Type-safe decoding
-
-Create decoders with type validation:
-
-```typescript
-interface UserData {
- id: number;
- name: string;
- balance: number;
- active: boolean;
-}
-
-function decodeUser(cv: ClarityValue): UserData {
- if (cv.type !== ClarityType.Tuple) {
- throw new Error('Expected tuple');
- }
-
- const data = cv.data;
-
- // Validate and extract each field
- if (!data.id || data.id.type !== ClarityType.UInt) {
- throw new Error('Invalid id field');
- }
-
- if (!data.name || (
- data.name.type !== ClarityType.StringASCII &&
- data.name.type !== ClarityType.StringUTF8
- )) {
- throw new Error('Invalid name field');
- }
-
- return {
- id: Number(cvToValue(data.id)),
- name: cvToString(data.name),
- balance: Number(cvToValue(data.balance)),
- active: cvToValue(data.active) as boolean,
- };
-}
-```
-
-### Batch encoding utilities
-
-Encode multiple values efficiently:
-
-```typescript
-class ClarityEncoder {
- static encodeArray(
- items: T[],
- encoder: (item: T) => ClarityValue
- ): ClarityValue {
- return listCV(items.map(encoder));
- }
-
- static encodeTuple>(
- obj: T,
- schema: { [K in keyof T]: (value: T[K]) => ClarityValue }
- ): TupleCV {
- const tupleData: { [key: string]: ClarityValue } = {};
-
- for (const [key, encoder] of Object.entries(schema)) {
- tupleData[key] = encoder(obj[key as keyof T]);
- }
-
- return tupleCV(tupleData);
- }
-
- static encodeOptional(
- value: T | null | undefined,
- encoder: (value: T) => ClarityValue
- ): OptionalCV {
- if (value === null || value === undefined) {
- return noneCV();
- }
- return someCV(encoder(value));
- }
-}
-
-// Usage
-const users = [
- { id: 1, name: 'Alice', balance: 1000 },
- { id: 2, name: 'Bob', balance: 2000 },
-];
-
-const encoded = ClarityEncoder.encodeArray(users, user =>
- ClarityEncoder.encodeTuple(user, {
- id: (id) => uintCV(id),
- name: (name) => stringUtf8CV(name),
- balance: (balance) => uintCV(balance),
- })
-);
-```
-
-## Serialization and deserialization
-
-Work with serialized Clarity values:
-
-```typescript
-import {
- serializeCV,
- deserializeCV,
- cvToHex,
- hexToCV
-} from '@stacks/transactions';
-
-// Serialize to buffer
-const cv = tupleCV({ amount: uintCV(1000), memo: stringUtf8CV('Payment') });
-const serialized = serializeCV(cv); // Buffer
-
-// Convert to hex for storage/transport
-const hex = cvToHex(cv); // '0x0c00000002046d656d6f...'
-
-// Deserialize from hex
-const deserialized = hexToCV(hex);
-const value = cvToValue(deserialized); // { amount: 1000, memo: 'Payment' }
-
-// Work with raw buffers
-const buffer = Buffer.from(hex, 'hex');
-const fromBuffer = deserializeCV(buffer);
-```
-
-## Common conversion patterns
-
-### Contract call arguments
-
-Prepare arguments for contract calls:
-
-```typescript
-function prepareTransferArgs(
- recipient: string,
- amount: number,
- memo?: string
-): ClarityValue[] {
- const args = [
- standardPrincipalCV(recipient),
- uintCV(amount),
- ];
-
- if (memo) {
- args.push(someCV(stringUtf8CV(memo)));
- } else {
- args.push(noneCV());
- }
-
- return args;
-}
-
-// Usage in contract call
-const functionArgs = prepareTransferArgs(
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY',
- 1000000,
- 'Monthly payment'
-);
-```
-
-### Response handling
-
-Process contract responses:
-
-```typescript
-function handleContractResponse(response: ClarityValue): {
- success: boolean;
- data: any;
- error?: string;
-} {
- if (response.type === ClarityType.ResponseOk) {
- return {
- success: true,
- data: cvToValue(response.value),
- };
- } else if (response.type === ClarityType.ResponseErr) {
- const errorValue = cvToValue(response.value);
- return {
- success: false,
- data: null,
- error: typeof errorValue === 'string' ? errorValue : `Error: ${errorValue}`,
- };
- }
-
- throw new Error('Invalid response type');
-}
-```
-
-## Best practices
-
-- **Validate types**: Always check CV types before decoding
-- **Handle edge cases**: Consider null, undefined, and empty values
-- **Use appropriate string types**: ASCII for simple text, UTF-8 for international
-- **Preserve precision**: Use BigInt for large numbers
-- **Type narrowing**: Use TypeScript type guards for safety
-
-## Common mistakes
-
-**String type confusion**
-
-```typescript
-// Bad: Using ASCII for Unicode
-const bad = stringAsciiCV('Hello 世界'); // Will throw error
-
-// Good: Use UTF-8 for Unicode
-const good = stringUtf8CV('Hello 世界');
-```
-
-**Number overflow**
-
-```typescript
-// Bad: JavaScript number too large
-const bad = uintCV(Number.MAX_SAFE_INTEGER + 1); // Precision loss
-
-// Good: Use BigInt
-const good = uintCV(BigInt('9007199254740992'));
-```
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/(utils)/meta.json b/content/docs/en/reference/stacks.js/(utils)/meta.json
deleted file mode 100644
index e7ed428ff..000000000
--- a/content/docs/en/reference/stacks.js/(utils)/meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "title": "Common Utilities",
- "defaultOpen": false,
- "pages": ["encoding-decoding", "network-configuration", "address-validation", "unit-conversion"]
-}
diff --git a/content/docs/en/reference/stacks.js/(utils)/network-configuration.mdx b/content/docs/en/reference/stacks.js/(utils)/network-configuration.mdx
deleted file mode 100644
index de8aa8dce..000000000
--- a/content/docs/en/reference/stacks.js/(utils)/network-configuration.mdx
+++ /dev/null
@@ -1,537 +0,0 @@
----
-title: Network configuration
-description: Configure and customize Stacks network connections
----
-
-## Overview
-
-Stacks.js supports multiple networks—mainnet for production, testnet for development, and custom networks for local testing. Proper network configuration ensures your app connects to the right blockchain instance with optimal settings.
-
-## Basic network setup
-
-Configure standard networks:
-
-```typescript
-import {
- StacksMainnet,
- StacksTestnet,
- StacksMocknet
-} from '@stacks/network';
-
-// Production network
-const mainnet = new StacksMainnet();
-console.log('Mainnet API:', mainnet.coreApiUrl);
-// https://api.hiro.so
-
-// Test network
-const testnet = new StacksTestnet();
-console.log('Testnet API:', testnet.coreApiUrl);
-// https://api.testnet.hiro.so
-
-// Local development network
-const mocknet = new StacksMocknet();
-console.log('Mocknet API:', mocknet.coreApiUrl);
-// http://localhost:3999
-```
-
-## Custom network configuration
-
-Create networks with custom endpoints:
-
-```typescript
-import { StacksNetwork } from '@stacks/network';
-
-// Custom mainnet configuration
-const customMainnet = new StacksMainnet({
- url: 'https://my-custom-node.com',
- fetchFn: fetch, // Custom fetch implementation
-});
-
-// Custom testnet with specific endpoints
-const customTestnet = new StacksTestnet({
- url: 'https://my-testnet-node.com:3999',
-});
-
-// Fully custom network
-class CustomNetwork extends StacksNetwork {
- constructor() {
- super({
- url: 'https://custom-stacks-node.com',
- networkType: 'mainnet', // or 'testnet', 'mocknet'
- });
- }
-
- // Override methods as needed
- getBroadcastApiUrl() {
- return `${this.coreApiUrl}/custom/broadcast`;
- }
-}
-```
-
-## Environment-based configuration
-
-Manage networks across environments:
-
-```typescript
-// config/network.ts
-import {
- StacksNetwork,
- StacksMainnet,
- StacksTestnet,
- StacksMocknet
-} from '@stacks/network';
-
-interface NetworkConfig {
- network: StacksNetwork;
- apiUrl: string;
- wsUrl?: string;
- explorerUrl: string;
- faucetUrl?: string;
-}
-
-const configs: Record = {
- production: {
- network: new StacksMainnet(),
- apiUrl: 'https://api.hiro.so',
- wsUrl: 'wss://api.hiro.so',
- explorerUrl: 'https://explorer.hiro.so',
- },
- staging: {
- network: new StacksTestnet(),
- apiUrl: 'https://api.testnet.hiro.so',
- wsUrl: 'wss://api.testnet.hiro.so',
- explorerUrl: 'https://explorer.hiro.so/?chain=testnet',
- faucetUrl: 'https://api.testnet.hiro.so/extended/v1/faucets/stx',
- },
- development: {
- network: new StacksMocknet(),
- apiUrl: 'http://localhost:3999',
- explorerUrl: 'http://localhost:8000',
- },
-};
-
-export function getNetworkConfig(): NetworkConfig {
- const env = process.env.NODE_ENV || 'development';
- return configs[env];
-}
-
-// Usage
-const { network, apiUrl } = getNetworkConfig();
-```
-
-## Network detection and validation
-
-Detect and validate network connections:
-
-```typescript
-async function detectNetwork(url: string): Promise<'mainnet' | 'testnet' | 'unknown'> {
- try {
- const response = await fetch(`${url}/v2/info`);
- const info = await response.json();
-
- // Check network ID
- if (info.network_id === 1) {
- return 'mainnet';
- } else if (info.network_id === 2147483648) {
- return 'testnet';
- }
-
- return 'unknown';
- } catch (error) {
- console.error('Failed to detect network:', error);
- return 'unknown';
- }
-}
-
-// Validate network matches expectation
-async function validateNetwork(
- network: StacksNetwork,
- expected: 'mainnet' | 'testnet'
-): Promise {
- const detected = await detectNetwork(network.coreApiUrl);
-
- if (detected !== expected) {
- console.warn(`Network mismatch! Expected ${expected}, got ${detected}`);
- return false;
- }
-
- return true;
-}
-```
-
-## Advanced network features
-
-### Custom headers and authentication
-
-Add authentication or custom headers:
-
-```typescript
-class AuthenticatedNetwork extends StacksMainnet {
- private apiKey: string;
-
- constructor(apiKey: string) {
- super();
- this.apiKey = apiKey;
- }
-
- createFetchFn(): FetchFn {
- return (url: string, init?: RequestInit) => {
- const headers = {
- ...init?.headers,
- 'x-api-key': this.apiKey,
- 'x-client-version': '1.0.0',
- };
-
- return fetch(url, { ...init, headers });
- };
- }
-}
-
-// Usage
-const network = new AuthenticatedNetwork(process.env.API_KEY!);
-```
-
-### Request retry and timeout
-
-Implement resilient network requests:
-
-```typescript
-class ResilientNetwork extends StacksTestnet {
- private maxRetries = 3;
- private timeout = 30000; // 30 seconds
-
- createFetchFn(): FetchFn {
- return async (url: string, init?: RequestInit) => {
- for (let attempt = 0; attempt < this.maxRetries; attempt++) {
- try {
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
-
- const response = await fetch(url, {
- ...init,
- signal: controller.signal,
- });
-
- clearTimeout(timeoutId);
-
- if (!response.ok && attempt < this.maxRetries - 1) {
- // Retry on server errors
- if (response.status >= 500) {
- await this.delay(1000 * Math.pow(2, attempt));
- continue;
- }
- }
-
- return response;
- } catch (error) {
- if (attempt === this.maxRetries - 1) throw error;
- await this.delay(1000 * Math.pow(2, attempt));
- }
- }
-
- throw new Error('Max retries exceeded');
- };
- }
-
- private delay(ms: number): Promise {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
-}
-```
-
-## Network-specific configurations
-
-### Configure by chain ID
-
-Set up network based on chain identifier:
-
-```typescript
-function getNetworkByChainId(chainId: number): StacksNetwork {
- switch (chainId) {
- case 1: // Mainnet
- return new StacksMainnet();
- case 2147483648: // Testnet
- return new StacksTestnet();
- default:
- throw new Error(`Unknown chain ID: ${chainId}`);
- }
-}
-
-// Dynamic network from wallet
-async function getNetworkFromWallet(): Promise {
- const userData = userSession.loadUserData();
- const address = userData.profile.stxAddress.testnet;
-
- // Determine network from address prefix
- if (address.startsWith('SP') || address.startsWith('SM')) {
- return new StacksMainnet();
- } else if (address.startsWith('ST') || address.startsWith('SN')) {
- return new StacksTestnet();
- }
-
- throw new Error('Unable to determine network from address');
-}
-```
-
-### Multi-network support
-
-Support multiple networks simultaneously:
-
-```typescript
-class NetworkManager {
- private networks: Map = new Map();
- private currentNetwork: string = 'testnet';
-
- constructor() {
- this.networks.set('mainnet', new StacksMainnet());
- this.networks.set('testnet', new StacksTestnet());
- this.networks.set('devnet', new StacksMocknet());
- }
-
- getNetwork(name?: string): StacksNetwork {
- const networkName = name || this.currentNetwork;
- const network = this.networks.get(networkName);
-
- if (!network) {
- throw new Error(`Unknown network: ${networkName}`);
- }
-
- return network;
- }
-
- setCurrentNetwork(name: string): void {
- if (!this.networks.has(name)) {
- throw new Error(`Unknown network: ${name}`);
- }
- this.currentNetwork = name;
- }
-
- addCustomNetwork(name: string, url: string): void {
- const network = new StacksNetwork({ url });
- this.networks.set(name, network);
- }
-}
-
-// Usage
-const manager = new NetworkManager();
-const mainnet = manager.getNetwork('mainnet');
-manager.setCurrentNetwork('mainnet');
-```
-
-## Network connection monitoring
-
-Monitor network health and status:
-
-```typescript
-class NetworkMonitor {
- private network: StacksNetwork;
- private isHealthy = true;
- private listeners: Set<(healthy: boolean) => void> = new Set();
-
- constructor(network: StacksNetwork) {
- this.network = network;
- this.startMonitoring();
- }
-
- private async startMonitoring() {
- setInterval(async () => {
- try {
- const response = await fetch(
- `${this.network.coreApiUrl}/v2/info`,
- { signal: AbortSignal.timeout(5000) }
- );
-
- const wasHealthy = this.isHealthy;
- this.isHealthy = response.ok;
-
- if (wasHealthy !== this.isHealthy) {
- this.notifyListeners();
- }
- } catch (error) {
- const wasHealthy = this.isHealthy;
- this.isHealthy = false;
-
- if (wasHealthy) {
- this.notifyListeners();
- }
- }
- }, 30000); // Check every 30 seconds
- }
-
- onHealthChange(callback: (healthy: boolean) => void): () => void {
- this.listeners.add(callback);
- return () => this.listeners.delete(callback);
- }
-
- private notifyListeners() {
- this.listeners.forEach(callback => callback(this.isHealthy));
- }
-
- async waitForHealth(timeout = 60000): Promise {
- const start = Date.now();
-
- while (!this.isHealthy && Date.now() - start < timeout) {
- await new Promise(resolve => setTimeout(resolve, 1000));
- }
-
- if (!this.isHealthy) {
- throw new Error('Network unhealthy after timeout');
- }
- }
-}
-```
-
-## WebSocket configuration
-
-Set up real-time connections:
-
-```typescript
-interface WebSocketConfig {
- url: string;
- reconnectInterval: number;
- maxReconnectAttempts: number;
-}
-
-class StacksWebSocketClient {
- private ws: WebSocket | null = null;
- private config: WebSocketConfig;
- private reconnectAttempts = 0;
-
- constructor(network: StacksNetwork) {
- this.config = {
- url: this.getWebSocketUrl(network),
- reconnectInterval: 5000,
- maxReconnectAttempts: 10,
- };
- }
-
- private getWebSocketUrl(network: StacksNetwork): string {
- const apiUrl = network.coreApiUrl;
- return apiUrl.replace('https://', 'wss://').replace('http://', 'ws://');
- }
-
- connect(): void {
- this.ws = new WebSocket(this.config.url);
-
- this.ws.onopen = () => {
- console.log('WebSocket connected');
- this.reconnectAttempts = 0;
- };
-
- this.ws.onclose = () => {
- this.handleReconnect();
- };
-
- this.ws.onerror = (error) => {
- console.error('WebSocket error:', error);
- };
- }
-
- private handleReconnect(): void {
- if (this.reconnectAttempts < this.config.maxReconnectAttempts) {
- setTimeout(() => {
- this.reconnectAttempts++;
- this.connect();
- }, this.config.reconnectInterval);
- }
- }
-
- subscribe(event: string, callback: (data: any) => void): void {
- if (!this.ws) throw new Error('WebSocket not connected');
-
- this.ws.send(JSON.stringify({
- method: 'subscribe',
- params: { event }
- }));
-
- this.ws.onmessage = (message) => {
- const data = JSON.parse(message.data);
- if (data.event === event) {
- callback(data);
- }
- };
- }
-}
-```
-
-## Testing with different networks
-
-Set up tests across networks:
-
-```typescript
-import { describe, it, beforeEach } from 'vitest';
-
-describe('Cross-network tests', () => {
- const networks = [
- { name: 'mainnet', network: new StacksMainnet() },
- { name: 'testnet', network: new StacksTestnet() },
- ];
-
- networks.forEach(({ name, network }) => {
- describe(`${name} tests`, () => {
- it('should connect to network', async () => {
- const response = await fetch(`${network.coreApiUrl}/v2/info`);
- expect(response.ok).toBe(true);
- });
-
- it('should have correct chain ID', async () => {
- const response = await fetch(`${network.coreApiUrl}/v2/info`);
- const info = await response.json();
-
- if (name === 'mainnet') {
- expect(info.network_id).toBe(1);
- } else {
- expect(info.network_id).toBe(2147483648);
- }
- });
- });
- });
-});
-```
-
-## Best practices
-
-- **Use environment variables**: Never hardcode network URLs
-- **Implement retry logic**: Networks can be temporarily unavailable
-- **Monitor connection health**: Detect and handle network issues
-- **Cache network info**: Reduce redundant API calls
-- **Validate network type**: Ensure you're on the expected network
-
-## Common issues
-
-**CORS errors**
-
-```typescript
-// Configure proxy for development
-const devNetwork = new StacksTestnet({
- url: '/api', // Proxy through your dev server
-});
-
-// Or use CORS-enabled endpoints
-const corsNetwork = new StacksTestnet({
- url: 'https://api.testnet.hiro.so',
-});
-```
-
-**Timeout handling**
-
-```typescript
-// Add timeout to all requests
-class TimeoutNetwork extends StacksMainnet {
- async fetchWithTimeout(url: string, timeout = 30000): Promise {
- const controller = new AbortController();
- const id = setTimeout(() => controller.abort(), timeout);
-
- try {
- const response = await fetch(url, {
- signal: controller.signal,
- });
- clearTimeout(id);
- return response;
- } catch (error) {
- clearTimeout(id);
- throw new Error(`Request timeout: ${url}`);
- }
- }
-}
-```
diff --git a/content/docs/en/reference/stacks.js/(utils)/unit-conversion.mdx b/content/docs/en/reference/stacks.js/(utils)/unit-conversion.mdx
deleted file mode 100644
index 5928c4283..000000000
--- a/content/docs/en/reference/stacks.js/(utils)/unit-conversion.mdx
+++ /dev/null
@@ -1,219 +0,0 @@
----
-title: Unit conversion
-description: Convert between STX, microSTX, and other units
----
-
-Learn how to convert between different unit denominations in Stacks. The blockchain uses microSTX as its base unit, where 1 STX = 1,000,000 microSTX. Proper unit conversion is essential for displaying amounts to users and processing transactions.
-
-## Basic conversions
-
-Convert between STX and microSTX using simple conversion functions.
-
-```typescript
-// Convert STX to microSTX
-function stxToMicroStx(stx: number | string): bigint {
- const stxAmount = typeof stx === 'string' ? parseFloat(stx) : stx;
- return BigInt(Math.floor(stxAmount * 1_000_000));
-}
-
-// Convert microSTX to STX
-function microStxToStx(microStx: number | bigint | string): string {
- const amount = BigInt(microStx);
- const stx = Number(amount) / 1_000_000;
- return stx.toFixed(6).replace(/\.?0+$/, '');
-}
-
-// Usage examples
-const microStx = stxToMicroStx(1.5); // 1500000n
-const stx = microStxToStx(1500000); // "1.5"
-```
-
-## Precision-safe handling
-
-Handle large numbers without precision loss using BigInt operations.
-
-```typescript
-class StxConverter {
- static readonly MICROSTX_PER_STX = 1_000_000n;
-
- static toMicroStx(amount: string | number, decimals = 6): bigint {
- const amountStr = amount.toString();
- const [whole, decimal = ''] = amountStr.split('.');
- const paddedDecimal = decimal.padEnd(decimals, '0').slice(0, decimals);
- return BigInt(whole + paddedDecimal);
- }
-
- static toStx(microStx: bigint | string | number): string {
- const amount = BigInt(microStx);
- const isNegative = amount < 0n;
- const absoluteAmount = isNegative ? -amount : amount;
-
- const str = absoluteAmount.toString().padStart(7, '0');
- const whole = str.slice(0, -6) || '0';
- const decimal = str.slice(-6);
-
- let result = `${whole}.${decimal}`.replace(/\.?0+$/, '');
- return isNegative ? `-${result}` : result;
- }
-}
-
-// Precise conversion examples
-const precise1 = StxConverter.toMicroStx('123.456789'); // 123456789n
-const precise2 = StxConverter.toStx(123456789n); // "123.456789"
-```
-
-## Token conversions
-
-Handle tokens with different decimal places using a flexible converter class.
-
-```typescript
-interface TokenInfo {
- decimals: number;
- symbol: string;
- name: string;
-}
-
-class TokenConverter {
- constructor(private tokenInfo: TokenInfo) {}
-
- toSmallestUnit(amount: string | number): bigint {
- if (typeof amount === 'string') {
- const [whole, decimal = ''] = amount.split('.');
- const paddedDecimal = decimal
- .padEnd(this.tokenInfo.decimals, '0')
- .slice(0, this.tokenInfo.decimals);
- return BigInt(whole + paddedDecimal);
- }
-
- const multiplier = 10n ** BigInt(this.tokenInfo.decimals);
- return BigInt(Math.floor(amount * Number(multiplier)));
- }
-
- fromSmallestUnit(amount: bigint | string): string {
- const value = BigInt(amount);
- const divisor = 10n ** BigInt(this.tokenInfo.decimals);
- const whole = value / divisor;
- const remainder = value % divisor;
-
- if (remainder === 0n) return whole.toString();
-
- const decimal = remainder
- .toString()
- .padStart(this.tokenInfo.decimals, '0')
- .replace(/0+$/, '');
-
- return `${whole}.${decimal}`;
- }
-}
-
-// Different token examples
-const usdc = new TokenConverter({ decimals: 6, symbol: 'USDC', name: 'USD Coin' });
-const btc = new TokenConverter({ decimals: 8, symbol: 'BTC', name: 'Bitcoin' });
-
-const usdcAmount = usdc.toSmallestUnit('100.50'); // 100500000n
-const btcAmount = btc.toSmallestUnit('0.00123456'); // 123456n
-```
-
-## Display formatting
-
-Format amounts for user interfaces with localization support.
-
-```typescript
-class StxFormatter {
- static format(microStx: bigint, options?: {
- decimals?: number;
- locale?: string;
- symbol?: boolean;
- }): string {
- const stx = StxConverter.toStx(microStx);
- const number = parseFloat(stx);
-
- const formatted = new Intl.NumberFormat(options?.locale || 'en-US', {
- minimumFractionDigits: 0,
- maximumFractionDigits: options?.decimals ?? 6,
- }).format(number);
-
- return options?.symbol ? `${formatted} STX` : formatted;
- }
-
- static compact(microStx: bigint): string {
- const stx = Number(StxConverter.toStx(microStx));
-
- if (stx >= 1_000_000) {
- return `${(stx / 1_000_000).toFixed(2)}M STX`;
- } else if (stx >= 1_000) {
- return `${(stx / 1_000).toFixed(2)}K STX`;
- }
-
- return this.format(microStx, { decimals: 6, symbol: true });
- }
-}
-
-// Formatting examples
-const formatted = StxFormatter.format(123456789n, {
- decimals: 2,
- symbol: true
-}); // "123.46 STX"
-
-const compact = StxFormatter.compact(1234567890000n); // "1.23K STX"
-```
-
-## Input validation
-
-Validate and sanitize user input for amount fields.
-
-```typescript
-class AmountInput {
- static validate(input: string, options?: {
- decimals?: number;
- min?: string;
- max?: string;
- }): { valid: boolean; error?: string } {
- // Check format
- if (!/^\d*\.?\d*$/.test(input)) {
- return { valid: false, error: 'Invalid number format' };
- }
-
- // Check decimal places
- const parts = input.split('.');
- if (parts[1] && parts[1].length > (options?.decimals || 6)) {
- return { valid: false, error: `Maximum ${options?.decimals || 6} decimal places` };
- }
-
- // Check range
- if (options?.min) {
- const value = parseFloat(input);
- if (value < parseFloat(options.min)) {
- return { valid: false, error: `Minimum amount is ${options.min}` };
- }
- }
-
- return { valid: true };
- }
-
- static sanitize(input: string, decimals = 6): string {
- let sanitized = input.replace(/[^\d.]/g, '');
- const parts = sanitized.split('.');
-
- if (parts.length > 2) {
- sanitized = parts[0] + '.' + parts.slice(1).join('');
- }
-
- if (parts[1] && parts[1].length > decimals) {
- sanitized = parts[0] + '.' + parts[1].slice(0, decimals);
- }
-
- return sanitized;
- }
-}
-
-// Validation examples
-const result1 = AmountInput.validate('123.456', {
- decimals: 6,
- min: '0.000001'
-}); // { valid: true }
-
-const result2 = AmountInput.validate('123.4567890', {
- decimals: 6
-}); // { valid: false, error: 'Maximum 6 decimal places' }
-```
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/index.mdx b/content/docs/en/reference/stacks.js/index.mdx
deleted file mode 100644
index 1ca9db3e3..000000000
--- a/content/docs/en/reference/stacks.js/index.mdx
+++ /dev/null
@@ -1,74 +0,0 @@
----
-title: Stacks.js
-sidebarTitle: Overview
-description: A JavaScript/TypeScript SDK for building applications on the Stacks blockchain.
-llm: false
----
-
-## Overview
-
-Stacks.js is a collection of JavaScript libraries that enable you to build web applications on the Stacks blockchain. From wallet authentication to smart contract interactions.
-
-To explore Stacks.js with AI, copy and paste [llms.txt](/reference/stacks.js/llms.txt) into your LLM of choice.
-
-## Key features
-
-- **Transaction construction** - Build and broadcast all transaction types with type-safe APIs
-- **Smart contract interaction** - Deploy contracts and call functions with automatic encoding
-- **Wallet integration** - Connect to Leather, Xverse, and other Stacks wallets seamlessly
-- **Post-conditions** - Protect users with built-in asset transfer validations
-
-## Installation
-
-Stacks.js is separated into focused packages published under the `@stacks` scope. Install only what you need:
-
-
- ```terminal !! transactions
- $ npm install @stacks/transactions
- ```
-
- ```terminal !! connect
- $ npm install @stacks/connect
- ```
-
- ```terminal !! network
- $ npm install @stacks/network
- ```
-
- ```terminal !! common
- $ npm install @stacks/common
- ```
-
-
-
-
- Available packages
-
- - `@stacks/api`
- - `@stacks/auth`
- - `@stacks/encryption`
- - `@stacks/network`
- - `@stacks/stacking`
- - `@stacks/transactions`
- - `@stacks/bns`
- - `@stacks/common`
- - `@stacks/profile`
- - `@stacks/storage`
- - `@stacks/wallet-sdk`
-
-
-
-
-
-## Next steps
-
-:::next-steps
-- [Connect wallet](/reference/stacks.js/connect-wallet): Add wallet authentication
-- [Build transactions](/reference/stacks.js/build-transactions): Build and broadcast transactions
-:::
-
-:::callout
-type: help
-### Need help building with Stacks.js?
-Reach out to us on the **#stacks-js** channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET.
-:::
diff --git a/content/docs/en/reference/stacks.js/meta.json b/content/docs/en/reference/stacks.js/meta.json
deleted file mode 100644
index 61a619baa..000000000
--- a/content/docs/en/reference/stacks.js/meta.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "title": "Stacks.js",
- "root": true,
- "pages": [
- "---Stacks.js---",
- "index",
- "...(overview)",
- "---Local accounts---",
- "...(local-accounts)",
- "---Stacks Connect---",
- "...(connect)",
- "---Post-conditions---",
- "...(post-conditions)",
- "---Integrations---",
- "...(integrations)",
- "---Reference---",
- "...packages"
- ]
-}
diff --git a/content/docs/en/reference/stacks.js/packages/connect.mdx b/content/docs/en/reference/stacks.js/packages/connect.mdx
deleted file mode 100644
index 4c6ffacd7..000000000
--- a/content/docs/en/reference/stacks.js/packages/connect.mdx
+++ /dev/null
@@ -1,355 +0,0 @@
----
-title: '@stacks/connect'
-description: Authenticate users and interact with Stacks wallets in web applications.
----
-
-The `@stacks/connect` package provides a simple interface for connecting web applications to Stacks wallets, enabling user authentication, transaction signing, and message signing capabilities.
-
-## Installation
-
-```package-install
-@stacks/connect
-```
-
-## Connection functions
-
-### connect [#connect]
-
-`connect` initiates a wallet connection and stores user addresses in local storage.
-
-### Signature
-
-```typescript
-function connect(options?: ConnectOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `options` | `ConnectOptions` | No | Configuration options for connection |
-
-### Examples
-
-#### Basic connection
-
-```typescript
-import { connect } from '@stacks/connect';
-
-const response = await connect();
-// Response contains user addresses stored in local storage
-```
-
-#### Connection with options
-
-```typescript
-const response = await connect({
- forceWalletSelect: true,
- approvedProviderIds: ['LeatherProvider', 'xverse']
-});
-```
-
-### isConnected [#isConnected]
-
-`isConnected` checks if a wallet is currently connected.
-
-```typescript
-import { isConnected } from '@stacks/connect';
-
-if (isConnected()) {
- console.log('Wallet is connected');
-}
-```
-
-### disconnect [#disconnect]
-
-`disconnect` clears the connection state and local storage.
-
-```typescript
-import { disconnect } from '@stacks/connect';
-
-disconnect(); // Clears wallet connection
-```
-
-### getLocalStorage [#getLocalStorage]
-
-`getLocalStorage` retrieves stored connection data.
-
-```typescript
-import { getLocalStorage } from '@stacks/connect';
-
-const data = getLocalStorage();
-// {
-// "addresses": {
-// "stx": [{ "address": "SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN" }],
-// "btc": [{ "address": "bc1pp3ha248m0mnaevhp0txfxj5xaxmy03h0j7zuj2upg34mt7s7e32q7mdfae" }]
-// }
-// }
-```
-
-## Request method
-
-### request [#request]
-
-`request` is the primary method for interacting with connected wallets.
-
-### Signature
-
-```typescript
-function request(
- options: RequestOptions | undefined,
- method: T,
- params?: MethodParams[T]
-): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `options` | `RequestOptions` | No | Request configuration options |
-| `method` | `StacksMethod` | Yes | Method to call on the wallet |
-| `params` | `MethodParams[T]` | Depends on method | Parameters for the method |
-
-### Request options
-
-| Name | Type | Default | Description |
-|------|------|---------|-------------|
-| `provider` | `StacksProvider` | Auto-detect | Custom provider instance |
-| `forceWalletSelect` | `boolean` | `false` | Force wallet selection modal |
-| `persistWalletSelect` | `boolean` | `true` | Persist wallet selection |
-| `enableOverrides` | `boolean` | `true` | Enable compatibility fixes |
-| `enableLocalStorage` | `boolean` | `true` | Store addresses locally |
-| `approvedProviderIds` | `string[]` | All providers | Filter available wallets |
-
-### Examples
-
-#### Basic request
-
-```typescript
-import { request } from '@stacks/connect';
-
-const addresses = await request('getAddresses');
-```
-
-#### Request with options
-
-```typescript
-const response = await request(
- { forceWalletSelect: true },
- 'stx_transferStx',
- {
- amount: '1000000', // 1 STX in microSTX
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159'
- }
-);
-```
-
-## Wallet methods
-
-### getAddresses [#getAddresses]
-
-`getAddresses` retrieves Bitcoin and Stacks addresses from the wallet.
-
-```typescript
-const response = await request('getAddresses');
-// {
-// "addresses": [
-// {
-// "address": "bc1pp3ha248m0mnaevhp0txfxj5xaxmy03h0j7zuj2upg34mt7s7e32q7mdfae",
-// "publicKey": "062bd2c825300d74f4f9feb6b2fec2590beac02b8938f0fc042a34254581ee69"
-// },
-// {
-// "address": "SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN",
-// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cdea520f08c0cc68584a96e8ac19d8d304"
-// }
-// ]
-// }
-```
-
-### sendTransfer [#sendTransfer]
-
-`sendTransfer` sends Bitcoin to one or more recipients.
-
-```typescript
-const response = await request('sendTransfer', {
- recipients: [
- {
- address: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4',
- amount: '1000' // Amount in satoshis
- },
- {
- address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
- amount: '2000'
- }
- ]
-});
-// { "txid": "0x1234..." }
-```
-
-### signPsbt [#signPsbt]
-
-`signPsbt` signs a partially signed Bitcoin transaction.
-
-```typescript
-const response = await request('signPsbt', {
- psbt: 'cHNidP...', // Base64 encoded PSBT
- signInputs: [{ index: 0, address }], // Optional: specify inputs to sign
- broadcast: false // Optional: broadcast after signing
-});
-// {
-// "psbt": "cHNidP...", // Signed PSBT
-// "txid": "0x1234..." // If broadcast is true
-// }
-```
-
-## Stacks-specific methods
-
-### stx_transferStx [#stx_transferStx]
-
-`stx_transferStx` transfers STX tokens between addresses.
-
-```typescript
-const response = await request('stx_transferStx', {
- amount: '1000000', // Amount in microSTX (1 STX = 1,000,000 microSTX)
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- memo: 'Payment for services', // Optional
- network: 'mainnet' // Optional, defaults to mainnet
-});
-// { "txid": "0x1234..." }
-```
-
-### stx_callContract [#stx_callContract]
-
-`stx_callContract` calls a public function on a smart contract.
-
-```typescript
-import { Cl } from '@stacks/transactions';
-
-const response = await request('stx_callContract', {
- contract: 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.hello-world',
- functionName: 'say-hi',
- functionArgs: [Cl.stringUtf8('Hello!')],
- network: 'mainnet'
-});
-// { "txid": "0x1234..." }
-```
-
-### stx_deployContract [#stx_deployContract]
-
-`stx_deployContract` deploys a new smart contract.
-
-```typescript
-const response = await request('stx_deployContract', {
- name: 'my-contract',
- clarityCode: `(define-public (say-hi (name (string-utf8 50)))
- (ok (concat "Hello, " name "!"))
- )`,
- clarityVersion: '2', // Optional
- network: 'testnet'
-});
-// { "txid": "0x1234..." }
-```
-
-### stx_signMessage [#stx_signMessage]
-
-`stx_signMessage` signs a plain text message.
-
-```typescript
-const response = await request('stx_signMessage', {
- message: 'Hello, World!'
-});
-// {
-// "signature": "0x1234...",
-// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cdea520f08c0cc68584a96e8ac19d8d304"
-// }
-```
-
-### stx_signStructuredMessage [#stx_signStructuredMessage]
-
-`stx_signStructuredMessage` signs a structured Clarity message following SIP-018.
-
-```typescript
-import { Cl } from '@stacks/transactions';
-
-const message = Cl.tuple({
- action: Cl.stringAscii('transfer'),
- amount: Cl.uint(1000000n)
-});
-
-const domain = Cl.tuple({
- name: Cl.stringAscii('MyApp'),
- version: Cl.stringAscii('1.0.0'),
- 'chain-id': Cl.uint(1) // mainnet
-});
-
-const response = await request('stx_signStructuredMessage', {
- message,
- domain
-});
-// {
-// "signature": "0x1234...",
-// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cdea520f08c0cc68584a96e8ac19d8d304"
-// }
-```
-
-### stx_getAccounts [#stx_getAccounts]
-
-`stx_getAccounts` retrieves detailed account information including Gaia configuration.
-
-```typescript
-const response = await request('stx_getAccounts');
-// {
-// "addresses": [{
-// "address": "SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN",
-// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cd...",
-// "gaiaHubUrl": "https://hub.hiro.so",
-// "gaiaAppKey": "0488ade4040658015580000000dc81e3a5..."
-// }]
-// }
-```
-
-## Error handling
-
-Handle wallet errors using standard Promise error handling patterns.
-
-```typescript
-try {
- const response = await request('stx_transferStx', {
- amount: '1000000',
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159'
- });
- console.log('Transaction successful:', response.txid);
-} catch (error) {
- console.error('Transaction failed:', error);
-}
-```
-
-## Advanced usage
-
-### requestRaw [#requestRaw]
-
-`requestRaw` provides direct access to wallet providers without compatibility features.
-
-### Signature
-
-```typescript
-function requestRaw(
- provider: StacksProvider,
- method: T,
- params?: MethodParams[T]
-): Promise
-```
-
-### Example
-
-```typescript
-import { requestRaw } from '@stacks/connect';
-
-const provider = window.StacksProvider;
-const response = await requestRaw(provider, 'getAddresses');
-```
-
-## Migration notes
-
-Version 8.x.x implements [SIP-030](https://github.com/janniks/sips/blob/main/sips/sip-030/sip-030-wallet-interface.md) wallet standards. For legacy JWT-based authentication, use version 7.10.1.
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/packages/meta.json b/content/docs/en/reference/stacks.js/packages/meta.json
deleted file mode 100644
index 921fd97ce..000000000
--- a/content/docs/en/reference/stacks.js/packages/meta.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "title": "Packages",
- "pages": ["connect", "transactions", "network", "sbtc"]
-}
diff --git a/content/docs/en/reference/stacks.js/packages/network.mdx b/content/docs/en/reference/stacks.js/packages/network.mdx
deleted file mode 100644
index 2c95a041f..000000000
--- a/content/docs/en/reference/stacks.js/packages/network.mdx
+++ /dev/null
@@ -1,163 +0,0 @@
----
-title: '@stacks/network'
-description: Network configuration constants and utilities for Stacks.
----
-
-The `@stacks/network` package exports network configurations and helper functions for working with different Stacks networks.
-
-## Installation
-
-```package-install
-@stacks/network
-```
-
-## Network constants
-
-### STACKS_MAINNET
-
-`STACKS_MAINNET` provides the mainnet network configuration.
-
-```typescript
-import { STACKS_MAINNET } from '@stacks/network';
-
-console.log(STACKS_MAINNET);
-// {
-// chainId: 1,
-// transactionVersion: 0,
-// peerNetworkId: 385875968,
-// magicBytes: "X2",
-// bootAddress: "SP000000000000000000002Q6VF78",
-// addressVersion: {
-// singleSig: 22,
-// multiSig: 20,
-// },
-// client: {
-// baseUrl: "https://api.mainnet.hiro.so",
-// },
-// }
-```
-
-### STACKS_TESTNET
-
-`STACKS_TESTNET` provides the testnet network configuration.
-
-```typescript
-import { STACKS_TESTNET } from '@stacks/network';
-
-console.log(STACKS_TESTNET.chainId); // 2147483648
-```
-
-### STACKS_DEVNET / STACKS_MOCKNET
-
-`STACKS_DEVNET` provides the devnet network configuration.
-
-```typescript
-import { STACKS_DEVNET, STACKS_MOCKNET } from '@stacks/network';
-
-// Use in transactions
-import { makeSTXTokenTransfer } from '@stacks/transactions';
-
-const tx = await makeSTXTokenTransfer({
- network: STACKS_DEVNET, // or STACKS_MOCKNET
- // ... other options
-});
-```
-
-## networkFromName [#networkFromName]
-
-`networkFromName` returns a network configuration for a given name string.
-
-### Signature
-
-```typescript
-function networkFromName(name: 'mainnet' | 'testnet' | 'devnet' | 'mocknet'): StacksNetwork
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `name` | `'mainnet' \| 'testnet' \| 'devnet' \| 'mocknet'` | Yes | Network name |
-
-### Examples
-
-```typescript
-import { networkFromName } from '@stacks/network';
-
-const mainnet = networkFromName('mainnet'); // Same as STACKS_MAINNET
-const testnet = networkFromName('testnet'); // Same as STACKS_TESTNET
-const devnet = networkFromName('devnet'); // Same as STACKS_DEVNET
-const mocknet = networkFromName('mocknet'); // Same as STACKS_MOCKNET
-```
-
-### Using with transactions
-
-```typescript
-import { networkFromName } from '@stacks/network';
-import { makeContractCall } from '@stacks/transactions';
-
-const network = networkFromName('testnet');
-
-const tx = await makeContractCall({
- network,
- contractAddress: 'ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH',
- contractName: 'hello-world',
- functionName: 'say-hi',
- functionArgs: [],
- senderKey: privateKey
-});
-```
-
-## clientFromNetwork [#clientFromNetwork]
-
-`clientFromNetwork` extracts the API client configuration from a network.
-
-### Signature
-
-```typescript
-function clientFromNetwork(network: StacksNetwork): Required
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `network` | `StacksNetwork` | Yes | Network configuration object |
-
-### Example
-
-```typescript
-import { clientFromNetwork, STACKS_MAINNET } from '@stacks/network';
-
-const client = clientFromNetwork(STACKS_MAINNET);
-console.log(client.baseUrl); // 'https://api.mainnet.hiro.so'
-
-// Use with custom fetch
-const customClient = {
- ...client,
- fetch: customFetchFunction
-};
-```
-
-## Network configuration properties
-
-All network constants share these properties:
-
-| Property | Type | Description |
-|----------|------|-------------|
-| `chainId` | number | Unique identifier for the network |
-| `transactionVersion` | number | Transaction serialization version |
-| `peerNetworkId` | number | P2P network identifier |
-| `magicBytes` | string | Network magic bytes for serialization |
-| `bootAddress` | string | Boot contract address |
-
-## Default values
-
-The package also exports default configuration values:
-
-```typescript
-import { DEFAULT_CHAIN_ID, DEFAULT_TRANSACTION_VERSION } from '@stacks/network';
-
-console.log(DEFAULT_CHAIN_ID); // 1
-console.log(DEFAULT_TRANSACTION_VERSION); // 0
-```
diff --git a/content/docs/en/reference/stacks.js/packages/sbtc.mdx b/content/docs/en/reference/stacks.js/packages/sbtc.mdx
deleted file mode 100644
index b8ffa1604..000000000
--- a/content/docs/en/reference/stacks.js/packages/sbtc.mdx
+++ /dev/null
@@ -1,322 +0,0 @@
----
-title: 'sbtc'
-description: Build and manage sBTC deposits and withdrawals on Bitcoin and Stacks.
----
-
-The `sbtc` package provides functions for creating sBTC deposits on Bitcoin and interacting with the sBTC protocol across Bitcoin and Stacks networks.
-
-## Installation
-
-```package-install
-sbtc
-```
-
-## Deposit functions
-
-### buildSbtcDepositAddress [#buildSbtcDepositAddress]
-
-`buildSbtcDepositAddress` creates a Bitcoin address for sBTC deposits with embedded metadata.
-
-### Signature
-
-```typescript
-function buildSbtcDepositAddress(options: DepositAddressOptions): DepositAddress
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `stacksAddress` | `string` | Yes | Stacks address to receive sBTC |
-| `signersPublicKey` | `string` | Yes | Aggregated public key of signers |
-| `maxSignerFee` | `number` | No | Maximum fee for signers (default: 80,000 sats) |
-| `reclaimLockTime` | `number` | No | Lock time for reclaim script (default: 6,000) |
-| `network` | `BitcoinNetwork` | No | Bitcoin network to use (default: MAINNET) |
-
-### Example
-
-```typescript
-import { buildSbtcDepositAddress, SbtcApiClientMainnet } from 'sbtc';
-
-const client = new SbtcApiClientMainnet();
-
-// Build deposit address
-const deposit = buildSbtcDepositAddress({
- stacksAddress: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- signersPublicKey: await client.fetchSignersPublicKey(),
- maxSignerFee: 80_000, // Fee taken from deposit amount
- reclaimLockTime: 6_000
-});
-
-// Send BTC to deposit.address using any Bitcoin wallet
-const txid = await wallet.sendTransfer({
- recipient: deposit.address,
- amount: 1_000_000 // 0.01 BTC
-});
-
-// Notify signers about the deposit
-await client.notifySbtc({ txid, ...deposit });
-```
-
-### buildSbtcDepositTx [#buildSbtcDepositTx]
-
-`buildSbtcDepositTx` creates a complete Bitcoin transaction for sBTC deposits.
-
-### Signature
-
-```typescript
-function buildSbtcDepositTx(options: DepositTxOptions): DepositTransaction
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `amountSats` | `number \| bigint` | Yes | Amount to deposit in satoshis |
-| `stacksAddress` | `string` | Yes | Stacks address to receive sBTC |
-| `signersPublicKey` | `string` | Yes | Aggregated public key of signers |
-| `maxSignerFee` | `number` | No | Maximum fee for signers (default: 80,000 sats) |
-| `reclaimLockTime` | `number` | No | Lock time for reclaim script (default: 144) |
-| `network` | `BitcoinNetwork` | No | Bitcoin network to use |
-
-### Example
-
-```typescript
-import { buildSbtcDepositTx, SbtcApiClientMainnet } from 'sbtc';
-
-const client = new SbtcApiClientMainnet();
-
-// Build deposit transaction
-const deposit = buildSbtcDepositTx({
- amountSats: 100_000,
- stacksAddress: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- signersPublicKey: await client.fetchSignersPublicKey()
-});
-
-// Sign transaction
-deposit.transaction.sign(privateKey);
-deposit.transaction.finalize();
-
-// Broadcast and notify
-const txid = await client.broadcastTx(deposit.transaction);
-await client.notifySbtc(deposit);
-```
-
-### sbtcDepositHelper [#sbtcDepositHelper]
-
-`sbtcDepositHelper` creates a fully-formed deposit transaction from UTXOs.
-
-### Signature
-
-```typescript
-function sbtcDepositHelper(options: DepositHelperOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `amountSats` | `number \| bigint` | Yes | Amount to deposit in satoshis |
-| `stacksAddress` | `string` | Yes | Stacks address to receive sBTC |
-| `signersPublicKey` | `string` | Yes | Aggregated public key of signers |
-| `feeRate` | `number` | Yes | Fee rate in sat/vbyte |
-| `utxos` | `UtxoWithTx[]` | Yes | UTXOs to fund the transaction |
-| `bitcoinChangeAddress` | `string` | Yes | Address for change output |
-| `reclaimPublicKey` | `string` | No | Public key for reclaiming deposits |
-| `reclaimLockTime` | `number` | No | Lock time for reclaim (default: 144) |
-| `maxSignerFee` | `number` | No | Maximum signer fee (default: 80,000) |
-| `network` | `BitcoinNetwork` | No | Bitcoin network (default: MAINNET) |
-
-### Example
-
-```typescript
-import { sbtcDepositHelper, SbtcApiClientMainnet } from 'sbtc';
-
-const client = new SbtcApiClientMainnet();
-const btcAddress = 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4';
-
-// Create complete deposit transaction
-const deposit = await sbtcDepositHelper({
- amountSats: 1_000_000,
- stacksAddress: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- signersPublicKey: await client.fetchSignersPublicKey(),
- feeRate: await client.fetchFeeRate('medium'),
- utxos: await client.fetchUtxos(btcAddress),
- bitcoinChangeAddress: btcAddress
-});
-
-// Sign and broadcast
-deposit.transaction.sign(privateKey);
-deposit.transaction.finalize();
-
-const txid = await client.broadcastTx(deposit.transaction);
-await client.notifySbtc(deposit);
-```
-
-## API clients
-
-### SbtcApiClientMainnet
-
-`SbtcApiClientMainnet` provides mainnet API access for sBTC operations.
-
-```typescript
-import { SbtcApiClientMainnet } from 'sbtc';
-
-const client = new SbtcApiClientMainnet();
-```
-
-### SbtcApiClientTestnet
-
-`SbtcApiClientTestnet` provides testnet API access for sBTC operations.
-
-```typescript
-import { SbtcApiClientTestnet } from 'sbtc';
-
-const client = new SbtcApiClientTestnet();
-```
-
-### SbtcApiClientDevenv
-
-`SbtcApiClientDevenv` provides local development API access.
-
-```typescript
-import { SbtcApiClientDevenv } from 'sbtc';
-
-const client = new SbtcApiClientDevenv();
-```
-
-## Client methods
-
-### fetchSignersPublicKey [#fetchSignersPublicKey]
-
-`fetchSignersPublicKey` retrieves the aggregated public key of sBTC signers.
-
-```typescript
-const publicKey = await client.fetchSignersPublicKey();
-// '02abc123...' (32-byte hex string)
-```
-
-### fetchSignersAddress [#fetchSignersAddress]
-
-`fetchSignersAddress` retrieves the Bitcoin address of sBTC signers.
-
-```typescript
-const address = await client.fetchSignersAddress();
-// 'bc1p...' (p2tr address)
-```
-
-### fetchFeeRate [#fetchFeeRate]
-
-`fetchFeeRate` retrieves current Bitcoin network fee rates.
-
-```typescript
-const feeRate = await client.fetchFeeRate('medium');
-// 15 (sat/vbyte)
-
-// Also supports 'low' and 'high'
-const lowFee = await client.fetchFeeRate('low');
-const highFee = await client.fetchFeeRate('high');
-```
-
-### fetchUtxos [#fetchUtxos]
-
-`fetchUtxos` retrieves unspent transaction outputs for a Bitcoin address.
-
-```typescript
-const utxos = await client.fetchUtxos('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4');
-// Array of UTXOs with transaction data
-```
-
-### broadcastTx [#broadcastTx]
-
-`broadcastTx` broadcasts a Bitcoin transaction to the network.
-
-```typescript
-const txid = await client.broadcastTx(transaction);
-// '0x1234abcd...'
-```
-
-### notifySbtc [#notifySbtc]
-
-`notifySbtc` notifies the sBTC API about a deposit transaction.
-
-```typescript
-const response = await client.notifySbtc({
- txid,
- stacksAddress,
- reclaimScript,
- depositScript
-});
-// { status: 200, statusMessage: 'OK' }
-```
-
-### fetchSbtcBalance [#fetchSbtcBalance]
-
-`fetchSbtcBalance` retrieves the sBTC balance for a Stacks address.
-
-```typescript
-const balance = await client.fetchSbtcBalance('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159');
-// 1000000n (in micro-sBTC)
-```
-
-## Configuration
-
-### Client configuration options
-
-| Name | Type | Description |
-|------|------|-------------|
-| `sbtcContract` | `string` | sBTC contract address |
-| `sbtcApiUrl` | `string` | sBTC API (Emily) base URL |
-| `btcApiUrl` | `string` | Bitcoin API base URL |
-| `stxApiUrl` | `string` | Stacks API base URL |
-
-### Custom client configuration
-
-```typescript
-import { SbtcApiClient } from 'sbtc';
-
-const client = new SbtcApiClient({
- sbtcContract: 'SP000000000000000000002Q6VF78.sbtc',
- sbtcApiUrl: 'https://api.sbtc.tech',
- btcApiUrl: 'https://mempool.space/api',
- stxApiUrl: 'https://api.mainnet.hiro.so'
-});
-```
-
-## Complete deposit example
-
-```typescript
-import { sbtcDepositHelper, SbtcApiClientMainnet } from 'sbtc';
-
-async function depositBtcForSbtc() {
- const client = new SbtcApiClientMainnet();
- const btcAddress = 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4';
- const stxAddress = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
-
- // 1. Create deposit transaction
- const deposit = await sbtcDepositHelper({
- amountSats: 100_000,
- stacksAddress: stxAddress,
- signersPublicKey: await client.fetchSignersPublicKey(),
- feeRate: await client.fetchFeeRate('medium'),
- utxos: await client.fetchUtxos(btcAddress),
- bitcoinChangeAddress: btcAddress
- });
-
- // 2. Sign transaction
- deposit.transaction.sign(privateKey);
- deposit.transaction.finalize();
-
- // 3. Broadcast to Bitcoin network
- const txid = await client.broadcastTx(deposit.transaction);
- console.log('Bitcoin transaction:', txid);
-
- // 4. Notify sBTC signers
- await client.notifySbtc(deposit);
- console.log('Deposit submitted successfully');
-
- // 5. Check sBTC balance (after confirmation)
- const balance = await client.fetchSbtcBalance(stxAddress);
- console.log('sBTC balance:', balance);
-}
-```
\ No newline at end of file
diff --git a/content/docs/en/reference/stacks.js/packages/transactions.mdx b/content/docs/en/reference/stacks.js/packages/transactions.mdx
deleted file mode 100644
index c6bc184ab..000000000
--- a/content/docs/en/reference/stacks.js/packages/transactions.mdx
+++ /dev/null
@@ -1,525 +0,0 @@
----
-title: '@stacks/transactions'
-description: Construct, decode, and broadcast transactions for the Stacks blockchain.
----
-
-The `@stacks/transactions` package provides comprehensive functionality for creating, signing, and broadcasting transactions on the Stacks blockchain, including STX transfers, contract deployments, and contract calls.
-
-## Installation
-
-```package-install
-@stacks/transactions
-```
-
-## Transaction functions
-
-### makeSTXTokenTransfer [#makeSTXTokenTransfer]
-
-`makeSTXTokenTransfer` creates a signed STX token transfer transaction.
-
-### Signature
-
-```typescript
-function makeSTXTokenTransfer(options: SignedTokenTransferOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `recipient` | `string` | Yes | Recipient STX address |
-| `amount` | `bigint` | Yes | Amount to transfer in microSTX |
-| `senderKey` | `string` | Yes | Sender's private key |
-| `network` | `StacksNetwork \| string` | Yes | Network configuration |
-| `memo` | `string` | No | Optional memo field |
-| `fee` | `bigint` | No | Transaction fee in microSTX |
-| `nonce` | `bigint` | No | Account nonce |
-| `anchorMode` | `AnchorMode` | No | Block anchoring mode |
-
-### Examples
-
-#### Basic transfer
-
-```typescript
-import { makeSTXTokenTransfer, broadcastTransaction } from '@stacks/transactions';
-
-const transaction = await makeSTXTokenTransfer({
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- amount: 1000000n, // 1 STX in microSTX
- senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01',
- network: 'mainnet'
-});
-
-const response = await broadcastTransaction({ transaction, network: 'mainnet' });
-console.log(response.txid);
-```
-
-#### Transfer with memo
-
-```typescript
-const transaction = await makeSTXTokenTransfer({
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- amount: 2500000n,
- memo: 'Payment for services',
- senderKey: privateKey,
- network: 'testnet'
-});
-```
-
-### makeUnsignedSTXTokenTransfer [#makeUnsignedSTXTokenTransfer]
-
-`makeUnsignedSTXTokenTransfer` creates an unsigned STX token transfer transaction.
-
-### Signature
-
-```typescript
-function makeUnsignedSTXTokenTransfer(options: UnsignedTokenTransferOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `recipient` | `string` | Yes | Recipient STX address |
-| `amount` | `bigint` | Yes | Amount to transfer in microSTX |
-| `publicKey` | `string` | Yes | Sender's public key |
-| `network` | `StacksNetwork \| string` | Yes | Network configuration |
-| `memo` | `string` | No | Optional memo field |
-| `fee` | `bigint` | No | Transaction fee in microSTX |
-| `nonce` | `bigint` | No | Account nonce |
-
-### Example
-
-```typescript
-import { makeUnsignedSTXTokenTransfer } from '@stacks/transactions';
-
-const unsignedTx = await makeUnsignedSTXTokenTransfer({
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- amount: 1000000n,
- publicKey: publicKeyString,
- network: 'mainnet'
-});
-```
-
-### makeContractDeploy [#makeContractDeploy]
-
-`makeContractDeploy` creates a signed smart contract deployment transaction.
-
-### Signature
-
-```typescript
-function makeContractDeploy(options: SignedContractDeployOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `contractName` | `string` | Yes | Name for the contract |
-| `codeBody` | `string` | Yes | Clarity contract source code |
-| `senderKey` | `string` | Yes | Deployer's private key |
-| `network` | `StacksNetwork \| string` | Yes | Network configuration |
-| `clarityVersion` | `ClarityVersion` | No | Clarity version (defaults to latest) |
-| `fee` | `bigint` | No | Transaction fee in microSTX |
-| `nonce` | `bigint` | No | Account nonce |
-
-### Examples
-
-#### Deploy a contract
-
-```typescript
-import { makeContractDeploy, broadcastTransaction } from '@stacks/transactions';
-import { readFileSync } from 'fs';
-
-const codeBody = readFileSync('./contract.clar', 'utf-8');
-
-const transaction = await makeContractDeploy({
- contractName: 'my-contract',
- codeBody,
- senderKey: privateKey,
- network: 'testnet'
-});
-
-const response = await broadcastTransaction({ transaction, network: 'testnet' });
-```
-
-#### Deploy with Clarity version
-
-```typescript
-const transaction = await makeContractDeploy({
- contractName: 'clarity-v3-contract',
- codeBody: contractCode,
- clarityVersion: 3,
- senderKey: privateKey,
- network: 'mainnet'
-});
-```
-
-### makeContractCall [#makeContractCall]
-
-`makeContractCall` creates a signed contract function call transaction.
-
-### Signature
-
-```typescript
-function makeContractCall(options: SignedContractCallOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `contractAddress` | `string` | Yes | Contract address |
-| `contractName` | `string` | Yes | Contract name |
-| `functionName` | `string` | Yes | Function to call |
-| `functionArgs` | `ClarityValue[]` | Yes | Function arguments |
-| `senderKey` | `string` | Yes | Caller's private key |
-| `network` | `StacksNetwork \| string` | Yes | Network configuration |
-| `postConditions` | `PostCondition[]` | No | Post conditions |
-| `validateWithAbi` | `boolean \| ClarityAbi` | No | Validate arguments against ABI |
-| `fee` | `bigint` | No | Transaction fee in microSTX |
-| `nonce` | `bigint` | No | Account nonce |
-
-### Examples
-
-#### Basic contract call
-
-```typescript
-import { makeContractCall, broadcastTransaction, Cl } from '@stacks/transactions';
-
-const transaction = await makeContractCall({
- contractAddress: 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR',
- contractName: 'hello-world',
- functionName: 'say-hi',
- functionArgs: [Cl.stringUtf8('Hello!')],
- senderKey: privateKey,
- network: 'testnet'
-});
-
-const response = await broadcastTransaction({ transaction, network: 'testnet' });
-```
-
-#### Call with post conditions
-
-```typescript
-import { makeContractCall, Cl, Pc } from '@stacks/transactions';
-
-const postCondition = Pc.principal('SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE')
- .willSendLte(1000000n)
- .ustx();
-
-const transaction = await makeContractCall({
- contractAddress: 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR',
- contractName: 'token-contract',
- functionName: 'transfer',
- functionArgs: [
- Cl.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159'),
- Cl.uint(100n)
- ],
- postConditions: [postCondition],
- validateWithAbi: true,
- senderKey: privateKey,
- network: 'mainnet'
-});
-```
-
-### sponsorTransaction [#sponsorTransaction]
-
-`sponsorTransaction` adds a sponsor signature to a transaction, enabling sponsored transactions.
-
-### Signature
-
-```typescript
-function sponsorTransaction(options: SponsorTransactionOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `transaction` | `StacksTransaction` | Yes | Transaction to sponsor |
-| `sponsorPrivateKey` | `string` | Yes | Sponsor's private key |
-| `fee` | `bigint` | Yes | Fee to be paid by sponsor |
-| `sponsorNonce` | `bigint` | No | Sponsor account nonce |
-
-### Example
-
-```typescript
-import { sponsorTransaction, deserializeTransaction, broadcastTransaction } from '@stacks/transactions';
-
-// Deserialize the transaction from the origin
-const deserializedTx = deserializeTransaction(serializedTx);
-
-// Sponsor the transaction
-const sponsoredTx = await sponsorTransaction({
- transaction: deserializedTx,
- sponsorPrivateKey: sponsorKey,
- fee: 1000n,
- sponsorNonce: 0
-});
-
-const response = await broadcastTransaction({ transaction: sponsoredTx, network: 'testnet' });
-```
-
-### fetchCallReadOnlyFunction [#fetchCallReadOnlyFunction]
-
-`fetchCallReadOnlyFunction` calls a read-only contract function without creating a transaction.
-
-### Signature
-
-```typescript
-function fetchCallReadOnlyFunction(options: CallReadOnlyFunctionOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `contractAddress` | `string` | Yes | Contract address |
-| `contractName` | `string` | Yes | Contract name |
-| `functionName` | `string` | Yes | Function to call |
-| `functionArgs` | `ClarityValue[]` | Yes | Function arguments |
-| `network` | `StacksNetwork` | Yes | Network configuration |
-| `senderAddress` | `string` | Yes | Address of the caller |
-
-### Example
-
-```typescript
-import { fetchCallReadOnlyFunction, Cl } from '@stacks/transactions';
-import { STACKS_MAINNET } from '@stacks/network';
-
-const result = await fetchCallReadOnlyFunction({
- contractAddress: 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR',
- contractName: 'data-store',
- functionName: 'get-value',
- functionArgs: [Cl.stringUtf8('key')],
- network: STACKS_MAINNET,
- senderAddress: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159'
-});
-
-console.log(result);
-```
-
-### broadcastTransaction [#broadcastTransaction]
-
-`broadcastTransaction` broadcasts a signed transaction to the network.
-
-### Signature
-
-```typescript
-function broadcastTransaction(options: BroadcastTransactionOptions): Promise
-```
-
-### Parameters
-
-| Name | Type | Required | Description |
-|------|------|----------|-------------|
-| `transaction` | `StacksTransaction` | Yes | Signed transaction to broadcast |
-| `network` | `StacksNetwork \| string` | Yes | Network to broadcast to |
-
-### Example
-
-```typescript
-import { broadcastTransaction } from '@stacks/transactions';
-
-const result = await broadcastTransaction({
- transaction: signedTx,
- network: 'mainnet'
-});
-
-if (result.error) {
- console.error('Broadcast failed:', result.reason);
-} else {
- console.log('Transaction ID:', result.txid);
-}
-```
-
-## Clarity value construction
-
-### Primitive values
-
-```typescript
-import { Cl } from '@stacks/transactions';
-
-// Boolean values
-const isTrue = Cl.bool(true);
-const isFalse = Cl.bool(false);
-
-// Integer values (signed 128-bit)
-const positiveInt = Cl.int(42n);
-const negativeInt = Cl.int(-100n);
-
-// Unsigned integer values (unsigned 128-bit)
-const unsignedInt = Cl.uint(100n);
-
-// Buffer values
-const buffer = Cl.bufferFromUtf8('hello world');
-const hexBuffer = Cl.bufferFromHex('0x1234');
-
-// String values
-const asciiStr = Cl.stringAscii('Hello ASCII');
-const utf8Str = Cl.stringUtf8('Hello UTF-8! 👋');
-```
-
-### Complex values
-
-```typescript
-// Principal values
-const standardPrincipal = Cl.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159');
-const contractPrincipal = Cl.contractPrincipal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', 'my-contract');
-
-// Optional values
-const none = Cl.none();
-const some = Cl.some(Cl.uint(42n));
-
-// Response values
-const okResponse = Cl.ok(Cl.stringUtf8('Success'));
-const errResponse = Cl.error(Cl.uint(404n));
-
-// Tuple values
-const tuple = Cl.tuple({
- name: Cl.stringUtf8('Alice'),
- age: Cl.uint(30n),
- active: Cl.bool(true)
-});
-
-// List values
-const list = Cl.list([Cl.uint(1n), Cl.uint(2n), Cl.uint(3n)]);
-```
-
-## Post conditions
-
-### STX post conditions
-
-```typescript
-import { Pc } from '@stacks/transactions';
-
-// Standard principal STX post condition
-const stxPostCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159')
- .willSendGte(1000000n)
- .ustx();
-
-// Contract principal STX post condition
-const contractStxCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159.my-contract')
- .willSendEq(500000n)
- .ustx();
-```
-
-### Fungible token post conditions
-
-```typescript
-// Standard principal fungible token post condition
-const ftPostCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159')
- .willSendLte(100n)
- .ft('SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.token-contract', 'my-token');
-
-// Contract principal fungible token post condition
-const contractFtCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159.vault')
- .willNotSend()
- .ft('SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.token-contract', 'my-token');
-```
-
-### Non-fungible token post conditions
-
-```typescript
-// Standard principal NFT post condition
-const nftPostCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159')
- .willSend()
- .nft('SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.nft-contract', 'my-nft', Cl.uint(1n));
-
-// Contract principal NFT post condition
-const contractNftCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159.marketplace')
- .willNotSend()
- .nft('SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.nft-contract', 'my-nft', Cl.uint(1n));
-```
-
-## Multi-signature transactions
-
-Multi-signature transactions require multiple signatures before broadcasting.
-
-```typescript
-import {
- makeUnsignedSTXTokenTransfer,
- createStacksPrivateKey,
- deserializeTransaction,
- pubKeyfromPrivKey,
- publicKeyToString,
- TransactionSigner,
- BytesReader
-} from '@stacks/transactions';
-
-// Create unsigned multi-sig transaction
-const transaction = await makeUnsignedSTXTokenTransfer({
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- amount: 1000000n,
- fee: 200n,
- numSignatures: 2, // Require 2 of 3 signatures
- publicKeys: [publicKey1, publicKey2, publicKey3],
- network: 'mainnet'
-});
-
-// Sign with multiple parties
-const deserializedTx = deserializeTransaction(transaction.serialize());
-const signer = new TransactionSigner(deserializedTx);
-
-// Add required signatures
-signer.signOrigin(privateKey1);
-signer.signOrigin(privateKey2);
-
-// Append public key of non-signing party
-signer.appendOrigin(publicKey3);
-
-// Broadcast the multi-sig transaction
-const signedTx = deserializedTx;
-const response = await broadcastTransaction({ transaction: signedTx, network: 'mainnet' });
-```
-
-## Key generation utilities
-
-### randomPrivateKey [#randomPrivateKey]
-
-`randomPrivateKey` generates a new random private key.
-
-```typescript
-import { randomPrivateKey } from '@stacks/transactions';
-
-const privateKey = randomPrivateKey();
-console.log(privateKey); // Random 32-byte hex string with optional compression flag
-```
-
-### privateKeyToPublicKey [#privateKeyToPublicKey]
-
-`privateKeyToPublicKey` derives a public key from a private key.
-
-```typescript
-import { privateKeyToPublicKey } from '@stacks/transactions';
-
-const privateKey = 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01';
-const publicKey = privateKeyToPublicKey(privateKey);
-console.log(publicKey); // Compressed public key
-```
-
-## Utility functions
-
-### deserializeTransaction [#deserializeTransaction]
-
-`deserializeTransaction` converts a serialized transaction back to a transaction object.
-
-```typescript
-import { deserializeTransaction } from '@stacks/transactions';
-
-const serializedTx = '0x00000000...'; // Hex string
-const transaction = deserializeTransaction(serializedTx);
-```
-
-### cvToJSON [#cvToJSON]
-
-`cvToJSON` converts Clarity values to JSON format for easier manipulation.
-
-```typescript
-import { cvToJSON, hexToCV } from '@stacks/transactions';
-
-const clarityValue = hexToCV('0x0100000000000000000000000000000001');
-const json = cvToJSON(clarityValue);
-console.log(json); // { type: 'uint', value: '1' }
-```
\ No newline at end of file
diff --git a/content/docs/en/resources/clarity/(integrations)/external-data.mdx b/content/docs/en/resources/clarity/(integrations)/external-data.mdx
deleted file mode 100644
index 25b03b3e3..000000000
--- a/content/docs/en/resources/clarity/(integrations)/external-data.mdx
+++ /dev/null
@@ -1,223 +0,0 @@
----
-title: Using Pyth oracle data
-sidebarTitle: Oracle integration
-description: In this guide, you'll learn how to read real-time price data from Pyth Network's decentralized oracle in your Clarity contracts.
----
-
-:::objectives
-- Understand Pyth's pull-based oracle model
-- Read and process price feed data
-- Work with fixed-point price representation
-- Build USD-denominated smart contracts
-:::
-
-:::prerequisites
-- Basic understanding of Clarity smart contracts
-- A Clarinet project set up for local development
-:::
-
-## Understanding Pyth oracles
-
-Pyth Network uses a **pull-based** oracle model, different from traditional push-based oracles:
-
-- **Push model**: Oracle continuously sends price updates on-chain
-- **Pull model**: Users fetch and submit price updates when needed
-
-This approach is more gas-efficient and allows for higher-frequency price updates.
-
-### Supported price feeds
-
-The Pyth integration on Stacks currently supports these price feeds:
-
-| Asset | Price Feed ID | Explorer Link |
-|-------|--------------|---------------|
-| BTC/USD | `0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43` | [View](https://www.pyth.network/price-feeds/crypto-btc-usd) |
-| STX/USD | `0xec7a775f46379b5e943c3526b1c8d54cd49749176b0b98e02dde68d1bd335c17` | [View](https://www.pyth.network/price-feeds/crypto-stx-usd) |
-| ETH/USD | `0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace` | [View](https://www.pyth.network/price-feeds/crypto-eth-usd) |
-| USDC/USD | `0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a` | [View](https://www.pyth.network/price-feeds/crypto-usdc-usd) |
-
-## Quickstart
-
-
-
- ### Set up contract references
-
- The Pyth oracle on Stacks consists of several contracts. Add these references to your contract:
-
- ```clarity
- ;; Pyth oracle contract addresses (mainnet)
- (define-constant PYTH-ORACLE-CONTRACT 'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-oracle-v3)
- (define-constant PYTH-STORAGE-CONTRACT 'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3)
- (define-constant PYTH-DECODER-CONTRACT 'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-pnau-decoder-v2)
- (define-constant WORMHOLE-CORE-CONTRACT 'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.wormhole-core-v3)
-
- ;; Price feed IDs
- (define-constant BTC-USD-FEED-ID 0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43)
- ```
-
-
-
- ### Update and read price data
-
- Create a function that updates the price feed and reads the current price:
-
- ```clarity
- (define-public (get-btc-price (price-feed-bytes (buff 8192)))
- (let (
- ;; Update the price feed with fresh data
- (update-result (try! (contract-call? PYTH-ORACLE-CONTRACT
- verify-and-update-price-feeds price-feed-bytes {
- pyth-storage-contract: PYTH-STORAGE-CONTRACT,
- pyth-decoder-contract: PYTH-DECODER-CONTRACT,
- wormhole-core-contract: WORMHOLE-CORE-CONTRACT
- })))
-
- ;; Read the updated price
- (price-data (try! (contract-call? PYTH-ORACLE-CONTRACT
- get-price
- BTC-USD-FEED-ID
- PYTH-STORAGE-CONTRACT)))
- )
- (ok price-data)
- ))
- ```
-
- The update operation requires a small fee (typically 1 uSTX) to prevent spam.
-
-
-
- ### Process price data
-
- Price data uses fixed-point representation. Convert it to a usable format:
-
- ```clarity
- (define-read-only (process-price-data (price-data {
- price-identifier: (buff 32),
- price: int,
- conf: uint,
- expo: int,
- ema-price: int,
- ema-conf: uint,
- publish-time: uint,
- prev-publish-time: uint
- }))
- (let (
- ;; Calculate the denominator based on the exponent
- ;; For expo = -8, denominator = 10^8 = 100,000,000
- (exponent (get expo price-data))
- (denominator (pow u10 (to-uint (* exponent -1))))
-
- ;; Convert to standard decimal representation
- ;; If price = 10603557773590 and expo = -8
- ;; Actual price = 10603557773590 / 100,000,000 = 106,035.58
- (adjusted-price (/ (to-uint (get price price-data)) denominator))
- )
- adjusted-price
- ))
- ```
-
-
-
-## Common patterns
-
-### USD-denominated NFT minting
-
-Create an NFT that costs exactly $100 worth of sBTC:
-
-```clarity contracts/benjamin-club.clar
-;; Benjamin Club - $100 NFT minting contract
-(define-constant BENJAMIN-COST u100) ;; $100 USD
-(define-constant ERR-INSUFFICIENT-FUNDS (err u100))
-(define-constant ERR-PRICE-UPDATE-FAILED (err u101))
-
-(define-non-fungible-token benjamin-nft uint)
-(define-data-var last-token-id uint u0)
-
-(define-public (mint-for-hundred-dollars (price-feed-bytes (buff 8192)))
- (let (
- ;; Update and get BTC price
- (price-data (try! (get-btc-price price-feed-bytes)))
- (btc-price-cents (process-price-data price-data))
-
- ;; Calculate required sBTC amount
- ;; $100 = 10,000 cents
- (required-sbtc (/ (* u10000 u100000000) btc-price-cents))
-
- ;; Get user's sBTC balance
- (user-balance (unwrap!
- (contract-call? .sbtc-token get-balance tx-sender)
- ERR-INSUFFICIENT-FUNDS))
- )
- ;; Verify user has enough sBTC
- (asserts! (>= user-balance required-sbtc) ERR-INSUFFICIENT-FUNDS)
-
- ;; Transfer sBTC and mint NFT
- (try! (contract-call? .sbtc-token transfer
- required-sbtc tx-sender (as-contract tx-sender) none))
-
- ;; Mint the NFT
- (let ((token-id (+ (var-get last-token-id) u1)))
- (try! (nft-mint? benjamin-nft token-id tx-sender))
- (var-set last-token-id token-id)
- (ok token-id))))
-```
-
-### Price staleness protection
-
-Ensure price data is recent enough for your use case:
-
-```clarity
-(define-constant MAX-PRICE-AGE u300) ;; 5 minutes in seconds
-
-(define-read-only (is-price-fresh (price-data (tuple)))
- (let (
- (current-time (unwrap-panic (get-block-info? time block-height)))
- (publish-time (get publish-time price-data))
- )
- (<= (- current-time publish-time) MAX-PRICE-AGE))
-)
-```
-
-### Multi-asset price aggregation
-
-Get multiple price feeds in one transaction:
-
-```clarity
-(define-public (get-multiple-prices
- (btc-vaa (buff 8192))
- (eth-vaa (buff 8192))
- (stx-vaa (buff 8192)))
- (let (
- ;; Update all price feeds
- (updates (try! (contract-call? PYTH-ORACLE-CONTRACT
- verify-and-update-price-feeds
- (concat btc-vaa (concat eth-vaa stx-vaa))
- { pyth-storage-contract: PYTH-STORAGE-CONTRACT,
- pyth-decoder-contract: PYTH-DECODER-CONTRACT,
- wormhole-core-contract: WORMHOLE-CORE-CONTRACT })))
-
- ;; Read all prices
- (btc-price (try! (get-price-by-id BTC-USD-FEED-ID)))
- (eth-price (try! (get-price-by-id ETH-USD-FEED-ID)))
- (stx-price (try! (get-price-by-id STX-USD-FEED-ID)))
- )
- (ok { btc: btc-price, eth: eth-price, stx: stx-price }))
-)
-```
-
-## Testnet deployment
-
-For testnet development, use these contract addresses:
-
-```clarity
-;; Testnet addresses
-(define-constant PYTH-ORACLE-CONTRACT-TESTNET 'ST20M5GABDT6WYJHXBT5CDH4501V1Q65242SPRMXH.pyth-oracle-v3)
-(define-constant PYTH-STORAGE-CONTRACT-TESTNET 'ST20M5GABDT6WYJHXBT5CDH4501V1Q65242SPRMXH.pyth-storage-v3)
-```
-
-## Next steps
-
-:::next-steps
-- [Frontend integration](/reference/stacks.js/pyth-oracle-integration): Learn how to fetch VAA messages and call your oracle-enabled contracts
-- [Testing with Clarinet](/tools/clarinet/pyth-oracle-integration): Set up tests for contracts that depend on oracle data
-:::
\ No newline at end of file
diff --git a/content/docs/en/resources/clarity/(integrations)/meta.json b/content/docs/en/resources/clarity/(integrations)/meta.json
deleted file mode 100644
index ac589c6a8..000000000
--- a/content/docs/en/resources/clarity/(integrations)/meta.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "title": "Integrations",
- "pages": ["external-data"]
-}
diff --git a/content/docs/en/resources/clarity/index.mdx b/content/docs/en/resources/clarity/index.mdx
deleted file mode 100644
index 9020dc075..000000000
--- a/content/docs/en/resources/clarity/index.mdx
+++ /dev/null
@@ -1,18 +0,0 @@
----
-title: Clarity
-sidebarTitle: Overview
-description: Explore and master Clarity's built-in functions for smart contract development.
-llm: false
----
-
-## Overview
-
-Each page in this section covers one or more related Clarity functions, explaining their purpose, demonstrating implementation with code samples, and discussing best practices. Ready to enhance your Clarity smart contract development skills?
-
-To explore Clarity with AI, copy and paste [llms.txt](/resources/clarity/llms.txt) into your LLM of choice.
-
-:::callout
-type: help
-### Need help building with Clarity?
-Reach out to us on the #clarity channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET.
-:::
diff --git a/content/docs/en/resources/clarity/meta.json b/content/docs/en/resources/clarity/meta.json
deleted file mode 100644
index a8bc09825..000000000
--- a/content/docs/en/resources/clarity/meta.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "title": "Clarity",
- "root": true,
- "pages": [
- "---Clarity---",
- "index",
- "---Reference---",
- "...reference",
- "---Integrations---",
- "...(integrations)"
- ]
-}
diff --git a/content/docs/en/resources/clarity/reference/functions.mdx b/content/docs/en/resources/clarity/reference/functions.mdx
deleted file mode 100644
index ced12eca2..000000000
--- a/content/docs/en/resources/clarity/reference/functions.mdx
+++ /dev/null
@@ -1,3330 +0,0 @@
----
-title: Functions reference
-sidebarTitle: Functions
-description: Complete reference for all Clarity functions organized by category, from arithmetic operations to token management.
----
-
-Clarity provides a comprehensive set of built-in functions for smart contract development. These functions cover everything from basic arithmetic to complex token operations and blockchain interactions.
-
-## Arithmetic operations [#arithmetic-operations]
-
-### + (add) [#add]
-
-`+` performs addition on a variable number of integer inputs.
-
-**Signature**
-
-```clarity
-(+ i1 i2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| i1, i2, ... | `int` or `uint` | Two or more integers to add |
-
-```clarity
-(+ 1 2 3) ;; Returns 6
-(+ u10 u20) ;; Returns u30
-
-;; Counter example
-(define-data-var counter int 0)
-(define-public (increment (amount int))
- (begin
- (var-set counter (+ (var-get counter) amount))
- (ok (var-get counter))))
-```
-
-### - (subtract) [#subtract]
-
-`-` performs subtraction on a variable number of integer inputs.
-
-**Signature**
-
-```clarity
-(- i1 i2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| i1, i2, ... | `int` or `uint` | Two or more integers to subtract |
-
-```clarity
-(- 10 3) ;; Returns 7
-(- 100 20 10) ;; Returns 70
-(- u50 u30) ;; Returns u20
-
-;; Decrease balance
-(define-public (withdraw (amount uint))
- (let ((balance (var-get user-balance)))
- (asserts! (>= balance amount) (err u1))
- (var-set user-balance (- balance amount))
- (ok amount)))
-```
-
-### * (multiply) [#multiply]
-
-`*` performs multiplication on a variable number of integer inputs.
-
-**Signature**
-
-```clarity
-(* i1 i2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| i1, i2, ... | `int` or `uint` | Two or more integers to multiply |
-
-```clarity
-(* 3 4) ;; Returns 12
-(* 2 3 4) ;; Returns 24
-(* u5 u10) ;; Returns u50
-
-;; Calculate percentage
-(define-read-only (calculate-fee (amount uint))
- (/ (* amount u3) u100)) ;; 3% fee
-```
-
-### / (divide) [#divide]
-
-`/` performs integer division on a variable number of integer inputs.
-
-**Signature**
-
-```clarity
-(/ i1 i2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| i1, i2, ... | `int` or `uint` | Two or more integers to divide |
-
-```clarity
-(/ 10 2) ;; Returns 5
-(/ 100 10 2) ;; Returns 5
-(/ u60 u3) ;; Returns u20
-
-;; Calculate average
-(define-read-only (average (a uint) (b uint))
- (/ (+ a b) u2))
-```
-
-### mod [#mod]
-
-`mod` returns the remainder of integer division.
-
-**Signature**
-
-```clarity
-(mod i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | Dividend |
-| `i2` | `int` or `uint` | Divisor |
-
-```clarity
-(mod 10 3) ;; Returns 1
-(mod u17 u5) ;; Returns u2
-
-;; Check if even
-(define-read-only (is-even (n uint))
- (is-eq (mod n u2) u0))
-```
-
-### pow [#pow]
-
-`pow` raises a number to a power.
-
-**Signature**
-
-```clarity
-(pow i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | Base |
-| `i2` | `int` or `uint` | Exponent |
-
-```clarity
-(pow 2 3) ;; Returns 8
-(pow u10 u2) ;; Returns u100
-
-;; Calculate compound interest
-(define-read-only (compound-interest (principal uint) (rate uint) (periods uint))
- (let ((rate-factor (+ u100 rate)))
- (/ (* principal (pow rate-factor periods)) (pow u100 periods))))
-```
-
-### sqrti [#sqrti]
-
-`sqrti` returns the integer square root of a number.
-
-**Signature**
-
-```clarity
-(sqrti n)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `n` | `int` or `uint` | Number to find square root of |
-
-```clarity
-(sqrti u16) ;; Returns u4
-(sqrti u100) ;; Returns u10
-(sqrti 25) ;; Returns 5
-
-;; Calculate distance (simplified)
-(define-read-only (distance (x uint) (y uint))
- (sqrti (+ (* x x) (* y y))))
-```
-
-### log2 [#log2]
-
-`log2` returns the base-2 logarithm of a number.
-
-**Signature**
-
-```clarity
-(log2 n)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `n` | `int` or `uint` | Number to find logarithm of |
-
-```clarity
-(log2 u8) ;; Returns u3
-(log2 u256) ;; Returns u8
-
-;; Calculate bit position
-(define-read-only (highest-bit-position (n uint))
- (if (> n u0)
- (some (log2 n))
- none))
-```
-
-### < (less-than) [#less-than]
-
-`<` returns true if the first argument is less than the second.
-
-**Signature**
-
-```clarity
-(< i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | First value |
-| `i2` | `int` or `uint` | Second value |
-
-```clarity
-(< 5 10) ;; Returns true
-(< u100 u50) ;; Returns false
-
-;; Validate minimum
-(define-public (deposit (amount uint))
- (begin
- (asserts! (< u0 amount) (err u1))
- (ok amount)))
-```
-
-### > (greater-than) [#greater-than]
-
-`>` returns true if the first argument is greater than the second.
-
-**Signature**
-
-```clarity
-(> i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | First value |
-| `i2` | `int` or `uint` | Second value |
-
-```clarity
-(> 10 5) ;; Returns true
-(> u50 u100) ;; Returns false
-
-;; Check maximum
-(define-read-only (exceeds-limit (value uint))
- (> value u1000000))
-```
-
-### <= (less-than-or-equal) [#less-than-or-equal]
-
-`<=` returns true if the first argument is less than or equal to the second.
-
-**Signature**
-
-```clarity
-(<= i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | First value |
-| `i2` | `int` or `uint` | Second value |
-
-```clarity
-(<= 5 10) ;; Returns true
-(<= 10 10) ;; Returns true
-(<= u100 u50) ;; Returns false
-
-;; Validate range
-(define-read-only (is-valid-percentage (value uint))
- (and (<= u0 value) (<= value u100)))
-```
-
-### >= (greater-than-or-equal) [#greater-than-or-equal]
-
-`>=` returns true if the first argument is greater than or equal to the second.
-
-**Signature**
-
-```clarity
-(>= i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | First value |
-| `i2` | `int` or `uint` | Second value |
-
-```clarity
-(>= 10 5) ;; Returns true
-(>= 10 10) ;; Returns true
-(>= u50 u100) ;; Returns false
-
-;; Check balance
-(define-public (can-afford (price uint))
- (ok (>= (stx-get-balance tx-sender) price)))
-```
-
-## Logical operations [#logical-operations]
-
-### and [#and]
-
-`and` returns true if all arguments are true.
-
-**Signature**
-
-```clarity
-(and b1 b2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| b1, b2, ... | `bool` | Boolean values to evaluate |
-
-```clarity
-(and true true) ;; Returns true
-(and true false) ;; Returns false
-(and true true true) ;; Returns true
-
-;; Multiple conditions
-(define-read-only (is-valid-transfer (amount uint) (recipient principal))
- (and
- (> amount u0)
- (not (is-eq recipient tx-sender))
- (<= amount (get-balance tx-sender))))
-```
-
-### or [#or]
-
-`or` returns true if at least one argument is true.
-
-**Signature**
-
-```clarity
-(or b1 b2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| b1, b2, ... | `bool` | Boolean values to evaluate |
-
-```clarity
-(or true false) ;; Returns true
-(or false false) ;; Returns false
-(or false false true) ;; Returns true
-
-;; Check permissions
-(define-read-only (can-access (user principal))
- (or
- (is-eq user contract-owner)
- (default-to false (map-get? admins user))
- (var-get public-access)))
-```
-
-### not [#not]
-
-`not` returns the logical negation of a boolean value.
-
-**Signature**
-
-```clarity
-(not b)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `b` | `bool` | Boolean value to negate |
-
-```clarity
-(not true) ;; Returns false
-(not false) ;; Returns true
-
-;; Check if not owner
-(define-read-only (is-not-owner (user principal))
- (not (is-eq user contract-owner)))
-```
-
-### xor [#xor]
-
-`xor` returns true if exactly one of two arguments is true.
-
-**Signature**
-
-```clarity
-(xor b1 b2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `b1` | `bool` | First boolean value |
-| `b2` | `bool` | Second boolean value |
-
-```clarity
-(xor true false) ;; Returns true
-(xor true true) ;; Returns false
-(xor false false) ;; Returns false
-
-;; Exclusive access
-(define-read-only (has-exclusive-role (is-admin bool) (is-moderator bool))
- (xor is-admin is-moderator))
-```
-
-### is-eq [#is-eq]
-
-`is-eq` returns true if all arguments are equal.
-
-**Signature**
-
-```clarity
-(is-eq v1 v2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| v1, v2, ... | any | Values to compare for equality |
-
-```clarity
-(is-eq 5 5) ;; Returns true
-(is-eq "hello" "hello") ;; Returns true
-(is-eq u10 u20) ;; Returns false
-(is-eq 1 1 1) ;; Returns true
-
-;; Check owner
-(define-public (admin-only)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (ok true)))
-```
-
-## Sequence & string operations [#sequence-string-operations]
-
-### list [#list]
-
-`list` constructs a list from provided values.
-
-**Signature**
-
-```clarity
-(list v1 v2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| v1, v2, ... | any | Values to include in the list |
-
-```clarity
-(list 1 2 3) ;; Returns (1 2 3)
-(list true false true) ;; Returns (true false true)
-
-;; Create address list
-(define-data-var admins (list 5 principal)
- (list 'SP1234... 'SP5678...))
-```
-
-### append [#append]
-
-`append` adds an element to the end of a list.
-
-**Signature**
-
-```clarity
-(append list-expr element)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `list-expr` | `list` | List to append to |
-| `element` | any | Element to add |
-
-```clarity
-(append (list 1 2) 3) ;; Returns (1 2 3)
-(append (list) u10) ;; Returns (u10)
-
-;; Add to list
-(define-public (add-member (member principal))
- (let ((current-list (var-get members)))
- (match (as-max-len? (append current-list member) u100)
- new-list (begin
- (var-set members new-list)
- (ok true))
- (err u1))))
-```
-
-### concat [#concat]
-
-`concat` joins two sequences of the same type.
-
-**Signature**
-
-```clarity
-(concat sequence1 sequence2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `sequence1` | sequence | First sequence |
-| `sequence2` | sequence | Second sequence |
-
-```clarity
-(concat "Hello " "World") ;; Returns "Hello World"
-(concat 0x0102 0x0304) ;; Returns 0x01020304
-(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4)
-
-;; Combine strings
-(define-read-only (format-message (prefix (string-ascii 10)) (msg (string-ascii 50)))
- (concat prefix msg))
-```
-
-### len [#len]
-
-`len` returns the length of a sequence.
-
-**Signature**
-
-```clarity
-(len sequence)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `sequence` | sequence | Sequence to measure |
-
-```clarity
-(len "Hello") ;; Returns u5
-(len (list 1 2 3)) ;; Returns u3
-(len 0x0102) ;; Returns u2
-
-;; Validate length
-(define-public (set-name (name (string-ascii 50)))
- (begin
- (asserts! (> (len name) u0) (err u1))
- (asserts! (<= (len name) u20) (err u2))
- (ok name)))
-```
-
-### element-at? [#element-at?]
-
-`element-at?` retrieves an element at a specific index.
-
-**Signature**
-
-```clarity
-(element-at? sequence index)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `sequence` | sequence | Sequence to access |
-| `index` | `uint` | Zero-based index |
-
-```clarity
-(element-at? "Hello" u1) ;; Returns (some "e")
-(element-at? (list 10 20 30) u2) ;; Returns (some 30)
-(element-at? (list 1 2) u5) ;; Returns none
-
-;; Get from list safely
-(define-read-only (get-member-at (index uint))
- (element-at? (var-get members) index))
-```
-
-### index-of? [#index-of]
-
-`index-of?` finds the first occurrence of an element in a sequence.
-
-**Signature**
-
-```clarity
-(index-of? sequence element)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `sequence` | sequence | Sequence to search |
-| `element` | any | Element to find |
-
-```clarity
-(index-of? "Hello" "l") ;; Returns (some u2)
-(index-of? (list 1 2 3 2) 2) ;; Returns (some u1)
-(index-of? (list 1 2 3) 5) ;; Returns none
-
-;; Check membership
-(define-read-only (is-member (user principal))
- (is-some (index-of? (var-get members) user)))
-```
-
-### slice? [#slice]
-
-`slice?` extracts a subsequence from a sequence.
-
-**Signature**
-
-```clarity
-(slice? sequence left-position right-position)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `sequence` | sequence | Sequence to slice |
-| `left-position` | `uint` | Starting index (inclusive) |
-| `right-position` | `uint` | Ending index (exclusive) |
-
-```clarity
-(slice? "Hello World" u0 u5) ;; Returns (some "Hello")
-(slice? (list 1 2 3 4 5) u1 u4) ;; Returns (some (2 3 4))
-
-;; Extract substring
-(define-read-only (get-prefix (text (string-ascii 100)) (length uint))
- (slice? text u0 length))
-```
-
-### replace-at? [#replace-at]
-
-`replace-at?` replaces an element at a specific index.
-
-**Signature**
-
-```clarity
-(replace-at? sequence index new-element)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `sequence` | sequence | Sequence to modify |
-| `index` | `uint` | Index to replace at |
-| `new-element` | any | New element |
-
-```clarity
-(replace-at? "Hello" u1 "a") ;; Returns (some "Hallo")
-(replace-at? (list 1 2 3) u1 5) ;; Returns (some (1 5 3))
-
-;; Update list element
-(define-public (update-member (index uint) (new-member principal))
- (match (replace-at? (var-get members) index new-member)
- new-list (begin
- (var-set members new-list)
- (ok true))
- (err u404)))
-```
-
-
-### int-to-ascii [#int-to-ascii]
-
-`int-to-ascii` converts an integer to its ASCII string representation.
-
-**Signature**
-
-```clarity
-(int-to-ascii value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `value` | `int` or `uint` | Integer to convert |
-
-```clarity
-(int-to-ascii 123) ;; Returns "123"
-(int-to-ascii u456) ;; Returns "456"
-
-;; Format ID
-(define-read-only (format-id (id uint))
- (concat "ID-" (int-to-ascii id)))
-```
-
-### int-to-utf8 [#int-to-utf8]
-
-`int-to-utf8` converts an integer to its UTF-8 string representation.
-
-**Signature**
-
-```clarity
-(int-to-utf8 value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `value` | `int` or `uint` | Integer to convert |
-
-```clarity
-(int-to-utf8 789) ;; Returns u"789"
-(int-to-utf8 u100) ;; Returns u"100"
-
-;; Create UTF-8 label
-(define-read-only (create-label (num uint))
- (concat u"Label #" (int-to-utf8 num)))
-```
-
-### string-to-int? [#string-to-int]
-
-`string-to-int?` converts a string to an optional integer.
-
-**Signature**
-
-```clarity
-(string-to-int? string)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `string` | `string-ascii` or `string-utf8` | String to convert |
-
-```clarity
-(string-to-int? "123") ;; Returns (some 123)
-(string-to-int? "-456") ;; Returns (some -456)
-(string-to-int? "abc") ;; Returns none
-
-;; Parse user input
-(define-public (set-value (input (string-ascii 10)))
- (match (string-to-int? input)
- value (ok (var-set stored-value value))
- (err u1)))
-```
-
-### string-to-uint? [#string-to-uint]
-
-`string-to-uint?` converts a string to an optional unsigned integer.
-
-**Signature**
-
-```clarity
-(string-to-uint? string)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `string` | `string-ascii` or `string-utf8` | String to convert |
-
-```clarity
-(string-to-uint? "123") ;; Returns (some u123)
-(string-to-uint? "0") ;; Returns (some u0)
-(string-to-uint? "-123") ;; Returns none
-
-;; Parse amount
-(define-read-only (parse-amount (input (string-ascii 20)))
- (string-to-uint? input))
-```
-
-### buff-to-int-be [#buff-to-int-be]
-
-`buff-to-int-be` converts a buffer to a signed integer (big-endian).
-
-**Signature**
-
-```clarity
-(buff-to-int-be buffer)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `buffer` | `buff` | Buffer to convert |
-
-```clarity
-(buff-to-int-be 0x0001) ;; Returns 1
-(buff-to-int-be 0x00ff) ;; Returns 255
-(buff-to-int-be 0xffff) ;; Returns -1
-
-;; Parse signed data
-(define-read-only (parse-signed-data (data (buff 8)))
- (buff-to-int-be data))
-```
-
-### buff-to-int-le [#buff-to-int-le]
-
-`buff-to-int-le` converts a buffer to a signed integer (little-endian).
-
-**Signature**
-
-```clarity
-(buff-to-int-le buffer)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `buffer` | `buff` | Buffer to convert |
-
-```clarity
-(buff-to-int-le 0x0100) ;; Returns 1
-(buff-to-int-le 0xff00) ;; Returns 255
-
-;; Parse little-endian data
-(define-read-only (parse-le-data (data (buff 4)))
- (buff-to-int-le data))
-```
-
-### buff-to-uint-be [#buff-to-uint-be]
-
-`buff-to-uint-be` converts a buffer to an unsigned integer (big-endian).
-
-**Signature**
-
-```clarity
-(buff-to-uint-be buffer)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `buffer` | `buff` | Buffer to convert |
-
-```clarity
-(buff-to-uint-be 0x0001) ;; Returns u1
-(buff-to-uint-be 0x0100) ;; Returns u256
-
-;; Parse network data
-(define-read-only (parse-network-uint (data (buff 8)))
- (buff-to-uint-be data))
-```
-
-### buff-to-uint-le [#buff-to-uint-le]
-
-`buff-to-uint-le` converts a buffer to an unsigned integer (little-endian).
-
-**Signature**
-
-```clarity
-(buff-to-uint-le buffer)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `buffer` | `buff` | Buffer to convert |
-
-```clarity
-(buff-to-uint-le 0x0100) ;; Returns u1
-(buff-to-uint-le 0x0001) ;; Returns u256
-
-;; Parse file data
-(define-read-only (parse-file-size (data (buff 4)))
- (buff-to-uint-le data))
-```
-
-## Iterators [#iterators]
-
-### map [#map]
-
-`map` applies a function to each element of a list.
-
-**Signature**
-
-```clarity
-(map func list1 list2...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `func` | function | Function to apply |
-| list1, list2, ... | `list` | Lists to map over |
-
-```clarity
-(map + (list 1 2 3) (list 10 20 30)) ;; Returns (11 22 33)
-
-;; Double all values
-(define-private (double (x uint))
- (* x u2))
-
-(define-read-only (double-all (numbers (list 10 uint)))
- (map double numbers))
-```
-
-### filter [#filter]
-
-`filter` returns elements that satisfy a predicate.
-
-**Signature**
-
-```clarity
-(filter func list)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `func` | function | Predicate function |
-| `list` | `list` | List to filter |
-
-```clarity
-(define-private (is-even (x uint))
- (is-eq (mod x u2) u0))
-
-(filter is-even (list u1 u2 u3 u4)) ;; Returns (u2 u4)
-
-;; Filter active users
-(define-read-only (get-active-users)
- (filter is-active (var-get all-users)))
-```
-
-### fold [#fold]
-
-`fold` reduces a list to a single value.
-
-**Signature**
-
-```clarity
-(fold func list initial-value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `func` | function | Reducer function |
-| `list` | `list` | List to reduce |
-| `initial-value` | any | Starting value |
-
-```clarity
-(fold + (list u1 u2 u3 u4) u0) ;; Returns u10
-
-;; Sum balances
-(define-private (add-balance (user principal) (total uint))
- (+ total (default-to u0 (map-get? balances user))))
-
-(define-read-only (get-total-balance)
- (fold add-balance (var-get users) u0))
-```
-
-## Data storage & variables [#data-storage-variables]
-
-### define-constant [#define-constant]
-
-`define-constant` creates an immutable constant value.
-
-**Signature**
-
-```clarity
-(define-constant name value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `name` | symbol | Name of the constant |
-| `value` | any | Value of the constant |
-
-```clarity
-(define-constant contract-owner tx-sender)
-(define-constant token-name "MyToken")
-(define-constant max-supply u1000000)
-
-;; Use in functions
-(define-read-only (get-owner)
- contract-owner)
-```
-
-### define-data-var [#define-data-var]
-
-`define-data-var` creates a mutable data variable.
-
-**Signature**
-
-```clarity
-(define-data-var name type value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `name` | symbol | Name of the variable |
-| `type` | type | Type of the variable |
-| `value` | any | Initial value |
-
-```clarity
-(define-data-var counter uint u0)
-(define-data-var is-paused bool false)
-(define-data-var admin principal tx-sender)
-
-;; Update variable
-(define-public (increment)
- (begin
- (var-set counter (+ (var-get counter) u1))
- (ok (var-get counter))))
-```
-
-### var-get [#var-get]
-
-`var-get` retrieves the value of a data variable.
-
-**Signature**
-
-```clarity
-(var-get name)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `name` | symbol | Name of the variable |
-
-```clarity
-(define-data-var balance uint u100)
-
-(define-read-only (get-balance)
- (var-get balance))
-
-;; Use in calculations
-(define-public (double-balance)
- (let ((current (var-get balance)))
- (var-set balance (* current u2))
- (ok (var-get balance))))
-```
-
-### var-set [#var-set]
-
-`var-set` updates the value of a data variable.
-
-**Signature**
-
-```clarity
-(var-set name value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `name` | symbol | Name of the variable |
-| `value` | any | New value |
-
-```clarity
-(define-data-var counter uint u0)
-
-(define-public (set-counter (value uint))
- (begin
- (var-set counter value)
- (ok true)))
-
-;; Conditional update
-(define-public (update-if-higher (value uint))
- (if (> value (var-get counter))
- (begin
- (var-set counter value)
- (ok true))
- (err u1)))
-```
-
-### define-map [#define-map]
-
-`define-map` creates a new data map.
-
-**Signature**
-
-```clarity
-(define-map name key-type value-type)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `name` | symbol | Name of the map |
-| `key-type` | type | Type of the keys |
-| `value-type` | type | Type of the values |
-
-```clarity
-(define-map balances principal uint)
-(define-map user-profiles
- principal
- {
- name: (string-ascii 50),
- age: uint,
- active: bool
- })
-
-;; Composite key
-(define-map allowances
- { owner: principal, spender: principal }
- uint)
-```
-
-### map-get? [#map-get]
-
-`map-get?` retrieves a value from a map.
-
-**Signature**
-
-```clarity
-(map-get? map-name key)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `map-name` | symbol | Name of the map |
-| `key` | any | Key to look up |
-
-```clarity
-(define-map balances principal uint)
-
-(define-read-only (get-balance (user principal))
- (default-to u0 (map-get? balances user)))
-
-;; Pattern matching
-(define-read-only (get-profile-name (user principal))
- (match (map-get? user-profiles user)
- profile (get name profile)
- "Unknown"))
-```
-
-### map-set [#map-set]
-
-`map-set` sets or updates a value in a map.
-
-**Signature**
-
-```clarity
-(map-set map-name key value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `map-name` | symbol | Name of the map |
-| `key` | any | Key to set |
-| `value` | any | Value to store |
-
-```clarity
-(define-map balances principal uint)
-
-(define-public (set-balance (user principal) (amount uint))
- (begin
- (map-set balances user amount)
- (ok true)))
-
-;; Update profile
-(define-public (update-profile (name (string-ascii 50)) (age uint))
- (begin
- (map-set user-profiles tx-sender {
- name: name,
- age: age,
- active: true
- })
- (ok true)))
-```
-
-### map-insert [#map-insert]
-
-`map-insert` inserts a value only if the key doesn't exist.
-
-**Signature**
-
-```clarity
-(map-insert map-name key value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `map-name` | symbol | Name of the map |
-| `key` | any | Key to insert |
-| `value` | any | Value to store |
-
-```clarity
-(define-map users principal { joined: uint })
-
-(define-public (register)
- (if (map-insert users tx-sender { joined: block-height })
- (ok "Registered successfully")
- (err u409))) ;; Already exists
-
-;; One-time initialization
-(define-public (initialize-user (user principal))
- (begin
- (asserts! (map-insert balances user u1000) (err u1))
- (ok true)))
-```
-
-### map-delete [#map-delete]
-
-`map-delete` removes a key-value pair from a map.
-
-**Signature**
-
-```clarity
-(map-delete map-name key)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `map-name` | symbol | Name of the map |
-| `key` | any | Key to delete |
-
-```clarity
-(define-map users principal { data: uint })
-
-(define-public (remove-user (user principal))
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (map-delete users user)
- (ok true)))
-
-;; Clear data
-(define-public (clear-balance)
- (begin
- (map-delete balances tx-sender)
- (ok true)))
-```
-
-### define-private [#define-private]
-
-`define-private` creates a private function only callable within the contract.
-
-**Signature**
-
-```clarity
-(define-private (function-name (arg-name arg-type)...) body)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `function-name` | symbol | Name of the function |
-| `arg-name` | symbol | Argument names |
-| `arg-type` | type | Argument types |
-| `body` | expression | Function body |
-
-```clarity
-(define-private (calculate-fee (amount uint))
- (/ (* amount u3) u100)) ;; 3% fee
-
-(define-public (transfer-with-fee (recipient principal) (amount uint))
- (let ((fee (calculate-fee amount)))
- (try! (stx-transfer? (- amount fee) tx-sender recipient))
- (try! (stx-transfer? fee tx-sender contract-owner))
- (ok true)))
-
-;; Helper functions
-(define-private (is-valid-amount (amount uint))
- (and (> amount u0) (<= amount u1000000)))
-```
-
-### define-public [#define-public]
-
-`define-public` creates a public function callable from outside the contract.
-
-**Signature**
-
-```clarity
-(define-public (function-name (arg-name arg-type)...) body)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `function-name` | symbol | Name of the function |
-| `arg-name` | symbol | Argument names |
-| `arg-type` | type | Argument types |
-| `body` | expression | Function body (must return response) |
-
-```clarity
-(define-public (transfer (recipient principal) (amount uint))
- (begin
- (asserts! (not (is-eq tx-sender recipient)) (err u1))
- (asserts! (> amount u0) (err u2))
- (try! (ft-transfer? my-token amount tx-sender recipient))
- (ok true)))
-
-;; State-changing function
-(define-public (set-name (new-name (string-ascii 50)))
- (begin
- (map-set user-names tx-sender new-name)
- (ok new-name)))
-```
-
-### define-read-only [#define-read-only]
-
-`define-read-only` creates a public read-only function.
-
-**Signature**
-
-```clarity
-(define-read-only (function-name (arg-name arg-type)...) body)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `function-name` | symbol | Name of the function |
-| `arg-name` | symbol | Argument names |
-| `arg-type` | type | Argument types |
-| `body` | expression | Function body |
-
-```clarity
-(define-read-only (get-balance (user principal))
- (default-to u0 (map-get? balances user)))
-
-(define-read-only (calculate-reward (staked uint) (days uint))
- (/ (* staked days u5) u36500)) ;; ~5% APY
-
-;; Complex query
-(define-read-only (get-user-info (user principal))
- {
- balance: (get-balance user),
- profile: (map-get? user-profiles user),
- is-admin: (is-eq user contract-owner)
- })
-```
-
-## Error handling [#error-handling]
-
-### ok [#ok]
-
-`ok` constructs a successful response value.
-
-**Signature**
-
-```clarity
-(ok value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `value` | any | Success value |
-
-```clarity
-(ok u42) ;; Returns (ok u42)
-(ok { status: "success", value: u100 })
-
-;; Success response
-(define-public (deposit (amount uint))
- (begin
- (map-set balances tx-sender
- (+ (get-balance tx-sender) amount))
- (ok amount)))
-```
-
-### err [#err]
-
-`err` constructs an error response value.
-
-**Signature**
-
-```clarity
-(err value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `value` | any | Error value |
-
-```clarity
-(err u404) ;; Returns (err u404)
-(err { code: u500, message: "Internal error" })
-
-;; Error responses
-(define-public (withdraw (amount uint))
- (let ((balance (get-balance tx-sender)))
- (if (>= balance amount)
- (ok amount)
- (err u1)))) ;; Insufficient balance
-```
-
-### asserts! [#asserts]
-
-`asserts!` checks a condition and exits with an error if false.
-
-**Signature**
-
-```clarity
-(asserts! condition thrown-value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `condition` | `bool` | Condition to check |
-| `thrown-value` | any | Value to return if false |
-
-```clarity
-(define-public (transfer (amount uint) (recipient principal))
- (begin
- (asserts! (> amount u0) (err u1))
- (asserts! (not (is-eq tx-sender recipient)) (err u2))
- (asserts! (<= amount (get-balance tx-sender)) (err u3))
- (ok true)))
-
-;; Guard functions
-(define-public (admin-only-function)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- ;; Admin logic here
- (ok true)))
-```
-
-### try! [#try]
-
-`try!` attempts to unwrap a response, propagating any error.
-
-**Signature**
-
-```clarity
-(try! response)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `response` | response | Response to try |
-
-```clarity
-(try! (ok u42)) ;; Returns u42
-(try! (err u404)) ;; Propagates (err u404)
-
-;; Chain operations
-(define-public (complex-operation (amount uint))
- (begin
- (try! (check-preconditions amount))
- (try! (process-payment amount))
- (try! (update-records))
- (ok true)))
-```
-
-### unwrap! [#unwrap]
-
-`unwrap!` extracts the inner value from an optional or ok response.
-
-**Signature**
-
-```clarity
-(unwrap! optional-or-response thrown-value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `optional-or-response` | optional/response | Value to unwrap |
-| `thrown-value` | any | Value if none/err |
-
-```clarity
-(unwrap! (some u42) (err u1)) ;; Returns u42
-(unwrap! none (err u404)) ;; Throws (err u404)
-
-;; Safe access
-(define-public (transfer-from-map (recipient principal))
- (let ((amount (unwrap! (map-get? pending-transfers tx-sender) (err u404))))
- (try! (ft-transfer? token amount tx-sender recipient))
- (map-delete pending-transfers tx-sender)
- (ok amount)))
-```
-
-### unwrap-err! [#unwrap-err]
-
-`unwrap-err!` extracts the error value from an err response.
-
-**Signature**
-
-```clarity
-(unwrap-err! response thrown-value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `response` | response | Response to unwrap |
-| `thrown-value` | any | Value if ok |
-
-```clarity
-(unwrap-err! (err u404) u0) ;; Returns u404
-(unwrap-err! (ok u42) u0) ;; Returns u0
-
-;; Error handling
-(define-public (handle-error)
- (let ((error-code (unwrap-err! (process-action) u0)))
- (print { error: error-code })
- (ok error-code)))
-```
-
-### unwrap-panic [#unwrap-panic]
-
-`unwrap-panic` extracts a value or causes a runtime panic.
-
-**Signature**
-
-```clarity
-(unwrap-panic optional-or-response)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `optional-or-response` | optional/response | Value to unwrap |
-
-```clarity
-(unwrap-panic (some u42)) ;; Returns u42
-(unwrap-panic none) ;; Runtime panic
-
-;; Critical unwrap
-(define-read-only (get-critical-value)
- (unwrap-panic (map-get? critical-config "version")))
-```
-
-### unwrap-err-panic [#unwrap-err-panic]
-
-`unwrap-err-panic` extracts an error value or causes a runtime panic.
-
-**Signature**
-
-```clarity
-(unwrap-err-panic response)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `response` | response | Response to unwrap |
-
-```clarity
-(unwrap-err-panic (err u404)) ;; Returns u404
-(unwrap-err-panic (ok u42)) ;; Runtime panic
-
-;; Force error
-(define-read-only (get-error-code)
- (unwrap-err-panic (always-fails)))
-```
-
-## Data helpers [#data-helpers]
-
-### default-to [#default-to]
-
-`default-to` returns a default value for none.
-
-**Signature**
-
-```clarity
-(default-to default optional)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `default` | any | Default value |
-| `optional` | optional | Optional value |
-
-```clarity
-(default-to u0 (some u42)) ;; Returns u42
-(default-to u0 none) ;; Returns u0
-
-;; Safe defaults
-(define-read-only (get-balance-safe (user principal))
- (default-to u0 (map-get? balances user)))
-```
-
-### merge [#merge]
-
-`merge` combines two tuples, with the second overriding the first.
-
-**Signature**
-
-```clarity
-(merge tuple1 tuple2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `tuple1` | tuple | Base tuple |
-| `tuple2` | tuple | Override tuple |
-
-```clarity
-(merge { a: u1, b: u2 } { b: u3, c: u4 })
-;; Returns { a: u1, b: u3, c: u4 }
-
-;; Update record
-(define-public (update-profile (updates { name: (optional (string-ascii 50)), age: (optional uint) }))
- (let ((current (default-to { name: "", age: u0 } (map-get? profiles tx-sender))))
- (map-set profiles tx-sender (merge current updates))
- (ok true)))
-```
-
-### get [#get]
-
-`get` extracts a value from a tuple by key.
-
-**Signature**
-
-```clarity
-(get key tuple)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `key` | symbol | Key to extract |
-| `tuple` | tuple | Tuple to access |
-
-```clarity
-(get balance { balance: u100, locked: u50 }) ;; Returns u100
-
-;; Access nested data
-(define-read-only (get-user-balance (user principal))
- (match (map-get? accounts user)
- account (get balance account)
- u0))
-```
-
-### as-max-len? [#as-max-len]
-
-`as-max-len?` checks if a sequence fits within a maximum length.
-
-**Signature**
-
-```clarity
-(as-max-len? sequence max-length)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `sequence` | sequence | Sequence to check |
-| `max-length` | uint | Maximum allowed length |
-
-```clarity
-(as-max-len? (list 1 2 3) u5) ;; Returns (some (1 2 3))
-(as-max-len? "Hello" u3) ;; Returns none
-
-;; Safe append
-(define-public (add-to-list (item uint))
- (match (as-max-len? (append (var-get items) item) u100)
- new-list (begin
- (var-set items new-list)
- (ok true))
- (err u1)))
-```
-
-## Control flow [#control-flow]
-
-### if [#if]
-
-`if` evaluates a condition and returns one of two values.
-
-**Signature**
-
-```clarity
-(if condition true-branch false-branch)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `condition` | `bool` | Condition to evaluate |
-| `true-branch` | any | Value if true |
-| `false-branch` | any | Value if false |
-
-```clarity
-(if (> u10 u5)
- "Greater"
- "Not greater") ;; Returns "Greater"
-
-;; Conditional logic
-(define-public (withdraw (amount uint))
- (let ((balance (get-balance tx-sender)))
- (if (>= balance amount)
- (begin
- (map-set balances tx-sender (- balance amount))
- (ok amount))
- (err u1))))
-```
-
-### match [#match]
-
-`match` performs pattern matching on optional and response types.
-
-**Signature**
-
-```clarity
-(match value
- some-name some-branch
- none-branch)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `value` | optional/response | Value to match |
-| `some-name` | symbol | Binding for some value |
-| `some-branch` | expression | Expression if some |
-| `none-branch` | expression | Expression if none |
-
-```clarity
-(match (map-get? balances tx-sender)
- balance (ok balance)
- (err u404))
-
-;; Response matching
-(match (ft-transfer? token u100 tx-sender recipient)
- success (ok "Transfer successful")
- error (err error))
-
-;; Nested matching
-(define-read-only (get-user-name (user principal))
- (match (map-get? user-profiles user)
- profile (match (get name profile)
- name (ok name)
- (err u1))
- (err u404)))
-```
-
-### begin [#begin]
-
-`begin` executes multiple expressions in sequence.
-
-**Signature**
-
-```clarity
-(begin expr1 expr2... last-expr)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| expr1, expr2, ... | any | Expressions to execute |
-| `last-expr` | any | Final expression (return value) |
-
-```clarity
-(begin
- (print "Starting")
- (var-set counter u1)
- (ok true))
-
-;; Multiple operations
-(define-public (initialize)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (var-set is-initialized true)
- (map-set admins tx-sender true)
- (print { event: "initialized", by: tx-sender })
- (ok true)))
-```
-
-### let [#let]
-
-`let` creates local bindings for use in an expression.
-
-**Signature**
-
-```clarity
-(let ((name1 value1) (name2 value2)...) body)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `name` | symbol | Binding name |
-| `value` | any | Value to bind |
-| `body` | expression | Expression using bindings |
-
-```clarity
-(let ((x 10) (y 20))
- (+ x y)) ;; Returns 30
-
-;; Complex calculations
-(define-public (calculate-reward (days uint))
- (let (
- (balance (get-balance tx-sender))
- (rate u5) ;; 5% annual
- (reward (/ (* balance rate days) u36500)))
- (begin
- (map-set rewards tx-sender reward)
- (ok reward))))
-```
-
-## Optional & response types [#optional-response-types]
-
-### some [#some]
-
-`some` constructs an optional value that contains a value.
-
-**Signature**
-
-```clarity
-(some value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `value` | any | Value to wrap |
-
-```clarity
-(some u42) ;; Returns (some u42)
-(some "Hello") ;; Returns (some "Hello")
-
-;; Return optional
-(define-read-only (find-user (id uint))
- (if (map-get? users id)
- (some (map-get? users id))
- none))
-```
-
-### is-ok [#is-ok]
-
-`is-ok` checks if a response is ok.
-
-**Signature**
-
-```clarity
-(is-ok response)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `response` | response | Response to check |
-
-```clarity
-(is-ok (ok u42)) ;; Returns true
-(is-ok (err u1)) ;; Returns false
-
-;; Check success
-(define-read-only (was-successful (tx-id uint))
- (is-ok (map-get? transaction-results tx-id)))
-```
-
-### is-err [#is-err]
-
-`is-err` checks if a response is err.
-
-**Signature**
-
-```clarity
-(is-err response)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `response` | response | Response to check |
-
-```clarity
-(is-err (err u404)) ;; Returns true
-(is-err (ok u42)) ;; Returns false
-
-;; Check failure
-(define-read-only (has-error (result (response uint uint)))
- (is-err result))
-```
-
-### is-some [#is-some]
-
-`is-some` checks if an optional contains a value.
-
-**Signature**
-
-```clarity
-(is-some optional)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `optional` | optional | Optional to check |
-
-```clarity
-(is-some (some u42)) ;; Returns true
-(is-some none) ;; Returns false
-
-;; Check existence
-(define-read-only (user-exists (user principal))
- (is-some (map-get? users user)))
-```
-
-### is-none [#is-none]
-
-`is-none` checks if an optional is none.
-
-**Signature**
-
-```clarity
-(is-none optional)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `optional` | optional | Optional to check |
-
-```clarity
-(is-none none) ;; Returns true
-(is-none (some u42)) ;; Returns false
-
-;; Check absence
-(define-read-only (is-available (name (string-ascii 50)))
- (is-none (map-get? reserved-names name)))
-```
-
-## Fungible tokens [#fungible-tokens]
-
-### define-fungible-token [#define-fungible-token]
-
-`define-fungible-token` creates a new fungible token.
-
-**Signature**
-
-```clarity
-(define-fungible-token token-name [total-supply])
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token-name` | symbol | Name of the token |
-| `total-supply` | `uint` (optional) | Maximum supply |
-
-```clarity
-(define-fungible-token my-token)
-(define-fungible-token limited-token u1000000)
-
-;; With helper functions
-(define-public (get-balance (user principal))
- (ok (ft-get-balance my-token user)))
-```
-
-### ft-mint? [#ft-mint]
-
-`ft-mint?` creates new tokens for a recipient.
-
-**Signature**
-
-```clarity
-(ft-mint? token amount recipient)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | Token to mint |
-| `amount` | `uint` | Amount to mint |
-| `recipient` | `principal` | Recipient of tokens |
-
-```clarity
-(ft-mint? my-token u100 tx-sender)
-
-;; Mint with checks
-(define-public (mint-tokens (amount uint) (recipient principal))
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (ft-mint? my-token amount recipient)))
-```
-
-### ft-burn? [#ft-burn]
-
-`ft-burn?` destroys tokens from an owner.
-
-**Signature**
-
-```clarity
-(ft-burn? token amount owner)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | Token to burn |
-| `amount` | `uint` | Amount to burn |
-| `owner` | `principal` | Owner of tokens |
-
-```clarity
-(ft-burn? my-token u50 tx-sender)
-
-;; Burn own tokens
-(define-public (burn (amount uint))
- (ft-burn? my-token amount tx-sender))
-```
-
-### ft-transfer? [#ft-transfer]
-
-`ft-transfer?` transfers tokens between principals.
-
-**Signature**
-
-```clarity
-(ft-transfer? token amount sender recipient)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | Token to transfer |
-| `amount` | `uint` | Amount to transfer |
-| `sender` | `principal` | Sender |
-| `recipient` | `principal` | Recipient |
-
-```clarity
-(ft-transfer? my-token u50 tx-sender recipient)
-
-;; Transfer with memo
-(define-public (transfer-memo (amount uint) (recipient principal) (memo (buff 32)))
- (begin
- (print { action: "transfer", amount: amount, memo: memo })
- (ft-transfer? my-token amount tx-sender recipient)))
-```
-
-### ft-get-balance [#ft-get-balance]
-
-`ft-get-balance` returns the token balance of a principal.
-
-**Signature**
-
-```clarity
-(ft-get-balance token principal)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | Token to query |
-| `principal` | `principal` | Account to check |
-
-```clarity
-(ft-get-balance my-token tx-sender) ;; Returns uint
-
-;; Balance check
-(define-read-only (has-sufficient-balance (user principal) (required uint))
- (>= (ft-get-balance my-token user) required))
-```
-
-### ft-get-supply [#ft-get-supply]
-
-`ft-get-supply` returns the current token supply.
-
-**Signature**
-
-```clarity
-(ft-get-supply token)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | Token to query |
-
-```clarity
-(ft-get-supply my-token) ;; Returns uint
-
-;; Supply metrics
-(define-read-only (get-supply-info)
- {
- current: (ft-get-supply my-token),
- max: u1000000,
- remaining: (- u1000000 (ft-get-supply my-token))
- })
-```
-
-## Non-fungible tokens [#non-fungible-tokens]
-
-### define-non-fungible-token [#define-non-fungible-token]
-
-`define-non-fungible-token` creates a new non-fungible token.
-
-**Signature**
-
-```clarity
-(define-non-fungible-token token-name identifier-type)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token-name` | symbol | Name of the NFT |
-| `identifier-type` | type | Type of the identifier |
-
-```clarity
-(define-non-fungible-token my-nft uint)
-(define-non-fungible-token complex-nft { id: uint, serial: (buff 20) })
-
-;; NFT with metadata
-(define-map nft-metadata uint {
- name: (string-ascii 50),
- uri: (string-ascii 200)
-})
-```
-
-### nft-mint? [#nft-mint]
-
-`nft-mint?` creates a new NFT for a recipient.
-
-**Signature**
-
-```clarity
-(nft-mint? token identifier recipient)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | NFT to mint |
-| `identifier` | any | Unique identifier |
-| `recipient` | `principal` | Recipient |
-
-```clarity
-(nft-mint? my-nft u1 tx-sender)
-
-;; Mint with metadata
-(define-public (mint-with-metadata (id uint) (name (string-ascii 50)) (uri (string-ascii 200)))
- (begin
- (try! (nft-mint? my-nft id tx-sender))
- (map-set nft-metadata id { name: name, uri: uri })
- (ok id)))
-```
-
-### nft-burn? [#nft-burn]
-
-`nft-burn?` destroys an NFT.
-
-**Signature**
-
-```clarity
-(nft-burn? token identifier owner)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | NFT to burn |
-| `identifier` | any | NFT identifier |
-| `owner` | `principal` | Current owner |
-
-```clarity
-(nft-burn? my-nft u1 tx-sender)
-
-;; Burn with ownership check
-(define-public (burn-nft (id uint))
- (let ((owner (unwrap! (nft-get-owner? my-nft id) (err u404))))
- (asserts! (is-eq owner tx-sender) (err u403))
- (nft-burn? my-nft id tx-sender)))
-```
-
-### nft-transfer? [#nft-transfer]
-
-`nft-transfer?` transfers an NFT between principals.
-
-**Signature**
-
-```clarity
-(nft-transfer? token identifier sender recipient)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | NFT to transfer |
-| `identifier` | any | NFT identifier |
-| `sender` | `principal` | Current owner |
-| `recipient` | `principal` | New owner |
-
-```clarity
-(nft-transfer? my-nft u1 tx-sender recipient)
-
-;; Safe transfer
-(define-public (transfer (id uint) (recipient principal))
- (let ((owner (unwrap! (nft-get-owner? my-nft id) (err u404))))
- (asserts! (is-eq owner tx-sender) (err u403))
- (nft-transfer? my-nft id tx-sender recipient)))
-```
-
-### nft-get-owner? [#nft-get-owner]
-
-`nft-get-owner?` returns the owner of an NFT.
-
-**Signature**
-
-```clarity
-(nft-get-owner? token identifier)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `token` | token-name | NFT to query |
-| `identifier` | any | NFT identifier |
-
-```clarity
-(nft-get-owner? my-nft u1) ;; Returns (optional principal)
-
-;; Ownership check
-(define-read-only (is-owner (id uint) (user principal))
- (match (nft-get-owner? my-nft id)
- owner (is-eq owner user)
- false))
-```
-
-## STX operations [#stx-operations]
-
-### stx-transfer? [#stx-transfer]
-
-`stx-transfer?` transfers STX between addresses.
-
-**Signature**
-
-```clarity
-(stx-transfer? amount sender recipient)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `amount` | `uint` | Amount in microSTX |
-| `sender` | `principal` | Sender address |
-| `recipient` | `principal` | Recipient address |
-
-```clarity
-(stx-transfer? u1000000 tx-sender recipient) ;; Transfer 1 STX
-
-;; Payment function
-(define-public (pay (amount uint) (recipient principal))
- (begin
- (asserts! (> amount u0) (err u1))
- (stx-transfer? amount tx-sender recipient)))
-```
-
-### stx-transfer-memo? [#stx-transfer-memo]
-
-`stx-transfer-memo?` transfers STX with a memo.
-
-**Signature**
-
-```clarity
-(stx-transfer-memo? amount sender recipient memo)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `amount` | `uint` | Amount in microSTX |
-| `sender` | `principal` | Sender address |
-| `recipient` | `principal` | Recipient address |
-| `memo` | `(buff 34)` | Transfer memo |
-
-```clarity
-(stx-transfer-memo? u1000000 tx-sender recipient 0x12345678)
-
-;; Payment with reference
-(define-public (pay-invoice (amount uint) (recipient principal) (invoice-id (buff 16)))
- (stx-transfer-memo? amount tx-sender recipient
- (concat 0x494e56 invoice-id))) ;; "INV" prefix
-```
-
-### stx-burn? [#stx-burn]
-
-`stx-burn?` burns STX by sending to a burn address.
-
-**Signature**
-
-```clarity
-(stx-burn? amount sender)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `amount` | `uint` | Amount to burn |
-| `sender` | `principal` | Address burning STX |
-
-```clarity
-(stx-burn? u1000000 tx-sender)
-
-;; Burn mechanism
-(define-public (burn-stx (amount uint))
- (begin
- (asserts! (> amount u0) (err u1))
- (stx-burn? amount tx-sender)))
-```
-
-### stx-get-balance [#stx-get-balance]
-
-`stx-get-balance` returns the STX balance of an address.
-
-**Signature**
-
-```clarity
-(stx-get-balance principal)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `principal` | `principal` | Address to check |
-
-```clarity
-(stx-get-balance tx-sender) ;; Returns uint
-
-;; Balance check
-(define-read-only (can-afford-fee (user principal) (fee uint))
- (>= (stx-get-balance user) fee))
-```
-
-### stx-account [#stx-account]
-
-`stx-account` returns detailed account information.
-
-**Signature**
-
-```clarity
-(stx-account principal)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `principal` | `principal` | Address to query |
-
-```clarity
-(stx-account tx-sender)
-;; Returns { locked: uint, unlock-height: uint, unlocked: uint }
-
-;; Get available balance
-(define-read-only (get-available-balance (user principal))
- (get unlocked (stx-account user)))
-```
-
-## Cryptographic functions [#cryptographic-functions]
-
-### sha256 [#sha256]
-
-`sha256` computes the SHA-256 hash of input data.
-
-**Signature**
-
-```clarity
-(sha256 data)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `data` | sequence | Data to hash |
-
-```clarity
-(sha256 0x616263) ;; Returns SHA-256 of "abc"
-(sha256 "Hello") ;; Hash string
-
-;; Create hash commitment
-(define-public (commit-hash (data (buff 32)))
- (let ((hash (sha256 data)))
- (map-set commitments tx-sender hash)
- (ok hash)))
-```
-
-### sha512 [#sha512]
-
-`sha512` computes the SHA-512 hash of input data.
-
-**Signature**
-
-```clarity
-(sha512 data)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `data` | sequence | Data to hash |
-
-```clarity
-(sha512 0x616263) ;; Returns SHA-512 hash
-(sha512 "data") ;; Hash string
-
-;; High security hash
-(define-read-only (secure-hash (input (buff 1024)))
- (sha512 input))
-```
-
-### sha512/256 [#sha512-256]
-
-`sha512/256` computes the SHA-512/256 hash of input data.
-
-**Signature**
-
-```clarity
-(sha512/256 data)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `data` | sequence | Data to hash |
-
-```clarity
-(sha512/256 0x616263) ;; Returns 256-bit hash
-(sha512/256 "secure") ;; Hash string
-
-;; Merkle tree node
-(define-private (hash-pair (left (buff 32)) (right (buff 32)))
- (sha512/256 (concat left right)))
-```
-
-### keccak256 [#keccak256]
-
-`keccak256` computes the Keccak-256 hash of input data.
-
-**Signature**
-
-```clarity
-(keccak256 data)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `data` | sequence | Data to hash |
-
-```clarity
-(keccak256 0x616263) ;; Returns Keccak-256 hash
-(keccak256 "ethereum") ;; Hash string
-
-;; Ethereum compatibility
-(define-read-only (eth-compatible-hash (data (buff 256)))
- (keccak256 data))
-```
-
-### hash160 [#hash160]
-
-`hash160` computes RIPEMD160(SHA256(data)).
-
-**Signature**
-
-```clarity
-(hash160 data)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `data` | sequence | Data to hash |
-
-```clarity
-(hash160 0x616263) ;; Returns 160-bit hash
-(hash160 "address") ;; Hash string
-
-;; Bitcoin-style address
-(define-read-only (create-hash160-id (data (buff 32)))
- (hash160 data))
-```
-
-### secp256k1-verify [#secp256k1-verify]
-
-`secp256k1-verify` verifies a signature against a message hash.
-
-**Signature**
-
-```clarity
-(secp256k1-verify hash signature public-key)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `hash` | `(buff 32)` | Message hash |
-| `signature` | `(buff 65)` | Signature |
-| `public-key` | `(buff 33)` | Public key |
-
-```clarity
-(secp256k1-verify
- 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
- signature
- public-key) ;; Returns bool
-
-;; Signature verification
-(define-public (verify-signature (hash (buff 32)) (sig (buff 65)) (pubkey (buff 33)))
- (ok (secp256k1-verify hash sig pubkey)))
-```
-
-### secp256k1-recover? [#secp256k1-recover]
-
-`secp256k1-recover?` recovers a public key from a signature.
-
-**Signature**
-
-```clarity
-(secp256k1-recover? hash signature)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `hash` | `(buff 32)` | Message hash |
-| `signature` | `(buff 65)` | Signature |
-
-```clarity
-(secp256k1-recover? message-hash signature)
-;; Returns (optional (buff 33))
-
-;; Recover signer
-(define-read-only (recover-signer (hash (buff 32)) (sig (buff 65)))
- (secp256k1-recover? hash sig))
-```
-
-## Blockchain data [#blockchain-data]
-
-### get-block-info? [#get-block-info]
-
-`get-block-info?` retrieves information about a block.
-
-**Signature**
-
-```clarity
-(get-block-info? property block)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `property` | PropertyName | Property to retrieve |
-| `block` | `uint` | Block height |
-
-Properties: `header-hash`, `burnchain-header-hash`, `time`, `miner-address`, `block-reward`, `miner-spend-total`, `miner-spend-winner`
-
-```clarity
-(get-block-info? time u100) ;; Returns (optional uint)
-(get-block-info? miner-address u200) ;; Returns (optional principal)
-
-;; Get block time
-(define-read-only (get-block-timestamp (height uint))
- (get-block-info? time height))
-```
-
-### get-burn-block-info? [#get-burn-block-info]
-
-`get-burn-block-info?` retrieves Bitcoin block information.
-
-**Signature**
-
-```clarity
-(get-burn-block-info? property block)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `property` | PropertyName | Property to retrieve |
-| `block` | `uint` | Burn block height |
-
-Properties: `header-hash`, `pox-addrs`
-
-```clarity
-(get-burn-block-info? header-hash u100) ;; Returns (optional (buff 32))
-
-;; Get burn block hash
-(define-read-only (get-btc-header-hash (height uint))
- (get-burn-block-info? header-hash height))
-```
-
-### get-stacks-block-info? [#get-stacks-block-info]
-
-`get-stacks-block-info?` retrieves Stacks block information.
-
-**Signature**
-
-```clarity
-(get-stacks-block-info? property block)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `property` | PropertyName | Property to retrieve |
-| `block` | `uint` | Stacks block height |
-
-Properties: `header-hash`, `block-hash`, `miner-address`, `block-reward`
-
-```clarity
-(get-stacks-block-info? block-hash u100) ;; Returns (optional (buff 32))
-
-;; Get stacks block data
-(define-read-only (get-stacks-block-hash (height uint))
- (get-stacks-block-info? block-hash height))
-```
-
-### get-tenure-info? [#get-tenure-info]
-
-`get-tenure-info?` retrieves tenure information.
-
-**Signature**
-
-```clarity
-(get-tenure-info? property block)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `property` | PropertyName | Property to retrieve |
-| `block` | `uint` | Tenure block |
-
-Properties: `burnchain-header-hash`, `miner-address`, `time`, `vrf-seed`
-
-```clarity
-(get-tenure-info? vrf-seed u100) ;; Returns (optional (buff 32))
-
-;; Get tenure VRF seed
-(define-read-only (get-vrf-seed (tenure uint))
- (get-tenure-info? vrf-seed tenure))
-```
-
-### at-block [#at-block]
-
-`at-block` evaluates an expression at a specific block context.
-
-**Signature**
-
-```clarity
-(at-block block-hash expr)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `block-hash` | `(buff 32)` | Block hash |
-| `expr` | expression | Expression to evaluate |
-
-```clarity
-(at-block 0x1234... (var-get counter)) ;; Get historical value
-
-;; Historical balance
-(define-read-only (get-balance-at-block (user principal) (block-hash (buff 32)))
- (at-block block-hash (ft-get-balance my-token user)))
-```
-
-## Principal & contract operations [#principal-contract-operations]
-
-### principal-construct? [#principal-construct]
-
-`principal-construct?` creates a principal from address components.
-
-**Signature**
-
-```clarity
-(principal-construct? version-byte hash)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `version-byte` | `(buff 1)` | Version byte |
-| `hash` | `(buff 20)` | Address hash |
-
-```clarity
-(principal-construct? 0x16 0x1234567890abcdef1234567890abcdef12345678)
-;; Returns (optional principal)
-
-;; Construct address
-(define-read-only (make-principal (version (buff 1)) (hash (buff 20)))
- (principal-construct? version hash))
-```
-
-### principal-destruct? [#principal-destruct]
-
-`principal-destruct?` decomposes a principal into components.
-
-**Signature**
-
-```clarity
-(principal-destruct? principal)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `principal` | `principal` | Principal to decompose |
-
-```clarity
-(principal-destruct? tx-sender)
-;; Returns (optional { version: (buff 1), hash: (buff 20) })
-
-;; Get address components
-(define-read-only (get-principal-parts (user principal))
- (principal-destruct? user))
-```
-
-### principal-of? [#principal-of]
-
-`principal-of?` returns the principal from a public key.
-
-**Signature**
-
-```clarity
-(principal-of? public-key)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `public-key` | `(buff 33)` | Public key |
-
-```clarity
-(principal-of? 0x0234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12)
-;; Returns (optional principal)
-
-;; Derive address
-(define-read-only (pubkey-to-principal (pubkey (buff 33)))
- (principal-of? pubkey))
-```
-
-### contract-call? [#contract-call]
-
-`contract-call?` calls a public function in another contract.
-
-**Signature**
-
-```clarity
-(contract-call? contract function-name args...)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `contract` | principal | Contract to call |
-| `function-name` | symbol | Function name |
-| `args` | any | Function arguments |
-
-```clarity
-(contract-call? .other-contract transfer u100 tx-sender recipient)
-
-;; Cross-contract call
-(define-public (forward-call (amount uint))
- (contract-call? .token-contract transfer amount tx-sender contract-owner))
-```
-
-### as-contract [#as-contract]
-
-`as-contract` executes an expression with the contract as tx-sender.
-
-**Signature**
-
-```clarity
-(as-contract expr)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `expr` | expression | Expression to execute |
-
-```clarity
-(as-contract (stx-transfer? u1000 tx-sender recipient))
-
-;; Contract-owned transfers
-(define-public (withdraw-fees (recipient principal))
- (let ((balance (stx-get-balance (as-contract tx-sender))))
- (as-contract (stx-transfer? balance tx-sender recipient))))
-```
-
-### contract-of [#contract-of]
-
-`contract-of` returns the principal of a trait reference.
-
-**Signature**
-
-```clarity
-(contract-of trait-ref)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `trait-ref` | trait | Trait reference |
-
-```clarity
-(contract-of token-trait) ;; Returns principal
-
-;; Get implementation
-(define-read-only (get-token-contract)
- (contract-of deployed-token))
-```
-
-### is-standard [#is-standard]
-
-`is-standard` checks if a principal matches the current network type and can spend tokens.
-
-**Signature**
-
-```clarity
-(is-standard standard-or-contract-principal)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `standard-or-contract-principal` | `principal` | Principal to check |
-
-```clarity
-;; On testnet
-(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6) ;; Returns true
-(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.foo) ;; Returns true
-(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY) ;; Returns false
-
-;; On mainnet
-(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY) ;; Returns true
-(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY.foo) ;; Returns true
-(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6) ;; Returns false
-```
-
-Key points:
-- Tests if a principal can spend tokens on the current network
-- Mainnet: Only `SP` and `SM` addresses can spend
-- Testnet: Only `ST` and `SN` addresses can spend
-- All addresses can receive tokens, but only matching network types can spend
-- Available starting with Stacks 2.1
-
-```clarity
-;; Network-aware validation
-(define-read-only (can-spend-on-network (address principal))
- (is-standard address))
-
-;; Check if address matches network before allowing spending
-(define-public (network-aware-transfer (recipient principal) (amount uint))
- (begin
- (asserts! (is-standard tx-sender) (err u401))
- (asserts! (is-standard recipient) (err u402))
- ;; Transfer logic
- (ok true)))
-```
-
-## Traits [#traits]
-
-### define-trait [#define-trait]
-
-`define-trait` creates a new trait definition.
-
-**Signature**
-
-```clarity
-(define-trait trait-name ((function-name (args...) response-type)...))
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `trait-name` | symbol | Name of the trait |
-| `function-name` | symbol | Function signatures |
-
-```clarity
-(define-trait fungible-token (
- (transfer (uint principal principal) (response bool uint))
- (get-balance (principal) (response uint uint))
-))
-
-;; NFT trait
-(define-trait nft-trait (
- (transfer (uint principal principal) (response bool uint))
- (get-owner (uint) (response (optional principal) uint))
-))
-```
-
-### impl-trait [#impl-trait]
-
-`impl-trait` declares that a contract implements a trait.
-
-**Signature**
-
-```clarity
-(impl-trait trait-identifier)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `trait-identifier` | trait | Trait to implement |
-
-```clarity
-(impl-trait .token-trait.fungible-token)
-
-;; Multiple traits
-(impl-trait .dao-traits.proposal-trait)
-(impl-trait .dao-traits.voting-trait)
-```
-
-### use-trait [#use-trait]
-
-`use-trait` creates a trait alias for use in functions.
-
-**Signature**
-
-```clarity
-(use-trait alias trait-identifier)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `alias` | symbol | Local alias |
-| `trait-identifier` | trait | Trait to alias |
-
-```clarity
-(use-trait token-trait .token-trait.fungible-token)
-
-(define-public (swap (token ) (amount uint))
- (contract-call? token transfer amount tx-sender .pool))
-```
-
-## Type conversions [#type-conversions]
-
-### to-int [#to-int]
-
-`to-int` converts an unsigned integer to a signed integer.
-
-**Signature**
-
-```clarity
-(to-int uint)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `uint` | `uint` | Unsigned integer |
-
-```clarity
-(to-int u100) ;; Returns 100
-(to-int u0) ;; Returns 0
-
-;; Convert for calculations
-(define-read-only (calculate-delta (a uint) (b uint))
- (- (to-int a) (to-int b)))
-```
-
-### to-uint [#to-uint]
-
-`to-uint` converts a signed integer to an unsigned integer.
-
-**Signature**
-
-```clarity
-(to-uint int)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `int` | `int` | Signed integer |
-
-```clarity
-(to-uint 100) ;; Returns u100
-(to-uint -50) ;; Causes runtime error
-
-;; Safe conversion
-(define-read-only (safe-to-uint (value int))
- (if (>= value 0)
- (some (to-uint value))
- none))
-```
-
-### to-consensus-buff? [#to-consensus-buff]
-
-`to-consensus-buff?` serializes a value to consensus format.
-
-**Signature**
-
-```clarity
-(to-consensus-buff? value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `value` | any | Value to serialize |
-
-```clarity
-(to-consensus-buff? u100) ;; Returns (optional (buff 3))
-(to-consensus-buff? { a: u1, b: u2 }) ;; Serializes tuple
-
-;; Create hash of data
-(define-read-only (hash-value (data uint))
- (match (to-consensus-buff? data)
- buff (sha256 buff)
- 0x00))
-```
-
-### from-consensus-buff? [#from-consensus-buff]
-
-`from-consensus-buff?` deserializes from consensus format.
-
-**Signature**
-
-```clarity
-(from-consensus-buff? type buffer)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `type` | type-signature | Expected type |
-| `buffer` | `buff` | Buffer to deserialize |
-
-```clarity
-(from-consensus-buff? uint 0x0100) ;; Returns (optional u1)
-(from-consensus-buff? { a: uint, b: uint } buff) ;; Deserialize tuple
-
-;; Parse stored data
-(define-read-only (decode-data (data (buff 128)))
- (from-consensus-buff? { value: uint, timestamp: uint } data))
-```
-
-## Bit operations [#bit-operations]
-
-### bit-and [#bit-and]
-
-`bit-and` performs bitwise AND operation.
-
-**Signature**
-
-```clarity
-(bit-and i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | First value |
-| `i2` | `int` or `uint` | Second value |
-
-```clarity
-(bit-and u12 u10) ;; Returns u8 (1100 & 1010 = 1000)
-(bit-and 0xFF 0x0F) ;; Returns 0x0F
-
-;; Check flags
-(define-read-only (has-permission (flags uint) (permission uint))
- (> (bit-and flags permission) u0))
-```
-
-### bit-or [#bit-or]
-
-`bit-or` performs bitwise OR operation.
-
-**Signature**
-
-```clarity
-(bit-or i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | First value |
-| `i2` | `int` or `uint` | Second value |
-
-```clarity
-(bit-or u12 u10) ;; Returns u14 (1100 | 1010 = 1110)
-(bit-or 0xF0 0x0F) ;; Returns 0xFF
-
-;; Set flags
-(define-public (add-permission (current uint) (new-permission uint))
- (ok (bit-or current new-permission)))
-```
-
-### bit-xor [#bit-xor]
-
-`bit-xor` performs bitwise XOR operation.
-
-**Signature**
-
-```clarity
-(bit-xor i1 i2)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i1` | `int` or `uint` | First value |
-| `i2` | `int` or `uint` | Second value |
-
-```clarity
-(bit-xor u12 u10) ;; Returns u6 (1100 ^ 1010 = 0110)
-(bit-xor 0xFF 0xFF) ;; Returns 0x00
-
-;; Toggle flags
-(define-public (toggle-flag (flags uint) (flag uint))
- (ok (bit-xor flags flag)))
-```
-
-### bit-not [#bit-not]
-
-`bit-not` performs bitwise NOT operation.
-
-**Signature**
-
-```clarity
-(bit-not i)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i` | `int` or `uint` | Value to invert |
-
-```clarity
-(bit-not u0) ;; Returns maximum uint
-(bit-not 0xFF) ;; Returns -256
-
-;; Invert permissions
-(define-read-only (get-inverse-permissions (permissions uint))
- (bit-not permissions))
-```
-
-### bit-shift-left [#bit-shift-left]
-
-`bit-shift-left` shifts bits to the left.
-
-**Signature**
-
-```clarity
-(bit-shift-left i positions)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i` | `int` or `uint` | Value to shift |
-| `positions` | `uint` | Positions to shift |
-
-```clarity
-(bit-shift-left u1 u3) ;; Returns u8 (1 << 3)
-(bit-shift-left u5 u2) ;; Returns u20
-
-;; Calculate power of 2
-(define-read-only (pow2 (exponent uint))
- (bit-shift-left u1 exponent))
-```
-
-### bit-shift-right [#bit-shift-right]
-
-`bit-shift-right` shifts bits to the right.
-
-**Signature**
-
-```clarity
-(bit-shift-right i positions)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `i` | `int` or `uint` | Value to shift |
-| `positions` | `uint` | Positions to shift |
-
-```clarity
-(bit-shift-right u8 u3) ;; Returns u1 (8 >> 3)
-(bit-shift-right u20 u2) ;; Returns u5
-
-;; Fast division by power of 2
-(define-read-only (div-pow2 (value uint) (exponent uint))
- (bit-shift-right value exponent))
-```
-
-## Utility functions [#utility-functions]
-
-### print [#print]
-
-`print` outputs a value and returns it.
-
-**Signature**
-
-```clarity
-(print value)
-```
-
-**Parameters**
-
-| Name | Type | Description |
-|------|------|-------------|
-| `value` | any | Value to print |
-
-```clarity
-(print "Debug message") ;; Prints and returns "Debug message"
-(print { event: "transfer", amount: u100 })
-
-;; Debug function
-(define-public (debug-transfer (amount uint))
- (begin
- (print { function: "transfer", amount: amount, sender: tx-sender })
- (ok true)))
-```
diff --git a/content/docs/en/resources/clarity/reference/keywords.mdx b/content/docs/en/resources/clarity/reference/keywords.mdx
deleted file mode 100644
index 2c8b9cc1c..000000000
--- a/content/docs/en/resources/clarity/reference/keywords.mdx
+++ /dev/null
@@ -1,552 +0,0 @@
----
-title: Keywords reference
-sidebarTitle: Keywords
-description: Complete reference for all Clarity keywords including constants, context variables, and blockchain data.
-isNew: true
----
-
-Clarity provides built-in keywords for accessing blockchain state, transaction context, and constant values. These keywords enable smart contracts to interact with the Stacks blockchain and make decisions based on current execution context.
-
-- Boolean constants: [`true`](#true), [`false`](#false)
-- Optional constant: [`none`](#none)
-- Block information: [`block-height`](#block-height), [`burn-block-height`](#burn-block-height), [`stacks-block-height`](#stacks-block-height), [`tenure-height`](#tenure-height)
-- Transaction context: [`tx-sender`](#tx-sender), [`tx-sponsor`](#tx-sponsor), [`contract-caller`](#contract-caller)
-- Chain information: [`chain-id`](#chain-id), [`is-in-mainnet`](#is-in-mainnet), [`is-in-regtest`](#is-in-regtest)
-- Economic data: [`stx-liquid-supply`](#stx-liquid-supply)
-
-## Boolean constants [#boolean-constants]
-
-### true [#true]
-
-`true` represents the boolean true value in Clarity.
-
-**Type**
-
-```clarity
-bool
-```
-
-```clarity
-;; Direct usage
-(define-constant is-active true)
-
-;; In conditionals
-(if true
- (print "This will execute")
- (print "This won't execute"))
-
-;; Boolean operations
-(and true true) ;; Returns true
-(or false true) ;; Returns true
-```
-
-Common patterns include using `true` for:
-- Default enabled states in configuration
-- Success return values in public functions
-- Feature flags and toggles
-
-```clarity
-(define-data-var protocol-enabled bool true)
-
-(define-public (pause-protocol)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (var-set protocol-enabled false)
- (ok true)))
-
-;; Feature toggle pattern
-(define-map features (string-ascii 50) bool)
-(map-set features "trading" true)
-(map-set features "staking" true)
-```
-
-### false [#false]
-
-`false` represents the boolean false value in Clarity.
-
-**Type**
-
-```clarity
-bool
-```
-
-```clarity
-;; Direct usage
-(define-constant is-paused false)
-
-;; In conditionals
-(if false
- (print "This won't execute")
- (print "This will execute"))
-
-;; Boolean operations
-(and true false) ;; Returns false
-(or false false) ;; Returns false
-```
-
-Common patterns include using `false` for:
-- Default disabled states
-- Failure indicators
-- Initial unset states
-
-```clarity
-(define-data-var is-initialized bool false)
-
-(define-public (initialize)
- (begin
- (asserts! (not (var-get is-initialized)) (err u100))
- (var-set is-initialized true)
- (ok true)))
-
-;; Access control pattern
-(define-map admins principal bool)
-(define-read-only (is-admin (user principal))
- (default-to false (map-get? admins user)))
-```
-
-## Optional constant [#optional-constant]
-
-### none [#none]
-
-`none` represents an empty optional value.
-
-**Type**
-
-```clarity
-(optional ?)
-```
-
-```clarity
-;; Direct usage
-(define-constant empty-value none)
-
-;; Optional map returns
-(map-get? non-existent-map non-existent-key) ;; Returns none
-
-;; Pattern matching
-(match (map-get? balances user)
- balance (+ balance u100)
- u0) ;; If none, return u0
-```
-
-Common patterns include:
-- Default values for optional types
-- Representing absence of data
-- Initial states before data is set
-
-```clarity
-(define-map user-profiles principal
- {
- name: (string-ascii 50),
- created-at: uint
- })
-
-(define-read-only (get-user-name (user principal))
- (match (map-get? user-profiles user)
- profile (some (get name profile))
- none)) ;; Return none if profile doesn't exist
-
-;; Clearing optional data
-(define-data-var current-proposal (optional uint) none)
-(define-public (clear-proposal)
- (begin
- (var-set current-proposal none)
- (ok true)))
-```
-
-## Block information [#block-information]
-
-### block-height [#block-height]
-
-`block-height` returns the current Stacks block height.
-
-**Type**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get current height
-(print block-height)
-
-;; Time-locked functionality
-(define-public (claim-rewards)
- (begin
- (asserts! (> block-height u50000) (err u1))
- (ok true)))
-```
-
-Use cases include:
-- Implementing vesting schedules
-- Creating time-based phases
-- Recording timestamps
-- Enforcing delays
-
-```clarity
-(define-constant VESTING_START u100000)
-(define-constant VESTING_PERIOD u4320) ;; ~30 days
-
-(define-read-only (get-vested-amount (total uint))
- (if (<= block-height VESTING_START)
- u0
- (let ((blocks-elapsed (- block-height VESTING_START)))
- (if (>= blocks-elapsed VESTING_PERIOD)
- total
- (/ (* total blocks-elapsed) VESTING_PERIOD)))))
-
-;; Phase-based protocol
-(define-constant PHASE1_END u100000)
-(define-constant PHASE2_END u200000)
-
-(define-read-only (get-current-phase)
- (if (<= block-height PHASE1_END)
- u1
- (if (<= block-height PHASE2_END)
- u2
- u3)))
-```
-
-### burn-block-height [#burn-block-height]
-
-`burn-block-height` returns the current Bitcoin block height.
-
-**Type**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get current Bitcoin height
-(print burn-block-height)
-
-;; Bitcoin-anchored timing
-(define-read-only (get-burn-height-difference)
- (- burn-block-height u700000))
-```
-
-Common uses:
-- Bitcoin-anchored timestamps
-- Cross-chain timing coordination
-- Proof-of-Transfer calculations
-
-```clarity
-(define-map btc-price-at-height uint uint)
-
-(define-public (record-btc-price (price uint))
- (begin
- (map-set btc-price-at-height burn-block-height price)
- (ok burn-block-height)))
-
-;; Time calculations based on Bitcoin blocks
-(define-read-only (hours-since (btc-height uint))
- (/ (- burn-block-height btc-height) u6)) ;; ~6 blocks per hour
-```
-
-### stacks-block-height [#stacks-block-height]
-
-`stacks-block-height` returns the current Stacks chain tip height (for Stacks 2.5+).
-
-**Type**
-
-```clarity
-uint
-```
-
-```clarity
-;; Stacks 2.5+ specific height
-(print stacks-block-height)
-
-;; Height comparison
-(define-read-only (get-height-info)
- {
- stacks: stacks-block-height,
- block: block-height,
- difference: (- stacks-block-height block-height)
- })
-```
-
-### tenure-height [#tenure-height]
-
-`tenure-height` returns the number of tenures (reward cycles) that have passed.
-
-**Type**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get current tenure
-(print tenure-height)
-
-;; Tenure-based rewards
-(define-map tenure-rewards uint uint)
-
-(define-read-only (get-rewards-for-tenure (tenure uint))
- (default-to u0 (map-get? tenure-rewards tenure)))
-```
-
-## Transaction context [#transaction-context]
-
-### tx-sender [#tx-sender]
-
-`tx-sender` returns the principal that initiated the current transaction.
-
-**Type**
-
-```clarity
-principal
-```
-
-```clarity
-;; Get transaction originator
-(print tx-sender)
-
-;; Authorization pattern
-(define-constant contract-owner tx-sender)
-
-(define-public (admin-only-function)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (ok true)))
-```
-
-Key characteristics:
-- Remains constant throughout all contract calls
-- Always represents the original transaction initiator
-- Used for authorization and ownership
-
-```clarity
-(define-map balances principal uint)
-
-(define-public (deposit (amount uint))
- (begin
- (try! (stx-transfer? amount tx-sender (as-contract tx-sender)))
- (map-set balances tx-sender
- (+ (default-to u0 (map-get? balances tx-sender)) amount))
- (ok amount)))
-
-;; Multi-signature pattern
-(define-map signers principal bool)
-(define-public (add-signature (proposal-id uint))
- (begin
- (asserts! (default-to false (map-get? signers tx-sender)) (err u401))
- ;; Add signature logic
- (ok true)))
-```
-
-### tx-sponsor [#tx-sponsor]
-
-`tx-sponsor` returns the principal paying for the transaction fees (optional).
-
-**Type**
-
-```clarity
-(optional principal)
-```
-
-```clarity
-;; Check if transaction is sponsored
-(match tx-sponsor
- sponsor (print { sponsored-by: sponsor })
- (print "Not a sponsored transaction"))
-
-;; Get sponsor or sender
-(define-read-only (get-fee-payer)
- (default-to tx-sender tx-sponsor))
-```
-
-Use cases:
-- Fee subsidy programs
-- Gasless transactions
-- Sponsored onboarding
-- User acquisition
-
-```clarity
-(define-map sponsored-actions { user: principal, sponsor: principal } uint)
-
-(define-public (sponsored-action)
- (match tx-sponsor
- sponsor (begin
- ;; Record sponsored action
- (map-set sponsored-actions
- { user: tx-sender, sponsor: sponsor }
- (+ (default-to u0 (map-get? sponsored-actions
- { user: tx-sender, sponsor: sponsor })) u1))
- (ok { user: tx-sender, sponsor: sponsor }))
- (err u1))) ;; Must be sponsored
-
-;; Subsidized operations with approved sponsors
-(define-map approved-sponsors principal bool)
-
-(define-public (subsidized-transfer (recipient principal) (amount uint))
- (match tx-sponsor
- sponsor (begin
- (asserts! (default-to false (map-get? approved-sponsors sponsor)) (err u401))
- (ft-transfer? my-token amount tx-sender recipient))
- ;; Not sponsored - user pays normally
- (ft-transfer? my-token amount tx-sender recipient)))
-```
-
-### contract-caller [#contract-caller]
-
-`contract-caller` returns the immediate calling principal (contract or user).
-
-**Type**
-
-```clarity
-principal
-```
-
-```clarity
-;; Get immediate caller
-(print contract-caller)
-
-;; Direct-call only
-(define-public (direct-only)
- (begin
- (asserts! (is-eq tx-sender contract-caller) (err u405))
- (ok true)))
-```
-
-Important distinctions:
-- Changes with each contract call
-- Equals `tx-sender` for direct calls
-- Represents calling contract in contract-to-contract calls
-
-```clarity
-;; Contract A
-(define-public (call-contract-b)
- (contract-call? .contract-b check-callers))
-
-;; Contract B
-(define-public (check-callers)
- (begin
- (print {
- tx-sender: tx-sender, ;; Original user
- contract-caller: contract-caller ;; Contract A
- })
- (ok true)))
-
-;; Allowlist pattern
-(define-map allowed-contracts principal bool)
-(define-public (restricted-function)
- (begin
- (asserts!
- (or
- (is-eq tx-sender contract-caller) ;; Direct call
- (default-to false (map-get? allowed-contracts contract-caller)))
- (err u401))
- (ok true)))
-```
-
-## Chain information [#chain-information]
-
-### chain-id [#chain-id]
-
-`chain-id` returns the 32-byte chain identifier.
-
-**Type**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get chain ID
-(print chain-id)
-
-;; Mainnet: 0x00000001
-;; Testnet: 0x80000000
-```
-
-### is-in-mainnet [#is-in-mainnet]
-
-`is-in-mainnet` returns true if contract is running on mainnet.
-
-**Type**
-
-```clarity
-bool
-```
-
-```clarity
-;; Check if on mainnet
-(asserts! is-in-mainnet (err u500))
-
-;; Environment-specific constants
-(define-constant TOKEN-SUPPLY
- (if is-in-mainnet
- u1000000000 ;; 1 billion on mainnet
- u1000000)) ;; 1 million on testnet
-```
-
-### is-in-regtest [#is-in-regtest]
-
-`is-in-regtest` returns true if contract is running on regtest.
-
-**Type**
-
-```clarity
-bool
-```
-
-```clarity
-;; Development-only functions
-(define-public (debug-function)
- (begin
- (asserts! is-in-regtest (err u403))
- ;; Debug logic
- (ok true)))
-```
-
-## Economic data [#economic-data]
-
-### stx-liquid-supply [#stx-liquid-supply]
-
-`stx-liquid-supply` returns the total liquid STX supply in micro-STX.
-
-**Type**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get current liquid supply
-(print stx-liquid-supply)
-
-;; Calculate percentage of supply
-(define-read-only (get-percent-of-liquid (amount uint))
- (/ (* amount u10000) stx-liquid-supply)) ;; Returns basis points
-```
-
-Use cases:
-- Economic calculations
-- Supply-based limits
-- Tokenomics implementations
-- Governance thresholds
-
-```clarity
-;; Dynamic fee based on supply percentage
-(define-constant FEE_BASIS_POINTS u50) ;; 0.5%
-
-(define-read-only (calculate-dynamic-fee (amount uint))
- (let (
- (supply-ratio (/ (* amount u1000000) stx-liquid-supply))
- (multiplier (+ u100 supply-ratio)))
- (/ (* amount FEE_BASIS_POINTS multiplier) u10000)))
-
-;; Governance with supply-based thresholds
-(define-constant PROPOSAL_THRESHOLD_BASIS u100) ;; 1% of liquid supply
-
-(define-public (create-proposal (description (string-utf8 500)))
- (let (
- (required-stake (/ (* stx-liquid-supply PROPOSAL_THRESHOLD_BASIS) u10000))
- (user-balance (stx-get-balance tx-sender)))
- (asserts! (>= user-balance required-stake) (err u402))
- (try! (stx-transfer? required-stake tx-sender (as-contract tx-sender)))
- (ok required-stake)))
-```
\ No newline at end of file
diff --git a/content/docs/en/resources/clarity/reference/types.mdx b/content/docs/en/resources/clarity/reference/types.mdx
deleted file mode 100644
index 6e3b29e4c..000000000
--- a/content/docs/en/resources/clarity/reference/types.mdx
+++ /dev/null
@@ -1,193 +0,0 @@
----
-title: Types reference
-sidebarTitle: Types
-description: Clarity's type system ensures program correctness through static type checking
----
-
-Clarity uses a strong static type system. Function arguments and database schemas require specified types, and all types are known at publish time.
-
-## Primitive types
-
-### int
-
-Signed 128-bit integer. Ranges from -2^127 to 2^127 - 1.
-
-```clarity
-(define-constant my-int -10)
-(define-constant max-int 170141183460469231731687303715884105727)
-```
-
-### uint
-
-Unsigned 128-bit integer. Ranges from 0 to 2^128 - 1.
-
-```clarity
-(define-constant my-uint u10)
-(define-constant max-uint u340282366920938463463374607431768211455)
-```
-
-### bool
-
-Boolean value representing true or false.
-
-```clarity
-(define-constant is-active true)
-(define-constant is-disabled false)
-```
-
-### principal
-
-Represents an object that can have a token balance. Can be a standard principal (user address) or contract principal.
-
-```clarity
-;; Standard principal
-'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
-
-;; Contract principal
-'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.contract-name
-```
-
-## Sequence types
-
-### (buff max-len)
-
-Byte buffer with a maximum length. Used for arbitrary binary data.
-
-```clarity
-(define-constant my-buff 0x68656c6c6f) ;; "hello" in hex
-(define-data-var message (buff 20) 0x00)
-```
-
-### (string-ascii max-len)
-
-ASCII string with maximum length. Only supports ASCII characters.
-
-```clarity
-(define-constant name (string-ascii 50) "Clarity")
-(define-data-var user-name (string-ascii 100) "")
-```
-
-### (string-utf8 max-len)
-
-UTF-8 string with maximum length. Supports Unicode characters.
-
-```clarity
-(define-constant greeting (string-utf8 50) u"Hello L! =�")
-(define-data-var status-message (string-utf8 280) u"")
-```
-
-### (list max-len entry-type)
-
-Homogeneous list with specified maximum length and entry type.
-
-```clarity
-(define-constant numbers (list 5 uint) (list u1 u2 u3 u4 u5))
-(define-data-var prices (list 100 uint) (list))
-```
-
-## Composite types
-
-### Tuple
-
-Record with named fields. Each field has a specified type.
-
-```clarity
-{
- name: (string-ascii 50),
- age: uint,
- active: bool
-}
-
-;; Example usage
-(define-constant user {
- name: "Alice",
- age: u30,
- active: true
-})
-```
-
-Tuples are commonly used for:
-- Returning multiple values from functions
-- Structuring complex data
-- Map keys and values
-
-## Special types
-
-### (optional type)
-
-Represents a value that might not exist. Can be `(some value)` or `none`.
-
-```clarity
-(define-data-var winner (optional principal) none)
-
-;; Set value
-(var-set winner (some 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM))
-
-;; Check value
-(match (var-get winner)
- user (print user)
- (print "No winner yet")
-)
-```
-
-### (response ok-type err-type)
-
-Used by public functions to indicate success or failure. Successful responses commit state changes, while error responses abort all changes.
-
-```clarity
-(define-public (divide (a uint) (b uint))
- (if (is-eq b u0)
- (err u1) ;; Division by zero error
- (ok (/ a b))
- )
-)
-```
-
-Response types enable:
-- Atomic transaction semantics
-- Composable error handling
-- Clear success/failure paths
-
-## Type signatures
-
-Functions must specify complete type signatures:
-
-```clarity
-;; Read-only function
-(define-read-only (get-balance (user principal))
- (response uint uint)
- ;; Function body
-)
-
-;; Public function
-(define-public (transfer (amount uint) (recipient principal))
- (response bool uint)
- ;; Function body
-)
-
-;; Private function
-(define-private (validate-amount (amount uint))
- bool
- ;; Function body
-)
-```
-
-## Type inference
-
-While Clarity requires explicit type annotations for function signatures and data declarations, it can infer types within function bodies:
-
-```clarity
-(define-read-only (calculate)
- (let ((x 10) ;; Inferred as int
- (y u20) ;; Inferred as uint
- (name "Test")) ;; Inferred as string-ascii
- (ok x))
-)
-```
-
-
-
-:::callout
-### Type safety
-Clarity's type system prevents many common programming errors at publish time, before any code is executed. This includes type mismatches, null pointer exceptions, and buffer overflows.
-:::
\ No newline at end of file
diff --git a/content/docs/en/resources/guides/using-pyth-price-feeds.mdx b/content/docs/en/resources/guides/using-pyth-price-feeds.mdx
index daf69fe68..8e7d40811 100644
--- a/content/docs/en/resources/guides/using-pyth-price-feeds.mdx
+++ b/content/docs/en/resources/guides/using-pyth-price-feeds.mdx
@@ -177,7 +177,7 @@ We'll create a "Benjamin Club" - an exclusive NFT that costs exactly $100 worth
)
```
- For a detailed explanation of the contract components, see our [Clarity integration guide](/resources/clarity/external-data).
+ For a detailed explanation of the contract components, see the [Stacks smart contract reference](https://docs.stacks.co/reference).
@@ -260,7 +260,7 @@ We'll create a "Benjamin Club" - an exclusive NFT that costs exactly $100 worth
}
```
- For complete frontend integration details, see our [Stacks.js integration guide](/reference/stacks.js/pyth-oracle-integration).
+ For complete frontend integration details, see the [Stacks developer reference](https://docs.stacks.co/reference).
@@ -300,7 +300,7 @@ We'll create a "Benjamin Club" - an exclusive NFT that costs exactly $100 worth
});
```
- For advanced testing strategies including mainnet simulation, see our [Clarinet testing guide](/tools/clarinet/pyth-oracle-integration).
+ For advanced testing strategies including mainnet simulation, review the [official Stacks reference](https://docs.stacks.co/reference).
@@ -413,6 +413,6 @@ Batch multiple price updates when possible:
## Next steps
:::next-steps
-- [Deep dive on Clarity](/resources/clarity/external-data): Advanced oracle patterns and optimizations
-- [Deep dive on frontend](/reference/stacks.js/pyth-oracle-integration): Building production-ready oracle UIs
+- [Deep dive on Clarity](https://docs.stacks.co/reference): Advanced oracle patterns and optimizations
+- [Deep dive on frontend](https://docs.stacks.co/reference): Building production-ready oracle UIs
:::
diff --git a/content/docs/en/tools/clarinet/(clarinet-cli)/clarity-formatter.mdx b/content/docs/en/tools/clarinet/(clarinet-cli)/clarity-formatter.mdx
deleted file mode 100644
index 7cac50a7d..000000000
--- a/content/docs/en/tools/clarinet/(clarinet-cli)/clarity-formatter.mdx
+++ /dev/null
@@ -1,162 +0,0 @@
----
-title: Clarity formatter
-sidebarTitle: Clarity formatter
-description: The Clarity formatter is a tool designed to automatically format your Clarity smart contract code according to standardized style rules. Using consistent formatting improves code readability and maintainability, making it easier for developers to understand, collaborate on, and learn from existing Clarity projects.
----
-
-## Formatting philosophy
-
-The formatter applies an opinionated standard designed to make Clarity code more readable:
-
-- **Line length** - Lines wrap at 80 characters by default
-- **Indentation** - Uses 2 spaces for consistency
-- **Structure** - Enforces consistent patterns for functions, let bindings, and control flow
-
-These defaults are configurable to match your preferences.
-
-### Integration points
-
-The formatter is available in two primary development tools:
-
-1. **Clarity VS Code Extension** - Format directly within your editor
-2. **Clarinet CLI** - Format via command line, including entire projects
-
-## Comparison table
-
-| Aspect | Manual Formatting | Clarity Formatter |
-|--------|------------------|-------------------|
-| Consistency | Varies by developer | Uniform across codebase |
-| Speed | Time-consuming | Instant |
-| Error-prone | Yes | No |
-| Team coordination | Requires style guide | Automatic enforcement |
-
-## Best practices
-
-- **Format on save** - Enable automatic formatting in VS Code
-- **Pre-commit hooks** - Ensure all code is formatted before commits
-- **Team adoption** - Use consistent settings across your team
-
-## Further reading
-
-### Formatting rules in detail
-
-The formatter handles many Clarity constructs with specific rules:
-
-
-
- Function definitions
-
- Functions always span multiple lines with consistent indentation:
-
- ```clarity
- (define-public (my-func
- (amount uint)
- (sender principal)
- )
- (ok true)
- )
- ```
-
- Single arguments may stay on the first line:
-
- ```clarity
- (define-read-only (get-balance (who principal))
- (ok u0)
- )
- ```
-
-
-
-
- Let expressions
-
- Bindings are placed on separate lines with consistent indentation:
-
- ```clarity
- (let (
- (a u1)
- (b u2)
- )
- (body-expression)
- )
- ```
-
-
-
-
- Control flow (if, match)
-
- Each branch gets its own line:
-
- ```clarity
- (if condition
- (then-expression)
- (else-expression)
- )
-
- (match optional-value
- value (handle-some value)
- (handle-none)
- )
- ```
-
-
-
-
- Tuples and maps
-
- Automatically converts to sugared syntax with proper formatting:
-
- ```clarity
- ;; Input: (tuple (n1 u1) (n2 u2))
- ;; Output:
- {
- n1: u1,
- n2: u2,
- }
- ```
-
-
-
-
-### Usage examples
-
-#### VS Code integration
-
-```json
-// settings.json
-"[clarity]": {
- "editor.formatOnSave": true,
-},
-```
-
-#### CLI usage
-
-```terminal
-$ clarinet format --in-place
-```
-
-Format with custom settings:
-
-```terminal
-$ clarinet format -i 4 -l 120 --in-place
-```
-
-Check formatting in CI/CD pipelines:
-
-```terminal
-$ clarinet format --check
-```
-
-The `--check` flag validates that all Clarity files are properly formatted without modifying them. This is perfect for continuous integration workflows where you want to ensure code style consistency.
-
-### Ignoring blocks of code
-
-Prevent formatting of specific code blocks:
-
-```clarity
-;; @format-ignore
-(define-constant something (list
- 1 2 3 ;; Preserves custom spacing
- 4 5 ))
-```
diff --git a/content/docs/en/tools/clarinet/(clarinet-cli)/cli-reference.mdx b/content/docs/en/tools/clarinet/(clarinet-cli)/cli-reference.mdx
deleted file mode 100644
index 69a3e816f..000000000
--- a/content/docs/en/tools/clarinet/(clarinet-cli)/cli-reference.mdx
+++ /dev/null
@@ -1,419 +0,0 @@
----
-title: CLI reference
-sidebarTitle: CLI reference
-isNew: true
----
-
-The Clarinet CLI provides a comprehensive suite of tools for Clarity smart contract development. From project initialization to deployment, Clarinet streamlines your entire development workflow.
-
-- Create a new project: [`clarinet new`](#clarinet-new)
-- Generate a new smart contract: [`clarinet contracts new`](#clarinet-contracts)
-- Validate contract syntax and types: [`clarinet check`](#clarinet-check)
-- Interactive REPL for testing contracts: [`clarinet console`](#clarinet-console)
-- Launch a local development network: [`clarinet devnet start`](#clarinet-devnet)
-- Manage deployments: [`clarinet deployments`](#clarinet-deployments)
-
-## Initialize a new project [#initialize-a-new-project]
-
-### clarinet new
-
-`clarinet new` creates a new project with all necessary configuration files and directory structure.
-
-**Usage**
-
-```console
-clarinet new [OPTIONS]
-```
-
-```terminal
-$ clarinet new my-defi-protocol
-[32mCreate directory[0m [1mmy-defi-protocol[0m
-[32mCreate directory[0m [1mcontracts[0m
-[32mCreate directory[0m [1msettings[0m
-[32mCreate directory[0m [1mtests[0m
-[32mCreate file[0m [1mClarinet.toml[0m
-[32mCreate file[0m [1msettings/Mainnet.toml[0m
-[32mCreate file[0m [1msettings/Testnet.toml[0m
-[32mCreate file[0m [1msettings/Devnet.toml[0m
-[32mCreate directory[0m [1m.vscode[0m
-[32mCreate file[0m [1m.vscode/settings.json[0m
-[32mCreate file[0m [1m.vscode/tasks.json[0m
-[32mCreate file[0m [1m.gitignore[0m
-[32mCreate file[0m [1m.gitattributes[0m
-[32mCreate file[0m [1mpackage.json[0m
-[32mCreate file[0m [1mtsconfig.json[0m
-[32mCreate file[0m [1mvitest.config.js[0m
-```
-
-| Option | Description |
-|--------|-------------|
-| `--disable-telemetry` | Do not provide developer usage telemetry for this project |
-
-## Manage your contracts [#manage-your-contracts]
-
-### clarinet contracts
-
-`clarinet contracts` is a subcommand for working with contracts. It has two subcommands:
-
-| Command | Description |
-|---------|-------------|
-| `new` | Generate files and settings for a new contract |
-| `rm` | Remove files and settings for a contract |
-
-**Usage with `new`**
-
-```console
-clarinet contracts new
-```
-
-```terminal
-$ clarinet contracts new fungible-token
-[32mCreated file[0m [1mcontracts/fungible-token.clar[0m
-[32mCreated file[0m [1mtests/fungible-token.test.ts[0m
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-**Usage with `rm`**
-
-```console
-clarinet contracts rm
-```
-
-```terminal
-$ clarinet contracts rm old-token
-[33mRemoved file[0m [1mcontracts/old-token.clar[0m
-[33mRemoved file[0m [1mtests/old-token.test.ts[0m
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-| Option | Description |
-|--------|-------------|
-| `--manifest-path ` | Path to Clarinet.toml |
-
-## Validate your contracts [#validate-your-contracts]
-
-### clarinet check
-
-`clarinet check` checks contracts syntax and performs type checking.
-
-**Usage**
-
-```console
-$ clarinet check [FILE] [OPTIONS]
-```
-
-```terminal
-$ clarinet check
-[32m✔[0m [1m3 contracts checked[0m
-$ clarinet check contracts/token.clar
-[32m✔[0m [1mcontracts/token.clar syntax checks passed[0m
-```
-
-| Option | Short | Description |
-|--------|-------|-------------|
-| `--manifest-path ` | `-m` | Path to Clarinet.toml |
-| `--deployment-plan-path ` | `-p` | If specified, use this deployment file |
-| `--use-on-disk-deployment-plan` | `-d` | Use on disk deployment plan (prevent updates computing) |
-| `--use-computed-deployment-plan` | `-c` | Use computed deployment plan (will overwrite on disk version if any update) |
-| `--enable-clarity-wasm` | | Allow the Clarity Wasm preview to run in parallel with the Clarity interpreter (beta) |
-
-## Interact with your contracts in a local REPL [#interact-with-your-contracts-in-a-local-repl]
-
-### clarinet console
-
-`clarinet console` loads contracts in a REPL for an interactive session.
-
-**Usage**
-
-```console
-$ clarinet console [OPTIONS]
-```
-
-```terminal
-$ clarinet console
-[32mclarity-repl v1.0.0[0m
-Enter ".help" for usage hints.
-Connected to a transient in-memory database.
-```
-
-The Clarinet console offers a variety of commands for contract interaction:
-
-- `::help`: Lists all console commands
-- `::functions`: Display all the native functions available in Clarity
-- `::keywords`: Display all the native keywords available in Clarity
-- `::describe | `: Display documentation for a given native function or keyword
-- `::toggle_costs`: Display cost analysis after every expression
-- `::toggle_timings`: Display the execution duration
-- `::mint_stx `: Mint STX balance for a given principal
-- `::set_tx_sender `: Set tx-sender variable to principal
-- `::get_assets_maps`: Get assets maps for active accounts
-- `::get_contracts`: Get contracts
-- `::get_block_height`: Get current block height
-- `::advance_chain_tip `: Simulate mining of `` blocks
-- `::advance_stacks_chain_tip `: Simulate mining of `` stacks blocks
-- `::advance_burn_chain_tip `: Simulate mining of `` burnchain blocks
-- `::set_epoch `: Update the current epoch
-- `::get_epoch`: Get current epoch
-- `::debug `: Start an interactive debug session executing ``
-- `::trace `: Generate an execution trace for ``
-- `::get_costs `: Display the cost analysis
-- `::reload`: Reload the existing contract(s) in the session
-- `::read `: Read expressions from a file
-- `::encode `: Encode an expression to a Clarity Value bytes representation
-- `::decode `: Decode a Clarity Value bytes representation
-
-| Option | Short | Description |
-|--------|-------|-------------|
-| `--manifest-path ` | `-m` | Path to Clarinet.toml |
-| `--deployment-plan-path ` | `-p` | If specified, use this deployment file |
-| `--use-on-disk-deployment-plan` | `-d` | Use on disk deployment plan (prevent updates computing) |
-| `--use-computed-deployment-plan` | `-c` | Use computed deployment plan (will overwrite on disk version if any update) |
-| `--enable-remote-data` | `-r` | Enable remote data fetching from mainnet or a testnet |
-| `--remote-data-api-url ` | `-a` | Set a custom Stacks Blockchain API URL for remote data fetching |
-| `--remote-data-initial-height ` | `-b` | Initial remote Stacks block height |
-| `--enable-clarity-wasm` | | Allow the Clarity Wasm preview to run in parallel with the Clarity interpreter (beta) |
-
-## Start a local development network [#start-a-local-development-network]
-
-### clarinet devnet
-
-`clarinet devnet` is a subcommand for working with Devnet. It has two subcommands:
-
-| Command | Description |
-|----------|-------------------------------------------------------|
-| `start` | Start a local Devnet network for interacting with your contracts |
-| `package`| Generate package of all required devnet artifacts |
-
-**Usage with `start`**
-
-```console
-$ clarinet devnet start [OPTIONS]
-```
-
-```terminal
-$ clarinet devnet start
-```
-
-| Option | Short | Description |
-|--------|-------|-------------|
-| `--manifest-path ` | `-m` | Path to Clarinet.toml |
-| `--no-dashboard` | | Display streams of logs instead of terminal UI dashboard |
-| `--deployment-plan-path ` | `-p` | If specified, use this deployment file |
-| `--use-on-disk-deployment-plan` | `-d` | Use on disk deployment plan (prevent updates computing) |
-| `--use-computed-deployment-plan` | `-c` | Use computed deployment plan (will overwrite on disk version if any update) |
-| `--package ` | | Path to Package.json produced by 'clarinet devnet package' |
-
-
-**Usage with `package`**
-
-```console
-$ clarinet devnet package [OPTIONS]
-```
-
-```terminal
-$ clarinet devnet package --name my-devnet
-[32mPackaging devnet artifacts...[0m
-[32mCreated file[0m [1mmy-devnet.json[0m
-```
-
-| Option | Short | Description |
-|--------|-------|-------------|
-| `--name ` | `-n` | Output json file name |
-| `--manifest-path ` | `-m` | Path to Clarinet.toml |
-
-
-## Manage your deployments [#manage-your-deployments]
-
-### clarinet deployments
-
-`clarinet deployments` is a subcommand for managing deployments on Devnet/Testnet/Mainnet.
-
-| Command | Description |
-|------------|-------------|
-| `check` | Check deployments format |
-| `generate` | Generate new deployment |
-| `apply` | Apply deployment |
-
-**Usage with `check`**
-
-```console
-$ clarinet deployments check [OPTIONS]
-```
-
-```terminal
-$ clarinet deployments check
-[32m✔[0m Deployment files are valid
-```
-
-| Option | Description |
-|--------|-------------|
-| `--manifest-path ` | Path to Clarinet.toml |
-
-**Usage with `generate`**
-
-```console
-$ clarinet deployments generate [OPTIONS]
-```
-
-
-```terminal
-$ clarinet deployments generate --testnet
-[32mGenerated deployment plan[0m
-[32mCreated file[0m [1mdeployments/default.testnet-plan.yaml[0m
-```
-
-| Option | Description |
-|--------|-------------|
-| `--simnet` | Generate a deployment file for simnet environments (console, tests) |
-| `--devnet` | Generate a deployment file for devnet, using settings/Devnet.toml |
-| `--testnet` | Generate a deployment file for testnet, using settings/Testnet.toml |
-| `--mainnet` | Generate a deployment file for mainnet, using settings/Mainnet.toml |
-| `--manifest-path ` | Path to Clarinet.toml |
-| `--no-batch` | Generate a deployment file without trying to batch transactions (simnet only) |
-| `--low-cost` | Compute and set cost, using low priority (network connection required) |
-| `--medium-cost` | Compute and set cost, using medium priority (network connection required) |
-| `--high-cost` | Compute and set cost, using high priority (network connection required) |
-| `--manual-cost` | Leave cost estimation manual |
-
-**Usage with `apply`**
-
-```console
-$ clarinet deployments apply [OPTIONS]
-```
-
-```terminal
-$ clarinet deployments apply --testnet
-[33mApplying deployment to testnet[0m
-[32m✔[0m Broadcasting transaction for token.clar
- Transaction ID: 0x3d4f5...
- Contract: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.token
-[32m✔[0m All contracts deployed successfully
-```
-
-| Option | Short | Description |
-|--------|-------|-------------|
-| `--devnet` | | Apply default deployment settings/default.devnet-plan.toml |
-| `--testnet` | | Apply default deployment settings/default.testnet-plan.toml |
-| `--mainnet` | | Apply default deployment settings/default.mainnet-plan.toml |
-| `--manifest-path ` | `-m` | Path to Clarinet.toml |
-| `--deployment-plan-path ` | `-p` | Apply deployment plan specified |
-| `--no-dashboard` | | Display streams of logs instead of terminal UI dashboard |
-| `--use-on-disk-deployment-plan` | `-d` | Use on disk deployment plan (prevent updates computing) |
-| `--use-computed-deployment-plan` | `-c` | Use computed deployment plan (will overwrite on disk version if any update) |
-
-## Interact with Mainnet contracts [#interact-with-mainnet-contracts]
-
-### clarinet requirements
-
-`clarinet requirements` is a subcommand for interacting with Mainnet contracts.
-
-| Command | Description |
-|---------|-------------|
-| `add` | Add a mainnet contract as a dependency to your project |
-
-**Usage**
-
-```console
-$ clarinet requirements
-```
-
-```terminal
-$ clarinet requirements add SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[32mAdded requirement[0m SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-| Option | Description |
-|--------|-------------|
-| `--manifest-path ` | Path to Clarinet.toml |
-
-
-## Editor Integrations [#editor-integrations]
-
-### clarinet lsp
-
-`clarinet lsp` starts the Language Server Protocol service for Clarity, enabling intelligent code completion, error highlighting, and other IDE features in supported editors.
-
-**Usage**
-
-```console
-$ clarinet lsp
-```
-
-## Debugging [#debugging]
-
-### clarinet dap
-
-`clarinet dap` starts the Debug Adapter Protocol service, enabling debugging features like breakpoints, step-through execution, and variable inspection in supported editors.
-
-**Usage**
-
-```console
-$ clarinet dap
-```
-
-## Format your code [#format-your-code]
-
-### clarinet format
-
-`clarinet format` formats Clarity code files according to standard conventions.
-
-**Usage**
-
-```console
-$ clarinet format [OPTIONS]
-```
-
-```terminal
-$ clarinet format --check
-$ clarinet format --dry-run
-$ clarinet format --file contracts/token.clar --in-place
-```
-
-| Option | Short | Description | Required |
-|--------|-------|-------------|----------|
-| `--check` | | Check if code is formatted without modifying files | No |
-| `--dry-run` | | Only echo the result of formatting | No |
-| `--in-place` | | Replace the contents of a file with the formatted code | No |
-| `--manifest-path ` | `-m` | Path to Clarinet.toml | No |
-| `--file ` | `-f` | If specified, format only this file | No |
-| `--max-line-length ` | `-l` | Maximum line length | No |
-| `--indent ` | `-i` | Indentation size, e.g. 2 | No |
-| `--tabs` | `-t` | Use tabs instead of spaces | No |
-
-## Utilities [#utilities]
-
-### clarinet completions
-
-`clarinet completions` generates shell completion scripts for your shell.
-
-**Usage**
-
-```console
-$ clarinet completions
-```
-
-```terminal
-$ clarinet completions zsh > ~/.zsh/completions/_clarinet
-$ source ~/.zshrc
-```
-
-**Supported Shells**
-
-- `bash`
-- `zsh`
-- `fish`
-- `powershell`
-- `elvish`
-
-| Option | Short | Description |
-|--------|-------|-------------|
-| `--shell ` | `-s` | Specify which shell to generation completions script for |
-
-## Environment Variables [#environment-variables]
-
-Clarinet supports environment variables for configuration. All environment variables are prefixed with `CLARINET_`:
-
-```terminal
-$ export CLARINET_MANIFEST_PATH=/path/to/project
-```
\ No newline at end of file
diff --git a/content/docs/en/tools/clarinet/(clarinet-cli)/contract-interaction.mdx b/content/docs/en/tools/clarinet/(clarinet-cli)/contract-interaction.mdx
deleted file mode 100644
index 3fa7ae1c5..000000000
--- a/content/docs/en/tools/clarinet/(clarinet-cli)/contract-interaction.mdx
+++ /dev/null
@@ -1,186 +0,0 @@
----
-title: Contract interaction
-sidebarTitle: Contract interaction
-description: Clarinet provides powerful tools for interacting with your contracts during development. The console gives you an interactive REPL environment where you can call functions, check state, and debug issues in real-time.
----
-
-## Starting the console
-
-The `clarinet console` command launches an interactive session with all your contracts deployed to a local simulated blockchain:
-
-```terminal
-$ clarinet console
-[32mclarity-repl v3.3.0[0m
-[1mEnter "::help" for usage hints.[0m
-[1mConnected to a transient in-memory database.[0m
-```
-
-Once in the console, you have access to a Clarity REPL with your project's contracts already deployed and ready to interact with. The console supports several powerful options for different development scenarios:
-
-| Option | Description |
-|--------|-------------|
-| `--enable-remote-data` | Connect to mainnet/testnet to query real contracts |
-| `--deployment-plan-path ` | Use specific deployment plan |
-| `--manifest-path ` | Use alternate Clarinet.toml location |
-| `--remote-data-api-url ` | Use custom Stacks API endpoint |
-| `--remote-data-initial-height ` | Set starting block height for remote data |
-
-## Working with remote data
-
-One of the most powerful features is the ability to interact with real mainnet or testnet contracts from your local console. This lets you test against actual deployed contracts:
-
-```terminal
-$ clarinet console --enable-remote-data
-```
-
-Now you can interact with mainnet contracts directly:
-
-```terminal -o
-$ (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token get-decimals)
-[32m(ok u8)[0m
-$ (contract-call? 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.arkadiko-token get-name)
-[32m(ok "Arkadiko Token")[0m
-```
-
-This is invaluable for:
-- Testing integrations with existing protocols
-- Verifying contract behavior against mainnet state
-- Developing contracts that depend on mainnet contracts
-
-:::callout
-type: warn
-### Remote data requirements
-Before using remote data, make sure you add the remote contract to your `Clarinet.toml` file with `clarinet requirements add SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token`.
-:::
-
-### Using the Hiro API key
-
-To avoid rate limits when using remote data, set the `HIRO_API_KEY` environment variable. Clarinet automatically includes this key in all API requests:
-
-```terminal
-$ export HIRO_API_KEY=your_api_key_here
-$ clarinet console --enable-remote-data
-```
-
-The API key is sent as the `x-api-key` header in all requests to Hiro's APIs. You can obtain a free API key from the [Hiro Platform](https://platform.hiro.so).
-
-### Working with contracts
-
-The `::get_contracts` command lists all available contracts:
-
-```terminal -o
-$ ::get_contracts
-[1m+---------------------------------------------------------+----------------+
-| Contract identifier | Public functions |
-|---------------------------------------------------------+----------------------|
-| ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter | (count-up) |
-| | (get-count (who principal))|
-+---------------------------------------------------------+----------------------+[0m
-$ (contract-call? .counter count-up)
-[32m(ok true)[0m
-$ (contract-call? .counter get-count tx-sender)
-[32mu1[0m
-```
-
-### Working with different principals
-
-The console provides several test wallets you can use. Switch between them to test multi-user scenarios:
-
-```terminal -o
-$ ::get_assets_maps
-[1m+-------------------------------------------+-----------------+
-| Address | uSTX |
-|-------------------------------------------+-----------------|
-| ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST2NEB84ASENDXKYGJPQW86YXQCEFEX2ZQPG87ND | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST2REHHS5J3CERCRBEPMGH7921Q6PYKAADT7JP2VB | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST3AM1A56AK2C1XAFJ4115ZSV26EB49BVQ10MGCS0 | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST3NBRSFKX28FQ2ZJ1MAKX58HKHSDGNV5N7R21XCP | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST3PF13W7Z0RRM42A8VZRVFQ75SV1K26RXEP8YGKJ | 100000000000000 |
-|-------------------------------------------+-----------------|
-| STNHKEPYEPJ8ET55ZZ0M5A34J0R3N5FM2CMMMAZ6 | 100000000000000 |
-+-------------------------------------------+-----------------+[0m
-$ ::set_tx_sender ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5
-[1mtx-sender switched to ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5[0m
-```
-
-### Working with block heights
-
-Test "time-dependent" logic by advancing the chain:
-
-```terminal -o
-$ ::get_block_height
-[1mCurrent block height: 4[0m
-$ ::advance_chain_tip 100
-[32mnew burn height: 3[0m
-[32mnew stacks height: 104[0m
-$ ::get_block_height
-[1mCurrent block height: 104[0m
-```
-
-:::callout
-### Console commands
-For a complete list of available console commands and their usage, view the [CLI reference](/tools/clarinet/cli-reference#clarinet-console).
-:::
-
-## Common issues
-
-
-
- Contract not found errors
-
-
- If you see "use of unresolved contract" errors:
-
- ```terminal
- $ (contract-call? .missing-contract get-value)
- [31merror: use of unresolved contract[0m
- ```
-
- **Common causes:**
- - Contract name typo
- - Contract not deployed in the session
- - Using wrong contract prefix (`.` for local contracts)
-
- **Solution**: Check deployed contracts with `::get_contracts` and use the correct name.
-
-
-
-
-
- Remote data connection issues
-
-
- When using `--enable-remote-data`, you might encounter rate limits or connection errors:
-
- ```terminal
- $ (contract-call? 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.arkadiko-token get-name)
- [31merror: API rate limit exceeded[0m
- ```
-
- **Solutions:**
- 1. Set your Hiro API key: `export HIRO_API_KEY=your_key_here`
- 2. Use a custom API endpoint: `--remote-data-api-url https://your-node.com`
- 3. Wait for rate limit to reset (usually 1 minute)
-
-
-
-
-
-## Next steps
-
-:::next-steps
-- [Validation and analysis](/tools/clarinet/validation-and-analysis): Learn how to test and validate your Clarinet project.
-- [Deployment](/tools/clarinet/deployment): Learn how to deploy your Clarinet project.
-:::
diff --git a/content/docs/en/tools/clarinet/(clarinet-cli)/deployment.mdx b/content/docs/en/tools/clarinet/(clarinet-cli)/deployment.mdx
deleted file mode 100644
index 900e653cd..000000000
--- a/content/docs/en/tools/clarinet/(clarinet-cli)/deployment.mdx
+++ /dev/null
@@ -1,427 +0,0 @@
----
-title: Deploying your contracts
-sidebarTitle: Contract deployment
-description: Clarinet provides comprehensive deployment tools to help you move your contracts from local development to production networks. Whether you're testing on devnet, staging on testnet, or launching on mainnet, Clarinet streamlines the entire deployment process.
----
-
-## Generating deployment plans
-
-Deployment plans are YAML files that define exactly how your contracts will be deployed. They specify the order, configuration, and network details for each contract, ensuring reproducible deployments across all environments. To create a deployment plan for any network, run the following command:
-
-```terminal
-$ clarinet deployments generate --testnet
-[32mAnalyzing contracts...[0m
-[32mCalculating deployment costs...[0m
-[32mGenerating deployment plan[0m
-[32mCreated file[0m [1mdeployments/default.testnet-plan.yaml[0m
-```
-
-This creates a deployment plan based on your project's configuration:
-
-```yaml deployments/default.devnet-plan.yaml
----
-id: 0
-name: Devnet deployment
-network: devnet
-stacks-node: "http://localhost:20443"
-bitcoin-node: "http://devnet:devnet@localhost:18443"
-plan:
- batches:
- - id: 0
- transactions:
- - contract-publish:
- contract-name: counter
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
- cost: 6940
- path: contracts/counter.clar
- anchor-block-only: true
- clarity-version: 2
- epoch: "2.5"
-```
-
-### Deployment plan structure
-
-Key components of a deployment plan:
-
-| Field | Description |
-|-------|-------------|
-| `id` | Unique identifier for the deployment |
-| `name` | Human-readable deployment name |
-| `network` | Target network (devnet/testnet/mainnet) |
-| `stacks-node` | RPC endpoint for the Stacks node |
-| `bitcoin-node` | RPC endpoint for the Bitcoin node |
-| `plan.batches` | Array of deployment batches |
-
-### Deployment specifications
-
-Deployment behavior is configured in two places:
-
-**Project configuration** (`Clarinet.toml`):
-- Clarity version for contracts
-- Contract dependencies
-- Epoch requirements
-
-**Network configuration** (`settings/.toml`):
-- Account details and balances
-- Network endpoints
-- Custom deployment accounts
-
-Example network configuration:
-
-```toml settings/Testnet.toml
-[network]
-name = "testnet"
-deployment_fee_rate = 10
-
-[accounts.deployer]
-mnemonic = ""
-balance = 100_000_000_000_000
-derivation = "m/44'/5757'/0'/0/0"
-```
-
-## Working with contract requirements
-
-Your project can reference contracts that already exist on the blockchain. This is especially useful for implementing standardized traits.
-
-### Adding requirements
-
-Add external contract dependencies:
-
-```terminal
-$ clarinet requirements add SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[32mAdded requirement[0m SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-This updates your project configuration:
-
-```toml Clarinet.toml
-[project]
-name = "my-nft-project"
-requirements = [
- { contract_id = "SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait" }
-]
-```
-
-When deploying, Clarinet automatically:
-- Downloads the contract via the Stacks API
-- Remaps the principal to a local account for devnet
-- Ensures the requirement is available before deploying your contracts
-
-## Deploying to different networks
-
-
-
-
- Devnet
-
-
- Testnet
-
-
- Mainnet
-
-
-
-
- **Quick deployment for local development**
-
- Devnet automatically deploys contracts when started:
-
- ```terminal
- $ clarinet devnet start
- [32mStarting devnet...[0m
- [32mDeploying contracts...[0m
- [90mDeploying[0m counter.clar [32m✓[0m ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter
- [90mDeploying[0m token.clar [32m✓[0m ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.token
- ```
-
- For manual deployment to a running devnet:
-
- ```terminal
- $ clarinet deployments apply --devnet
- ```
-
- See [local development](/tools/clarinet/local-development) for detailed devnet configuration.
-
-
-
- :::callout
-### Prerequisites
-Before deploying to testnet:
- - Get testnet STX from the [faucet](https://explorer.hiro.so/sandbox/faucet?chain=testnet)
- - Configure your account in `settings/Testnet.toml`
- - Validate contracts with `clarinet check`
-:::
-
- **Generate deployment plan with cost estimation**:
-
- ```terminal
- $ clarinet deployments generate --testnet --medium-cost
- ```
-
- **Deploy contracts**:
-
- ```terminal
- $ clarinet deployments apply --testnet
- ```
-
-
-
- :::callout
-type: warn
-### Mainnet checklist
-Before deploying to mainnet:
- 1. Complete thorough testing on testnet
- 2. Audit your contracts for security vulnerabilities
- 3. Ensure you have sufficient STX for deployment fees
- 4. Back up your deployment keys securely
- 5. Consider using a hardware wallet for deployment
-:::
-
- **Generate mainnet deployment plan**:
-
- ```terminal
- $ clarinet deployments generate --mainnet --high-cost
- ```
-
- **Deploy with confirmation**:
-
- ```terminal
- $ clarinet deployments apply --mainnet
- ```
-
-
-
-## Cost estimation and optimization
-
-### Fee levels
-
-Choose the right fee level for your deployment:
-
-```terminal
-$ clarinet deployments generate --testnet --manual-cost
-```
-
-Fee level options:
-- `--low-cost`: Minimize fees, slower confirmation
-- `--medium-cost`: Balanced fees and speed
-- `--high-cost`: Priority inclusion
-- `--manual-cost`: Choose interactively
-
-### Analyzing deployment costs
-
-Get detailed cost breakdown before deploying:
-
-```terminal
-$ clarinet deployments generate --testnet --medium-cost
-```
-
-## Advanced deployment configurations
-
-### Multi-batch deployments
-
-Deploy complex systems with dependencies using batches:
-
-```yaml deployments/defi-protocol.yaml
-plan:
- batches:
- - id: 0
- transactions:
- - contract-publish:
- contract-name: trait-definitions
- path: contracts/traits.clar
- clarity-version: 2
- - id: 1
- transactions:
- - contract-publish:
- contract-name: token
- path: contracts/token.clar
- - contract-publish:
- contract-name: oracle
- path: contracts/oracle.clar
- - id: 2
- transactions:
- - contract-publish:
- contract-name: defi-pool
- path: contracts/defi-pool.clar
-```
-
-Batches ensure:
-- Dependencies are deployed first
-- Parallel deployment within batches
-- Sequential execution between batches
-
-### Transaction types
-
-Deployment plans support various transaction types:
-
-| Transaction Type | Description |
-|--------------------|-----------------------------------------------------------------------------|
-| Contract Operations| Involves publishing and calling contracts, specifying sender, cost, and path|
-| Asset Transfers | Transfers assets like STX or BTC, specifying sender, recipient, and amounts |
-
-**With contract operations**:
-```yaml
-- contract-publish:
- contract-name: my-contract
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
- cost: 5960
- path: contracts/my-contract.clar
- clarity-version: 2
-
-- contract-call:
- contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.my-contract
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
- method: initialize
- parameters:
- - u1000000
- - "Token Name"
- cost: 5960
-```
-
-**With asset transfers**:
-```yaml
-- stx-transfer:
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
- recipient: ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG
- mstx-amount: 1000000
- memo: '0x48656c6c6f' # "Hello" in hex
-
-- btc-transfer:
- expected-sender: mjSrB3wS4xab3kYqFktwBzfTdPg367ZJ2d
- recipient: bcrt1qnxknq3wqtphv7sfwy07m7e4sr6ut9yt6ed99jg
- sats-amount: 100000000
- sats-per-byte: 10
-```
-
-### Manual plan customization
-
-You can manually edit deployment plans for complex scenarios:
-
-:::callout
-### Manual edits
-When deploying, Clarinet prompts to overwrite manual changes. Type `no` to keep your customizations.
-:::
-
-**Contract initialization example**:
-```yaml
-- id: 3
- transactions:
- - contract-call:
- contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.token
- method: initialize
- parameters:
- - u1000000 # Initial supply
- - { name: "My Token", symbol: "MTK", decimals: u6 }
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
-```
-
-## Common issues
-
-
-
- Insufficient STX balance
-
-
- **Error**: "Contract 'token' already deployed at this address"
-
- **Causes**:
- - Contract with same name already deployed
- - Previous deployment attempt succeeded
-
- **Solutions**:
- 1. Use a different contract name
- 2. Deploy from a different address
- 3. If testing, use a fresh testnet account
-
-
-
-
-
- Network connection failures
-
-
- **Error**: "Failed to connect to testnet node"
-
- **Check network settings**:
- ```toml settings/Testnet.toml
- [network]
- name = "testnet"
- node_rpc_address = "https://stacks-node-api.testnet.stacks.co"
- ```
-
- **Try alternative endpoints**:
- - Hiro: `https://api.testnet.hiro.so`
- - Use your own node
-
- **Debug connection**:
- ```terminal
- $ curl -I https://api.testnet.hiro.so/v2/info
- ```
-
- **Error**: "Docker responded with status code 409: network with name `.devnet` already exists"
-
- This happens when a previous devnet session wasn't properly cleaned up, leaving a Docker network behind.
-
- **Solution - Remove the existing network**:
- ```terminal
- $ docker network rm .devnet
- ```
-
- Or if you're unsure of the exact network name:
- ```terminal
- $ docker network ls | grep devnet
- $ docker network rm
- ```
-
- **Prevention**:
- - Use `Ctrl+C` to gracefully stop devnet
- - Check for orphaned networks after crashes:
-
- ```terminal
- $ docker network prune
- ```
-
- **Note**: The network name is based on your project directory name, so a `clarinet new hello-world` project will have a network name of `hello-world.devnet`.
-
-
-
-
-
- Docker stream error during startup
-
-
- **Error**: "Fatal: unable to create image: Docker stream error"
-
- This error often occurs when Docker images are corrupted or when explorers fail to start properly.
-
- **Solution 1 - Disable explorers**:
-
- If you don't need the web explorers, disable them in `settings/Devnet.toml`:
- ```toml
- disable_bitcoin_explorer = true
- disable_stacks_explorer = true
- ```
-
- **Solution 2 - Clean Docker environment**:
-
- Remove all containers and images, then restart:
- ```terminal
- $ docker stop $(docker ps -a -q)
- $ docker system prune -a
- $ docker volume prune
- ```
-
- **Solution 3 - Full cleanup and restart**:
-
- ```terminal
- $ docker stop $(docker ps -a -q)
- $ docker network rm .devnet
- $ docker system prune --all --volumes
- $ clarinet devnet start
- ```
-
- This ensures a clean Docker environment for devnet to start fresh.
-
-
-
-
-
-## Next steps
-
-:::next-steps
-- [Integration testing](/tools/clarinet/integration-testing): Learn how to test your contract with integration testing.
-- [Mainnet execution simulation](/tools/clarinet/mainnet-execution-simulation): Learn how to test your contract with mainnet state.
-:::
diff --git a/content/docs/en/tools/clarinet/(integrations)/chainhook-integration.mdx b/content/docs/en/tools/clarinet/(integrations)/chainhook-integration.mdx
deleted file mode 100644
index 617a4cff2..000000000
--- a/content/docs/en/tools/clarinet/(integrations)/chainhook-integration.mdx
+++ /dev/null
@@ -1,160 +0,0 @@
----
-title: Register Chainhooks on devnet
-sidebarTitle: Chainhook integration
-description: In this guide, you'll learn how to register Chainhooks on devnet to monitor and react to smart contract events during local development.
----
-
-## What you'll learn
-
-:::objectives
-- Create Chainhook predicate files for event monitoring
-- Register Chainhooks with Clarinet devnet
-- Monitor contract calls and blockchain events
-- Set up webhooks for real-time notifications
-:::
-
-## Prerequisites
-
-:::prerequisites
-- Clarinet version 2.1.0 or higher required. Check with `clarinet --version`.
-- Node.js version 16 or higher required. Check with `node --version`.
-:::
-
-## Quickstart
-
-
-
- ### Create your Chainhook predicates
-
- Create Chainhook predicate files in your project root or a dedicated folder:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Example predicate for monitoring increment events:
-
- ```json chainhooks/increment.json
- {
- "chain": "stacks",
- "uuid": "increment-hook",
- "name": "Increment Counter Hook",
- "version": 1,
- "networks": {
- "devnet": {
- "if_this": {
- "scope": "contract_call",
- "contract_identifier": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter",
- "method": "increment"
- },
- "then_that": {
- "http_post": {
- "url": "http://localhost:3000/api/increment",
- "authorization_header": "Bearer my-secret"
- }
- }
- }
- }
- }
- ```
-
-
-
- ### Start devnet with Chainhooks
-
- Start devnet from your project root. Clarinet automatically registers all Chainhook files:
-
- ```terminal
- $ clarinet devnet start
- ```
-
- Look for the registration confirmation:
-
- ```terminal
- $ clarinet devnet start
- # ...
- INFO Feb 5 15:20:07.233382 2 chainhooks registered
- ```
-
-
-
- ### Monitor Chainhook activity
-
- When contract actions occur, you'll see Chainhook triggers in the terminal:
-
- ```terminal
- $ clarinet devnet start
- # ...
- INFO Feb 5 15:21:07.233382 1 hooks triggered
- ```
-
- Verify the payload based on your `then_that` configuration:
- - **`http_post`** - Check your endpoint received the POST request
- - **`file_append`** - Verify the file was created/updated
-
-
-
-## Common patterns
-
-### Contract deployment hook
-
-Monitor when specific contracts are deployed:
-
-```json chainhooks/deploy-monitor.json
-{
- "chain": "stacks",
- "uuid": "deploy-hook",
- "name": "Contract Deploy Monitor",
- "version": 1,
- "networks": {
- "devnet": {
- "if_this": {
- "scope": "contract_deployment",
- "deployer": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM"
- },
- "then_that": {
- "file_append": {
- "path": "./deployments.log"
- }
- }
- }
- }
-}
-```
-
-### STX transfer monitoring
-
-Track STX transfers above a certain threshold:
-
-```json chainhooks/stx-transfers.json
-{
- "chain": "stacks",
- "uuid": "stx-transfer-hook",
- "name": "Large STX Transfer Monitor",
- "version": 1,
- "networks": {
- "devnet": {
- "if_this": {
- "scope": "stx_event",
- "actions": ["transfer"],
- "amount_upper_bound": "1000000000000"
- },
- "then_that": {
- "http_post": {
- "url": "http://localhost:3000/api/large-transfer"
- }
- }
- }
- }
-}
-```
diff --git a/content/docs/en/tools/clarinet/(integrations)/meta.json b/content/docs/en/tools/clarinet/(integrations)/meta.json
deleted file mode 100644
index 68fd03848..000000000
--- a/content/docs/en/tools/clarinet/(integrations)/meta.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "title": "Guides",
- "pages": [
- "pyth-oracle-integration",
- "chainhook-integration",
- "stacks-js-integration",
- "sbtc-integration"
- ]
-}
diff --git a/content/docs/en/tools/clarinet/(integrations)/pyth-oracle-integration.mdx b/content/docs/en/tools/clarinet/(integrations)/pyth-oracle-integration.mdx
deleted file mode 100644
index e6082306d..000000000
--- a/content/docs/en/tools/clarinet/(integrations)/pyth-oracle-integration.mdx
+++ /dev/null
@@ -1,380 +0,0 @@
----
-title: Pyth oracle integration
-sidebarTitle: Pyth oracle integration
-description: Learn how to test smart contracts that depend on Pyth oracle price feeds using Clarinet.
----
-
-## What you'll learn
-
-:::objectives
-- Set up mainnet contract dependencies
-- Use mainnet transaction execution (MXS) for oracle testing
-- Create mock price feeds for unit tests
-- Write integration tests with real oracle data
-:::
-
-## Prerequisites
-
-:::prerequisites
-
-- Clarinet version 2.1.0 or higher with MXS support
-- Understanding of [Pyth oracle contracts](/resources/clarity/external-data)
-:::
-
-## Quickstart
-
-
-
- ### Configure mainnet dependencies
-
- Add the Pyth oracle contracts to your Clarinet.toml requirements:
-
- ```toml Clarinet.toml
- [project]
- name = "my-oracle-project"
-
- [[project.requirements]]
- contract_id = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-oracle-v3"
-
- [[project.requirements]]
- contract_id = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3"
-
- [[project.requirements]]
- contract_id = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-pnau-decoder-v2"
-
- [[project.requirements]]
- contract_id = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.wormhole-core-v3"
- ```
-
- This allows your tests to interact with the actual mainnet oracle contracts.
-
-
-
- ### Create a mock oracle for unit tests
-
- For fast unit tests, create a mock oracle contract:
-
- ```clarity tests/mocks/mock-pyth-oracle.clar
- ;; Mock Pyth Oracle for testing
- (define-map price-feeds
- (buff 32) ;; price-feed-id
- {
- price: int,
- conf: uint,
- expo: int,
- ema-price: int,
- ema-conf: uint,
- publish-time: uint,
- prev-publish-time: uint
- }
- )
-
- ;; Set a mock price
- (define-public (set-mock-price
- (feed-id (buff 32))
- (price int)
- (expo int))
- (ok (map-set price-feeds feed-id {
- price: price,
- conf: u1000000,
- expo: expo,
- ema-price: price,
- ema-conf: u1000000,
- publish-time: block-height,
- prev-publish-time: (- block-height u1)
- }))
- )
-
- ;; Mock get-price function matching real oracle interface
- (define-read-only (get-price
- (feed-id (buff 32))
- (storage-contract principal))
- (ok (unwrap!
- (map-get? price-feeds feed-id)
- (err u404)))
- )
-
- ;; Mock verify-and-update-price-feeds (no-op for testing)
- (define-public (verify-and-update-price-feeds
- (vaa (buff 8192))
- (params (tuple)))
- (ok u1)
- )
- ```
-
-
-
- ### Write unit tests with mocked prices
-
- Create unit tests using the mock oracle:
-
- ```typescript tests/benjamin-club.test.ts
- import { Cl } from '@stacks/transactions';
- import { describe, expect, it } from "vitest";
-
- const accounts = simnet.getAccounts();
- const deployer = accounts.get("deployer")!;
- const wallet1 = accounts.get("wallet_1")!;
-
- describe("Benjamin Club with Mock Oracle", () => {
- it("should set up mock BTC price", () => {
- // Set BTC price to $100,000 (with 8 decimals)
- const btcFeedId = "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43";
- const mockPrice = Cl.int(10000000000000); // $100,000.00 * 10^8
- const expo = Cl.int(-8);
-
- const setPriceResponse = simnet.callPublicFn(
- "mock-pyth-oracle",
- "set-mock-price",
- [Cl.bufferFromHex(btcFeedId), mockPrice, expo],
- deployer
- );
-
- expect(setPriceResponse.result).toBeOk(Cl.uint(1));
- });
-
- it("should calculate correct sBTC amount for $100", () => {
- // With BTC at $100,000, $100 = 0.001 BTC
- const response = simnet.callReadOnlyFn(
- "benjamin-club",
- "get-required-sbtc-amount",
- [],
- wallet1
- );
-
- // 0.001 BTC = 100,000 sats
- expect(response.result).toBeOk(Cl.uint(100000));
- });
-
- it("should mint NFT when user has enough sBTC", () => {
- // Mock VAA data (can be dummy data for unit tests)
- const mockVaa = Cl.bufferFromHex("00".repeat(100));
-
- // Give user 1 BTC worth of sBTC
- simnet.callPublicFn(
- "sbtc-token",
- "mint",
- [Cl.uint(100000000), Cl.principal(wallet1)],
- deployer
- );
-
- const mintResponse = simnet.callPublicFn(
- "benjamin-club",
- "mint-for-hundred-dollars",
- [mockVaa],
- wallet1
- );
-
- expect(mintResponse.result).toBeOk(Cl.uint(1));
- });
- });
- ```
-
-
-
- ### Set up mainnet execution tests
-
- For integration tests with real oracle data, use mainnet transaction execution:
-
- ```typescript tests/benjamin-club-mxs.test.ts
- import { buildDevnetNetworkOrchestrator } from "@hirosystems/clarinet-sdk";
- import { Cl } from '@stacks/transactions';
- import { PriceServiceConnection } from '@pythnetwork/price-service-client';
- import { describe, expect, it } from "vitest";
-
- describe("Benjamin Club with Mainnet Oracle", () => {
- let orchestrator: any;
-
- beforeAll(async () => {
- orchestrator = buildDevnetNetworkOrchestrator({
- // Point to a mainnet fork
- manifest: "./Clarinet.toml",
- networkId: 1 // Mainnet
- });
- });
-
- it("should interact with real Pyth oracle", async () => {
- // Fetch real VAA from Pyth
- const pythClient = new PriceServiceConnection(
- "https://hermes.pyth.network",
- { priceFeedRequestConfig: { binary: true } }
- );
-
- const btcFeedId = "e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43";
- const vaas = await pythClient.getLatestVaas([btcFeedId]);
- const vaaHex = Buffer.from(vaas[0], 'base64').toString('hex');
-
- // Use mainnet execution to test with real oracle
- const response = await orchestrator.callPublicFn(
- "benjamin-club",
- "get-current-btc-price",
- [Cl.bufferFromHex(vaaHex)],
- "wallet_1"
- );
-
- expect(response.result).toBeOk();
-
- // Verify price is reasonable (between $10k and $200k)
- const priceData = response.result.value;
- const price = priceData.data.price.value;
- expect(price).toBeGreaterThan(1000000000000); // $10k
- expect(price).toBeLessThan(20000000000000); // $200k
- });
- });
- ```
-
-
-
-## Common patterns
-
-### Testing different price scenarios
-
-Create helper functions to test various market conditions:
-
-```typescript tests/helpers/oracle-helpers.ts
-export function setupPriceScenario(
- scenario: 'bull' | 'bear' | 'stable',
- simnet: any
-) {
- const prices = {
- bull: {
- btc: 15000000000000, // $150,000
- stx: 500000000, // $5.00
- eth: 500000000000 // $5,000
- },
- bear: {
- btc: 2000000000000, // $20,000
- stx: 50000000, // $0.50
- eth: 100000000000 // $1,000
- },
- stable: {
- btc: 10000000000000, // $100,000
- stx: 200000000, // $2.00
- eth: 300000000000 // $3,000
- }
- };
-
- const selectedPrices = prices[scenario];
-
- // Set up all price feeds
- Object.entries(selectedPrices).forEach(([asset, price]) => {
- const feedId = getFeedId(asset);
- simnet.callPublicFn(
- "mock-pyth-oracle",
- "set-mock-price",
- [Cl.bufferFromHex(feedId), Cl.int(price), Cl.int(-8)],
- "deployer"
- );
- });
-}
-```
-
-### Testing price staleness
-
-Ensure your contract handles stale prices correctly:
-
-```typescript tests/price-staleness.test.ts
-describe("Price Staleness Handling", () => {
- it("should reject stale prices", () => {
- // Set a price with old timestamp
- const oldTimestamp = simnet.getBlockHeight() - 1000;
-
- simnet.callPublicFn(
- "mock-pyth-oracle",
- "set-price-with-timestamp",
- [
- Cl.bufferFromHex(BTC_FEED_ID),
- Cl.int(10000000000000),
- Cl.int(-8),
- Cl.uint(oldTimestamp)
- ],
- deployer
- );
-
- const response = simnet.callPublicFn(
- "benjamin-club",
- "mint-for-hundred-dollars",
- [mockVaa],
- wallet1
- );
-
- expect(response.result).toBeErr(Cl.uint(ERR_STALE_PRICE));
- });
-});
-```
-
-### Deployment testing
-
-Create deployment tests to ensure proper configuration:
-
-```toml deployments/mainnet.yaml
----
-id: 0
-name: "Mainnet deployment"
-network: mainnet
-stacks-node: "https://api.mainnet.hiro.so"
-bitcoin-node: "https://blockstream.info/api/"
-plan:
- batches:
- - id: 0
- transactions:
- - contract-call:
- contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R.benjamin-club
- method: initialize
- parameters:
- - "'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-oracle-v3"
- - "'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3"
-```
-
-### Gas estimation
-
-Test gas consumption for oracle operations:
-
-```typescript tests/gas-estimation.test.ts
-describe("Gas Estimation", () => {
- it("should estimate gas for oracle update + mint", () => {
- const txCost = simnet.getTransactionCost(
- "benjamin-club",
- "mint-for-hundred-dollars",
- [Cl.bufferFromHex("00".repeat(1000))], // Typical VAA size
- wallet1
- );
-
- console.log("Estimated gas cost:", txCost);
-
- // Ensure gas cost is reasonable
- expect(txCost.write_length).toBeLessThan(20000);
- expect(txCost.runtime).toBeLessThan(50000000);
- });
-});
-```
-
-## CI/CD integration
-
-Set up GitHub Actions for automated testing:
-
-```yaml .github/workflows/test-oracle.yml
-name: Test Oracle Integration
-
-on: [push, pull_request]
-
-jobs:
- test:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v3
-
- - name: Install Clarinet
- run: |
- curl -L https://github.com/hirosystems/clarinet/releases/download/v2.1.0/clarinet-linux-x64.tar.gz | tar xz
- chmod +x ./clarinet
- sudo mv ./clarinet /usr/local/bin
-
- - name: Run unit tests
- run: clarinet test --coverage
-
- - name: Run mainnet fork tests
- run: clarinet test --mainnet-fork
- env:
- MAINNET_API_KEY: ${{ secrets.MAINNET_API_KEY }}
-```
\ No newline at end of file
diff --git a/content/docs/en/tools/clarinet/(integrations)/sbtc-integration.mdx b/content/docs/en/tools/clarinet/(integrations)/sbtc-integration.mdx
deleted file mode 100644
index 8c87bead1..000000000
--- a/content/docs/en/tools/clarinet/(integrations)/sbtc-integration.mdx
+++ /dev/null
@@ -1,269 +0,0 @@
----
-title: sBTC integration with Clarinet
-sidebarTitle: sBTC integration
-description: In this guide, you'll learn how to interact with the mainnet sBTC contract in your Clarinet project.
----
-
-## What you'll learn
-
-:::objectives
-- Add sBTC smart contracts to your Clarinet project
-- Test contracts with automatic sBTC funding in devnet
-- Work with sBTC as a SIP-010 fungible token
-- Deploy sBTC contracts to testnet and mainnet
-:::
-
-## Prerequisites
-
-:::prerequisites
-- Clarinet 2.15.0 or later required for automatic sBTC integration.
-:::
-
-## Quickstart
-
-
-
- ### Add sBTC to your project
-
- Add the sBTC smart contracts to your Clarinet project requirements:
-
- ```terminal
- $ clarinet requirements add SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-deposit
- ```
-
- This command adds three essential contracts:
- - **`sbtc-token`** - The core SIP-010 token contract
- - **`sbtc-registry`** - Registry for managing sBTC configuration
- - **`sbtc-deposit`** - Handles deposit and withdrawal operations
-
- When Clarinet detects these contracts, it automatically funds your test wallets with sBTC for testing.
-
-
-
- ### Create an sBTC-enabled contract
-
- Build a simple NFT marketplace that accepts sBTC payments:
-
- ```clarity contracts/nft-marketplace.clar
- ;; Define NFT
- (define-non-fungible-token marketplace-nft uint)
-
- ;; Price in sats (smallest sBTC unit)
- (define-data-var mint-price uint u100)
- (define-data-var next-id uint u0)
-
- ;; Mint NFT with sBTC payment
- (define-public (mint-with-sbtc)
- (begin
- ;; Transfer sBTC from buyer to contract
- (try! (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token transfer
- (var-get mint-price)
- tx-sender
- (as-contract tx-sender)
- none
- ))
-
- ;; Mint the NFT
- (try! (nft-mint? marketplace-nft (var-get next-id) tx-sender))
-
- ;; Increment ID for next mint
- (ok (var-set next-id (+ (var-get next-id) u1)))
- )
- )
-
- ;; Check sBTC balance
- (define-read-only (get-sbtc-balance (owner principal))
- (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token get-balance owner)
- )
- ```
-
-
-
- ### Test in Clarinet console
-
- Clarinet automatically funds test wallets with sBTC. Test your contract:
-
- ```terminal
- $ clarinet console
- ```
-
- Check wallet balances and mint an NFT:
-
- ```clarity
- ;; Check deployer's sBTC balance (auto-funded)
- (contract-call? .nft-marketplace get-sbtc-balance tx-sender)
-
- ;; Mint NFT with wallet_1 (also auto-funded)
- (contract-call? .nft-marketplace mint-with-sbtc)
-
- ;; Verify NFT ownership
- (nft-get-owner? .nft-marketplace marketplace-nft u0)
- ```
-
-
-
- ### Write unit tests
-
- Test sBTC functionality in your TypeScript tests:
-
- ```ts tests/nft-marketplace.test.ts
- import { describe, expect, it } from "vitest";
- import { Cl } from "@stacks/transactions";
-
- describe("NFT Marketplace", () => {
- it("mints NFT with sBTC payment", () => {
- const mintPrice = 100;
-
- // Get initial sBTC balance
- const initialBalance = simnet.callReadOnlyFn(
- "nft-marketplace",
- "get-sbtc-balance",
- [Cl.standardPrincipal(accounts.get("wallet_1")!.address)],
- accounts.get("wallet_1")!.address
- );
-
- // Mint NFT
- const mintResult = simnet.callPublicFn(
- "nft-marketplace",
- "mint-with-sbtc",
- [],
- accounts.get("wallet_1")!.address
- );
-
- expect(mintResult.result).toBeOk();
-
- // Verify sBTC was transferred
- const finalBalance = simnet.callReadOnlyFn(
- "nft-marketplace",
- "get-sbtc-balance",
- [Cl.standardPrincipal(accounts.get("wallet_1")!.address)],
- accounts.get("wallet_1")!.address
- );
-
- expect(Number(Cl.parse(finalBalance.result))).toBeLessThan(
- Number(Cl.parse(initialBalance.result))
- );
- });
- });
- ```
-
-
-
- ### Deploy to testnet
-
- On testnet, Clarinet automatically remaps to the official Hiro sBTC contracts:
-
- ```terminal
- $ clarinet deployments generate --testnet
- ```
-
- Your deployment plan shows the remapped addresses:
-
- ```yaml deployments/default.testnet-plan.yaml
- ---
- id: 0
- name: Testnet deployment
- network: testnet
- stacks-node: "https://api.testnet.hiro.so"
- bitcoin-node: "http://blockstream.info"
- plan:
- batches:
- - id: 0
- transactions:
- - requirement-publish:
- contract-id: ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-token
- remap-sender: SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4
- remap-principals:
- SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4: ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT
- cost: 50000
- path: "./.cache/requirements/SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token.clar"
- ```
-
- Deploy to testnet:
-
- ```terminal
- $ clarinet deployments apply -p deployments/default.testnet-plan.yaml
- ```
-
-
-
-## Common patterns
-
-## Working with sBTC addresses
-
-Clarinet handles sBTC contract address mapping across networks:
-
-| Network | sBTC Contract Address |
-|---------|---------------------|
-| Simnet/Devnet | `SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token` |
-| Testnet | `ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-token` |
-| Mainnet | Contract address remains unchanged |
-
-Your contract code always references the simnet address. Clarinet automatically remaps during deployment.
-
-## Manual sBTC minting in unit tests
-
-While Clarinet 2.15.0+ automatically funds wallets with sBTC in devnet, you may need to manually mint sBTC in unit tests for specific scenarios:
-
-### Minting sBTC using the deployer address
-
-The sBTC token contract allows the deployer (multisig) address to mint tokens. Use this approach in your tests:
-
-```typescript tests/manual-sbtc-mint.test.ts -c
-import { describe, expect, it } from "vitest";
-import { Cl } from "@stacks/transactions";
-
-describe("Manual sBTC minting", () => {
- it("mints sBTC to custom addresses", () => {
- // The sBTC multisig address that can mint
- const sbtcDeployer = "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4";
- const customWallet = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM";
-
- // Mint 1000 sats to custom wallet
- const mintResult = simnet.callPublicFn(
- "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
- "mint",
- [
- Cl.uint(1000), // amount in sats
- Cl.principal(customWallet) // recipient
- ],
- sbtcDeployer // sender must be deployer
- );
-
- expect(mintResult.result).toBeOk(Cl.bool(true));
-
- // Verify balance
- const balance = simnet.callReadOnlyFn(
- "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
- "get-balance",
- [Cl.principal(customWallet)],
- customWallet
- );
-
- expect(balance.result).toBeOk(Cl.uint(1000));
- });
-});
-```
-
-### Testing with mainnet execution simulation
-
-When using mainnet execution simulation, you can mint sBTC using the actual mainnet multisig:
-
-```typescript -c
-const mainnetMultisig = "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4";
-const mainnetWallet = "SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR";
-
-// Mint sBTC to any mainnet address
-simnet.callPublicFn(
- "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
- "mint",
- [Cl.uint(100000), Cl.principal(mainnetWallet)],
- mainnetMultisig
-);
-```
-
-This approach is useful for:
-- Testing specific sBTC amounts
-- Simulating different wallet balances
-- Testing edge cases with precise token amounts
-- Integration testing with mainnet contracts
diff --git a/content/docs/en/tools/clarinet/(integrations)/stacks-js-integration.mdx b/content/docs/en/tools/clarinet/(integrations)/stacks-js-integration.mdx
deleted file mode 100644
index 54cb6e514..000000000
--- a/content/docs/en/tools/clarinet/(integrations)/stacks-js-integration.mdx
+++ /dev/null
@@ -1,246 +0,0 @@
----
-title: Stacks.js integration with devnet
-sidebarTitle: Stacks.js integration
-description: In this guide, you'll learn how to interacts with your smart contracts on devnet using the Stacks.js libraries.
----
-
-## What you'll learn
-
-:::objectives
-- Configure Stacks.js for local devnet connection
-- Make STX transfers between devnet accounts
-- Call smart contract functions from JavaScript
-- Deploy contracts programmatically
-:::
-
-## Quickstart
-
-
-
- ### Install Stacks.js packages
-
- Add the required Stacks.js packages to your frontend project:
-
- ```package-install
- @stacks/transactions @stacks/network
- ```
-
-
-
- ### Configure for devnet
-
- Set up a devnet network configuration:
-
- ```ts devnet-config.ts
- import { StacksDevnet } from '@stacks/network';
-
- // Configure for local devnet
- export const devnet = new StacksDevnet({
- url: 'http://localhost:3999'
- });
-
- // Get devnet accounts (matches Clarinet wallets)
- export const accounts = {
- deployer: {
- address: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- key: 'cb3df38053d132895220b9ce471f6b676db5b9bf0b4adefb55f2118ece2478df01'
- },
- wallet1: {
- address: 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5',
- key: '7287ba251d44a4d3fd9276c88ce34c5c52a038955511cccaf77e61068649c17801'
- }
- };
- ```
-
-
-
- ### Test STX transfers
-
- Create a simple STX transfer between devnet accounts:
-
- ```ts stx-transfer.ts
- import { makeSTXTokenTransfer, broadcastTransaction, AnchorMode } from '@stacks/transactions';
- import { devnet, accounts } from './devnet-config';
-
- async function transferSTX() {
- const tx = await makeSTXTokenTransfer({
- amount: 1000000n, // 1 STX in microSTX
- recipient: accounts.wallet1.address,
- senderKey: accounts.deployer.key,
- network: devnet,
- anchorMode: AnchorMode.Any,
- });
-
- const result = await broadcastTransaction(tx, devnet);
- console.log('Transaction ID:', result.txid);
-
- // Transaction will be mined in next devnet block
- return result.txid;
- }
-
- transferSTX().catch(console.error);
- ```
-
- Run the transfer:
-
- ```terminal
- $ ts-node stx-transfer.ts
- Transaction ID: 0x3d5f8a70c4821e0f8c985b1f5b9d77f8c4b6d1a2e7f9c3b8a4d5e6f1c8d9b7a3
- ```
-
-
-
- ### Call smart contracts
-
- Interact with contracts deployed on devnet:
-
- ```ts contract-call.ts
- import { makeContractCall, broadcastTransaction, AnchorMode, Cl } from '@stacks/transactions';
- import { devnet, accounts } from './devnet-config';
-
- async function callContract() {
- const tx = await makeContractCall({
- contractAddress: accounts.deployer.address,
- contractName: 'counter',
- functionName: 'increment',
- functionArgs: [],
- senderKey: accounts.wallet1.key,
- network: devnet,
- anchorMode: AnchorMode.Any,
- });
-
- const result = await broadcastTransaction(tx, devnet);
- console.log('Contract call ID:', result.txid);
-
- return result.txid;
- }
-
- // Read contract state
- async function readCount() {
- const response = await fetch(
- `${devnet.coreApiUrl}/v2/contracts/call-read/${accounts.deployer.address}/counter/get-count`,
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- sender: accounts.wallet1.address,
- arguments: []
- })
- }
- );
-
- const data = await response.json();
- console.log('Current count:', data.result);
- }
-
- callContract()
- .then(() => readCount())
- .catch(console.error);
- ```
-
-
-
- ### Deploy contracts from frontend
-
- Deploy new contracts to devnet programmatically:
-
- ```ts deploy-contract.ts
- import { makeContractDeploy, broadcastTransaction, AnchorMode } from '@stacks/transactions';
- import { devnet, accounts } from './devnet-config';
-
- async function deployContract() {
- const contractCode = `
- (define-data-var count uint u0)
-
- (define-public (increment)
- (ok (var-set count (+ (var-get count) u1)))
- )
-
- (define-read-only (get-count)
- (var-get count)
- )
- `;
-
- const tx = await makeContractDeploy({
- contractName: 'my-counter',
- codeBody: contractCode,
- senderKey: accounts.deployer.key,
- network: devnet,
- anchorMode: AnchorMode.Any,
- });
-
- const result = await broadcastTransaction(tx, devnet);
- console.log('Contract deployed:', result.txid);
-
- return result.txid;
- }
-
- deployContract().catch(console.error);
- ```
-
-
-
-## Common patterns
-
-### Watching for transaction confirmation
-
-Monitor when transactions are confirmed on devnet:
-
-```ts transaction-monitor.ts
-async function waitForTransaction(txid: string) {
- let attempts = 0;
- const maxAttempts = 10;
-
- while (attempts < maxAttempts) {
- const response = await fetch(
- `${devnet.coreApiUrl}/extended/v1/tx/${txid}`
- );
-
- const tx = await response.json();
-
- if (tx.tx_status === 'success') {
- console.log('Transaction confirmed!');
- return tx;
- }
-
- if (tx.tx_status === 'abort_by_response') {
- throw new Error(`Transaction failed: ${tx.tx_result.repr}`);
- }
-
- // Wait for next block
- await new Promise(resolve => setTimeout(resolve, 5000));
- attempts++;
- }
-
- throw new Error('Transaction timeout');
-}
-```
-
-### Post conditions for safety
-
-Add post conditions to ensure contract calls behave as expected:
-
-```ts safe-transfer.ts
-import { Pc } from '@stacks/transactions';
-
-const postConditions = [
- // Ensure sender's balance decreases by exactly the amount
- Pc.principal(accounts.wallet1.address)
- .willSendEq(1000000n)
- .ustx(),
-
- // Ensure recipient receives the amount
- Pc.principal(accounts.deployer.address)
- .willReceiveEq(1000000n)
- .ustx()
-];
-
-const tx = await makeSTXTokenTransfer({
- amount: 1000000n,
- recipient: accounts.deployer.address,
- senderKey: accounts.wallet1.key,
- network: devnet,
- postConditions,
- anchorMode: AnchorMode.Any,
-});
-```
diff --git a/content/docs/en/tools/clarinet/(overview)/faq.mdx b/content/docs/en/tools/clarinet/(overview)/faq.mdx
deleted file mode 100644
index 530b4f3a4..000000000
--- a/content/docs/en/tools/clarinet/(overview)/faq.mdx
+++ /dev/null
@@ -1,195 +0,0 @@
----
-title: Frequently asked questions
-sidebarTitle: FAQ
-description: Common questions and solutions for Clarinet development
----
-
-This page addresses common questions and issues encountered when developing with Clarinet, based on community feedback and support interactions.
-
-## Testing and development
-
-
-
- How do I test with sBTC tokens in my development environment?
-
-
- To test with sBTC tokens, add the mainnet sBTC contract as a requirement and mint tokens using the deployer address:
-
- **Step 1: Add sBTC as a requirement**
- ```terminal
- $ clarinet requirements add SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token
- ```
-
- **Step 2: Mint sBTC in your tests**
- ```typescript
- // The sBTC multisig address that can mint
- const sbtcDeployer = "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4";
-
- // Mint sBTC to your test wallet
- const mintTx = simnet.callPublicFn(
- "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
- "mint",
- [Cl.uint(1000000), Cl.principal(wallet1)],
- sbtcDeployer
- );
- ```
-
- This approach allows you to work with sBTC in unit tests without complex Bitcoin transaction simulation.
-
-
-
-
-
- Why am I getting an error when using mainnet addresses during mainnet simulation?
-
-
- When using mainnet execution simulation, it's possible that the mainnet contract is checking for mainnet address contract calls, not testnet addresses.
-
- **As of Clarinet v3.4.0**, you can enable mainnet addresses in simnet by adding `use_mainnet_wallets = true` to your configuration:
-
- ```toml Clarinet.toml
- [repl.remote_data]
- enabled = true
- initial_height = 522000
- use_mainnet_wallets = true # Enable mainnet addresses
- ```
-
- **Alternative: Manually use mainnet addresses:**
- ```typescript
- // Instead of using simnet.getAccounts()
- const mainnetAddress = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY";
-
- // Mint STX to any mainnet address
- simnet.mintSTX(mainnetAddress, 1000000n);
-
- // Call functions with mainnet address
- const result = simnet.callReadOnlyFn(
- "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3",
- "get-price",
- [priceFeed],
- mainnetAddress
- );
- ```
-
- The simnet is permissive and accepts any valid Stacks address when mainnet simulation is enabled.
-
-
-
-
-
- How do I migrate from expectSTXTransferEvent to the new SDK?
-
-
- The Clarinet v2 SDK uses standard Vitest matchers instead of custom event helpers. Here's how to migrate:
-
- **Old approach (Clarinet v1):**
- ```typescript
- block.receipts[0].events.expectSTXTransferEvent(
- amount,
- sender,
- recipient
- );
- ```
-
- **New approach (Clarinet v2):**
- ```typescript
- // Check for exact event match
- expect(events).toContainEqual({
- event: "stx_transfer_event",
- data: {
- amount: "1000000",
- memo: "",
- recipient: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM",
- sender: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5",
- },
- });
-
- // Or check only specific properties
- expect(events).toContainEqual({
- event: "stx_transfer_event",
- data: expect.objectContaining({
- sender: address1,
- recipient: contractAddress,
- }),
- });
- ```
-
- For Clarity value assertions, use the built-in matchers:
- ```typescript
- expect(result).toBeOk(Cl.bool(true));
- expect(result).toBeErr(Cl.uint(500));
- ```
-
-
-
-
-
-## Configuration and setup
-
-
-
- Why am I getting "bip39 error" when generating deployment plans?
-
-
- Starting with Clarinet 2.15.0, deployment configurations require 24-word mnemonics. 12-word mnemonics are no longer supported.
-
- **Update your configuration:**
- ```toml settings/Mainnet.toml
- [accounts.deployer]
- # Use a 24-word mnemonic
- mnemonic = "twice kind fence tip hidden tilt action fragile skin nothing glory cousin green tomorrow spring wrist shed math olympic multiply hip blue scout claw"
- ```
-
- Generate a new 24-word mnemonic using a BIP39 generator if needed. This change improves security for production deployments.
-
-
-
-
-
-## Known limitations
-
-
-
- Can I test Bitcoin transaction verification in Clarinet?
-
-
- Testing contracts that use clarity-bitcoin-lib for Bitcoin transaction verification has limitations in simnet and devnet:
-
- **Current limitations:**
- - No real Bitcoin blocks or transactions in simnet
- - Mock blocks don't contain verifiable Bitcoin transactions
- - `get-burn-block-info?` returns mock data unsuitable for verification
-
- **Workarounds:**
- - Test Bitcoin verification logic on mainnet or with mainnet execution simulation
- - Create unit tests that mock expected behavior without actual verification
- - Consider separating Bitcoin verification logic for easier testing
-
- The Clarinet team is exploring solutions for better Bitcoin testing support.
-
-
-
-
-
- Why does my devnet freeze at epoch 3.0 transition?
-
-
- The epoch 3.0 transition in devnet can be unstable, with success rates varying between 50-80% depending on your setup.
-
- **Current workarounds:**
- - Restart devnet if it freezes around blocks 139-140
- - Try Clarinet 2.14.0 which some users report as more stable
- - Wait for the upcoming feature to start devnet directly in epoch 3.0
-
- **Monitoring the transition:**
- ```console
- # Watch for the transition around these blocks
- Block 139: Epoch 2.5
- Block 140: Should transition to 3.0
- ```
-
- The Clarinet team is working on improving epoch transition stability and plans to allow starting devnet directly in epoch 3.0.
-
-
-
-
diff --git a/content/docs/en/tools/clarinet/(overview)/meta.json b/content/docs/en/tools/clarinet/(overview)/meta.json
deleted file mode 100644
index 0b86dc6e7..000000000
--- a/content/docs/en/tools/clarinet/(overview)/meta.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "title": "Overview",
- "pages": ["quickstart", "project-structure"]
-}
diff --git a/content/docs/en/tools/clarinet/(overview)/project-structure.mdx b/content/docs/en/tools/clarinet/(overview)/project-structure.mdx
deleted file mode 100644
index 9544eacec..000000000
--- a/content/docs/en/tools/clarinet/(overview)/project-structure.mdx
+++ /dev/null
@@ -1,276 +0,0 @@
----
-title: Project structure
-sidebarTitle: Project structure
-description: Understand the complete structure and configuration of a Clarinet project
-type: concept
----
-
-A Clarinet project follows a carefully designed structure that separates contracts, tests, and configuration. Understanding this structure helps you organize code effectively and configure tools for optimal development workflow.
-
-## Core project layout
-
-Every Clarinet project contains these essential directories and files:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Each component serves a specific purpose in your development workflow. Let's explore how they work together to create a complete development environment.
-
-## The project manifest
-
-### Clarinet.toml
-
-The **Clarinet.toml** file is the heart of your project. It defines project metadata and tracks all contracts:
-
-```toml Clarinet.toml
-[project]
-name = "counter"
-description = "A counter smart contract"
-
-[contracts.traits]
-path = "contracts/traits.clar"
-clarity_version = 3
-epoch = "latest"
-
-[contracts.counter]
-path = 'contracts/counter.clar'
-clarity_version = 3
-epoch = "latest"
-```
-
-The manifest handles several critical functions:
-
-- **Contract registration**: Every contract must be listed here
-- **Stacks Epoch and Clarity version**: Specifies Clarity version and epoch for each contract
-- **Boot sequence**: Lists contracts to deploy on `clarinet devnet start`
-
-### Epoch configuration
-
-You can specify the epoch in two ways:
-
-```toml
-# Use a specific epoch version
-epoch = 3.1
-
-# Use the latest available epoch (default)
-epoch = "latest"
-```
-
-Using `"latest"` ensures your contracts always use the newest Clarity features and optimizations available in your version of Clarinet.
-
-## Testing infrastructure
-
-### Package configuration
-
-The **package.json** defines your testing environment and dependencies:
-
-```json package.json
-{
- "name": "counter-tests",
- "version": "1.0.0",
- "description": "Run unit tests on this project.",
- "type": "module",
- "private": true,
- "scripts": {
- "test": "vitest run",
- "test:report": "vitest run -- --coverage --costs",
- "test:watch": "chokidar \"tests/**/*.ts\" \"contracts/**/*.clar\" -c \"npm run test:report\""
- },
- "author": "",
- "license": "ISC",
- "dependencies": {
- "@hirosystems/clarinet-sdk": "^3.0.2",
- "@stacks/transactions": "^7.0.6",
- "@types/node": "^24.0.14",
- "chokidar-cli": "^3.0.0",
- "vitest": "^3.1.3",
- "vitest-environment-clarinet": "^2.3.0"
- }
-}
-```
-
-| Package | Purpose |
-|---------|---------|
-| `@hirosystems/clarinet-sdk` | WebAssembly-compiled Clarinet for Node.js |
-| `@stacks/transactions` | Clarity value manipulation in TypeScript |
-| `vitest` | Modern testing framework with native TypeScript support |
-| `vitest-environment-clarinet` | Simnet bootstrapping for tests |
-
-### Vitest configuration
-
-The **vitest.config.js** configures the testing framework:
-
-```js vitest.config.js
-///
-import { defineConfig } from "vite";
-import { vitestSetupFilePath, getClarinetVitestsArgv } from "@hirosystems/clarinet-sdk/vitest";
-
-export default defineConfig({
- test: {
- environment: "clarinet", // use vitest-environment-clarinet
- pool: "forks",
- poolOptions: {
- threads: { singleThread: true },
- forks: { singleFork: true },
- },
- setupFiles: [
- vitestSetupFilePath,
- // custom setup files can be added here
- ],
- environmentOptions: {
- clarinet: {
- ...getClarinetVitestsArgv(),
- // add or override options
- },
- },
- },
-});
-```
-
-This configuration enables:
-
-- **Clarinet environment**: Automatic `simnet` setup for each test
-- **Single fork mode**: Efficient test execution with proper isolation
-- **Coverage tracking**: Generate reports in multiple formats
-- **Custom setup**: Add project-specific test utilities
-
-### TypeScript configuration
-
-The **tsconfig.json** provides TypeScript support:
-
-```json tsconfig.json
-
-{
- "compilerOptions": {
- "target": "ESNext",
- "useDefineForClassFields": true,
- "module": "ESNext",
- "lib": ["ESNext"],
- "skipLibCheck": true,
-
- "moduleResolution": "bundler",
- "allowImportingTsExtensions": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "noEmit": true,
-
- "strict": true,
- "noImplicitAny": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noFallthroughCasesInSwitch": true
- },
- // !mark(1:4)
- "include": [
- "node_modules/@hirosystems/clarinet-sdk/vitest-helpers/src",
- "tests"
- ]
-}
-```
-
-It's important to properly set the include property, by default it points to the helpers files defined in the clarinet-sdk package, and to the tests directory.
-
-## Network configurations
-
-### Environment settings
-
-Each network has its own configuration file in the **settings** directory:
-
-```toml settings/Devnet.toml
-[network]
-name = "devnet"
-deployment_fee_rate = 10
-
-[accounts.deployer]
-mnemonic = "twice kind fence tip hidden..."
-balance = 100_000_000_000_000
-
-[accounts.wallet_1]
-mnemonic = "sell invite acquire kitten..."
-balance = 10_000_000_000_000
-```
-
-These settings control:
-
-- **Network ports**: API, RPC, and explorer endpoints
-- **Account configuration**: Test wallets with STX balances
-- **Chain parameters**: Network-specific blockchain settings
-
-:::callout
-type: warn
-### Security Notice
-Never commit mainnet private keys or mnemonics. Use environment variables for production credentials.
-:::
-
-## Common issues
-
-
-
- Imports failing in tests
-
-
- If you're encountering import errors in your tests, update your TypeScript configuration to use Vite's bundler resolution:
-
- ```json tsconfig.json
- {
- "compilerOptions": {
- "moduleResolution": "bundler", // !mark
- "allowImportingTsExtensions": true
- }
- }
- ```
-
- This configuration ensures TypeScript understands Vite's module resolution strategy and allows importing `.ts` files directly.
-
-
-
-
-
- Mismatched versions
-
-
- All contracts in your project should use the same Clarity version and epoch to avoid compatibility issues:
-
- ```toml Clarinet.toml
- [contracts.token]
- clarity_version = 3
- epoch = "latest" # !mark
-
- [contracts.pool]
- clarity_version = 3
- epoch = "latest" # !mark
- ```
-
- Mismatched versions can cause deployment failures and unexpected behavior. Always upgrade all contracts together when moving to a new Clarity version.
-
-
-
-
-
-## Next steps
-
-:::next-steps
-- [Writing Clarity contracts](/tools/clarinet/project-development): Create and manage Clarity contracts.
-- [Testing and validation](/tools/clarinet/contract-interaction): Interact with Clarity contracts in your project.
-:::
diff --git a/content/docs/en/tools/clarinet/(overview)/quickstart.mdx b/content/docs/en/tools/clarinet/(overview)/quickstart.mdx
deleted file mode 100644
index e9ba6a567..000000000
--- a/content/docs/en/tools/clarinet/(overview)/quickstart.mdx
+++ /dev/null
@@ -1,158 +0,0 @@
----
-title: Quickstart
-description: In this guide, you'll build a simple counter smart contract and interact with it in a local environment.
----
-
-## What you'll learn
-
-:::objectives
-- Create a Clarity smart contract project
-- Write Clarity code with maps and public functions
-- Test and validate your contracts using Clarinet's console
-:::
-
-## Prerequisites
-
-:::prerequisites
-- Clarinet installed on your machine. Follow the [installation guide](/tools/clarinet#installation) if needed.
-- A code editor like VS Code for editing Clarity files.
-:::
-
-## Quickstart
-
-
-
- ### Create your project
-
- Let's start by creating a new Clarinet project. The `clarinet new` command sets up everything you need for smart contract development, including a testing framework, deployment configurations, and a local development environment:
-
- ```terminal
- $ clarinet new counter
- [32mCreate directory[0m [1mcounter[0m
- [32mCreate directory[0m [1mcontracts[0m
- [32mCreate directory[0m [1msettings[0m
- [32mCreate directory[0m [1mtests[0m
- [32mCreate file[0m [1mClarinet.toml[0m
- [32mCreate file[0m [1mpackage.json[0m
- [32mCreate file[0m [1mvitest.config.js[0m
- ```
-
- Clarinet creates a complete project structure for you. Each folder serves a specific purpose in your development workflow:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ### Generate your contract
-
- Now that we have our project structure, let's create a smart contract. Navigate into your project directory and use Clarinet's contract generator:
-
- ```terminal
- $ cd counter
- $ clarinet contract new counter
- [32mCreated file[0m [1mcontracts/counter.clar[0m
- [32mCreated file[0m [1mtests/counter.test.ts[0m
- [33mUpdated Clarinet.toml[0m [1mwith contract counter[0m
- ```
-
- Clarinet automatically creates both your contract file and a corresponding test file. This follows the best practice of writing tests alongside your contract code:
-
- | File | Purpose |
- |------|---------|
- | `contracts/counter.clar` | Your smart contract code |
- | `tests/counter.test.ts` | Test file for your contract |
-
- :::callout
- Notice that Clarinet also updated your `Clarinet.toml` file. This configuration file tracks all contracts in your project and their deployment settings.
- :::
-
-
-
- ### Write your contract code
-
- Open `contracts/counter.clar` and replace its contents with our counter implementation. This contract will maintain a separate count for each user who interacts with it:
-
- ```clarity contracts/counter.clar -c
- ;; Define a map to store counts for each user
- (define-map counters principal uint)
-
- ;; Increment the count for the caller
- (define-public (count-up)
- (ok (map-set counters tx-sender (+ (get-count tx-sender) u1)))
- )
-
- ;; Get the current count for a user
- (define-read-only (get-count (who principal))
- (default-to u0 (map-get? counters who))
- )
- ```
-
- Let's understand what each part does:
- - [`define-map`](/resources/clarity/reference/functions#define-map) creates a persistent storage map that associates each user (principal) with their count
- - [`tx-sender`](/resources/clarity/reference/keywords#tx-sender) is a built-in variable that contains the address of whoever calls the function
- - [`define-public`](/resources/clarity/reference/functions#define-public) declares functions that can modify contract state
- - [`define-read-only`](/resources/clarity/reference/functions#define-read-only) declares functions that only read data without modifying it
-
-
-
- ### Validate your contract
-
- Before we can test our contract, let's make sure it's syntactically correct and type-safe. Clarinet's check command analyzes your contract without deploying it:
-
- ```terminal
- $ clarinet check
- [32m✔[0m [1m1 contract checked[0m
- ```
-
- If you see errors instead, here are the most common issues and how to fix them:
-
- | Error | Fix |
- |-------|-----|
- | `Unknown keyword` | Check spelling of Clarity functions |
- | `Type mismatch` | Ensure you're using correct types (uint, principal, etc.) |
- | `Unresolved contract` | Verify contract name in `Clarinet.toml` matches the contract name in the file |
-
-
-
- ### Test in the console
-
- Now for the exciting part—let's interact with our contract! Clarinet provides an interactive console where you can call functions and see results immediately. Start the console with:
-
- ```terminal
- $ clarinet console
- ```
-
- Once the console loads, you can call your contract functions directly. Here are a few examples you can try:
-
- ```terminal
- $ (contract-call? .counter count-up)
- [32m(ok true)[0m
- $ (contract-call? .counter get-count tx-sender)
- [32mu1[0m
- $ (contract-call? .counter count-up)
- [32m(ok true)[0m
- $ (contract-call? .counter get-count tx-sender)
- [32mu2[0m
- ```
-
-
-
-## Next steps
-
-:::next-steps
-- [Project structure](/tools/clarinet/project-structure): Learn about the project structure and how to manage your contracts.
-- [Local blockchain development](/tools/clarinet/local-blockchain-development): Spin up a local blockchain to test your contracts.
-:::
diff --git a/content/docs/en/tools/clarinet/(vscode-extension)/meta.json b/content/docs/en/tools/clarinet/(vscode-extension)/meta.json
deleted file mode 100644
index 43668fc6e..000000000
--- a/content/docs/en/tools/clarinet/(vscode-extension)/meta.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "title": "VSCode Extension",
- "pages": ["vscode-extension"]
-}
diff --git a/content/docs/en/tools/clarinet/(vscode-extension)/vscode-extension.mdx b/content/docs/en/tools/clarinet/(vscode-extension)/vscode-extension.mdx
deleted file mode 100644
index 9086ec788..000000000
--- a/content/docs/en/tools/clarinet/(vscode-extension)/vscode-extension.mdx
+++ /dev/null
@@ -1,102 +0,0 @@
----
-title: VS Code extension
-sidebarTitle: Introduction
-description: The Clarity VS Code extension transforms your editor into a powerful smart contract development environment. You get syntax highlighting, auto-completion, debugging, and real-time error checking.
----
-
-## Features
-
-### Smart auto-completion
-
-The extension provides intelligent code completion that understands Clarity's context. When you start typing any Clarity function, you get instant suggestions with documentation:
-
-```clarity
-;; Type "stx-tr" and get:
-(stx-transfer? amount sender recipient)
-;; ^ ^ ^
-;; Placeholders for easy navigation
-```
-
-Use `Tab` to jump between placeholders and `Escape` to exit placeholder mode.
-
-### Documentation on hover
-
-Access comprehensive documentation without leaving your editor. Hover over any Clarity function or keyword to see:
-
-```clarity
-;; Hover over 'map-set' to see:
-;; - Function signature
-;; - Parameter descriptions
-;; - Return type
-;; - Usage examples
-(map-set my-map {key: "value"} "data")
-```
-
-### Go-to definition
-
-Navigate your codebase efficiently with jump-to-definition features:
-
-- `F12` or `Ctrl+Click` - Go to definition
-- `Alt+F12` - Peek definition without leaving current file
-- Works across contract files and contract calls
-
-### Real-time error checking
-
-The extension validates your code continuously, providing immediate feedback:
-
-- **Red squiggles** - Syntax errors, unknown keywords
-- **Yellow squiggles** - Warnings for potentially unsafe code
-- **Error list** - All issues in the Problems panel (`Ctrl+Shift+M`)
-
-Common errors caught include undefined variables, type mismatches, missing trait implementations, and invalid function signatures.
-
-### Local contract resolution
-
-Auto-completion works across your entire project. Reference functions from other contracts in your workspace:
-
-```clarity
-;; Auto-complete local contract calls
-(contract-call? .my-token transfer amount sender recipient)
-;; ^
-;; Suggests contracts in your project
-```
-
-### Trait support
-
-When implementing traits (like SIP-009 NFTs or SIP-010 tokens), the extension verifies:
-
-- All required functions are implemented
-- Function signatures match trait definitions
-- Return types are correct
-
-```clarity
-;; Extension warns if missing required trait functions
-(impl-trait .sip-010-trait.sip-010-trait)
-
-;; ⚠️ Warning: Missing required function 'get-balance'
-```
-
-### Visual debugging
-
-The extension includes a visual debugger for step-by-step code execution:
-
-1. Set breakpoints by clicking line numbers
-2. Press `F5` or use Run → Start Debugging
-3. Step through code line-by-line
-4. Inspect variables and stack state
-
-:::callout
-### Requirements
-Visual debugging requires VS Code Desktop and Clarinet installed locally.
-:::
-
-## Comparison table
-
-| Feature | Basic Editor | VS Code Extension |
-|---------|--------------|-------------------|
-| Syntax highlighting | Limited | Full Clarity support |
-| Auto-completion | None | Context-aware with docs |
-| Error checking | On deploy only | Real-time validation |
-| Documentation | External lookup | Inline hover docs |
-| Debugging | Console only | Visual debugger |
-| Cross-file navigation | Manual | Jump to definition |
diff --git a/content/docs/en/tools/clarinet/index.mdx b/content/docs/en/tools/clarinet/index.mdx
deleted file mode 100644
index 60dee21ea..000000000
--- a/content/docs/en/tools/clarinet/index.mdx
+++ /dev/null
@@ -1,72 +0,0 @@
----
-title: Clarinet
-sidebarTitle: Overview
-description: Clarinet is everything you need to write, test, and deploy Clarity smart contracts on Stacks.
-type: overview
-llm: false
----
-
-## Overview
-
-Clarinet is the fastest way to build, test, and deploy smart contracts on the Stacks blockchain. It gives you a local devnet, REPL, testing framework, and debugging tools to ship high-quality Clarity code with confidence.
-
-
-
-To explore Clarinet features with AI, copy and paste [llms.txt](/tools/clarinet/llms.txt) into your LLM of choice.
-
-## Key features
-
-- [**Leverage a powerful CLI**](/tools/clarinet/cli-reference) - Create new projects, manage your smart contracts and their dependencies using clarinet requirements, and interact with your code through the built-in REPL.
-- [**Write unit tests with the SDK**](/tools/clarinet/sdk-introduction) - Use the Clarinet SDK to write unit tests in a familiar JS environment and validate contract behavior.
-- [**Run a private blockchain environment**](/tools/clarinet/local-blockchain-development) - Spin up a local devnet with nodes, miners, and APIs so you can test and integrate your code.
-- [**VSCode extension**](/tools/clarinet/vscode-extension) - Linter, step by step debugger, helps writing smart contracts (autocompletion, documentation etc).
-
-## Installation
-
-
- ```terminal !! Homebrew
- $ brew install clarinet
- ```
-
- ```terminal !! Winget
- $ winget install clarinet
- ```
-
- ```terminal !! Source
- $ sudo apt install build-essential pkg-config libssl-dev
- $ git clone https://github.com/hirosystems/clarinet
- $ cd clarinet
- $ cargo clarinet-install
- ```
-
- ```terminal !! Binary
- $ wget -nv https://github.com/hirosystems/clarinet/releases/latest/download/clarinet-linux-x64-glibc.tar.gz -O clarinet-linux-x64.tar.gz
- $ tar -xf clarinet-linux-x64.tar.gz
- $ chmod +x ./clarinet
- $ mv ./clarinet /usr/local/bin
- ```
-
-
-## Networks
-
-Clarinet supports different network types to cater to various development and testing needs:
-
-| Network | Description | Use case
-| -------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
-| `simnet` | Optimized for fast feedback loops, introspection, and portability. | Ideal for initial development and unit-testing. |
-| `devnet` | Local Stacks and Bitcoin nodes running on Docker for faster feedback loops. | Use for integration tests or local frontend development. |
-| `testnet` | A pre-production network that offers a realistic environment for testing. | Ideal for final testing before deploying to Mainnet. |
-| `mainnet` | The production network where real transactions occur. | Use when you're ready to deploy your smart contract to production. |
-
-## Next steps
-
-:::next-steps
-- [Quickstart](/tools/clarinet/quickstart): Get started with Clarinet.
-- [Create a project](/tools/clarinet/project-development): Create a new Clarinet project.
-:::
-
-:::callout
-type: help
-### Need help building with Clarinet?
-Reach out to us on the **#clarinet** channel on [Discord](https://stacks.chat/) under the Hiro Developer Tools section. There's also a [weekly office hours](https://www.addevent.com/event/kI22007085) call every Wednesday at 1pm ET.
-:::
diff --git a/content/docs/en/tools/clarinet/meta.json b/content/docs/en/tools/clarinet/meta.json
deleted file mode 100644
index 008ac3413..000000000
--- a/content/docs/en/tools/clarinet/meta.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "title": "Clarinet",
- "root": true,
- "pages": [
- "---Clarinet---",
- "index",
- "...(overview)",
- "---Clarinet CLI---",
- "...(clarinet-cli)",
- "---Clarinet JS SDK---",
- "...(clarinet-js-sdk)",
- "---VSCode Extension---",
- "...(vscode-extension)",
- "---Integrations---",
- "...(integrations)"
- ]
-}
diff --git a/content/docs/es/reference/stacks.js/(connect)/broadcast-transactions.mdx b/content/docs/es/reference/stacks.js/(connect)/broadcast-transactions.mdx
deleted file mode 100644
index 3964f983e..000000000
--- a/content/docs/es/reference/stacks.js/(connect)/broadcast-transactions.mdx
+++ /dev/null
@@ -1,168 +0,0 @@
----
-title: Transmitir transacciones
-description: Solicita a los usuarios que firmen transacciones y las transmitan a la cadena de bloques de Stacks.
----
-import { Badge } from '@/components/ui/badge';
-import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
-
-import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';
-import { ChevronRight, Code, Terminal } from 'lucide-react';
-import { File, Folder, Files } from 'fumadocs-ui/components/files';
-
-El proceso de transmitir transacciones es fundamental para interactuar con blockchains, ya sea que estés transfiriendo tokens, desplegando contratos o ejecutando funciones de contratos.
-
-En esta guía, aprenderás cómo:
-
-1. [Instale los paquetes necesarios](#setup-and-installation)
-2. [Conectar a la billetera de un usuario](#connect-to-a-users-wallet)
-3. [Firmar y transmitir transacciones](#sign-and-broadcast-transactions)
-4. [Manejar resultados de transacciones](#handle-transaction-results)
-
-***
-
-## Configuración e instalación
-
-Instale los paquetes necesarios para comenzar a construir y transmitir transacciones:
-
-```package-install
-@stacks/connect @stacks/transactions
-```
-
-## Conectar a la billetera de un usuario
-
-Antes de firmar transacciones, los usuarios necesitan conectar su billetera a su aplicación. Use el `connect` función para iniciar una conexión de billetera:
-
-```ts
-import { connect, isConnected } from '@stacks/connect';
-
-async function connectWallet() {
- if (!isConnected()) {
- const response = await connect();
- console.log('Connected with addresses:', response);
- }
-}
-```
-
-## Firmar y transmitir transacciones
-
-Hay tres tipos de transacciones que puedes crear: transferencias de STX, implementaciones de contratos y llamadas a contratos.
-
-
-
-
- Transferencia de STX
-
-
-
- Despliegue de contratos
-
-
-
- Ejecución del contrato
-
-
-
-
- Para transferir tokens STX, utiliza el `request` método con `stx_transferStx`:
-
- ```ts
- import { request } from '@stacks/connect';
-
- async function transferStx() {
- const response = await request('stx_transferStx', {
- recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV',
- amount: '100', // in micro-STX (1 STX = 1,000,000 micro-STX)
- memo: 'Reimbursement', // optional
- });
-
- console.log('Transaction ID:', response.txId);
- }
- ```
-
-
-
- Para desplegar un contrato inteligente, utiliza el `request` método con `stx_deployContract`:
-
- ```ts
- import { request } from '@stacks/connect';
-
- async function deployContract() {
- const codeBody = '(define-public (say-hi) (ok "hello world"))';
-
- const response = await request('stx_deployContract', {
- name: 'my-contract',
- code: codeBody,
- clarityVersion: 3, // optional, defaults to latest version
- });
-
- console.log('Transaction ID:', response.txId);
- }
- ```
-
- Los contratos se implementarán en la dirección de Stacks de la billetera conectada.
-
-
-
- Para llamar a una función de contrato, utiliza el `request` método con 'stx\_callContract'. Aquí hay un ejemplo usando un contrato simple:
-
- ```clarity
- (define-public (say-hi)
- (print "hi")
- (ok u0)
- )
- ```
-
- Así es como se llama a esta función:
-
- ```ts
- import { request } from '@stacks/connect';
- import { Cl } from '@stacks/transactions';
-
- async function callContract() {
- const response = await request('stx_callContract', {
- contractAddress: 'ST22T6ZS7HVWEMZHHFK77H4GTNDTWNPQAX8WZAKHJ',
- contractName: 'my-contract',
- functionName: 'say-hi',
- functionArgs: [], // array of Clarity values
- });
-
- console.log('Transaction ID:', response.txId);
- }
- ```
-
- Para funciones que toman argumentos, puedes usar el `Cl` espacio de nombres para construir valores de Clarity:
-
- ```ts
- const functionArgs = [
- Cl.uint(123),
- Cl.stringAscii("hello"),
- Cl.standardPrincipalCV("ST1X.."),
- ];
- ```
-
-
-
-## Manejar resultados de transacciones
-
-Cuando una transacción es firmada y transmitida, el `request` el método devuelve un objeto de respuesta que contiene información sobre la transacción:
-
-```ts
-interface TransactionResponse {
- txId: string; // The transaction ID
- txRaw: string; // The raw transaction hex
-}
-```
-
-Puedes usar el ID de la transacción para crear un enlace para ver la transacción en el explorador:
-
-```ts
-async function handleTransaction() {
- const response = await request('stx_transferStx', {
- recipient: 'ST2EB9WEQNR9P0K28D2DC352TM75YG3K0GT7V13CV',
- amount: '100',
- });
-
- const explorerUrl = `https://explorer.stacks.co/txid/${response.txId}`;
- console.log('View transaction in explorer:', explorerUrl);
-}
-```
diff --git a/content/docs/es/reference/stacks.js/(connect)/connect-wallet.mdx b/content/docs/es/reference/stacks.js/(connect)/connect-wallet.mdx
deleted file mode 100644
index 3c05f0861..000000000
--- a/content/docs/es/reference/stacks.js/(connect)/connect-wallet.mdx
+++ /dev/null
@@ -1,135 +0,0 @@
----
-title: Conectar billetera
-description: Aprende cómo conectarte a billeteras de Stacks y autenticar usuarios.
----
-Aprende cómo integrar conexiones de billetera en tu aplicación de Stacks. Conectar una billetera autentica a los usuarios y permite interacciones con la blockchain como transferencias y llamadas a contratos.
-
-## Lo que aprenderás
-
-:::objectives
-* Instale el `@stacks/connect` paquete
-* Conectar a una billetera y autenticar usuarios
-* Gestionar el estado de autenticación
-* Acceder a los datos de la cuenta del usuario
-:::
-
-## Requisitos previos
-
-:::prerequisites
-* Node.js instalado en tu máquina
-* Una configuración de aplicación web (React, Vue o JavaScript puro)
-* Comprensión básica de async/await
-:::
-
-## Inicio rápido
-
-
-
- ### Instalar paquete
-
- Agregue el paquete Stacks Connect a su proyecto.
-
- ```package-install
- @stacks/connect
- ```
-
- Este paquete proporciona todas las funciones necesarias para las conexiones de billeteras y la autenticación de usuarios.
-
-
-
- ### Conectar y autenticar
-
- El `connect` La función inicia la conexión de la billetera y almacena los datos del usuario en el almacenamiento local para la persistencia de la sesión.
-
- ```ts
- import { connect, isConnected } from '@stacks/connect';
-
- async function connectWallet() {
- // Check if already connected
- if (isConnected()) {
- console.log('Already authenticated');
- return;
- }
-
- // Connect to wallet
- const response = await connect();
- console.log('Connected:', response.addresses);
- }
- ```
-
- Gestiona el estado de autenticación en toda tu aplicación.
-
- ```ts
- import { disconnect, isConnected } from '@stacks/connect';
-
- // Check authentication status
- const authenticated = isConnected();
-
- // Logout function
- function logout() {
- disconnect(); // Clears storage and wallet selection
- console.log('User disconnected');
- }
- ```
-
-
-
- ### Acceder a los datos del usuario
-
- Recuperar direcciones almacenadas y solicitar información detallada de la cuenta.
-
- ```ts
- import { getLocalStorage, request } from '@stacks/connect';
-
- // Get stored addresses from local storage
- const userData = getLocalStorage();
- if (userData?.addresses) {
- const stxAddress = userData.addresses.stx[0].address;
- const btcAddress = userData.addresses.btc[0].address;
- console.log('STX:', stxAddress);
- console.log('BTC:', btcAddress);
- }
- ```
-
- Obtenga información detallada de la cuenta, incluyendo las claves públicas.
-
- ```ts
- // Request full account details
- const accounts = await request('stx_getAccounts');
- const account = accounts.addresses[0];
-
- console.log('Address:', account.address);
- console.log('Public key:', account.publicKey);
- console.log('Gaia URL:', account.gaiaHubUrl);
- ```
-
-
-
- ### Realiza tu primera transacción
-
- Utilice la conexión autenticada para enviar tokens STX.
-
- ```ts
- import { request } from '@stacks/connect';
-
- async function sendTransaction() {
- const response = await request('stx_transferStx', {
- amount: '1000000', // 1 STX in micro-STX
- recipient: 'SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN',
- memo: 'First transfer', // optional
- });
-
- console.log('Transaction ID:', response.txid);
- }
- ```
-
- La billetera solicitará al usuario que apruebe la transacción antes de transmitirla.
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Firmar mensajes](/reference/stacks.js/message-signing): Demostrar la propiedad de la dirección
-* [Transmitir transacciones](/reference/stacks.js/broadcast-transactions): Aprende sobre diferentes tipos de transacciones
-:::
diff --git a/content/docs/es/reference/stacks.js/(connect)/message-signing.mdx b/content/docs/es/reference/stacks.js/(connect)/message-signing.mdx
deleted file mode 100644
index 7ed6944bf..000000000
--- a/content/docs/es/reference/stacks.js/(connect)/message-signing.mdx
+++ /dev/null
@@ -1,199 +0,0 @@
----
-title: Firmar mensajes
-description: Aprende cómo firmar y verificar mensajes para demostrar la propiedad de una dirección y autorizar acciones
----
-Aprende cómo implementar la firma de mensajes en tu aplicación Stacks. La firma de mensajes permite a los usuarios probar criptográficamente que controlan una dirección sin realizar una transacción en la cadena, permitiendo autenticación, autorización y declaraciones verificables.
-
-:::objectives
-* Conéctese a la billetera de un usuario y solicite firmas de mensajes
-* Firme tanto mensajes de texto simples como datos estructurados
-* Verificar firmas para garantizar la autenticidad
-:::
-
-:::prerequisites
-* Node.js instalado en tu máquina
-* Un editor de código como VS Code
-:::
-
-## Instalación
-
-Instale los paquetes necesarios para la firma y verificación de mensajes.
-
-```package-install
-@stacks/connect @stacks/encryption
-```
-
-## Conectar a la billetera
-
-Antes de firmar mensajes, establezca una conexión con la billetera del usuario. La conexión persiste a través de las recargas de página.
-
-```ts
-import { connect, isConnected } from '@stacks/connect';
-
-async function connectWallet() {
- if (!isConnected()) {
- const response = await connect();
- console.log('Connected addresses:', response.addresses);
- }
-}
-```
-
-Llama a esta función cuando tu aplicación se cargue o cuando el usuario haga clic en un botón de conexión.
-
-## Firmar mensajes de texto
-
-Solicitar una firma para un mensaje de texto simple utilizando el `request` método.
-
-```ts
-import { request } from '@stacks/connect';
-
-async function signMessage() {
- const message = 'Hello World';
-
- const response = await request('stx_signMessage', {
- message,
- });
-
- console.log('Signature:', response.signature);
- console.log('Public key:', response.publicKey);
-
- return response;
-}
-```
-
-La cartera mostrará el mensaje al usuario para su aprobación antes de firmar.
-
-## Firmar datos estructurados
-
-Para datos más complejos, utilice la firma de mensajes estructurados con valores de Clarity.
-
-```ts
-import { request } from '@stacks/connect';
-import { Cl } from '@stacks/transactions';
-
-async function signStructuredMessage() {
- const message = Cl.tuple({
- action: Cl.stringAscii('transfer'),
- amount: Cl.uint(1000),
- recipient: Cl.stringAscii('alice.btc')
- });
-
- const domain = Cl.tuple({
- name: Cl.stringAscii('My App'),
- version: Cl.stringAscii('1.0.0'),
- 'chain-id': Cl.uint(1) // 1 for mainnet
- });
-
- const response = await request('stx_signStructuredMessage', {
- message,
- domain
- });
-
- return response;
-}
-```
-
-Los mensajes estructurados proporcionan una mejor seguridad de tipos y son más fáciles de analizar en la cadena.
-
-## Verificar firmas
-
-Validar firmas para asegurar que coincidan con el mensaje esperado y la clave pública.
-
-```ts
-import { verifyMessageSignatureRsv } from '@stacks/encryption';
-
-async function verifySignature(
- message: string,
- signature: string,
- publicKey: string
-): Promise {
- const isValid = verifyMessageSignatureRsv({
- message,
- signature,
- publicKey
- });
-
- if (isValid) {
- console.log('✓ Signature verified successfully');
- } else {
- console.log('✗ Invalid signature');
- }
-
- return isValid;
-}
-```
-
-Siempre verifique las firmas antes de confiar en los datos firmados.
-
-### Completar el flujo de verificación
-
-```ts
-async function signAndVerify() {
- // Request signature
- const message = 'Authorize login at ' + new Date().toISOString();
- const signResponse = await request('stx_signMessage', { message });
-
- // Verify immediately
- const isValid = await verifySignature(
- message,
- signResponse.signature,
- signResponse.publicKey
- );
-
- if (isValid) {
- // Proceed with authenticated action
- console.log('Authentication successful');
- }
-}
-```
-
-## Pruébalo
-
-Crea un sistema de autenticación simple utilizando firmas de mensajes.
-
-```ts
-// Generate a unique challenge
-function generateChallenge(): string {
- const nonce = Math.random().toString(36).substring(7);
- const timestamp = Date.now();
- return `Sign this message to authenticate:\nNonce: ${nonce}\nTime: ${timestamp}`;
-}
-
-// Complete auth flow
-async function authenticate() {
- const challenge = generateChallenge();
-
- try {
- const response = await request('stx_signMessage', {
- message: challenge
- });
-
- const isValid = verifyMessageSignatureRsv({
- message: challenge,
- signature: response.signature,
- publicKey: response.publicKey
- });
-
- if (isValid) {
- // Store auth token or session
- localStorage.setItem('auth', JSON.stringify({
- publicKey: response.publicKey,
- timestamp: Date.now()
- }));
-
- return { success: true };
- }
- } catch (error) {
- console.error('Authentication failed:', error);
- }
-
- return { success: false };
-}
-```
-
-## Próximos pasos
-
-:::next-steps
-* [Transmitir transacciones](/reference/stacks.js/broadcast-transactions): Aprende cómo firmar y transmitir transacciones
-* [Referencia de la API de Connect](/reference/stacks.js/packages/connect): Explora todos los métodos disponibles
-:::
diff --git a/content/docs/es/reference/stacks.js/(connect)/migration-guide.mdx b/content/docs/es/reference/stacks.js/(connect)/migration-guide.mdx
deleted file mode 100644
index 9c3cbebca..000000000
--- a/content/docs/es/reference/stacks.js/(connect)/migration-guide.mdx
+++ /dev/null
@@ -1,103 +0,0 @@
----
-title: Guía de Migración
-description: Cómo migrar de v7.x.x a v8.x.x de @stacks/connect
----
-import { Steps, Step } from 'fumadocs-ui/components/steps'
-
-Durante un tiempo, la comunidad de Stacks ha estado trabajando en un nuevo estándar para la comunicación entre billeteras y dapps.
-Stacks Connect y proyectos relacionados ahora utilizan estándares como [WBIPs](https://wbips.netlify.app/) y [SIP-030](https://github.com/janniks/sips/blob/main/sips/sip-030/sip-030-wallet-interface.md) para permitir que las billeteras se comuniquen con las dapps de una manera más simplificada y flexible.
-
-:::callout
-### Estado de la Migración
-
-**Siéntete libre de seguir usando Stacks Connect `7.x.x` mientras las cosas se estabilizan.**
-El `7.x.x` La versión puede seguir siendo mejor soportada por algunas billeteras.
-
-Para la versión heredada de `@stacks/connect` usando tokens JWT, puedes usar:
-
-```sh
-npm install @stacks/connect@7.10.1
-```
-:::
-
-## Obsolescencias
-
-Las siguientes clases, métodos y tipos están obsoletos en favor de los nuevos `request` Métodos RPC:
-
-* `show...` y `open...` métodos
-* `authenticate` método
-* `UserSession` clase y funcionalidad relacionada
-* `AppConfig` clase
-* `SessionOptions` interfaz
-* `SessionData` interfaz
-* `UserData` interfaz
-* `SessionDataStore` clase
-* `InstanceDataStore` clase
-* `LocalStorageStore` clase
-
-:::callout
-### Compatibilidad hacia atrás
-
-Para facilitar la migración, el familiar `UserSession` & `AppConfig` la clase aún existe y es semi-compatible con versiones anteriores para el `8.x.x` lanzamiento.
-"Almacenará en caché" la dirección del usuario en el almacenamiento local y permitirá el acceso a ella a través del `loadUserData` método (como se hizo anteriormente).
-:::
-
-## Pasos de migración
-
-Para actualizar desde `<=7.x.x` a la última/`8.x.x`, sigue estos pasos:
-
-
-
- ```sh
- npm install @stacks/connect@latest
- ```
-
-
-
- Cambiar de `showXyz`, `openXyz`, `doXyz` métodos al `request` método:
-
- * `request` sigue el patrón `request(method: string, params: object)`, ver [Uso](#usage) para más detalles
- * `request` es una función asíncrona, así que reemplaza el `onFinish` y `onCancel` devoluciones de llamada con `.then().catch()` o `try & await`
-
- Ejemplos:
-
- * `showConnect()`, `authenticate()` → `connect()`
- * `useConnect().doContractCall({})` → `request("stx_callContract", {})`
- * `openContractDeploy()` → `request("stx_deployContract", {})`
-
-
-
- Cambiar de `showConnect` o `authenticate` a `connect()` métodos:
-
- * `connect()` es un alias para `request({forceWalletSelect: true}, 'getAddresses')`
- * `connect()` por defecto almacena en caché la dirección del usuario en el almacenamiento local
-
-
-
- * Cambiar de `UserSession.isSignedIn()` a `isConnected()`
- * Cambiar de `UserSession.signUserOut()` a `disconnect()`
-
-
-
- * Eliminar código que haga referencia a métodos obsoletos (`AppConfig`, `UserSession`, etc.)
- * Elimina el `@stacks/connect-react` paquete
- * Es posible que necesites recargar manualmente un componente para ver las actualizaciones del almacenamiento local
- * Ya no se necesitan hooks personalizados para usar Stacks Connect
- * Estamos trabajando en un nuevo `@stacks/react` paquete que hará que el uso sea aún más fácil en el futuro (por ejemplo, seguimiento del estado de las transacciones, recarga de componentes cuando se establece una conexión, actualización de la página cuando cambia la red, y más)
-
-
-
-## Acceso a Direcciones
-
-Anteriormente, el `UserSession` La clase se utilizaba para acceder a las direcciones y datos del usuario, lo cual abstraía los detalles de implementación subyacentes.
-Ahora, el `request` El método se utiliza para interactuar directamente con la billetera, dando a los desarrolladores un control más explícito y claridad sobre lo que está sucediendo internamente.
-Este enfoque manual hace que la interacción con la billetera sea más transparente y personalizable.
-Los desarrolladores pueden gestionar manualmente la dirección del usuario actualmente conectado en, por ejemplo, almacenamiento local, jotai, etc. o usar el `connect()`/`request()` método para almacenar en caché la dirección en el almacenamiento local.
-
-:::callout
-type: warn
-
-### Nota de seguridad
-
-Por razones de seguridad, el `8.x.x` release solo devuelve la dirección de la red actual (donde anteriormente se devolvían las direcciones tanto de mainnet como de testnet).
-:::
diff --git a/content/docs/es/reference/stacks.js/(connect)/wallet-support.mdx b/content/docs/es/reference/stacks.js/(connect)/wallet-support.mdx
deleted file mode 100644
index 0ef88a5d3..000000000
--- a/content/docs/es/reference/stacks.js/(connect)/wallet-support.mdx
+++ /dev/null
@@ -1,56 +0,0 @@
----
-title: Soporte de Billetera
-description: Información de compatibilidad para diferentes proveedores de billeteras
----
-Esta página proporciona información detallada sobre qué métodos y eventos son compatibles con diferentes proveedores de billeteras en el ecosistema de Stacks.
-
-## Compatibilidad de Métodos
-
-* 🔴 Sin soporte (aún)
-* 🟡 Soporte parcial
-* 🟢 Soportado
-
-| Método | Cuero | Tipo Xverse |
-|-----------------------------|----------------------------------------------|---------------------------------------------------------------|
-| `getAddresses` | 🟡 Sin soporte para fines experimentales | 🟡 Uso `wallet_connect` en su lugar |
-| `sendTransfer` | 🟡 Espera `amount` como cadena | 🟡 Espera `amount` como número |
-| `signPsbt` | 🟡 Usa solo el array de índices de firma | 🟡 Usa `signInputs` registro en lugar de matriz |
-| `stx_getAddresses` | 🟢 | 🔴 |
-| `stx_getAccounts` | 🔴 | 🟢 |
-| `stx_getNetworks` | 🔴 | 🔴 |
-| `stx_transferStx` | 🟢 | 🟢 |
-| `stx_transferSip10Ft` | 🟢 | 🔴 |
-| `stx_transferSip9Nft` | 🟢 | 🔴 |
-| `stx_callContract` | 🟡 Valores de Clarity codificados en hexadecimal solamente | 🟡 Valores de Clarity codificados en hexadecimal solamente, sin soporte para `postConditions` |
-| `stx_deployContract` | 🟡 Valores de Clarity codificados en hexadecimal solamente | 🟡 Valores de Clarity codificados en hexadecimal solamente, sin soporte para `postConditions` |
-| `stx_signTransaction` | 🟡 Valores de Clarity codificados en hexadecimal solamente | 🟡 Valores de Clarity codificados en hexadecimal solamente |
-| `stx_signMessage` | 🟡 Valores de Clarity codificados en hexadecimal solamente | 🟡 Valores de Clarity codificados en hexadecimal solamente |
-| `stx_signStructuredMessage` | 🟡 Valores de Clarity codificados en hexadecimal solamente | 🟡 Valores de Clarity codificados en hexadecimal solamente |
-| `stx_updateProfile` | 🔴 | 🔴 |
-
-## Compatibilidad de Eventos
-
-| Evento | Leather | Xverse |
-|---------------------|---------|--------|
-| `stx_accountChange` | 🔴 | 🔴 |
-| `stx_networkChange` | 🔴 | 🔴 |
-
-## Capa de Compatibilidad
-
-El `request` método en `@stacks/connect` agrega una capa de auto-compatibilidad para diferentes proveedores de billeteras. Esto ayuda a unificar la interfaz donde los proveedores de billeteras pueden implementar métodos y resultados de manera diferente.
-
-* 🟢 No se necesitan anulaciones para ninguna cartera
-* 🔵 Tiene anulaciones de compatibilidad que mantienen la funcionalidad
-* 🟡 Tiene anulaciones disruptivas que pueden perder cierta información
-
-| Método | Estado | Notas |
-| --------------------------- | ------ | ---------------------------------------------------------------------------------------------------- |
-| `getAddresses` | 🔵 | Se asigna a `wallet_connect` para billeteras tipo Xverse |
-| `sendTransfer` | 🔵 | Convierte `amount` para número en Xverse, cadena en Leather |
-| `signPsbt` | 🟡 | Transforma el formato PSBT para Leather (base64 a hex) con reestructuración con pérdidas de `signInputs` |
-| `stx_getAddresses` | 🔵 | Se asigna a `wallet_connect` para billeteras tipo Xverse |
-| `stx_callContract` | 🔵 | Transforma los valores de Clarity a formato codificado en hexadecimal para compatibilidad |
-| `stx_deployContract` | 🔵 | Transforma los valores de Clarity a formato codificado en hexadecimal para compatibilidad |
-| `stx_signTransaction` | 🔵 | Transforma los valores de Clarity a formato codificado en hexadecimal para compatibilidad |
-| `stx_signMessage` | 🔵 | Transforma los valores de Clarity a formato codificado en hexadecimal para compatibilidad |
-| `stx_signStructuredMessage` | 🔵 | Transforma los valores de Clarity a formato codificado en hexadecimal para compatibilidad |
diff --git a/content/docs/es/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx b/content/docs/es/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx
deleted file mode 100644
index bdcad9224..000000000
--- a/content/docs/es/reference/stacks.js/(integrations)/pyth-oracle-integration.mdx
+++ /dev/null
@@ -1,201 +0,0 @@
----
-title: Integración del oráculo Pyth
-sidebarTitle: Integración del oráculo Pyth
-description: En esta guía, aprenderás cómo integrar las fuentes de precios de Pyth Network en tu aplicación frontend utilizando Stacks.js.
-isNew: true
----
-import { File, Folder, Files } from 'fumadocs-ui/components/files';
-import { Steps, Step } from '@/components/steps';
-import { ArrowRight, Check } from 'lucide-react';
-
-## Lo que aprenderás
-
-:::objectives
-* Instalar y configurar el SDK de Pyth
-* Obtener mensajes VAA de la API de Hermes
-* Construir transacciones con datos de oráculo
-* Manejar las post-condiciones para las tarifas del oráculo
-:::
-
-## Requisitos previos
-
-:::prerequisites
-* Una aplicación de React o Node.js con Stacks.js instalado
-* Comprensión de [Contratos de oráculo Pyth](/resources/clarity/external-data)
-:::
-
-## Inicio rápido
-
-
-
- ### Instalar dependencias
-
- Instale el SDK de Pyth junto con sus paquetes existentes de Stacks.js:
-
- ```package-install
- @pythnetwork/price-service-client buffer
- ```
-
- El paquete buffer es necesario para la conversión de formato de datos en entornos de navegador.
-
-
-
- ### Configurar el cliente de Pyth
-
- Crear un servicio para manejar las interacciones del feed de precios de Pyth:
-
- ```typescript services/pyth.ts
- import { PriceServiceConnection } from '@pythnetwork/price-service-client';
- import { Buffer } from 'buffer';
-
- // Price feed IDs
- export const PRICE_FEEDS = {
- BTC_USD: '0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
- STX_USD: '0xec7a775f46379b5e943c3526b1c8d54cd49749176b0b98e02dde68d1bd335c17',
- ETH_USD: '0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace',
- USDC_USD: '0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a'
- };
-
- // Initialize Pyth client
- const pythClient = new PriceServiceConnection(
- 'https://hermes.pyth.network',
- {
- priceFeedRequestConfig: {
- binary: true // Request binary format for on-chain use
- }
- }
- );
-
- export async function fetchPriceUpdateVAA(priceFeedId: string): Promise {
- try {
- // Fetch the latest VAA for the price feed
- const vaas = await pythClient.getLatestVaas([priceFeedId]);
-
- if (!vaas || vaas.length === 0) {
- throw new Error('No VAA data received');
- }
-
- // Convert base64 to hex for Clarity
- const messageBuffer = Buffer.from(vaas[0], 'base64');
- const hexString = messageBuffer.toString('hex');
-
- return `0x${hexString}`;
- } catch (error) {
- console.error('Failed to fetch price VAA:', error);
- throw error;
- }
- }
- ```
-
-
-
- ### Construir transacciones habilitadas por oráculo
-
- Crear una transacción que incluya datos de precios actualizados:
-
- ```typescript components/PythTransaction.tsx
- import { request } from '@stacks/connect';
- import {
- Cl,
- PostConditionMode
- } from '@stacks/transactions';
- import { fetchPriceUpdateVAA, PRICE_FEEDS } from '../services/pyth';
- import { useState } from 'react';
-
- export function MintWithOraclePrice() {
- const [loading, setLoading] = useState(false);
-
- const handleMint = async () => {
- setLoading(true);
- try {
- // Fetch fresh price data
- const priceVAA = await fetchPriceUpdateVAA(PRICE_FEEDS.BTC_USD);
-
- // Convert hex string to buffer Clarity value
- const vaaBuffer = Cl.bufferFromHex(priceVAA.slice(2));
-
- // Call contract with price data using request
- const response = await request('stx_callContract', {
- contract: 'SP1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R.benjamin-club',
- functionName: 'mint-for-hundred-dollars',
- functionArgs: [vaaBuffer],
- postConditionMode: 'deny',
- network: 'mainnet'
- });
-
- console.log('Transaction submitted:', response.txid);
- alert(`NFT minted! Transaction ID: ${response.txid}`);
- } catch (error) {
- console.error('Minting failed:', error);
- alert('Failed to mint NFT');
- } finally {
- setLoading(false);
- }
- };
-
- return (
-
- );
- }
- ```
-
-
-
- ### Agregar post-condiciones para las tarifas del oráculo
-
- Las actualizaciones del oráculo de Pyth requieren una pequeña tarifa. Incluya condiciones posteriores al llamar a contratos:
-
- ```typescript components/MintWithPostConditions.tsx
- import { request } from '@stacks/connect';
- import { Cl, Pc } from '@stacks/transactions';
- import { fetchPriceUpdateVAA, PRICE_FEEDS } from '../services/pyth';
-
- export function MintWithPostConditions() {
- const handleMint = async () => {
- const userAddress = 'SP1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R';
-
- // Create post-conditions
- const postConditions = [
- // Oracle fee (1 uSTX)
- Pc.principal(userAddress).willSendLte(1).ustx(),
- // sBTC transfer for $100 worth (example: 100,000 sats)
- Pc.principal(userAddress)
- .willSendEq(100000)
- .ft('SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE.sbtc-token', 'sbtc')
- ];
-
- try {
- const priceVAA = await fetchPriceUpdateVAA(PRICE_FEEDS.BTC_USD);
-
- const response = await request('stx_callContract', {
- contract: `${userAddress}.benjamin-club`,
- functionName: 'mint-for-hundred-dollars',
- functionArgs: [Cl.bufferFromHex(priceVAA.slice(2))],
- postConditions,
- postConditionMode: 'deny',
- network: 'mainnet'
- });
-
- console.log('Transaction successful:', response.txid);
- } catch (error) {
- console.error('Transaction failed:', error);
- }
- };
-
- return ;
- }
- ```
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Contratos de Clarity](/resources/clarity/external-data): Aprende cómo integrar el oráculo Pyth con contratos de Clarity.
-* [Pruebas con Clarinet](/tools/clarinet/pyth-oracle-integration): Aprende cómo probar la integración del oráculo Pyth con Clarinet.
-:::
diff --git a/content/docs/es/reference/stacks.js/(integrations)/react-native-integration.mdx b/content/docs/es/reference/stacks.js/(integrations)/react-native-integration.mdx
deleted file mode 100644
index 706d0004d..000000000
--- a/content/docs/es/reference/stacks.js/(integrations)/react-native-integration.mdx
+++ /dev/null
@@ -1,292 +0,0 @@
----
-title: Uso de Stacks.js con React Native
-sidebarTitle: Integración de React Native
-description: Aprende cómo integrar la funcionalidad de la blockchain de Stacks en aplicaciones móviles de React Native
----
-Stacks.js puede integrarse en aplicaciones de React Native para llevar la funcionalidad de blockchain a dispositivos móviles. Este tutorial te guía a través de la configuración de un proyecto de React Native con Expo y su configuración para trabajar con las bibliotecas de Stacks.js.
-
-:::objectives
-* Configurar un proyecto Expo configurado para Stacks.js
-* Instalar y configurar los polyfills necesarios para React Native
-* Generar billeteras y firmar transacciones en una aplicación móvil
-* Manejar las limitaciones del entorno JavaScript de React Native
-* Construye una aplicación móvil funcional de Stacks
-:::
-
-:::prerequisites
-* Node.js y npm instalados en tu máquina de desarrollo
-* Conocimiento básico de React Native y Expo
-* Familiaridad con los conceptos de Stacks.js
-* Dispositivo o simulador iOS o Android para pruebas
-:::
-
-## Configurar el proyecto Expo
-
-Comience creando un nuevo proyecto de Expo. La última versión de Expo proporciona la mejor compatibilidad con los polyfills de Stacks.js.
-
-```terminal
-$ npx create-expo-app@latest my-stacks-app
-$ cd my-stacks-app
-```
-
-El proyecto de plantilla incluye todo lo necesario para comenzar a construir. Pruebe la configuración inicial ejecutando el servidor de desarrollo.
-
-```terminal
-$ npm start
-```
-
-Conecte su dispositivo móvil usando la aplicación Expo Go y escanee el código QR para verificar que el proyecto base funciona correctamente.
-
-## Instalar las dependencias necesarias
-
-El entorno JavaScript de React Native carece de ciertas APIs de Node.js y del navegador que Stacks.js requiere. Instale las bibliotecas principales de Stacks junto con los polyfills necesarios.
-
-```terminal
-$ npm install @stacks/transactions @stacks/wallet-sdk
-```
-
-Instale las dependencias del polyfill como dependencias de desarrollo para manejar las APIs faltantes.
-
-```terminal
-$ npm install --save-dev buffer process react-native-get-random-values \
- text-encoding readable-stream crypto-browserify @peculiar/webcrypto
-```
-
-Estos polyfills proporcionan:
-
-* `buffer` y `process` - Globales de Node.js
-* `react-native-get-random-values` - Valores aleatorios criptográficos
-* `text-encoding` - APIs de TextEncoder/TextDecoder
-* `crypto-browserify` y `@peculiar/webcrypto` - Funciones criptográficas
-
-## Configurar el empaquetador Metro
-
-El empaquetador Metro necesita configuración para resolver correctamente los módulos de Node.js. Cree un archivo de configuración personalizado de Metro.
-
-```terminal
-$ npx expo customize metro.config.js
-```
-
-Actualice la configuración para mapear los módulos de Node.js a sus versiones compatibles con React Native.
-
-```js metro.config.js
-const { getDefaultConfig } = require("expo/metro-config");
-
-const config = getDefaultConfig(__dirname);
-
-config.resolver.extraNodeModules = {
- stream: require.resolve("readable-stream"),
- crypto: require.resolve("crypto-browserify"),
-};
-
-module.exports = config;
-```
-
-Esta configuración garantiza que cuando Stacks.js solicita módulos de Node.js, Metro proporciona los polyfills adecuados.
-
-## Configurar polyfills globales
-
-Crear un sistema de polyfill para hacer que las APIs del navegador y Node.js estén disponibles en React Native. Esto requiere modificar el punto de entrada de la aplicación.
-
-### Crear el archivo polyfill
-
-Cree un nuevo archivo para inicializar todos los objetos globales requeridos.
-
-```js polyfill.js
-import { Buffer } from "buffer/";
-import process from "process";
-import "react-native-get-random-values";
-import { TextDecoder, TextEncoder } from "text-encoding";
-
-global.process = process;
-global.Buffer = Buffer;
-global.TextEncoder = TextEncoder;
-global.TextDecoder = TextDecoder;
-```
-
-### Crear punto de entrada personalizado
-
-Crear un nuevo punto de entrada que cargue polyfills antes de que la aplicación se inicie.
-
-```js index.js
-import "./polyfill";
-import { Crypto } from "@peculiar/webcrypto";
-
-Object.assign(global.crypto, new Crypto());
-
-import "expo-router/entry";
-```
-
-### Actualizar package.json
-
-Dirija la aplicación para que utilice el nuevo punto de entrada.
-
-```json package.json
-{
- "main": "index.js",
- // ... other configuration
-}
-```
-
-:::callout
-type: warn
-
-### Errores de inicialización en tiempo de ejecución
-
-Los polyfills deben cargarse en archivos separados como se muestra. Cargarlos en el mismo archivo puede causar errores de inicialización en tiempo de ejecución.
-:::
-
-## Implementar la funcionalidad de pilas
-
-Con el entorno configurado, ahora puede utilizar Stacks.js en sus componentes de React Native. Actualice la pantalla principal para demostrar la generación de billeteras y la firma de transacciones.
-
-### Importar módulos de Stacks.js
-
-Edite el componente de la pantalla principal para importar las funciones necesarias de Stacks.js.
-
-```tsx app/(tabs)/index.tsx
-import {
- TransactionVersion,
- getAddressFromPrivateKey,
- makeSTXTokenTransfer,
-} from "@stacks/transactions";
-import { Wallet, generateSecretKey, generateWallet } from "@stacks/wallet-sdk";
-import { useState } from "react";
-import { Button } from "react-native";
-```
-
-### Configurar el estado del componente
-
-Crear variables de estado para gestionar los datos de la cartera y la retroalimentación del usuario.
-
-```tsx app/(tabs)/index.tsx
-export default function HomeScreen() {
- const [mnemonic, setMnemonic] = useState("Press button to generate");
- const [wallet, setWallet] = useState(null);
- const [log, setLog] = useState("");
-
- // Component implementation continues...
-}
-```
-
-### Generar billetera y firmar transacción
-
-Implementar la funcionalidad principal para crear una billetera y firmar una transacción.
-
-```tsx app/(tabs)/index.tsx
-const generate = async () => {
- try {
- // Generate a new seed phrase
- const mnemonic = generateSecretKey();
- setMnemonic(mnemonic);
-
- // Create wallet from seed phrase
- const wallet = await generateWallet({
- secretKey: mnemonic,
- password: "",
- });
- setWallet(wallet);
-
- // Create and sign a transaction
- const txOptions = {
- amount: 1000,
- anchorMode: "any" as const,
- recipient: "SP3W993D3BRDYB284CY3SBFDEGTC5XEDJPDEA21CN",
- senderKey: wallet.accounts[0].stxPrivateKey,
- fee: 300,
- network: "testnet" as const,
- nonce: 0,
- };
-
- const transaction = await makeSTXTokenTransfer(txOptions);
- setLog("Transaction signed successfully ✓");
- } catch (error) {
- setLog(`Error: ${error.message}`);
- }
-};
-```
-
-### Construir la interfaz de usuario
-
-Crear una interfaz de usuario simple para mostrar información de la billetera y activar la generación de billeteras.
-
-```tsx app/(tabs)/index.tsx
-return (
-
- Stacks Wallet Demo
-
-
- Seed Phrase
- {mnemonic}
-
-
-
- {wallet && (
-
- Wallet Address
-
- {getAddressFromPrivateKey(
- wallet.accounts[0].stxPrivateKey,
- TransactionVersion.Testnet
- )}
-
-
- )}
-
- {log && (
-
- Status
- {log}
-
- )}
-
-);
-```
-
-## Prueba tu implementación
-
-Ejecute su aplicación para verificar que todo funcione correctamente.
-
-```terminal
-$ npm start
-```
-
-Cuando presionas "Generar Nueva Billetera":
-
-1. Una nueva frase semilla aparece
-2. La dirección de la billetera se muestra a continuación
-3. Una transacción es firmada (no transmitida)
-4. Mensaje de éxito confirma la firma
-
-:::callout
-type: tip
-
-### Almacenamiento seguro
-
-Para aplicaciones de producción, nunca muestre frases semilla directamente. Implemente almacenamiento seguro utilizando bibliotecas como `react-native-keychain` o `expo-secure-store`.
-:::
-
-## Pruébalo
-
-Amplíe la implementación básica con características adicionales.
-
-```tsx
-// Challenge: Add a function to check STX balance
-const checkBalance = async (address: string) => {
- // Implement balance checking
- // Hint: You'll need to use @stacks/blockchain-api-client
-};
-
-// Challenge: Implement transaction broadcasting
-const broadcastTransaction = async (transaction: StacksTransaction) => {
- // Implement broadcasting logic
- // Remember to handle network selection
-};
-```
-
-## Próximos pasos
-
-:::next-steps
-* [Paquete de transacciones](/reference/stacks.js/packages/transactions): Aprende sobre el paquete de transacciones.
-* [Paquete de red](/reference/stacks.js/packages/network): Aprende sobre las utilidades del paquete de red.
-:::
diff --git a/content/docs/es/reference/stacks.js/(local-accounts)/build-transactions.mdx b/content/docs/es/reference/stacks.js/(local-accounts)/build-transactions.mdx
deleted file mode 100644
index b234d6a43..000000000
--- a/content/docs/es/reference/stacks.js/(local-accounts)/build-transactions.mdx
+++ /dev/null
@@ -1,259 +0,0 @@
----
-title: Construyendo transacciones
-sidebarTitle: Construir transacciones
-description: Aprende cómo construir transacciones de forma programática para tener un control completo sobre las interacciones con la blockchain.
----
-:::objectives
-* Construir transacciones firmadas para transmisión inmediata
-* Crear transacciones sin firmar para flujos de trabajo de firma múltiple
-* Implementar transacciones patrocinadas para pagar tarifas por los usuarios
-:::
-
-## Tipos de transacciones
-
-Stacks admite cinco tipos principales de transacciones, cada uno con un propósito específico.
-
-```typescript
-// STX Transfer - Send native tokens
-const stxTransfer = await makeSTXTokenTransfer(options);
-
-// Contract Deployment - Deploy Clarity contracts
-const deployment = await makeContractDeploy(options);
-
-// Contract Call - Execute contract functions
-const contractCall = await makeContractCall(options);
-
-// Each transaction type accepts similar base options:
-interface TransactionOptions {
- senderKey: string; // Private key for signing
- network: string; // 'mainnet' or 'testnet'
- fee?: bigint; // Manual fee in microSTX
- nonce?: bigint; // Manual nonce
- anchorMode?: AnchorMode; // Block anchoring strategy
-}
-```
-
-## Construyendo transacciones firmadas
-
-Las transacciones firmadas están listas para transmitirse inmediatamente. La clave privada firma durante la creación.
-
-### Transferencia de tokens STX
-
-```typescript
-import { makeSTXTokenTransfer, broadcastTransaction } from '@stacks/transactions';
-
-const transaction = await makeSTXTokenTransfer({
- recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- amount: 1000000n, // 1 STX = 1,000,000 microSTX
- senderKey: 'your-private-key-hex',
- network: 'testnet',
- memo: 'Payment for services', // Optional memo (max 34 bytes)
-});
-
-const result = await broadcastTransaction({ transaction });
-console.log('Transaction ID:', result.txid);
-```
-
-### Implementación de contratos inteligentes
-
-```typescript
-import { makeContractDeploy, ClarityVersion } from '@stacks/transactions';
-
-const contractCode = `
-(define-public (say-hello)
- (ok "Hello, Stacks!"))
-`;
-
-const transaction = await makeContractDeploy({
- contractName: 'hello-world',
- codeBody: contractCode,
- senderKey: 'your-private-key-hex',
- network: 'testnet',
- clarityVersion: ClarityVersion.Clarity3,
-});
-
-const result = await broadcastTransaction({ transaction });
-```
-
-### Llamadas a funciones de contrato
-
-```typescript
-import { makeContractCall, Cl } from '@stacks/transactions';
-
-const transaction = await makeContractCall({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'counter',
- functionName: 'increment',
- functionArgs: [Cl.uint(1)],
- senderKey: 'your-private-key-hex',
- network: 'testnet',
-});
-```
-
-## Transacciones no firmadas
-
-Crear transacciones sin firmar para flujos de trabajo de firma múltiple o firma fuera de línea.
-
-```typescript
-import { makeUnsignedSTXTokenTransfer, TransactionSigner } from '@stacks/transactions';
-import { publicKeyFromPrivate } from '@stacks/encryption';
-
-// Create unsigned transaction
-const publicKey = publicKeyFromPrivate('your-private-key');
-
-const unsignedTx = await makeUnsignedSTXTokenTransfer({
- recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- amount: 1000000n,
- publicKey,
- network: 'testnet',
-});
-
-// Sign separately
-const signer = new TransactionSigner(unsignedTx);
-signer.signOrigin('your-private-key');
-
-const signedTx = signer.transaction;
-```
-
-## Transacciones patrocinadas
-
-Permita que una cuenta pague las tarifas de la transacción de otra cuenta.
-
-```typescript
-// User creates sponsored transaction
-const userTx = await makeContractCall({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'my-contract',
- functionName: 'transfer',
- functionArgs: [Cl.principal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG')],
- senderKey: 'user-private-key',
- sponsored: true,
- fee: 0n, // User doesn't pay
- network: 'testnet',
-});
-
-// Sponsor completes and pays
-import { sponsorTransaction } from '@stacks/transactions';
-
-const sponsoredTx = await sponsorTransaction({
- transaction: userTx,
- sponsorPrivateKey: 'sponsor-private-key',
- fee: 2000n, // Sponsor pays the fee
- network: 'testnet',
-});
-
-const result = await broadcastTransaction({ transaction: sponsoredTx });
-```
-
-## Transacciones de firma múltiple
-
-Requerir múltiples firmas para una seguridad mejorada.
-
-```typescript
-// Create multi-sig transaction (2-of-3)
-const publicKeys = [publicKey1, publicKey2, publicKey3];
-
-const multiSigTx = await makeUnsignedSTXTokenTransfer({
- recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- amount: 5000000n,
- numSignatures: 2, // Require 2 of 3
- publicKeys,
- network: 'testnet',
-});
-
-// Collect signatures
-const signer = new TransactionSigner(multiSigTx);
-signer.signOrigin(privateKey1); // First signature
-signer.appendOrigin(privateKey2); // Second signature
-
-const signedTx = signer.transaction;
-```
-
-## Trabajando con valores de Clarity
-
-Utilice el `Cl` ayudante para argumentos de contrato con seguridad de tipos.
-
-```typescript
-import { Cl } from '@stacks/transactions';
-
-const functionArgs = [
- // Primitives
- Cl.uint(42),
- Cl.int(-10),
- Cl.bool(true),
- Cl.stringUtf8('Hello 世界'),
- Cl.stringAscii('Hello World'),
-
- // Principals
- Cl.standardPrincipal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'),
- Cl.contractPrincipal('ST123...', 'my-contract'),
-
- // Composites
- Cl.list([Cl.uint(1), Cl.uint(2), Cl.uint(3)]),
- Cl.tuple({
- name: Cl.stringUtf8('Alice'),
- age: Cl.uint(30)
- }),
-
- // Optionals and responses
- Cl.some(Cl.uint(42)),
- Cl.none(),
- Cl.ok(Cl.uint(200)),
- Cl.err(Cl.uint(404))
-];
-```
-
-## Postcondiciones
-
-Agregar restricciones de seguridad para proteger a los usuarios de transferencias inesperadas.
-
-```typescript
-import { Pc, PostConditionMode } from '@stacks/transactions';
-
-const transaction = await makeContractCall({
- // ... other options
- postConditions: [
- // Sender must send exactly 1 STX
- Pc.principal('ST1ADDRESS...')
- .willSendEq(1000000n)
- .ustx(),
-
- // Contract must transfer tokens
- Pc.principal('ST2CONTRACT...')
- .willSendGte(100n)
- .ft('ST2CONTRACT.token-contract', 'my-token')
- ],
- postConditionMode: PostConditionMode.Deny, // Strict mode
-});
-```
-
-## Estimación de tarifas
-
-Obtenga estimaciones precisas de tarifas antes de transmitir.
-
-```typescript
-import { estimateFee } from '@stacks/transactions';
-
-// Build transaction first
-const tx = await makeSTXTokenTransfer({
- recipient: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- amount: 1000000n,
- senderKey: privateKey,
- network: 'testnet',
- fee: 1n, // Minimal fee for estimation
-});
-
-// Estimate appropriate fee
-const feeRate = await estimateFee(tx);
-tx.setFee(feeRate);
-
-// Now broadcast with accurate fee
-const result = await broadcastTransaction({ transaction: tx });
-```
-
-## Próximos pasos
-
-:::next-steps
-* [Llamadas de contrato](/reference/stacks.js/contract-calls): Aprende cómo llamar a funciones de contratos.
-* [Postcondiciones](/reference/stacks.js/post-conditions): Comprendiendo las post-condiciones.
-:::
diff --git a/content/docs/es/reference/stacks.js/(local-accounts)/contract-calls.mdx b/content/docs/es/reference/stacks.js/(local-accounts)/contract-calls.mdx
deleted file mode 100644
index 68c881139..000000000
--- a/content/docs/es/reference/stacks.js/(local-accounts)/contract-calls.mdx
+++ /dev/null
@@ -1,224 +0,0 @@
----
-title: Llamadas de contrato
-description: Ejecutar funciones de contratos inteligentes con transacciones
----
-Las llamadas de contrato te permiten ejecutar funciones que cambian el estado en contratos inteligentes. A diferencia de las llamadas de solo lectura, estas crean transacciones que deben ser firmadas y transmitidas a la red.
-
-## Llamada básica a contrato
-
-Ejecuta una función simple de contrato creando una transacción con los parámetros requeridos.
-
-```typescript
-import {
- makeContractCall,
- broadcastTransaction,
- AnchorMode
-} from '@stacks/transactions';
-
-async function callContract() {
- const txOptions = {
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'my-contract',
- functionName: 'transfer',
- functionArgs: [],
- senderKey: 'your-private-key',
- network: 'testnet',
- anchorMode: AnchorMode.Any,
- };
-
- const transaction = await makeContractCall(txOptions);
- const broadcastResponse = await broadcastTransaction({ transaction });
-
- console.log('Transaction ID:', broadcastResponse.txid);
-}
-```
-
-El `makeContractCall` La función crea una transacción que ejecutará la función especificada cuando se confirme en la cadena.
-
-## Pasando argumentos de función
-
-La mayoría de las funciones de contrato requieren argumentos. Utiliza los constructores de valores de Clarity para coincidir con los tipos de parámetros esperados.
-
-```typescript
-import {
- Cl,
- makeContractCall,
-} from '@stacks/transactions';
-
-const functionArgs = [
- Cl.principal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'), // recipient
- Cl.uint(1000000), // amount
- Cl.buffer(Buffer.from('Transfer memo', 'utf-8')), // memo
-];
-
-const txOptions = {
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'sip-010-token',
- functionName: 'transfer',
- functionArgs,
- senderKey: 'your-private-key',
- network: "testnet",
-};
-
-const transaction = await makeContractCall(txOptions);
-const result = await broadcastTransaction({ transaction });
-console.log('Transaction ID:', result.txid);
-```
-
-Cada tipo de Clarity tiene una función constructora correspondiente que garantiza la codificación adecuada para la blockchain.
-
-### Tipos de argumentos complejos
-
-```typescript
-// Tuple arguments
-const userInfo = Cl.tuple({
- name: Cl.string('Alice'),
- age: Cl.uint(30),
- active: Cl.bool(true),
-});
-
-// List arguments
-const addresses = Cl.list([
- Cl.principal('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'),
- Cl.principal('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'),
-]);
-
-```
-
-Los valores opcionales y de respuesta tienen constructores dedicados para una adecuada seguridad de tipos.
-
-```typescript
-// Optional values
-const optionalValue = Cl.some(Cl.uint(42)); // (some 42)
-const noValue = Cl.none(); // none
-
-// Response values
-const successResponse = Cl.ok(Cl.uint(100));
-const errorResponse = Cl.err(Cl.uint(404));
-```
-
-## Llamada de contrato con transferencia de STX
-
-Algunos contratos requieren que se envíen STX junto con la llamada a la función, como al acuñar NFTs o pagar por servicios.
-
-```typescript
-async function mintNFT() {
- const mintPrice = 1000000; // 1 STX
-
- const txOptions = {
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'nft-collection',
- functionName: 'mint',
- functionArgs: [],
- senderKey: 'your-private-key',
- network: new StacksTestnet(),
- anchorMode: AnchorMode.Any,
- // Attach STX to the contract call
- amount: mintPrice,
- };
-
- const transaction = await makeContractCall(txOptions);
- return broadcastTransaction(transaction, network);
-}
-```
-
-## Manejo de respuestas de contratos
-
-Procesar resultados de transacciones y respuestas de contratos:
-
-```typescript
-async function executeAndMonitor() {
- // Execute contract call
- const transaction = await makeContractCall({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'my-contract',
- functionName: 'process',
- functionArgs: [uintCV(100)],
- senderKey: 'your-private-key',
- network: new StacksTestnet(),
- anchorMode: AnchorMode.Any,
- });
-
- const broadcastResponse = await broadcastTransaction(transaction, network);
- const txId = broadcastResponse.txid;
-
- // Wait for confirmation
- const txInfo = await waitForConfirmation(txId, network);
-
- // Check transaction result
- if (txInfo.tx_status === 'success') {
- console.log('Contract returned:', txInfo.tx_result);
- // Parse the result based on expected return type
- } else {
- console.error('Transaction failed:', txInfo.tx_result);
- }
-}
-
-async function waitForConfirmation(txId: string, network: StacksNetwork) {
- let attempts = 0;
- const maxAttempts = 30;
-
- while (attempts < maxAttempts) {
- const response = await fetch(
- `${network.coreApiUrl}/extended/v1/tx/${txId}`
- );
- const txInfo = await response.json();
-
- if (txInfo.tx_status === 'success' || txInfo.tx_status === 'abort_by_response') {
- return txInfo;
- }
-
- await new Promise(resolve => setTimeout(resolve, 10000));
- attempts++;
- }
-
- throw new Error('Transaction confirmation timeout');
-}
-```
-
-## Interacciones de contrato de múltiples pasos
-
-Encadena múltiples llamadas a contratos:
-
-```typescript
-async function complexWorkflow() {
- // Step 1: Approve spending
- const approveTx = await makeContractCall({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'token',
- functionName: 'approve',
- functionArgs: [
- standardPrincipalCV('ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG'),
- uintCV(1000000),
- ],
- senderKey: 'your-private-key',
- network: new StacksTestnet(),
- anchorMode: AnchorMode.Any,
- });
-
- const approveResult = await broadcastTransaction(approveTx, network);
- await waitForConfirmation(approveResult.txid, network);
-
- // Step 2: Execute swap after approval
- const swapTx = await makeContractCall({
- contractAddress: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- contractName: 'dex',
- functionName: 'swap-tokens',
- functionArgs: [
- standardPrincipalCV('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'),
- uintCV(1000000),
- ],
- senderKey: 'your-private-key',
- network: new StacksTestnet(),
- anchorMode: AnchorMode.Any,
- });
-
- return broadcastTransaction(swapTx, network);
-}
-```
-
-## Lecturas adicionales
-
-* [Despliegue de contratos](/reference/stacks.js/contract-deployment)
-* [Llamadas de solo lectura](/reference/stacks.js/read-only-calls)
-* [Postcondiciones](/reference/stacks.js/post-conditions)
diff --git a/content/docs/es/reference/stacks.js/(local-accounts)/contract-deployment.mdx b/content/docs/es/reference/stacks.js/(local-accounts)/contract-deployment.mdx
deleted file mode 100644
index 4c0bcead2..000000000
--- a/content/docs/es/reference/stacks.js/(local-accounts)/contract-deployment.mdx
+++ /dev/null
@@ -1,44 +0,0 @@
----
-title: Despliegue de contratos
-description: Implementa contratos inteligentes en la cadena de bloques de Stacks
----
-## Visión general
-
-El despliegue de contratos crea nuevos contratos inteligentes en la blockchain. Stacks.js proporciona herramientas para compilar, desplegar y verificar contratos de Clarity de forma programática. Los despliegues pueden ser contratos individuales simples o sistemas complejos de múltiples contratos con dependencias.
-
-## Despliegue básico de contratos
-
-Despliegue un contrato inteligente simple:
-
-```typescript
-import {
- makeContractDeploy,
- broadcastTransaction,
- AnchorMode
-} from '@stacks/transactions';
-import { STACKS_TESTNET } from '@stacks/network';
-import { readFileSync } from 'fs';
-
-async function deployContract() {
- const network = new StacksTestnet();
-
- // Read contract source code
- const contractSource = readFileSync('./contracts/my-contract.clar', 'utf-8');
-
- const txOptions = {
- contractName: 'my-contract',
- codeBody: contractSource,
- senderKey: 'your-private-key',
- network,
- anchorMode: AnchorMode.Any,
- fee: 10000, // Higher fee for deployment
- };
-
- const transaction = await makeContractDeploy(txOptions);
- const broadcastResponse = await broadcastTransaction(transaction, network);
-
- console.log('Contract deployed!');
- console.log('Transaction ID:', broadcastResponse.txid);
- console.log('Contract address:', `${senderAddress}.${txOptions.contractName}`);
-}
-```
diff --git a/content/docs/es/reference/stacks.js/(local-accounts)/read-only-calls.mdx b/content/docs/es/reference/stacks.js/(local-accounts)/read-only-calls.mdx
deleted file mode 100644
index 74ec6cbb6..000000000
--- a/content/docs/es/reference/stacks.js/(local-accounts)/read-only-calls.mdx
+++ /dev/null
@@ -1,113 +0,0 @@
----
-title: Llamadas de solo lectura
-description: Consultar el estado del contrato inteligente sin crear transacciones
----
-Las llamadas a funciones de solo lectura te permiten consultar datos de contratos inteligentes sin crear una transacción. Estas llamadas son gratuitas, instantáneas y no requieren interacción con la billetera.
-
-## Llamada básica de solo lectura
-
-Llama a una función de solo lectura para obtener datos del contrato sin ninguna tarifa de transacción:
-
-```typescript
-import { fetchCallReadOnlyFunction, cvToValue } from '@stacks/transactions';
-
-const contractAddress = 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM';
-const contractName = 'my-contract';
-const functionName = 'get-balance';
-
-const response = await fetchCallReadOnlyFunction({
- contractAddress,
- contractName,
- functionName,
- functionArgs: [],
- senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
-});
-
-const balance = cvToValue(response);
-console.log('Balance:', balance);
-```
-
-## Pasando argumentos de función
-
-La mayoría de las funciones de solo lectura requieren argumentos. Utiliza los constructores de valores de Clarity para construir los tipos apropiados:
-
-```typescript
-import {
- fetchCallReadOnlyFunction,
- principalCV,
- uintCV,
- stringUtf8CV
-} from '@stacks/transactions';
-
-const functionArgs = [
- principalCV('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'),
- stringUtf8CV('admin')
-];
-
-const response = await fetchCallReadOnlyFunction({
- contractAddress: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
- contractName: 'access-control',
- functionName: 'has-role',
- functionArgs,
- senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
-});
-
-const hasRole = cvToValue(response);
-console.log('Has admin role:', hasRole);
-```
-
-## Manejo de tipos de respuesta
-
-Las funciones de solo lectura pueden devolver tipos de respuesta (ok/err). Verifica el tipo de respuesta para manejar tanto los casos de éxito como los de error:
-
-```typescript
-import {
- fetchCallReadOnlyFunction,
- cvToJSON,
- ResponseOkCV,
- ResponseErrorCV
-} from '@stacks/transactions';
-
-const response = await fetchCallReadOnlyFunction({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'sip-010-token',
- functionName: 'get-token-info',
- functionArgs: [],
- senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
-});
-
-if (response.type === 'ok') {
- const tokenInfo = cvToJSON(response.value);
- console.log('Token info:', tokenInfo);
- // {
- // name: "My Token",
- // symbol: "MTK",
- // decimals: 6,
- // totalSupply: "1000000000000"
- // }
-} else {
- console.error('Error:', cvToValue(response.value));
-}
-```
-
-## Uso de red personalizada
-
-Especifique una URL de red personalizada para conexiones de testnet o nodos personalizados:
-
-```typescript
-import { fetchCallReadOnlyFunction } from '@stacks/transactions';
-
-const response = await fetchCallReadOnlyFunction({
- contractAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- contractName: 'my-contract',
- functionName: 'get-data',
- functionArgs: [],
- senderAddress: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- network: 'testnet', // or custom URL like 'http://localhost:3999'
-});
-```
-
-## Lecturas adicionales
-
-* [Ejecutar funciones de contrato que cambian el estado](/reference/stacks.js/contract-calls)
-* [Trabajar con valores y tipos de Clarity](/reference/stacks.js/encoding-decoding)
diff --git a/content/docs/es/reference/stacks.js/(overview)/accounts-and-addresses.mdx b/content/docs/es/reference/stacks.js/(overview)/accounts-and-addresses.mdx
deleted file mode 100644
index 66c034d26..000000000
--- a/content/docs/es/reference/stacks.js/(overview)/accounts-and-addresses.mdx
+++ /dev/null
@@ -1,178 +0,0 @@
----
-title: Cuentas y direcciones
-description: Aprende cómo obtener una dirección a partir de una cuenta
----
-Stacks utiliza el concepto de una "cuenta" para representar la identidad de un usuario en la blockchain. Una cuenta se identifica mediante una dirección única derivada de la clave pública de la cuenta.
-
-## Formatos de dirección
-
-Las direcciones de Stacks utilizan diferentes prefijos para indicar la red a la que pertenecen, lo que facilita distinguir entre direcciones de mainnet y testnet.
-
-```typescript
-// Mainnet address starts with 'SP'
-const mainnetAddress = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
-
-// Testnet address starts with 'ST'
-const testnetAddress = 'ST2F4BK4GZH6YFBNHYDDGN4T1RKBA7DA1BJZPJEJJ';
-```
-
-El formato de dirección garantiza que los tokens en la red de pruebas no puedan enviarse accidentalmente a direcciones de la red principal y viceversa.
-
-## Obtener una dirección
-
-Existen varias formas de obtener una dirección de Stacks dependiendo de tu caso de uso y del material criptográfico que tengas disponible.
-
-### Uso de Stacks Connect
-
-Al crear aplicaciones orientadas al usuario, normalmente obtendrás direcciones de usuarios que conectan sus billeteras a través de Stacks Connect.
-
-```tsx
-import { connect, getLocalStorage, request } from '@stacks/connect';
-
-async function handleWalletConnection() {
- // Connect to wallet
- const response = await connect();
-
- // Get stored addresses
- const data = getLocalStorage();
- const stxAddresses = data.addresses.stx;
-
- if (stxAddresses && stxAddresses.length > 0) {
- const address = stxAddresses[0].address;
- console.log('STX Address:', address);
- // 'SP1MXSZF4NFC8JQ1TTYGEC2WADMC7Y3GHVZYRX6RF'
- }
-
- // Get detailed account info if needed
- const accounts = await request('stx_getAccounts');
- console.log('Account details:', accounts.addresses[0]);
-}
-```
-
-Stacks Connect almacena las direcciones conectadas en el almacenamiento local, permitiendo que tu aplicación mantenga la conexión a través de recargas de página.
-
-### Uso de una frase semilla
-
-Para la generación programática de billeteras o al restaurar cuentas desde una copia de seguridad, puedes derivar direcciones a partir de una frase semilla (también conocida como mnemotécnica).
-
-```typescript
-import { generateWallet, generateSecretKey } from '@stacks/wallet-sdk';
-
-async function createWalletFromSeed() {
- // Generate a new 24-word seed phrase
- const secretKey = generateSecretKey();
-
- // Or use an existing seed phrase
- // const secretKey = 'already owned seed phrase ...';
-
- const wallet = await generateWallet({
- secretKey,
- password: 'optional-encryption-password',
- });
-
- // Get the first account's address
- const account = wallet.accounts[0];
- const mainnetAddress = account.address;
-
- console.log('Address:', mainnetAddress);
- console.log('Private key:', account.stxPrivateKey);
-}
-```
-
-Cada billetera puede contener múltiples cuentas, todas derivadas de la misma frase semilla utilizando diferentes rutas de derivación.
-
-### Uso de una clave privada
-
-Si ya tienes una clave privada, puedes derivar directamente la dirección correspondiente sin pasar por el proceso de generación de billetera.
-
-```typescript
-import { privateKeyToAddress, TransactionVersion } from '@stacks/transactions';
-
-function getAddressFromPrivateKey() {
- // Compressed private key (64 or 66 characters)
- const privateKey = 'your-private-key-here';
-
- // For mainnet
- const mainnetAddress = privateKeyToAddress(
- privateKey,
- TransactionVersion.Mainnet
- );
-
- // For testnet
- const testnetAddress = privateKeyToAddress(
- privateKey,
- TransactionVersion.Testnet
- );
-
- console.log('Mainnet:', mainnetAddress);
- console.log('Testnet:', testnetAddress);
-}
-```
-
-La misma clave privada generará diferentes direcciones para la red principal y la red de pruebas debido a los bytes de versión específicos de cada red.
-
-### Uso de una clave pública
-
-Cuando solo tienes acceso a una clave pública (por ejemplo, en un escenario de billetera de solo visualización), aún puedes derivar la dirección correspondiente.
-
-```typescript
-import { publicKeyToAddress, TransactionVersion } from '@stacks/transactions';
-
-function getAddressFromPublicKey() {
- // Compressed public key (66 characters starting with 02 or 03)
- const publicKey = '03b3e0a76b292b2c83fc0ac14ae6160d0438ebe94e14bbb7d0ded3c217f3d29ba7';
-
- // For mainnet
- const mainnetAddress = publicKeyToAddress(
- publicKey,
- TransactionVersion.Mainnet
- );
-
- // For testnet
- const testnetAddress = publicKeyToAddress(
- publicKey,
- TransactionVersion.Testnet
- );
-
- console.log('Mainnet:', mainnetAddress);
- // 'SP1MXSZF4NFC8JQ1TTYGEC2WADMC7Y3GHVZYRX6RF'
-}
-```
-
-Esto es útil para crear billeteras de solo visualización o verificar direcciones sin acceso a las claves privadas.
-
-## Validación de dirección
-
-Antes de enviar transacciones, es importante validar que las direcciones estén correctamente formateadas.
-
-```typescript
-import { validateStacksAddress } from '@stacks/transactions';
-
-function isValidAddress(address: string): boolean {
- try {
- // Check if it's a valid mainnet address
- if (address.startsWith('SP')) {
- return validateStacksAddress(address);
- }
-
- // Check if it's a valid testnet address
- if (address.startsWith('ST')) {
- return validateStacksAddress(address);
- }
-
- return false;
- } catch (error) {
- return false;
- }
-}
-
-// Examples
-console.log(isValidAddress('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159')); // true
-console.log(isValidAddress('invalid-address')); // false
-```
-
-Siempre verifique las direcciones antes de usarlas en transacciones para evitar la pérdida de fondos debido a errores tipográficos o de formato.
-
-## Lecturas adicionales
-
-* [Conectar billetera](/reference/stacks.js/connect-wallet)
diff --git a/content/docs/es/reference/stacks.js/(overview)/networks.mdx b/content/docs/es/reference/stacks.js/(overview)/networks.mdx
deleted file mode 100644
index ebeb71d17..000000000
--- a/content/docs/es/reference/stacks.js/(overview)/networks.mdx
+++ /dev/null
@@ -1,53 +0,0 @@
----
-title: Redes
-description: Aprende a utilizar diferentes redes.
----
-import { Star } from 'lucide-react';
-
-Típicamente, hablamos de `mainnet` y `testnet` como las redes de Stacks.
-La mayoría de las billeteras están configuradas para `mainnet` por defecto—este es el entorno de producción, la blockchain real que contiene tokens STX reales.
-
-Como su nombre indica, `testnet` es una red pública para pruebas.
-Es un estado de blockchain separado que contiene tokens de prueba, los cuales no tienen valor.
-
-Por completitud también mencionamos `devnet`.
-Esto no es "una" red, sino cómo los desarrolladores se refieren a redes locales efímeras utilizadas para pruebas.
-Es lo mismo que `testnet`, pero para desarrollo local.
-[Más información](/tools/clarinet/local-blockchain-development).
-
-## Configurando la red
-
-La mayoría de las funciones de Stacks.js aceptan un `network` parámetro o un último argumento opcional.
-
-El `network` type es una cadena de texto y puede ser uno de los siguientes:
-
-* `'mainnet'` (predeterminado)
-* `'testnet'`
-* `'devnet'`
-* `'mocknet'` (alias de `devnet`)
-
-### Ejemplos
-
-Red en la firma de transacciones:
-
-```ts
-const tx = makeSTXTokenTransfer({
- // ...
- network: 'testnet',
-});
-```
-
-Red en la derivación de direcciones:
-
-```ts
-const address = privateKeyToAddress(privateKey, 'devnet');
-// ST3NBRSFKX28FQ2ZJ1MAKX58HKHSDGNV5N7R21XCP
-```
-
-:::callout
-type: tip
-
-### Uso avanzado
-
-Para usos más avanzados, puedes pasar un objeto de configuración de red. Lee más sobre el objeto de red en el [`@stacks/network`](/reference/stacks.js/packages/network) paquete.
-:::
diff --git a/content/docs/es/reference/stacks.js/(overview)/private-keys.mdx b/content/docs/es/reference/stacks.js/(overview)/private-keys.mdx
deleted file mode 100644
index b4809b786..000000000
--- a/content/docs/es/reference/stacks.js/(overview)/private-keys.mdx
+++ /dev/null
@@ -1,178 +0,0 @@
----
-title: Claves privadas
-description: Aprende cómo gestionar claves privadas con Stacks.js
----
-Las aplicaciones de Stacks pueden funcionar con dos tipos diferentes de cuentas: billeteras web (como Hiro Wallet o Xverse) que los usuarios controlan, o cuentas locales de las que gestionas directamente las claves privadas.
-
-## Monederos web (controlados por el usuario)
-
-La mayoría de los usuarios interactúan con las aplicaciones de Stacks a través de billeteras web, donde la billetera maneja toda la gestión de claves privadas y la firma de transacciones.
-
-```typescript
-import { connect } from '@stacks/connect';
-
-// Users connect their wallet
-const response = await connect();
-console.log('Connected addresses:', response.addresses);
-
-// The wallet handles all cryptographic operations
-// when signing transactions or messages
-```
-
-Utilice billeteras web al crear aplicaciones orientadas al usuario donde los usuarios deben mantener el control de sus claves.
-
-## Cuentas locales (controladas por la aplicación)
-
-Las cuentas locales otorgan a tu aplicación control directo sobre las claves privadas, permitiendo la firma programática de transacciones sin interacción del usuario.
-
-```typescript
-import { makeSTXTokenTransfer } from '@stacks/transactions';
-
-// Your application controls the private key
-const privateKey = 'your-private-key-here';
-
-const txOptions = {
- recipient: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- amount: 1000000n,
- senderKey: privateKey, // Direct private key usage
- network: 'testnet',
-};
-
-const transaction = await makeSTXTokenTransfer(txOptions);
-// Transaction is signed programmatically
-```
-
-Utilice cuentas locales para servicios backend, sistemas automatizados o herramientas de desarrollo que necesiten firmar transacciones sin interacción del usuario.
-
-## Trabajando con claves privadas
-
-Al crear aplicaciones que utilizan cuentas locales, necesitarás generar y gestionar claves privadas de forma segura.
-
-### Generando claves privadas aleatorias
-
-Crea una nueva clave privada para uso único o con fines de prueba.
-
-```typescript
-import { randomPrivateKey } from '@stacks/transactions';
-
-function generateNewAccount() {
- const privateKey = randomPrivateKey();
- console.log('Private key:', privateKey);
- // 'f5a31c1268a1e37d4edaa05c7d11183c5fbf...'
-
- // IMPORTANT: Store this securely!
- // Anyone with this key can control the account
- return privateKey;
-}
-```
-
-Las claves privadas en Stacks son números de 256 bits, generalmente representados como cadenas hexadecimales de 64 caracteres.
-
-## Formatos de clave privada
-
-Stacks.js admite múltiples formatos de clave privada para diferentes casos de uso.
-
-```typescript
-import { PrivateKey } from '@stacks/transactions';
-
-// Hex string format (most common)
-const hexKey = 'f5a31c1268a1e37d4edaa05c7d11183c5fbf...';
-
-// Compressed format with suffix
-const compressedKey = 'f5a31c1268a1e37d4edaa05c7d11183c5fbf...01';
-
-// Create from raw bytes
-const bytes = new Uint8Array(32); // 32 bytes = 256 bits
-crypto.getRandomValues(bytes);
-const privateKeyFromBytes = PrivateKey.fromBytes(bytes);
-```
-
-El formato comprimido incluye un byte de sufijo (01) que indica que la clave debe usar codificación de clave pública comprimida.
-
-## Generación de billetera con frases semilla
-
-Para una mejor seguridad y recuperabilidad, utiliza carteras determinísticas jerárquicas (HD) basadas en frases semilla.
-
-### Generar una frase semilla
-
-Crea una nueva frase semilla mnemónica de 24 palabras que pueda regenerar todas las cuentas de la billetera.
-
-```typescript
-import { generateSecretKey } from '@stacks/wallet-sdk';
-
-function createNewWallet() {
- const secretKey = generateSecretKey();
- console.log('Seed phrase:', secretKey);
- // "warrior volume sport ... figure cake since"
-
- // Users should write this down and store it securely
- // This phrase can regenerate all accounts in the wallet
- return secretKey;
-}
-```
-
-Las frases semilla proporcionan una copia de seguridad legible por humanos que puede restaurar toda una jerarquía de billeteras.
-
-### Crear billetera a partir de frase semilla
-
-Generar una estructura completa de billetera a partir de una frase semilla, incluyendo múltiples cuentas.
-
-```typescript
-import { generateWallet, generateSecretKey } from '@stacks/wallet-sdk';
-
-async function setupWallet() {
- // Use existing seed phrase or generate new one
- const seedPhrase = generateSecretKey();
-
- const wallet = await generateWallet({
- secretKey: seedPhrase,
- password: 'optional-encryption-password',
- });
-
- // Access the first account
- const account = wallet.accounts[0];
- console.log('STX address:', account.address);
- console.log('STX private key:', account.stxPrivateKey);
- console.log('Data private key:', account.dataPrivateKey);
-
- return wallet;
-}
-```
-
-Cada billetera puede contener múltiples cuentas, todas derivadas de la misma frase semilla pero con diferentes claves privadas.
-
-### Administración de múltiples cuentas
-
-Las billeteras HD admiten múltiples cuentas a partir de una sola frase semilla, útil para organizar fondos o separar asuntos.
-
-```typescript
-import { generateNewAccount, generateWallet, generateSecretKey } from '@stacks/wallet-sdk';
-
-async function createMultipleAccounts() {
- const seedPhrase = generateSecretKey();
-
- let wallet = await generateWallet({
- secretKey: seedPhrase,
- password: 'my-password',
- });
-
- console.log('Accounts:', wallet.accounts.length); // 1 (default)
-
- // Add more accounts
- wallet = generateNewAccount(wallet);
- wallet = generateNewAccount(wallet);
-
- console.log('Accounts:', wallet.accounts.length); // 3
-
- // Each account has its own keys and address
- wallet.accounts.forEach((account, index) => {
- console.log(`Account ${index}:`, account.address);
- });
-}
-```
-
-Todas las cuentas pueden regenerarse a partir de la frase semilla original, lo que simplifica la copia de seguridad mientras se mantienen direcciones separadas.
-
-## Lecturas adicionales
-
-* [Conectar con Stacks](/reference/stacks.js/connect-wallet) - Creando aplicaciones con billeteras web
diff --git a/content/docs/es/reference/stacks.js/(post-conditions)/implementing-post-conditions.mdx b/content/docs/es/reference/stacks.js/(post-conditions)/implementing-post-conditions.mdx
deleted file mode 100644
index afdfd955f..000000000
--- a/content/docs/es/reference/stacks.js/(post-conditions)/implementing-post-conditions.mdx
+++ /dev/null
@@ -1,246 +0,0 @@
----
-title: Implementando post-condiciones
-sidebarTitle: Implementar post-condiciones
-description: Aprende cómo agregar post-condiciones para proteger tus transacciones de Stacks
----
-Las post-condiciones son una poderosa característica de seguridad en Stacks que protege a los usuarios de resultados inesperados en las transacciones. Este tutorial te guiará a través de la implementación de post-condiciones en tus aplicaciones para garantizar que las transacciones se comporten exactamente como los usuarios esperan.
-
-## Lo que aprenderás
-
-:::objectives
-* Construir post-condiciones utilizando la API auxiliar Pc
-* Agregar post-condiciones a diferentes tipos de transacciones
-* Configurar modos de post-condición para la seguridad de las transacciones
-* Implementar post-condiciones para STX, tokens fungibles y NFTs
-* Manejar tokens semi-fungibles (SFTs) con post-condiciones
-:::
-
-## Requisitos previos
-
-:::prerequisites
-* Comprensión básica de las transacciones de Stacks
-* Biblioteca Stacks.js instalada (`npm install @stacks/transactions`)
-* Un entorno de desarrollo configurado para Stacks
-:::
-
-## Construyendo post-condiciones
-
-El ayudante Pc en Stacks.js proporciona una API fluida inspirada en BDD para construir post-condiciones. Comienza con `Pc.principal()` para especificar qué dirección será verificada, luego encadene métodos para definir la condición.
-
-```ts
-import { Pc } from '@stacks/transactions';
-
-// Basic structure of a post-condition
-const postCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendEq(1000)
- .ustx();
-```
-
-El ayudante de PC utiliza encadenamiento de métodos para una construcción intuitiva de condiciones. Su IDE proporcionará autocompletado para los métodos disponibles en cada paso.
-
-## Métodos de transferencia disponibles
-
-Las post-condiciones admiten diferentes operadores de comparación y tipos de activos. Elija el método apropiado según sus requisitos de seguridad.
-
-### Métodos de STX y tokens fungibles
-
-```ts
-// Exact amount
-Pc.principal(address).willSendEq(1000).ustx();
-
-// Greater than or equal
-Pc.principal(address).willSendGte(500).ustx();
-
-// Less than
-Pc.principal(address).willSendLt(2000).ustx();
-```
-
-Métodos de comparación disponibles:
-
-* `.willSendEq(amount)` - Exactamente igual al monto
-* `.willSendGte(amount)` - Mayor o igual que la cantidad
-* `.willSendGt(amount)` - Mayor que la cantidad
-* `.willSendLte(amount)` - Menor o igual a la cantidad
-* `.willSendLt(amount)` - Menos que la cantidad
-
-### Métodos de tipos de activos
-
-```ts
-// STX transfers
-.ustx()
-
-// Fungible token transfers
-.ft(contractAddress, tokenName)
-
-// NFT transfers
-.nft(assetIdentifier, tokenId)
-```
-
-### Métodos específicos de NFT
-
-```ts
-// Ensure NFT is sent
-Pc.principal(address).willSendAsset().nft(...);
-
-// Ensure NFT is NOT sent
-Pc.principal(address).willNotSendAsset().nft(...);
-```
-
-## Configuración del modo de post-condición
-
-El modo de post-condición determina cómo la blockchain de Stacks maneja las transferencias de activos no cubiertas explícitamente por sus post-condiciones. Esta es una configuración de seguridad crítica.
-
-```ts
-import { PostConditionMode, makeContractCall } from '@stacks/transactions';
-
-const tx = await makeContractCall({
- // ... other transaction properties
- postConditionMode: PostConditionMode.Deny, // Recommended default
- postConditions: [
- // your post-conditions here
- ],
-});
-```
-
-Opciones de modo:
-
-* **`PostConditionMode.Deny`** (default): La transacción falla si ocurre alguna transferencia no especificada
-* **`PostConditionMode.Allow`**: La transacción permite transferencias más allá de las condiciones posteriores especificadas
-
-## Patrones de implementación comunes
-
-### Condiciones posteriores a la transferencia de STX
-
-Proteja las transferencias de STX especificando cantidades exactas o rangos.
-
-```ts
-import { Pc, makeSTXTokenTransfer } from '@stacks/transactions';
-
-// Exact amount post-condition
-const exactAmountCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendEq(1000)
- .ustx();
-
-// Use in a transaction
-const tx = await makeSTXTokenTransfer({
- recipient: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- amount: 1000,
- postConditions: [exactAmountCondition],
- postConditionMode: PostConditionMode.Deny,
- // ... other properties
-});
-```
-
-### Condiciones posteriores de tokens fungibles
-
-Asegúrese de que los tokens fungibles se transfieran según lo esperado en las llamadas de contrato.
-
-```ts
-import { Pc, makeContractCall } from '@stacks/transactions';
-
-// Minimum amount condition
-const ftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendGte(500)
- .ft('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.token-ft', 'token');
-
-// Use in a contract call
-const tx = await makeContractCall({
- contractAddress: 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6',
- contractName: 'token-transfer',
- functionName: 'transfer',
- functionArgs: [
- // ... function arguments
- ],
- postConditions: [ftCondition],
- // ... other properties
-});
-```
-
-### Condiciones posteriores a la transferencia de NFT
-
-Controla los cambios de propiedad de NFT con condiciones posteriores específicas.
-
-```ts
-import { Pc, Cl } from '@stacks/transactions';
-
-// Ensure NFT is sent
-const sendNftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendAsset()
- .nft('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.nft-contract::nft-name', Cl.uint(1));
-
-// Ensure NFT is NOT sent (protection against unwanted transfers)
-const keepNftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willNotSendAsset()
- .nft('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.nft-contract::nft-name', Cl.uint(1));
-```
-
-Usar `willNotSendAsset()` para proteger valiosos NFTs de ser transferidos inesperadamente.
-
-### Condiciones posteriores de token semi-fungible (SFT)
-
-Los SFT requieren un manejo especial ya que tienen propiedades tanto fungibles como no fungibles.
-
-```ts
-import { Cl, Pc } from '@stacks/transactions';
-
-// SFT as NFT (specific token ID)
-const sftNftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendAsset()
- .nft(
- 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.sft-contract::sft-id',
- Cl.tuple({
- 'token-id': Cl.uint(1),
- owner: Cl.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- })
- );
-
-// SFT as FT (amount-based)
-const sftFtCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendEq(500)
- .ft('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.sft-contract', 'sft-token');
-```
-
-## Múltiples post-condiciones
-
-Las transacciones complejas a menudo requieren múltiples condiciones posteriores para proteger completamente todas las transferencias de activos.
-
-```ts
-const tx = await makeContractCall({
- // ... transaction properties
- postConditions: [
- // Sender must send exactly 1000 uSTX
- Pc.principal(senderAddress).willSendEq(1000).ustx(),
-
- // Contract must send at least 100 tokens to user
- Pc.principal(contractAddress).willSendGte(100)
- .ft(contractAddress + '.my-token', 'my-token'),
-
- // User must not lose their NFT
- Pc.principal(senderAddress).willNotSendAsset()
- .nft(nftContract + '::my-nft', Cl.uint(1)),
- ],
- postConditionMode: PostConditionMode.Deny,
-});
-```
-
-:::callout
-type: tip
-
-### Pruébalo
-
-Explora el [Plantilla de post-condiciones](https://platform.hiro.so) para ejemplos interactivos.
-:::
-
-## Próximos pasos
-
-:::next-steps
-* [Llamada de contrato](/reference/stacks.js/contract-calls): Aprende cómo llamar contratos en Stacks
-* [Transmisión de transacciones](/reference/stacks.js/broadcast-transactions): Aprende cómo transmitir transacciones protegidas
-:::
diff --git a/content/docs/es/reference/stacks.js/(post-conditions)/post-conditions.mdx b/content/docs/es/reference/stacks.js/(post-conditions)/post-conditions.mdx
deleted file mode 100644
index 93b853a7d..000000000
--- a/content/docs/es/reference/stacks.js/(post-conditions)/post-conditions.mdx
+++ /dev/null
@@ -1,131 +0,0 @@
----
-title: Introducción
-sidebarTitle: Introducción
-description: Aprende cómo las post-condiciones protegen a los usuarios de resultados inesperados en las transacciones
----
-Las post-condiciones son características de seguridad en Stacks que protegen a los usuarios al garantizar que las transacciones se ejecuten exactamente como se espera. Verifican que se produzcan transferencias específicas de activos durante una transacción, y si las condiciones no se cumplen, toda la transacción falla sin cambios de estado.
-
-## ¿Qué son las post-condiciones?
-
-Las post-condiciones actúan como salvaguardias que verifican que las transferencias de activos coincidan con tus expectativas. Pueden comprobar transferencias de STX, tokens fungibles y cambios de propiedad de tokens no fungibles.
-
-```ts
-import { Pc } from '@stacks/transactions';
-
-const tx = await makeContractCall({
- // ...
- postConditions: [
- Pc.principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6').willSendEq(1000).ustx(),
- ],
-});
-```
-
-Las post-condiciones solo verifican que los activos sean enviados, no recibidos. No pueden garantizar el destinatario final de los tokens.
-
-## Uso del asistente de PC
-
-El `Pc` helper proporciona una API fluida para crear post-condiciones con mejor seguridad de tipos y legibilidad.
-
-```ts
-import { Pc } from '@stacks/transactions';
-
-// STX transfer post-condition
-const stxCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendGte(1000)
- .ustx();
-
-// Fungible token post-condition
-const ftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendEq(50)
- .ft('SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-token', 'my-token');
-
-// NFT post-condition
-const nftCondition = Pc
- .principal('STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6')
- .willSendAsset()
- .nft('SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-nft::my-asset', Cl.uint(1));
-```
-
-## Creación manual
-
-Cree post-condiciones manualmente utilizando definiciones de tipo al construir condiciones dinámicamente.
-
-```ts
-import {
- StxPostCondition,
- FungiblePostCondition,
- NonFungiblePostCondition
-} from '@stacks/transactions';
-
-// STX post-condition
-const stxPostCondition: StxPostCondition = {
- type: 'stx-postcondition',
- address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
- condition: 'gte', // 'eq' | 'gt' | 'gte' | 'lt' | 'lte'
- amount: '100',
-};
-```
-
-Tipos de condiciones disponibles:
-
-* `eq`: Exactamente igual a la cantidad
-* `gt`: Mayor que cantidad
-* `gte`: Mayor o igual que cantidad
-* `lt`: Menos que cantidad
-* `lte`: Menor o igual que la cantidad
-
-### Tokens fungibles
-
-```ts
-const ftPostCondition: FungiblePostCondition = {
- type: 'ft-postcondition',
- address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
- condition: 'eq',
- amount: '100',
- asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-ft-token::my-token',
-};
-```
-
-### Tokens no fungibles
-
-```ts
-const nftPostCondition: NonFungiblePostCondition = {
- type: 'nft-postcondition',
- address: 'SP2JXKMSH007NPYAQHKJPQMAQYAD90NQGTVJVQ02B',
- condition: 'sent', // 'sent' | 'not-sent'
- asset: 'SP3D6PV2ACBPEKYJTCMH7HEN02KP87QSP8KTEH335.my-nft::my-asset',
- assetId: Cl.uint(602),
-};
-```
-
-## Modo de post-condición
-
-Controla cómo se manejan las transferencias de activos no especificadas con el modo de post-condición.
-
-```ts
-import { PostConditionMode } from '@stacks/transactions';
-
-const tx = await makeContractCall({
- // ...
- postConditionMode: PostConditionMode.Deny,
- postConditions: [
- // your conditions
- ],
-});
-```
-
-:::callout
-type: warn
-
-### Modo de post-condición
-
-Siempre usa `Deny` modo a menos que tenga una razón específica para permitir transferencias adicionales. Esto proporciona la máxima seguridad para los usuarios.
-:::
-
-## Lecturas adicionales
-
-* [Implementando post-condiciones](/reference/stacks.js/implementing-post-conditions)
-* [Construcción de transacciones](/reference/stacks.js/build-transactions)
-* [Llamadas de contrato](/reference/stacks.js/contract-calls)
diff --git a/content/docs/es/reference/stacks.js/(utils)/address-validation.mdx b/content/docs/es/reference/stacks.js/(utils)/address-validation.mdx
deleted file mode 100644
index 94323b358..000000000
--- a/content/docs/es/reference/stacks.js/(utils)/address-validation.mdx
+++ /dev/null
@@ -1,561 +0,0 @@
----
-title: Validación de direcciones
-description: Validar y formatear direcciones y principales de Stacks
----
-## Visión general
-
-Las direcciones de Stacks siguen formatos específicos que difieren entre la red principal y la red de pruebas. Una validación adecuada garantiza que tu aplicación maneje correctamente las direcciones, evitando la pérdida de fondos y mejorando la experiencia del usuario. Esta guía cubre la validación de direcciones, el formateo y las utilidades de conversión.
-
-## Validación básica de direcciones
-
-Validar direcciones de Stacks:
-
-```typescript
-import {
- validateStacksAddress,
- validateContractName
-} from '@stacks/transactions';
-
-// Validate standard addresses
-const isValidMainnet = validateStacksAddress('SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY');
-console.log('Valid mainnet:', isValidMainnet); // true
-
-const isValidTestnet = validateStacksAddress('ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC');
-console.log('Valid testnet:', isValidTestnet); // true
-
-const isInvalid = validateStacksAddress('invalid-address');
-console.log('Valid:', isInvalid); // false
-
-// Validate contract names
-const validContract = validateContractName('my-contract');
-console.log('Valid contract name:', validContract); // true
-
-const invalidContract = validateContractName('My Contract!');
-console.log('Valid contract name:', invalidContract); // false
-```
-
-## Tipos de direcciones y detección
-
-Identificar tipos de direcciones y redes:
-
-```typescript
-import {
- getAddressFromPrivateKey,
- getAddressFromPublicKey,
- TransactionVersion
-} from '@stacks/transactions';
-
-// Detect address type from prefix
-function getAddressInfo(address: string): {
- type: 'standard' | 'contract' | 'multisig' | 'invalid';
- network: 'mainnet' | 'testnet' | 'unknown';
-} {
- if (!validateStacksAddress(address)) {
- return { type: 'invalid', network: 'unknown' };
- }
-
- // Mainnet prefixes
- if (address.startsWith('SP')) {
- return { type: 'standard', network: 'mainnet' };
- } else if (address.startsWith('SM')) {
- return { type: 'multisig', network: 'mainnet' };
- }
-
- // Testnet prefixes
- else if (address.startsWith('ST')) {
- return { type: 'standard', network: 'testnet' };
- } else if (address.startsWith('SN')) {
- return { type: 'multisig', network: 'testnet' };
- }
-
- // Contract address (contains .)
- if (address.includes('.')) {
- const [principal] = address.split('.');
- const info = getAddressInfo(principal);
- return { ...info, type: 'contract' };
- }
-
- return { type: 'invalid', network: 'unknown' };
-}
-
-// Usage
-const info = getAddressInfo('SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.my-contract');
-console.log(info); // { type: 'contract', network: 'mainnet' }
-```
-
-## Generación de direcciones
-
-Generar direcciones a partir de claves:
-
-```typescript
-import {
- makeRandomPrivKey,
- getPublicKey,
- getAddressFromPrivateKey,
- getAddressFromPublicKey,
- TransactionVersion,
- AddressHashMode
-} from '@stacks/transactions';
-
-// Generate new random address
-function generateNewAddress(network: 'mainnet' | 'testnet') {
- const privateKey = makeRandomPrivKey();
- const publicKey = getPublicKey(privateKey);
-
- const version = network === 'mainnet'
- ? TransactionVersion.Mainnet
- : TransactionVersion.Testnet;
-
- const address = getAddressFromPrivateKey(privateKey, version);
-
- return {
- privateKey,
- publicKey,
- address,
- };
-}
-
-// Generate address from existing private key
-function getAddressFromKey(privateKey: string, network: 'mainnet' | 'testnet') {
- const version = network === 'mainnet'
- ? TransactionVersion.Mainnet
- : TransactionVersion.Testnet;
-
- return getAddressFromPrivateKey(privateKey, version);
-}
-
-// Generate multisig address
-function generateMultisigAddress(
- publicKeys: string[],
- signaturesRequired: number,
- network: 'mainnet' | 'testnet'
-) {
- const version = network === 'mainnet'
- ? TransactionVersion.Mainnet
- : TransactionVersion.Testnet;
-
- const hashMode = AddressHashMode.SerializeP2SH;
-
- // Implementation depends on multisig setup
- // This is a simplified example
- return getAddressFromPublicKey(
- publicKeys[0], // Simplified - real implementation needs all keys
- version,
- hashMode
- );
-}
-```
-
-## Manejo de direcciones de contrato
-
-Trabajar con directores de contrato:
-
-```typescript
-// Parse contract address components
-function parseContractAddress(contractAddress: string): {
- principal: string;
- contractName: string;
- isValid: boolean;
-} {
- const parts = contractAddress.split('.');
-
- if (parts.length !== 2) {
- return { principal: '', contractName: '', isValid: false };
- }
-
- const [principal, contractName] = parts;
-
- const isValid = validateStacksAddress(principal) &&
- validateContractName(contractName);
-
- return { principal, contractName, isValid };
-}
-
-// Build contract address
-function buildContractAddress(principal: string, contractName: string): string {
- if (!validateStacksAddress(principal)) {
- throw new Error('Invalid principal address');
- }
-
- if (!validateContractName(contractName)) {
- throw new Error('Invalid contract name');
- }
-
- return `${principal}.${contractName}`;
-}
-
-// Validate full contract identifier
-function validateContractAddress(address: string): boolean {
- const { isValid } = parseContractAddress(address);
- return isValid;
-}
-
-// Usage
-const parsed = parseContractAddress('SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.my-token');
-console.log(parsed);
-// { principal: 'SP2J6...', contractName: 'my-token', isValid: true }
-```
-
-## Utilidades de conversión de direcciones
-
-Convertir entre formatos y redes:
-
-```typescript
-import { c32addressDecode, c32address } from 'c32check';
-
-// Convert between testnet and mainnet addresses
-function convertAddressNetwork(
- address: string,
- toNetwork: 'mainnet' | 'testnet'
-): string {
- try {
- // Decode the address
- const decoded = c32addressDecode(address);
-
- // Determine new version
- let newVersion: number;
- if (toNetwork === 'mainnet') {
- newVersion = decoded[0] === 26 ? 22 : 20; // Multi-sig or standard
- } else {
- newVersion = decoded[0] === 22 ? 26 : 21; // Multi-sig or standard
- }
-
- // Re-encode with new version
- const newAddress = c32address(newVersion, decoded[1]);
- return newAddress;
- } catch (error) {
- throw new Error('Invalid address format');
- }
-}
-
-// Extract address hash
-function getAddressHash(address: string): string {
- const decoded = c32addressDecode(address);
- return Buffer.from(decoded[1]).toString('hex');
-}
-
-// Check if addresses are same (ignoring network)
-function isSameAddress(addr1: string, addr2: string): boolean {
- try {
- const hash1 = getAddressHash(addr1);
- const hash2 = getAddressHash(addr2);
- return hash1 === hash2;
- } catch {
- return false;
- }
-}
-```
-
-## Patrones de validación avanzados
-
-### Validador de direcciones completo
-
-Crea un sistema de validación robusto:
-
-```typescript
-class AddressValidator {
- private cache = new Map();
-
- validate(address: string, options?: {
- network?: 'mainnet' | 'testnet';
- allowContracts?: boolean;
- allowMultisig?: boolean;
- }): { valid: boolean; reason?: string } {
- // Check cache
- const cacheKey = `${address}-${JSON.stringify(options)}`;
- if (this.cache.has(cacheKey)) {
- return { valid: this.cache.get(cacheKey)! };
- }
-
- // Basic validation
- if (!validateStacksAddress(address)) {
- return { valid: false, reason: 'Invalid address format' };
- }
-
- const info = getAddressInfo(address);
-
- // Check network if specified
- if (options?.network && info.network !== options.network) {
- return {
- valid: false,
- reason: `Address is for ${info.network}, expected ${options.network}`
- };
- }
-
- // Check contract addresses
- if (info.type === 'contract' && !options?.allowContracts) {
- return { valid: false, reason: 'Contract addresses not allowed' };
- }
-
- // Check multisig
- if (info.type === 'multisig' && !options?.allowMultisig) {
- return { valid: false, reason: 'Multisig addresses not allowed' };
- }
-
- // Cache result
- this.cache.set(cacheKey, true);
-
- return { valid: true };
- }
-
- validateBatch(addresses: string[], options?: any): Map {
- const results = new Map();
-
- for (const address of addresses) {
- const { valid } = this.validate(address, options);
- results.set(address, valid);
- }
-
- return results;
- }
-}
-```
-
-### Formato de dirección
-
-Formatear direcciones para mostrar:
-
-```typescript
-function formatAddress(
- address: string,
- options?: {
- truncate?: boolean;
- length?: number;
- separator?: string;
- }
-): string {
- if (!validateStacksAddress(address)) {
- return 'Invalid Address';
- }
-
- if (options?.truncate) {
- const length = options.length || 8;
- const start = address.slice(0, length);
- const end = address.slice(-length);
- const separator = options.separator || '...';
- return `${start}${separator}${end}`;
- }
-
- return address;
-}
-
-// Format for display with copy functionality
-function AddressDisplay({ address }: { address: string }) {
- const [copied, setCopied] = useState(false);
-
- const formatted = formatAddress(address, {
- truncate: true,
- length: 6
- });
-
- const copyToClipboard = () => {
- navigator.clipboard.writeText(address);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- };
-
- return (
-
- );
-}
-```
-
-## Consideraciones de seguridad
-
-Implementar manejo seguro de direcciones:
-
-```typescript
-// Sanitize user input
-function sanitizeAddress(input: string): string {
- // Remove whitespace and common separators
- return input.trim().replace(/[\s\-_]/g, '');
-}
-
-// Verify address ownership
-async function verifyAddressOwnership(
- address: string,
- signature: string,
- message: string
-): Promise {
- try {
- // Verify the signature matches the address
- const verified = verifyMessageSignature({
- message,
- signature,
- publicKey: await getPublicKeyFromAddress(address),
- });
-
- return verified;
- } catch {
- return false;
- }
-}
-
-// Validate address for specific use case
-function validateRecipientAddress(
- address: string,
- options: {
- blockList?: string[];
- allowList?: string[];
- requireMainnet?: boolean;
- }
-): { valid: boolean; reason?: string } {
- // Check blocklist
- if (options.blockList?.includes(address)) {
- return { valid: false, reason: 'Address is blocked' };
- }
-
- // Check allowlist
- if (options.allowList && !options.allowList.includes(address)) {
- return { valid: false, reason: 'Address not in allowlist' };
- }
-
- // Check network
- const info = getAddressInfo(address);
- if (options.requireMainnet && info.network !== 'mainnet') {
- return { valid: false, reason: 'Mainnet address required' };
- }
-
- return { valid: true };
-}
-```
-
-## Utilidades de prueba
-
-Prueba de validación de dirección:
-
-```typescript
-import { describe, it, expect } from 'vitest';
-
-describe('Address validation', () => {
- const validAddresses = [
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY',
- 'ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC',
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.my-contract',
- ];
-
- const invalidAddresses = [
- 'invalid',
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZ', // Too short
- 'XP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY', // Wrong prefix
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.', // Missing contract
- ];
-
- validAddresses.forEach(address => {
- it(`should validate ${address}`, () => {
- expect(validateStacksAddress(address)).toBe(true);
- });
- });
-
- invalidAddresses.forEach(address => {
- it(`should reject ${address}`, () => {
- expect(validateStacksAddress(address)).toBe(false);
- });
- });
-});
-```
-
-## Mejores prácticas
-
-* **Siempre valide la entrada del usuario**: Nunca confíes en las direcciones proporcionadas por los usuarios
-* **Comprobar la compatibilidad de la red**: Asegúrate de que las direcciones coincidan con tu red
-* **Manejar casos extremos**: Direcciones de contrato, multifirma, etc.
-* **Resultados de validación de caché**: Evitar validación redundante
-* **Proporcionar mensajes de error claros**: Ayuda a los usuarios a corregir entradas inválidas
-
-## Errores comunes
-
-**No comprobar el tipo de red**
-
-```typescript
-// Bad: Accepting any valid address
-const isValid = validateStacksAddress(userInput);
-
-// Good: Checking network matches
-const info = getAddressInfo(userInput);
-if (info.network !== 'mainnet') {
- throw new Error('Please use a mainnet address');
-}
-```
-
-**Suponiendo el formato de dirección**
-
-```typescript
-// Bad: Assuming standard address
-const [principal, contract] = address.split('.');
-
-// Good: Proper validation
-const parsed = parseContractAddress(address);
-if (!parsed.isValid) {
- throw new Error('Invalid contract address');
-}
-```
diff --git a/content/docs/es/reference/stacks.js/(utils)/encoding-decoding.mdx b/content/docs/es/reference/stacks.js/(utils)/encoding-decoding.mdx
deleted file mode 100644
index 004741c77..000000000
--- a/content/docs/es/reference/stacks.js/(utils)/encoding-decoding.mdx
+++ /dev/null
@@ -1,517 +0,0 @@
----
-title: Codificación y decodificación
-description: Convertir entre valores de Clarity y tipos de JavaScript
----
-## Visión general
-
-Stacks utiliza valores de Clarity (CVs) para representar datos en contratos inteligentes. Al construir aplicaciones, necesitarás codificar valores de JavaScript en CVs para llamadas a contratos y decodificar CVs de vuelta a JavaScript para su visualización. Esta guía cubre todos los tipos de CV y patrones de conversión.
-
-## Conversiones básicas de tipos
-
-### Enteros
-
-Convertir entre números de JavaScript y enteros de Clarity:
-
-```typescript
-import {
- intCV,
- uintCV,
- cvToValue,
- cvToJSON
-} from '@stacks/transactions';
-
-// Encoding
-const positiveInt = uintCV(42); // u42
-const negativeInt = intCV(-100); // -100
-const largeUint = uintCV(1000000); // u1000000
-
-// Decoding
-const jsValue = cvToValue(positiveInt); // 42
-const jsonValue = cvToJSON(positiveInt); // { type: 'uint', value: '42' }
-
-// Working with BigInt for large numbers
-const bigNumber = uintCV(BigInt('123456789012345678901234567890'));
-const decoded = cvToValue(bigNumber); // '123456789012345678901234567890'
-```
-
-### Booleanos
-
-Valores simples de verdadero/falso:
-
-```typescript
-import { trueCV, falseCV, boolCV } from '@stacks/transactions';
-
-// Encoding
-const clarityTrue = trueCV(); // true
-const clarityFalse = falseCV(); // false
-const fromBoolean = boolCV(true); // true
-
-// Decoding
-const jsBoolean = cvToValue(clarityTrue); // true
-```
-
-### Cadenas
-
-Manejar cadenas ASCII y UTF-8:
-
-```typescript
-import {
- stringAsciiCV,
- stringUtf8CV,
- cvToString
-} from '@stacks/transactions';
-
-// ASCII strings (limited character set)
-const asciiString = stringAsciiCV('Hello World');
-const asciiDecoded = cvToValue(asciiString); // 'Hello World'
-
-// UTF-8 strings (full Unicode support)
-const utf8String = stringUtf8CV('Hello 世界! 🌍');
-const utf8Decoded = cvToValue(utf8String); // 'Hello 世界! 🌍'
-
-// Direct string extraction
-const directString = cvToString(utf8String); // 'Hello 世界! 🌍'
-```
-
-### Directores
-
-Codifica direcciones de Stacks y principales de contratos:
-
-```typescript
-import {
- standardPrincipalCV,
- contractPrincipalCV,
- cvToValue
-} from '@stacks/transactions';
-
-// Standard principal (user address)
-const userPrincipal = standardPrincipalCV('SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY');
-
-// Contract principal
-const contractPrincipal = contractPrincipalCV(
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY',
- 'my-contract'
-);
-
-// Decoding
-const address = cvToValue(userPrincipal);
-// 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY'
-
-const contract = cvToValue(contractPrincipal);
-// 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY.my-contract'
-```
-
-## Manejo de tipos complejos
-
-### Búferes
-
-Trabajar con datos binarios:
-
-```typescript
-import {
- bufferCV,
- bufferCVFromString,
- cvToValue
-} from '@stacks/transactions';
-
-// From hex string
-const hexBuffer = bufferCV(Buffer.from('deadbeef', 'hex'));
-
-// From UTF-8 string
-const stringBuffer = bufferCVFromString('Hello Buffer');
-
-// From byte array
-const byteBuffer = bufferCV(new Uint8Array([1, 2, 3, 4]));
-
-// Decoding returns hex string
-const decoded = cvToValue(hexBuffer); // '0xdeadbeef'
-
-// Get raw buffer
-const rawBuffer = hexBuffer.buffer; // Buffer instance
-```
-
-### Valores opcionales
-
-Manejar el tipo opcional de Clarity:
-
-```typescript
-import {
- someCV,
- noneCV,
- cvToValue
-} from '@stacks/transactions';
-
-// Some value (contains a value)
-const someValue = someCV(uintCV(42)); // (some u42)
-const someString = someCV(stringUtf8CV('hi')); // (some u"hi")
-
-// None value (no value)
-const noneValue = noneCV(); // none
-
-// Decoding
-const decodedSome = cvToValue(someValue); // 42
-const decodedNone = cvToValue(noneValue); // null
-
-// Check optional type
-if (someValue.type === ClarityType.OptionalSome) {
- const innerValue = cvToValue(someValue.value);
-}
-```
-
-### Valores de respuesta
-
-Manejar tipos de respuesta de contrato:
-
-```typescript
-import {
- responseOkCV,
- responseErrorCV,
- cvToValue
-} from '@stacks/transactions';
-
-// Success response
-const okResponse = responseOkCV(uintCV(100)); // (ok u100)
-const okString = responseOkCV(stringUtf8CV('Success')); // (ok u"Success")
-
-// Error response
-const errorResponse = responseErrorCV(uintCV(404)); // (err u404)
-const errorMsg = responseErrorCV(stringUtf8CV('Not found')); // (err u"Not found")
-
-// Decoding and checking
-const result = okResponse;
-if (result.type === ClarityType.ResponseOk) {
- console.log('Success:', cvToValue(result.value));
-} else {
- console.log('Error:', cvToValue(result.value));
-}
-```
-
-### Tuplas
-
-Crear y decodificar datos estructurados:
-
-```typescript
-import {
- tupleCV,
- cvToValue,
- cvToJSON
-} from '@stacks/transactions';
-
-// Create tuple
-const userInfo = tupleCV({
- id: uintCV(1),
- name: stringUtf8CV('Alice'),
- balance: uintCV(1000000),
- active: trueCV(),
- metadata: tupleCV({
- created: uintCV(Date.now()),
- tags: listCV([stringAsciiCV('user'), stringAsciiCV('premium')])
- })
-});
-
-// Decode to JavaScript object
-const decoded = cvToValue(userInfo);
-// {
-// id: 1,
-// name: 'Alice',
-// balance: 1000000,
-// active: true,
-// metadata: {
-// created: 1234567890,
-// tags: ['user', 'premium']
-// }
-// }
-
-// Access tuple fields
-const nameCV = userInfo.data.name;
-const name = cvToValue(nameCV); // 'Alice'
-```
-
-### Listas
-
-Trabajar con matrices de valores:
-
-```typescript
-import {
- listCV,
- cvToValue
-} from '@stacks/transactions';
-
-// List of same type
-const numbers = listCV([uintCV(1), uintCV(2), uintCV(3)]);
-const strings = listCV([
- stringUtf8CV('apple'),
- stringUtf8CV('banana'),
- stringUtf8CV('cherry')
-]);
-
-// List of tuples (common pattern)
-const users = listCV([
- tupleCV({ id: uintCV(1), name: stringUtf8CV('Alice') }),
- tupleCV({ id: uintCV(2), name: stringUtf8CV('Bob') }),
-]);
-
-// Decoding
-const decodedNumbers = cvToValue(numbers); // [1, 2, 3]
-const decodedUsers = cvToValue(users);
-// [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
-
-// Iterate over list
-numbers.list.forEach((cv, index) => {
- console.log(`Item ${index}:`, cvToValue(cv));
-});
-```
-
-## Patrones de codificación avanzados
-
-### Codificación de tipo dinámica
-
-Construye codificadores para valores en tiempo de ejecución:
-
-```typescript
-function encodeValue(value: any): ClarityValue {
- if (typeof value === 'number') {
- return value >= 0 ? uintCV(value) : intCV(value);
- } else if (typeof value === 'string') {
- // Check if valid ASCII
- if (/^[\x00-\x7F]*$/.test(value)) {
- return stringAsciiCV(value);
- }
- return stringUtf8CV(value);
- } else if (typeof value === 'boolean') {
- return boolCV(value);
- } else if (value === null || value === undefined) {
- return noneCV();
- } else if (Array.isArray(value)) {
- return listCV(value.map(encodeValue));
- } else if (typeof value === 'object') {
- const tupleData: { [key: string]: ClarityValue } = {};
- for (const [key, val] of Object.entries(value)) {
- tupleData[key] = encodeValue(val);
- }
- return tupleCV(tupleData);
- }
-
- throw new Error(`Cannot encode value: ${value}`);
-}
-
-// Usage
-const encoded = encodeValue({
- name: 'Alice',
- age: 30,
- tags: ['user', 'admin'],
- active: true
-});
-```
-
-### Decodificación segura de tipos
-
-Crea decodificadores con validación de tipo:
-
-```typescript
-interface UserData {
- id: number;
- name: string;
- balance: number;
- active: boolean;
-}
-
-function decodeUser(cv: ClarityValue): UserData {
- if (cv.type !== ClarityType.Tuple) {
- throw new Error('Expected tuple');
- }
-
- const data = cv.data;
-
- // Validate and extract each field
- if (!data.id || data.id.type !== ClarityType.UInt) {
- throw new Error('Invalid id field');
- }
-
- if (!data.name || (
- data.name.type !== ClarityType.StringASCII &&
- data.name.type !== ClarityType.StringUTF8
- )) {
- throw new Error('Invalid name field');
- }
-
- return {
- id: Number(cvToValue(data.id)),
- name: cvToString(data.name),
- balance: Number(cvToValue(data.balance)),
- active: cvToValue(data.active) as boolean,
- };
-}
-```
-
-### Utilidades de codificación por lotes
-
-Codifica múltiples valores de manera eficiente:
-
-```typescript
-class ClarityEncoder {
- static encodeArray(
- items: T[],
- encoder: (item: T) => ClarityValue
- ): ClarityValue {
- return listCV(items.map(encoder));
- }
-
- static encodeTuple>(
- obj: T,
- schema: { [K in keyof T]: (value: T[K]) => ClarityValue }
- ): TupleCV {
- const tupleData: { [key: string]: ClarityValue } = {};
-
- for (const [key, encoder] of Object.entries(schema)) {
- tupleData[key] = encoder(obj[key as keyof T]);
- }
-
- return tupleCV(tupleData);
- }
-
- static encodeOptional(
- value: T | null | undefined,
- encoder: (value: T) => ClarityValue
- ): OptionalCV {
- if (value === null || value === undefined) {
- return noneCV();
- }
- return someCV(encoder(value));
- }
-}
-
-// Usage
-const users = [
- { id: 1, name: 'Alice', balance: 1000 },
- { id: 2, name: 'Bob', balance: 2000 },
-];
-
-const encoded = ClarityEncoder.encodeArray(users, user =>
- ClarityEncoder.encodeTuple(user, {
- id: (id) => uintCV(id),
- name: (name) => stringUtf8CV(name),
- balance: (balance) => uintCV(balance),
- })
-);
-```
-
-## Serialización y deserialización
-
-Trabaja con valores serializados de Clarity:
-
-```typescript
-import {
- serializeCV,
- deserializeCV,
- cvToHex,
- hexToCV
-} from '@stacks/transactions';
-
-// Serialize to buffer
-const cv = tupleCV({ amount: uintCV(1000), memo: stringUtf8CV('Payment') });
-const serialized = serializeCV(cv); // Buffer
-
-// Convert to hex for storage/transport
-const hex = cvToHex(cv); // '0x0c00000002046d656d6f...'
-
-// Deserialize from hex
-const deserialized = hexToCV(hex);
-const value = cvToValue(deserialized); // { amount: 1000, memo: 'Payment' }
-
-// Work with raw buffers
-const buffer = Buffer.from(hex, 'hex');
-const fromBuffer = deserializeCV(buffer);
-```
-
-## Patrones de conversión comunes
-
-### Argumentos de llamada de contrato
-
-Preparar argumentos para llamadas de contrato:
-
-```typescript
-function prepareTransferArgs(
- recipient: string,
- amount: number,
- memo?: string
-): ClarityValue[] {
- const args = [
- standardPrincipalCV(recipient),
- uintCV(amount),
- ];
-
- if (memo) {
- args.push(someCV(stringUtf8CV(memo)));
- } else {
- args.push(noneCV());
- }
-
- return args;
-}
-
-// Usage in contract call
-const functionArgs = prepareTransferArgs(
- 'SP2J6Y09JMFWWZCT4VJX0BA5W7A9HZP5EX96Y6VZY',
- 1000000,
- 'Monthly payment'
-);
-```
-
-### Manejo de respuestas
-
-Procesar respuestas de contratos:
-
-```typescript
-function handleContractResponse(response: ClarityValue): {
- success: boolean;
- data: any;
- error?: string;
-} {
- if (response.type === ClarityType.ResponseOk) {
- return {
- success: true,
- data: cvToValue(response.value),
- };
- } else if (response.type === ClarityType.ResponseErr) {
- const errorValue = cvToValue(response.value);
- return {
- success: false,
- data: null,
- error: typeof errorValue === 'string' ? errorValue : `Error: ${errorValue}`,
- };
- }
-
- throw new Error('Invalid response type');
-}
-```
-
-## Mejores prácticas
-
-* **Validar tipos**: Siempre verifica los tipos de CV antes de decodificar
-* **Manejar casos extremos**: Considerar valores nulos, indefinidos y vacíos
-* **Utiliza los tipos de cadena apropiados**: ASCII para texto simple, UTF-8 para internacional
-* **Preservar la precisión**: Usa BigInt para números grandes
-* **Estrechamiento de tipos**: Usa guardas de tipo de TypeScript para seguridad
-
-## Errores comunes
-
-**Confusión de tipos de cadena**
-
-```typescript
-// Bad: Using ASCII for Unicode
-const bad = stringAsciiCV('Hello 世界'); // Will throw error
-
-// Good: Use UTF-8 for Unicode
-const good = stringUtf8CV('Hello 世界');
-```
-
-**Desbordamiento de números**
-
-```typescript
-// Bad: JavaScript number too large
-const bad = uintCV(Number.MAX_SAFE_INTEGER + 1); // Precision loss
-
-// Good: Use BigInt
-const good = uintCV(BigInt('9007199254740992'));
-```
diff --git a/content/docs/es/reference/stacks.js/(utils)/network-configuration.mdx b/content/docs/es/reference/stacks.js/(utils)/network-configuration.mdx
deleted file mode 100644
index 942896a43..000000000
--- a/content/docs/es/reference/stacks.js/(utils)/network-configuration.mdx
+++ /dev/null
@@ -1,536 +0,0 @@
----
-title: Configuración de red
-description: Configurar y personalizar las conexiones de red de Stacks
----
-## Visión general
-
-Stacks.js admite múltiples redes: mainnet para producción, testnet para desarrollo y redes personalizadas para pruebas locales. La configuración adecuada de la red garantiza que su aplicación se conecte a la instancia correcta de blockchain con la configuración óptima.
-
-## Configuración básica de red
-
-Configurar redes estándar:
-
-```typescript
-import {
- StacksMainnet,
- StacksTestnet,
- StacksMocknet
-} from '@stacks/network';
-
-// Production network
-const mainnet = new StacksMainnet();
-console.log('Mainnet API:', mainnet.coreApiUrl);
-// https://api.hiro.so
-
-// Test network
-const testnet = new StacksTestnet();
-console.log('Testnet API:', testnet.coreApiUrl);
-// https://api.testnet.hiro.so
-
-// Local development network
-const mocknet = new StacksMocknet();
-console.log('Mocknet API:', mocknet.coreApiUrl);
-// http://localhost:3999
-```
-
-## Configuración de red personalizada
-
-Crear redes con puntos finales personalizados:
-
-```typescript
-import { StacksNetwork } from '@stacks/network';
-
-// Custom mainnet configuration
-const customMainnet = new StacksMainnet({
- url: 'https://my-custom-node.com',
- fetchFn: fetch, // Custom fetch implementation
-});
-
-// Custom testnet with specific endpoints
-const customTestnet = new StacksTestnet({
- url: 'https://my-testnet-node.com:3999',
-});
-
-// Fully custom network
-class CustomNetwork extends StacksNetwork {
- constructor() {
- super({
- url: 'https://custom-stacks-node.com',
- networkType: 'mainnet', // or 'testnet', 'mocknet'
- });
- }
-
- // Override methods as needed
- getBroadcastApiUrl() {
- return `${this.coreApiUrl}/custom/broadcast`;
- }
-}
-```
-
-## Configuración basada en el entorno
-
-Gestionar redes en diferentes entornos:
-
-```typescript
-// config/network.ts
-import {
- StacksNetwork,
- StacksMainnet,
- StacksTestnet,
- StacksMocknet
-} from '@stacks/network';
-
-interface NetworkConfig {
- network: StacksNetwork;
- apiUrl: string;
- wsUrl?: string;
- explorerUrl: string;
- faucetUrl?: string;
-}
-
-const configs: Record = {
- production: {
- network: new StacksMainnet(),
- apiUrl: 'https://api.hiro.so',
- wsUrl: 'wss://api.hiro.so',
- explorerUrl: 'https://explorer.hiro.so',
- },
- staging: {
- network: new StacksTestnet(),
- apiUrl: 'https://api.testnet.hiro.so',
- wsUrl: 'wss://api.testnet.hiro.so',
- explorerUrl: 'https://explorer.hiro.so/?chain=testnet',
- faucetUrl: 'https://api.testnet.hiro.so/extended/v1/faucets/stx',
- },
- development: {
- network: new StacksMocknet(),
- apiUrl: 'http://localhost:3999',
- explorerUrl: 'http://localhost:8000',
- },
-};
-
-export function getNetworkConfig(): NetworkConfig {
- const env = process.env.NODE_ENV || 'development';
- return configs[env];
-}
-
-// Usage
-const { network, apiUrl } = getNetworkConfig();
-```
-
-## Detección y validación de red
-
-Detectar y validar conexiones de red:
-
-```typescript
-async function detectNetwork(url: string): Promise<'mainnet' | 'testnet' | 'unknown'> {
- try {
- const response = await fetch(`${url}/v2/info`);
- const info = await response.json();
-
- // Check network ID
- if (info.network_id === 1) {
- return 'mainnet';
- } else if (info.network_id === 2147483648) {
- return 'testnet';
- }
-
- return 'unknown';
- } catch (error) {
- console.error('Failed to detect network:', error);
- return 'unknown';
- }
-}
-
-// Validate network matches expectation
-async function validateNetwork(
- network: StacksNetwork,
- expected: 'mainnet' | 'testnet'
-): Promise {
- const detected = await detectNetwork(network.coreApiUrl);
-
- if (detected !== expected) {
- console.warn(`Network mismatch! Expected ${expected}, got ${detected}`);
- return false;
- }
-
- return true;
-}
-```
-
-## Características de red avanzadas
-
-### Encabezados personalizados y autenticación
-
-Agregar autenticación o encabezados personalizados:
-
-```typescript
-class AuthenticatedNetwork extends StacksMainnet {
- private apiKey: string;
-
- constructor(apiKey: string) {
- super();
- this.apiKey = apiKey;
- }
-
- createFetchFn(): FetchFn {
- return (url: string, init?: RequestInit) => {
- const headers = {
- ...init?.headers,
- 'x-api-key': this.apiKey,
- 'x-client-version': '1.0.0',
- };
-
- return fetch(url, { ...init, headers });
- };
- }
-}
-
-// Usage
-const network = new AuthenticatedNetwork(process.env.API_KEY!);
-```
-
-### Solicitud de reintento y tiempo de espera
-
-Implementar solicitudes de red resilientes:
-
-```typescript
-class ResilientNetwork extends StacksTestnet {
- private maxRetries = 3;
- private timeout = 30000; // 30 seconds
-
- createFetchFn(): FetchFn {
- return async (url: string, init?: RequestInit) => {
- for (let attempt = 0; attempt < this.maxRetries; attempt++) {
- try {
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
-
- const response = await fetch(url, {
- ...init,
- signal: controller.signal,
- });
-
- clearTimeout(timeoutId);
-
- if (!response.ok && attempt < this.maxRetries - 1) {
- // Retry on server errors
- if (response.status >= 500) {
- await this.delay(1000 * Math.pow(2, attempt));
- continue;
- }
- }
-
- return response;
- } catch (error) {
- if (attempt === this.maxRetries - 1) throw error;
- await this.delay(1000 * Math.pow(2, attempt));
- }
- }
-
- throw new Error('Max retries exceeded');
- };
- }
-
- private delay(ms: number): Promise {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
-}
-```
-
-## Configuraciones específicas de red
-
-### Configurar por ID de cadena
-
-Configurar la red basada en el identificador de cadena:
-
-```typescript
-function getNetworkByChainId(chainId: number): StacksNetwork {
- switch (chainId) {
- case 1: // Mainnet
- return new StacksMainnet();
- case 2147483648: // Testnet
- return new StacksTestnet();
- default:
- throw new Error(`Unknown chain ID: ${chainId}`);
- }
-}
-
-// Dynamic network from wallet
-async function getNetworkFromWallet(): Promise {
- const userData = userSession.loadUserData();
- const address = userData.profile.stxAddress.testnet;
-
- // Determine network from address prefix
- if (address.startsWith('SP') || address.startsWith('SM')) {
- return new StacksMainnet();
- } else if (address.startsWith('ST') || address.startsWith('SN')) {
- return new StacksTestnet();
- }
-
- throw new Error('Unable to determine network from address');
-}
-```
-
-### Soporte para múltiples redes
-
-Admite múltiples redes simultáneamente:
-
-```typescript
-class NetworkManager {
- private networks: Map = new Map();
- private currentNetwork: string = 'testnet';
-
- constructor() {
- this.networks.set('mainnet', new StacksMainnet());
- this.networks.set('testnet', new StacksTestnet());
- this.networks.set('devnet', new StacksMocknet());
- }
-
- getNetwork(name?: string): StacksNetwork {
- const networkName = name || this.currentNetwork;
- const network = this.networks.get(networkName);
-
- if (!network) {
- throw new Error(`Unknown network: ${networkName}`);
- }
-
- return network;
- }
-
- setCurrentNetwork(name: string): void {
- if (!this.networks.has(name)) {
- throw new Error(`Unknown network: ${name}`);
- }
- this.currentNetwork = name;
- }
-
- addCustomNetwork(name: string, url: string): void {
- const network = new StacksNetwork({ url });
- this.networks.set(name, network);
- }
-}
-
-// Usage
-const manager = new NetworkManager();
-const mainnet = manager.getNetwork('mainnet');
-manager.setCurrentNetwork('mainnet');
-```
-
-## Monitoreo de conexión de red
-
-Monitorear la salud y el estado de la red:
-
-```typescript
-class NetworkMonitor {
- private network: StacksNetwork;
- private isHealthy = true;
- private listeners: Set<(healthy: boolean) => void> = new Set();
-
- constructor(network: StacksNetwork) {
- this.network = network;
- this.startMonitoring();
- }
-
- private async startMonitoring() {
- setInterval(async () => {
- try {
- const response = await fetch(
- `${this.network.coreApiUrl}/v2/info`,
- { signal: AbortSignal.timeout(5000) }
- );
-
- const wasHealthy = this.isHealthy;
- this.isHealthy = response.ok;
-
- if (wasHealthy !== this.isHealthy) {
- this.notifyListeners();
- }
- } catch (error) {
- const wasHealthy = this.isHealthy;
- this.isHealthy = false;
-
- if (wasHealthy) {
- this.notifyListeners();
- }
- }
- }, 30000); // Check every 30 seconds
- }
-
- onHealthChange(callback: (healthy: boolean) => void): () => void {
- this.listeners.add(callback);
- return () => this.listeners.delete(callback);
- }
-
- private notifyListeners() {
- this.listeners.forEach(callback => callback(this.isHealthy));
- }
-
- async waitForHealth(timeout = 60000): Promise {
- const start = Date.now();
-
- while (!this.isHealthy && Date.now() - start < timeout) {
- await new Promise(resolve => setTimeout(resolve, 1000));
- }
-
- if (!this.isHealthy) {
- throw new Error('Network unhealthy after timeout');
- }
- }
-}
-```
-
-## Configuración de WebSocket
-
-Configurar conexiones en tiempo real:
-
-```typescript
-interface WebSocketConfig {
- url: string;
- reconnectInterval: number;
- maxReconnectAttempts: number;
-}
-
-class StacksWebSocketClient {
- private ws: WebSocket | null = null;
- private config: WebSocketConfig;
- private reconnectAttempts = 0;
-
- constructor(network: StacksNetwork) {
- this.config = {
- url: this.getWebSocketUrl(network),
- reconnectInterval: 5000,
- maxReconnectAttempts: 10,
- };
- }
-
- private getWebSocketUrl(network: StacksNetwork): string {
- const apiUrl = network.coreApiUrl;
- return apiUrl.replace('https://', 'wss://').replace('http://', 'ws://');
- }
-
- connect(): void {
- this.ws = new WebSocket(this.config.url);
-
- this.ws.onopen = () => {
- console.log('WebSocket connected');
- this.reconnectAttempts = 0;
- };
-
- this.ws.onclose = () => {
- this.handleReconnect();
- };
-
- this.ws.onerror = (error) => {
- console.error('WebSocket error:', error);
- };
- }
-
- private handleReconnect(): void {
- if (this.reconnectAttempts < this.config.maxReconnectAttempts) {
- setTimeout(() => {
- this.reconnectAttempts++;
- this.connect();
- }, this.config.reconnectInterval);
- }
- }
-
- subscribe(event: string, callback: (data: any) => void): void {
- if (!this.ws) throw new Error('WebSocket not connected');
-
- this.ws.send(JSON.stringify({
- method: 'subscribe',
- params: { event }
- }));
-
- this.ws.onmessage = (message) => {
- const data = JSON.parse(message.data);
- if (data.event === event) {
- callback(data);
- }
- };
- }
-}
-```
-
-## Probando con diferentes redes
-
-Configurar pruebas en diferentes redes:
-
-```typescript
-import { describe, it, beforeEach } from 'vitest';
-
-describe('Cross-network tests', () => {
- const networks = [
- { name: 'mainnet', network: new StacksMainnet() },
- { name: 'testnet', network: new StacksTestnet() },
- ];
-
- networks.forEach(({ name, network }) => {
- describe(`${name} tests`, () => {
- it('should connect to network', async () => {
- const response = await fetch(`${network.coreApiUrl}/v2/info`);
- expect(response.ok).toBe(true);
- });
-
- it('should have correct chain ID', async () => {
- const response = await fetch(`${network.coreApiUrl}/v2/info`);
- const info = await response.json();
-
- if (name === 'mainnet') {
- expect(info.network_id).toBe(1);
- } else {
- expect(info.network_id).toBe(2147483648);
- }
- });
- });
- });
-});
-```
-
-## Mejores prácticas
-
-* **Utilizar variables de entorno**: Nunca codifiques URLs de red de forma estática
-* **Implementar lógica de reintento**: Las redes pueden estar temporalmente no disponibles
-* **Monitorear la salud de la conexión**: Detectar y manejar problemas de red
-* **Información de red en caché**: Reducir llamadas redundantes a la API
-* **Validar tipo de red**: Asegúrate de estar en la red esperada
-
-## Problemas comunes
-
-**Errores de CORS**
-
-```typescript
-// Configure proxy for development
-const devNetwork = new StacksTestnet({
- url: '/api', // Proxy through your dev server
-});
-
-// Or use CORS-enabled endpoints
-const corsNetwork = new StacksTestnet({
- url: 'https://api.testnet.hiro.so',
-});
-```
-
-**Manejo de tiempo de espera**
-
-```typescript
-// Add timeout to all requests
-class TimeoutNetwork extends StacksMainnet {
- async fetchWithTimeout(url: string, timeout = 30000): Promise {
- const controller = new AbortController();
- const id = setTimeout(() => controller.abort(), timeout);
-
- try {
- const response = await fetch(url, {
- signal: controller.signal,
- });
- clearTimeout(id);
- return response;
- } catch (error) {
- clearTimeout(id);
- throw new Error(`Request timeout: ${url}`);
- }
- }
-}
-```
diff --git a/content/docs/es/reference/stacks.js/(utils)/unit-conversion.mdx b/content/docs/es/reference/stacks.js/(utils)/unit-conversion.mdx
deleted file mode 100644
index 6c3ea9ce3..000000000
--- a/content/docs/es/reference/stacks.js/(utils)/unit-conversion.mdx
+++ /dev/null
@@ -1,218 +0,0 @@
----
-title: Conversión de unidades
-description: Convertir entre STX, microSTX y otras unidades
----
-Aprende cómo convertir entre diferentes denominaciones de unidades en Stacks. La blockchain utiliza microSTX como su unidad base, donde 1 STX = 1,000,000 microSTX. La conversión adecuada de unidades es esencial para mostrar cantidades a los usuarios y procesar transacciones.
-
-## Conversiones básicas
-
-Convierta entre STX y microSTX utilizando funciones de conversión simples.
-
-```typescript
-// Convert STX to microSTX
-function stxToMicroStx(stx: number | string): bigint {
- const stxAmount = typeof stx === 'string' ? parseFloat(stx) : stx;
- return BigInt(Math.floor(stxAmount * 1_000_000));
-}
-
-// Convert microSTX to STX
-function microStxToStx(microStx: number | bigint | string): string {
- const amount = BigInt(microStx);
- const stx = Number(amount) / 1_000_000;
- return stx.toFixed(6).replace(/\.?0+$/, '');
-}
-
-// Usage examples
-const microStx = stxToMicroStx(1.5); // 1500000n
-const stx = microStxToStx(1500000); // "1.5"
-```
-
-## Manejo seguro de precisión
-
-Maneja números grandes sin pérdida de precisión utilizando operaciones BigInt.
-
-```typescript
-class StxConverter {
- static readonly MICROSTX_PER_STX = 1_000_000n;
-
- static toMicroStx(amount: string | number, decimals = 6): bigint {
- const amountStr = amount.toString();
- const [whole, decimal = ''] = amountStr.split('.');
- const paddedDecimal = decimal.padEnd(decimals, '0').slice(0, decimals);
- return BigInt(whole + paddedDecimal);
- }
-
- static toStx(microStx: bigint | string | number): string {
- const amount = BigInt(microStx);
- const isNegative = amount < 0n;
- const absoluteAmount = isNegative ? -amount : amount;
-
- const str = absoluteAmount.toString().padStart(7, '0');
- const whole = str.slice(0, -6) || '0';
- const decimal = str.slice(-6);
-
- let result = `${whole}.${decimal}`.replace(/\.?0+$/, '');
- return isNegative ? `-${result}` : result;
- }
-}
-
-// Precise conversion examples
-const precise1 = StxConverter.toMicroStx('123.456789'); // 123456789n
-const precise2 = StxConverter.toStx(123456789n); // "123.456789"
-```
-
-## Conversiones de tokens
-
-Maneja tokens con diferentes decimales usando una clase de conversión flexible.
-
-```typescript
-interface TokenInfo {
- decimals: number;
- symbol: string;
- name: string;
-}
-
-class TokenConverter {
- constructor(private tokenInfo: TokenInfo) {}
-
- toSmallestUnit(amount: string | number): bigint {
- if (typeof amount === 'string') {
- const [whole, decimal = ''] = amount.split('.');
- const paddedDecimal = decimal
- .padEnd(this.tokenInfo.decimals, '0')
- .slice(0, this.tokenInfo.decimals);
- return BigInt(whole + paddedDecimal);
- }
-
- const multiplier = 10n ** BigInt(this.tokenInfo.decimals);
- return BigInt(Math.floor(amount * Number(multiplier)));
- }
-
- fromSmallestUnit(amount: bigint | string): string {
- const value = BigInt(amount);
- const divisor = 10n ** BigInt(this.tokenInfo.decimals);
- const whole = value / divisor;
- const remainder = value % divisor;
-
- if (remainder === 0n) return whole.toString();
-
- const decimal = remainder
- .toString()
- .padStart(this.tokenInfo.decimals, '0')
- .replace(/0+$/, '');
-
- return `${whole}.${decimal}`;
- }
-}
-
-// Different token examples
-const usdc = new TokenConverter({ decimals: 6, symbol: 'USDC', name: 'USD Coin' });
-const btc = new TokenConverter({ decimals: 8, symbol: 'BTC', name: 'Bitcoin' });
-
-const usdcAmount = usdc.toSmallestUnit('100.50'); // 100500000n
-const btcAmount = btc.toSmallestUnit('0.00123456'); // 123456n
-```
-
-## Mostrar formato
-
-Formatear cantidades para interfaces de usuario con soporte de localización.
-
-```typescript
-class StxFormatter {
- static format(microStx: bigint, options?: {
- decimals?: number;
- locale?: string;
- symbol?: boolean;
- }): string {
- const stx = StxConverter.toStx(microStx);
- const number = parseFloat(stx);
-
- const formatted = new Intl.NumberFormat(options?.locale || 'en-US', {
- minimumFractionDigits: 0,
- maximumFractionDigits: options?.decimals ?? 6,
- }).format(number);
-
- return options?.symbol ? `${formatted} STX` : formatted;
- }
-
- static compact(microStx: bigint): string {
- const stx = Number(StxConverter.toStx(microStx));
-
- if (stx >= 1_000_000) {
- return `${(stx / 1_000_000).toFixed(2)}M STX`;
- } else if (stx >= 1_000) {
- return `${(stx / 1_000).toFixed(2)}K STX`;
- }
-
- return this.format(microStx, { decimals: 6, symbol: true });
- }
-}
-
-// Formatting examples
-const formatted = StxFormatter.format(123456789n, {
- decimals: 2,
- symbol: true
-}); // "123.46 STX"
-
-const compact = StxFormatter.compact(1234567890000n); // "1.23K STX"
-```
-
-## Validación de entrada
-
-Validar y desinfectar la entrada del usuario para los campos de cantidad.
-
-```typescript
-class AmountInput {
- static validate(input: string, options?: {
- decimals?: number;
- min?: string;
- max?: string;
- }): { valid: boolean; error?: string } {
- // Check format
- if (!/^\d*\.?\d*$/.test(input)) {
- return { valid: false, error: 'Invalid number format' };
- }
-
- // Check decimal places
- const parts = input.split('.');
- if (parts[1] && parts[1].length > (options?.decimals || 6)) {
- return { valid: false, error: `Maximum ${options?.decimals || 6} decimal places` };
- }
-
- // Check range
- if (options?.min) {
- const value = parseFloat(input);
- if (value < parseFloat(options.min)) {
- return { valid: false, error: `Minimum amount is ${options.min}` };
- }
- }
-
- return { valid: true };
- }
-
- static sanitize(input: string, decimals = 6): string {
- let sanitized = input.replace(/[^\d.]/g, '');
- const parts = sanitized.split('.');
-
- if (parts.length > 2) {
- sanitized = parts[0] + '.' + parts.slice(1).join('');
- }
-
- if (parts[1] && parts[1].length > decimals) {
- sanitized = parts[0] + '.' + parts[1].slice(0, decimals);
- }
-
- return sanitized;
- }
-}
-
-// Validation examples
-const result1 = AmountInput.validate('123.456', {
- decimals: 6,
- min: '0.000001'
-}); // { valid: true }
-
-const result2 = AmountInput.validate('123.4567890', {
- decimals: 6
-}); // { valid: false, error: 'Maximum 6 decimal places' }
-```
diff --git a/content/docs/es/reference/stacks.js/index.mdx b/content/docs/es/reference/stacks.js/index.mdx
deleted file mode 100644
index f42a48415..000000000
--- a/content/docs/es/reference/stacks.js/index.mdx
+++ /dev/null
@@ -1,75 +0,0 @@
----
-title: Stacks.js
-sidebarTitle: Visión general
-description: Un SDK de JavaScript/TypeScript para construir aplicaciones en la cadena de bloques Stacks.
-llm: false
----
-## Visión general
-
-Stacks.js es una colección de bibliotecas de JavaScript que te permiten construir aplicaciones web en la cadena de bloques Stacks. Desde autenticación de billeteras hasta interacciones con contratos inteligentes.
-
-Para explorar Stacks.js con IA, copie y pegue [llms.txt](/reference/stacks.js/llms.txt) en tu LLM de elección.
-
-## Características principales
-
-* **Construcción de transacciones** - Construir y transmitir todos los tipos de transacciones con APIs de tipo seguro
-* **Interacción con contratos inteligentes** - Desplegar contratos y llamar funciones con codificación automática
-* **Integración de billetera** - Conéctese a Leather, Xverse y otras billeteras de Stacks sin problemas
-* **Postcondiciones** - Proteger a los usuarios con validaciones de transferencia de activos incorporadas
-
-## Instalación
-
-Stacks.js está separado en paquetes específicos publicados bajo el `@stacks` alcance. Instala solo lo que necesitas:
-
-
- ```terminal !! transactions
- $ npm install @stacks/transactions
- ```
-
- ```terminal !! connect
- $ npm install @stacks/connect
- ```
-
- ```terminal !! network
- $ npm install @stacks/network
- ```
-
- ```terminal !! common
- $ npm install @stacks/common
- ```
-
-
-
-
- Paquetes disponibles
-
-
- * `@stacks/api`
- * `@stacks/auth`
- * `@stacks/encryption`
- * `@stacks/network`
- * `@stacks/stacking`
- * `@stacks/transactions`
- * `@stacks/bns`
- * `@stacks/common`
- * `@stacks/profile`
- * `@stacks/storage`
- * `@stacks/wallet-sdk`
-
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Conectar billetera](/reference/stacks.js/connect-wallet): Agregar autenticación de billetera
-* [Construir transacciones](/reference/stacks.js/build-transactions): Construir y transmitir transacciones
-:::
-
-:::callout
-type: help
-
-### ¿Necesitas ayuda para construir con Stacks.js?
-
-Contáctenos en el **#stacks-js** canal encendido [Discord](https://stacks.chat/) bajo la sección de Herramientas para Desarrolladores de Hiro. También hay una [horario de oficina semanal](https://www.addevent.com/event/kI22007085) llamada todos los miércoles a la 1 pm ET.
-:::
diff --git a/content/docs/es/reference/stacks.js/meta.json b/content/docs/es/reference/stacks.js/meta.json
deleted file mode 100644
index 61a619baa..000000000
--- a/content/docs/es/reference/stacks.js/meta.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "title": "Stacks.js",
- "root": true,
- "pages": [
- "---Stacks.js---",
- "index",
- "...(overview)",
- "---Local accounts---",
- "...(local-accounts)",
- "---Stacks Connect---",
- "...(connect)",
- "---Post-conditions---",
- "...(post-conditions)",
- "---Integrations---",
- "...(integrations)",
- "---Reference---",
- "...packages"
- ]
-}
diff --git a/content/docs/es/reference/stacks.js/packages/connect.mdx b/content/docs/es/reference/stacks.js/packages/connect.mdx
deleted file mode 100644
index 239abac84..000000000
--- a/content/docs/es/reference/stacks.js/packages/connect.mdx
+++ /dev/null
@@ -1,354 +0,0 @@
----
-title: '@stacks/connect'
-description: Autenticar usuarios e interactuar con billeteras Stacks en aplicaciones web.
----
-El `@stacks/connect` El paquete proporciona una interfaz simple para conectar aplicaciones web a billeteras Stacks, habilitando capacidades de autenticación de usuario, firma de transacciones y firma de mensajes.
-
-## Instalación
-
-```package-install
-@stacks/connect
-```
-
-## Funciones de conexión
-
-### conectar \[#connect]
-
-`connect` inicia una conexión de billetera y almacena las direcciones de usuario en el almacenamiento local.
-
-### Firma
-
-```typescript
-function connect(options?: ConnectOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `options` | `ConnectOptions` | No | Opciones de configuración para la conexión |
-
-### Ejemplos
-
-#### Conexión básica
-
-```typescript
-import { connect } from '@stacks/connect';
-
-const response = await connect();
-// Response contains user addresses stored in local storage
-```
-
-#### Conexión con opciones
-
-```typescript
-const response = await connect({
- forceWalletSelect: true,
- approvedProviderIds: ['LeatherProvider', 'xverse']
-});
-```
-
-### isConnected \[#isConnected]
-
-`isConnected` comprueba si una billetera está actualmente conectada.
-
-```typescript
-import { isConnected } from '@stacks/connect';
-
-if (isConnected()) {
- console.log('Wallet is connected');
-}
-```
-
-### desconectar \[#disconnect]
-
-`disconnect` borra el estado de la conexión y el almacenamiento local.
-
-```typescript
-import { disconnect } from '@stacks/connect';
-
-disconnect(); // Clears wallet connection
-```
-
-### getLocalStorage \[#getLocalStorage]
-
-`getLocalStorage` recupera los datos de conexión almacenados.
-
-```typescript
-import { getLocalStorage } from '@stacks/connect';
-
-const data = getLocalStorage();
-// {
-// "addresses": {
-// "stx": [{ "address": "SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN" }],
-// "btc": [{ "address": "bc1pp3ha248m0mnaevhp0txfxj5xaxmy03h0j7zuj2upg34mt7s7e32q7mdfae" }]
-// }
-// }
-```
-
-## Método de solicitud
-
-### solicitud \[#request]
-
-`request` es el método principal para interactuar con las billeteras conectadas.
-
-### Firma
-
-```typescript
-function request(
- options: RequestOptions | undefined,
- method: T,
- params?: MethodParams[T]
-): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `options` | `RequestOptions` | No | Opciones de configuración de solicitud |
-| `method` | `StacksMethod` | Sí | Método para llamar en la billetera |
-| `params` | `MethodParams[T]` | Depende del método | Parámetros para el método |
-
-### Opciones de solicitud
-
-| Nombre | Tipo | Predeterminado | Descripción |
-|--------|------|----------------|-------------|
-| `provider` | `StacksProvider` | Detección automática | Instancia de proveedor personalizada |
-| `forceWalletSelect` | `boolean` | `false` | Forzar modal de selección de billetera |
-| `persistWalletSelect` | `boolean` | `true` | Mantener selección de billetera |
-| `enableOverrides` | `boolean` | `true` | Habilitar correcciones de compatibilidad |
-| `enableLocalStorage` | `boolean` | `true` | Almacenar direcciones localmente |
-| `approvedProviderIds` | `string[]` | Todos los proveedores | Filtrar billeteras disponibles |
-
-### Ejemplos
-
-#### Solicitud básica
-
-```typescript
-import { request } from '@stacks/connect';
-
-const addresses = await request('getAddresses');
-```
-
-#### Solicitud con opciones
-
-```typescript
-const response = await request(
- { forceWalletSelect: true },
- 'stx_transferStx',
- {
- amount: '1000000', // 1 STX in microSTX
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159'
- }
-);
-```
-
-## Métodos de billetera
-
-### getAddresses \[#getAddresses]
-
-`getAddresses` recupera direcciones de Bitcoin y Stacks de la cartera.
-
-```typescript
-const response = await request('getAddresses');
-// {
-// "addresses": [
-// {
-// "address": "bc1pp3ha248m0mnaevhp0txfxj5xaxmy03h0j7zuj2upg34mt7s7e32q7mdfae",
-// "publicKey": "062bd2c825300d74f4f9feb6b2fec2590beac02b8938f0fc042a34254581ee69"
-// },
-// {
-// "address": "SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN",
-// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cdea520f08c0cc68584a96e8ac19d8d304"
-// }
-// ]
-// }
-```
-
-### sendTransfer \[#sendTransfer]
-
-`sendTransfer` envía Bitcoin a uno o más destinatarios.
-
-```typescript
-const response = await request('sendTransfer', {
- recipients: [
- {
- address: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4',
- amount: '1000' // Amount in satoshis
- },
- {
- address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh',
- amount: '2000'
- }
- ]
-});
-// { "txid": "0x1234..." }
-```
-
-### signPsbt \[#signPsbt]
-
-`signPsbt` firma una transacción de Bitcoin parcialmente firmada.
-
-```typescript
-const response = await request('signPsbt', {
- psbt: 'cHNidP...', // Base64 encoded PSBT
- signInputs: [{ index: 0, address }], // Optional: specify inputs to sign
- broadcast: false // Optional: broadcast after signing
-});
-// {
-// "psbt": "cHNidP...", // Signed PSBT
-// "txid": "0x1234..." // If broadcast is true
-// }
-```
-
-## Métodos específicos de Stacks
-
-### stx\_transferStx \[#stx\_transferStx]
-
-`stx_transferStx` transfiere tokens STX entre direcciones.
-
-```typescript
-const response = await request('stx_transferStx', {
- amount: '1000000', // Amount in microSTX (1 STX = 1,000,000 microSTX)
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- memo: 'Payment for services', // Optional
- network: 'mainnet' // Optional, defaults to mainnet
-});
-// { "txid": "0x1234..." }
-```
-
-### stx\_callContract \[#stx\_callContract]
-
-`stx_callContract` llama a una función pública en un contrato inteligente.
-
-```typescript
-import { Cl } from '@stacks/transactions';
-
-const response = await request('stx_callContract', {
- contract: 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.hello-world',
- functionName: 'say-hi',
- functionArgs: [Cl.stringUtf8('Hello!')],
- network: 'mainnet'
-});
-// { "txid": "0x1234..." }
-```
-
-### stx\_deployContract \[#stx\_deployContract]
-
-`stx_deployContract` despliega un nuevo contrato inteligente.
-
-```typescript
-const response = await request('stx_deployContract', {
- name: 'my-contract',
- clarityCode: `(define-public (say-hi (name (string-utf8 50)))
- (ok (concat "Hello, " name "!"))
- )`,
- clarityVersion: '2', // Optional
- network: 'testnet'
-});
-// { "txid": "0x1234..." }
-```
-
-### stx\_signMessage \[#stx\_signMessage]
-
-`stx_signMessage` firma un mensaje de texto plano.
-
-```typescript
-const response = await request('stx_signMessage', {
- message: 'Hello, World!'
-});
-// {
-// "signature": "0x1234...",
-// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cdea520f08c0cc68584a96e8ac19d8d304"
-// }
-```
-
-### stx\_signStructuredMessage \[#stx\_signStructuredMessage]
-
-`stx_signStructuredMessage` firma un mensaje estructurado de Clarity siguiendo SIP-018.
-
-```typescript
-import { Cl } from '@stacks/transactions';
-
-const message = Cl.tuple({
- action: Cl.stringAscii('transfer'),
- amount: Cl.uint(1000000n)
-});
-
-const domain = Cl.tuple({
- name: Cl.stringAscii('MyApp'),
- version: Cl.stringAscii('1.0.0'),
- 'chain-id': Cl.uint(1) // mainnet
-});
-
-const response = await request('stx_signStructuredMessage', {
- message,
- domain
-});
-// {
-// "signature": "0x1234...",
-// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cdea520f08c0cc68584a96e8ac19d8d304"
-// }
-```
-
-### stx\_getAccounts \[#stx\_getAccounts]
-
-`stx_getAccounts` recupera información detallada de la cuenta, incluyendo la configuración de Gaia.
-
-```typescript
-const response = await request('stx_getAccounts');
-// {
-// "addresses": [{
-// "address": "SP2MF04VAGYHGAZWGTEDW5VYCPDWWSY08Z1QFNDSN",
-// "publicKey": "02d3331cbb9f72fe635e6f87c2cf1a13cd...",
-// "gaiaHubUrl": "https://hub.hiro.so",
-// "gaiaAppKey": "0488ade4040658015580000000dc81e3a5..."
-// }]
-// }
-```
-
-## Manejo de errores
-
-Maneja los errores de la billetera utilizando patrones estándar de manejo de errores de Promesas.
-
-```typescript
-try {
- const response = await request('stx_transferStx', {
- amount: '1000000',
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159'
- });
- console.log('Transaction successful:', response.txid);
-} catch (error) {
- console.error('Transaction failed:', error);
-}
-```
-
-## Uso avanzado
-
-### requestRaw \[#requestRaw]
-
-`requestRaw` proporciona acceso directo a los proveedores de billeteras sin características de compatibilidad.
-
-### Firma
-
-```typescript
-function requestRaw(
- provider: StacksProvider,
- method: T,
- params?: MethodParams[T]
-): Promise
-```
-
-### Ejemplo
-
-```typescript
-import { requestRaw } from '@stacks/connect';
-
-const provider = window.StacksProvider;
-const response = await requestRaw(provider, 'getAddresses');
-```
-
-## Notas de migración
-
-La versión 8.x.x implementa [SIP-030](https://github.com/janniks/sips/blob/main/sips/sip-030/sip-030-wallet-interface.md) estándares de billetera. Para la autenticación heredada basada en JWT, use la versión 7.10.1.
diff --git a/content/docs/es/reference/stacks.js/packages/network.mdx b/content/docs/es/reference/stacks.js/packages/network.mdx
deleted file mode 100644
index 8499ce277..000000000
--- a/content/docs/es/reference/stacks.js/packages/network.mdx
+++ /dev/null
@@ -1,162 +0,0 @@
----
-title: '@stacks/network'
-description: Constantes y utilidades de configuración de red para Stacks.
----
-El `@stacks/network` El paquete exporta configuraciones de red y funciones auxiliares para trabajar con diferentes redes de Stacks.
-
-## Instalación
-
-```package-install
-@stacks/network
-```
-
-## Constantes de red
-
-### STACKS\_MAINNET
-
-`STACKS_MAINNET` proporciona la configuración de la red mainnet.
-
-```typescript
-import { STACKS_MAINNET } from '@stacks/network';
-
-console.log(STACKS_MAINNET);
-// {
-// chainId: 1,
-// transactionVersion: 0,
-// peerNetworkId: 385875968,
-// magicBytes: "X2",
-// bootAddress: "SP000000000000000000002Q6VF78",
-// addressVersion: {
-// singleSig: 22,
-// multiSig: 20,
-// },
-// client: {
-// baseUrl: "https://api.mainnet.hiro.so",
-// },
-// }
-```
-
-### STACKS\_TESTNET
-
-`STACKS_TESTNET` proporciona la configuración de la red testnet.
-
-```typescript
-import { STACKS_TESTNET } from '@stacks/network';
-
-console.log(STACKS_TESTNET.chainId); // 2147483648
-```
-
-### STACKS\_DEVNET / STACKS\_MOCKNET
-
-`STACKS_DEVNET` proporciona la configuración de red devnet.
-
-```typescript
-import { STACKS_DEVNET, STACKS_MOCKNET } from '@stacks/network';
-
-// Use in transactions
-import { makeSTXTokenTransfer } from '@stacks/transactions';
-
-const tx = await makeSTXTokenTransfer({
- network: STACKS_DEVNET, // or STACKS_MOCKNET
- // ... other options
-});
-```
-
-## networkFromName \[#networkFromName]
-
-`networkFromName` devuelve una configuración de red para una cadena de nombre dada.
-
-### Firma
-
-```typescript
-function networkFromName(name: 'mainnet' | 'testnet' | 'devnet' | 'mocknet'): StacksNetwork
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `name` | `'mainnet' \| 'testnet' \| 'devnet' \| 'mocknet'` | Sí | Nombre de la red |
-
-### Ejemplos
-
-```typescript
-import { networkFromName } from '@stacks/network';
-
-const mainnet = networkFromName('mainnet'); // Same as STACKS_MAINNET
-const testnet = networkFromName('testnet'); // Same as STACKS_TESTNET
-const devnet = networkFromName('devnet'); // Same as STACKS_DEVNET
-const mocknet = networkFromName('mocknet'); // Same as STACKS_MOCKNET
-```
-
-### Uso con transacciones
-
-```typescript
-import { networkFromName } from '@stacks/network';
-import { makeContractCall } from '@stacks/transactions';
-
-const network = networkFromName('testnet');
-
-const tx = await makeContractCall({
- network,
- contractAddress: 'ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH',
- contractName: 'hello-world',
- functionName: 'say-hi',
- functionArgs: [],
- senderKey: privateKey
-});
-```
-
-## clienteDeRed \[#clienteDeRed]
-
-`clientFromNetwork` extrae la configuración del cliente de API de una red.
-
-### Firma
-
-```typescript
-function clientFromNetwork(network: StacksNetwork): Required
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `network` | `StacksNetwork` | Sí | Objeto de configuración de red |
-
-### Ejemplo
-
-```typescript
-import { clientFromNetwork, STACKS_MAINNET } from '@stacks/network';
-
-const client = clientFromNetwork(STACKS_MAINNET);
-console.log(client.baseUrl); // 'https://api.mainnet.hiro.so'
-
-// Use with custom fetch
-const customClient = {
- ...client,
- fetch: customFetchFunction
-};
-```
-
-## Propiedades de configuración de red
-
-Todas las constantes de red comparten estas propiedades:
-
-| Propiedad | Tipo | Descripción |
-|-----------|------|-------------|
-| `chainId` | número | Identificador único para la red |
-| `transactionVersion` | número | Versión de serialización de transacción |
-| `peerNetworkId` | número | identificador de red P2P |
-| `magicBytes` | cadena | Bytes mágicos de red para serialización |
-| `bootAddress` | cadena | Dirección del contrato de arranque |
-
-## Valores predeterminados
-
-El paquete también exporta valores de configuración predeterminados:
-
-```typescript
-import { DEFAULT_CHAIN_ID, DEFAULT_TRANSACTION_VERSION } from '@stacks/network';
-
-console.log(DEFAULT_CHAIN_ID); // 1
-console.log(DEFAULT_TRANSACTION_VERSION); // 0
-```
diff --git a/content/docs/es/reference/stacks.js/packages/sbtc.mdx b/content/docs/es/reference/stacks.js/packages/sbtc.mdx
deleted file mode 100644
index 459bb95d7..000000000
--- a/content/docs/es/reference/stacks.js/packages/sbtc.mdx
+++ /dev/null
@@ -1,321 +0,0 @@
----
-title: 'sbtc'
-description: Construye y gestiona depósitos y retiros de sBTC en Bitcoin y Stacks.
----
-El `sbtc` El paquete proporciona funciones para crear depósitos de sBTC en Bitcoin e interactuar con el protocolo sBTC a través de las redes de Bitcoin y Stacks.
-
-## Instalación
-
-```package-install
-sbtc
-```
-
-## Funciones de depósito
-
-### buildSbtcDepositAddress \[#buildSbtcDepositAddress]
-
-`buildSbtcDepositAddress` crea una dirección de Bitcoin para depósitos de sBTC con metadatos incorporados.
-
-### Firma
-
-```typescript
-function buildSbtcDepositAddress(options: DepositAddressOptions): DepositAddress
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `stacksAddress` | `string` | Sí | Dirección de Stacks para recibir sBTC |
-| `signersPublicKey` | `string` | Sí | Clave pública agregada de los firmantes |
-| `maxSignerFee` | `number` | No | Tarifa máxima para firmantes (predeterminado: 80,000 sats) |
-| `reclaimLockTime` | `number` | No | Tiempo de bloqueo para el script de recuperación (predeterminado: 6.000) |
-| `network` | `BitcoinNetwork` | No | Red de Bitcoin a utilizar (predeterminado: MAINNET) |
-
-### Ejemplo
-
-```typescript
-import { buildSbtcDepositAddress, SbtcApiClientMainnet } from 'sbtc';
-
-const client = new SbtcApiClientMainnet();
-
-// Build deposit address
-const deposit = buildSbtcDepositAddress({
- stacksAddress: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- signersPublicKey: await client.fetchSignersPublicKey(),
- maxSignerFee: 80_000, // Fee taken from deposit amount
- reclaimLockTime: 6_000
-});
-
-// Send BTC to deposit.address using any Bitcoin wallet
-const txid = await wallet.sendTransfer({
- recipient: deposit.address,
- amount: 1_000_000 // 0.01 BTC
-});
-
-// Notify signers about the deposit
-await client.notifySbtc({ txid, ...deposit });
-```
-
-### buildSbtcDepositTx \[#buildSbtcDepositTx]
-
-`buildSbtcDepositTx` crea una transacción completa de Bitcoin para depósitos de sBTC.
-
-### Firma
-
-```typescript
-function buildSbtcDepositTx(options: DepositTxOptions): DepositTransaction
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `amountSats` | `number \| bigint` | Sí | Cantidad a depositar en satoshis |
-| `stacksAddress` | `string` | Sí | Dirección de Stacks para recibir sBTC |
-| `signersPublicKey` | `string` | Sí | Clave pública agregada de los firmantes |
-| `maxSignerFee` | `number` | No | Tarifa máxima para firmantes (predeterminado: 80,000 sats) |
-| `reclaimLockTime` | `number` | No | Tiempo de bloqueo para el script de recuperación (predeterminado: 144) |
-| `network` | `BitcoinNetwork` | No | Red de Bitcoin a utilizar |
-
-### Ejemplo
-
-```typescript
-import { buildSbtcDepositTx, SbtcApiClientMainnet } from 'sbtc';
-
-const client = new SbtcApiClientMainnet();
-
-// Build deposit transaction
-const deposit = buildSbtcDepositTx({
- amountSats: 100_000,
- stacksAddress: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- signersPublicKey: await client.fetchSignersPublicKey()
-});
-
-// Sign transaction
-deposit.transaction.sign(privateKey);
-deposit.transaction.finalize();
-
-// Broadcast and notify
-const txid = await client.broadcastTx(deposit.transaction);
-await client.notifySbtc(deposit);
-```
-
-### sbtcDepositHelper \[#sbtcDepositHelper]
-
-`sbtcDepositHelper` crea una transacción de depósito completamente formada a partir de UTXOs.
-
-### Firma
-
-```typescript
-function sbtcDepositHelper(options: DepositHelperOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `amountSats` | `number \| bigint` | Sí | Cantidad a depositar en satoshis |
-| `stacksAddress` | `string` | Sí | Dirección de Stacks para recibir sBTC |
-| `signersPublicKey` | `string` | Sí | Clave pública agregada de los firmantes |
-| `feeRate` | `number` | Sí | Tasa de comisión en sat/vbyte |
-| `utxos` | `UtxoWithTx[]` | Sí | UTXOs para financiar la transacción |
-| `bitcoinChangeAddress` | `string` | Sí | Dirección para el cambio de salida |
-| `reclaimPublicKey` | `string` | No | Clave pública para reclamar depósitos |
-| `reclaimLockTime` | `number` | No | Tiempo de bloqueo para reclamar (predeterminado: 144) |
-| `maxSignerFee` | `number` | No | Tarifa máxima del firmante (predeterminado: 80,000) |
-| `network` | `BitcoinNetwork` | No | Red de Bitcoin (predeterminado: MAINNET) |
-
-### Ejemplo
-
-```typescript
-import { sbtcDepositHelper, SbtcApiClientMainnet } from 'sbtc';
-
-const client = new SbtcApiClientMainnet();
-const btcAddress = 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4';
-
-// Create complete deposit transaction
-const deposit = await sbtcDepositHelper({
- amountSats: 1_000_000,
- stacksAddress: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- signersPublicKey: await client.fetchSignersPublicKey(),
- feeRate: await client.fetchFeeRate('medium'),
- utxos: await client.fetchUtxos(btcAddress),
- bitcoinChangeAddress: btcAddress
-});
-
-// Sign and broadcast
-deposit.transaction.sign(privateKey);
-deposit.transaction.finalize();
-
-const txid = await client.broadcastTx(deposit.transaction);
-await client.notifySbtc(deposit);
-```
-
-## Clientes de API
-
-### SbtcApiClientMainnet
-
-`SbtcApiClientMainnet` proporciona acceso a la API de la red principal para operaciones de sBTC.
-
-```typescript
-import { SbtcApiClientMainnet } from 'sbtc';
-
-const client = new SbtcApiClientMainnet();
-```
-
-### SbtcApiClientTestnet
-
-`SbtcApiClientTestnet` proporciona acceso a la API de testnet para operaciones de sBTC.
-
-```typescript
-import { SbtcApiClientTestnet } from 'sbtc';
-
-const client = new SbtcApiClientTestnet();
-```
-
-### SbtcApiClientDevenv
-
-`SbtcApiClientDevenv` proporciona acceso a la API de desarrollo local.
-
-```typescript
-import { SbtcApiClientDevenv } from 'sbtc';
-
-const client = new SbtcApiClientDevenv();
-```
-
-## Métodos del cliente
-
-### fetchSignersPublicKey \[#fetchSignersPublicKey]
-
-`fetchSignersPublicKey` recupera la clave pública agregada de los firmantes de sBTC.
-
-```typescript
-const publicKey = await client.fetchSignersPublicKey();
-// '02abc123...' (32-byte hex string)
-```
-
-### fetchSignersAddress \[#fetchSignersAddress]
-
-`fetchSignersAddress` recupera la dirección de Bitcoin de los firmantes de sBTC.
-
-```typescript
-const address = await client.fetchSignersAddress();
-// 'bc1p...' (p2tr address)
-```
-
-### fetchFeeRate \[#fetchFeeRate]
-
-`fetchFeeRate` recupera las tarifas actuales de la red Bitcoin.
-
-```typescript
-const feeRate = await client.fetchFeeRate('medium');
-// 15 (sat/vbyte)
-
-// Also supports 'low' and 'high'
-const lowFee = await client.fetchFeeRate('low');
-const highFee = await client.fetchFeeRate('high');
-```
-
-### fetchUtxos \[#fetchUtxos]
-
-`fetchUtxos` recupera las salidas de transacciones no gastadas para una dirección de Bitcoin.
-
-```typescript
-const utxos = await client.fetchUtxos('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4');
-// Array of UTXOs with transaction data
-```
-
-### broadcastTx \[#broadcastTx]
-
-`broadcastTx` transmite una transacción de Bitcoin a la red.
-
-```typescript
-const txid = await client.broadcastTx(transaction);
-// '0x1234abcd...'
-```
-
-### notificarSbtc \[#notifySbtc]
-
-`notifySbtc` notifica a la API de sBTC sobre una transacción de depósito.
-
-```typescript
-const response = await client.notifySbtc({
- txid,
- stacksAddress,
- reclaimScript,
- depositScript
-});
-// { status: 200, statusMessage: 'OK' }
-```
-
-### fetchSbtcBalance \[#fetchSbtcBalance]
-
-`fetchSbtcBalance` recupera el saldo de sBTC para una dirección de Stacks.
-
-```typescript
-const balance = await client.fetchSbtcBalance('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159');
-// 1000000n (in micro-sBTC)
-```
-
-## Configuración
-
-### Opciones de configuración del cliente
-
-| Nombre | Tipo | Descripción |
-|--------|------|-------------|
-| `sbtcContract` | `string` | Dirección del contrato sBTC |
-| `sbtcApiUrl` | `string` | URL base de la API de sBTC (Emily) |
-| `btcApiUrl` | `string` | URL base de la API de Bitcoin |
-| `stxApiUrl` | `string` | URL base de la API de Stacks |
-
-### Configuración personalizada del cliente
-
-```typescript
-import { SbtcApiClient } from 'sbtc';
-
-const client = new SbtcApiClient({
- sbtcContract: 'SP000000000000000000002Q6VF78.sbtc',
- sbtcApiUrl: 'https://api.sbtc.tech',
- btcApiUrl: 'https://mempool.space/api',
- stxApiUrl: 'https://api.mainnet.hiro.so'
-});
-```
-
-## Ejemplo completo de depósito
-
-```typescript
-import { sbtcDepositHelper, SbtcApiClientMainnet } from 'sbtc';
-
-async function depositBtcForSbtc() {
- const client = new SbtcApiClientMainnet();
- const btcAddress = 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4';
- const stxAddress = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
-
- // 1. Create deposit transaction
- const deposit = await sbtcDepositHelper({
- amountSats: 100_000,
- stacksAddress: stxAddress,
- signersPublicKey: await client.fetchSignersPublicKey(),
- feeRate: await client.fetchFeeRate('medium'),
- utxos: await client.fetchUtxos(btcAddress),
- bitcoinChangeAddress: btcAddress
- });
-
- // 2. Sign transaction
- deposit.transaction.sign(privateKey);
- deposit.transaction.finalize();
-
- // 3. Broadcast to Bitcoin network
- const txid = await client.broadcastTx(deposit.transaction);
- console.log('Bitcoin transaction:', txid);
-
- // 4. Notify sBTC signers
- await client.notifySbtc(deposit);
- console.log('Deposit submitted successfully');
-
- // 5. Check sBTC balance (after confirmation)
- const balance = await client.fetchSbtcBalance(stxAddress);
- console.log('sBTC balance:', balance);
-}
-```
diff --git a/content/docs/es/reference/stacks.js/packages/transactions.mdx b/content/docs/es/reference/stacks.js/packages/transactions.mdx
deleted file mode 100644
index 0d8282277..000000000
--- a/content/docs/es/reference/stacks.js/packages/transactions.mdx
+++ /dev/null
@@ -1,524 +0,0 @@
----
-title: '@stacks/transactions'
-description: Construye, decodifica y transmite transacciones para la cadena de bloques Stacks.
----
-El `@stacks/transactions` El paquete proporciona funcionalidad integral para crear, firmar y transmitir transacciones en la cadena de bloques de Stacks, incluyendo transferencias de STX, implementaciones de contratos y llamadas a contratos.
-
-## Instalación
-
-```package-install
-@stacks/transactions
-```
-
-## Funciones de transacción
-
-### makeSTXTokenTransfer \[#makeSTXTokenTransfer]
-
-`makeSTXTokenTransfer` crea una transacción de transferencia de tokens STX firmada.
-
-### Firma
-
-```typescript
-function makeSTXTokenTransfer(options: SignedTokenTransferOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `recipient` | `string` | Sí | Dirección STX del destinatario |
-| `amount` | `bigint` | Sí | Cantidad a transferir en microSTX |
-| `senderKey` | `string` | Sí | Clave privada del remitente |
-| `network` | `StacksNetwork \| string` | Sí | Configuración de red |
-| `memo` | `string` | No | Campo de memo opcional |
-| `fee` | `bigint` | No | Tarifa de transacción en microSTX |
-| `nonce` | `bigint` | No | Nonce de cuenta |
-| `anchorMode` | `AnchorMode` | No | Modo de anclaje de bloques |
-
-### Ejemplos
-
-#### Transferencia básica
-
-```typescript
-import { makeSTXTokenTransfer, broadcastTransaction } from '@stacks/transactions';
-
-const transaction = await makeSTXTokenTransfer({
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- amount: 1000000n, // 1 STX in microSTX
- senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01',
- network: 'mainnet'
-});
-
-const response = await broadcastTransaction({ transaction, network: 'mainnet' });
-console.log(response.txid);
-```
-
-#### Transferencia con memo
-
-```typescript
-const transaction = await makeSTXTokenTransfer({
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- amount: 2500000n,
- memo: 'Payment for services',
- senderKey: privateKey,
- network: 'testnet'
-});
-```
-
-### makeUnsignedSTXTokenTransfer \[#makeUnsignedSTXTokenTransfer]
-
-`makeUnsignedSTXTokenTransfer` crea una transacción de transferencia de tokens STX sin firmar.
-
-### Firma
-
-```typescript
-function makeUnsignedSTXTokenTransfer(options: UnsignedTokenTransferOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `recipient` | `string` | Sí | Dirección STX del destinatario |
-| `amount` | `bigint` | Sí | Cantidad a transferir en microSTX |
-| `publicKey` | `string` | Sí | Clave pública del remitente |
-| `network` | `StacksNetwork \| string` | Sí | Configuración de red |
-| `memo` | `string` | No | Campo de memo opcional |
-| `fee` | `bigint` | No | Tarifa de transacción en microSTX |
-| `nonce` | `bigint` | No | Nonce de cuenta |
-
-### Ejemplo
-
-```typescript
-import { makeUnsignedSTXTokenTransfer } from '@stacks/transactions';
-
-const unsignedTx = await makeUnsignedSTXTokenTransfer({
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- amount: 1000000n,
- publicKey: publicKeyString,
- network: 'mainnet'
-});
-```
-
-### makeContractDeploy \[#makeContractDeploy]
-
-`makeContractDeploy` crea una transacción de despliegue de contrato inteligente firmada.
-
-### Firma
-
-```typescript
-function makeContractDeploy(options: SignedContractDeployOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `contractName` | `string` | Sí | Nombre para el contrato |
-| `codeBody` | `string` | Sí | Código fuente del contrato Clarity |
-| `senderKey` | `string` | Sí | Clave privada del implementador |
-| `network` | `StacksNetwork \| string` | Sí | Configuración de red |
-| `clarityVersion` | `ClarityVersion` | No | Versión de Clarity (por defecto la más reciente) |
-| `fee` | `bigint` | No | Tarifa de transacción en microSTX |
-| `nonce` | `bigint` | No | Nonce de cuenta |
-
-### Ejemplos
-
-#### Desplegar un contrato
-
-```typescript
-import { makeContractDeploy, broadcastTransaction } from '@stacks/transactions';
-import { readFileSync } from 'fs';
-
-const codeBody = readFileSync('./contract.clar', 'utf-8');
-
-const transaction = await makeContractDeploy({
- contractName: 'my-contract',
- codeBody,
- senderKey: privateKey,
- network: 'testnet'
-});
-
-const response = await broadcastTransaction({ transaction, network: 'testnet' });
-```
-
-#### Implementar con la versión de Clarity
-
-```typescript
-const transaction = await makeContractDeploy({
- contractName: 'clarity-v3-contract',
- codeBody: contractCode,
- clarityVersion: 3,
- senderKey: privateKey,
- network: 'mainnet'
-});
-```
-
-### makeContractCall \[#makeContractCall]
-
-`makeContractCall` crea una transacción de llamada de función de contrato firmada.
-
-### Firma
-
-```typescript
-function makeContractCall(options: SignedContractCallOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `contractAddress` | `string` | Sí | Dirección del contrato |
-| `contractName` | `string` | Sí | Nombre del contrato |
-| `functionName` | `string` | Sí | Función a llamar |
-| `functionArgs` | `ClarityValue[]` | Sí | Argumentos de función |
-| `senderKey` | `string` | Sí | Clave privada del llamante |
-| `network` | `StacksNetwork \| string` | Sí | Configuración de red |
-| `postConditions` | `PostCondition[]` | No | Condiciones posteriores |
-| `validateWithAbi` | `boolean \| ClarityAbi` | No | Validar argumentos contra ABI |
-| `fee` | `bigint` | No | Tarifa de transacción en microSTX |
-| `nonce` | `bigint` | No | Nonce de cuenta |
-
-### Ejemplos
-
-#### Llamada básica a contrato
-
-```typescript
-import { makeContractCall, broadcastTransaction, Cl } from '@stacks/transactions';
-
-const transaction = await makeContractCall({
- contractAddress: 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR',
- contractName: 'hello-world',
- functionName: 'say-hi',
- functionArgs: [Cl.stringUtf8('Hello!')],
- senderKey: privateKey,
- network: 'testnet'
-});
-
-const response = await broadcastTransaction({ transaction, network: 'testnet' });
-```
-
-#### Llamada con condiciones posteriores
-
-```typescript
-import { makeContractCall, Cl, Pc } from '@stacks/transactions';
-
-const postCondition = Pc.principal('SP2ZD731ANQZT6J4K3F5N8A40ZXWXC1XFXHVVQFKE')
- .willSendLte(1000000n)
- .ustx();
-
-const transaction = await makeContractCall({
- contractAddress: 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR',
- contractName: 'token-contract',
- functionName: 'transfer',
- functionArgs: [
- Cl.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159'),
- Cl.uint(100n)
- ],
- postConditions: [postCondition],
- validateWithAbi: true,
- senderKey: privateKey,
- network: 'mainnet'
-});
-```
-
-### sponsorTransaction \[#sponsorTransaction]
-
-`sponsorTransaction` agrega una firma de patrocinador a una transacción, permitiendo transacciones patrocinadas.
-
-### Firma
-
-```typescript
-function sponsorTransaction(options: SponsorTransactionOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `transaction` | `StacksTransaction` | Sí | Transacción a patrocinar |
-| `sponsorPrivateKey` | `string` | Sí | Clave privada del patrocinador |
-| `fee` | `bigint` | Sí | Tarifa a ser pagada por el patrocinador |
-| `sponsorNonce` | `bigint` | No | Nonce de la cuenta del patrocinador |
-
-### Ejemplo
-
-```typescript
-import { sponsorTransaction, deserializeTransaction, broadcastTransaction } from '@stacks/transactions';
-
-// Deserialize the transaction from the origin
-const deserializedTx = deserializeTransaction(serializedTx);
-
-// Sponsor the transaction
-const sponsoredTx = await sponsorTransaction({
- transaction: deserializedTx,
- sponsorPrivateKey: sponsorKey,
- fee: 1000n,
- sponsorNonce: 0
-});
-
-const response = await broadcastTransaction({ transaction: sponsoredTx, network: 'testnet' });
-```
-
-### fetchCallReadOnlyFunction \[#fetchCallReadOnlyFunction]
-
-`fetchCallReadOnlyFunction` llama a una función de contrato de solo lectura sin crear una transacción.
-
-### Firma
-
-```typescript
-function fetchCallReadOnlyFunction(options: CallReadOnlyFunctionOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `contractAddress` | `string` | Sí | Dirección del contrato |
-| `contractName` | `string` | Sí | Nombre del contrato |
-| `functionName` | `string` | Sí | Función a llamar |
-| `functionArgs` | `ClarityValue[]` | Sí | Argumentos de función |
-| `network` | `StacksNetwork` | Sí | Configuración de red |
-| `senderAddress` | `string` | Sí | Dirección del llamante |
-
-### Ejemplo
-
-```typescript
-import { fetchCallReadOnlyFunction, Cl } from '@stacks/transactions';
-import { STACKS_MAINNET } from '@stacks/network';
-
-const result = await fetchCallReadOnlyFunction({
- contractAddress: 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR',
- contractName: 'data-store',
- functionName: 'get-value',
- functionArgs: [Cl.stringUtf8('key')],
- network: STACKS_MAINNET,
- senderAddress: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159'
-});
-
-console.log(result);
-```
-
-### broadcastTransaction \[#broadcastTransaction]
-
-`broadcastTransaction` transmite una transacción firmada a la red.
-
-### Firma
-
-```typescript
-function broadcastTransaction(options: BroadcastTransactionOptions): Promise
-```
-
-### Parámetros
-
-| Nombre | Tipo | Obligatorio | Descripción |
-|--------|------|-------------|-------------|
-| `transaction` | `StacksTransaction` | Sí | Transacción firmada para transmitir |
-| `network` | `StacksNetwork \| string` | Sí | Red a la que transmitir |
-
-### Ejemplo
-
-```typescript
-import { broadcastTransaction } from '@stacks/transactions';
-
-const result = await broadcastTransaction({
- transaction: signedTx,
- network: 'mainnet'
-});
-
-if (result.error) {
- console.error('Broadcast failed:', result.reason);
-} else {
- console.log('Transaction ID:', result.txid);
-}
-```
-
-## Construcción de valor de claridad
-
-### Valores primitivos
-
-```typescript
-import { Cl } from '@stacks/transactions';
-
-// Boolean values
-const isTrue = Cl.bool(true);
-const isFalse = Cl.bool(false);
-
-// Integer values (signed 128-bit)
-const positiveInt = Cl.int(42n);
-const negativeInt = Cl.int(-100n);
-
-// Unsigned integer values (unsigned 128-bit)
-const unsignedInt = Cl.uint(100n);
-
-// Buffer values
-const buffer = Cl.bufferFromUtf8('hello world');
-const hexBuffer = Cl.bufferFromHex('0x1234');
-
-// String values
-const asciiStr = Cl.stringAscii('Hello ASCII');
-const utf8Str = Cl.stringUtf8('Hello UTF-8! 👋');
-```
-
-### Valores complejos
-
-```typescript
-// Principal values
-const standardPrincipal = Cl.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159');
-const contractPrincipal = Cl.contractPrincipal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', 'my-contract');
-
-// Optional values
-const none = Cl.none();
-const some = Cl.some(Cl.uint(42n));
-
-// Response values
-const okResponse = Cl.ok(Cl.stringUtf8('Success'));
-const errResponse = Cl.error(Cl.uint(404n));
-
-// Tuple values
-const tuple = Cl.tuple({
- name: Cl.stringUtf8('Alice'),
- age: Cl.uint(30n),
- active: Cl.bool(true)
-});
-
-// List values
-const list = Cl.list([Cl.uint(1n), Cl.uint(2n), Cl.uint(3n)]);
-```
-
-## Postcondiciones
-
-### Condiciones posteriores de STX
-
-```typescript
-import { Pc } from '@stacks/transactions';
-
-// Standard principal STX post condition
-const stxPostCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159')
- .willSendGte(1000000n)
- .ustx();
-
-// Contract principal STX post condition
-const contractStxCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159.my-contract')
- .willSendEq(500000n)
- .ustx();
-```
-
-### Condiciones posteriores de tokens fungibles
-
-```typescript
-// Standard principal fungible token post condition
-const ftPostCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159')
- .willSendLte(100n)
- .ft('SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.token-contract', 'my-token');
-
-// Contract principal fungible token post condition
-const contractFtCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159.vault')
- .willNotSend()
- .ft('SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.token-contract', 'my-token');
-```
-
-### Condiciones posteriores de tokens no fungibles
-
-```typescript
-// Standard principal NFT post condition
-const nftPostCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159')
- .willSend()
- .nft('SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.nft-contract', 'my-nft', Cl.uint(1n));
-
-// Contract principal NFT post condition
-const contractNftCondition = Pc.principal('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159.marketplace')
- .willNotSend()
- .nft('SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.nft-contract', 'my-nft', Cl.uint(1n));
-```
-
-## Transacciones de firma múltiple
-
-Las transacciones de firma múltiple requieren múltiples firmas antes de ser transmitidas.
-
-```typescript
-import {
- makeUnsignedSTXTokenTransfer,
- createStacksPrivateKey,
- deserializeTransaction,
- pubKeyfromPrivKey,
- publicKeyToString,
- TransactionSigner,
- BytesReader
-} from '@stacks/transactions';
-
-// Create unsigned multi-sig transaction
-const transaction = await makeUnsignedSTXTokenTransfer({
- recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159',
- amount: 1000000n,
- fee: 200n,
- numSignatures: 2, // Require 2 of 3 signatures
- publicKeys: [publicKey1, publicKey2, publicKey3],
- network: 'mainnet'
-});
-
-// Sign with multiple parties
-const deserializedTx = deserializeTransaction(transaction.serialize());
-const signer = new TransactionSigner(deserializedTx);
-
-// Add required signatures
-signer.signOrigin(privateKey1);
-signer.signOrigin(privateKey2);
-
-// Append public key of non-signing party
-signer.appendOrigin(publicKey3);
-
-// Broadcast the multi-sig transaction
-const signedTx = deserializedTx;
-const response = await broadcastTransaction({ transaction: signedTx, network: 'mainnet' });
-```
-
-## Utilidades de generación de claves
-
-### randomPrivateKey \[#randomPrivateKey]
-
-`randomPrivateKey` genera una nueva clave privada aleatoria.
-
-```typescript
-import { randomPrivateKey } from '@stacks/transactions';
-
-const privateKey = randomPrivateKey();
-console.log(privateKey); // Random 32-byte hex string with optional compression flag
-```
-
-### privateKeyToPublicKey \[#privateKeyToPublicKey]
-
-`privateKeyToPublicKey` deriva una clave pública a partir de una clave privada.
-
-```typescript
-import { privateKeyToPublicKey } from '@stacks/transactions';
-
-const privateKey = 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01';
-const publicKey = privateKeyToPublicKey(privateKey);
-console.log(publicKey); // Compressed public key
-```
-
-## Funciones de utilidad
-
-### deserializarTransacción \[#deserializeTransaction]
-
-`deserializeTransaction` convierte una transacción serializada de vuelta a un objeto de transacción.
-
-```typescript
-import { deserializeTransaction } from '@stacks/transactions';
-
-const serializedTx = '0x00000000...'; // Hex string
-const transaction = deserializeTransaction(serializedTx);
-```
-
-### cvToJSON \[#cvToJSON]
-
-`cvToJSON` convierte valores de Clarity a formato JSON para una manipulación más fácil.
-
-```typescript
-import { cvToJSON, hexToCV } from '@stacks/transactions';
-
-const clarityValue = hexToCV('0x0100000000000000000000000000000001');
-const json = cvToJSON(clarityValue);
-console.log(json); // { type: 'uint', value: '1' }
-```
diff --git a/content/docs/es/resources/clarity/(integrations)/external-data.mdx b/content/docs/es/resources/clarity/(integrations)/external-data.mdx
deleted file mode 100644
index cdd433463..000000000
--- a/content/docs/es/resources/clarity/(integrations)/external-data.mdx
+++ /dev/null
@@ -1,222 +0,0 @@
----
-title: Uso de datos del oráculo Pyth
-sidebarTitle: Integración de Oracle
-description: En esta guía, aprenderás cómo leer datos de precios en tiempo real del oráculo descentralizado de Pyth Network en tus contratos de Clarity.
----
-:::objectives
-* Comprender el modelo de oráculo basado en extracción de Pyth
-* Leer y procesar datos de alimentación de precios
-* Trabajar con representación de precios de punto fijo
-* Construir contratos inteligentes denominados en USD
-:::
-
-:::prerequisites
-* Comprensión básica de los contratos inteligentes de Clarity
-* Un proyecto de Clarinet configurado para desarrollo local
-:::
-
-## Entendiendo los oráculos de Pyth
-
-Pyth Network utiliza una **basado en pull** modelo de oráculo, diferente de los oráculos tradicionales basados en push:
-
-* **Modelo push**: Oracle envía continuamente actualizaciones de precios en la cadena
-* **Modelo de extracción**: Los usuarios obtienen y envían actualizaciones de precios cuando es necesario
-
-Este enfoque es más eficiente en cuanto al gas y permite actualizaciones de precios con mayor frecuencia.
-
-### Fuentes de precios admitidas
-
-La integración de Pyth en Stacks actualmente admite estos feeds de precios:
-
-| Activo | ID del Feed de Precios | Enlace del Explorador |
-|-------|--------------|---------------|
-| BTC/USD | `0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43` | [Ver](https://www.pyth.network/price-feeds/crypto-btc-usd) |
-| STX/USD | `0xec7a775f46379b5e943c3526b1c8d54cd49749176b0b98e02dde68d1bd335c17` | [Ver](https://www.pyth.network/price-feeds/crypto-stx-usd) |
-| ETH/USD | `0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace` | [Ver](https://www.pyth.network/price-feeds/crypto-eth-usd) |
-| USDC/USD | `0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a` | [Ver](https://www.pyth.network/price-feeds/crypto-usdc-usd) |
-
-## Inicio rápido
-
-
-
- ### Configurar referencias de contratos
-
- El oráculo Pyth en Stacks consta de varios contratos. Agregue estas referencias a su contrato:
-
- ```clarity
- ;; Pyth oracle contract addresses (mainnet)
- (define-constant PYTH-ORACLE-CONTRACT 'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-oracle-v3)
- (define-constant PYTH-STORAGE-CONTRACT 'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3)
- (define-constant PYTH-DECODER-CONTRACT 'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-pnau-decoder-v2)
- (define-constant WORMHOLE-CORE-CONTRACT 'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.wormhole-core-v3)
-
- ;; Price feed IDs
- (define-constant BTC-USD-FEED-ID 0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43)
- ```
-
-
-
- ### Actualizar y leer datos de precios
-
- Crear una función que actualice el feed de precios y lea el precio actual:
-
- ```clarity
- (define-public (get-btc-price (price-feed-bytes (buff 8192)))
- (let (
- ;; Update the price feed with fresh data
- (update-result (try! (contract-call? PYTH-ORACLE-CONTRACT
- verify-and-update-price-feeds price-feed-bytes {
- pyth-storage-contract: PYTH-STORAGE-CONTRACT,
- pyth-decoder-contract: PYTH-DECODER-CONTRACT,
- wormhole-core-contract: WORMHOLE-CORE-CONTRACT
- })))
-
- ;; Read the updated price
- (price-data (try! (contract-call? PYTH-ORACLE-CONTRACT
- get-price
- BTC-USD-FEED-ID
- PYTH-STORAGE-CONTRACT)))
- )
- (ok price-data)
- ))
- ```
-
- La operación de actualización requiere una pequeña tarifa (típicamente 1 uSTX) para prevenir el spam.
-
-
-
- ### Procesar datos de precios
-
- Los datos de precio utilizan representación de punto fijo. Conviértelos a un formato utilizable:
-
- ```clarity
- (define-read-only (process-price-data (price-data {
- price-identifier: (buff 32),
- price: int,
- conf: uint,
- expo: int,
- ema-price: int,
- ema-conf: uint,
- publish-time: uint,
- prev-publish-time: uint
- }))
- (let (
- ;; Calculate the denominator based on the exponent
- ;; For expo = -8, denominator = 10^8 = 100,000,000
- (exponent (get expo price-data))
- (denominator (pow u10 (to-uint (* exponent -1))))
-
- ;; Convert to standard decimal representation
- ;; If price = 10603557773590 and expo = -8
- ;; Actual price = 10603557773590 / 100,000,000 = 106,035.58
- (adjusted-price (/ (to-uint (get price price-data)) denominator))
- )
- adjusted-price
- ))
- ```
-
-
-
-## Patrones comunes
-
-### Acuñación de NFT denominados en USD
-
-Crear un NFT que cueste exactamente $100 en valor de sBTC:
-
-```clarity contracts/benjamin-club.clar
-;; Benjamin Club - $100 NFT minting contract
-(define-constant BENJAMIN-COST u100) ;; $100 USD
-(define-constant ERR-INSUFFICIENT-FUNDS (err u100))
-(define-constant ERR-PRICE-UPDATE-FAILED (err u101))
-
-(define-non-fungible-token benjamin-nft uint)
-(define-data-var last-token-id uint u0)
-
-(define-public (mint-for-hundred-dollars (price-feed-bytes (buff 8192)))
- (let (
- ;; Update and get BTC price
- (price-data (try! (get-btc-price price-feed-bytes)))
- (btc-price-cents (process-price-data price-data))
-
- ;; Calculate required sBTC amount
- ;; $100 = 10,000 cents
- (required-sbtc (/ (* u10000 u100000000) btc-price-cents))
-
- ;; Get user's sBTC balance
- (user-balance (unwrap!
- (contract-call? .sbtc-token get-balance tx-sender)
- ERR-INSUFFICIENT-FUNDS))
- )
- ;; Verify user has enough sBTC
- (asserts! (>= user-balance required-sbtc) ERR-INSUFFICIENT-FUNDS)
-
- ;; Transfer sBTC and mint NFT
- (try! (contract-call? .sbtc-token transfer
- required-sbtc tx-sender (as-contract tx-sender) none))
-
- ;; Mint the NFT
- (let ((token-id (+ (var-get last-token-id) u1)))
- (try! (nft-mint? benjamin-nft token-id tx-sender))
- (var-set last-token-id token-id)
- (ok token-id))))
-```
-
-### Protección contra la obsolescencia de precios
-
-Asegúrese de que los datos de precios sean lo suficientemente recientes para su caso de uso:
-
-```clarity
-(define-constant MAX-PRICE-AGE u300) ;; 5 minutes in seconds
-
-(define-read-only (is-price-fresh (price-data (tuple)))
- (let (
- (current-time (unwrap-panic (get-block-info? time block-height)))
- (publish-time (get publish-time price-data))
- )
- (<= (- current-time publish-time) MAX-PRICE-AGE))
-)
-```
-
-### Agregación de precios de múltiples activos
-
-Obtén múltiples fuentes de precios en una sola transacción:
-
-```clarity
-(define-public (get-multiple-prices
- (btc-vaa (buff 8192))
- (eth-vaa (buff 8192))
- (stx-vaa (buff 8192)))
- (let (
- ;; Update all price feeds
- (updates (try! (contract-call? PYTH-ORACLE-CONTRACT
- verify-and-update-price-feeds
- (concat btc-vaa (concat eth-vaa stx-vaa))
- { pyth-storage-contract: PYTH-STORAGE-CONTRACT,
- pyth-decoder-contract: PYTH-DECODER-CONTRACT,
- wormhole-core-contract: WORMHOLE-CORE-CONTRACT })))
-
- ;; Read all prices
- (btc-price (try! (get-price-by-id BTC-USD-FEED-ID)))
- (eth-price (try! (get-price-by-id ETH-USD-FEED-ID)))
- (stx-price (try! (get-price-by-id STX-USD-FEED-ID)))
- )
- (ok { btc: btc-price, eth: eth-price, stx: stx-price }))
-)
-```
-
-## Despliegue en testnet
-
-Para el desarrollo en testnet, utilice estas direcciones de contrato:
-
-```clarity
-;; Testnet addresses
-(define-constant PYTH-ORACLE-CONTRACT-TESTNET 'ST20M5GABDT6WYJHXBT5CDH4501V1Q65242SPRMXH.pyth-oracle-v3)
-(define-constant PYTH-STORAGE-CONTRACT-TESTNET 'ST20M5GABDT6WYJHXBT5CDH4501V1Q65242SPRMXH.pyth-storage-v3)
-```
-
-## Próximos pasos
-
-:::next-steps
-* [Integración frontend](/reference/stacks.js/pyth-oracle-integration): Aprende cómo obtener mensajes VAA y llamar a tus contratos habilitados para oráculos
-* [Pruebas con Clarinet](/tools/clarinet/pyth-oracle-integration): Configurar pruebas para contratos que dependen de datos de oráculos
-:::
diff --git a/content/docs/es/resources/clarity/index.mdx b/content/docs/es/resources/clarity/index.mdx
deleted file mode 100644
index 563579f15..000000000
--- a/content/docs/es/resources/clarity/index.mdx
+++ /dev/null
@@ -1,19 +0,0 @@
----
-title: Clarity
-sidebarTitle: Visión general
-description: Explora y domina las funciones incorporadas de Clarity para el desarrollo de contratos inteligentes.
-llm: false
----
-## Visión general
-
-Cada página en esta sección cubre una o más funciones relacionadas de Clarity, explicando su propósito, demostrando la implementación con ejemplos de código y discutiendo las mejores prácticas. ¿Listo para mejorar tus habilidades de desarrollo de contratos inteligentes en Clarity?
-
-Para explorar Clarity con IA, copie y pegue [llms.txt](/resources/clarity/llms.txt) en tu LLM de elección.
-
-:::callout
-type: help
-
-### ¿Necesitas ayuda para construir con Clarity?
-
-Contáctenos en el #clarity canal activado [Discord](https://stacks.chat/) bajo la sección de Herramientas para Desarrolladores de Hiro. También hay una [horario de oficina semanal](https://www.addevent.com/event/kI22007085) llamada todos los miércoles a la 1 pm ET.
-:::
diff --git a/content/docs/es/resources/clarity/meta.json b/content/docs/es/resources/clarity/meta.json
deleted file mode 100644
index a8bc09825..000000000
--- a/content/docs/es/resources/clarity/meta.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "title": "Clarity",
- "root": true,
- "pages": [
- "---Clarity---",
- "index",
- "---Reference---",
- "...reference",
- "---Integrations---",
- "...(integrations)"
- ]
-}
diff --git a/content/docs/es/resources/clarity/reference/functions.mdx b/content/docs/es/resources/clarity/reference/functions.mdx
deleted file mode 100644
index 986935308..000000000
--- a/content/docs/es/resources/clarity/reference/functions.mdx
+++ /dev/null
@@ -1,3329 +0,0 @@
----
-title: Referencia de funciones
-sidebarTitle: Funciones
-description: Referencia completa de todas las funciones de Clarity organizadas por categoría, desde operaciones aritméticas hasta gestión de tokens.
----
-Clarity proporciona un conjunto completo de funciones incorporadas para el desarrollo de contratos inteligentes. Estas funciones abarcan desde aritmética básica hasta operaciones complejas de tokens e interacciones con la cadena de bloques.
-
-## Operaciones aritméticas \[#arithmetic-operations]
-
-### + (agregar) \[#add]
-
-`+` realiza la suma de un número variable de entradas enteras.
-
-**Firma**
-
-```clarity
-(+ i1 i2...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| i1, i2, ... | `int` o `uint` | Dos o más enteros para sumar |
-
-```clarity
-(+ 1 2 3) ;; Returns 6
-(+ u10 u20) ;; Returns u30
-
-;; Counter example
-(define-data-var counter int 0)
-(define-public (increment (amount int))
- (begin
- (var-set counter (+ (var-get counter) amount))
- (ok (var-get counter))))
-```
-
-### - (restar) \[#subtract]
-
-`-` realiza la resta en un número variable de entradas enteras.
-
-**Firma**
-
-```clarity
-(- i1 i2...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| i1, i2, ... | `int` o `uint` | Dos o más enteros para restar |
-
-```clarity
-(- 10 3) ;; Returns 7
-(- 100 20 10) ;; Returns 70
-(- u50 u30) ;; Returns u20
-
-;; Decrease balance
-(define-public (withdraw (amount uint))
- (let ((balance (var-get user-balance)))
- (asserts! (>= balance amount) (err u1))
- (var-set user-balance (- balance amount))
- (ok amount)))
-```
-
-### \* (multiplicar) \[#multiply]
-
-`*` realiza la multiplicación de un número variable de entradas enteras.
-
-**Firma**
-
-```clarity
-(* i1 i2...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| i1, i2, ... | `int` o `uint` | Dos o más números enteros para multiplicar |
-
-```clarity
-(* 3 4) ;; Returns 12
-(* 2 3 4) ;; Returns 24
-(* u5 u10) ;; Returns u50
-
-;; Calculate percentage
-(define-read-only (calculate-fee (amount uint))
- (/ (* amount u3) u100)) ;; 3% fee
-```
-
-### / (dividir) \[#divide]
-
-`/` realiza la división entera en un número variable de entradas enteras.
-
-**Firma**
-
-```clarity
-(/ i1 i2...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| i1, i2, ... | `int` o `uint` | Dos o más enteros para dividir |
-
-```clarity
-(/ 10 2) ;; Returns 5
-(/ 100 10 2) ;; Returns 5
-(/ u60 u3) ;; Returns u20
-
-;; Calculate average
-(define-read-only (average (a uint) (b uint))
- (/ (+ a b) u2))
-```
-
-### mod \[#mod]
-
-`mod` devuelve el resto de la división entera.
-
-**Firma**
-
-```clarity
-(mod i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Dividendo |
-| `i2` | `int` o `uint` | Divisor |
-
-```clarity
-(mod 10 3) ;; Returns 1
-(mod u17 u5) ;; Returns u2
-
-;; Check if even
-(define-read-only (is-even (n uint))
- (is-eq (mod n u2) u0))
-```
-
-### pow \[#pow]
-
-`pow` eleva un número a una potencia.
-
-**Firma**
-
-```clarity
-(pow i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Base |
-| `i2` | `int` o `uint` | Exponente |
-
-```clarity
-(pow 2 3) ;; Returns 8
-(pow u10 u2) ;; Returns u100
-
-;; Calculate compound interest
-(define-read-only (compound-interest (principal uint) (rate uint) (periods uint))
- (let ((rate-factor (+ u100 rate)))
- (/ (* principal (pow rate-factor periods)) (pow u100 periods))))
-```
-
-### sqrti \[#sqrti]
-
-`sqrti` devuelve la raíz cuadrada entera de un número.
-
-**Firma**
-
-```clarity
-(sqrti n)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `n` | `int` o `uint` | Número del que se quiere encontrar la raíz cuadrada |
-
-```clarity
-(sqrti u16) ;; Returns u4
-(sqrti u100) ;; Returns u10
-(sqrti 25) ;; Returns 5
-
-;; Calculate distance (simplified)
-(define-read-only (distance (x uint) (y uint))
- (sqrti (+ (* x x) (* y y))))
-```
-
-### log2 \[#log2]
-
-`log2` devuelve el logaritmo en base 2 de un número.
-
-**Firma**
-
-```clarity
-(log2 n)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `n` | `int` o `uint` | Número del que se quiere encontrar el logaritmo |
-
-```clarity
-(log2 u8) ;; Returns u3
-(log2 u256) ;; Returns u8
-
-;; Calculate bit position
-(define-read-only (highest-bit-position (n uint))
- (if (> n u0)
- (some (log2 n))
- none))
-```
-
-### \< (menor que) \[#less-than]
-
-`<` devuelve true si el primer argumento es menor que el segundo.
-
-**Firma**
-
-```clarity
-(< i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Primer valor |
-| `i2` | `int` o `uint` | Segundo valor |
-
-```clarity
-(< 5 10) ;; Returns true
-(< u100 u50) ;; Returns false
-
-;; Validate minimum
-(define-public (deposit (amount uint))
- (begin
- (asserts! (< u0 amount) (err u1))
- (ok amount)))
-```
-
-### > (mayor que) \[#greater-than]
-
-`>` devuelve true si el primer argumento es mayor que el segundo.
-
-**Firma**
-
-```clarity
-(> i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Primer valor |
-| `i2` | `int` o `uint` | Segundo valor |
-
-```clarity
-(> 10 5) ;; Returns true
-(> u50 u100) ;; Returns false
-
-;; Check maximum
-(define-read-only (exceeds-limit (value uint))
- (> value u1000000))
-```
-
-### \<= (menor o igual) \[#less-than-or-equal]
-
-`<=` devuelve verdadero si el primer argumento es menor o igual que el segundo.
-
-**Firma**
-
-```clarity
-(<= i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Primer valor |
-| `i2` | `int` o `uint` | Segundo valor |
-
-```clarity
-(<= 5 10) ;; Returns true
-(<= 10 10) ;; Returns true
-(<= u100 u50) ;; Returns false
-
-;; Validate range
-(define-read-only (is-valid-percentage (value uint))
- (and (<= u0 value) (<= value u100)))
-```
-
-### >= (mayor o igual que) \[#greater-than-or-equal]
-
-`>=` devuelve verdadero si el primer argumento es mayor o igual que el segundo.
-
-**Firma**
-
-```clarity
-(>= i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Primer valor |
-| `i2` | `int` o `uint` | Segundo valor |
-
-```clarity
-(>= 10 5) ;; Returns true
-(>= 10 10) ;; Returns true
-(>= u50 u100) ;; Returns false
-
-;; Check balance
-(define-public (can-afford (price uint))
- (ok (>= (stx-get-balance tx-sender) price)))
-```
-
-## Operaciones lógicas \[#logical-operations]
-
-### y \[#and]
-
-`and` devuelve true si todos los argumentos son true.
-
-**Firma**
-
-```clarity
-(and b1 b2...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| b1, b2, ... | `bool` | Valores booleanos para evaluar |
-
-```clarity
-(and true true) ;; Returns true
-(and true false) ;; Returns false
-(and true true true) ;; Returns true
-
-;; Multiple conditions
-(define-read-only (is-valid-transfer (amount uint) (recipient principal))
- (and
- (> amount u0)
- (not (is-eq recipient tx-sender))
- (<= amount (get-balance tx-sender))))
-```
-
-### o \[#or]
-
-`or` devuelve verdadero si al menos un argumento es verdadero.
-
-**Firma**
-
-```clarity
-(or b1 b2...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| b1, b2, ... | `bool` | Valores booleanos para evaluar |
-
-```clarity
-(or true false) ;; Returns true
-(or false false) ;; Returns false
-(or false false true) ;; Returns true
-
-;; Check permissions
-(define-read-only (can-access (user principal))
- (or
- (is-eq user contract-owner)
- (default-to false (map-get? admins user))
- (var-get public-access)))
-```
-
-### no \[#not]
-
-`not` devuelve la negación lógica de un valor booleano.
-
-**Firma**
-
-```clarity
-(not b)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `b` | `bool` | Valor booleano a negar |
-
-```clarity
-(not true) ;; Returns false
-(not false) ;; Returns true
-
-;; Check if not owner
-(define-read-only (is-not-owner (user principal))
- (not (is-eq user contract-owner)))
-```
-
-### xor \[#xor]
-
-`xor` devuelve verdadero si exactamente uno de los dos argumentos es verdadero.
-
-**Firma**
-
-```clarity
-(xor b1 b2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `b1` | `bool` | Primer valor booleano |
-| `b2` | `bool` | Segundo valor booleano |
-
-```clarity
-(xor true false) ;; Returns true
-(xor true true) ;; Returns false
-(xor false false) ;; Returns false
-
-;; Exclusive access
-(define-read-only (has-exclusive-role (is-admin bool) (is-moderator bool))
- (xor is-admin is-moderator))
-```
-
-### is-eq \[#is-eq]
-
-`is-eq` devuelve true si todos los argumentos son iguales.
-
-**Firma**
-
-```clarity
-(is-eq v1 v2...)
-```
-
-**Parámetros**
-
-| Name | Type | Description |
-|------|------|-------------|
-| v1, v2, ... | any | Valores a comparar para igualdad |
-
-```clarity
-(is-eq 5 5) ;; Returns true
-(is-eq "hello" "hello") ;; Returns true
-(is-eq u10 u20) ;; Returns false
-(is-eq 1 1 1) ;; Returns true
-
-;; Check owner
-(define-public (admin-only)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (ok true)))
-```
-
-## Operaciones de secuencia y cadena \[#sequence-string-operations]
-
-### lista \[#list]
-
-`list` construye una lista a partir de los valores proporcionados.
-
-**Firma**
-
-```clarity
-(list v1 v2...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| v1, v2, ... | any | Valores para incluir en la lista |
-
-```clarity
-(list 1 2 3) ;; Returns (1 2 3)
-(list true false true) ;; Returns (true false true)
-
-;; Create address list
-(define-data-var admins (list 5 principal)
- (list 'SP1234... 'SP5678...))
-```
-
-### append \[#append]
-
-`append` agrega un elemento al final de una lista.
-
-**Firma**
-
-```clarity
-(append list-expr element)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `list-expr` | `list` | Lista a la que añadir |
-| `element` | cualquiera | Elemento para agregar |
-
-```clarity
-(append (list 1 2) 3) ;; Returns (1 2 3)
-(append (list) u10) ;; Returns (u10)
-
-;; Add to list
-(define-public (add-member (member principal))
- (let ((current-list (var-get members)))
- (match (as-max-len? (append current-list member) u100)
- new-list (begin
- (var-set members new-list)
- (ok true))
- (err u1))))
-```
-
-### concat \[#concat]
-
-`concat` une dos secuencias del mismo tipo.
-
-**Firma**
-
-```clarity
-(concat sequence1 sequence2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `sequence1` | sequence | Primera secuencia |
-| `sequence2` | secuencia | Segunda secuencia |
-
-```clarity
-(concat "Hello " "World") ;; Returns "Hello World"
-(concat 0x0102 0x0304) ;; Returns 0x01020304
-(concat (list 1 2) (list 3 4)) ;; Returns (1 2 3 4)
-
-;; Combine strings
-(define-read-only (format-message (prefix (string-ascii 10)) (msg (string-ascii 50)))
- (concat prefix msg))
-```
-
-### len \[#len]
-
-`len` devuelve la longitud de una secuencia.
-
-**Firma**
-
-```clarity
-(len sequence)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `sequence` | sequence | Secuencia a medir |
-
-```clarity
-(len "Hello") ;; Returns u5
-(len (list 1 2 3)) ;; Returns u3
-(len 0x0102) ;; Returns u2
-
-;; Validate length
-(define-public (set-name (name (string-ascii 50)))
- (begin
- (asserts! (> (len name) u0) (err u1))
- (asserts! (<= (len name) u20) (err u2))
- (ok name)))
-```
-
-### element-at? \[#element-at?]
-
-`element-at?` recupera un elemento en un índice específico.
-
-**Firma**
-
-```clarity
-(element-at? sequence index)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `sequence` | secuencia | Secuencia para acceder |
-| `index` | `uint` | Índice basado en cero |
-
-```clarity
-(element-at? "Hello" u1) ;; Returns (some "e")
-(element-at? (list 10 20 30) u2) ;; Returns (some 30)
-(element-at? (list 1 2) u5) ;; Returns none
-
-;; Get from list safely
-(define-read-only (get-member-at (index uint))
- (element-at? (var-get members) index))
-```
-
-### index-of? \[#index-of]
-
-`index-of?` encuentra la primera aparición de un elemento en una secuencia.
-
-**Firma**
-
-```clarity
-(index-of? sequence element)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `sequence` | secuencia | Secuencia a buscar |
-| `element` | cualquiera | Elemento a encontrar |
-
-```clarity
-(index-of? "Hello" "l") ;; Returns (some u2)
-(index-of? (list 1 2 3 2) 2) ;; Returns (some u1)
-(index-of? (list 1 2 3) 5) ;; Returns none
-
-;; Check membership
-(define-read-only (is-member (user principal))
- (is-some (index-of? (var-get members) user)))
-```
-
-### slice? \[#slice]
-
-`slice?` extrae una subsecuencia de una secuencia.
-
-**Firma**
-
-```clarity
-(slice? sequence left-position right-position)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `sequence` | secuencia | Secuencia para cortar |
-| `left-position` | `uint` | Índice inicial (inclusivo) |
-| `right-position` | `uint` | Índice final (exclusivo) |
-
-```clarity
-(slice? "Hello World" u0 u5) ;; Returns (some "Hello")
-(slice? (list 1 2 3 4 5) u1 u4) ;; Returns (some (2 3 4))
-
-;; Extract substring
-(define-read-only (get-prefix (text (string-ascii 100)) (length uint))
- (slice? text u0 length))
-```
-
-### replace-at? \[#replace-at]
-
-`replace-at?` reemplaza un elemento en un índice específico.
-
-**Firma**
-
-```clarity
-(replace-at? sequence index new-element)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `sequence` | secuencia | Secuencia a modificar |
-| `index` | `uint` | Índice a reemplazar en |
-| `new-element` | cualquier | Nuevo elemento |
-
-```clarity
-(replace-at? "Hello" u1 "a") ;; Returns (some "Hallo")
-(replace-at? (list 1 2 3) u1 5) ;; Returns (some (1 5 3))
-
-;; Update list element
-(define-public (update-member (index uint) (new-member principal))
- (match (replace-at? (var-get members) index new-member)
- new-list (begin
- (var-set members new-list)
- (ok true))
- (err u404)))
-```
-
-### int-to-ascii \[#int-to-ascii]
-
-`int-to-ascii` converts an integer to its ASCII string representation.
-
-**Firma**
-
-```clarity
-(int-to-ascii value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `value` | `int` o `uint` | Entero a convertir |
-
-```clarity
-(int-to-ascii 123) ;; Returns "123"
-(int-to-ascii u456) ;; Returns "456"
-
-;; Format ID
-(define-read-only (format-id (id uint))
- (concat "ID-" (int-to-ascii id)))
-```
-
-### int-to-utf8 \[#int-to-utf8]
-
-`int-to-utf8` convierte un número entero a su representación de cadena UTF-8.
-
-**Firma**
-
-```clarity
-(int-to-utf8 value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `value` | `int` o `uint` | Entero a convertir |
-
-```clarity
-(int-to-utf8 789) ;; Returns u"789"
-(int-to-utf8 u100) ;; Returns u"100"
-
-;; Create UTF-8 label
-(define-read-only (create-label (num uint))
- (concat u"Label #" (int-to-utf8 num)))
-```
-
-### string-to-int? \[#string-to-int]
-
-`string-to-int?` convierte una cadena a un entero opcional.
-
-**Firma**
-
-```clarity
-(string-to-int? string)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `string` | `string-ascii` o `string-utf8` | Cadena para convertir |
-
-```clarity
-(string-to-int? "123") ;; Returns (some 123)
-(string-to-int? "-456") ;; Returns (some -456)
-(string-to-int? "abc") ;; Returns none
-
-;; Parse user input
-(define-public (set-value (input (string-ascii 10)))
- (match (string-to-int? input)
- value (ok (var-set stored-value value))
- (err u1)))
-```
-
-### string-to-uint? \[#string-to-uint]
-
-`string-to-uint?` convierte una cadena a un número entero sin signo opcional.
-
-**Firma**
-
-```clarity
-(string-to-uint? string)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `string` | `string-ascii` o `string-utf8` | Cadena para convertir |
-
-```clarity
-(string-to-uint? "123") ;; Returns (some u123)
-(string-to-uint? "0") ;; Returns (some u0)
-(string-to-uint? "-123") ;; Returns none
-
-;; Parse amount
-(define-read-only (parse-amount (input (string-ascii 20)))
- (string-to-uint? input))
-```
-
-### buff-to-int-be \[#buff-to-int-be]
-
-`buff-to-int-be` convierte un búfer a un número entero con signo (big-endian).
-
-**Firma**
-
-```clarity
-(buff-to-int-be buffer)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `buffer` | `buff` | Búfer a convertir |
-
-```clarity
-(buff-to-int-be 0x0001) ;; Returns 1
-(buff-to-int-be 0x00ff) ;; Returns 255
-(buff-to-int-be 0xffff) ;; Returns -1
-
-;; Parse signed data
-(define-read-only (parse-signed-data (data (buff 8)))
- (buff-to-int-be data))
-```
-
-### buff-to-int-le \[#buff-to-int-le]
-
-`buff-to-int-le` convierte un búfer a un número entero con signo (little-endian).
-
-**Firma**
-
-```clarity
-(buff-to-int-le buffer)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `buffer` | `buff` | Búfer a convertir |
-
-```clarity
-(buff-to-int-le 0x0100) ;; Returns 1
-(buff-to-int-le 0xff00) ;; Returns 255
-
-;; Parse little-endian data
-(define-read-only (parse-le-data (data (buff 4)))
- (buff-to-int-le data))
-```
-
-### buff-to-uint-be \[#buff-to-uint-be]
-
-`buff-to-uint-be` convierte un búfer a un número entero sin signo (big-endian).
-
-**Firma**
-
-```clarity
-(buff-to-uint-be buffer)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `buffer` | `buff` | Búfer a convertir |
-
-```clarity
-(buff-to-uint-be 0x0001) ;; Returns u1
-(buff-to-uint-be 0x0100) ;; Returns u256
-
-;; Parse network data
-(define-read-only (parse-network-uint (data (buff 8)))
- (buff-to-uint-be data))
-```
-
-### buff-to-uint-le \[#buff-to-uint-le]
-
-`buff-to-uint-le` convierte un búfer a un número entero sin signo (little-endian).
-
-**Firma**
-
-```clarity
-(buff-to-uint-le buffer)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `buffer` | `buff` | Búfer a convertir |
-
-```clarity
-(buff-to-uint-le 0x0100) ;; Returns u1
-(buff-to-uint-le 0x0001) ;; Returns u256
-
-;; Parse file data
-(define-read-only (parse-file-size (data (buff 4)))
- (buff-to-uint-le data))
-```
-
-## Iteradores \[#iterators]
-
-### mapa \[#map]
-
-`map` aplica una función a cada elemento de una lista.
-
-**Firma**
-
-```clarity
-(map func list1 list2...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `func` | función | Función a aplicar |
-| lista1, lista2, ... | `list` | Listas para recorrer |
-
-```clarity
-(map + (list 1 2 3) (list 10 20 30)) ;; Returns (11 22 33)
-
-;; Double all values
-(define-private (double (x uint))
- (* x u2))
-
-(define-read-only (double-all (numbers (list 10 uint)))
- (map double numbers))
-```
-
-### filtro \[#filter]
-
-`filter` devuelve elementos que satisfacen un predicado.
-
-**Firma**
-
-```clarity
-(filter func list)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `func` | función | Función de predicado |
-| `list` | `list` | Lista para filtrar |
-
-```clarity
-(define-private (is-even (x uint))
- (is-eq (mod x u2) u0))
-
-(filter is-even (list u1 u2 u3 u4)) ;; Returns (u2 u4)
-
-;; Filter active users
-(define-read-only (get-active-users)
- (filter is-active (var-get all-users)))
-```
-
-### plegar \[#fold]
-
-`fold` reduce una lista a un solo valor.
-
-**Firma**
-
-```clarity
-(fold func list initial-value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `func` | función | Función reductora |
-| `list` | `list` | Lista para reducir |
-| `initial-value` | cualquier | Valor inicial |
-
-```clarity
-(fold + (list u1 u2 u3 u4) u0) ;; Returns u10
-
-;; Sum balances
-(define-private (add-balance (user principal) (total uint))
- (+ total (default-to u0 (map-get? balances user))))
-
-(define-read-only (get-total-balance)
- (fold add-balance (var-get users) u0))
-```
-
-## Almacenamiento de datos y variables \[#data-storage-variables]
-
-### define-constant \[#define-constant]
-
-`define-constant` crea un valor constante inmutable.
-
-**Firma**
-
-```clarity
-(define-constant name value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `name` | símbolo | Nombre de la constante |
-| `value` | cualquiera | Valor de la constante |
-
-```clarity
-(define-constant contract-owner tx-sender)
-(define-constant token-name "MyToken")
-(define-constant max-supply u1000000)
-
-;; Use in functions
-(define-read-only (get-owner)
- contract-owner)
-```
-
-### define-data-var \[#define-data-var]
-
-`define-data-var` crea una variable de datos mutable.
-
-**Firma**
-
-```clarity
-(define-data-var name type value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `name` | símbolo | Nombre de la variable |
-| `type` | tipo | Tipo de la variable |
-| `value` | cualquier | Valor inicial |
-
-```clarity
-(define-data-var counter uint u0)
-(define-data-var is-paused bool false)
-(define-data-var admin principal tx-sender)
-
-;; Update variable
-(define-public (increment)
- (begin
- (var-set counter (+ (var-get counter) u1))
- (ok (var-get counter))))
-```
-
-### var-get \[#var-get]
-
-`var-get` recupera el valor de una variable de datos.
-
-**Firma**
-
-```clarity
-(var-get name)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `name` | símbolo | Nombre de la variable |
-
-```clarity
-(define-data-var balance uint u100)
-
-(define-read-only (get-balance)
- (var-get balance))
-
-;; Use in calculations
-(define-public (double-balance)
- (let ((current (var-get balance)))
- (var-set balance (* current u2))
- (ok (var-get balance))))
-```
-
-### var-set \[#var-set]
-
-`var-set` actualiza el valor de una variable de datos.
-
-**Firma**
-
-```clarity
-(var-set name value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `name` | símbolo | Nombre de la variable |
-| `value` | cualquiera | Nuevo valor |
-
-```clarity
-(define-data-var counter uint u0)
-
-(define-public (set-counter (value uint))
- (begin
- (var-set counter value)
- (ok true)))
-
-;; Conditional update
-(define-public (update-if-higher (value uint))
- (if (> value (var-get counter))
- (begin
- (var-set counter value)
- (ok true))
- (err u1)))
-```
-
-### define-map \[#define-map]
-
-`define-map` crea un nuevo mapa de datos.
-
-**Firma**
-
-```clarity
-(define-map name key-type value-type)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `name` | símbolo | Nombre del mapa |
-| `key-type` | tipo | Tipo de las claves |
-| `value-type` | tipo | Tipo de los valores |
-
-```clarity
-(define-map balances principal uint)
-(define-map user-profiles
- principal
- {
- name: (string-ascii 50),
- age: uint,
- active: bool
- })
-
-;; Composite key
-(define-map allowances
- { owner: principal, spender: principal }
- uint)
-```
-
-### map-get? \[#map-get]
-
-`map-get?` recupera un valor de un mapa.
-
-**Firma**
-
-```clarity
-(map-get? map-name key)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `map-name` | símbolo | Nombre del mapa |
-| `key` | cualquiera | Clave para buscar |
-
-```clarity
-(define-map balances principal uint)
-
-(define-read-only (get-balance (user principal))
- (default-to u0 (map-get? balances user)))
-
-;; Pattern matching
-(define-read-only (get-profile-name (user principal))
- (match (map-get? user-profiles user)
- profile (get name profile)
- "Unknown"))
-```
-
-### map-set \[#map-set]
-
-`map-set` establece o actualiza un valor en un mapa.
-
-**Firma**
-
-```clarity
-(map-set map-name key value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `map-name` | símbolo | Nombre del mapa |
-| `key` | cualquiera | Key to set |
-| `value` | cualquier | Valor para almacenar |
-
-```clarity
-(define-map balances principal uint)
-
-(define-public (set-balance (user principal) (amount uint))
- (begin
- (map-set balances user amount)
- (ok true)))
-
-;; Update profile
-(define-public (update-profile (name (string-ascii 50)) (age uint))
- (begin
- (map-set user-profiles tx-sender {
- name: name,
- age: age,
- active: true
- })
- (ok true)))
-```
-
-### map-insert \[#map-insert]
-
-`map-insert` inserta un valor solo si la clave no existe.
-
-**Firma**
-
-```clarity
-(map-insert map-name key value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `map-name` | símbolo | Nombre del mapa |
-| `key` | cualquiera | Tecla para insertar |
-| `value` | cualquier | Valor para almacenar |
-
-```clarity
-(define-map users principal { joined: uint })
-
-(define-public (register)
- (if (map-insert users tx-sender { joined: block-height })
- (ok "Registered successfully")
- (err u409))) ;; Already exists
-
-;; One-time initialization
-(define-public (initialize-user (user principal))
- (begin
- (asserts! (map-insert balances user u1000) (err u1))
- (ok true)))
-```
-
-### map-delete \[#map-delete]
-
-`map-delete` elimina un par clave-valor de un mapa.
-
-**Firma**
-
-```clarity
-(map-delete map-name key)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `map-name` | símbolo | Nombre del mapa |
-| `key` | cualquiera | Key to delete |
-
-```clarity
-(define-map users principal { data: uint })
-
-(define-public (remove-user (user principal))
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (map-delete users user)
- (ok true)))
-
-;; Clear data
-(define-public (clear-balance)
- (begin
- (map-delete balances tx-sender)
- (ok true)))
-```
-
-### define-private \[#define-private]
-
-`define-private` crea una función privada que solo se puede llamar dentro del contrato.
-
-**Firma**
-
-```clarity
-(define-private (function-name (arg-name arg-type)...) body)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `function-name` | símbolo | Nombre de la función |
-| `arg-name` | símbolo | Nombres de argumentos |
-| `arg-type` | tipo | Tipos de argumentos |
-| `body` | expresión | Cuerpo de la función |
-
-```clarity
-(define-private (calculate-fee (amount uint))
- (/ (* amount u3) u100)) ;; 3% fee
-
-(define-public (transfer-with-fee (recipient principal) (amount uint))
- (let ((fee (calculate-fee amount)))
- (try! (stx-transfer? (- amount fee) tx-sender recipient))
- (try! (stx-transfer? fee tx-sender contract-owner))
- (ok true)))
-
-;; Helper functions
-(define-private (is-valid-amount (amount uint))
- (and (> amount u0) (<= amount u1000000)))
-```
-
-### define-public \[#define-public]
-
-`define-public` crea una función pública que se puede llamar desde fuera del contrato.
-
-**Firma**
-
-```clarity
-(define-public (function-name (arg-name arg-type)...) body)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `function-name` | símbolo | Nombre de la función |
-| `arg-name` | símbolo | Nombres de argumentos |
-| `arg-type` | tipo | Tipos de argumentos |
-| `body` | expresión | Cuerpo de la función (debe devolver respuesta) |
-
-```clarity
-(define-public (transfer (recipient principal) (amount uint))
- (begin
- (asserts! (not (is-eq tx-sender recipient)) (err u1))
- (asserts! (> amount u0) (err u2))
- (try! (ft-transfer? my-token amount tx-sender recipient))
- (ok true)))
-
-;; State-changing function
-(define-public (set-name (new-name (string-ascii 50)))
- (begin
- (map-set user-names tx-sender new-name)
- (ok new-name)))
-```
-
-### define-read-only \[#define-read-only]
-
-`define-read-only` crea una función pública de solo lectura.
-
-**Firma**
-
-```clarity
-(define-read-only (function-name (arg-name arg-type)...) body)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `function-name` | símbolo | Nombre de la función |
-| `arg-name` | símbolo | Nombres de argumentos |
-| `arg-type` | tipo | Tipos de argumentos |
-| `body` | expresión | Cuerpo de la función |
-
-```clarity
-(define-read-only (get-balance (user principal))
- (default-to u0 (map-get? balances user)))
-
-(define-read-only (calculate-reward (staked uint) (days uint))
- (/ (* staked days u5) u36500)) ;; ~5% APY
-
-;; Complex query
-(define-read-only (get-user-info (user principal))
- {
- balance: (get-balance user),
- profile: (map-get? user-profiles user),
- is-admin: (is-eq user contract-owner)
- })
-```
-
-## Manejo de errores \[#error-handling]
-
-### ok \[#ok]
-
-`ok` construye un valor de respuesta exitoso.
-
-**Firma**
-
-```clarity
-(ok value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `value` | cualquier | Valor de éxito |
-
-```clarity
-(ok u42) ;; Returns (ok u42)
-(ok { status: "success", value: u100 })
-
-;; Success response
-(define-public (deposit (amount uint))
- (begin
- (map-set balances tx-sender
- (+ (get-balance tx-sender) amount))
- (ok amount)))
-```
-
-### err \[#err]
-
-`err` construye un valor de respuesta de error.
-
-**Firma**
-
-```clarity
-(err value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `value` | cualquier | Valor de error |
-
-```clarity
-(err u404) ;; Returns (err u404)
-(err { code: u500, message: "Internal error" })
-
-;; Error responses
-(define-public (withdraw (amount uint))
- (let ((balance (get-balance tx-sender)))
- (if (>= balance amount)
- (ok amount)
- (err u1)))) ;; Insufficient balance
-```
-
-### asserts! \[#asserts]
-
-`asserts!` comprueba una condición y sale con un error si es falsa.
-
-**Firma**
-
-```clarity
-(asserts! condition thrown-value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `condition` | `bool` | Condición a verificar |
-| `thrown-value` | cualquiera | Valor a devolver si es falso |
-
-```clarity
-(define-public (transfer (amount uint) (recipient principal))
- (begin
- (asserts! (> amount u0) (err u1))
- (asserts! (not (is-eq tx-sender recipient)) (err u2))
- (asserts! (<= amount (get-balance tx-sender)) (err u3))
- (ok true)))
-
-;; Guard functions
-(define-public (admin-only-function)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- ;; Admin logic here
- (ok true)))
-```
-
-### try! \[#try]
-
-`try!` intenta desenvolver una respuesta, propagando cualquier error.
-
-**Firma**
-
-```clarity
-(try! response)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `response` | respuesta | Respuesta para probar |
-
-```clarity
-(try! (ok u42)) ;; Returns u42
-(try! (err u404)) ;; Propagates (err u404)
-
-;; Chain operations
-(define-public (complex-operation (amount uint))
- (begin
- (try! (check-preconditions amount))
- (try! (process-payment amount))
- (try! (update-records))
- (ok true)))
-```
-
-### unwrap! \[#unwrap]
-
-`unwrap!` extrae el valor interno de una respuesta opcional o exitosa.
-
-**Firma**
-
-```clarity
-(unwrap! optional-or-response thrown-value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `optional-or-response` | opcional/respuesta | Valor para desenvolver |
-| `thrown-value` | cualquiera | Valor si ninguno/error |
-
-```clarity
-(unwrap! (some u42) (err u1)) ;; Returns u42
-(unwrap! none (err u404)) ;; Throws (err u404)
-
-;; Safe access
-(define-public (transfer-from-map (recipient principal))
- (let ((amount (unwrap! (map-get? pending-transfers tx-sender) (err u404))))
- (try! (ft-transfer? token amount tx-sender recipient))
- (map-delete pending-transfers tx-sender)
- (ok amount)))
-```
-
-### unwrap-err! \[#unwrap-err]
-
-`unwrap-err!` extrae el valor de error de una respuesta de error.
-
-**Firma**
-
-```clarity
-(unwrap-err! response thrown-value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `response` | respuesta | Respuesta a desenvolver |
-| `thrown-value` | cualquiera | Valor si está bien |
-
-```clarity
-(unwrap-err! (err u404) u0) ;; Returns u404
-(unwrap-err! (ok u42) u0) ;; Returns u0
-
-;; Error handling
-(define-public (handle-error)
- (let ((error-code (unwrap-err! (process-action) u0)))
- (print { error: error-code })
- (ok error-code)))
-```
-
-### unwrap-panic \[#unwrap-panic]
-
-`unwrap-panic` extrae un valor o provoca un pánico en tiempo de ejecución.
-
-**Firma**
-
-```clarity
-(unwrap-panic optional-or-response)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `optional-or-response` | opcional/respuesta | Valor a desenvolver |
-
-```clarity
-(unwrap-panic (some u42)) ;; Returns u42
-(unwrap-panic none) ;; Runtime panic
-
-;; Critical unwrap
-(define-read-only (get-critical-value)
- (unwrap-panic (map-get? critical-config "version")))
-```
-
-### unwrap-err-panic \[#unwrap-err-panic]
-
-`unwrap-err-panic` extrae un valor de error o causa un pánico en tiempo de ejecución.
-
-**Firma**
-
-```clarity
-(unwrap-err-panic response)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `response` | respuesta | Respuesta para desenvolver |
-
-```clarity
-(unwrap-err-panic (err u404)) ;; Returns u404
-(unwrap-err-panic (ok u42)) ;; Runtime panic
-
-;; Force error
-(define-read-only (get-error-code)
- (unwrap-err-panic (always-fails)))
-```
-
-## Ayudantes de datos \[#data-helpers]
-
-### default-to \[#default-to]
-
-`default-to` devuelve un valor predeterminado para none.
-
-**Firma**
-
-```clarity
-(default-to default optional)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `default` | cualquiera | Valor predeterminado |
-| `optional` | opcional | Valor opcional |
-
-```clarity
-(default-to u0 (some u42)) ;; Returns u42
-(default-to u0 none) ;; Returns u0
-
-;; Safe defaults
-(define-read-only (get-balance-safe (user principal))
- (default-to u0 (map-get? balances user)))
-```
-
-### fusionar \[#merge]
-
-`merge` combina dos tuplas, con la segunda anulando la primera.
-
-**Firma**
-
-```clarity
-(merge tuple1 tuple2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `tuple1` | tupla | Tupla base |
-| `tuple2` | tupla | Anular tupla |
-
-```clarity
-(merge { a: u1, b: u2 } { b: u3, c: u4 })
-;; Returns { a: u1, b: u3, c: u4 }
-
-;; Update record
-(define-public (update-profile (updates { name: (optional (string-ascii 50)), age: (optional uint) }))
- (let ((current (default-to { name: "", age: u0 } (map-get? profiles tx-sender))))
- (map-set profiles tx-sender (merge current updates))
- (ok true)))
-```
-
-### get \[#get]
-
-`get` extrae un valor de una tupla por clave.
-
-**Firma**
-
-```clarity
-(get key tuple)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `key` | símbolo | Clave para extraer |
-| `tuple` | tupla | Tupla a la que acceder |
-
-```clarity
-(get balance { balance: u100, locked: u50 }) ;; Returns u100
-
-;; Access nested data
-(define-read-only (get-user-balance (user principal))
- (match (map-get? accounts user)
- account (get balance account)
- u0))
-```
-
-### as-max-len? \[#as-max-len]
-
-`as-max-len?` comprueba si una secuencia se ajusta a una longitud máxima.
-
-**Firma**
-
-```clarity
-(as-max-len? sequence max-length)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `sequence` | secuencia | Secuencia a verificar |
-| `max-length` | uint | Longitud máxima permitida |
-
-```clarity
-(as-max-len? (list 1 2 3) u5) ;; Returns (some (1 2 3))
-(as-max-len? "Hello" u3) ;; Returns none
-
-;; Safe append
-(define-public (add-to-list (item uint))
- (match (as-max-len? (append (var-get items) item) u100)
- new-list (begin
- (var-set items new-list)
- (ok true))
- (err u1)))
-```
-
-## Control de flujo \[#control-flow]
-
-### si \[#if]
-
-`if` evalúa una condición y devuelve uno de dos valores.
-
-**Firma**
-
-```clarity
-(if condition true-branch false-branch)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `condition` | `bool` | Condición a evaluar |
-| `true-branch` | cualquiera | Valor si es verdadero |
-| `false-branch` | cualquiera | Valor si es falso |
-
-```clarity
-(if (> u10 u5)
- "Greater"
- "Not greater") ;; Returns "Greater"
-
-;; Conditional logic
-(define-public (withdraw (amount uint))
- (let ((balance (get-balance tx-sender)))
- (if (>= balance amount)
- (begin
- (map-set balances tx-sender (- balance amount))
- (ok amount))
- (err u1))))
-```
-
-### match \[#partido]
-
-`match` realiza coincidencia de patrones en tipos opcionales y de respuesta.
-
-**Firma**
-
-```clarity
-(match value
- some-name some-branch
- none-branch)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `value` | opcional/respuesta | Valor a coincidir |
-| `some-name` | símbolo | Enlace para algún valor |
-| `some-branch` | expresión | Expresión si alguna |
-| `none-branch` | expresión | Expresión si no hay ninguna |
-
-```clarity
-(match (map-get? balances tx-sender)
- balance (ok balance)
- (err u404))
-
-;; Response matching
-(match (ft-transfer? token u100 tx-sender recipient)
- success (ok "Transfer successful")
- error (err error))
-
-;; Nested matching
-(define-read-only (get-user-name (user principal))
- (match (map-get? user-profiles user)
- profile (match (get name profile)
- name (ok name)
- (err u1))
- (err u404)))
-```
-
-### begin \[#begin]
-
-`begin` ejecuta múltiples expresiones en secuencia.
-
-**Firma**
-
-```clarity
-(begin expr1 expr2... last-expr)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| expr1, expr2, ... | any | Expresiones a ejecutar |
-| `last-expr` | cualquiera | Expresión final (valor de retorno) |
-
-```clarity
-(begin
- (print "Starting")
- (var-set counter u1)
- (ok true))
-
-;; Multiple operations
-(define-public (initialize)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (var-set is-initialized true)
- (map-set admins tx-sender true)
- (print { event: "initialized", by: tx-sender })
- (ok true)))
-```
-
-### let \[#let]
-
-`let` crea enlaces locales para su uso en una expresión.
-
-**Firma**
-
-```clarity
-(let ((name1 value1) (name2 value2)...) body)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `name` | símbolo | Nombre de enlace |
-| `value` | cualquier | Valor para vincular |
-| `body` | expresión | Expresión usando enlaces |
-
-```clarity
-(let ((x 10) (y 20))
- (+ x y)) ;; Returns 30
-
-;; Complex calculations
-(define-public (calculate-reward (days uint))
- (let (
- (balance (get-balance tx-sender))
- (rate u5) ;; 5% annual
- (reward (/ (* balance rate days) u36500)))
- (begin
- (map-set rewards tx-sender reward)
- (ok reward))))
-```
-
-## Tipos opcionales y de respuesta \[#optional-response-types]
-
-### algunos \[#some]
-
-`some` construye un valor opcional que contiene un valor.
-
-**Firma**
-
-```clarity
-(some value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `value` | cualquiera | Valor para envolver |
-
-```clarity
-(some u42) ;; Returns (some u42)
-(some "Hello") ;; Returns (some "Hello")
-
-;; Return optional
-(define-read-only (find-user (id uint))
- (if (map-get? users id)
- (some (map-get? users id))
- none))
-```
-
-### is-ok \[#is-ok]
-
-`is-ok` comprueba si una respuesta es correcta.
-
-**Firma**
-
-```clarity
-(is-ok response)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `response` | respuesta | Respuesta a verificar |
-
-```clarity
-(is-ok (ok u42)) ;; Returns true
-(is-ok (err u1)) ;; Returns false
-
-;; Check success
-(define-read-only (was-successful (tx-id uint))
- (is-ok (map-get? transaction-results tx-id)))
-```
-
-### is-err \[#is-err]
-
-`is-err` comprueba si una respuesta es err.
-
-**Firma**
-
-```clarity
-(is-err response)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `response` | respuesta | Respuesta a verificar |
-
-```clarity
-(is-err (err u404)) ;; Returns true
-(is-err (ok u42)) ;; Returns false
-
-;; Check failure
-(define-read-only (has-error (result (response uint uint)))
- (is-err result))
-```
-
-### is-some \[#is-some]
-
-`is-some` comprueba si un opcional contiene un valor.
-
-**Firma**
-
-```clarity
-(is-some optional)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `optional` | opcional | Opcional para verificar |
-
-```clarity
-(is-some (some u42)) ;; Returns true
-(is-some none) ;; Returns false
-
-;; Check existence
-(define-read-only (user-exists (user principal))
- (is-some (map-get? users user)))
-```
-
-### is-none \[#is-none]
-
-`is-none` comprueba si un opcional es none.
-
-**Firma**
-
-```clarity
-(is-none optional)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `optional` | opcional | Opcional para verificar |
-
-```clarity
-(is-none none) ;; Returns true
-(is-none (some u42)) ;; Returns false
-
-;; Check absence
-(define-read-only (is-available (name (string-ascii 50)))
- (is-none (map-get? reserved-names name)))
-```
-
-## Tokens fungibles \[#fungible-tokens]
-
-### define-fungible-token \[#define-fungible-token]
-
-`define-fungible-token` crea un nuevo token fungible.
-
-**Firma**
-
-```clarity
-(define-fungible-token token-name [total-supply])
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token-name` | symbol | Nombre del token |
-| `total-supply` | `uint` (opcional) | Suministro máximo |
-
-```clarity
-(define-fungible-token my-token)
-(define-fungible-token limited-token u1000000)
-
-;; With helper functions
-(define-public (get-balance (user principal))
- (ok (ft-get-balance my-token user)))
-```
-
-### ft-mint? \[#ft-mint]
-
-`ft-mint?` crea nuevos tokens para un destinatario.
-
-**Firma**
-
-```clarity
-(ft-mint? token amount recipient)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | Token para acuñar |
-| `amount` | `uint` | Cantidad a acuñar |
-| `recipient` | `principal` | Destinatario de tokens |
-
-```clarity
-(ft-mint? my-token u100 tx-sender)
-
-;; Mint with checks
-(define-public (mint-tokens (amount uint) (recipient principal))
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (ft-mint? my-token amount recipient)))
-```
-
-### ft-burn? \[#ft-burn]
-
-`ft-burn?` destruye tokens de un propietario.
-
-**Firma**
-
-```clarity
-(ft-burn? token amount owner)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | Token para quemar |
-| `amount` | `uint` | Cantidad para quemar |
-| `owner` | `principal` | Propietario de tokens |
-
-```clarity
-(ft-burn? my-token u50 tx-sender)
-
-;; Burn own tokens
-(define-public (burn (amount uint))
- (ft-burn? my-token amount tx-sender))
-```
-
-### ft-transfer? \[#ft-transfer]
-
-`ft-transfer?` transfiere tokens entre principales.
-
-**Firma**
-
-```clarity
-(ft-transfer? token amount sender recipient)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | Token a transferir |
-| `amount` | `uint` | Cantidad a transferir |
-| `sender` | `principal` | Remitente |
-| `recipient` | `principal` | Destinatario |
-
-```clarity
-(ft-transfer? my-token u50 tx-sender recipient)
-
-;; Transfer with memo
-(define-public (transfer-memo (amount uint) (recipient principal) (memo (buff 32)))
- (begin
- (print { action: "transfer", amount: amount, memo: memo })
- (ft-transfer? my-token amount tx-sender recipient)))
-```
-
-### ft-get-balance \[#ft-get-balance]
-
-`ft-get-balance` devuelve el saldo de tokens de un principal.
-
-**Firma**
-
-```clarity
-(ft-get-balance token principal)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | Token a consultar |
-| `principal` | `principal` | Cuenta a verificar |
-
-```clarity
-(ft-get-balance my-token tx-sender) ;; Returns uint
-
-;; Balance check
-(define-read-only (has-sufficient-balance (user principal) (required uint))
- (>= (ft-get-balance my-token user) required))
-```
-
-### ft-get-supply \[#ft-get-supply]
-
-`ft-get-supply` devuelve el suministro actual de tokens.
-
-**Firma**
-
-```clarity
-(ft-get-supply token)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | Token a consultar |
-
-```clarity
-(ft-get-supply my-token) ;; Returns uint
-
-;; Supply metrics
-(define-read-only (get-supply-info)
- {
- current: (ft-get-supply my-token),
- max: u1000000,
- remaining: (- u1000000 (ft-get-supply my-token))
- })
-```
-
-## Tokens no fungibles \[#non-fungible-tokens]
-
-### define-non-fungible-token \[#define-non-fungible-token]
-
-`define-non-fungible-token` crea un nuevo token no fungible.
-
-**Firma**
-
-```clarity
-(define-non-fungible-token token-name identifier-type)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token-name` | symbol | Nombre del NFT |
-| `identifier-type` | tipo | Tipo del identificador |
-
-```clarity
-(define-non-fungible-token my-nft uint)
-(define-non-fungible-token complex-nft { id: uint, serial: (buff 20) })
-
-;; NFT with metadata
-(define-map nft-metadata uint {
- name: (string-ascii 50),
- uri: (string-ascii 200)
-})
-```
-
-### nft-mint? \[#nft-mint]
-
-`nft-mint?` crea un nuevo NFT para un destinatario.
-
-**Firma**
-
-```clarity
-(nft-mint? token identifier recipient)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | NFT para acuñar |
-| `identifier` | cualquier | Identificador único |
-| `recipient` | `principal` | Destinatario |
-
-```clarity
-(nft-mint? my-nft u1 tx-sender)
-
-;; Mint with metadata
-(define-public (mint-with-metadata (id uint) (name (string-ascii 50)) (uri (string-ascii 200)))
- (begin
- (try! (nft-mint? my-nft id tx-sender))
- (map-set nft-metadata id { name: name, uri: uri })
- (ok id)))
-```
-
-### nft-burn? \[#nft-burn]
-
-`nft-burn?` destruye un NFT.
-
-**Firma**
-
-```clarity
-(nft-burn? token identifier owner)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | NFT para quemar |
-| `identifier` | cualquier | identificador de NFT |
-| `owner` | `principal` | Propietario actual |
-
-```clarity
-(nft-burn? my-nft u1 tx-sender)
-
-;; Burn with ownership check
-(define-public (burn-nft (id uint))
- (let ((owner (unwrap! (nft-get-owner? my-nft id) (err u404))))
- (asserts! (is-eq owner tx-sender) (err u403))
- (nft-burn? my-nft id tx-sender)))
-```
-
-### nft-transfer? \[#nft-transfer]
-
-`nft-transfer?` transfiere un NFT entre principales.
-
-**Firma**
-
-```clarity
-(nft-transfer? token identifier sender recipient)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | NFT a transferir |
-| `identifier` | cualquier | identificador de NFT |
-| `sender` | `principal` | Propietario actual |
-| `recipient` | `principal` | Nuevo propietario |
-
-```clarity
-(nft-transfer? my-nft u1 tx-sender recipient)
-
-;; Safe transfer
-(define-public (transfer (id uint) (recipient principal))
- (let ((owner (unwrap! (nft-get-owner? my-nft id) (err u404))))
- (asserts! (is-eq owner tx-sender) (err u403))
- (nft-transfer? my-nft id tx-sender recipient)))
-```
-
-### nft-get-owner? \[#nft-get-owner]
-
-`nft-get-owner?` devuelve el propietario de un NFT.
-
-**Firma**
-
-```clarity
-(nft-get-owner? token identifier)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `token` | token-name | NFT a consultar |
-| `identifier` | cualquier | identificador de NFT |
-
-```clarity
-(nft-get-owner? my-nft u1) ;; Returns (optional principal)
-
-;; Ownership check
-(define-read-only (is-owner (id uint) (user principal))
- (match (nft-get-owner? my-nft id)
- owner (is-eq owner user)
- false))
-```
-
-## Operaciones STX \[#stx-operations]
-
-### stx-transfer? \[#stx-transfer]
-
-`stx-transfer?` transfiere STX entre direcciones.
-
-**Firma**
-
-```clarity
-(stx-transfer? amount sender recipient)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `amount` | `uint` | Cantidad en microSTX |
-| `sender` | `principal` | Dirección del remitente |
-| `recipient` | `principal` | Dirección del destinatario |
-
-```clarity
-(stx-transfer? u1000000 tx-sender recipient) ;; Transfer 1 STX
-
-;; Payment function
-(define-public (pay (amount uint) (recipient principal))
- (begin
- (asserts! (> amount u0) (err u1))
- (stx-transfer? amount tx-sender recipient)))
-```
-
-### stx-transfer-memo? \[#stx-transfer-memo]
-
-`stx-transfer-memo?` transfiere STX con un memo.
-
-**Firma**
-
-```clarity
-(stx-transfer-memo? amount sender recipient memo)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `amount` | `uint` | Cantidad en microSTX |
-| `sender` | `principal` | Dirección del remitente |
-| `recipient` | `principal` | Dirección del destinatario |
-| `memo` | `(buff 34)` | Memo de transferencia |
-
-```clarity
-(stx-transfer-memo? u1000000 tx-sender recipient 0x12345678)
-
-;; Payment with reference
-(define-public (pay-invoice (amount uint) (recipient principal) (invoice-id (buff 16)))
- (stx-transfer-memo? amount tx-sender recipient
- (concat 0x494e56 invoice-id))) ;; "INV" prefix
-```
-
-### stx-burn? \[#stx-burn]
-
-`stx-burn?` quema STX enviándolo a una dirección de quemado.
-
-**Firma**
-
-```clarity
-(stx-burn? amount sender)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `amount` | `uint` | Cantidad para quemar |
-| `sender` | `principal` | Dirección quemando STX |
-
-```clarity
-(stx-burn? u1000000 tx-sender)
-
-;; Burn mechanism
-(define-public (burn-stx (amount uint))
- (begin
- (asserts! (> amount u0) (err u1))
- (stx-burn? amount tx-sender)))
-```
-
-### stx-get-balance \[#stx-get-balance]
-
-`stx-get-balance` devuelve el saldo de STX de una dirección.
-
-**Firma**
-
-```clarity
-(stx-get-balance principal)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `principal` | `principal` | Dirección a verificar |
-
-```clarity
-(stx-get-balance tx-sender) ;; Returns uint
-
-;; Balance check
-(define-read-only (can-afford-fee (user principal) (fee uint))
- (>= (stx-get-balance user) fee))
-```
-
-### stx-account \[#stx-account]
-
-`stx-account` devuelve información detallada de la cuenta.
-
-**Firma**
-
-```clarity
-(stx-account principal)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `principal` | `principal` | Dirección para consultar |
-
-```clarity
-(stx-account tx-sender)
-;; Returns { locked: uint, unlock-height: uint, unlocked: uint }
-
-;; Get available balance
-(define-read-only (get-available-balance (user principal))
- (get unlocked (stx-account user)))
-```
-
-## Funciones criptográficas \[#cryptographic-functions]
-
-### sha256 \[#sha256]
-
-`sha256` calcula el hash SHA-256 de los datos de entrada.
-
-**Firma**
-
-```clarity
-(sha256 data)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `data` | secuencia | Datos para hacer hash |
-
-```clarity
-(sha256 0x616263) ;; Returns SHA-256 of "abc"
-(sha256 "Hello") ;; Hash string
-
-;; Create hash commitment
-(define-public (commit-hash (data (buff 32)))
- (let ((hash (sha256 data)))
- (map-set commitments tx-sender hash)
- (ok hash)))
-```
-
-### sha512 \[#sha512]
-
-`sha512` calcula el hash SHA-512 de los datos de entrada.
-
-**Firma**
-
-```clarity
-(sha512 data)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `data` | secuencia | Datos para hacer hash |
-
-```clarity
-(sha512 0x616263) ;; Returns SHA-512 hash
-(sha512 "data") ;; Hash string
-
-;; High security hash
-(define-read-only (secure-hash (input (buff 1024)))
- (sha512 input))
-```
-
-### sha512/256 \[#sha512-256]
-
-`sha512/256` calcula el hash SHA-512/256 de los datos de entrada.
-
-**Firma**
-
-```clarity
-(sha512/256 data)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `data` | secuencia | Datos para hacer hash |
-
-```clarity
-(sha512/256 0x616263) ;; Returns 256-bit hash
-(sha512/256 "secure") ;; Hash string
-
-;; Merkle tree node
-(define-private (hash-pair (left (buff 32)) (right (buff 32)))
- (sha512/256 (concat left right)))
-```
-
-### keccak256 \[#keccak256]
-
-`keccak256` calcula el hash Keccak-256 de los datos de entrada.
-
-**Firma**
-
-```clarity
-(keccak256 data)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `data` | secuencia | Datos para hacer hash |
-
-```clarity
-(keccak256 0x616263) ;; Returns Keccak-256 hash
-(keccak256 "ethereum") ;; Hash string
-
-;; Ethereum compatibility
-(define-read-only (eth-compatible-hash (data (buff 256)))
- (keccak256 data))
-```
-
-### hash160 \[#hash160]
-
-`hash160` computes RIPEMD160(SHA256(data)).
-
-**Firma**
-
-```clarity
-(hash160 data)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `data` | secuencia | Datos para hacer hash |
-
-```clarity
-(hash160 0x616263) ;; Returns 160-bit hash
-(hash160 "address") ;; Hash string
-
-;; Bitcoin-style address
-(define-read-only (create-hash160-id (data (buff 32)))
- (hash160 data))
-```
-
-### secp256k1-verify \[#secp256k1-verify]
-
-`secp256k1-verify` verifica una firma contra un hash de mensaje.
-
-**Firma**
-
-```clarity
-(secp256k1-verify hash signature public-key)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `hash` | `(buff 32)` | Hash del mensaje |
-| `signature` | `(buff 65)` | Firma |
-| `public-key` | `(buff 33)` | Clave pública |
-
-```clarity
-(secp256k1-verify
- 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
- signature
- public-key) ;; Returns bool
-
-;; Signature verification
-(define-public (verify-signature (hash (buff 32)) (sig (buff 65)) (pubkey (buff 33)))
- (ok (secp256k1-verify hash sig pubkey)))
-```
-
-### secp256k1-recover? \[#secp256k1-recover]
-
-`secp256k1-recover?` recupera una clave pública a partir de una firma.
-
-**Firma**
-
-```clarity
-(secp256k1-recover? hash signature)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `hash` | `(buff 32)` | Hash del mensaje |
-| `signature` | `(buff 65)` | Firma |
-
-```clarity
-(secp256k1-recover? message-hash signature)
-;; Returns (optional (buff 33))
-
-;; Recover signer
-(define-read-only (recover-signer (hash (buff 32)) (sig (buff 65)))
- (secp256k1-recover? hash sig))
-```
-
-## Datos de blockchain \[#blockchain-data]
-
-### get-block-info? \[#get-block-info]
-
-`get-block-info?` recupera información sobre un bloque.
-
-**Firma**
-
-```clarity
-(get-block-info? property block)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `property` | Nombre de la propiedad | Propiedad a recuperar |
-| `block` | `uint` | Altura del bloque |
-
-Propiedades: `header-hash`, `burnchain-header-hash`, `time`, `miner-address`, `block-reward`, `miner-spend-total`, `miner-spend-winner`
-
-```clarity
-(get-block-info? time u100) ;; Returns (optional uint)
-(get-block-info? miner-address u200) ;; Returns (optional principal)
-
-;; Get block time
-(define-read-only (get-block-timestamp (height uint))
- (get-block-info? time height))
-```
-
-### get-burn-block-info? \[#get-burn-block-info]
-
-`get-burn-block-info?` recupera información del bloque de Bitcoin.
-
-**Firma**
-
-```clarity
-(get-burn-block-info? property block)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `property` | Nombre de la propiedad | Propiedad a recuperar |
-| `block` | `uint` | Altura del bloque de quemado |
-
-Propiedades: `header-hash`, `pox-addrs`
-
-```clarity
-(get-burn-block-info? header-hash u100) ;; Returns (optional (buff 32))
-
-;; Get burn block hash
-(define-read-only (get-btc-header-hash (height uint))
- (get-burn-block-info? header-hash height))
-```
-
-### get-stacks-block-info? \[#get-stacks-block-info]
-
-`get-stacks-block-info?` recupera información del bloque de Stacks.
-
-**Firma**
-
-```clarity
-(get-stacks-block-info? property block)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `property` | Nombre de la propiedad | Propiedad a recuperar |
-| `block` | `uint` | Altura del bloque de Stacks |
-
-Propiedades: `header-hash`, `block-hash`, `miner-address`, `block-reward`
-
-```clarity
-(get-stacks-block-info? block-hash u100) ;; Returns (optional (buff 32))
-
-;; Get stacks block data
-(define-read-only (get-stacks-block-hash (height uint))
- (get-stacks-block-info? block-hash height))
-```
-
-### get-tenure-info? \[#get-tenure-info]
-
-`get-tenure-info?` recupera información sobre la tenencia.
-
-**Firma**
-
-```clarity
-(get-tenure-info? property block)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `property` | Nombre de la propiedad | Propiedad a recuperar |
-| `block` | `uint` | Bloque de tenencia |
-
-Propiedades: `burnchain-header-hash`, `miner-address`, `time`, `vrf-seed`
-
-```clarity
-(get-tenure-info? vrf-seed u100) ;; Returns (optional (buff 32))
-
-;; Get tenure VRF seed
-(define-read-only (get-vrf-seed (tenure uint))
- (get-tenure-info? vrf-seed tenure))
-```
-
-### at-block \[#at-block]
-
-`at-block` evalúa una expresión en un contexto de bloque específico.
-
-**Firma**
-
-```clarity
-(at-block block-hash expr)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `block-hash` | `(buff 32)` | Hash del bloque |
-| `expr` | expresión | Expresión a evaluar |
-
-```clarity
-(at-block 0x1234... (var-get counter)) ;; Get historical value
-
-;; Historical balance
-(define-read-only (get-balance-at-block (user principal) (block-hash (buff 32)))
- (at-block block-hash (ft-get-balance my-token user)))
-```
-
-## Operaciones principales y de contrato \[#principal-contract-operations]
-
-### principal-construct? \[#principal-construct]
-
-`principal-construct?` crea un principal a partir de componentes de dirección.
-
-**Firma**
-
-```clarity
-(principal-construct? version-byte hash)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `version-byte` | `(buff 1)` | Byte de versión |
-| `hash` | `(buff 20)` | Hash de dirección |
-
-```clarity
-(principal-construct? 0x16 0x1234567890abcdef1234567890abcdef12345678)
-;; Returns (optional principal)
-
-;; Construct address
-(define-read-only (make-principal (version (buff 1)) (hash (buff 20)))
- (principal-construct? version hash))
-```
-
-### principal-destruct? \[#principal-destruct]
-
-`principal-destruct?` descompone un principal en componentes.
-
-**Firma**
-
-```clarity
-(principal-destruct? principal)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `principal` | `principal` | Principal a descomponer |
-
-```clarity
-(principal-destruct? tx-sender)
-;; Returns (optional { version: (buff 1), hash: (buff 20) })
-
-;; Get address components
-(define-read-only (get-principal-parts (user principal))
- (principal-destruct? user))
-```
-
-### principal-of? \[#principal-of]
-
-`principal-of?` devuelve el principal de una clave pública.
-
-**Firma**
-
-```clarity
-(principal-of? public-key)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `public-key` | `(buff 33)` | Clave pública |
-
-```clarity
-(principal-of? 0x0234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12)
-;; Returns (optional principal)
-
-;; Derive address
-(define-read-only (pubkey-to-principal (pubkey (buff 33)))
- (principal-of? pubkey))
-```
-
-### contract-call? \[#contract-call]
-
-`contract-call?` llama a una función pública en otro contrato.
-
-**Firma**
-
-```clarity
-(contract-call? contract function-name args...)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `contract` | principal | Contrato a llamar |
-| `function-name` | símbolo | Nombre de la función |
-| `args` | cualquier | Argumentos de función |
-
-```clarity
-(contract-call? .other-contract transfer u100 tx-sender recipient)
-
-;; Cross-contract call
-(define-public (forward-call (amount uint))
- (contract-call? .token-contract transfer amount tx-sender contract-owner))
-```
-
-### as-contract \[#as-contract]
-
-`as-contract` ejecuta una expresión con el contrato como tx-sender.
-
-**Firma**
-
-```clarity
-(as-contract expr)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `expr` | expresión | Expresión a ejecutar |
-
-```clarity
-(as-contract (stx-transfer? u1000 tx-sender recipient))
-
-;; Contract-owned transfers
-(define-public (withdraw-fees (recipient principal))
- (let ((balance (stx-get-balance (as-contract tx-sender))))
- (as-contract (stx-transfer? balance tx-sender recipient))))
-```
-
-### contrato-de \[#contract-of]
-
-`contract-of` devuelve el principal de una referencia de trait.
-
-**Firma**
-
-```clarity
-(contract-of trait-ref)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `trait-ref` | rasgo | Referencia de rasgo |
-
-```clarity
-(contract-of token-trait) ;; Returns principal
-
-;; Get implementation
-(define-read-only (get-token-contract)
- (contract-of deployed-token))
-```
-
-### es-estándar \[#is-standard]
-
-`is-standard` verifica si un principal coincide con el tipo de red actual y puede gastar tokens.
-
-**Firma**
-
-```clarity
-(is-standard standard-or-contract-principal)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `standard-or-contract-principal` | `principal` | Principal a verificar |
-
-```clarity
-;; On testnet
-(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6) ;; Returns true
-(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6.foo) ;; Returns true
-(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY) ;; Returns false
-
-;; On mainnet
-(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY) ;; Returns true
-(is-standard 'SP3X6QWWETNBZWGBK6DRGTR1KX50S74D3433WDGJY.foo) ;; Returns true
-(is-standard 'STB44HYPYAT2BB2QE513NSP81HTMYWBJP02HPGK6) ;; Returns false
-```
-
-Puntos clave:
-
-* Comprueba si un principal puede gastar tokens en la red actual
-* Mainnet: Solo `SP` y `SM` las direcciones pueden gastar
-* Testnet: Solo `ST` y `SN` las direcciones pueden gastar
-* Todas las direcciones pueden recibir tokens, pero solo los tipos de red coincidentes pueden gastarlos
-* Disponible a partir de Stacks 2.1
-
-```clarity
-;; Network-aware validation
-(define-read-only (can-spend-on-network (address principal))
- (is-standard address))
-
-;; Check if address matches network before allowing spending
-(define-public (network-aware-transfer (recipient principal) (amount uint))
- (begin
- (asserts! (is-standard tx-sender) (err u401))
- (asserts! (is-standard recipient) (err u402))
- ;; Transfer logic
- (ok true)))
-```
-
-## Rasgos \[#traits]
-
-### define-trait \[#define-trait]
-
-`define-trait` crea una nueva definición de rasgo.
-
-**Firma**
-
-```clarity
-(define-trait trait-name ((function-name (args...) response-type)...))
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `trait-name` | símbolo | Nombre del rasgo |
-| `function-name` | símbolo | Firmas de funciones |
-
-```clarity
-(define-trait fungible-token (
- (transfer (uint principal principal) (response bool uint))
- (get-balance (principal) (response uint uint))
-))
-
-;; NFT trait
-(define-trait nft-trait (
- (transfer (uint principal principal) (response bool uint))
- (get-owner (uint) (response (optional principal) uint))
-))
-```
-
-### impl-trait \[#impl-trait]
-
-`impl-trait` declara que un contrato implementa un rasgo.
-
-**Firma**
-
-```clarity
-(impl-trait trait-identifier)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `trait-identifier` | trait | Rasgo a implementar |
-
-```clarity
-(impl-trait .token-trait.fungible-token)
-
-;; Multiple traits
-(impl-trait .dao-traits.proposal-trait)
-(impl-trait .dao-traits.voting-trait)
-```
-
-### use-trait \[#use-trait]
-
-`use-trait` crea un alias de rasgo para usar en funciones.
-
-**Firma**
-
-```clarity
-(use-trait alias trait-identifier)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `alias` | símbolo | Alias local |
-| `trait-identifier` | rasgo | Rasgo a alias |
-
-```clarity
-(use-trait token-trait .token-trait.fungible-token)
-
-(define-public (swap (token ) (amount uint))
- (contract-call? token transfer amount tx-sender .pool))
-```
-
-## Conversiones de tipo \[#type-conversions]
-
-### to-int \[#to-int]
-
-`to-int` convierte un número entero sin signo a un número entero con signo.
-
-**Firma**
-
-```clarity
-(to-int uint)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `uint` | `uint` | Entero sin signo |
-
-```clarity
-(to-int u100) ;; Returns 100
-(to-int u0) ;; Returns 0
-
-;; Convert for calculations
-(define-read-only (calculate-delta (a uint) (b uint))
- (- (to-int a) (to-int b)))
-```
-
-### to-uint \[#to-uint]
-
-`to-uint` convierte un número entero con signo a un número entero sin signo.
-
-**Firma**
-
-```clarity
-(to-uint int)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `int` | `int` | Número entero con signo |
-
-```clarity
-(to-uint 100) ;; Returns u100
-(to-uint -50) ;; Causes runtime error
-
-;; Safe conversion
-(define-read-only (safe-to-uint (value int))
- (if (>= value 0)
- (some (to-uint value))
- none))
-```
-
-### to-consensus-buff? \[#to-consensus-buff]
-
-`to-consensus-buff?` serializa un valor al formato de consenso.
-
-**Firma**
-
-```clarity
-(to-consensus-buff? value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `value` | cualquier | Valor para serializar |
-
-```clarity
-(to-consensus-buff? u100) ;; Returns (optional (buff 3))
-(to-consensus-buff? { a: u1, b: u2 }) ;; Serializes tuple
-
-;; Create hash of data
-(define-read-only (hash-value (data uint))
- (match (to-consensus-buff? data)
- buff (sha256 buff)
- 0x00))
-```
-
-### from-consensus-buff? \[#from-consensus-buff]
-
-`from-consensus-buff?` deserializa desde el formato de consenso.
-
-**Firma**
-
-```clarity
-(from-consensus-buff? type buffer)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `type` | tipo-firma | Tipo esperado |
-| `buffer` | `buff` | Buffer a deserializar |
-
-```clarity
-(from-consensus-buff? uint 0x0100) ;; Returns (optional u1)
-(from-consensus-buff? { a: uint, b: uint } buff) ;; Deserialize tuple
-
-;; Parse stored data
-(define-read-only (decode-data (data (buff 128)))
- (from-consensus-buff? { value: uint, timestamp: uint } data))
-```
-
-## Operaciones de bits \[#bit-operations]
-
-### bit-and \[#bit-and]
-
-`bit-and` realiza la operación AND a nivel de bits.
-
-**Firma**
-
-```clarity
-(bit-and i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Primer valor |
-| `i2` | `int` o `uint` | Segundo valor |
-
-```clarity
-(bit-and u12 u10) ;; Returns u8 (1100 & 1010 = 1000)
-(bit-and 0xFF 0x0F) ;; Returns 0x0F
-
-;; Check flags
-(define-read-only (has-permission (flags uint) (permission uint))
- (> (bit-and flags permission) u0))
-```
-
-### bit-or \[#bit-or]
-
-`bit-or` realiza la operación OR a nivel de bits.
-
-**Firma**
-
-```clarity
-(bit-or i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Primer valor |
-| `i2` | `int` o `uint` | Segundo valor |
-
-```clarity
-(bit-or u12 u10) ;; Returns u14 (1100 | 1010 = 1110)
-(bit-or 0xF0 0x0F) ;; Returns 0xFF
-
-;; Set flags
-(define-public (add-permission (current uint) (new-permission uint))
- (ok (bit-or current new-permission)))
-```
-
-### bit-xor \[#bit-xor]
-
-`bit-xor` realiza la operación XOR a nivel de bits.
-
-**Firma**
-
-```clarity
-(bit-xor i1 i2)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i1` | `int` o `uint` | Primer valor |
-| `i2` | `int` o `uint` | Segundo valor |
-
-```clarity
-(bit-xor u12 u10) ;; Returns u6 (1100 ^ 1010 = 0110)
-(bit-xor 0xFF 0xFF) ;; Returns 0x00
-
-;; Toggle flags
-(define-public (toggle-flag (flags uint) (flag uint))
- (ok (bit-xor flags flag)))
-```
-
-### bit-not \[#bit-not]
-
-`bit-not` realiza la operación de NOT a nivel de bits.
-
-**Firma**
-
-```clarity
-(bit-not i)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i` | `int` o `uint` | Valor a invertir |
-
-```clarity
-(bit-not u0) ;; Returns maximum uint
-(bit-not 0xFF) ;; Returns -256
-
-;; Invert permissions
-(define-read-only (get-inverse-permissions (permissions uint))
- (bit-not permissions))
-```
-
-### bit-shift-left \[#bit-shift-left]
-
-`bit-shift-left` desplaza bits hacia la izquierda.
-
-**Firma**
-
-```clarity
-(bit-shift-left i positions)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i` | `int` o `uint` | Valor a desplazar |
-| `positions` | `uint` | Posiciones para desplazar |
-
-```clarity
-(bit-shift-left u1 u3) ;; Returns u8 (1 << 3)
-(bit-shift-left u5 u2) ;; Returns u20
-
-;; Calculate power of 2
-(define-read-only (pow2 (exponent uint))
- (bit-shift-left u1 exponent))
-```
-
-### bit-shift-right \[#bit-shift-right]
-
-`bit-shift-right` desplaza bits hacia la derecha.
-
-**Firma**
-
-```clarity
-(bit-shift-right i positions)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `i` | `int` o `uint` | Valor a desplazar |
-| `positions` | `uint` | Posiciones para desplazar |
-
-```clarity
-(bit-shift-right u8 u3) ;; Returns u1 (8 >> 3)
-(bit-shift-right u20 u2) ;; Returns u5
-
-;; Fast division by power of 2
-(define-read-only (div-pow2 (value uint) (exponent uint))
- (bit-shift-right value exponent))
-```
-
-## Funciones de utilidad \[#utility-functions]
-
-### print \[#print]
-
-`print` devuelve un valor y lo retorna.
-
-**Firma**
-
-```clarity
-(print value)
-```
-
-**Parámetros**
-
-| Nombre | Tipo | Descripción |
-|------|------|-------------|
-| `value` | cualquiera | Valor a imprimir |
-
-```clarity
-(print "Debug message") ;; Prints and returns "Debug message"
-(print { event: "transfer", amount: u100 })
-
-;; Debug function
-(define-public (debug-transfer (amount uint))
- (begin
- (print { function: "transfer", amount: amount, sender: tx-sender })
- (ok true)))
-```
diff --git a/content/docs/es/resources/clarity/reference/keywords.mdx b/content/docs/es/resources/clarity/reference/keywords.mdx
deleted file mode 100644
index e006c6503..000000000
--- a/content/docs/es/resources/clarity/reference/keywords.mdx
+++ /dev/null
@@ -1,560 +0,0 @@
----
-title: Referencia de palabras clave
-sidebarTitle: Palabras clave
-description: Referencia completa de todas las palabras clave de Clarity, incluyendo constantes, variables de contexto y datos de blockchain.
-isNew: true
----
-Clarity proporciona palabras clave incorporadas para acceder al estado de la blockchain, el contexto de la transacción y valores constantes. Estas palabras clave permiten a los contratos inteligentes interactuar con la blockchain de Stacks y tomar decisiones basadas en el contexto de ejecución actual.
-
-* Constantes booleanas: [`true`](#true), [`false`](#false)
-* Constante opcional: [`none`](#none)
-* Información del bloque: [`block-height`](#block-height), [`burn-block-height`](#burn-block-height), [`stacks-block-height`](#stacks-block-height), [`tenure-height`](#tenure-height)
-* Contexto de la transacción: [`tx-sender`](#tx-sender), [`tx-sponsor`](#tx-sponsor), [`contract-caller`](#contract-caller)
-* Información de la cadena: [`chain-id`](#chain-id), [`is-in-mainnet`](#is-in-mainnet), [`is-in-regtest`](#is-in-regtest)
-* Datos económicos: [`stx-liquid-supply`](#stx-liquid-supply)
-
-## Constantes booleanas \[#boolean-constants]
-
-### verdadero \[#true]
-
-`true` representa el valor booleano verdadero en Clarity.
-
-**Tipo**
-
-```clarity
-bool
-```
-
-```clarity
-;; Direct usage
-(define-constant is-active true)
-
-;; In conditionals
-(if true
- (print "This will execute")
- (print "This won't execute"))
-
-;; Boolean operations
-(and true true) ;; Returns true
-(or false true) ;; Returns true
-```
-
-Los patrones comunes incluyen el uso de `true` para:
-
-* Estados habilitados por defecto en la configuración
-* Valores de retorno de éxito en funciones públicas
-* Banderas y conmutadores de características
-
-```clarity
-(define-data-var protocol-enabled bool true)
-
-(define-public (pause-protocol)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (var-set protocol-enabled false)
- (ok true)))
-
-;; Feature toggle pattern
-(define-map features (string-ascii 50) bool)
-(map-set features "trading" true)
-(map-set features "staking" true)
-```
-
-### falso \[#false]
-
-`false` representa el valor booleano falso en Clarity.
-
-**Tipo**
-
-```clarity
-bool
-```
-
-```clarity
-;; Direct usage
-(define-constant is-paused false)
-
-;; In conditionals
-(if false
- (print "This won't execute")
- (print "This will execute"))
-
-;; Boolean operations
-(and true false) ;; Returns false
-(or false false) ;; Returns false
-```
-
-Los patrones comunes incluyen el uso de `false` para:
-
-* Estados deshabilitados predeterminados
-* Indicadores de fallo
-* Estados iniciales no establecidos
-
-```clarity
-(define-data-var is-initialized bool false)
-
-(define-public (initialize)
- (begin
- (asserts! (not (var-get is-initialized)) (err u100))
- (var-set is-initialized true)
- (ok true)))
-
-;; Access control pattern
-(define-map admins principal bool)
-(define-read-only (is-admin (user principal))
- (default-to false (map-get? admins user)))
-```
-
-## Constante opcional \[#optional-constant]
-
-### ninguno \[#ninguno]
-
-`none` representa un valor opcional vacío.
-
-**Tipo**
-
-```clarity
-(optional ?)
-```
-
-```clarity
-;; Direct usage
-(define-constant empty-value none)
-
-;; Optional map returns
-(map-get? non-existent-map non-existent-key) ;; Returns none
-
-;; Pattern matching
-(match (map-get? balances user)
- balance (+ balance u100)
- u0) ;; If none, return u0
-```
-
-Los patrones comunes incluyen:
-
-* Valores predeterminados para tipos opcionales
-* Representando la ausencia de datos
-* Estados iniciales antes de que se establezcan los datos
-
-```clarity
-(define-map user-profiles principal
- {
- name: (string-ascii 50),
- created-at: uint
- })
-
-(define-read-only (get-user-name (user principal))
- (match (map-get? user-profiles user)
- profile (some (get name profile))
- none)) ;; Return none if profile doesn't exist
-
-;; Clearing optional data
-(define-data-var current-proposal (optional uint) none)
-(define-public (clear-proposal)
- (begin
- (var-set current-proposal none)
- (ok true)))
-```
-
-## Información del bloque \[#block-information]
-
-### altura-del-bloque \[#altura-del-bloque]
-
-`block-height` devuelve la altura actual del bloque de Stacks.
-
-**Tipo**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get current height
-(print block-height)
-
-;; Time-locked functionality
-(define-public (claim-rewards)
- (begin
- (asserts! (> block-height u50000) (err u1))
- (ok true)))
-```
-
-Los casos de uso incluyen:
-
-* Implementación de programas de adquisición de derechos
-* Creando fases basadas en tiempo
-* Grabación de marcas de tiempo
-* Aplicando retrasos
-
-```clarity
-(define-constant VESTING_START u100000)
-(define-constant VESTING_PERIOD u4320) ;; ~30 days
-
-(define-read-only (get-vested-amount (total uint))
- (if (<= block-height VESTING_START)
- u0
- (let ((blocks-elapsed (- block-height VESTING_START)))
- (if (>= blocks-elapsed VESTING_PERIOD)
- total
- (/ (* total blocks-elapsed) VESTING_PERIOD)))))
-
-;; Phase-based protocol
-(define-constant PHASE1_END u100000)
-(define-constant PHASE2_END u200000)
-
-(define-read-only (get-current-phase)
- (if (<= block-height PHASE1_END)
- u1
- (if (<= block-height PHASE2_END)
- u2
- u3)))
-```
-
-### altura-del-bloque-quemado \[#altura-del-bloque-quemado]
-
-`burn-block-height` devuelve la altura actual del bloque de Bitcoin.
-
-**Tipo**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get current Bitcoin height
-(print burn-block-height)
-
-;; Bitcoin-anchored timing
-(define-read-only (get-burn-height-difference)
- (- burn-block-height u700000))
-```
-
-Usos comunes:
-
-* Marcas de tiempo ancladas a Bitcoin
-* Coordinación de tiempos entre cadenas
-* Cálculos de Prueba de Transferencia
-
-```clarity
-(define-map btc-price-at-height uint uint)
-
-(define-public (record-btc-price (price uint))
- (begin
- (map-set btc-price-at-height burn-block-height price)
- (ok burn-block-height)))
-
-;; Time calculations based on Bitcoin blocks
-(define-read-only (hours-since (btc-height uint))
- (/ (- burn-block-height btc-height) u6)) ;; ~6 blocks per hour
-```
-
-### altura-del-bloque-stacks \[#altura-del-bloque-stacks]
-
-`stacks-block-height` devuelve la altura actual de la punta de la cadena Stacks (para Stacks 2.5+).
-
-**Tipo**
-
-```clarity
-uint
-```
-
-```clarity
-;; Stacks 2.5+ specific height
-(print stacks-block-height)
-
-;; Height comparison
-(define-read-only (get-height-info)
- {
- stacks: stacks-block-height,
- block: block-height,
- difference: (- stacks-block-height block-height)
- })
-```
-
-### altura-de-tenencia \[#altura-de-tenencia]
-
-`tenure-height` devuelve el número de tenencias (ciclos de recompensa) que han transcurrido.
-
-**Tipo**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get current tenure
-(print tenure-height)
-
-;; Tenure-based rewards
-(define-map tenure-rewards uint uint)
-
-(define-read-only (get-rewards-for-tenure (tenure uint))
- (default-to u0 (map-get? tenure-rewards tenure)))
-```
-
-## Contexto de transacción \[#transaction-context]
-
-### tx-sender \[#tx-sender]
-
-`tx-sender` devuelve el principal que inició la transacción actual.
-
-**Tipo**
-
-```clarity
-principal
-```
-
-```clarity
-;; Get transaction originator
-(print tx-sender)
-
-;; Authorization pattern
-(define-constant contract-owner tx-sender)
-
-(define-public (admin-only-function)
- (begin
- (asserts! (is-eq tx-sender contract-owner) (err u401))
- (ok true)))
-```
-
-Características clave:
-
-* Se mantiene constante durante todas las llamadas al contrato
-* Siempre representa al iniciador original de la transacción
-* Utilizado para autorización y propiedad
-
-```clarity
-(define-map balances principal uint)
-
-(define-public (deposit (amount uint))
- (begin
- (try! (stx-transfer? amount tx-sender (as-contract tx-sender)))
- (map-set balances tx-sender
- (+ (default-to u0 (map-get? balances tx-sender)) amount))
- (ok amount)))
-
-;; Multi-signature pattern
-(define-map signers principal bool)
-(define-public (add-signature (proposal-id uint))
- (begin
- (asserts! (default-to false (map-get? signers tx-sender)) (err u401))
- ;; Add signature logic
- (ok true)))
-```
-
-### tx-sponsor \[#tx-sponsor]
-
-`tx-sponsor` devuelve el principal que paga las tarifas de transacción (opcional).
-
-**Tipo**
-
-```clarity
-(optional principal)
-```
-
-```clarity
-;; Check if transaction is sponsored
-(match tx-sponsor
- sponsor (print { sponsored-by: sponsor })
- (print "Not a sponsored transaction"))
-
-;; Get sponsor or sender
-(define-read-only (get-fee-payer)
- (default-to tx-sender tx-sponsor))
-```
-
-Casos de uso:
-
-* Programas de subsidio de tarifas
-* Transacciones sin gas
-* Incorporación patrocinada
-* Adquisición de usuarios
-
-```clarity
-(define-map sponsored-actions { user: principal, sponsor: principal } uint)
-
-(define-public (sponsored-action)
- (match tx-sponsor
- sponsor (begin
- ;; Record sponsored action
- (map-set sponsored-actions
- { user: tx-sender, sponsor: sponsor }
- (+ (default-to u0 (map-get? sponsored-actions
- { user: tx-sender, sponsor: sponsor })) u1))
- (ok { user: tx-sender, sponsor: sponsor }))
- (err u1))) ;; Must be sponsored
-
-;; Subsidized operations with approved sponsors
-(define-map approved-sponsors principal bool)
-
-(define-public (subsidized-transfer (recipient principal) (amount uint))
- (match tx-sponsor
- sponsor (begin
- (asserts! (default-to false (map-get? approved-sponsors sponsor)) (err u401))
- (ft-transfer? my-token amount tx-sender recipient))
- ;; Not sponsored - user pays normally
- (ft-transfer? my-token amount tx-sender recipient)))
-```
-
-### contract-caller \[#contract-caller]
-
-`contract-caller` devuelve el principal llamante inmediato (contrato o usuario).
-
-**Tipo**
-
-```clarity
-principal
-```
-
-```clarity
-;; Get immediate caller
-(print contract-caller)
-
-;; Direct-call only
-(define-public (direct-only)
- (begin
- (asserts! (is-eq tx-sender contract-caller) (err u405))
- (ok true)))
-```
-
-Distinciones importantes:
-
-* Cambios con cada llamada de contrato
-* Igual a `tx-sender` para llamadas directas
-* Representa el contrato que llama en llamadas de contrato a contrato
-
-```clarity
-;; Contract A
-(define-public (call-contract-b)
- (contract-call? .contract-b check-callers))
-
-;; Contract B
-(define-public (check-callers)
- (begin
- (print {
- tx-sender: tx-sender, ;; Original user
- contract-caller: contract-caller ;; Contract A
- })
- (ok true)))
-
-;; Allowlist pattern
-(define-map allowed-contracts principal bool)
-(define-public (restricted-function)
- (begin
- (asserts!
- (or
- (is-eq tx-sender contract-caller) ;; Direct call
- (default-to false (map-get? allowed-contracts contract-caller)))
- (err u401))
- (ok true)))
-```
-
-## Información de la cadena \[#chain-information]
-
-### chain-id \[#chain-id]
-
-`chain-id` devuelve el identificador de cadena de 32 bytes.
-
-**Tipo**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get chain ID
-(print chain-id)
-
-;; Mainnet: 0x00000001
-;; Testnet: 0x80000000
-```
-
-### está-en-mainnet \[#esta-en-mainnet]
-
-`is-in-mainnet` devuelve true si el contrato se está ejecutando en la red principal.
-
-**Tipo**
-
-```clarity
-bool
-```
-
-```clarity
-;; Check if on mainnet
-(asserts! is-in-mainnet (err u500))
-
-;; Environment-specific constants
-(define-constant TOKEN-SUPPLY
- (if is-in-mainnet
- u1000000000 ;; 1 billion on mainnet
- u1000000)) ;; 1 million on testnet
-```
-
-### está-en-regtest \[#esta-en-regtest]
-
-`is-in-regtest` devuelve true si el contrato se está ejecutando en regtest.
-
-**Tipo**
-
-```clarity
-bool
-```
-
-```clarity
-;; Development-only functions
-(define-public (debug-function)
- (begin
- (asserts! is-in-regtest (err u403))
- ;; Debug logic
- (ok true)))
-```
-
-## Datos económicos \[#economic-data]
-
-### suministro-líquido-de-stx \[#suministro-líquido-de-stx]
-
-`stx-liquid-supply` devuelve el suministro total de STX líquido en micro-STX.
-
-**Tipo**
-
-```clarity
-uint
-```
-
-```clarity
-;; Get current liquid supply
-(print stx-liquid-supply)
-
-;; Calculate percentage of supply
-(define-read-only (get-percent-of-liquid (amount uint))
- (/ (* amount u10000) stx-liquid-supply)) ;; Returns basis points
-```
-
-Casos de uso:
-
-* Cálculos económicos
-* Límites basados en el suministro
-* Implementaciones de tokenomía
-* Umbrales de gobernanza
-
-```clarity
-;; Dynamic fee based on supply percentage
-(define-constant FEE_BASIS_POINTS u50) ;; 0.5%
-
-(define-read-only (calculate-dynamic-fee (amount uint))
- (let (
- (supply-ratio (/ (* amount u1000000) stx-liquid-supply))
- (multiplier (+ u100 supply-ratio)))
- (/ (* amount FEE_BASIS_POINTS multiplier) u10000)))
-
-;; Governance with supply-based thresholds
-(define-constant PROPOSAL_THRESHOLD_BASIS u100) ;; 1% of liquid supply
-
-(define-public (create-proposal (description (string-utf8 500)))
- (let (
- (required-stake (/ (* stx-liquid-supply PROPOSAL_THRESHOLD_BASIS) u10000))
- (user-balance (stx-get-balance tx-sender)))
- (asserts! (>= user-balance required-stake) (err u402))
- (try! (stx-transfer? required-stake tx-sender (as-contract tx-sender)))
- (ok required-stake)))
-```
diff --git a/content/docs/es/resources/clarity/reference/types.mdx b/content/docs/es/resources/clarity/reference/types.mdx
deleted file mode 100644
index b0e7ab4f2..000000000
--- a/content/docs/es/resources/clarity/reference/types.mdx
+++ /dev/null
@@ -1,193 +0,0 @@
----
-title: Referencia de tipos
-sidebarTitle: Tipos
-description: El sistema de tipos de Clarity garantiza la corrección del programa mediante la comprobación estática de tipos
----
-Clarity utiliza un sistema de tipos estático robusto. Los argumentos de las funciones y los esquemas de bases de datos requieren tipos especificados, y todos los tipos son conocidos al momento de la publicación.
-
-## Tipos primitivos
-
-### int
-
-Entero con signo de 128 bits. Rango desde -2^127 hasta 2^127 - 1.
-
-```clarity
-(define-constant my-int -10)
-(define-constant max-int 170141183460469231731687303715884105727)
-```
-
-### uint
-
-Entero sin signo de 128 bits. Rango de 0 a 2^128 - 1.
-
-```clarity
-(define-constant my-uint u10)
-(define-constant max-uint u340282366920938463463374607431768211455)
-```
-
-### booleano
-
-Valor booleano que representa verdadero o falso.
-
-```clarity
-(define-constant is-active true)
-(define-constant is-disabled false)
-```
-
-### principal
-
-Representa un objeto que puede tener un saldo de tokens. Puede ser un principal estándar (dirección de usuario) o un principal de contrato.
-
-```clarity
-;; Standard principal
-'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
-
-;; Contract principal
-'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.contract-name
-```
-
-## Tipos de secuencias
-
-### (buff max-len)
-
-Búfer de bytes con una longitud máxima. Utilizado para datos binarios arbitrarios.
-
-```clarity
-(define-constant my-buff 0x68656c6c6f) ;; "hello" in hex
-(define-data-var message (buff 20) 0x00)
-```
-
-### (cadena-ascii longitud-máxima)
-
-Cadena ASCII con longitud máxima. Solo admite caracteres ASCII.
-
-```clarity
-(define-constant name (string-ascii 50) "Clarity")
-(define-data-var user-name (string-ascii 100) "")
-```
-
-### (cadena-utf8 longitud-máxima)
-
-Cadena UTF-8 con longitud máxima. Admite caracteres Unicode.
-
-```clarity
-(define-constant greeting (string-utf8 50) u"Hello L! =�")
-(define-data-var status-message (string-utf8 280) u"")
-```
-
-### (lista longitud-máxima tipo-entrada)
-
-Lista homogénea con longitud máxima especificada y tipo de entrada.
-
-```clarity
-(define-constant numbers (list 5 uint) (list u1 u2 u3 u4 u5))
-(define-data-var prices (list 100 uint) (list))
-```
-
-## Tipos compuestos
-
-### Tupla
-
-Registro con campos nombrados. Cada campo tiene un tipo especificado.
-
-```clarity
-{
- name: (string-ascii 50),
- age: uint,
- active: bool
-}
-
-;; Example usage
-(define-constant user {
- name: "Alice",
- age: u30,
- active: true
-})
-```
-
-Los tuples se utilizan comúnmente para:
-
-* Devolviendo múltiples valores desde funciones
-* Estructurando datos complejos
-* Mapear claves y valores
-
-## Tipos especiales
-
-### (tipo opcional)
-
-Representa un valor que podría no existir. Puede ser `(some value)` o `none`.
-
-```clarity
-(define-data-var winner (optional principal) none)
-
-;; Set value
-(var-set winner (some 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM))
-
-;; Check value
-(match (var-get winner)
- user (print user)
- (print "No winner yet")
-)
-```
-
-### (respuesta tipo-ok tipo-err)
-
-Utilizado por funciones públicas para indicar éxito o fracaso. Las respuestas exitosas confirman los cambios de estado, mientras que las respuestas de error abortan todos los cambios.
-
-```clarity
-(define-public (divide (a uint) (b uint))
- (if (is-eq b u0)
- (err u1) ;; Division by zero error
- (ok (/ a b))
- )
-)
-```
-
-Los tipos de respuesta permiten:
-
-* Semántica de transacciones atómicas
-* Manejo de errores componible
-* Rutas claras de éxito/fracaso
-
-## Firmas de tipo
-
-Las funciones deben especificar firmas de tipo completas:
-
-```clarity
-;; Read-only function
-(define-read-only (get-balance (user principal))
- (response uint uint)
- ;; Function body
-)
-
-;; Public function
-(define-public (transfer (amount uint) (recipient principal))
- (response bool uint)
- ;; Function body
-)
-
-;; Private function
-(define-private (validate-amount (amount uint))
- bool
- ;; Function body
-)
-```
-
-## Inferencia de tipos
-
-Si bien Clarity requiere anotaciones de tipo explícitas para las firmas de funciones y declaraciones de datos, puede inferir tipos dentro de los cuerpos de las funciones:
-
-```clarity
-(define-read-only (calculate)
- (let ((x 10) ;; Inferred as int
- (y u20) ;; Inferred as uint
- (name "Test")) ;; Inferred as string-ascii
- (ok x))
-)
-```
-
-:::callout
-### Seguridad de tipos
-
-El sistema de tipos de Clarity previene muchos errores comunes de programación en el momento de la publicación, antes de que se ejecute cualquier código. Esto incluye incompatibilidades de tipos, excepciones de puntero nulo y desbordamientos de búfer.
-:::
diff --git a/content/docs/es/resources/guides/using-pyth-price-feeds.mdx b/content/docs/es/resources/guides/using-pyth-price-feeds.mdx
index 272dfb4fb..5fbb2635d 100644
--- a/content/docs/es/resources/guides/using-pyth-price-feeds.mdx
+++ b/content/docs/es/resources/guides/using-pyth-price-feeds.mdx
@@ -182,7 +182,7 @@ Crearemos un "Benjamin Club" - un NFT exclusivo que cuesta exactamente $100 en v
)
```
- Para una explicación detallada de los componentes del contrato, consulte nuestra [Guía de integración de Clarity](/resources/clarity/external-data).
+ Para una explicación detallada de los componentes del contrato, consulte la [referencia de contratos inteligentes de Stacks](https://docs.stacks.co/reference).
@@ -265,7 +265,7 @@ Crearemos un "Benjamin Club" - un NFT exclusivo que cuesta exactamente $100 en v
}
```
- Para obtener detalles completos sobre la integración del frontend, consulte nuestra [Guía de integración de Stacks.js](/reference/stacks.js/pyth-oracle-integration).
+ Para obtener detalles completos sobre la integración del frontend, consulte la [referencia para desarrolladores de Stacks](https://docs.stacks.co/reference).
@@ -305,7 +305,7 @@ Crearemos un "Benjamin Club" - un NFT exclusivo que cuesta exactamente $100 en v
});
```
- Para estrategias avanzadas de pruebas, incluyendo simulación de mainnet, consulte nuestra [Guía de pruebas de Clarinet](/tools/clarinet/pyth-oracle-integration).
+ Para estrategias avanzadas de pruebas, incluyendo simulación de mainnet, consulte la [referencia oficial de Stacks](https://docs.stacks.co/reference).
@@ -421,6 +421,6 @@ Agrupe múltiples actualizaciones de precios cuando sea posible:
## Próximos pasos
:::next-steps
-* [Inmersión profunda en Clarity](/resources/clarity/external-data): Patrones avanzados de oráculos y optimizaciones
-* [Inmersión profunda en el frontend](/reference/stacks.js/pyth-oracle-integration): Construyendo interfaces de usuario de oráculos listas para producción
+* [Inmersión profunda en Clarity](https://docs.stacks.co/reference): Patrones avanzados de oráculos y optimizaciones
+* [Inmersión profunda en el frontend](https://docs.stacks.co/reference): Construyendo interfaces de usuario de oráculos listas para producción
:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-cli)/clarity-formatter.mdx b/content/docs/es/tools/clarinet/(clarinet-cli)/clarity-formatter.mdx
deleted file mode 100644
index 624eb25de..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-cli)/clarity-formatter.mdx
+++ /dev/null
@@ -1,165 +0,0 @@
----
-title: Formateador de claridad
-sidebarTitle: Formateador de claridad
-description: El formateador de Clarity es una herramienta diseñada para formatear automáticamente el código de tu contrato inteligente en Clarity según reglas de estilo estandarizadas. Usar un formato consistente mejora la legibilidad y mantenibilidad del código, facilitando a los desarrolladores entender, colaborar y aprender de proyectos existentes en Clarity.
----
-## Filosofía de formato
-
-El formateador aplica un estándar predefinido diseñado para hacer que el código de Clarity sea más legible:
-
-* **Longitud de línea** - Las líneas se ajustan a 80 caracteres por defecto
-* **Sangría** - Usa 2 espacios para consistencia
-* **Estructura** - Impone patrones consistentes para funciones, enlaces let y flujo de control
-
-Estos valores predeterminados son configurables para adaptarse a tus preferencias.
-
-### Puntos de integración
-
-El formateador está disponible en dos herramientas de desarrollo principales:
-
-1. **Extensión Clarity para VS Code** - Formatear directamente dentro de tu editor
-2. **Clarinet CLI** - Formatear a través de la línea de comandos, incluyendo proyectos completos
-
-## Tabla de comparación
-
-| Aspecto | Formato Manual | Formateador de Clarity |
-|--------|------------------|-------------------|
-| Consistencia | Varía según el desarrollador | Uniforme en toda la base de código |
-| Velocidad | Consume tiempo | Instantáneo |
-| Propenso a errores | Sí | No |
-| Coordinación del equipo | Requiere guía de estilo | Aplicación automática |
-
-## Mejores prácticas
-
-* **Formatear al guardar** - Habilitar el formato automático en VS Code
-* **Ganchos pre-commit** - Asegúrate de que todo el código esté formateado antes de los commits
-* **Adopción del equipo** - Utiliza configuraciones consistentes en todo tu equipo
-
-## Lecturas adicionales
-
-### Reglas de formato en detalle
-
-El formateador maneja muchas construcciones de Clarity con reglas específicas:
-
-
-
- Definiciones de funciones
-
-
- Las funciones siempre abarcan múltiples líneas con sangría consistente:
-
- ```clarity
- (define-public (my-func
- (amount uint)
- (sender principal)
- )
- (ok true)
- )
- ```
-
- Los argumentos individuales pueden permanecer en la primera línea:
-
- ```clarity
- (define-read-only (get-balance (who principal))
- (ok u0)
- )
- ```
-
-
-
-
- Expresiones let
-
-
- Los enlaces se colocan en líneas separadas con sangría consistente:
-
- ```clarity
- (let (
- (a u1)
- (b u2)
- )
- (body-expression)
- )
- ```
-
-
-
-
- Control de flujo (if, match)
-
-
- Cada rama obtiene su propia línea:
-
- ```clarity
- (if condition
- (then-expression)
- (else-expression)
- )
-
- (match optional-value
- value (handle-some value)
- (handle-none)
- )
- ```
-
-
-
-
- Tuplas y mapas
-
-
- Convierte automáticamente a sintaxis endulzada con formato adecuado:
-
- ```clarity
- ;; Input: (tuple (n1 u1) (n2 u2))
- ;; Output:
- {
- n1: u1,
- n2: u2,
- }
- ```
-
-
-
-
-### Ejemplos de uso
-
-#### Integración con VS Code
-
-```json
-// settings.json
-"[clarity]": {
- "editor.formatOnSave": true,
-},
-```
-
-#### Uso de la CLI
-
-```terminal
-$ clarinet format --in-place
-```
-
-Formato con configuraciones personalizadas:
-
-```terminal
-$ clarinet format -i 4 -l 120 --in-place
-```
-
-Verificar el formato en los pipelines de CI/CD:
-
-```terminal
-$ clarinet format --check
-```
-
-El `--check` flag valida que todos los archivos de Clarity estén correctamente formateados sin modificarlos. Esto es perfecto para flujos de trabajo de integración continua donde se desea garantizar la consistencia del estilo de código.
-
-### Ignorando bloques de código
-
-Evitar el formato de bloques de código específicos:
-
-```clarity
-;; @format-ignore
-(define-constant something (list
- 1 2 3 ;; Preserves custom spacing
- 4 5 ))
-```
diff --git a/content/docs/es/tools/clarinet/(clarinet-cli)/cli-reference.mdx b/content/docs/es/tools/clarinet/(clarinet-cli)/cli-reference.mdx
deleted file mode 100644
index b43689e39..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-cli)/cli-reference.mdx
+++ /dev/null
@@ -1,414 +0,0 @@
----
-title: Referencia de la CLI
-sidebarTitle: Referencia de la CLI
-isNew: true
----
-El CLI de Clarinet proporciona un conjunto completo de herramientas para el desarrollo de contratos inteligentes en Clarity. Desde la inicialización del proyecto hasta la implementación, Clarinet optimiza todo tu flujo de trabajo de desarrollo.
-
-* Crear un nuevo proyecto: [`clarinet new`](#clarinet-new)
-* Generar un nuevo contrato inteligente: [`clarinet contracts new`](#clarinet-contracts)
-* Validar la sintaxis y los tipos del contrato: [`clarinet check`](#clarinet-check)
-* Interactive REPL for testing contracts: [`clarinet console`](#clarinet-console)
-* Lanza una red de desarrollo local: [`clarinet devnet start`](#clarinet-devnet)
-* Gestionar despliegues: [`clarinet deployments`](#clarinet-deployments)
-
-## Inicializar un nuevo proyecto \[#initialize-a-new-project]
-
-### clarinet new
-
-`clarinet new` crea un nuevo proyecto con todos los archivos de configuración y la estructura de directorios necesarios.
-
-**Uso**
-
-```console
-clarinet new [OPTIONS]
-```
-
-```terminal
-$ clarinet new my-defi-protocol
-[32mCreate directory[0m [1mmy-defi-protocol[0m
-[32mCreate directory[0m [1mcontracts[0m
-[32mCreate directory[0m [1msettings[0m
-[32mCreate directory[0m [1mtests[0m
-[32mCreate file[0m [1mClarinet.toml[0m
-[32mCreate file[0m [1msettings/Mainnet.toml[0m
-[32mCreate file[0m [1msettings/Testnet.toml[0m
-[32mCreate file[0m [1msettings/Devnet.toml[0m
-[32mCreate directory[0m [1m.vscode[0m
-[32mCreate file[0m [1m.vscode/settings.json[0m
-[32mCreate file[0m [1m.vscode/tasks.json[0m
-[32mCreate file[0m [1m.gitignore[0m
-[32mCreate file[0m [1m.gitattributes[0m
-[32mCreate file[0m [1mpackage.json[0m
-[32mCreate file[0m [1mtsconfig.json[0m
-[32mCreate file[0m [1mvitest.config.js[0m
-```
-
-| Opción | Descripción |
-|--------|-------------|
-| `--disable-telemetry` | No proporcionar telemetría de uso del desarrollador para este proyecto |
-
-## Gestiona tus contratos \[#manage-your-contracts]
-
-### contratos de Clarinet
-
-`clarinet contracts` es un subcomando para trabajar con contratos. Tiene dos subcomandos:
-
-| Comando | Descripción |
-|---------|-------------|
-| `new` | Generar archivos y configuraciones para un nuevo contrato |
-| `rm` | Eliminar archivos y configuraciones de un contrato |
-
-**Uso con `new`**
-
-```console
-clarinet contracts new
-```
-
-```terminal
-$ clarinet contracts new fungible-token
-[32mCreated file[0m [1mcontracts/fungible-token.clar[0m
-[32mCreated file[0m [1mtests/fungible-token.test.ts[0m
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-**Uso con `rm`**
-
-```console
-clarinet contracts rm
-```
-
-```terminal
-$ clarinet contracts rm old-token
-[33mRemoved file[0m [1mcontracts/old-token.clar[0m
-[33mRemoved file[0m [1mtests/old-token.test.ts[0m
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-| Opción | Descripción |
-|--------|-------------|
-| `--manifest-path ` | Ruta a Clarinet.toml |
-
-## Valide sus contratos \[#validate-your-contracts]
-
-### clarinet check
-
-`clarinet check` verifica la sintaxis de los contratos y realiza la comprobación de tipos.
-
-**Uso**
-
-```console
-$ clarinet check [FILE] [OPTIONS]
-```
-
-```terminal
-$ clarinet check
-[32m✔[0m [1m3 contracts checked[0m
-$ clarinet check contracts/token.clar
-[32m✔[0m [1mcontracts/token.clar syntax checks passed[0m
-```
-
-| Opción | Corto | Descripción |
-|--------|-------|-------------|
-| `--manifest-path ` | `-m` | Ruta a Clarinet.toml |
-| `--deployment-plan-path ` | `-p` | Si se especifica, utilizar este archivo de implementación |
-| `--use-on-disk-deployment-plan` | `-d` | Usar plan de implementación en disco (evitar cálculos de actualizaciones) |
-| `--use-computed-deployment-plan` | `-c` | Usar plan de despliegue calculado (sobrescribirá la versión en disco si hay alguna actualización) |
-| `--enable-clarity-wasm` | | Permitir que la vista previa de Clarity Wasm se ejecute en paralelo con el intérprete de Clarity (beta) |
-
-## Interact with your contracts in a local REPL \[#interact-with-your-contracts-in-a-local-repl]
-
-### consola de clarinet
-
-`clarinet console` loads contracts in a REPL for an interactive session.
-
-**Uso**
-
-```console
-$ clarinet console [OPTIONS]
-```
-
-```terminal
-$ clarinet console
-[32mclarity-repl v1.0.0[0m
-Enter ".help" for usage hints.
-Connected to a transient in-memory database.
-```
-
-La consola de Clarinet ofrece una variedad de comandos para la interacción con contratos:
-
-* `::help`: Enumera todos los comandos de consola
-* `::functions`: Mostrar todas las funciones nativas disponibles en Clarity
-* `::keywords`: Mostrar todas las palabras clave nativas disponibles en Clarity
-* `::describe | `: Mostrar documentación para una función nativa o palabra clave determinada
-* `::toggle_costs`: Mostrar análisis de costo después de cada expresión
-* `::toggle_timings`: Mostrar la duración de la ejecución
-* `::mint_stx `: Acuñar saldo de STX para un principal dado
-* `::set_tx_sender `: Establecer la variable tx-sender al principal
-* `::get_assets_maps`: Obtener mapas de activos para cuentas activas
-* `::get_contracts`: Obtener contratos
-* `::get_block_height`: Obtener la altura actual del bloque
-* `::advance_chain_tip `: Simular la minería de `` bloques
-* `::advance_stacks_chain_tip `: Simular la minería de `` bloques de Stacks
-* `::advance_burn_chain_tip `: Simular la minería de `` bloques de burnchain
-* `::set_epoch `: Actualizar la época actual
-* `::get_epoch`: Obtener la época actual
-* `::debug `: Iniciar una sesión de depuración interactiva ejecutando ``
-* `::trace `: Generar un rastro de ejecución para ``
-* `::get_costs `: Mostrar el análisis de costos
-* `::reload`: Recargar el contrato o contratos existentes en la sesión
-* `::read `: Leer expresiones desde un archivo
-* `::encode `: Codificar una expresión a una representación en bytes de Valor Clarity
-* `::decode `: Decodificar una representación en bytes de un valor de Clarity
-
-| Opción | Corto | Descripción |
-|--------|-------|-------------|
-| `--manifest-path ` | `-m` | Ruta a Clarinet.toml |
-| `--deployment-plan-path ` | `-p` | Si se especifica, utilizar este archivo de implementación |
-| `--use-on-disk-deployment-plan` | `-d` | Usar plan de implementación en disco (evitar cálculos de actualizaciones) |
-| `--use-computed-deployment-plan` | `-c` | Usar plan de despliegue calculado (sobrescribirá la versión en disco si hay alguna actualización) |
-| `--enable-remote-data` | `-r` | Habilitar la obtención de datos remotos desde la red principal o una red de pruebas |
-| `--remote-data-api-url ` | `-a` | Establecer una URL personalizada de la API de Stacks Blockchain para la obtención de datos remotos |
-| `--remote-data-initial-height ` | `-b` | Altura inicial del bloque remoto de Stacks |
-| `--enable-clarity-wasm` | | Permitir que la vista previa de Clarity Wasm se ejecute en paralelo con el intérprete de Clarity (beta) |
-
-## Iniciar una red de desarrollo local \[#start-a-local-development-network]
-
-### clarinet devnet
-
-`clarinet devnet` es un subcomando para trabajar con Devnet. Tiene dos subcomandos:
-
-| Comando | Descripción |
-|----------|-------------------------------------------------------|
-| `start` | Inicie una red Devnet local para interactuar con sus contratos |
-| `package`| Generar paquete de todos los artefactos requeridos para devnet |
-
-**Uso con `start`**
-
-```console
-$ clarinet devnet start [OPTIONS]
-```
-
-```terminal
-$ clarinet devnet start
-```
-
-| Opción | Corto | Descripción |
-|--------|-------|-------------|
-| `--manifest-path ` | `-m` | Ruta a Clarinet.toml |
-| `--no-dashboard` | | Mostrar flujos de registros en lugar del panel de interfaz de usuario de la terminal |
-| `--deployment-plan-path ` | `-p` | Si se especifica, utilizar este archivo de implementación |
-| `--use-on-disk-deployment-plan` | `-d` | Usar plan de implementación en disco (evitar cálculos de actualizaciones) |
-| `--use-computed-deployment-plan` | `-c` | Usar plan de despliegue calculado (sobrescribirá la versión en disco si hay alguna actualización) |
-| `--package ` | | Ruta al Package.json producido por 'clarinet devnet package' |
-
-**Uso con `package`**
-
-```console
-$ clarinet devnet package [OPTIONS]
-```
-
-```terminal
-$ clarinet devnet package --name my-devnet
-[32mPackaging devnet artifacts...[0m
-[32mCreated file[0m [1mmy-devnet.json[0m
-```
-
-| Opción | Corto | Descripción |
-|--------|-------|-------------|
-| `--name ` | `-n` | Nombre del archivo json de salida |
-| `--manifest-path ` | `-m` | Ruta a Clarinet.toml |
-
-## Gestiona tus implementaciones \[#manage-your-deployments]
-
-### despliegues de Clarinet
-
-`clarinet deployments` es un subcomando para gestionar despliegues en Devnet/Testnet/Mainnet.
-
-| Comando | Descripción |
-|------------|-------------|
-| `check` | Verificar el formato de implementaciones |
-| `generate` | Generar nuevo despliegue |
-| `apply` | Aplicar despliegue |
-
-**Uso con `check`**
-
-```console
-$ clarinet deployments check [OPTIONS]
-```
-
-```terminal
-$ clarinet deployments check
-[32m✔[0m Deployment files are valid
-```
-
-| Opción | Descripción |
-|--------|-------------|
-| `--manifest-path ` | Ruta a Clarinet.toml |
-
-**Uso con `generate`**
-
-```console
-$ clarinet deployments generate [OPTIONS]
-```
-
-```terminal
-$ clarinet deployments generate --testnet
-[32mGenerated deployment plan[0m
-[32mCreated file[0m [1mdeployments/default.testnet-plan.yaml[0m
-```
-
-| Opción | Descripción |
-|--------|-------------|
-| `--simnet` | Generar un archivo de despliegue para entornos simnet (consola, pruebas) |
-| `--devnet` | Generar un archivo de implementación para devnet, utilizando settings/Devnet.toml |
-| `--testnet` | Generar un archivo de despliegue para testnet, utilizando settings/Testnet.toml |
-| `--mainnet` | Generar un archivo de despliegue para mainnet, utilizando settings/Mainnet.toml |
-| `--manifest-path ` | Ruta a Clarinet.toml |
-| `--no-batch` | Generar un archivo de despliegue sin intentar agrupar transacciones (solo simnet) |
-| `--low-cost` | Calcular y establecer el costo, utilizando baja prioridad (se requiere conexión de red) |
-| `--medium-cost` | Calcular y establecer el costo, utilizando prioridad media (se requiere conexión de red) |
-| `--high-cost` | Calcular y establecer el costo, utilizando alta prioridad (se requiere conexión de red) |
-| `--manual-cost` | Dejar la estimación de costos manual |
-
-**Uso con `apply`**
-
-```console
-$ clarinet deployments apply [OPTIONS]
-```
-
-```terminal
-$ clarinet deployments apply --testnet
-[33mApplying deployment to testnet[0m
-[32m✔[0m Broadcasting transaction for token.clar
- Transaction ID: 0x3d4f5...
- Contract: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.token
-[32m✔[0m All contracts deployed successfully
-```
-
-| Opción | Corto | Descripción |
-|--------|-------|-------------|
-| `--devnet` | | Aplicar configuración de implementación predeterminada/default.devnet-plan.toml |
-| `--testnet` | | Aplicar configuración de implementación predeterminada/default.testnet-plan.toml |
-| `--mainnet` | | Aplicar configuración de implementación predeterminada/default.mainnet-plan.toml |
-| `--manifest-path ` | `-m` | Ruta a Clarinet.toml |
-| `--deployment-plan-path ` | `-p` | Aplicar el plan de implementación especificado |
-| `--no-dashboard` | | Mostrar flujos de registros en lugar del panel de interfaz de usuario de la terminal |
-| `--use-on-disk-deployment-plan` | `-d` | Usar plan de implementación en disco (evitar cálculos de actualizaciones) |
-| `--use-computed-deployment-plan` | `-c` | Usar plan de despliegue calculado (sobrescribirá la versión en disco si hay alguna actualización) |
-
-## Interactuar con contratos de Mainnet \[#interact-with-mainnet-contracts]
-
-### requisitos de Clarinet
-
-`clarinet requirements` es un subcomando para interactuar con contratos de Mainnet.
-
-| Comando | Descripción |
-|---------|-------------|
-| `add` | Añada un contrato de mainnet como dependencia a su proyecto |
-
-**Uso**
-
-```console
-$ clarinet requirements
-```
-
-```terminal
-$ clarinet requirements add SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[32mAdded requirement[0m SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-| Opción | Descripción |
-|--------|-------------|
-| `--manifest-path ` | Ruta a Clarinet.toml |
-
-## Integraciones del Editor \[#editor-integrations]
-
-### clarinet lsp
-
-`clarinet lsp` inicia el servicio del Protocolo de Servidor de Lenguaje para Clarity, habilitando la finalización inteligente de código, el resaltado de errores y otras características de IDE en editores compatibles.
-
-**Uso**
-
-```console
-$ clarinet lsp
-```
-
-## Depuración \[#debugging]
-
-### clarinet dap
-
-`clarinet dap` inicia el servicio del Protocolo de Adaptador de Depuración, habilitando funciones de depuración como puntos de interrupción, ejecución paso a paso e inspección de variables en editores compatibles.
-
-**Uso**
-
-```console
-$ clarinet dap
-```
-
-## Formatea tu código \[#format-your-code]
-
-### formato de clarinet
-
-`clarinet format` da formato a los archivos de código Clarity según las convenciones estándar.
-
-**Uso**
-
-```console
-$ clarinet format [OPTIONS]
-```
-
-```terminal
-$ clarinet format --check
-$ clarinet format --dry-run
-$ clarinet format --file contracts/token.clar --in-place
-```
-
-| Opción | Corto | Descripción | Requerido |
-|--------|-------|-------------|----------|
-| `--check` | | Comprobar si el código está formateado sin modificar archivos | No |
-| `--dry-run` | | Solo reproducir el resultado del formato | No |
-| `--in-place` | | Reemplazar el contenido de un archivo con el código formateado | No |
-| `--manifest-path ` | `-m` | Ruta a Clarinet.toml | No |
-| `--file ` | `-f` | Si se especifica, formatear solo este archivo | No |
-| `--max-line-length ` | `-l` | Longitud máxima de línea | No |
-| `--indent ` | `-i` | Tamaño de sangría, p. ej. 2 | No |
-| `--tabs` | `-t` | Usar tabulaciones en lugar de espacios | No |
-
-## Utilidades \[#utilities]
-
-### completaciones de clarinet
-
-`clarinet completions` genera scripts de completado de shell para tu shell.
-
-**Uso**
-
-```console
-$ clarinet completions
-```
-
-```terminal
-$ clarinet completions zsh > ~/.zsh/completions/_clarinet
-$ source ~/.zshrc
-```
-
-**Shells compatibles**
-
-* `bash`
-* `zsh`
-* `fish`
-* `powershell`
-* `elvish`
-
-| Opción | Corto | Descripción |
-|--------|-------|-------------|
-| `--shell ` | `-s` | Especifique para qué shell generar el script de completado |
-
-## Variables de entorno \[#environment-variables]
-
-Clarinet admite variables de entorno para la configuración. Todas las variables de entorno tienen el prefijo `CLARINET_`:
-
-```terminal
-$ export CLARINET_MANIFEST_PATH=/path/to/project
-```
diff --git a/content/docs/es/tools/clarinet/(clarinet-cli)/contract-interaction.mdx b/content/docs/es/tools/clarinet/(clarinet-cli)/contract-interaction.mdx
deleted file mode 100644
index efd4bc9c3..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-cli)/contract-interaction.mdx
+++ /dev/null
@@ -1,193 +0,0 @@
----
-title: Interacción con contratos
-sidebarTitle: Interacción con contratos
-description: Clarinet proporciona herramientas poderosas para interactuar con tus contratos durante el desarrollo. La consola te ofrece un entorno REPL interactivo donde puedes llamar funciones, verificar el estado y depurar problemas en tiempo real.
----
-## Iniciando la consola
-
-El `clarinet console` el comando inicia una sesión interactiva con todos sus contratos implementados en una cadena de bloques local simulada:
-
-```terminal
-$ clarinet console
-[32mclarity-repl v3.3.0[0m
-[1mEnter "::help" for usage hints.[0m
-[1mConnected to a transient in-memory database.[0m
-```
-
-Once in the console, you have access to a Clarity REPL with your project's contracts already deployed and ready to interact with. The console supports several powerful options for different development scenarios:
-
-| Opción | Descripción |
-|--------|-------------|
-| `--enable-remote-data` | Conéctese a la red principal/red de pruebas para consultar contratos reales |
-| `--deployment-plan-path ` | Usar plan de despliegue específico |
-| `--manifest-path ` | Usar ubicación alternativa de Clarinet.toml |
-| `--remote-data-api-url ` | Usar punto final de API de Stacks personalizado |
-| `--remote-data-initial-height ` | Establecer la altura del bloque inicial para datos remotos |
-
-## Trabajando con datos remotos
-
-Una de las características más poderosas es la capacidad de interactuar con contratos reales de mainnet o testnet desde tu consola local. Esto te permite probar contra contratos realmente desplegados:
-
-```terminal
-$ clarinet console --enable-remote-data
-```
-
-Ahora puedes interactuar directamente con contratos de la red principal:
-
-```terminal -o
-$ (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token get-decimals)
-[32m(ok u8)[0m
-$ (contract-call? 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.arkadiko-token get-name)
-[32m(ok "Arkadiko Token")[0m
-```
-
-Esto es invaluable para:
-
-* Probando integraciones con protocolos existentes
-* Verificando el comportamiento del contrato contra el estado de la red principal
-* Desarrollando contratos que dependen de contratos de mainnet
-
-:::callout
-type: warn
-
-### Requisitos de datos remotos
-
-Antes de usar datos remotos, asegúrese de agregar el contrato remoto a su `Clarinet.toml` archivo con `clarinet requirements add SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token`.
-:::
-
-### Uso de la clave API de Hiro
-
-Para evitar límites de tasa al usar datos remotos, establezca el `HIRO_API_KEY` variable de entorno. Clarinet incluye automáticamente esta clave en todas las solicitudes de API:
-
-```terminal
-$ export HIRO_API_KEY=your_api_key_here
-$ clarinet console --enable-remote-data
-```
-
-La clave de API se envía como el `x-api-key` encabezado en todas las solicitudes a las APIs de Hiro. Puede obtener una clave API gratuita desde el [Plataforma Hiro](https://platform.hiro.so).
-
-### Trabajando con contratos
-
-El `::get_contracts` command muestra todos los contratos disponibles:
-
-```terminal -o
-$ ::get_contracts
-[1m+---------------------------------------------------------+----------------+
-| Contract identifier | Public functions |
-|---------------------------------------------------------+----------------------|
-| ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter | (count-up) |
-| | (get-count (who principal))|
-+---------------------------------------------------------+----------------------+[0m
-$ (contract-call? .counter count-up)
-[32m(ok true)[0m
-$ (contract-call? .counter get-count tx-sender)
-[32mu1[0m
-```
-
-### Trabajando con diferentes principales
-
-La consola proporciona varias carteras de prueba que puede utilizar. Cambie entre ellas para probar escenarios de múltiples usuarios:
-
-```terminal -o
-$ ::get_assets_maps
-[1m+-------------------------------------------+-----------------+
-| Address | uSTX |
-|-------------------------------------------+-----------------|
-| ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST2NEB84ASENDXKYGJPQW86YXQCEFEX2ZQPG87ND | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST2REHHS5J3CERCRBEPMGH7921Q6PYKAADT7JP2VB | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST3AM1A56AK2C1XAFJ4115ZSV26EB49BVQ10MGCS0 | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST3NBRSFKX28FQ2ZJ1MAKX58HKHSDGNV5N7R21XCP | 100000000000000 |
-|-------------------------------------------+-----------------|
-| ST3PF13W7Z0RRM42A8VZRVFQ75SV1K26RXEP8YGKJ | 100000000000000 |
-|-------------------------------------------+-----------------|
-| STNHKEPYEPJ8ET55ZZ0M5A34J0R3N5FM2CMMMAZ6 | 100000000000000 |
-+-------------------------------------------+-----------------+[0m
-$ ::set_tx_sender ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5
-[1mtx-sender switched to ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5[0m
-```
-
-### Trabajando con alturas de bloques
-
-Prueba la lógica "dependiente del tiempo" avanzando la cadena:
-
-```terminal -o
-$ ::get_block_height
-[1mCurrent block height: 4[0m
-$ ::advance_chain_tip 100
-[32mnew burn height: 3[0m
-[32mnew stacks height: 104[0m
-$ ::get_block_height
-[1mCurrent block height: 104[0m
-```
-
-:::callout
-### Comandos de consola
-
-Para obtener una lista completa de los comandos de consola disponibles y su uso, consulte el [Referencia de la CLI](/tools/clarinet/cli-reference#clarinet-console).
-:::
-
-## Problemas comunes
-
-
-
- Errores de contrato no encontrado
-
-
-
- Si ve errores de "uso de contrato no resuelto":
-
- ```terminal
- $ (contract-call? .missing-contract get-value)
- [31merror: use of unresolved contract[0m
- ```
-
- **Causas comunes:**
-
- * Nombre del contrato con error tipográfico
- * Contrato no desplegado en la sesión
- * Uso del prefijo de contrato incorrecto (`.` para contratos locales)
-
- **Solución**: Verificar contratos desplegados con `::get_contracts` y use el nombre correcto.
-
-
-
-
-
- Problemas de conexión de datos remotos
-
-
-
- Cuando se usa `--enable-remote-data`, es posible que encuentres límites de velocidad o errores de conexión:
-
- ```terminal
- $ (contract-call? 'SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.arkadiko-token get-name)
- [31merror: API rate limit exceeded[0m
- ```
-
- **Soluciones:**
-
- 1. Establece tu clave API de Hiro: `export HIRO_API_KEY=your_key_here`
- 2. Utilizar un punto final de API personalizado: `--remote-data-api-url https://your-node.com`
- 3. Esperar a que se restablezca el límite de tasa (generalmente 1 minuto)
-
-
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Validación y análisis](/tools/clarinet/validation-and-analysis): Aprende cómo probar y validar tu proyecto de Clarinet.
-* [Despliegue](/tools/clarinet/deployment): Aprende cómo desplegar tu proyecto de Clarinet.
-:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-cli)/deployment.mdx b/content/docs/es/tools/clarinet/(clarinet-cli)/deployment.mdx
deleted file mode 100644
index 568c1d16e..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-cli)/deployment.mdx
+++ /dev/null
@@ -1,447 +0,0 @@
----
-title: Desplegando tus contratos
-sidebarTitle: Despliegue de contratos
-description: Clarinet proporciona herramientas de implementación completas para ayudarte a mover tus contratos desde el desarrollo local a las redes de producción. Ya sea que estés probando en devnet, preparando en testnet o lanzando en mainnet, Clarinet simplifica todo el proceso de implementación.
----
-## Generando planes de despliegue
-
-Los planes de despliegue son archivos YAML que definen exactamente cómo se desplegarán tus contratos. Especifican el orden, la configuración y los detalles de red para cada contrato, asegurando despliegues reproducibles en todos los entornos. Para crear un plan de despliegue para cualquier red, ejecuta el siguiente comando:
-
-```terminal
-$ clarinet deployments generate --testnet
-[32mAnalyzing contracts...[0m
-[32mCalculating deployment costs...[0m
-[32mGenerating deployment plan[0m
-[32mCreated file[0m [1mdeployments/default.testnet-plan.yaml[0m
-```
-
-Esto crea un plan de despliegue basado en la configuración de su proyecto:
-
-```yaml deployments/default.devnet-plan.yaml
----
-id: 0
-name: Devnet deployment
-network: devnet
-stacks-node: "http://localhost:20443"
-bitcoin-node: "http://devnet:devnet@localhost:18443"
-plan:
- batches:
- - id: 0
- transactions:
- - contract-publish:
- contract-name: counter
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
- cost: 6940
- path: contracts/counter.clar
- anchor-block-only: true
- clarity-version: 2
- epoch: "2.5"
-```
-
-### Estructura del plan de despliegue
-
-Componentes clave de un plan de despliegue:
-
-| Campo | Descripción |
-|-------|-------------|
-| `id` | Identificador único para el despliegue |
-| `name` | Nombre de implementación legible por humanos |
-| `network` | Red objetivo (devnet/testnet/mainnet) |
-| `stacks-node` | Punto final RPC para el nodo Stacks |
-| `bitcoin-node` | Punto final RPC para el nodo de Bitcoin |
-| `plan.batches` | Matriz de lotes de implementación |
-
-### Especificaciones de despliegue
-
-El comportamiento de implementación se configura en dos lugares:
-
-**Configuración del proyecto** (`Clarinet.toml`):
-
-* Versión de Clarity para contratos
-* Dependencias contractuales
-* Requisitos de época
-
-**Configuración de red** (`settings/.toml`):
-
-* Detalles y saldos de la cuenta
-* Puntos finales de red
-* Cuentas de implementación personalizadas
-
-Ejemplo de configuración de red:
-
-```toml settings/Testnet.toml
-[network]
-name = "testnet"
-deployment_fee_rate = 10
-
-[accounts.deployer]
-mnemonic = ""
-balance = 100_000_000_000_000
-derivation = "m/44'/5757'/0'/0/0"
-```
-
-## Trabajando con requisitos contractuales
-
-Su proyecto puede hacer referencia a contratos que ya existen en la blockchain. Esto es especialmente útil para implementar rasgos estandarizados.
-
-### Añadiendo requisitos
-
-Agregar dependencias de contratos externos:
-
-```terminal
-$ clarinet requirements add SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[32mAdded requirement[0m SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-Esto actualiza la configuración de tu proyecto:
-
-```toml Clarinet.toml
-[project]
-name = "my-nft-project"
-requirements = [
- { contract_id = "SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait" }
-]
-```
-
-Al implementar, Clarinet automáticamente:
-
-* Descarga el contrato a través de la API de Stacks
-* Reasigna el principal a una cuenta local para devnet
-* Garantiza que el requisito esté disponible antes de desplegar tus contratos
-
-## Implementación en diferentes redes
-
-
-
-
- Devnet
-
-
-
- Testnet
-
-
-
- Mainnet
-
-
-
-
- **Implementación rápida para desarrollo local**
-
- Devnet despliega automáticamente los contratos cuando se inicia:
-
- ```terminal
- $ clarinet devnet start
- [32mStarting devnet...[0m
- [32mDeploying contracts...[0m
- [90mDeploying[0m counter.clar [32m✓[0m ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter
- [90mDeploying[0m token.clar [32m✓[0m ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.token
- ```
-
- Para el despliegue manual a una devnet en ejecución:
-
- ```terminal
- $ clarinet deployments apply --devnet
- ```
-
- Ver [desarrollo local](/tools/clarinet/local-development) para una configuración detallada de devnet.
-
-
-
- :::callout
- ### Requisitos previos
-
- Antes de implementar en la red de pruebas:
-
- * Obtén STX de testnet desde el [grifo](https://explorer.hiro.so/sandbox/faucet?chain=testnet)
- * Configura tu cuenta en `settings/Testnet.toml`
- * Validar contratos con `clarinet check`
- :::
-
- **Generar plan de despliegue con estimación de costos**:
-
- ```terminal
- $ clarinet deployments generate --testnet --medium-cost
- ```
-
- **Implementar contratos**:
-
- ```terminal
- $ clarinet deployments apply --testnet
- ```
-
-
-
- :::callout
- type: warn
-
- ### Lista de verificación de la red principal
-
- Antes de implementar en la red principal:
-
- 1. Completar pruebas exhaustivas en la red de pruebas
- 2. Audite sus contratos para detectar vulnerabilidades de seguridad
- 3. Asegúrate de tener suficiente STX para las tarifas de implementación
- 4. Haga una copia de seguridad de sus claves de implementación de forma segura
- 5. Considere usar una billetera de hardware para el despliegue
- :::
-
- **Generar plan de despliegue de red principal**:
-
- ```terminal
- $ clarinet deployments generate --mainnet --high-cost
- ```
-
- **Desplegar con confirmación**:
-
- ```terminal
- $ clarinet deployments apply --mainnet
- ```
-
-
-
-## Estimación y optimización de costos
-
-### Niveles de tarifas
-
-Elija el nivel de tarifa adecuado para su implementación:
-
-```terminal
-$ clarinet deployments generate --testnet --manual-cost
-```
-
-Opciones de nivel de tarifa:
-
-* `--low-cost`: Minimizar comisiones, confirmación más lenta
-* `--medium-cost`: Tarifas y velocidad equilibradas
-* `--high-cost`: Inclusión prioritaria
-* `--manual-cost`: Elegir interactivamente
-
-### Analizando los costos de implementación
-
-Obtenga un desglose detallado de costos antes de implementar:
-
-```terminal
-$ clarinet deployments generate --testnet --medium-cost
-```
-
-## Configuraciones avanzadas de implementación
-
-### Despliegues de múltiples lotes
-
-Despliegue sistemas complejos con dependencias utilizando lotes:
-
-```yaml deployments/defi-protocol.yaml
-plan:
- batches:
- - id: 0
- transactions:
- - contract-publish:
- contract-name: trait-definitions
- path: contracts/traits.clar
- clarity-version: 2
- - id: 1
- transactions:
- - contract-publish:
- contract-name: token
- path: contracts/token.clar
- - contract-publish:
- contract-name: oracle
- path: contracts/oracle.clar
- - id: 2
- transactions:
- - contract-publish:
- contract-name: defi-pool
- path: contracts/defi-pool.clar
-```
-
-Los lotes garantizan:
-
-* Las dependencias se implementan primero
-* Despliegue paralelo dentro de lotes
-* Ejecución secuencial entre lotes
-
-### Tipos de transacciones
-
-Los planes de implementación admiten varios tipos de transacciones:
-
-| Transaction Type | Descripción |
-|--------------------|--------------------------------------------------------------------------------------------|
-| Contract Operations| Implica publicar y llamar contratos, especificando remitente, costo y ruta |
-| Asset Transfers | Transfiere activos como STX o BTC, especificando remitente, destinatario y cantidades |
-
-**Con operaciones de contrato**:
-
-```yaml
-- contract-publish:
- contract-name: my-contract
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
- cost: 5960
- path: contracts/my-contract.clar
- clarity-version: 2
-
-- contract-call:
- contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.my-contract
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
- method: initialize
- parameters:
- - u1000000
- - "Token Name"
- cost: 5960
-```
-
-**Con transferencias de activos**:
-
-```yaml
-- stx-transfer:
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
- recipient: ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG
- mstx-amount: 1000000
- memo: '0x48656c6c6f' # "Hello" in hex
-
-- btc-transfer:
- expected-sender: mjSrB3wS4xab3kYqFktwBzfTdPg367ZJ2d
- recipient: bcrt1qnxknq3wqtphv7sfwy07m7e4sr6ut9yt6ed99jg
- sats-amount: 100000000
- sats-per-byte: 10
-```
-
-### Personalización manual del plan
-
-Puede editar manualmente los planes de implementación para escenarios complejos:
-
-:::callout
-### Ediciones manuales
-
-Al implementar, Clarinet solicita sobrescribir los cambios manuales. Escriba `no` para mantener tus personalizaciones.
-:::
-
-**Ejemplo de inicialización de contrato**:
-
-```yaml
-- id: 3
- transactions:
- - contract-call:
- contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.token
- method: initialize
- parameters:
- - u1000000 # Initial supply
- - { name: "My Token", symbol: "MTK", decimals: u6 }
- expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
-```
-
-## Problemas comunes
-
-
-
- Saldo de STX insuficiente
-
-
-
- **Error**: "Saldo de STX insuficiente para el despliegue"
-
- **Soluciones**:
-
- 1. **Obtener STX de testnet**: Visita el [faucet de testnet](https://explorer.hiro.so/sandbox/faucet?chain=testnet)
- 2. **Reducir la tasa de comisión**: Usar `--low-cost` opción
- 3. **Consultar saldo**:
-
- ```terminal
- $ clarinet console --testnet
- >> stx-account 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG
- ```
-
-
-
-
-
- El contrato ya existe
-
-
-
- **Error**: "Contrato 'token' ya desplegado en esta dirección"
-
- **Causas**:
-
- * Contrato con el mismo nombre ya desplegado
- * Intento de implementación anterior exitoso
-
- **Soluciones**:
-
- 1. Utilice un nombre de contrato diferente
- 2. Desplegar desde una dirección diferente
- 3. Si está realizando pruebas, utilice una cuenta nueva de testnet
-
-
-
-
-
- Fallos de conexión de red
-
-
-
- **Error**: "No se pudo conectar al nodo de testnet"
-
- **Comprobar la configuración de red**:
-
- ```toml settings/Testnet.toml
- [network]
- name = "testnet"
- node_rpc_address = "https://stacks-node-api.testnet.stacks.co"
- ```
-
- **Probar puntos finales alternativos**:
-
- * Hiro: `https://api.testnet.hiro.so`
- * Usa tu propio nodo
-
- **Depurar conexión**:
-
- ```terminal
- $ curl -I https://api.testnet.hiro.so/v2/info
- ```
-
-
-
-
-
- Plan de despliegue no válido
-
-
-
- **Errores comunes de YAML**:
-
- * Sangría incorrecta
- * Faltan campos obligatorios
- * Rutas de contrato inválidas
-
- **Valide su plan**:
-
- ```terminal
- $ clarinet deployments check
- ```
-
- **Regenerar si es necesario**:
-
- ```terminal
- $ clarinet deployments generate --testnet
- ```
-
- **Verificar que existan las rutas de los contratos**:
-
- ```terminal
- $ ls contracts/
- ```
-
-
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Chainhook](/tools/chainhook): Aprende cómo monitorear tus contratos con Chainhook.
-* [Monitoreo de contratos](/tools/contract-monitoring): Aprende cómo monitorear tus contratos con Chainhook.
-:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-cli)/local-blockchain-development.mdx b/content/docs/es/tools/clarinet/(clarinet-cli)/local-blockchain-development.mdx
deleted file mode 100644
index fdbb47016..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-cli)/local-blockchain-development.mdx
+++ /dev/null
@@ -1,491 +0,0 @@
----
-title: Trabajando con una blockchain local
-sidebarTitle: Desarrollo de blockchain local
-description: Clarinet proporciona un entorno de blockchain local completo, ofreciendo todos los servicios que necesitas para el desarrollo de contratos inteligentes sin necesidad de desplegar en una red pública.
----
-## Iniciando tu blockchain local
-
-Para iniciar devnet con todos los servicios requeridos, ejecute el siguiente comando:
-
-```terminal
-$ clarinet devnet start
-```
-
-| Opción | Descripción |
-|--------|-------------|
-| `--manifest-path ` | Usar ubicación alternativa de Clarinet.toml |
-| `--no-dashboard` | Mostrar registros en lugar de interfaz de usuario interactiva |
-| `--deployment-plan-path ` | Usar plan de despliegue específico |
-| `--use-on-disk-deployment-plan` | Usar el plan de despliegue existente sin actualizaciones |
-| `--use-computed-deployment-plan` | Calcular y sobrescribir el plan de implementación |
-| `--package ` | Usar configuración preempaquetada de devnet |
-
-:::callout
-### Requisitos previos
-
-Devnet requiere que Docker esté en ejecución. Si ves "clarinet was unable to create network", asegúrate de que Docker Desktop esté funcionando o que el demonio de Docker se haya iniciado.
-:::
-
-Por defecto, devnet inicia con un panel interactivo que muestra:
-
-* Estado del servicio y salud
-* Transacciones recientes
-* Producción de bloques
-* Despliegues de contratos
-* Uso de recursos
-
-Usa el `--no-dashboard` bandera para entornos de CI/CD o cuando prefieres registros en streaming.
-
-## Servicios y características principales
-
-Devnet crea un entorno blockchain completo con estos servicios:
-
-| Servicio | Puerto | Propósito |
-|---------|------|---------|
-| **Nodo de Stacks** | 20443 | Procesa transacciones y mina bloques |
-| **Nodo de Bitcoin** | 18443 | Proporciona anclaje de bloques en modo regtest |
-| **API de Stacks** | 3999 | REST API for querying blockchain data |
-| **Base de datos Postgres** | 5432 | Indexa los datos de la cadena de bloques para consultas rápidas |
-| **Explorador de Stacks** | 8000 | Interfaz web para navegar transacciones |
-| **Explorador de Bitcoin** | 8001 | Interfaz de usuario web para la cadena regtest de Bitcoin |
-
-Devnet incluye cuentas prefinanciadas con saldos de STX:
-
-```terminal -o
-$ clarinet console
-$ ::get_assets_maps
-[1m+-------------------------------------------+-----------------+
-| Address | STX Balance |
-|-------------------------------------------+-----------------|
-| ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM | 100000000000000 |
-| ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5 | 100000000000000 |
-| ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG | 100000000000000 |
-| ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC | 100000000000000 |
-| ST2NEB84ASENDXKYGJPQW86YXQCEFEX2ZQPG87ND | 100000000000000 |
-+-------------------------------------------+-----------------+[0m
-```
-
-Cuando se inicia devnet, automáticamente despliega los contratos de tu proyecto:
-
-```terminal -o
-$ clarinet devnet start
-[32mDeploying contracts...[0m
-[90mDeploying[0m counter.clar [32m✓[0m ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter
-[90mDeploying[0m token.clar [32m✓[0m ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.token
-[90mDeploying[0m marketplace.clar [32m✓[0m ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.marketplace
-
-[32mAll contracts deployed successfully[0m
-```
-
-## Configuración y personalización
-
-El comportamiento de Devnet se controla a través de archivos de configuración en su proyecto.
-
-### Configuración básica
-
-El `settings/Devnet.toml` archivo controla la configuración de red:
-
-```toml settings/Devnet.toml
-[network]
-name = "devnet"
-
-# Service ports
-stacks_node_rpc_port = 20443
-stacks_api_port = 3999
-stacks_explorer_port = 8000
-bitcoin_node_rpc_port = 18443
-
-# Mining configuration
-[network.devnet]
-bitcoin_controller_block_time = 30_000 # 30 seconds
-
-# Disable services you don't need
-disable_bitcoin_explorer = false
-disable_stacks_explorer = false
-disable_stacks_api = false
-```
-
-### Configuración del puerto
-
-Personalice los puertos para evitar conflictos:
-
-```toml
-# Change default ports
-stacks_node_rpc_port = 30443
-stacks_api_port = 4999
-postgres_port = 6432
-stacks_explorer_port = 4020
-```
-
-### Intervalos de minería
-
-Controlar la velocidad de producción de bloques:
-
-```toml
-# Fast blocks for development (1 second)
-bitcoin_controller_block_time = 1_000
-
-# Standard testing (30 seconds)
-bitcoin_controller_block_time = 30_000
-
-# Realistic timing (2 minutes)
-bitcoin_controller_block_time = 120_000
-```
-
-### Cuentas personalizadas
-
-Agregar cuentas con saldos específicos:
-
-```toml Clarinet.toml
-[accounts.treasury]
-mnemonic = "twice kind fence tip hidden tilt action fragile skin nothing glory cousin"
-balance = 10_000_000_000_000 # 10M STX
-
-[accounts.alice]
-mnemonic = "female adjust gallery certain visit token during great side clown fitness like"
-balance = 5_000_000_000_000 # 5M STX
-```
-
-## Accediendo a los servicios
-
-Accede a varios servicios para interactuar con la blockchain, incluyendo la navegación de datos, consulta de APIs y envío de transacciones directamente.
-
-
-
-
- Explorador de Stacks
-
-
-
- Puntos finales de la API
-
-
-
- RPC directo
-
-
-
-
- Explore transacciones, bloques y el estado de los contratos a través de la interfaz web:
-
- ```
- http://localhost:8000
- ```
-
- El explorador proporciona:
-
- * Historial y detalles de transacciones
- * Información del bloque
- * Código fuente y estado del contrato
- * Saldos de cuenta
-
-
-
- Consulta datos de blockchain utilizando la API de Stacks:
-
- ```terminal
- $ curl http://localhost:3999/v2/info
- {
- "peer_version": 4207599113,
- "burn_block_height": 102,
- "stacks_tip_height": 68,
- "network_id": 2147483648
- }
- ```
-
- Puntos finales comunes:
-
- * `/v2/info` - Información de la red
- * `/v2/accounts/{address}` - Detalles de la cuenta
- * `/v2/contracts/source/{address}/{name}` - Fuente del contrato
- * `/extended/v1/tx/{txid}` - Detalles de la transacción
-
-
-
- Enviar transacciones directamente al nodo de Stacks:
-
- ```terminal
- $ curl -X POST http://localhost:20443/v2/transactions \
- -H "Content-Type: application/json" \
- -d @transaction.json
- ```
-
- Puntos finales RPC:
-
- * `/v2/transactions` - Transmitir transacciones
- * `/v2/contracts/call-read` - Llamar funciones de solo lectura
- * `/v2/fees/transfer` - Obtener estimaciones de tarifas
-
-
-
-## Configuración avanzada
-
-### Optimización del rendimiento
-
-Para ciclos de desarrollo rápidos:
-
-```toml settings/Devnet.toml
-[network.devnet]
-# 1 second blocks
-bitcoin_controller_block_time = 1_000
-
-# Disable explorers for speed
-disable_bitcoin_explorer = true
-disable_stacks_explorer = true
-
-# Keep API for contract interaction
-disable_stacks_api = false
-```
-
-### Configuración de época
-
-Prueba diferentes versiones de Stacks:
-
-```toml
-[epochs]
-epoch_2_0 = 0 # Stacks 2.0 from genesis
-epoch_2_05 = 0 # Stacks 2.05 from genesis
-epoch_2_1 = 0 # Stacks 2.1 from genesis
-epoch_2_2 = 0 # Pox-2 from genesis
-epoch_2_3 = 0 # Pox-3 from genesis
-epoch_2_4 = 0 # Pox-4 from genesis
-epoch_3_0 = 101 # Nakamoto activation at block 101
-```
-
-### Despliegue de paquetes
-
-Crear configuraciones de devnet reutilizables:
-
-```terminal
-$ clarinet devnet package --name demo-env
-[32mPackaging devnet configuration...[0m
-[32mCreated[0m demo-env.json
-```
-
-Usar configuración empaquetada:
-
-```terminal
-$ clarinet devnet start --package demo-env.json
-```
-
-## Problemas comunes
-
-
-
- Errores de conexión de Docker
-
-
-
- **Error**: "clarinet no pudo crear la red"
-
- **Soluciones**:
-
- 1. Asegúrese de que Docker Desktop esté en ejecución (macOS/Windows)
- 2. Iniciar el daemon de Docker: `sudo systemctl start docker` (Linux)
- 3. Verificar los permisos de Docker: `docker ps`
- 4. Restablecer Docker a los valores predeterminados de fábrica si los problemas persisten
-
- **Verificar Docker**:
-
- ```terminal
- $ docker --version
- Docker version 24.0.7, build afdd53b
- $ docker ps
- CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
- ```
-
- **Error**: "Docker respondió con el código de estado 409: red con nombre `.devnet` ya existe"
-
- Esto ocurre cuando una sesión anterior de devnet no se limpió correctamente, dejando una red Docker atrás.
-
- **Solución - Eliminar la red existente**:
-
- ```terminal
- $ docker network rm .devnet
- ```
-
- O si no estás seguro del nombre exacto de la red:
-
- ```terminal
- $ docker network ls | grep devnet
- $ docker network rm
- ```
-
- **Prevención**:
-
- * Usar `Ctrl+C` para detener elegantemente devnet
- * Verificar si hay redes huérfanas después de bloqueos:
-
- ```terminal
- $ docker network prune
- ```
-
- **Nota**: El nombre de la red se basa en el nombre del directorio de su proyecto, por lo que un `clarinet new hello-world` el proyecto tendrá un nombre de red de `hello-world.devnet`.
-
-
-
-
-
- Error de flujo de Docker durante el inicio
-
-
-
- **Error**: "Fatal: no se puede crear la imagen: error de flujo de Docker"
-
- Este error suele ocurrir cuando las imágenes de Docker están dañadas o cuando los exploradores no logran iniciarse correctamente.
-
- **Solución 1 - Desactivar exploradores**:
-
- Si no necesitas los exploradores web, desactívalos en `settings/Devnet.toml`:
-
- ```toml
- disable_bitcoin_explorer = true
- disable_stacks_explorer = true
- ```
-
- **Solución 2 - Limpiar el entorno de Docker**:
-
- Eliminar todos los contenedores e imágenes, luego reiniciar:
-
- ```terminal
- $ docker stop $(docker ps -a -q)
- $ docker system prune -a
- $ docker volume prune
- ```
-
- **Solución 3 - Limpieza completa y reinicio**:
-
- ```terminal
- $ docker stop $(docker ps -a -q)
- $ docker network rm .devnet
- $ docker system prune --all --volumes
- $ clarinet devnet start
- ```
-
- Esto garantiza un entorno Docker limpio para que devnet comience de cero.
-
-
-
-
-
- Fallos en el despliegue de contratos
-
-
-
-
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Interacción con contratos](/tools/clarinet/contract-interaction): Aprende cómo interactuar con tus contratos.
-* [Despliegue](/tools/clarinet/deployment): Aprende cómo desplegar tu proyecto de Clarinet.
-:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-cli)/project-development.mdx b/content/docs/es/tools/clarinet/(clarinet-cli)/project-development.mdx
deleted file mode 100644
index 3e7bafad5..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-cli)/project-development.mdx
+++ /dev/null
@@ -1,174 +0,0 @@
----
-title: Administrando tus proyectos
-sidebarTitle: Desarrollo del proyecto
-description: Clarinet agiliza todo el ciclo de vida del desarrollo de contratos inteligentes en Clarity. Desde la inicialización del proyecto hasta la gestión de contratos y el formateo de código, tendrás todas las herramientas necesarias para un desarrollo profesional.
----
-## Creando un proyecto nuevo
-
-El `clarinet new` el comando crea una estructura de proyecto completa con todos los archivos de configuración necesarios:
-
-```terminal
-$ clarinet new my-defi-app
-[32mCreate directory[0m [1mmy-defi-app[0m
-[32mCreate directory[0m [1mcontracts[0m
-[32mCreate directory[0m [1msettings[0m
-[32mCreate directory[0m [1mtests[0m
-[32mCreate file[0m [1mClarinet.toml[0m
-[32mCreate file[0m [1msettings/Mainnet.toml[0m
-[32mCreate file[0m [1msettings/Testnet.toml[0m
-[32mCreate file[0m [1msettings/Devnet.toml[0m
-[32mCreate directory[0m [1m.vscode[0m
-[32mCreate file[0m [1m.vscode/settings.json[0m
-[32mCreate file[0m [1m.vscode/tasks.json[0m
-[32mCreate file[0m [1m.gitignore[0m
-[32mCreate file[0m [1m.gitattributes[0m
-[32mCreate file[0m [1mpackage.json[0m
-[32mCreate file[0m [1mtsconfig.json[0m
-[32mCreate file[0m [1mvitest.config.js[0m
-```
-
-| Opción | Descripción | Ejemplo |
-|--------|-------------|---------|
-| `--disable-telemetry` | Optar por no participar en la recopilación de telemetría | `clarinet new my-app --disable-telemetry` |
-
-Para una mirada más profunda a la estructura del proyecto generada, consulte el [estructura del proyecto](/tools/clarinet/project-structure) guía.
-
-## Gestionando contratos
-
-### Creando nuevos contratos
-
-El `clarinet contract new` el comando genera tanto un archivo de contrato como su archivo de prueba correspondiente:
-
-```terminal
-$ clarinet contract new token
-[32mCreated file[0m [1mcontracts/token.clar[0m
-[32mCreated file[0m [1mtests/token.test.ts[0m
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-El contrato generado incluye una plantilla mínima:
-
-```clarity contracts/token.clar
-;; token
-;;
-
-;; constants
-;;
-
-;; data vars
-;;
-
-;; data maps
-;;
-
-;; public functions
-;;
-
-;; read only functions
-;;
-
-;; private functions
-;;
-```
-
-### Eliminando contratos
-
-Limpiar contratos no utilizados con el `rm` comando:
-
-```terminal
-$ clarinet contract rm old-token
-[33mRemoved file[0m [1mcontracts/old-token.clar[0m
-[33mRemoved file[0m [1mtests/old-token.test.ts[0m
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-## Verificando la sintaxis de los contratos del proyecto
-
-Valide la configuración completa de su proyecto:
-
-```terminal
-$ clarinet check
-[32m✔[0m [1m3 contracts checked[0m
-```
-
-Verificar contratos específicos:
-
-```terminal
-$ clarinet check contracts/token.clar
-[32m✔[0m [1mcontracts/token.clar Syntax of contract successfully checked[0m
-```
-
-## Formato de código
-
-Clarinet incluye un potente formateador de código para mantener un estilo consistente en todo su proyecto:
-
-Formatear todos los contratos en tu proyecto:
-
-```terminal
-$ clarinet format --in-place
-[32mFormatted[0m [1m5 contracts[0m
-```
-
-### Opciones de formato
-
-Personaliza el formato para que coincida con la guía de estilo de tu equipo:
-
-| Opción | Descripción | Ejemplo |
-|--------|-------------|---------|
-| `--dry-run` | Vista previa de cambios sin modificar archivos | `clarinet format --dry-run` |
-| `--in-place` | Reemplazar contenido del archivo (requerido para el formato real) | `clarinet format --in-place` |
-| `--max-line-length` | Establecer longitud máxima de línea | `clarinet format --max-line-length 100` |
-| `--indent` | Establecer tamaño de sangría | `clarinet format --indent 2` |
-| `--tabs` | Utilice tabulaciones en lugar de espacios | `clarinet format --tabs` |
-
-### Dar formato a archivos individuales
-
-```terminal
-$ clarinet format contracts/messy-contract.clar --in-place
-[32mFormatted[0m [1mcontracts/messy-contract.clar[0m
-```
-
-Formatear contratos específicos utilizando patrones glob:
-
-```terminal
-$ clarinet format contracts/token*.clar --in-place
-[32mFormatted[0m [1mcontracts/token-trait.clar[0m
-[32mFormatted[0m [1mcontracts/token-impl.clar[0m
-```
-
-## Configuración del proyecto
-
-### Trabajando con requisitos
-
-Agregar contratos de mainnet como dependencias:
-
-```terminal
-$ clarinet requirements add SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[32mAdded requirement[0m SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait
-[33mUpdated[0m [1mClarinet.toml[0m
-```
-
-Esto actualiza tu configuración:
-
-```toml Clarinet.toml
-[project]
-requirements = [
- { contract_id = "SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait" }
-]
-```
-
-Ahora puedes implementar rasgos de contratos de la red principal:
-
-```clarity contracts/my-nft.clar
-(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait)
-
-(define-non-fungible-token my-nft uint)
-;; ... implement required functions
-```
-
-## Próximos pasos
-
-:::next-steps
-* [Interacción con contratos](/tools/clarinet/contract-interaction): Aprende cómo interactuar con tus contratos.
-* [Pruebas y validación](/tools/clarinet/validation-and-analysis): Aprende cómo probar y validar tu proyecto de Clarinet.
-:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-cli)/validation-and-analysis.mdx b/content/docs/es/tools/clarinet/(clarinet-cli)/validation-and-analysis.mdx
deleted file mode 100644
index 16232d6b5..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-cli)/validation-and-analysis.mdx
+++ /dev/null
@@ -1,242 +0,0 @@
----
-title: Validando tus contratos
-sidebarTitle: Validación y análisis
-description: Clarinet proporciona herramientas poderosas para validar, analizar y depurar sus contratos inteligentes. Desde la comprobación estática de tipos hasta el análisis de costos en tiempo real, puede asegurarse de que sus contratos sean correctos y eficientes antes de la implementación.
----
-La validación de contratos en el desarrollo de Clarity abarca análisis estático, depuración en tiempo de ejecución y optimización de costos. Cada enfoque sirve para diferentes propósitos en la garantía de la corrección y eficiencia del contrato.
-
-## Comprendiendo la validación de contratos
-
-**Análisis Estático vs Depuración en Tiempo de Ejecución**
-
-| Static Analysis | Runtime Debugging |
-|-----------------------------|------------------------------|
-| Detecta errores antes del despliegue | Revela el comportamiento durante la ejecución |
-| Incompatibilidades de tipos, errores de sintaxis | Costos reales de ejecución |
-| Violaciones de cumplimiento de rasgos | Cambios de estado y efectos secundarios |
-| Uso de variables no definidas | Flujo y resultados de transacciones |
-| Problemas con firmas de funciones | Cuellos de botella de rendimiento |
-
-## Análisis estático
-
-El `clarinet check` el comando realiza una validación exhaustiva de sus contratos sin ejecutarlos:
-
-```terminal
-$ clarinet check
-[32m✔[0m [1m3 contracts checked[0m
-```
-
-Cuando la validación falla, Clarinet proporciona diagnósticos detallados:
-
-```terminal
-$ clarinet check
-[31m✖[0m [1m1 error detected[0m
-[31mError in contracts/token.clar:15:10[0m
- |
-15| (ok (+ balance amount))
- | ^^^^^^^
- |
- = [1mType error: expected uint, found (response uint uint)[0m
-```
-
-**Alcance de validación**
-
-Clarinet valida múltiples aspectos de tus contratos:
-
-| Tipo de validación | Qué verifica |
-|----------------|----------------|
-| **Seguridad de tipos** | Parámetros de función, valores de retorno, tipos de variables |
-| **Cumplimiento de rasgos** | La implementación coincide con las definiciones de rasgos |
-| **Consistencia de respuesta** | Las ramas ok/err devuelven los mismos tipos |
-| **Ámbito de variables** | Todas las variables definidas antes de su uso |
-| **Visibilidad de funciones** | Modificadores públicos/privados/de solo lectura |
-
-**Verificando contratos específicos**
-
-Validar contratos individuales durante el desarrollo enfocado:
-
-```terminal
-$ clarinet check contracts/nft.clar
-[32m✔[0m [1mcontracts/nft.clar Syntax of contract successfully checked[0m
-```
-
-**Integración con CI**
-
-Automatice la validación en su pipeline de integración continua. Por ejemplo, utilice GitHub Actions:
-
-```yaml .github/workflows/validate.yml -c
-name: Contract Validation
-on: [push, pull_request]
-
-jobs:
- sanity-checks:
- runs-on: ubuntu-latest
- container: hirosystems/clarinet:latest
- steps:
- - uses: actions/checkout@v4
- - name: Check Clarity contracts check
- run: clarinet check --use-on-disk-deployment-plan
- - name: Check Clarity contracts format
- run: clarinet format --check
-```
-
-## Análisis de tiempo de ejecución
-
-La consola de Clarinet proporciona potentes herramientas de análisis en tiempo de ejecución que le permiten inspeccionar el comportamiento del contrato durante la ejecución.
-
-### **Análisis de costos con `::toggle_costs`**
-
-Habilitar la visualización automática del costo después de cada expresión:
-
-```terminal
-$ clarinet console
-$ ::toggle_costs
-[1mAlways show costs: true[0m
-$ (contract-call? .counter count-up)
-[1m+----------------------+----------+------------+------------+
-| | Consumed | Limit | Percentage |
-|----------------------+----------+------------+------------|
-| Runtime | 4775 | 5000000000 | 0.00 % |
-|----------------------+----------+------------+------------|
-| Read count | 5 | 15000 | 0.03 % |
-|----------------------+----------+------------+------------|
-| Read length (bytes) | 268 | 100000000 | 0.00 % |
-|----------------------+----------+------------+------------|
-| Write count | 1 | 15000 | 0.01 % |
-|----------------------+----------+------------+------------|
-| Write length (bytes) | 41 | 15000000 | 0.00 % |
-+----------------------+----------+------------+------------+[0m
-[1m(ok true)[0m
-```
-
-### **Trazado de ejecución con `::trace`**
-
-Rastree las llamadas de función para comprender el flujo de ejecución:
-
-```terminal
-$ ::trace (contract-call? .defi-pool swap u100 'token-a 'token-b)
-(contract-call? .defi-pool swap u100 'token-a 'token-b) [1m[0m
-( get-pool-balance 'token-a ) [1mdefi-pool:15:8[0m
- [31m↳ args:[0m [1m'token-a[0m
- [1mu50000[0m
-( get-pool-balance 'token-b ) [1mdefi-pool:16:8[0m
- [31m↳ args:[0m [1m'token-b[0m
- [1mu75000[0m
-( calculate-output u100 u50000 u75000 ) [1mdefi-pool:18:12[0m
- [31m↳ args:[0m [1mu100, u50000, u75000[0m
- [1mu149[0m
-[1m(ok u149)[0m
-```
-
-### **Depuración interactiva con `::debug`**
-
-Establece puntos de interrupción y avanza paso a paso por la ejecución:
-
-```terminal
-$ ::debug (contract-call? .complex-contract process-batch)
-$ break validate-input
-[32mBreakpoint set at validate-input[0m
-$ continue
-[33mHit breakpoint at validate-input:23[0m
-```
-
-Comandos de navegación de depuración:
-
-* `step` o `s` - Entrar en sub-expresiones
-* `finish` o `f` - Completar la expresión actual
-* `next` o `n` - Pasar por encima de sub-expresiones
-* `continue` o `c` - Continuar hasta el siguiente punto de interrupción
-
-### **Usando `::get_costs` para analizar los costos de funciones específicas**
-
-```terminal
-$ ::get_costs (contract-call? .defi-pool add-liquidity u1000 u1000)
-[1m+----------------------+----------+------------+------------+
-| | Consumed | Limit | Percentage |
-|----------------------+----------+------------+------------|
-| Runtime | 12250 | 5000000000 | 0.00 % |
-|----------------------+----------+------------+------------|
-| Read count | 6 | 15000 | 0.04 % |
-|----------------------+----------+------------+------------|
-| Read length (bytes) | 192 | 100000000 | 0.00 % |
-|----------------------+----------+------------+------------|
-| Write count | 3 | 15000 | 0.02 % |
-|----------------------+----------+------------+------------|
-| Write length (bytes) | 96 | 15000000 | 0.00 % |
-+----------------------+----------+------------+------------+[0m
-[1m(ok {lp-tokens: u1000})[0m
-```
-
-### **Identificando y optimizando operaciones costosas utilizando `::trace`**
-
-```terminal
-$ ::trace (contract-call? .complex-algo process-large-dataset)
-```
-
-Buscar:
-
-* Bucles con altos conteos de iteración
-* Operaciones anidadas de mapeo/filtrado
-* Llamadas repetidas a contratos
-* Manipulaciones de estructuras de datos grandes
-
-## Flujos de trabajo de depuración
-
-Domina la depuración interactiva para identificar problemas rápidamente iniciando una sesión de depuración:
-
-```terminal
-$ clarinet console
-$ ::debug (contract-call? .counter count-up)
-[1mST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter[0m[1m:9:3[0m
- 6
- 7 ;; Increment the count for the caller
- 8 (define-public (count-up)
--> 9 (ok (map-set counters tx-sender (+ (get-count tx-sender) u1)))
- ^
- 10 )
- 11
- 12 ;; Get the current count for a user
-(debug)
-$ continue
-```
-
-### **Analizando transacciones fallidas usando `::trace`**
-
-```terminal
-$ ::trace (contract-call? .marketplace purchase u999)
-(contract-call? .marketplace purchase u999) [1m[0m
-( get-listing u999 ) [1mmarketplace:45:12[0m
- [31m↳ args:[0m [1mu999[0m
- [1mnone[0m
-[31m(err u404)[0m [1m# Listing not found[0m
-```
-
-### **Usando `::encode` y `::decode` para inspección de datos**
-
-Depurar estructuras de datos complejas:
-
-```terminal
-$ ::encode { id: u1, active: true }
-[32m0c0000000206616374697665030269640100000000000000000000000000000001[0m
-$ ::decode 0d0000000b48656c6c6f20776f726c64
-[32m"Hello world"[0m
-```
-
-### **Probando la lógica dependiente del tiempo**
-
-```terminal
-$ ::get_block_height
-[1mCurrent block height: 4[0m
-$ ::advance_chain_tip 100
-[32mnew burn height: 3[0m
-[32mnew stacks height: 104[0m
-$ (contract-call? .vesting claim)
-[32m(ok {claimed: u2500, remaining: u7500})[0m
-```
-
-## Próximos pasos
-
-:::next-steps
-* [Despliegue](/tools/clarinet/deployment): Aprende cómo desplegar tu proyecto de Clarinet.
-* [SDK de Clarinet](/tools/clarinet/sdk-introduction): Aprende cómo usar el SDK de Clarinet.
-:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/browser-sdk-reference.mdx b/content/docs/es/tools/clarinet/(clarinet-js-sdk)/browser-sdk-reference.mdx
deleted file mode 100644
index d162cd38b..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/browser-sdk-reference.mdx
+++ /dev/null
@@ -1,118 +0,0 @@
----
-title: Referencia del SDK de navegador JS de Clarinet
-sidebarTitle: Referencia del SDK del navegador
-description: Utilice el SDK de Clarinet directamente en entornos de navegador
-isNew: true
----
-El SDK de Clarinet se puede utilizar para interactuar con la simnet directamente desde navegadores web, permitiendo pruebas y simulaciones de contratos inteligentes de Clarity sin un backend o entorno de Node.js.
-
-## Instalación
-
-```package-install
-@hirosystems/clarinet-sdk-browser
-```
-
-## Uso
-
-El SDK del navegador implementa la misma API que el Node.js [SDK de Clarinet](/tools/clarinet/sdk-reference). Todos los métodos, propiedades y comparadores personalizados funcionan de manera idéntica.
-
-### Sesión vacía
-
-Para pruebas rápidas y experimentación sin un proyecto de Clarinet:
-
-```ts
-import { initSimnet } from '@hirosystems/clarinet-sdk-browser';
-
-const simnet = await initSimnet();
-await simnet.initEmptySession();
-
-// Execute Clarity code directly
-const result = simnet.runSnippet("(+ 1 2)");
-console.log(result); // 3
-```
-
-### Con un proyecto de Clarinet
-
-Para probar con un proyecto Clarinet existente utilizando un sistema de archivos virtual:
-
-```ts
-import { initSimnet } from '@hirosystems/clarinet-sdk-browser';
-
-const simnet = await initSimnet();
-await simnet.initSession("/project", "Clarinet.toml");
-
-// Your contracts are now available
-const count = simnet.getDataVar('counter', 'count');
-```
-
-:::callout
-### Sistema de archivos virtual
-
-El uso de un proyecto Clarinet en el navegador requiere configurar un sistema de archivos virtual. La documentación y ejemplos para este caso de uso avanzado estarán disponibles próximamente.
-:::
-
-## Casos de uso comunes
-
-### Área de juego interactiva de contratos
-
-```ts
-import { initSimnet } from '@hirosystems/clarinet-sdk-browser';
-import { Cl } from '@stacks/transactions';
-
-// Initialize simnet
-const simnet = await initSimnet();
-await simnet.initEmptySession();
-
-// Deploy a simple contract
-const sourceCode = `
-(define-data-var counter uint u0)
-
-(define-public (increment)
- (ok (var-set counter (+ (var-get counter) u1))))
-
-(define-read-only (get-counter)
- (ok (var-get counter)))
-`;
-
-simnet.deployContract('counter', sourceCode, null, simnet.deployer);
-
-// Interact with the contract
-simnet.callPublicFn('counter', 'increment', [], simnet.deployer);
-const count = simnet.callReadOnlyFn('counter', 'get-counter', [], simnet.deployer);
-console.log(count.result); // (ok u1)
-```
-
-### Pruebas en IDEs basados en navegador
-
-```ts
-import { initSimnet } from '@hirosystems/clarinet-sdk-browser';
-import { expect } from 'vitest';
-
-const simnet = await initSimnet();
-await simnet.initEmptySession();
-
-// Run tests directly in the browser
-test('counter increments correctly', () => {
- simnet.deployContract('counter', counterCode, null, simnet.deployer);
-
- const result = simnet.callPublicFn('counter', 'increment', [], simnet.deployer);
- expect(result.result).toBeOk(Cl.uint(1));
-
- const count = simnet.getDataVar('counter', 'counter');
- expect(count).toBeUint(1);
-});
-```
-
-## Compatibilidad del navegador
-
-El SDK del navegador funciona en todos los navegadores modernos que admiten:
-
-* ES2020+ JavaScript features
-* WebAssembly
-* Importaciones dinámicas
-
-Los navegadores probados incluyen:
-
-* Chrome/Edge 90+
-* Firefox 89+
-* Safari 15+
diff --git a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/integration-testing.mdx b/content/docs/es/tools/clarinet/(clarinet-js-sdk)/integration-testing.mdx
deleted file mode 100644
index 70cfe6dba..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/integration-testing.mdx
+++ /dev/null
@@ -1,218 +0,0 @@
----
-title: Escribiendo pruebas de integración
-sidebarTitle: Pruebas de integración
-description: Las pruebas de integración son un paso crucial en el desarrollo de contratos inteligentes que implica probar cómo funcionan juntos los diferentes componentes de su sistema. El SDK de Clarinet JS proporciona herramientas poderosas para escribir y ejecutar pruebas de integración, permitiéndole simular escenarios complejos e interacciones entre múltiples contratos.
----
-import { ArrowRight, Check } from 'lucide-react';
-
-## Lo que aprenderás
-
-:::objectives
-* Configurar pruebas de integración para flujos de trabajo de múltiples pasos
-* Probando interacciones y dependencias de contratos
-* Simular escenarios del mundo real
-* Verificar cambios de estado en todo el sistema
-:::
-
-## Configura tu proyecto
-
-Crea un nuevo proyecto de Clarinet e instala las dependencias:
-
-```terminal
-$ clarinet new stx-defi
-$ cd stx-defi
-$ npm install
-```
-
-## Crear el contrato mejorado
-
-Utilizaremos un contrato DeFi mejorado que admite tanto depósitos como préstamos. Cree el contrato:
-
-```terminal
-$ clarinet contract new defi
-```
-
-Reemplazar `contracts/defi.clar` con esta versión mejorada:
-
-```clarity contracts/defi.clar
-;; Error constants
-(define-constant err-overborrow (err u300))
-
-;; Interest rate (10%)
-(define-data-var loan-interest-rate uint u10)
-
-;; Total deposits in the contract
-(define-data-var total-deposits uint u0)
-
-;; User deposits
-(define-map deposits { owner: principal } { amount: uint })
-
-;; User loans
-(define-map loans principal { amount: uint, last-interaction-block: uint })
-
-;; Deposit STX into the contract
-(define-public (deposit (amount uint))
- (let
- (
- (current-balance (default-to u0 (get amount (map-get? deposits { owner: tx-sender }))))
- )
- (try! (stx-transfer? amount tx-sender (as-contract tx-sender)))
- (map-set deposits { owner: tx-sender } { amount: (+ current-balance amount) })
- (var-set total-deposits (+ (var-get total-deposits) amount))
- (ok true)
- )
-)
-
-;; Borrow STX based on deposits (up to 50% of deposit)
-(define-public (borrow (amount uint))
- (let
- (
- (user-deposit (default-to u0 (get amount (map-get? deposits { owner: tx-sender }))))
- (allowed-borrow (/ user-deposit u2))
- (current-loan-details (default-to { amount: u0, last-interaction-block: u0 }
- (map-get? loans tx-sender)))
- (accrued-interest (calculate-accrued-interest
- (get amount current-loan-details)
- (get last-interaction-block current-loan-details)))
- (total-due (+ (get amount current-loan-details) (unwrap-panic accrued-interest)))
- (new-loan (+ amount))
- )
- (asserts! (<= new-loan allowed-borrow) err-overborrow)
- (try! (as-contract (stx-transfer? amount tx-sender tx-sender)))
- (map-set loans tx-sender { amount: new-loan, last-interaction-block: block-height })
- (ok true)
- )
-)
-
-;; Get user's balance
-(define-read-only (get-balance-by-sender)
- (ok (map-get? deposits { owner: tx-sender }))
-)
-
-;; Get amount owed including interest
-(define-read-only (get-amount-owed)
- (let
- (
- (current-loan-details (default-to { amount: u0, last-interaction-block: u0 }
- (map-get? loans tx-sender)))
- (accrued-interest (calculate-accrued-interest
- (get amount current-loan-details)
- (get last-interaction-block current-loan-details)))
- (total-due (+ (get amount current-loan-details) (unwrap-panic accrued-interest)))
- )
- (ok total-due)
- )
-)
-
-;; Calculate interest
-(define-private (calculate-accrued-interest (principal uint) (start-block uint))
- (let
- (
- (elapsed-blocks (- block-height start-block))
- (interest (/ (* principal (var-get loan-interest-rate) elapsed-blocks) u10000))
- )
- (asserts! (not (is-eq start-block u0)) (ok u0))
- (ok interest)
- )
-)
-```
-
-Correr `clarinet check` para asegurar que su contrato sea válido:
-
-```terminal
-$ clarinet check
-[32m✔ 1 contract checked[0m
-```
-
-## Escribir pruebas de integración
-
-Crea una prueba que simule un flujo de trabajo completo del usuario - depositar y luego pedir prestado:
-
-```typescript tests/defi.test.ts
-import { describe, it, expect } from 'vitest';
-import { Cl } from '@stacks/transactions';
-
-const accounts = simnet.getAccounts();
-const wallet1 = accounts.get('wallet_1')!;
-
-describe('stx-defi integration', () => {
- it('allows deposit and borrow workflow', () => {
- // Step 1: User deposits STX
- const depositResult = simnet.callPublicFn(
- 'defi',
- 'deposit',
- [Cl.uint(1000)],
- wallet1
- );
- expect(depositResult.result).toBeOk(Cl.bool(true));
-
- // Verify deposit was recorded
- const totalDeposits = simnet.getDataVar('defi', 'total-deposits');
- expect(totalDeposits).toBeUint(1000);
-
- // Step 2: User borrows against deposit
- const borrowResult = simnet.callPublicFn(
- 'defi',
- 'borrow',
- [Cl.uint(400)], // Borrowing 40% of deposit
- wallet1
- );
- expect(borrowResult.result).toBeOk(Cl.bool(true));
-
- // Step 3: Check amount owed
- const { result } = simnet.callReadOnlyFn(
- 'defi',
- 'get-amount-owed',
- [],
- wallet1
- );
- expect(result).toBeOk(Cl.uint(400)); // No interest yet at same block
- });
-
- it('prevents over-borrowing', () => {
- // Setup: deposit first
- simnet.callPublicFn('defi', 'deposit', [Cl.uint(1000)], wallet1);
-
- // Attempt to borrow more than allowed (>50%)
- const borrowResult = simnet.callPublicFn(
- 'defi',
- 'borrow',
- [Cl.uint(600)],
- wallet1
- );
-
- // Should fail with err-overborrow
- expect(borrowResult.result).toBeErr(Cl.uint(300));
- });
-});
-```
-
-En esta prueba de integración, estamos simulando un escenario donde un usuario deposita STX en el contrato DeFi y luego pide un préstamo contra ese depósito. Analicemos los aspectos clave:
-
-* **`callPublicFn`** - Simula la llamada a funciones públicas tal como en la cadena de bloques real
-* **`getDataVar`** - Recupera el valor de las variables de datos del contrato
-* **`callReadOnlyFn`** - Llama a funciones de solo lectura sin modificar el estado
-* **Comparadores personalizados** - `toBeOk()` y `toBeErr()` validar tipos de respuesta de Clarity
-
-## Pruébalo
-
-Ejecute sus pruebas de integración:
-
-```terminal
-$ npm run test
-```
-
-## Problemas comunes
-
-| Problema | Solución |
-|-------|----------|
-| Contaminación del estado entre pruebas | Cada prueba se ejecuta de forma aislada - el estado no se transfiere |
-| Problemas de sincronización | Usar `simnet.mineEmptyBlocks()` para avanzar la altura del bloque |
-| Afirmaciones complejas | Desglosar en pruebas más pequeñas y enfocadas |
-
-## Próximos pasos
-
-:::next-steps
-* [Referencia del SDK](/tools/clarinet/sdk-reference): Aprende más sobre el SDK de Clarinet JS.
-* [Integración de Stacks.js](/tools/clarinet/stacks-js-integration): Aprende cómo integrar Stacks.js con tu proyecto de Clarinet.
-:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/mainnet-execution-simulation.mdx b/content/docs/es/tools/clarinet/(clarinet-js-sdk)/mainnet-execution-simulation.mdx
deleted file mode 100644
index 273a16d0b..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/mainnet-execution-simulation.mdx
+++ /dev/null
@@ -1,132 +0,0 @@
----
-title: Pruebas con datos de la red principal
-sidebarTitle: Simulación de ejecución de la red principal
-description: Mainnet Execution Simulation (MXS) te permite probar tus contratos inteligentes de Clarity utilizando datos y estados reales de la red principal de Stacks. Esta poderosa función ayuda a garantizar que tus contratos se comporten como se espera en un entorno en vivo.
----
-:::objectives
-* Configurando MXS en tu proyecto de Clarinet
-* Escribiendo pruebas que interactúan con contratos de la red principal
-* Simulando transacciones históricas
-* Entendiendo las limitaciones de MXS
-:::
-
-## ¿Qué es la simulación de ejecución de Mainnet?
-
-Probar contratos inteligentes en condiciones realistas es esencial. Simnet ofrece un entorno aislado pero carece de la complejidad y el historial de la red principal de Stacks en vivo.
-
-MXS llena este vacío al permitir pruebas unitarias con el SDK de Clarinet JS y Vitest para simular el estado de la red principal de Stacks en una altura de bloque específica. Esto te permite:
-
-* **Validar la lógica del contrato con datos reales:** Prueba directamente contratos o datos de la red principal dentro de tus pruebas.
-* **(Re)simular transacciones:** Analiza los resultados, la ejecución o los costos de las transacciones de la red principal sin implementar ni usar STX reales.
-
-## Habilitar MXS en su proyecto
-
-Agregue la siguiente configuración a su `Clarinet.toml` archivo:
-
-```toml Clarinet.toml
-[repl.remote_data]
-# Enable mainnet execution simulation
-enabled = true
-# Specify the Stacks block height to fork from
-initial_height = 522000
-# API URL (optional, defaults to https://api.hiro.so)
-api_url = 'https://api.hiro.so'
-```
-
-:::callout
-type: tip
-
-### Consejo profesional
-
-Estableciendo un específico `initial_height` garantiza resultados de pruebas consistentes y reproducibles.
-:::
-
-## Uso de direcciones de mainnet
-
-Cuando se prueban contratos que verifican o requieren direcciones de la red principal, establezca `use_mainnet_wallets = true`. Esto permite que tus pruebas de simnet utilicen direcciones de mainnet (SP/SM) en lugar de direcciones de testnet (ST).
-
-```toml Clarinet.toml
-[repl.remote_data]
-enabled = true
-initial_height = 522000
-use_mainnet_wallets = true # !mark
-```
-
-Esto es particularmente útil cuando:
-
-* Pruebas contra contratos exclusivos de mainnet como protocolos DEX
-* Su contrato incluye [`(is-standard standard-or-contract-principal)`](/resources/clarity/reference/functions#is-standard) validación
-* Simulando transacciones que requieren formatos de dirección de mainnet
-
-## Configurar el acceso a la API
-
-Aunque MXS funciona sin una clave de API, es posible que encuentre límites de velocidad. Configure una clave de API para un acceso confiable:
-
-```terminal
-$ export HIRO_API_KEY=""
-```
-
-## Escribir pruebas con datos de la red principal
-
-Una vez que MXS está habilitado, tus pruebas operan automáticamente contra la instantánea del estado de la red principal. Aquí tienes un ejemplo de prueba contra la red principal `pox-4` contrato:
-
-```ts tests/pox-4.test.ts
-import { describe, it, expect } from "vitest";
-import { Cl } from "@stacks/transactions";
-
-const accounts = simnet.getAccounts();
-const deployer = accounts.get("deployer")!;
-
-describe("pox-4 mainnet interaction", () => {
- it("reads current reward cycle from mainnet", () => {
- // Call the mainnet pox-4 contract
- const call = simnet.callReadOnlyFn(
- "SP000000000000000000002Q6VF78.pox-4", // Mainnet contract
- "current-pox-reward-cycle",
- [],
- deployer
- );
-
- // Assert the result (adjust based on your initial_height)
- expect(call.result).toBeUint(109);
-
- console.log("Current POX reward cycle:", Cl.prettyPrint(call.result));
- });
-});
-```
-
-La prueba utiliza `simnet.callReadOnlyFn` al igual que en las pruebas unitarias estándar, pero debido a que MXS está habilitado, se dirige al real `pox-4` estado del contrato en la altura de bloque especificada.
-
-## Pruébalo
-
-Ejecuta tu prueba para ver MXS en acción:
-
-```terminal
-$ npm run test
-```
-
-## Problemas comunes
-
-| Problema | Solución |
-|----------|----------|
-| Errores de límite de tasa | Configurar `HIRO_API_KEY` variable de entorno |
-| Resultados inconsistentes | Corregir `initial_height` en configuración |
-| Función no encontrada | Verifique que el contrato exista en su altura de bloque |
-
-## Probando en el área de pruebas
-
-Experimente rápidamente con MXS sin configurar un proyecto:
-
-1. Visitar [https://play.hiro.so/?remote\_data=true](https://play.hiro.so/?remote_data=true)
-2. Ejecutar llamadas de contrato en la red principal:
-
-```terminal
-$ contract-call? 'SP000000000000000000002Q6VF78.pox-4 current-pox-reward-cycle
-```
-
-## Próximos pasos
-
-:::next-steps
-* [Integración del oráculo Pyth](/tools/clarinet/pyth-oracle-integration): Aprende cómo integrar el oráculo Pyth con tu proyecto Clarinet.
-* [Integración de sBTC](/tools/clarinet/sbtc-integration): Aprende cómo integrar el sBTC con tu proyecto Clarinet.
-:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/sdk-introduction.mdx b/content/docs/es/tools/clarinet/(clarinet-js-sdk)/sdk-introduction.mdx
deleted file mode 100644
index a3f542a8d..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/sdk-introduction.mdx
+++ /dev/null
@@ -1,301 +0,0 @@
----
-title: SDK de JavaScript para Clarinet
-sidebarTitle: Introducción
-description: Guía práctica para probar contratos inteligentes con el SDK JS de Clarinet
-type: concept
----
-import { File, Folder, Files } from 'fumadocs-ui/components/files';
-
-El SDK de Clarinet JS proporciona un potente marco de pruebas para contratos inteligentes de Clarity. Se integra perfectamente con Vitest para permitir pruebas exhaustivas de la lógica de tu contrato en un entorno simulado.
-
-## Configuración inicial
-
-Comience creando un nuevo proyecto de Node.js o utilizando uno existente:
-
-```package-install
-$ init -y
-```
-
-Instale el SDK de Clarinet JS y las dependencias requeridas:
-
-```package-install
-@hirosystems/clarinet-sdk vitest @stacks/transactions
-```
-
-## Estructura del proyecto
-
-Crea la siguiente estructura para tus pruebas de contratos inteligentes:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-## Prueba simple
-
-Crea un archivo de prueba simple para verificar que tu contrato funciona:
-
-```ts tests/counter.test.ts
-import { describe, expect, it } from "vitest";
-import { Cl } from "@stacks/transactions";
-
-const accounts = simnet.getAccounts();
-const wallet = accounts.get("wallet_1")!;
-
-describe("counter contract", () => {
- it("increments the count", () => {
- const countUpCall = simnet.callPublicFn("counter", "count-up", [], wallet);
- expect(countUpCall.result).toBeOk(Cl.bool(true));
- });
-});
-```
-
-El `simnet` El objeto está disponible automáticamente en tus pruebas y proporciona un entorno simulado de la cadena de bloques de Stacks.
-
-## Opciones de configuración
-
-### Configuración de Clarinet
-
-Crear un `Clarinet.toml` archivo para definir tus contratos:
-
-```toml Clarinet.toml
-[project]
-name = "my-project"
-
-[contracts.counter]
-path = "contracts/counter.clar"
-```
-
-### Configuración de TypeScript
-
-Configurar TypeScript para el SDK:
-
-```json tsconfig.json
-{
- "compilerOptions": {
- "target": "ES2020",
- "module": "ESNext",
- "moduleResolution": "node",
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "types": ["vitest/globals"]
- },
- "include": ["tests/**/*.ts"],
- "exclude": ["node_modules"]
-}
-```
-
-### Configuración de Vitest
-
-Configura Vitest para que funcione con el SDK:
-
-```js vitest.config.js
-import { defineConfig } from "vitest/config";
-import { vitestSetupFilePath } from "@hirosystems/clarinet-sdk/vitest";
-
-export default defineConfig({
- test: {
- environment: "node",
- globals: true,
- setupFiles: [vitestSetupFilePath],
- },
-});
-```
-
-:::callout
-type: warn
-
-### Importante
-
-El `vitestSetupFilePath` debe ser incluido en su `setupFiles` matriz para que el SDK funcione correctamente.
-:::
-
-### Scripts de paquete
-
-Añade scripts de prueba a tu `package.json`:
-
-```json package.json
-"scripts": {
- "test": "vitest run",
- "test:watch": "vitest",
- "test:coverage": "vitest run --coverage"
-}
-```
-
-## Patrones comunes
-
-### Probando funciones de solo lectura
-
-Cuando se prueban funciones que no modifican el estado, use `callReadOnlyFn`:
-
-```ts
-const getCountCall = simnet.callReadOnlyFn(
- "counter",
- "get-count",
- [Cl.principal(wallet)],
- wallet
-);
-expect(getCountCall.result).toBeUint(1);
-```
-
-### Probando funciones públicas con parámetros
-
-Pasa parámetros utilizando los ayudantes de tipo Clarity apropiados:
-
-```ts
-const depositCall = simnet.callPublicFn(
- "defi",
- "deposit",
- [Cl.uint(1000)], // Convert JS number to Clarity uint
- wallet
-);
-expect(depositCall.result).toBeOk(Cl.bool(true));
-```
-
-### Accediendo al estado del contrato
-
-Verificar variables de datos y mapas directamente:
-
-```ts
-// Get a data variable
-const totalDeposits = simnet.getDataVar("defi", "total-deposits");
-expect(totalDeposits).toBeUint(1000);
-
-// Get a map entry
-const balance = simnet.getMapEntry("defi", "balances", Cl.principal(wallet));
-expect(balance).toBeUint(1000);
-```
-
-## Ejemplos
-
-### Probando el despliegue de contratos
-
-Asegúrese de que su contrato esté correctamente desplegado antes de probar sus funciones:
-
-```ts
-it("ensures the contract is deployed", () => {
- const contractSource = simnet.getContractSource("counter");
- expect(contractSource).toBeDefined();
-});
-```
-
-### Probando condiciones de error
-
-Verifique que su contrato maneje los errores correctamente:
-
-```ts
-it("fails when borrowing too much", () => {
- const borrowCall = simnet.callPublicFn(
- "defi",
- "borrow",
- [Cl.uint(10000)], // Amount exceeds allowed
- wallet
- );
- expect(borrowCall.result).toBeErr(Cl.uint(300)); // err-overborrow
-});
-```
-
-### Pruebas con múltiples cuentas
-
-Simular interacciones entre diferentes usuarios:
-
-```ts
-const wallet1 = accounts.get("wallet_1")!;
-const wallet2 = accounts.get("wallet_2")!;
-
-// Wallet 1 deposits
-simnet.callPublicFn("defi", "deposit", [Cl.uint(1000)], wallet1);
-
-// Wallet 2 tries to withdraw wallet 1's funds (should fail)
-const withdrawCall = simnet.callPublicFn(
- "defi",
- "withdraw",
- [Cl.uint(1000)],
- wallet2
-);
-expect(withdrawCall.result).toBeErr(Cl.uint(401)); // err-unauthorized
-```
-
-## Ejecutando pruebas
-
-Ejecute su conjunto de pruebas:
-
-```terminal
-$ npm test
-```
-
-Generar informes de cobertura:
-
-```terminal
-$ npm run test:coverage
-```
-
-Esto crea un análisis detallado de cobertura y costos para las funciones de tu contrato.
-
-## Uso avanzado
-
-### Uso del SDK en proyectos existentes
-
-Si tienes un proyecto existente de JavaScript/TypeScript con una estructura personalizada, aún puedes utilizar el SDK:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Especifique la ubicación de Clarinet.toml en su configuración de Vitest:
-
-```js vitest.config.js
-export default defineConfig({
- test: {
- environment: "node",
- globals: true,
- setupFiles: [vitestSetupFilePath],
- env: {
- CLARINET_MANIFEST_PATH: "./blockchain/Clarinet.toml"
- }
- },
-});
-```
-
-## Próximos pasos
-
-:::next-steps
-* [Pruebas unitarias](/tools/clarinet/unit-testing): Aprende cómo probar tu contrato con pruebas unitarias.
-* [Referencia del SDK](/tools/clarinet/sdk-reference): Aprende más sobre el SDK de JS de Clarinet.
-:::
diff --git a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/sdk-reference.mdx b/content/docs/es/tools/clarinet/(clarinet-js-sdk)/sdk-reference.mdx
deleted file mode 100644
index 11998a550..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/sdk-reference.mdx
+++ /dev/null
@@ -1,617 +0,0 @@
----
-title: Referencia del SDK de Clarinet JS
-sidebarTitle: Referencia del SDK
-isNew: true
----
-El SDK de Clarinet JS proporciona una suite completa de métodos para probar e interactuar con contratos inteligentes de Clarity. Desde la inicialización del simnet hasta el despliegue de contratos, el SDK simplifica todo tu flujo de trabajo de pruebas.
-
-* Inicializar una red simulada: [`initSimnet`](#initSimnet)
-* Gestionar el estado del contrato: [`getDataVar`](#getDataVar), [`getMapEntry`](#getMapEntry)
-* Llamar a funciones de contrato: [`callReadOnlyFn`](#callReadOnlyFn), [`callPublicFn`](#callPublicFn)
-* Transferir STX: [`transferSTX`](#transferSTX)
-* Desplegar contratos: [`deployContract`](#deployContract)
-* Mina bloques: [`mineBlock`](#mineBlock), [`mineEmptyBlock`](#mineEmptyBlock)
-* Aserciones personalizadas: [`toBeOk`](#toBeOk), [`toBeErr`](#toBeErr)
-
-## Instalación
-
-```package-install
-@hirosystems/clarinet-sdk
-```
-
-## Inicializar red simulada \[#initalize-simnet]
-
-### iniciarSimnet
-
-`initSimnet` inicializa una red simulada para probar tus contratos inteligentes.
-
-**Uso**
-
-```console
-initSimnet(manifestPath?: string): Promise
-```
-
-```ts -c
-import { initSimnet } from '@hirosystems/clarinet-sdk';
-
-const simnet = await initSimnet();
-```
-
-| Parámetro | Tipo | Descripción |
-|-----------|------|-------------|
-| `manifestPath` | `string` | Ruta opcional al archivo de manifiesto Clarinet.toml |
-
-## Propiedades de Simnet \[#properties]
-
-### altura del bloque \[#blockHeight]
-
-Devuelve la altura actual del bloque de simnet.
-
-```ts -c
-const currentBlockHeight = simnet.blockHeight;
-// Returns: 1
-```
-
-### desplegador \[#deployer]
-
-Devuelve la dirección del deployer predeterminado según se define en el archivo del proyecto.
-
-```ts -c
-const deployerAddress = simnet.deployer;
-// Returns: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
-```
-
-También puedes actualizar el deployer:
-
-```ts -c
-simnet.deployer = 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5';
-```
-
-### épocaActual \[#épocaActual]
-
-Devuelve la época actual de simnet (por ejemplo, 2.5 para Stacks 2.5).
-
-```ts -c
-const epoch = simnet.currentEpoch;
-// Returns: 2.5
-```
-
-## Gestión de cuenta \[#account-management]
-
-### getAccounts \[#getAccounts]
-
-`getAccounts` recupera todas las direcciones de Stacks configuradas, incluyendo billeteras, implementadores y faucets.
-
-**Uso**
-
-```console
-getAccounts(): Map
-```
-
-```ts -c
-const accounts = simnet.getAccounts();
-const wallet1 = accounts.get('wallet_1')!;
-// Returns: ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5
-```
-
-## Saldos de activos \[#asset-balances]
-
-### getAssetsMap \[#getAssetsMap]
-
-`getAssetsMap` recupera los saldos de activos para todas las direcciones, incluyendo STX, tokens fungibles y no fungibles.
-
-**Uso**
-
-```console
-getAssetsMap(): Map>
-```
-
-```ts -c
-const assets = simnet.getAssetsMap();
-const stxBalances = assets.get('STX')!;
-const deployerBalance = stxBalances.get(simnet.deployer)!;
-// Returns: 100000000000000n
-```
-
-## Leer el estado del contrato \[#state-reading]
-
-### getDataVar \[#getDataVar]
-
-`getDataVar` recupera el valor de una variable de datos de un contrato.
-
-**Uso**
-
-```console
-getDataVar(contract: string, dataVar: string): ClarityValue
-```
-
-```ts -c
-const count = simnet.getDataVar('counter', 'count');
-// Returns: { type: 1, value: 1n }
-```
-
-| Parámetro | Tipo | Descripción |
-|-----------|------|-------------|
-| `contract` | `string` | Identificador del contrato |
-| `dataVar` | `string` | Nombre de la variable de datos |
-
-### getMapEntry \[#getMapEntry]
-
-`getMapEntry` recupera un valor de un mapa de contrato por su clave.
-
-**Uso**
-
-```console
-getMapEntry(contract: string, mapName: string, mapKey: ClarityValue): ClarityValue
-```
-
-```ts -c
-import { Cl } from '@stacks/transactions';
-
-const hasParticipated = simnet.getMapEntry(
- "pool",
- "Participants",
- Cl.standardPrincipal(wallet)
-);
-// Returns: { type: 10, value: { type: 3 } }
-```
-
-| Parámetro | Tipo | Descripción |
-|-----------|------|-------------|
-| `contract` | `string` | Identificador del contrato |
-| `mapName` | `string` | Nombre del mapa |
-| `mapKey` | `ClarityValue` | Clave para buscar |
-
-## Llamar a funciones de contrato \[#function-calls]
-
-### callReadOnlyFn \[#callReadOnlyFn]
-
-`callReadOnlyFn` llama a funciones de solo lectura sin minar un bloque.
-
-**Uso**
-
-```console
-callReadOnlyFn(
- contract: string,
- method: string,
- args: ClarityValue[],
- sender: string
-): ParsedTransactionResult
-```
-
-```ts -c
-import { Cl } from '@stacks/transactions';
-
-const result = simnet.callReadOnlyFn(
- 'pool',
- 'get-contribution-amount',
- [Cl.standardPrincipal(wallet)],
- wallet
-);
-// Returns: { result: { type: 1, value: 42000000n }, events: [] }
-```
-
-| Parámetro | Tipo | Descripción |
-|-----------|------|-------------|
-| `contract` | `string` | Identificador del contrato |
-| `method` | `string` | Nombre de la función |
-| `args` | `ClarityValue[]` | Argumentos de función |
-| `sender` | `string` | Dirección del remitente |
-
-### callPublicFn \[#callPublicFn]
-
-`callPublicFn` llama a funciones públicas y mina un bloque.
-
-**Uso**
-
-```console
-callPublicFn(
- contract: string,
- method: string,
- args: ClarityValue[],
- sender: string
-): ParsedTransactionResult
-```
-
-```ts -c
-import { Cl } from '@stacks/transactions';
-
-const result = simnet.callPublicFn(
- 'pool',
- 'register-participant',
- [Cl.standardPrincipal(wallet)],
- wallet
-);
-// Mines block and returns result
-```
-
-### callPrivateFn \[#callPrivateFn]
-
-`callPrivateFn` llama a funciones privadas (solo para pruebas) y mina un bloque.
-
-**Uso**
-
-```console
-callPrivateFn(
- contract: string,
- method: string,
- args: ClarityValue[],
- sender: string
-): ParsedTransactionResult
-```
-
-```ts -c
-const result = simnet.callPrivateFn(
- "pool",
- "reward-participant-points",
- [Cl.standardPrincipal(address1)],
- wallet
-);
-```
-
-## Transferir STX \[#transferSTX]
-
-`transferSTX` transfiere STX entre direcciones y mina un bloque.
-
-**Uso**
-
-```console
-transferSTX(
- amount: number | bigint,
- recipient: string,
- sender: string
-): ParsedTransactionResult
-```
-
-```ts -c
-const transfer = simnet.transferSTX(
- 42000000, // 42 STX in microSTX
- recipient,
- simnet.deployer
-);
-// Returns transaction result with transfer event
-```
-
-| Parámetro | Tipo | Descripción |
-|-----------|------|-------------|
-| `amount` | `number \| bigint` | Cantidad en microSTX |
-| `recipient` | `string` | Dirección del destinatario |
-| `sender` | `string` | Dirección del remitente |
-
-## Desplegar contratos \[#deployContract]
-
-`deployContract` despliega un nuevo contrato en simnet y mina un bloque.
-
-**Uso**
-
-```console
-deployContract(
- name: string,
- content: string,
- options: DeployContractOptions | null,
- sender: string
-): ParsedTransactionResult
-```
-
-```ts -c
-const sourceCode = '(define-read-only (say-hi) (ok "Hello World"))';
-
-const contract = simnet.deployContract(
- 'hello-world',
- sourceCode,
- { clarityVersion: 2 },
- simnet.deployer
-);
-```
-
-| Parámetro | Tipo | Descripción |
-|-----------|------|-------------|
-| `name` | `string` | Nombre del contrato |
-| `content` | `string` | Código fuente de Clarity |
-| `options` | `object \| null` | Opciones de implementación |
-| `sender` | `string` | Dirección del implementador |
-
-## Minería de bloques \[#block-mining]
-
-### minarBloque \[#mineBlock]
-
-`mineBlock` mina un bloque con múltiples transacciones.
-
-**Uso**
-
-```console
-mineBlock(txs: Tx[]): ParsedTransactionResult[]
-```
-
-```ts -c
-import { tx } from '@hirosystems/clarinet-sdk';
-import { Cl } from '@stacks/transactions';
-
-const block = simnet.mineBlock([
- tx.callPublicFn("counter", "increment", [], simnet.deployer),
- tx.transferSTX(19000000, wallet, simnet.deployer),
-]);
-```
-
-### minarBloqueVacío \[#mineEmptyBlock]
-
-`mineEmptyBlock` mina un bloque vacío y aumenta la altura del bloque.
-
-**Uso**
-
-```console
-mineEmptyBlock(): number
-```
-
-```ts -c
-simnet.mineEmptyBlock();
-const newHeight = simnet.blockHeight;
-// Returns: 2
-```
-
-### minarBloquesVacíos \[#mineEmptyBlocks]
-
-`mineEmptyBlocks` mina múltiples bloques vacíos.
-
-**Uso**
-
-```console
-mineEmptyBlocks(count?: number): number
-```
-
-```ts -c
-simnet.mineEmptyBlocks(5);
-const newHeight = simnet.blockHeight;
-// Returns: 6
-```
-
-## Métodos de utilidad \[#utility-methods]
-
-### ejecutarFragmento \[#ejecutarFragmento]
-
-`runSnippet` ejecuta código Clarity arbitrario sin desplegar.
-
-**Uso**
-
-```console
-runSnippet(snippet: string): string | ClarityValue
-```
-
-```ts -c
-const result = simnet.runSnippet('(stx-account tx-sender)');
-// Returns account balance information
-```
-
-### getContractsInterfaces \[#getContractsInterfaces]
-
-`getContractsInterfaces` devuelve interfaces de contrato con firmas de funciones y almacenamiento.
-
-**Uso**
-
-```console
-getContractsInterfaces(): Map
-```
-
-```ts -c
-const interfaces = simnet.getContractsInterfaces();
-const poolInterface = interfaces.get(`${simnet.deployer}.pool`);
-// Returns contract interface with functions, maps, variables
-```
-
-### getContractSource \[#getContractSource]
-
-`getContractSource` recupera el código fuente de un contrato implementado.
-
-**Uso**
-
-```console
-getContractSource(contract: string): string | undefined
-```
-
-```ts -c
-const source = simnet.getContractSource('pool');
-// Returns Clarity source code as string
-```
-
-### getContractAST \[#getContractAST]
-
-`getContractAST` devuelve el Árbol de Sintaxis Abstracta de un contrato.
-
-**Uso**
-
-```console
-getContractAST(contractId: string): ContractAST
-```
-
-```ts -c
-const ast = simnet.getContractAST('pool');
-// Returns parsed AST structure
-```
-
-## Comparadores personalizados \[#custom-matchers]
-
-El SDK proporciona comparadores de Vitest para aserciones de valores de Clarity.
-
-### Comparadores de respuesta \[#response-matchers]
-
-#### toBeOk \[#toBeOk]
-
-Afirma que una respuesta es `(ok )`.
-
-```ts
-expect(result).toBeOk(Cl.uint(1));
-```
-
-#### toBeErr \[#toBeErr]
-
-Afirma que una respuesta es `(err )`.
-
-```ts
-expect(result).toBeErr(Cl.uint(500));
-```
-
-#### toBeSome \[#toBeSome]
-
-Afirma que una respuesta es `(some )`.
-
-```ts
-expect(result).toBeSome(Cl.bool(true));
-```
-
-#### toBeNone \[#toBeNone]
-
-Afirma que una respuesta es `(none)`.
-
-```ts
-expect(result).toBeNone();
-```
-
-### Comparadores de valor \[#value-matchers]
-
-#### toBeBool \[#toBeBool]
-
-Afirma un valor booleano.
-
-```ts
-expect(result).toBeBool(true);
-```
-
-#### toBeInt \[#toBeInt]
-
-Afirma un valor entero con signo.
-
-```ts
-expect(result).toBeInt(1); // or 1n
-```
-
-#### toBeUint \[#toBeUint]
-
-Afirma un valor entero sin signo.
-
-```ts
-expect(result).toBeUint(1); // or 1n
-```
-
-#### toBeAscii \[#toBeAscii]
-
-Afirma un valor de cadena ASCII.
-
-```ts
-expect(result).toBeAscii('Hello World');
-```
-
-#### toBeUtf8 \[#toBeUtf8]
-
-Afirma un valor string-utf8.
-
-```ts
-expect(result).toBeUtf8('Hello World');
-```
-
-#### serPrincipal \[#serPrincipal]
-
-Afirma un valor principal.
-
-```ts
-expect(Cl.standardPrincipal(deployer)).toBePrincipal(deployer);
-```
-
-#### toBeBuff \[#toBeBuff]
-
-Afirma un valor de búfer.
-
-```ts
-const buffer = Uint8Array.from([1, 2, 3, 4]);
-expect(result).toBeBuff(buffer);
-```
-
-#### Lista de ser \[#toBeList]
-
-Afirma una lista de valores de Clarity.
-
-```ts
-expect(result).toBeList([
- Cl.standardPrincipal('ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM'),
- Cl.standardPrincipal('ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5')
-]);
-```
-
-#### toBeTupla \[#toBeTupla]
-
-Afirma un valor de tupla.
-
-```ts
-expect(result).toBeTuple({
- enrollmentBlock: Cl.some(Cl.uint(1)),
- contributionAmount: Cl.some(Cl.uint(19000000))
-});
-```
-
-### Comprobación de tipos \[#type-checking]
-
-#### toTenerTipoDeClarity \[#toTenerTipoDeClarity]
-
-Comprueba que un valor tiene el tipo de Clarity esperado.
-
-```ts
-expect(result).toHaveClarityType(ClarityType.ResponseOk);
-```
-
-### Comparadores de eventos \[#event-matchers]
-
-#### toContainEqual \[#toContainEqual]
-
-Afirma que un array de eventos contiene un evento específico. Esto es útil para verificar eventos de transacciones.
-
-```ts
-// STX transfer event
-expect(events).toContainEqual({
- event: "stx_transfer_event",
- data: {
- amount: "1000000",
- memo: "",
- recipient: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM",
- sender: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5",
- },
-});
-
-// Fungible token transfer event
-expect(events).toContainEqual({
- event: "ft_transfer_event",
- data: {
- amount: "1000",
- asset_identifier: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.token::my-token",
- recipient: recipientAddress,
- sender: senderAddress,
- },
-});
-
-// NFT transfer event
-expect(events).toContainEqual({
- event: "nft_transfer_event",
- data: {
- asset_identifier: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.nft::my-nft",
- value: Cl.serialize(Cl.uint(1)),
- recipient: newOwner,
- sender: previousOwner,
- },
-});
-
-// Print event
-expect(events).toContainEqual({
- event: "print_event",
- data: {
- contract_id: `${deployer}.my-contract`,
- value: Cl.serialize(Cl.tuple({ message: Cl.stringAscii("Hello") })),
- },
-});
-
-// Check only specific properties with objectContaining
-expect(events).toContainEqual({
- event: "stx_transfer_event",
- data: expect.objectContaining({
- sender: senderAddress,
- recipient: recipientAddress,
- }),
-});
-```
diff --git a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/unit-testing.mdx b/content/docs/es/tools/clarinet/(clarinet-js-sdk)/unit-testing.mdx
deleted file mode 100644
index 212b86f78..000000000
--- a/content/docs/es/tools/clarinet/(clarinet-js-sdk)/unit-testing.mdx
+++ /dev/null
@@ -1,217 +0,0 @@
----
-title: Escribiendo pruebas unitarias
-sidebarTitle: Pruebas unitarias
-description: El testing unitario es el proceso de probar componentes o funciones individuales de contratos inteligentes para asegurar que funcionen como se espera. El SDK de Clarinet JS proporciona un marco de pruebas que te permite escribir estas pruebas utilizando el framework de testing Vitest, ayudándote a detectar errores y fallos temprano en el proceso de desarrollo.
----
-import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
-
-import { ArrowRight, Check } from 'lucide-react';
-
-## Lo que aprenderás
-
-:::objectives
-* Configurar un proyecto de Clarinet para pruebas unitarias
-* Escribir pruebas unitarias para funciones públicas y de solo lectura
-* Probar condiciones de error y casos límite
-* Ejecutar pruebas y generar informes de cobertura
-:::
-
-## Configura tu proyecto
-
-Comience creando un nuevo proyecto con la CLI de Clarinet. Este comando crea una estructura de proyecto con los archivos y carpetas necesarios, incluyendo el SDK JS de Clarinet ya configurado para pruebas:
-
-```terminal
-$ clarinet new stx-defi
-$ cd stx-defi
-```
-
-Después de cambiar al directorio de su proyecto, instale las dependencias del paquete:
-
-```terminal
-$ npm install
-```
-
-## Crear el contrato
-
-Generar un nuevo archivo de contrato utilizando la CLI de Clarinet:
-
-```terminal
-$ clarinet contract new defi
-```
-
-Reemplace el contenido de `contracts/defi.clar` con este contrato DeFi:
-
-```clarity contracts/defi.clar
-;; Holds the total amount of deposits in the contract
-(define-data-var total-deposits uint u0)
-
-;; Maps a user's principal address to their deposited amount
-(define-map deposits { owner: principal } { amount: uint })
-
-;; Public function for users to deposit STX into the contract
-(define-public (deposit (amount uint))
- (let
- (
- ;; Fetch the current balance or default to 0 if none exists
- (current-balance (default-to u0 (get amount (map-get? deposits { owner: tx-sender }))))
- )
- ;; Transfer the STX from sender to contract
- (try! (stx-transfer? amount tx-sender (as-contract tx-sender)))
- ;; Update the user's deposit amount in the map
- (map-set deposits { owner: tx-sender } { amount: (+ current-balance amount) })
- ;; Update the total deposits variable
- (var-set total-deposits (+ (var-get total-deposits) amount))
- ;; Return success
- (ok true)
- )
-)
-
-;; Read-only function to get the balance by tx-sender
-(define-read-only (get-balance-by-sender)
- (ok (map-get? deposits { owner: tx-sender }))
-)
-```
-
-Correr `clarinet check` para garantizar que su contrato sea válido:
-
-```terminal
-$ clarinet check
-[32m✔ 1 contract checked[0m
-```
-
-## Escriba su prueba unitaria
-
-Las pruebas clave que queremos cubrir son que el depósito sea exitoso y que el saldo del usuario, así como los depósitos totales del contrato, se actualicen correctamente.
-
-Reemplace el contenido de `tests/defi.test.ts`:
-
-```typescript tests/defi.test.ts
-import { describe, it, expect } from 'vitest';
-import { Cl } from '@stacks/transactions';
-
-const accounts = simnet.getAccounts();
-const wallet1 = accounts.get('wallet_1')!;
-
-describe('stx-defi', () => {
- it('allows users to deposit STX', () => {
- // Define the amount to deposit
- const amount = 1000;
-
- // Call the deposit function
- const deposit = simnet.callPublicFn('defi', 'deposit', [Cl.uint(amount)], wallet1);
-
- // Assert the deposit was successful
- expect(deposit.result).toBeOk(Cl.bool(true));
-
- // Verify the contract's total deposits
- const totalDeposits = simnet.getDataVar('defi', 'total-deposits');
- expect(totalDeposits).toBeUint(amount);
-
- // Check the user's balance
- const balance = simnet.callReadOnlyFn('defi', 'get-balance-by-sender', [], wallet1);
- expect(balance.result).toBeOk(
- Cl.some(
- Cl.tuple({
- amount: Cl.uint(amount),
- })
- )
- );
- });
-});
-```
-
-Analicemos las partes clave de esta prueba:
-
-* **`simnet.callPublicFn`** - Llama a una función pública en tu contrato
-* **`expect().toBeOk()`** - Comparador personalizado que verifica la claridad `ok` respuesta
-* **`simnet.getDataVar`** - Recupera el valor de una variable de datos
-* **`Cl` ayudantes** - Crear valores de Clarity en JavaScript
-
-## Pruébalo
-
-Ejecuta tu prueba para verla en acción:
-
-```terminal
-$ npm run test
- PASS tests/defi.test.ts
- stx-defi
- allows users to deposit STX (5 ms)
-
-Test Files 1 passed (1)
- Tests 1 passed (1)
-```
-
-## Problemas comunes
-
-| Problema | Solución |
-|----------|----------|
-| `toBeOk is not a function` | Asegúrese de estar utilizando los comparadores personalizados del SDK |
-| `Contract not found` | Correr `clarinet check` para validar su contrato |
-| `Type errors` | Utilice el `Cl` ayudantes para crear valores de Clarity adecuados |
-
-
-
- Generar informes de cobertura
-
-
-
- Ejecutar pruebas con cobertura para identificar código no probado:
-
- ```terminal
- $ npm run test:report
- ```
-
- Esto genera:
-
- * `lcov.info` - Datos de cobertura de código
- * `costs-reports.json` - Análisis de costo de gas
-
- Para ver el informe de cobertura:
-
- ```terminal
- $ brew install lcov
- $ genhtml lcov.info --branch-coverage -o coverage
- $ open coverage/index.html
- ```
-
-
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Pruebas de integración](/tools/clarinet/integration-testing): Aprende cómo probar tu contrato con pruebas de integración.
-* [Simulación de ejecución de la red principal](/tools/clarinet/mainnet-execution-simulation): Aprende cómo probar tu contrato con el estado de la red principal.
-:::
diff --git a/content/docs/es/tools/clarinet/(integrations)/chainhook-integration.mdx b/content/docs/es/tools/clarinet/(integrations)/chainhook-integration.mdx
deleted file mode 100644
index 534192999..000000000
--- a/content/docs/es/tools/clarinet/(integrations)/chainhook-integration.mdx
+++ /dev/null
@@ -1,164 +0,0 @@
----
-title: Registrar Chainhooks en devnet
-sidebarTitle: Integración de Chainhook
-description: En esta guía, aprenderás cómo registrar Chainhooks en devnet para monitorear y reaccionar a eventos de contratos inteligentes durante el desarrollo local.
----
-## Lo que aprenderás
-
-:::objectives
-* Crear archivos de predicado Chainhook para monitoreo de eventos
-* Registrar Chainhooks con Clarinet devnet
-* Monitorear llamadas de contrato y eventos de blockchain
-* Configurar webhooks para notificaciones en tiempo real
-:::
-
-## Requisitos previos
-
-:::prerequisites
-* Se requiere Clarinet versión 2.1.0 o superior. Verificar con `clarinet --version`.
-* Se requiere Node.js versión 16 o superior. Verifique con `node --version`.
-:::
-
-## Inicio rápido
-
-
-
- ### Crea tus predicados de Chainhook
-
- Crea archivos de predicado Chainhook en la raíz de tu proyecto o en una carpeta dedicada:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Ejemplo de predicado para monitorear eventos de incremento:
-
- ```json chainhooks/increment.json
- {
- "chain": "stacks",
- "uuid": "increment-hook",
- "name": "Increment Counter Hook",
- "version": 1,
- "networks": {
- "devnet": {
- "if_this": {
- "scope": "contract_call",
- "contract_identifier": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter",
- "method": "increment"
- },
- "then_that": {
- "http_post": {
- "url": "http://localhost:3000/api/increment",
- "authorization_header": "Bearer my-secret"
- }
- }
- }
- }
- }
- ```
-
-
-
- ### Iniciar devnet con Chainhooks
-
- Inicie devnet desde la raíz de su proyecto. Clarinet registra automáticamente todos los archivos Chainhook:
-
- ```terminal
- $ clarinet devnet start
- ```
-
- Busque la confirmación de registro:
-
- ```terminal
- $ clarinet devnet start
- # ...
- INFO Feb 5 15:20:07.233382 2 chainhooks registered
- ```
-
-
-
- ### Monitorear la actividad de Chainhook
-
- Cuando se producen acciones de contrato, verás los disparadores de Chainhook en la terminal:
-
- ```terminal
- $ clarinet devnet start
- # ...
- INFO Feb 5 15:21:07.233382 1 hooks triggered
- ```
-
- Verifique la carga útil según su `then_that` configuration:
-
- * **`http_post`** - Verifica que tu endpoint haya recibido la solicitud POST
- * **`file_append`** - Verificar que el archivo fue creado/actualizado
-
-
-
-## Patrones comunes
-
-### Gancho de despliegue de contrato
-
-Monitorear cuándo se implementan contratos específicos:
-
-```json chainhooks/deploy-monitor.json
-{
- "chain": "stacks",
- "uuid": "deploy-hook",
- "name": "Contract Deploy Monitor",
- "version": 1,
- "networks": {
- "devnet": {
- "if_this": {
- "scope": "contract_deployment",
- "deployer": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM"
- },
- "then_that": {
- "file_append": {
- "path": "./deployments.log"
- }
- }
- }
- }
-}
-```
-
-### Monitoreo de transferencias STX
-
-Rastrea las transferencias de STX por encima de un cierto umbral:
-
-```json chainhooks/stx-transfers.json
-{
- "chain": "stacks",
- "uuid": "stx-transfer-hook",
- "name": "Large STX Transfer Monitor",
- "version": 1,
- "networks": {
- "devnet": {
- "if_this": {
- "scope": "stx_event",
- "actions": ["transfer"],
- "amount_upper_bound": "1000000000000"
- },
- "then_that": {
- "http_post": {
- "url": "http://localhost:3000/api/large-transfer"
- }
- }
- }
- }
-}
-```
diff --git a/content/docs/es/tools/clarinet/(integrations)/pyth-oracle-integration.mdx b/content/docs/es/tools/clarinet/(integrations)/pyth-oracle-integration.mdx
deleted file mode 100644
index fe9af5ba8..000000000
--- a/content/docs/es/tools/clarinet/(integrations)/pyth-oracle-integration.mdx
+++ /dev/null
@@ -1,378 +0,0 @@
----
-title: Integración del oráculo Pyth
-sidebarTitle: Integración del oráculo Pyth
-description: Aprende cómo probar contratos inteligentes que dependen de los feeds de precios del oráculo Pyth utilizando Clarinet.
----
-## Lo que aprenderás
-
-:::objectives
-* Configurar las dependencias del contrato de mainnet
-* Utilizar la ejecución de transacciones de mainnet (MXS) para pruebas de oráculos
-* Crear feeds de precios simulados para pruebas unitarias
-* Escribir pruebas de integración con datos reales de oracle
-:::
-
-## Requisitos previos
-
-:::prerequisites
-* Versión 2.1.0 o superior de Clarinet con soporte MXS
-* Comprensión de [Contratos de oráculo de Pyth](/resources/clarity/external-data)
-:::
-
-## Inicio rápido
-
-
-
- ### Configurar dependencias de mainnet
-
- Agregue los contratos de oráculo Pyth a sus requisitos de Clarinet.toml:
-
- ```toml Clarinet.toml
- [project]
- name = "my-oracle-project"
-
- [[project.requirements]]
- contract_id = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-oracle-v3"
-
- [[project.requirements]]
- contract_id = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3"
-
- [[project.requirements]]
- contract_id = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-pnau-decoder-v2"
-
- [[project.requirements]]
- contract_id = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.wormhole-core-v3"
- ```
-
- Esto permite que tus pruebas interactúen con los contratos de oráculo reales de la red principal.
-
-
-
- ### Crear un oráculo simulado para pruebas unitarias
-
- Para pruebas unitarias rápidas, cree un contrato de oráculo simulado:
-
- ```clarity tests/mocks/mock-pyth-oracle.clar
- ;; Mock Pyth Oracle for testing
- (define-map price-feeds
- (buff 32) ;; price-feed-id
- {
- price: int,
- conf: uint,
- expo: int,
- ema-price: int,
- ema-conf: uint,
- publish-time: uint,
- prev-publish-time: uint
- }
- )
-
- ;; Set a mock price
- (define-public (set-mock-price
- (feed-id (buff 32))
- (price int)
- (expo int))
- (ok (map-set price-feeds feed-id {
- price: price,
- conf: u1000000,
- expo: expo,
- ema-price: price,
- ema-conf: u1000000,
- publish-time: block-height,
- prev-publish-time: (- block-height u1)
- }))
- )
-
- ;; Mock get-price function matching real oracle interface
- (define-read-only (get-price
- (feed-id (buff 32))
- (storage-contract principal))
- (ok (unwrap!
- (map-get? price-feeds feed-id)
- (err u404)))
- )
-
- ;; Mock verify-and-update-price-feeds (no-op for testing)
- (define-public (verify-and-update-price-feeds
- (vaa (buff 8192))
- (params (tuple)))
- (ok u1)
- )
- ```
-
-
-
- ### Escribir pruebas unitarias con precios simulados
-
- Crear pruebas unitarias utilizando el oráculo simulado:
-
- ```typescript tests/benjamin-club.test.ts
- import { Cl } from '@stacks/transactions';
- import { describe, expect, it } from "vitest";
-
- const accounts = simnet.getAccounts();
- const deployer = accounts.get("deployer")!;
- const wallet1 = accounts.get("wallet_1")!;
-
- describe("Benjamin Club with Mock Oracle", () => {
- it("should set up mock BTC price", () => {
- // Set BTC price to $100,000 (with 8 decimals)
- const btcFeedId = "0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43";
- const mockPrice = Cl.int(10000000000000); // $100,000.00 * 10^8
- const expo = Cl.int(-8);
-
- const setPriceResponse = simnet.callPublicFn(
- "mock-pyth-oracle",
- "set-mock-price",
- [Cl.bufferFromHex(btcFeedId), mockPrice, expo],
- deployer
- );
-
- expect(setPriceResponse.result).toBeOk(Cl.uint(1));
- });
-
- it("should calculate correct sBTC amount for $100", () => {
- // With BTC at $100,000, $100 = 0.001 BTC
- const response = simnet.callReadOnlyFn(
- "benjamin-club",
- "get-required-sbtc-amount",
- [],
- wallet1
- );
-
- // 0.001 BTC = 100,000 sats
- expect(response.result).toBeOk(Cl.uint(100000));
- });
-
- it("should mint NFT when user has enough sBTC", () => {
- // Mock VAA data (can be dummy data for unit tests)
- const mockVaa = Cl.bufferFromHex("00".repeat(100));
-
- // Give user 1 BTC worth of sBTC
- simnet.callPublicFn(
- "sbtc-token",
- "mint",
- [Cl.uint(100000000), Cl.principal(wallet1)],
- deployer
- );
-
- const mintResponse = simnet.callPublicFn(
- "benjamin-club",
- "mint-for-hundred-dollars",
- [mockVaa],
- wallet1
- );
-
- expect(mintResponse.result).toBeOk(Cl.uint(1));
- });
- });
- ```
-
-
-
- ### Configurar pruebas de ejecución de mainnet
-
- Para pruebas de integración con datos reales de oracle, utilice la ejecución de transacciones de mainnet:
-
- ```typescript tests/benjamin-club-mxs.test.ts
- import { buildDevnetNetworkOrchestrator } from "@hirosystems/clarinet-sdk";
- import { Cl } from '@stacks/transactions';
- import { PriceServiceConnection } from '@pythnetwork/price-service-client';
- import { describe, expect, it } from "vitest";
-
- describe("Benjamin Club with Mainnet Oracle", () => {
- let orchestrator: any;
-
- beforeAll(async () => {
- orchestrator = buildDevnetNetworkOrchestrator({
- // Point to a mainnet fork
- manifest: "./Clarinet.toml",
- networkId: 1 // Mainnet
- });
- });
-
- it("should interact with real Pyth oracle", async () => {
- // Fetch real VAA from Pyth
- const pythClient = new PriceServiceConnection(
- "https://hermes.pyth.network",
- { priceFeedRequestConfig: { binary: true } }
- );
-
- const btcFeedId = "e62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43";
- const vaas = await pythClient.getLatestVaas([btcFeedId]);
- const vaaHex = Buffer.from(vaas[0], 'base64').toString('hex');
-
- // Use mainnet execution to test with real oracle
- const response = await orchestrator.callPublicFn(
- "benjamin-club",
- "get-current-btc-price",
- [Cl.bufferFromHex(vaaHex)],
- "wallet_1"
- );
-
- expect(response.result).toBeOk();
-
- // Verify price is reasonable (between $10k and $200k)
- const priceData = response.result.value;
- const price = priceData.data.price.value;
- expect(price).toBeGreaterThan(1000000000000); // $10k
- expect(price).toBeLessThan(20000000000000); // $200k
- });
- });
- ```
-
-
-
-## Patrones comunes
-
-### Probando diferentes escenarios de precios
-
-Crear funciones auxiliares para probar diversas condiciones del mercado:
-
-```typescript tests/helpers/oracle-helpers.ts
-export function setupPriceScenario(
- scenario: 'bull' | 'bear' | 'stable',
- simnet: any
-) {
- const prices = {
- bull: {
- btc: 15000000000000, // $150,000
- stx: 500000000, // $5.00
- eth: 500000000000 // $5,000
- },
- bear: {
- btc: 2000000000000, // $20,000
- stx: 50000000, // $0.50
- eth: 100000000000 // $1,000
- },
- stable: {
- btc: 10000000000000, // $100,000
- stx: 200000000, // $2.00
- eth: 300000000000 // $3,000
- }
- };
-
- const selectedPrices = prices[scenario];
-
- // Set up all price feeds
- Object.entries(selectedPrices).forEach(([asset, price]) => {
- const feedId = getFeedId(asset);
- simnet.callPublicFn(
- "mock-pyth-oracle",
- "set-mock-price",
- [Cl.bufferFromHex(feedId), Cl.int(price), Cl.int(-8)],
- "deployer"
- );
- });
-}
-```
-
-### Probando la obsolescencia de precios
-
-Asegúrate de que tu contrato maneje correctamente los precios obsoletos:
-
-```typescript tests/price-staleness.test.ts
-describe("Price Staleness Handling", () => {
- it("should reject stale prices", () => {
- // Set a price with old timestamp
- const oldTimestamp = simnet.getBlockHeight() - 1000;
-
- simnet.callPublicFn(
- "mock-pyth-oracle",
- "set-price-with-timestamp",
- [
- Cl.bufferFromHex(BTC_FEED_ID),
- Cl.int(10000000000000),
- Cl.int(-8),
- Cl.uint(oldTimestamp)
- ],
- deployer
- );
-
- const response = simnet.callPublicFn(
- "benjamin-club",
- "mint-for-hundred-dollars",
- [mockVaa],
- wallet1
- );
-
- expect(response.result).toBeErr(Cl.uint(ERR_STALE_PRICE));
- });
-});
-```
-
-### Pruebas de implementación
-
-Crear pruebas de implementación para garantizar una configuración adecuada:
-
-```toml deployments/mainnet.yaml
----
-id: 0
-name: "Mainnet deployment"
-network: mainnet
-stacks-node: "https://api.mainnet.hiro.so"
-bitcoin-node: "https://blockstream.info/api/"
-plan:
- batches:
- - id: 0
- transactions:
- - contract-call:
- contract-id: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRCBGD7R.benjamin-club
- method: initialize
- parameters:
- - "'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-oracle-v3"
- - "'SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3"
-```
-
-### Estimación de gas
-
-Probar el consumo de gas para operaciones de oráculo:
-
-```typescript tests/gas-estimation.test.ts
-describe("Gas Estimation", () => {
- it("should estimate gas for oracle update + mint", () => {
- const txCost = simnet.getTransactionCost(
- "benjamin-club",
- "mint-for-hundred-dollars",
- [Cl.bufferFromHex("00".repeat(1000))], // Typical VAA size
- wallet1
- );
-
- console.log("Estimated gas cost:", txCost);
-
- // Ensure gas cost is reasonable
- expect(txCost.write_length).toBeLessThan(20000);
- expect(txCost.runtime).toBeLessThan(50000000);
- });
-});
-```
-
-## Integración de CI/CD
-
-Configurar GitHub Actions para pruebas automatizadas:
-
-```yaml .github/workflows/test-oracle.yml
-name: Test Oracle Integration
-
-on: [push, pull_request]
-
-jobs:
- test:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v3
-
- - name: Install Clarinet
- run: |
- curl -L https://github.com/hirosystems/clarinet/releases/download/v2.1.0/clarinet-linux-x64.tar.gz | tar xz
- chmod +x ./clarinet
- sudo mv ./clarinet /usr/local/bin
-
- - name: Run unit tests
- run: clarinet test --coverage
-
- - name: Run mainnet fork tests
- run: clarinet test --mainnet-fork
- env:
- MAINNET_API_KEY: ${{ secrets.MAINNET_API_KEY }}
-```
diff --git a/content/docs/es/tools/clarinet/(integrations)/sbtc-integration.mdx b/content/docs/es/tools/clarinet/(integrations)/sbtc-integration.mdx
deleted file mode 100644
index ec9e7db6b..000000000
--- a/content/docs/es/tools/clarinet/(integrations)/sbtc-integration.mdx
+++ /dev/null
@@ -1,270 +0,0 @@
----
-title: Integración de sBTC con Clarinet
-sidebarTitle: Integración de sBTC
-description: En esta guía, aprenderás cómo interactuar con el contrato sBTC de la red principal en tu proyecto de Clarinet.
----
-## Lo que aprenderás
-
-:::objectives
-* Agregar contratos inteligentes de sBTC a su proyecto de Clarinet
-* Probar contratos con financiación automática de sBTC en devnet
-* Trabajar con sBTC como un token fungible SIP-010
-* Desplegar contratos de sBTC en testnet y mainnet
-:::
-
-## Requisitos previos
-
-:::prerequisites
-* Se requiere Clarinet 2.15.0 o posterior para la integración automática de sBTC.
-:::
-
-## Inicio rápido
-
-
-
- ### Añade sBTC a tu proyecto
-
- Agregue los contratos inteligentes de sBTC a los requisitos de su proyecto Clarinet:
-
- ```terminal
- $ clarinet requirements add SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-deposit
- ```
-
- Este comando agrega tres contratos esenciales:
-
- * **`sbtc-token`** - El contrato de token SIP-010 principal
- * **`sbtc-registry`** - Registro para gestionar la configuración de sBTC
- * **`sbtc-deposit`** - Maneja operaciones de depósito y retiro
-
- Cuando Clarinet detecta estos contratos, automáticamente financia sus billeteras de prueba con sBTC para realizar pruebas.
-
-
-
- ### Crear un contrato habilitado para sBTC
-
- Construye un mercado simple de NFT que acepte pagos en sBTC:
-
- ```clarity contracts/nft-marketplace.clar
- ;; Define NFT
- (define-non-fungible-token marketplace-nft uint)
-
- ;; Price in sats (smallest sBTC unit)
- (define-data-var mint-price uint u100)
- (define-data-var next-id uint u0)
-
- ;; Mint NFT with sBTC payment
- (define-public (mint-with-sbtc)
- (begin
- ;; Transfer sBTC from buyer to contract
- (try! (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token transfer
- (var-get mint-price)
- tx-sender
- (as-contract tx-sender)
- none
- ))
-
- ;; Mint the NFT
- (try! (nft-mint? marketplace-nft (var-get next-id) tx-sender))
-
- ;; Increment ID for next mint
- (ok (var-set next-id (+ (var-get next-id) u1)))
- )
- )
-
- ;; Check sBTC balance
- (define-read-only (get-sbtc-balance (owner principal))
- (contract-call? 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token get-balance owner)
- )
- ```
-
-
-
- ### Probar en la consola de Clarinet
-
- Clarinet financia automáticamente las billeteras de prueba con sBTC. Prueba tu contrato:
-
- ```terminal
- $ clarinet console
- ```
-
- Verifique los saldos de la billetera y acuñe un NFT:
-
- ```clarity
- ;; Check deployer's sBTC balance (auto-funded)
- (contract-call? .nft-marketplace get-sbtc-balance tx-sender)
-
- ;; Mint NFT with wallet_1 (also auto-funded)
- (contract-call? .nft-marketplace mint-with-sbtc)
-
- ;; Verify NFT ownership
- (nft-get-owner? .nft-marketplace marketplace-nft u0)
- ```
-
-
-
- ### Escribir pruebas unitarias
-
- Prueba la funcionalidad de sBTC en tus pruebas de TypeScript:
-
- ```ts tests/nft-marketplace.test.ts
- import { describe, expect, it } from "vitest";
- import { Cl } from "@stacks/transactions";
-
- describe("NFT Marketplace", () => {
- it("mints NFT with sBTC payment", () => {
- const mintPrice = 100;
-
- // Get initial sBTC balance
- const initialBalance = simnet.callReadOnlyFn(
- "nft-marketplace",
- "get-sbtc-balance",
- [Cl.standardPrincipal(accounts.get("wallet_1")!.address)],
- accounts.get("wallet_1")!.address
- );
-
- // Mint NFT
- const mintResult = simnet.callPublicFn(
- "nft-marketplace",
- "mint-with-sbtc",
- [],
- accounts.get("wallet_1")!.address
- );
-
- expect(mintResult.result).toBeOk();
-
- // Verify sBTC was transferred
- const finalBalance = simnet.callReadOnlyFn(
- "nft-marketplace",
- "get-sbtc-balance",
- [Cl.standardPrincipal(accounts.get("wallet_1")!.address)],
- accounts.get("wallet_1")!.address
- );
-
- expect(Number(Cl.parse(finalBalance.result))).toBeLessThan(
- Number(Cl.parse(initialBalance.result))
- );
- });
- });
- ```
-
-
-
- ### Desplegar en testnet
-
- En la red de pruebas, Clarinet automáticamente se reasigna a los contratos oficiales de sBTC de Hiro:
-
- ```terminal
- $ clarinet deployments generate --testnet
- ```
-
- Su plan de implementación muestra las direcciones reasignadas:
-
- ```yaml deployments/default.testnet-plan.yaml
- ---
- id: 0
- name: Testnet deployment
- network: testnet
- stacks-node: "https://api.testnet.hiro.so"
- bitcoin-node: "http://blockstream.info"
- plan:
- batches:
- - id: 0
- transactions:
- - requirement-publish:
- contract-id: ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-token
- remap-sender: SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4
- remap-principals:
- SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4: ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT
- cost: 50000
- path: "./.cache/requirements/SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token.clar"
- ```
-
- Desplegar en testnet:
-
- ```terminal
- $ clarinet deployments apply -p deployments/default.testnet-plan.yaml
- ```
-
-
-
-## Patrones comunes
-
-## Trabajando con direcciones sBTC
-
-Clarinet maneja el mapeo de direcciones de contratos sBTC a través de las redes:
-
-| Red | Dirección del Contrato sBTC |
-|---------|---------------------|
-| Simnet/Devnet | `SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token` |
-| Red de pruebas | `ST1F7QA2MDF17S807EPA36TSS8AMEFY4KA9TVGWXT.sbtc-token` |
-| Mainnet | La dirección del contrato permanece sin cambios |
-
-Su código de contrato siempre hace referencia a la dirección de simnet. Clarinet automáticamente reasigna durante el despliegue.
-
-## Minting manual de sBTC en pruebas unitarias
-
-Aunque Clarinet 2.15.0+ financia automáticamente las billeteras con sBTC en devnet, es posible que necesite acuñar manualmente sBTC en pruebas unitarias para escenarios específicos:
-
-### Acuñando sBTC utilizando la dirección del implementador
-
-El contrato de token sBTC permite que la dirección del implementador (multisig) acuñe tokens. Utiliza este enfoque en tus pruebas:
-
-```typescript tests/manual-sbtc-mint.test.ts -c
-import { describe, expect, it } from "vitest";
-import { Cl } from "@stacks/transactions";
-
-describe("Manual sBTC minting", () => {
- it("mints sBTC to custom addresses", () => {
- // The sBTC multisig address that can mint
- const sbtcDeployer = "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4";
- const customWallet = "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM";
-
- // Mint 1000 sats to custom wallet
- const mintResult = simnet.callPublicFn(
- "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
- "mint",
- [
- Cl.uint(1000), // amount in sats
- Cl.principal(customWallet) // recipient
- ],
- sbtcDeployer // sender must be deployer
- );
-
- expect(mintResult.result).toBeOk(Cl.bool(true));
-
- // Verify balance
- const balance = simnet.callReadOnlyFn(
- "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
- "get-balance",
- [Cl.principal(customWallet)],
- customWallet
- );
-
- expect(balance.result).toBeOk(Cl.uint(1000));
- });
-});
-```
-
-### Pruebas con simulación de ejecución en la red principal
-
-Cuando se utiliza la simulación de ejecución en la red principal, se puede acuñar sBTC utilizando la multifirma real de la red principal:
-
-```typescript -c
-const mainnetMultisig = "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4";
-const mainnetWallet = "SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR";
-
-// Mint sBTC to any mainnet address
-simnet.callPublicFn(
- "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
- "mint",
- [Cl.uint(100000), Cl.principal(mainnetWallet)],
- mainnetMultisig
-);
-```
-
-Este enfoque es útil para:
-
-* Probando cantidades específicas de sBTC
-* Simulando diferentes saldos de billetera
-* Probando casos límite con cantidades de tokens precisas
-* Pruebas de integración con contratos de mainnet
diff --git a/content/docs/es/tools/clarinet/(integrations)/stacks-js-integration.mdx b/content/docs/es/tools/clarinet/(integrations)/stacks-js-integration.mdx
deleted file mode 100644
index b61bf4aba..000000000
--- a/content/docs/es/tools/clarinet/(integrations)/stacks-js-integration.mdx
+++ /dev/null
@@ -1,245 +0,0 @@
----
-title: Integración de Stacks.js con devnet
-sidebarTitle: Integración de Stacks.js
-description: En esta guía, aprenderás cómo interactuar con tus contratos inteligentes en devnet utilizando las bibliotecas de Stacks.js.
----
-## Lo que aprenderás
-
-:::objectives
-* Configurar Stacks.js para conexión a devnet local
-* Realizar transferencias STX entre cuentas de devnet
-* Llamar a funciones de contratos inteligentes desde JavaScript
-* Implementar contratos de forma programática
-:::
-
-## Inicio rápido
-
-
-
- ### Instalar paquetes de Stacks.js
-
- Agregue los paquetes requeridos de Stacks.js a su proyecto frontend:
-
- ```package-install
- @stacks/transactions @stacks/network
- ```
-
-
-
- ### Configurar para devnet
-
- Configurar una configuración de red devnet:
-
- ```ts devnet-config.ts
- import { StacksDevnet } from '@stacks/network';
-
- // Configure for local devnet
- export const devnet = new StacksDevnet({
- url: 'http://localhost:3999'
- });
-
- // Get devnet accounts (matches Clarinet wallets)
- export const accounts = {
- deployer: {
- address: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM',
- key: 'cb3df38053d132895220b9ce471f6b676db5b9bf0b4adefb55f2118ece2478df01'
- },
- wallet1: {
- address: 'ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5',
- key: '7287ba251d44a4d3fd9276c88ce34c5c52a038955511cccaf77e61068649c17801'
- }
- };
- ```
-
-
-
- ### Prueba de transferencias STX
-
- Cree una transferencia STX simple entre cuentas de devnet:
-
- ```ts stx-transfer.ts
- import { makeSTXTokenTransfer, broadcastTransaction, AnchorMode } from '@stacks/transactions';
- import { devnet, accounts } from './devnet-config';
-
- async function transferSTX() {
- const tx = await makeSTXTokenTransfer({
- amount: 1000000n, // 1 STX in microSTX
- recipient: accounts.wallet1.address,
- senderKey: accounts.deployer.key,
- network: devnet,
- anchorMode: AnchorMode.Any,
- });
-
- const result = await broadcastTransaction(tx, devnet);
- console.log('Transaction ID:', result.txid);
-
- // Transaction will be mined in next devnet block
- return result.txid;
- }
-
- transferSTX().catch(console.error);
- ```
-
- Ejecute la transferencia:
-
- ```terminal
- $ ts-node stx-transfer.ts
- Transaction ID: 0x3d5f8a70c4821e0f8c985b1f5b9d77f8c4b6d1a2e7f9c3b8a4d5e6f1c8d9b7a3
- ```
-
-
-
- ### Llamar a contratos inteligentes
-
- Interactúa con contratos implementados en devnet:
-
- ```ts contract-call.ts
- import { makeContractCall, broadcastTransaction, AnchorMode, Cl } from '@stacks/transactions';
- import { devnet, accounts } from './devnet-config';
-
- async function callContract() {
- const tx = await makeContractCall({
- contractAddress: accounts.deployer.address,
- contractName: 'counter',
- functionName: 'increment',
- functionArgs: [],
- senderKey: accounts.wallet1.key,
- network: devnet,
- anchorMode: AnchorMode.Any,
- });
-
- const result = await broadcastTransaction(tx, devnet);
- console.log('Contract call ID:', result.txid);
-
- return result.txid;
- }
-
- // Read contract state
- async function readCount() {
- const response = await fetch(
- `${devnet.coreApiUrl}/v2/contracts/call-read/${accounts.deployer.address}/counter/get-count`,
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- sender: accounts.wallet1.address,
- arguments: []
- })
- }
- );
-
- const data = await response.json();
- console.log('Current count:', data.result);
- }
-
- callContract()
- .then(() => readCount())
- .catch(console.error);
- ```
-
-
-
- ### Desplegar contratos desde el frontend
-
- Desplegar nuevos contratos en devnet de forma programática:
-
- ```ts deploy-contract.ts
- import { makeContractDeploy, broadcastTransaction, AnchorMode } from '@stacks/transactions';
- import { devnet, accounts } from './devnet-config';
-
- async function deployContract() {
- const contractCode = `
- (define-data-var count uint u0)
-
- (define-public (increment)
- (ok (var-set count (+ (var-get count) u1)))
- )
-
- (define-read-only (get-count)
- (var-get count)
- )
- `;
-
- const tx = await makeContractDeploy({
- contractName: 'my-counter',
- codeBody: contractCode,
- senderKey: accounts.deployer.key,
- network: devnet,
- anchorMode: AnchorMode.Any,
- });
-
- const result = await broadcastTransaction(tx, devnet);
- console.log('Contract deployed:', result.txid);
-
- return result.txid;
- }
-
- deployContract().catch(console.error);
- ```
-
-
-
-## Patrones comunes
-
-### Esperando la confirmación de la transacción
-
-Monitorear cuándo se confirman las transacciones en devnet:
-
-```ts transaction-monitor.ts
-async function waitForTransaction(txid: string) {
- let attempts = 0;
- const maxAttempts = 10;
-
- while (attempts < maxAttempts) {
- const response = await fetch(
- `${devnet.coreApiUrl}/extended/v1/tx/${txid}`
- );
-
- const tx = await response.json();
-
- if (tx.tx_status === 'success') {
- console.log('Transaction confirmed!');
- return tx;
- }
-
- if (tx.tx_status === 'abort_by_response') {
- throw new Error(`Transaction failed: ${tx.tx_result.repr}`);
- }
-
- // Wait for next block
- await new Promise(resolve => setTimeout(resolve, 5000));
- attempts++;
- }
-
- throw new Error('Transaction timeout');
-}
-```
-
-### Condiciones posteriores para la seguridad
-
-Agregar condiciones posteriores para garantizar que las llamadas al contrato se comporten según lo esperado:
-
-```ts safe-transfer.ts
-import { Pc } from '@stacks/transactions';
-
-const postConditions = [
- // Ensure sender's balance decreases by exactly the amount
- Pc.principal(accounts.wallet1.address)
- .willSendEq(1000000n)
- .ustx(),
-
- // Ensure recipient receives the amount
- Pc.principal(accounts.deployer.address)
- .willReceiveEq(1000000n)
- .ustx()
-];
-
-const tx = await makeSTXTokenTransfer({
- amount: 1000000n,
- recipient: accounts.deployer.address,
- senderKey: accounts.wallet1.key,
- network: devnet,
- postConditions,
- anchorMode: AnchorMode.Any,
-});
-```
diff --git a/content/docs/es/tools/clarinet/(overview)/faq.mdx b/content/docs/es/tools/clarinet/(overview)/faq.mdx
deleted file mode 100644
index f8482a9ab..000000000
--- a/content/docs/es/tools/clarinet/(overview)/faq.mdx
+++ /dev/null
@@ -1,211 +0,0 @@
----
-title: Preguntas frecuentes
-sidebarTitle: Preguntas frecuentes
-description: Preguntas comunes y soluciones para el desarrollo de Clarinet
----
-Esta página aborda preguntas y problemas comunes encontrados al desarrollar con Clarinet, basados en comentarios de la comunidad e interacciones de soporte.
-
-## Pruebas y desarrollo
-
-
-
- ¿Cómo puedo probar con tokens sBTC en mi entorno de desarrollo?
-
-
-
- Para probar con tokens sBTC, añade el contrato sBTC de la red principal como requisito y acuña tokens usando la dirección del desplegador:
-
- **Paso 1: Agregar sBTC como requisito**
-
- ```terminal
- $ clarinet requirements add SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token
- ```
-
- **Paso 2: Acuñar sBTC en tus pruebas**
-
- ```typescript
- // The sBTC multisig address that can mint
- const sbtcDeployer = "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4";
-
- // Mint sBTC to your test wallet
- const mintTx = simnet.callPublicFn(
- "SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token",
- "mint",
- [Cl.uint(1000000), Cl.principal(wallet1)],
- sbtcDeployer
- );
- ```
-
- Este enfoque te permite trabajar con sBTC en pruebas unitarias sin una simulación compleja de transacciones de Bitcoin.
-
-
-
-
-
- ¿Por qué estoy recibiendo un error al usar direcciones de mainnet durante la simulación de mainnet?
-
-
-
- Al utilizar la simulación de ejecución en la red principal, es posible que el contrato de la red principal esté verificando las llamadas de contrato de direcciones de la red principal, no las direcciones de la red de prueba.
-
- **A partir de Clarinet v3.4.0**, puedes habilitar direcciones de mainnet en simnet agregando `use_mainnet_wallets = true` a tu configuración:
-
- ```toml Clarinet.toml
- [repl.remote_data]
- enabled = true
- initial_height = 522000
- use_mainnet_wallets = true # Enable mainnet addresses
- ```
-
- **Alternativa: Usar manualmente direcciones de mainnet:**
-
- ```typescript
- // Instead of using simnet.getAccounts()
- const mainnetAddress = "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY";
-
- // Mint STX to any mainnet address
- simnet.mintSTX(mainnetAddress, 1000000n);
-
- // Call functions with mainnet address
- const result = simnet.callReadOnlyFn(
- "SP3R4F6C1J3JQWWCVZ3S7FRRYPMYG6ZW6RZK31FXY.pyth-storage-v3",
- "get-price",
- [priceFeed],
- mainnetAddress
- );
- ```
-
- La simnet es permisiva y acepta cualquier dirección válida de Stacks cuando la simulación de mainnet está habilitada.
-
-
-
-
-
- ¿Cómo migro de expectSTXTransferEvent al nuevo SDK?
-
-
-
- El SDK de Clarinet v2 utiliza comparadores estándar de Vitest en lugar de ayudantes de eventos personalizados. Así es cómo migrar:
-
- **Enfoque antiguo (Clarinet v1):**
-
- ```typescript
- block.receipts[0].events.expectSTXTransferEvent(
- amount,
- sender,
- recipient
- );
- ```
-
- **Nuevo enfoque (Clarinet v2):**
-
- ```typescript
- // Check for exact event match
- expect(events).toContainEqual({
- event: "stx_transfer_event",
- data: {
- amount: "1000000",
- memo: "",
- recipient: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM",
- sender: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5",
- },
- });
-
- // Or check only specific properties
- expect(events).toContainEqual({
- event: "stx_transfer_event",
- data: expect.objectContaining({
- sender: address1,
- recipient: contractAddress,
- }),
- });
- ```
-
- Para las aserciones de valor de Clarity, utiliza los comparadores incorporados:
-
- ```typescript
- expect(result).toBeOk(Cl.bool(true));
- expect(result).toBeErr(Cl.uint(500));
- ```
-
-
-
-
-
-## Configuración e instalación
-
-
-
- ¿Por qué estoy recibiendo "error bip39" al generar planes de implementación?
-
-
-
- A partir de Clarinet 2.15.0, las configuraciones de implementación requieren mnemotécnicas de 24 palabras. Las mnemotécnicas de 12 palabras ya no son compatibles.
-
- **Actualice su configuración:**
-
- ```toml settings/Mainnet.toml
- [accounts.deployer]
- # Use a 24-word mnemonic
- mnemonic = "twice kind fence tip hidden tilt action fragile skin nothing glory cousin green tomorrow spring wrist shed math olympic multiply hip blue scout claw"
- ```
-
- Genere una nueva mnemotecnia de 24 palabras usando un generador BIP39 si es necesario. Este cambio mejora la seguridad para implementaciones en producción.
-
-
-
-
-
-## Limitaciones conocidas
-
-
-
- ¿Puedo probar la verificación de transacciones de Bitcoin en Clarinet?
-
-
-
- Probar contratos que utilizan clarity-bitcoin-lib para la verificación de transacciones de Bitcoin tiene limitaciones en simnet y devnet:
-
- **Limitaciones actuales:**
-
- * No hay bloques ni transacciones reales de Bitcoin en simnet
- * Los bloques simulados no contienen transacciones de Bitcoin verificables
- * `get-burn-block-info?` devuelve datos simulados no aptos para verificación
-
- **Soluciones alternativas:**
-
- * Probar la lógica de verificación de Bitcoin en la red principal o con simulación de ejecución de la red principal
- * Crear pruebas unitarias que simulen el comportamiento esperado sin verificación real
- * Considere separar la lógica de verificación de Bitcoin para facilitar las pruebas
-
- El equipo de Clarinet está explorando soluciones para un mejor soporte de pruebas de Bitcoin.
-
-
-
-
-
- ¿Por qué mi devnet se congela en la transición de la época 3.0?
-
-
-
- La transición de época 3.0 en devnet puede ser inestable, con tasas de éxito que varían entre el 50-80% dependiendo de tu configuración.
-
- **Soluciones temporales actuales:**
-
- * Reinicie devnet si se congela alrededor de los bloques 139-140
- * Prueba Clarinet 2.14.0, que algunos usuarios informan que es más estable
- * Espera a que la próxima función comience devnet directamente en la época 3.0
-
- **Monitoreando la transición:**
-
- ```console
- # Watch for the transition around these blocks
- Block 139: Epoch 2.5
- Block 140: Should transition to 3.0
- ```
-
- El equipo de Clarinet está trabajando en mejorar la estabilidad de la transición de época y planea permitir iniciar devnet directamente en la época 3.0.
-
-
-
-
diff --git a/content/docs/es/tools/clarinet/(overview)/project-structure.mdx b/content/docs/es/tools/clarinet/(overview)/project-structure.mdx
deleted file mode 100644
index d4331506e..000000000
--- a/content/docs/es/tools/clarinet/(overview)/project-structure.mdx
+++ /dev/null
@@ -1,291 +0,0 @@
----
-title: Estructura del proyecto
-sidebarTitle: Estructura del proyecto
-description: Comprender la estructura y configuración completa de un proyecto de Clarinet
-type: concept
----
-Un proyecto de Clarinet sigue una estructura cuidadosamente diseñada que separa contratos, pruebas y configuración. Comprender esta estructura te ayuda a organizar el código de manera efectiva y configurar herramientas para un flujo de trabajo de desarrollo óptimo.
-
-## Diseño del proyecto principal
-
-Cada proyecto de Clarinet contiene estos directorios y archivos esenciales:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Cada componente cumple un propósito específico en su flujo de trabajo de desarrollo. Exploremos cómo funcionan juntos para crear un entorno de desarrollo completo.
-
-## El manifiesto del proyecto
-
-### Clarinet.toml
-
-El **Clarinet.toml** file es el corazón de tu proyecto. Define los metadatos del proyecto y rastrea todos los contratos:
-
-```toml Clarinet.toml
-[project]
-name = "counter"
-description = "A counter smart contract"
-
-[contracts.traits]
-path = "contracts/traits.clar"
-clarity_version = 3
-epoch = "latest"
-
-[contracts.counter]
-path = 'contracts/counter.clar'
-clarity_version = 3
-epoch = "latest"
-```
-
-El manifiesto maneja varias funciones críticas:
-
-* **Registro de contrato**: Todo contrato debe estar listado aquí
-* **Época de Stacks y versión de Clarity**: Especifica la versión de Clarity y la época para cada contrato
-* **Secuencia de arranque**: Enumera los contratos a desplegar `clarinet devnet start`
-
-### Configuración de época
-
-Puedes especificar la época de dos maneras:
-
-```toml
-# Use a specific epoch version
-epoch = 3.1
-
-# Use the latest available epoch (default)
-epoch = "latest"
-```
-
-Usando `"latest"` garantiza que tus contratos siempre utilicen las características y optimizaciones de Clarity más recientes disponibles en tu versión de Clarinet.
-
-## Infraestructura de pruebas
-
-### Configuración del paquete
-
-El **package.json** define su entorno de pruebas y dependencias:
-
-```json package.json
-{
- "name": "counter-tests",
- "version": "1.0.0",
- "description": "Run unit tests on this project.",
- "type": "module",
- "private": true,
- "scripts": {
- "test": "vitest run",
- "test:report": "vitest run -- --coverage --costs",
- "test:watch": "chokidar \"tests/**/*.ts\" \"contracts/**/*.clar\" -c \"npm run test:report\""
- },
- "author": "",
- "license": "ISC",
- "dependencies": {
- "@hirosystems/clarinet-sdk": "^3.0.2",
- "@stacks/transactions": "^7.0.6",
- "@types/node": "^24.0.14",
- "chokidar-cli": "^3.0.0",
- "vitest": "^3.1.3",
- "vitest-environment-clarinet": "^2.3.0"
- }
-}
-```
-
-| Paquete | Propósito |
-|---------|---------|
-| `@hirosystems/clarinet-sdk` | WebAssembly-compilado Clarinet para Node.js |
-| `@stacks/transactions` | Manipulación de valores de Clarity en TypeScript |
-| `vitest` | Marco de pruebas moderno con soporte nativo para TypeScript |
-| `vitest-environment-clarinet` | Arranque de Simnet para pruebas |
-
-### Configuración de Vitest
-
-El **vitest.config.js** configura el marco de pruebas:
-
-```js vitest.config.js
-///
-import { defineConfig } from "vite";
-import { vitestSetupFilePath, getClarinetVitestsArgv } from "@hirosystems/clarinet-sdk/vitest";
-
-export default defineConfig({
- test: {
- environment: "clarinet", // use vitest-environment-clarinet
- pool: "forks",
- poolOptions: {
- threads: { singleThread: true },
- forks: { singleFork: true },
- },
- setupFiles: [
- vitestSetupFilePath,
- // custom setup files can be added here
- ],
- environmentOptions: {
- clarinet: {
- ...getClarinetVitestsArgv(),
- // add or override options
- },
- },
- },
-});
-```
-
-Esta configuración habilita:
-
-* **Entorno de Clarinet**: Automático `simnet` configuración para cada prueba
-* **Modo de bifurcación única**: Ejecución eficiente de pruebas con aislamiento adecuado
-* **Seguimiento de cobertura**: Generar informes en múltiples formatos
-* **Configuración personalizada**: Agregar utilidades de prueba específicas del proyecto
-
-### Configuración de TypeScript
-
-El **tsconfig.json** proporciona soporte para TypeScript:
-
-```json tsconfig.json
-
-{
- "compilerOptions": {
- "target": "ESNext",
- "useDefineForClassFields": true,
- "module": "ESNext",
- "lib": ["ESNext"],
- "skipLibCheck": true,
-
- "moduleResolution": "bundler",
- "allowImportingTsExtensions": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "noEmit": true,
-
- "strict": true,
- "noImplicitAny": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noFallthroughCasesInSwitch": true
- },
- // !mark(1:4)
- "include": [
- "node_modules/@hirosystems/clarinet-sdk/vitest-helpers/src",
- "tests"
- ]
-}
-```
-
-Es importante configurar correctamente la propiedad include, por defecto apunta a los archivos de ayuda definidos en el paquete clarinet-sdk, y al directorio de pruebas.
-
-## Configuraciones de red
-
-### Configuración del entorno
-
-Cada red tiene su propio archivo de configuración en el **configuración** directorio:
-
-```toml settings/Devnet.toml
-[network]
-name = "devnet"
-deployment_fee_rate = 10
-
-[accounts.deployer]
-mnemonic = "twice kind fence tip hidden..."
-balance = 100_000_000_000_000
-
-[accounts.wallet_1]
-mnemonic = "sell invite acquire kitten..."
-balance = 10_000_000_000_000
-```
-
-Estos ajustes controlan:
-
-* **Puertos de red**: Puntos finales de API, RPC y explorador
-* **Configuración de cuenta**: Carteras de prueba con saldos de STX
-* **Parámetros de la cadena**: Configuración específica de la cadena de bloques de la red
-
-:::callout
-type: warn
-
-### Aviso de Seguridad
-
-Nunca comprometas claves privadas o frases mnemónicas de la red principal. Utiliza variables de entorno para las credenciales de producción.
-:::
-
-## Problemas comunes
-
-
-
- Importaciones fallando en pruebas
-
-
-
- Si estás encontrando errores de importación en tus pruebas, actualiza tu configuración de TypeScript para usar la resolución del empaquetador de Vite:
-
- ```json tsconfig.json
- {
- "compilerOptions": {
- "moduleResolution": "bundler", // !mark
- "allowImportingTsExtensions": true
- }
- }
- ```
-
- Esta configuración asegura que TypeScript comprenda la estrategia de resolución de módulos de Vite y permita la importación `.ts` archivos directamente.
-
-
-
-
-
- Versiones incompatibles
-
-
-
- Todos los contratos en su proyecto deben usar la misma versión y época de Clarity para evitar problemas de compatibilidad:
-
- ```toml Clarinet.toml
- [contracts.token]
- clarity_version = 3
- epoch = "latest" # !mark
-
- [contracts.pool]
- clarity_version = 3
- epoch = "latest" # !mark
- ```
-
- Las versiones incompatibles pueden causar fallos en la implementación y comportamientos inesperados. Siempre actualice todos los contratos juntos cuando se cambie a una nueva versión de Clarity.
-
-
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Escribiendo contratos de Clarity](/tools/clarinet/project-development): Crea y gestiona contratos de Clarity.
-* [Pruebas y validación](/tools/clarinet/contract-interaction): Interactúa con contratos Clarity en tu proyecto.
-:::
diff --git a/content/docs/es/tools/clarinet/(overview)/quickstart.mdx b/content/docs/es/tools/clarinet/(overview)/quickstart.mdx
deleted file mode 100644
index 5a718927a..000000000
--- a/content/docs/es/tools/clarinet/(overview)/quickstart.mdx
+++ /dev/null
@@ -1,165 +0,0 @@
----
-title: Inicio rápido
-description: En esta guía, construirás un contrato inteligente de contador simple e interactuarás con él en un entorno local.
----
-## Lo que aprenderás
-
-:::objectives
-* Crear un proyecto de contrato inteligente en Clarity
-* Escribir código Clarity con mapas y funciones públicas
-* Prueba y valida tus contratos utilizando la consola de Clarinet
-:::
-
-## Requisitos previos
-
-:::prerequisites
-* Clarinet instalado en tu máquina. Sigue el [guía de instalación](/tools/clarinet#installation) si es necesario.
-* Un editor de código como VS Code para editar archivos de Clarity.
-:::
-
-## Inicio rápido
-
-
-
- ### Crea tu proyecto
-
- Comencemos creando un nuevo proyecto de Clarinet. El `clarinet new` el comando configura todo lo que necesitas para el desarrollo de contratos inteligentes, incluyendo un marco de pruebas, configuraciones de implementación y un entorno de desarrollo local:
-
- ```terminal
- $ clarinet new counter
- [32mCreate directory[0m [1mcounter[0m
- [32mCreate directory[0m [1mcontracts[0m
- [32mCreate directory[0m [1msettings[0m
- [32mCreate directory[0m [1mtests[0m
- [32mCreate file[0m [1mClarinet.toml[0m
- [32mCreate file[0m [1mpackage.json[0m
- [32mCreate file[0m [1mvitest.config.js[0m
- ```
-
- Clarinet crea una estructura de proyecto completa para ti. Cada carpeta tiene un propósito específico en tu flujo de trabajo de desarrollo:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ### Genera tu contrato
-
- Ahora que tenemos nuestra estructura de proyecto, vamos a crear un contrato inteligente. Navega a tu directorio de proyecto y utiliza el generador de contratos de Clarinet:
-
- ```terminal
- $ cd counter
- $ clarinet contract new counter
- [32mCreated file[0m [1mcontracts/counter.clar[0m
- [32mCreated file[0m [1mtests/counter.test.ts[0m
- [33mUpdated Clarinet.toml[0m [1mwith contract counter[0m
- ```
-
- Clarinet crea automáticamente tanto su archivo de contrato como un archivo de prueba correspondiente. Esto sigue la mejor práctica de escribir pruebas junto con su código de contrato:
-
- | Archivo | Propósito |
- |------|---------|
- | `contracts/counter.clar` | Tu código de contrato inteligente |
- | `tests/counter.test.ts` | Archivo de prueba para su contrato |
-
- :::callout
- Observe que Clarinet también actualizó su `Clarinet.toml` archivo. Este archivo de configuración rastrea todos los contratos en su proyecto y sus ajustes de implementación.
- :::
-
-
-
- ### Escriba el código de su contrato
-
- Abrir `contracts/counter.clar` y reemplazar su contenido con nuestra implementación del contador. Este contrato mantendrá un conteo separado para cada usuario que interactúe con él:
-
- ```clarity contracts/counter.clar -c
- ;; Define a map to store counts for each user
- (define-map counters principal uint)
-
- ;; Increment the count for the caller
- (define-public (count-up)
- (ok (map-set counters tx-sender (+ (get-count tx-sender) u1)))
- )
-
- ;; Get the current count for a user
- (define-read-only (get-count (who principal))
- (default-to u0 (map-get? counters who))
- )
- ```
-
- Entendamos qué hace cada parte:
-
- * [`define-map`](/resources/clarity/reference/functions#define-map) crea un mapa de almacenamiento persistente que asocia a cada usuario (principal) con su conteo
- * [`tx-sender`](/resources/clarity/reference/keywords#tx-sender) es una variable incorporada que contiene la dirección de quien llama a la función
- * [`define-public`](/resources/clarity/reference/functions#define-public) declara funciones que pueden modificar el estado del contrato
- * [`define-read-only`](/resources/clarity/reference/functions#define-read-only) declara funciones que solo leen datos sin modificarlos
-
-
-
- ### Valide su contrato
-
- Antes de poder probar nuestro contrato, asegurémonos de que sea sintácticamente correcto y seguro en cuanto a tipos. El comando check de Clarinet analiza tu contrato sin desplegarlo:
-
- ```terminal
- $ clarinet check
- [32m✔[0m [1m1 contract checked[0m
- ```
-
- Si ve errores en su lugar, estos son los problemas más comunes y cómo solucionarlos:
-
- | Error | Solución |
- |-------|-----|
- | `Unknown keyword` | Verificar la ortografía de las funciones de Clarity |
- | `Type mismatch` | Asegúrate de usar los tipos correctos (uint, principal, etc.) |
- | `Unresolved contract` | Verificar el nombre del contrato en `Clarinet.toml` coincide con el nombre del contrato en el archivo |
-
-
-
- ### Prueba en la consola
-
- Ahora viene la parte emocionante: ¡interactuemos con nuestro contrato! Clarinet proporciona una consola interactiva donde puedes llamar funciones y ver resultados inmediatamente. Inicia la consola con:
-
- ```terminal
- $ clarinet console
- ```
-
- Una vez que la consola se carga, puedes llamar a las funciones de tu contrato directamente. Aquí hay algunos ejemplos que puedes probar:
-
- ```terminal
- $ (contract-call? .counter count-up)
- [32m(ok true)[0m
- $ (contract-call? .counter get-count tx-sender)
- [32mu1[0m
- $ (contract-call? .counter count-up)
- [32m(ok true)[0m
- $ (contract-call? .counter get-count tx-sender)
- [32mu2[0m
- ```
-
-
-
-## Próximos pasos
-
-:::next-steps
-* [Estructura del proyecto](/tools/clarinet/project-structure): Aprende sobre la estructura del proyecto y cómo gestionar tus contratos.
-* [Desarrollo de blockchain local](/tools/clarinet/local-blockchain-development): Inicia una cadena de bloques local para probar tus contratos.
-:::
diff --git a/content/docs/es/tools/clarinet/(vscode-extension)/vscode-extension.mdx b/content/docs/es/tools/clarinet/(vscode-extension)/vscode-extension.mdx
deleted file mode 100644
index 0e7e3ff91..000000000
--- a/content/docs/es/tools/clarinet/(vscode-extension)/vscode-extension.mdx
+++ /dev/null
@@ -1,102 +0,0 @@
----
-title: Extensión de VS Code
-sidebarTitle: Introducción
-description: La extensión Clarity para VS Code transforma tu editor en un potente entorno de desarrollo de contratos inteligentes. Obtienes resaltado de sintaxis, autocompletado, depuración y verificación de errores en tiempo real.
----
-## Características
-
-### Autocompletado inteligente
-
-La extensión proporciona autocompletado de código inteligente que comprende el contexto de Clarity. Cuando comienzas a escribir cualquier función de Clarity, obtienes sugerencias instantáneas con documentación:
-
-```clarity
-;; Type "stx-tr" and get:
-(stx-transfer? amount sender recipient)
-;; ^ ^ ^
-;; Placeholders for easy navigation
-```
-
-Usar `Tab` para saltar entre marcadores de posición y `Escape` para salir del modo de marcador de posición.
-
-### Documentación al pasar el cursor
-
-Accede a documentación completa sin salir de tu editor. Pasa el cursor sobre cualquier función o palabra clave de Clarity para ver:
-
-```clarity
-;; Hover over 'map-set' to see:
-;; - Function signature
-;; - Parameter descriptions
-;; - Return type
-;; - Usage examples
-(map-set my-map {key: "value"} "data")
-```
-
-### Definición de referencia
-
-Navega por tu base de código de manera eficiente con las funciones de salto a definición:
-
-* `F12` o `Ctrl+Click` - Ir a la definición
-* `Alt+F12` - Ver la definición sin salir del archivo actual
-* Funciona en archivos de contrato y llamadas de contrato
-
-### Comprobación de errores en tiempo real
-
-La extensión valida tu código continuamente, proporcionando retroalimentación inmediata:
-
-* **Subrayados rojos** - Errores de sintaxis, palabras clave desconocidas
-* **Garabatos amarillos** - Advertencias para código potencialmente inseguro
-* **Lista de errores** - Todos los problemas en el panel Problemas (`Ctrl+Shift+M`)
-
-Los errores comunes detectados incluyen variables no definidas, incompatibilidades de tipos, implementaciones de rasgos faltantes y firmas de funciones inválidas.
-
-### Resolución de contratos locales
-
-La autocompletación funciona en todo tu proyecto. Haz referencia a funciones de otros contratos en tu espacio de trabajo:
-
-```clarity
-;; Auto-complete local contract calls
-(contract-call? .my-token transfer amount sender recipient)
-;; ^
-;; Suggests contracts in your project
-```
-
-### Soporte de rasgos
-
-Al implementar rasgos (como NFTs SIP-009 o tokens SIP-010), la extensión verifica:
-
-* Todas las funciones requeridas están implementadas
-* Las firmas de función coinciden con las definiciones de rasgos
-* Los tipos de retorno son correctos
-
-```clarity
-;; Extension warns if missing required trait functions
-(impl-trait .sip-010-trait.sip-010-trait)
-
-;; ⚠️ Warning: Missing required function 'get-balance'
-```
-
-### Depuración visual
-
-La extensión incluye un depurador visual para la ejecución de código paso a paso:
-
-1. Establece puntos de interrupción haciendo clic en los números de línea
-2. Presionar `F5` o usa Ejecutar → Iniciar depuración
-3. Recorre el código línea por línea
-4. Inspeccionar variables y estado de la pila
-
-:::callout
-### Requisitos
-
-La depuración visual requiere VS Code Desktop y Clarinet instalados localmente.
-:::
-
-## Tabla de comparación
-
-| Característica | Editor Básico | Extensión de VS Code |
-|----------------|----------------|------------------------|
-| Resaltado de sintaxis | Limitado | Soporte completo de Clarity |
-| Autocompletado | Ninguno | Contextual con documentación |
-| Verificación de errores | Solo al desplegar | Validación en tiempo real |
-| Documentación | Búsqueda externa | Documentación emergente en línea |
-| Depuración | Solo consola | Depurador visual |
-| Navegación entre archivos | Manual | Salto a definición |
diff --git a/content/docs/es/tools/clarinet/index.mdx b/content/docs/es/tools/clarinet/index.mdx
deleted file mode 100644
index 2a0ed79d9..000000000
--- a/content/docs/es/tools/clarinet/index.mdx
+++ /dev/null
@@ -1,73 +0,0 @@
----
-title: Clarinet
-sidebarTitle: Visión general
-description: Clarinet es todo lo que necesitas para escribir, probar e implementar contratos inteligentes de Clarity en Stacks.
-type: overview
-llm: false
----
-## Visión general
-
-Clarinet is the fastest way to build, test, and deploy smart contracts on the Stacks blockchain. It gives you a local devnet, REPL, testing framework, and debugging tools to ship high-quality Clarity code with confidence.
-
-
-
-Para explorar las funciones de Clarinet con IA, copie y pegue [llms.txt](/tools/clarinet/llms.txt) en tu LLM de elección.
-
-## Características principales
-
-* [**Aproveche una potente interfaz de línea de comandos**](/tools/clarinet/cli-reference) - Create new projects, manage your smart contracts and their dependencies using clarinet requirements, and interact with your code through the built-in REPL.
-* [**Escribir pruebas unitarias con el SDK**](/tools/clarinet/sdk-introduction) - Utiliza el SDK de Clarinet para escribir pruebas unitarias en un entorno JS familiar y validar el comportamiento del contrato.
-* [**Ejecutar un entorno de blockchain privado**](/tools/clarinet/local-blockchain-development) - Inicia una devnet local con nodos, mineros y APIs para que puedas probar e integrar tu código.
-* [**Extensión de VSCode**](/tools/clarinet/vscode-extension) - Linter, depurador paso a paso, ayuda a escribir contratos inteligentes (autocompletación, documentación, etc.).
-
-## Instalación
-
-
- ```terminal !! Homebrew
- $ brew install clarinet
- ```
-
- ```terminal !! Winget
- $ winget install clarinet
- ```
-
- ```terminal !! Source
- $ sudo apt install build-essential pkg-config libssl-dev
- $ git clone https://github.com/hirosystems/clarinet
- $ cd clarinet
- $ cargo clarinet-install
- ```
-
- ```terminal !! Binary
- $ wget -nv https://github.com/hirosystems/clarinet/releases/latest/download/clarinet-linux-x64-glibc.tar.gz -O clarinet-linux-x64.tar.gz
- $ tar -xf clarinet-linux-x64.tar.gz
- $ chmod +x ./clarinet
- $ mv ./clarinet /usr/local/bin
- ```
-
-
-## Redes
-
-Clarinet admite diferentes tipos de redes para satisfacer diversas necesidades de desarrollo y pruebas:
-
-| Red | Descripción | Caso de uso
-| -------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
-| `simnet` | Optimizado para ciclos de retroalimentación rápidos, introspección y portabilidad. | Ideal para el desarrollo inicial y las pruebas unitarias. |
-| `devnet` | Nodos locales de Stacks y Bitcoin ejecutándose en Docker para ciclos de retroalimentación más rápidos. | Utilizar para pruebas de integración o desarrollo frontend local. |
-| `testnet` | Una red de preproducción que ofrece un entorno realista para pruebas. | Ideal para pruebas finales antes de implementar en Mainnet. |
-| `mainnet` | La red de producción donde ocurren las transacciones reales. | Úsela cuando esté listo para implementar su contrato inteligente en producción. |
-
-## Próximos pasos
-
-:::next-steps
-* [Inicio rápido](/tools/clarinet/quickstart): Comienza con Clarinet.
-* [Crear un proyecto](/tools/clarinet/project-development): Crear un nuevo proyecto de Clarinet.
-:::
-
-:::callout
-type: help
-
-### ¿Necesitas ayuda para construir con Clarinet?
-
-Contáctenos en el **#clarinet** canal activado [Discord](https://stacks.chat/) bajo la sección de Herramientas para Desarrolladores de Hiro. También hay una [horario de oficina semanal](https://www.addevent.com/event/kI22007085) llamada todos los miércoles a la 1 pm ET.
-:::
diff --git a/content/docs/es/tools/clarinet/meta.json b/content/docs/es/tools/clarinet/meta.json
deleted file mode 100644
index 008ac3413..000000000
--- a/content/docs/es/tools/clarinet/meta.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "title": "Clarinet",
- "root": true,
- "pages": [
- "---Clarinet---",
- "index",
- "...(overview)",
- "---Clarinet CLI---",
- "...(clarinet-cli)",
- "---Clarinet JS SDK---",
- "...(clarinet-js-sdk)",
- "---VSCode Extension---",
- "...(vscode-extension)",
- "---Integrations---",
- "...(integrations)"
- ]
-}
diff --git a/hooks/use-localized-navigation.tsx b/hooks/use-localized-navigation.tsx
index fb241d0c2..ea3bf434c 100644
--- a/hooks/use-localized-navigation.tsx
+++ b/hooks/use-localized-navigation.tsx
@@ -18,11 +18,6 @@ export function useLocalizedNavigation(): BaseLayoutProps['links'] {
type: 'menu' as const,
text: t.navigation.menus.tools,
items: [
- {
- text: t.tools.clarinet.title,
- description: t.tools.clarinet.description,
- url: '/tools/clarinet',
- },
{
text: t.tools.chainhook.title,
description: t.tools.chainhook.description,
@@ -33,11 +28,6 @@ export function useLocalizedNavigation(): BaseLayoutProps['links'] {
description: t.tools.contractMonitoring.description,
url: '/tools/contract-monitoring',
},
- {
- text: t.tools.clarityVscode.title,
- description: t.tools.clarityVscode.description,
- url: '/tools/clarinet/vscode-extension',
- },
{
text: t.tools.bitcoinIndexer.title,
description: t.tools.bitcoinIndexer.description,
@@ -99,42 +89,11 @@ export function useLocalizedNavigation(): BaseLayoutProps['links'] {
],
},
// Libraries & SDKs menu
- {
- type: 'menu' as const,
- text: t.navigation.menus.libraries,
- items: [
- {
- text: t.libraries.stacksJs.title,
- description: t.libraries.stacksJs.description,
- url: '/reference/stacks.js',
- },
- {
- text: t.libraries.stacksConnect.title,
- description: t.libraries.stacksConnect.description,
- url: '/reference/stacks.js/connect-wallet',
- },
- {
- text: t.libraries.clarinetSdk.title,
- description: t.libraries.clarinetSdk.description,
- url: '/tools/clarinet/sdk-introduction',
- },
- {
- text: t.libraries.clarinetBrowserSdk.title,
- description: t.libraries.clarinetBrowserSdk.description,
- url: '/tools/clarinet/browser-sdk-reference',
- },
- ],
- },
// Resources menu
{
type: 'menu' as const,
text: t.navigation.menus.resources,
items: [
- {
- text: t.resources.clarityReference.title,
- description: t.resources.clarityReference.description,
- url: '/resources/clarity',
- },
{
text: t.resources.guides.title,
description: t.resources.guides.description,
diff --git a/lib/metadata.ts b/lib/metadata.ts
index 03133c184..272284569 100644
--- a/lib/metadata.ts
+++ b/lib/metadata.ts
@@ -86,36 +86,6 @@ const chainhookMetadata: Partial = {
},
};
-const clarinetMetadata: Partial = {
- title: 'Clarinet',
- description: "Build and test Clarity smart contracts with Clarinet's development tools.",
- openGraph: {
- title: 'Clarinet',
- description: "Build and test Clarity smart contracts with Clarinet's development tools.",
- images: [{ url: '/images/clarinet-og.jpg', width: 800, height: 600 }],
- },
- twitter: {
- title: 'Clarinet',
- description: "Build and test Clarity smart contracts with Clarinet's development tools.",
- images: ['/images/clarinet-og.jpg'],
- },
-};
-
-const clarinetJsSdkMetadata: Partial = {
- title: 'Clarinet JS SDK',
- description: "Integrate Clarinet's testing capabilities into your development workflow.",
- openGraph: {
- title: 'Clarinet JS SDK',
- description: "Integrate Clarinet's testing capabilities into your development workflow.",
- images: [{ url: '/images/clarinet-js-sdk-og.jpg', width: 800, height: 600 }],
- },
- twitter: {
- title: 'Clarinet JS SDK',
- description: "Integrate Clarinet's testing capabilities into your development workflow.",
- images: ['/images/clarinet-js-sdk-og.jpg'],
- },
-};
-
const cookbookMetadata: Partial = {
title: 'Hiro Cookbook',
description: 'Practical recipes and examples for building on Bitcoin layers.',
@@ -227,36 +197,6 @@ const stacksApiMetadata: Partial = {
},
};
-const stacksConnectMetadata: Partial = {
- title: 'Stacks Connect',
- description: 'Integrate Stacks authentication and transactions in your applications.',
- openGraph: {
- title: 'Stacks Connect',
- description: 'Integrate Stacks authentication and transactions in your applications.',
- images: [{ url: '/images/stacks-connect-og.jpg', width: 800, height: 600 }],
- },
- twitter: {
- title: 'Stacks Connect',
- description: 'Integrate Stacks authentication and transactions in your applications.',
- images: ['/images/stacks-connect-og.jpg'],
- },
-};
-
-const stacksJsMetadata: Partial = {
- title: 'Stacks.js',
- description: 'Build Stacks applications with the Stacks.js library.',
- openGraph: {
- title: 'Stacks.js',
- description: 'Build Stacks applications with the Stacks.js library.',
- images: [{ url: '/images/stacks-js-og.jpg', width: 800, height: 600 }],
- },
- twitter: {
- title: 'Stacks.js',
- description: 'Build Stacks applications with the Stacks.js library.',
- images: ['/images/stacks-js-og.jpg'],
- },
-};
-
const tokenMetadataApiMetadata: Partial = {
title: 'Token Metadata API',
description: 'Access and manage token metadata on the Stacks blockchain.',
@@ -313,8 +253,6 @@ export function getRouteMetadata(path: string): Partial {
}
if (path.startsWith('/stacks/hacks')) return hiroHacksMetadata;
if (path.startsWith('/tools/chainhook')) return chainhookMetadata;
- if (path.startsWith('/tools/clarinet')) return clarinetMetadata;
- if (path.startsWith('/tools/clarinet')) return clarinetJsSdkMetadata;
if (path.startsWith('/resources/snippets')) return cookbookMetadata;
if (path.startsWith('/resources/guides')) return guidesMetadata;
if (path.startsWith('/apis/ordinals')) return ordinalsApiMetadata;
@@ -322,8 +260,6 @@ export function getRouteMetadata(path: string): Partial {
if (path.startsWith('/apis/runes')) return runesApiMetadata;
if (path.startsWith('/apis/signer-metrics')) return signerMetricsApiMetadata;
if (path.startsWith('/apis/stacks-blockchain')) return stacksApiMetadata;
- if (path.startsWith('/reference/stacks.js')) return stacksJsMetadata;
- if (path.startsWith('/reference/stacks.js')) return stacksConnectMetadata;
if (path.startsWith('/apis/token-metadata')) return tokenMetadataApiMetadata;
if (path.startsWith('/tools/bitcoin-indexer')) return bitcoinIndexerMetadata;
return {};
diff --git a/lib/source.ts b/lib/source.ts
index 98feba1fb..df7599b88 100644
--- a/lib/source.ts
+++ b/lib/source.ts
@@ -193,13 +193,13 @@ function extractSectionFromUrl(url: string): string {
// Remove leading slash and split by slash
const pathParts = url.replace(/^\//, '').split('/');
- // For URLs like "/stacks/clarinet/guides/..." return "clarinet"
- // For URLs like "/tools/clarinet" return "clarinet"
+ // For URLs like "/stacks/example/guides/..." return "example"
+ // For URLs like "/tools/example" return "example"
if (pathParts.length >= 2) {
return pathParts[1];
}
- // For single level paths like "/clarinet", return that
+ // For single level paths like "/example", return that
if (pathParts.length === 1 && pathParts[0]) {
return pathParts[0];
}
@@ -588,7 +588,7 @@ export const source = loader({
// If this page has labels, add it to the filterable pages collection
// if (labels.length > 0 && node.url) {
- // // Extract section from URL (e.g., "/stacks/clarinet" -> "clarinet")
+ // // Extract section from URL (e.g., "/stacks/example" -> "example")
// const section = extractSectionFromUrl(node.url);
// const filterablePage: FilterablePage = {
diff --git a/lib/translations/en.ts b/lib/translations/en.ts
index 18ebe5ab2..ce6225a1b 100644
--- a/lib/translations/en.ts
+++ b/lib/translations/en.ts
@@ -52,20 +52,14 @@ export const en: Translations = {
auth: 'Auth',
// Tools
- clarinet: 'Clarinet',
chainhook: 'Chainhook',
// Specific pages/sections
guides: 'Guides',
- clarity: 'Clarity',
snippets: 'Snippets',
archive: 'Archive',
},
tools: {
- clarinet: {
- title: 'Clarinet',
- description: 'Development environment and testing framework for Clarity smart contracts.',
- },
chainhook: {
title: 'Chainhook',
description: 'Monitor and analyze Clarity smart contract activity.',
@@ -74,10 +68,6 @@ export const en: Translations = {
title: 'Contract Monitoring',
description: 'Monitor and analyze Clarity smart contract activity.',
},
- clarityVscode: {
- title: 'Clarity VSCode Extension',
- description: 'Monitor and analyze Clarity smart contract activity.',
- },
bitcoinIndexer: {
title: 'Bitcoin Indexer',
description: 'Indexer for Bitcoin blockchain data.',
@@ -122,29 +112,7 @@ export const en: Translations = {
description: 'API for accessing Signer metrics data and functionality.',
},
},
- libraries: {
- stacksJs: {
- title: 'Stacks.js',
- description: 'JavaScript library for building on Stacks.',
- },
- stacksConnect: {
- title: 'Stacks Connect',
- description: 'JavaScript library for connecting to Stacks wallets.',
- },
- clarinetSdk: {
- title: 'Clarinet JS SDK',
- description: 'JavaScript SDK for Clarinet.',
- },
- clarinetBrowserSdk: {
- title: 'Clarinet JS Browser SDK',
- description: 'JavaScript SDK for Clarinet in the browser.',
- },
- },
resources: {
- clarityReference: {
- title: 'Clarity Reference',
- description: 'Clarity language reference.',
- },
guides: {
title: 'Guides',
description: 'Guides for building on Stacks.',
diff --git a/lib/translations/es.ts b/lib/translations/es.ts
index e11be14f8..12f85ff80 100644
--- a/lib/translations/es.ts
+++ b/lib/translations/es.ts
@@ -52,20 +52,14 @@ export const es: Translations = {
auth: 'Auth',
// Tools
- clarinet: 'Clarinet',
chainhook: 'Chainhook',
// Specific pages/sections
guides: 'Guías',
- clarity: 'Clarity',
snippets: 'Fragmentos',
archive: 'Archivo',
},
tools: {
- clarinet: {
- title: 'Clarinet',
- description: 'Entorno de desarrollo y marco de pruebas para contratos inteligentes Clarity.',
- },
chainhook: {
title: 'Chainhook',
description: 'Monitorear y analizar la actividad de contratos inteligentes Clarity.',
@@ -74,10 +68,6 @@ export const es: Translations = {
title: 'Monitoreo de Contratos',
description: 'Monitorear y analizar la actividad de contratos inteligentes Clarity.',
},
- clarityVscode: {
- title: 'Extensión VSCode de Clarity',
- description: 'Monitorear y analizar la actividad de contratos inteligentes Clarity.',
- },
bitcoinIndexer: {
title: 'Indexador de Bitcoin',
description: 'Indexador para datos de la blockchain de Bitcoin.',
@@ -122,29 +112,7 @@ export const es: Translations = {
description: 'API para acceder a datos y funcionalidad de métricas de Firmante.',
},
},
- libraries: {
- stacksJs: {
- title: 'Stacks.js',
- description: 'Biblioteca JavaScript para construir en Stacks.',
- },
- stacksConnect: {
- title: 'Stacks Connect',
- description: 'Biblioteca JavaScript para conectar con billeteras Stacks.',
- },
- clarinetSdk: {
- title: 'SDK JS de Clarinet',
- description: 'SDK de JavaScript para Clarinet.',
- },
- clarinetBrowserSdk: {
- title: 'SDK de Navegador JS de Clarinet',
- description: 'SDK de JavaScript para Clarinet en el navegador.',
- },
- },
resources: {
- clarityReference: {
- title: 'Referencia de Clarity',
- description: 'Referencia del lenguaje Clarity.',
- },
guides: {
title: 'Guías',
description: 'Guías para construir en Stacks.',
diff --git a/lib/translations/types.ts b/lib/translations/types.ts
index bd899b692..1a5aaed30 100644
--- a/lib/translations/types.ts
+++ b/lib/translations/types.ts
@@ -50,20 +50,14 @@ export interface Translations {
auth: string;
// Tools
- clarinet: string;
chainhook: string;
// Specific pages/sections
guides: string;
- clarity: string;
snippets: string;
archive: string;
};
tools: {
- clarinet: {
- title: string;
- description: string;
- };
chainhook: {
title: string;
description: string;
@@ -72,10 +66,6 @@ export interface Translations {
title: string;
description: string;
};
- clarityVscode: {
- title: string;
- description: string;
- };
bitcoinIndexer: {
title: string;
description: string;
@@ -119,29 +109,8 @@ export interface Translations {
description: string;
};
};
- libraries: {
- stacksJs: {
- title: string;
- description: string;
- };
- stacksConnect: {
- title: string;
- description: string;
- };
- clarinetSdk: {
- title: string;
- description: string;
- };
- clarinetBrowserSdk: {
- title: string;
- description: string;
- };
- };
+ libraries?: never;
resources: {
- clarityReference: {
- title: string;
- description: string;
- };
guides: {
title: string;
description: string;
diff --git a/vercel.json b/vercel.json
index a7608f321..be9cd8f64 100644
--- a/vercel.json
+++ b/vercel.json
@@ -12,21 +12,55 @@
}
],
"redirects": [
- { "source": "/stacks/clarinet/:path*", "destination": "/tools/clarinet", "permanent": true },
+ {
+ "source": "/tools/clarinet/:path*",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
+ {
+ "source": "/:locale/tools/clarinet/:path*",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
+ {
+ "source": "/reference/stacks.js/:path*",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
+ {
+ "source": "/:locale/reference/stacks.js/:path*",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
+ {
+ "source": "/resources/clarity/:path*",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
+ {
+ "source": "/:locale/resources/clarity/:path*",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
+ {
+ "source": "/stacks/clarinet/:path*",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
{
"source": "/stacks/clarinet-js-sdk/:path*",
- "destination": "/tools/clarinet",
+ "destination": "https://docs.stacks.co/reference",
"permanent": true
},
{ "source": "/stacks/chainhook/:path*", "destination": "/tools/chainhook", "permanent": true },
{
"source": "/stacks/stacks.js/:path*",
- "destination": "/reference/stacks.js",
+ "destination": "https://docs.stacks.co/reference",
"permanent": true
},
{
"source": "/stacks/connect/:path*",
- "destination": "/reference/stacks.js",
+ "destination": "https://docs.stacks.co/reference",
"permanent": true
},
{
@@ -44,7 +78,21 @@
"destination": "/apis/ordinals-api",
"permanent": true
},
- { "source": "/clarinet", "destination": "/tools/clarinet", "permanent": true },
+ {
+ "source": "/clarinet",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
+ {
+ "source": "/clarity",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
+ {
+ "source": "/stacks.js",
+ "destination": "https://docs.stacks.co/reference",
+ "permanent": true
+ },
{
"source": "/token-metadata-api",
"destination": "/apis/token-metadata-api",