diff --git a/README.md b/README.md index c1a236a3c..2e863558a 100644 --- a/README.md +++ b/README.md @@ -11,10 +11,10 @@ Documentation for Hiro Systems PBC. Built with [Fumadocs](https://fumadocs.verce Example structure: ``` -/tools/clarinet/ +/tools/example-tool/ ├── Overview/ # Introduction and setup -├── Clarinet CLI/ # Command-line features -├── Clarinet JS SDK/ # Testing and programmatic usage +├── CLI/ # Command-line features +├── SDK/ # Testing and programmatic usage └── Integrations/ # External connections ``` diff --git a/app/[locale]/(home)/_pages/page.en.tsx b/app/[locale]/(home)/_pages/page.en.tsx index 321bbe10b..8255e291a 100644 --- a/app/[locale]/(home)/_pages/page.en.tsx +++ b/app/[locale]/(home)/_pages/page.en.tsx @@ -1,17 +1,7 @@ import { ImageZoom } from 'fumadocs-ui/components/image-zoom'; import { Braces, Database, Play } from 'lucide-react'; import { Card, Cards, SmallCard } from '@/components/card'; -import { - API, - Chainhook, - Clarinet, - Clarity, - Hiro, - Js, - Ordinals, - Runes, - StacksIcon, -} from '@/components/ui/icon'; +import { API, Chainhook, Hiro, Ordinals, Runes, StacksIcon } from '@/components/ui/icon'; import heroImage from '@/public/stacks-hero.svg'; export default function HomePage() { @@ -65,12 +55,6 @@ export default function HomePage() {
- } - href="/tools/clarinet" - title="Clarinet" - description="A comprehensive development environment for building and testing Clarity smart contracts." - /> } href="/tools/chainhook" @@ -140,44 +124,22 @@ export default function HomePage() {

- Libraries & SDKs + Resources


} - href="/reference/stacks.js" - title="Stacks.js" - description="JavaScript SDK for building applications on Stacks with transactions, network utilities, and wallet integration." + icon={} + href="/resources/guides" + title="Guides" + description="Step-by-step walkthroughs for building on Bitcoin layers." /> } - href="/tools/clarinet/sdk-introduction" - title="Clarinet JS SDK" - description="JavaScript SDK for testing and interacting with Clarity smart contracts in simulated environments." - /> - {/* } - href="/reference/stacks-blockchain-api" - title="Stacks Blockchain API Client" - description="Type-safe JavaScript client library for interacting with the Stacks Blockchain API." - /> */} - -
-
-

- - Resources - -

-
- - } - href="/resources/clarity" - title="Clarity Reference" - description="Comprehensive guides and function reference for the Clarity smart contract language." + icon={} + href="/resources/snippets" + title="Snippets" + description="Reusable code examples for common Stacks and Bitcoin tasks." /> } diff --git a/app/[locale]/(home)/_pages/page.es.tsx b/app/[locale]/(home)/_pages/page.es.tsx index 97d6ab0e1..44f72ca4b 100644 --- a/app/[locale]/(home)/_pages/page.es.tsx +++ b/app/[locale]/(home)/_pages/page.es.tsx @@ -1,17 +1,7 @@ import { ImageZoom } from 'fumadocs-ui/components/image-zoom'; import { Braces, Database, Play } from 'lucide-react'; import { Card, Cards, SmallCard } from '@/components/card'; -import { - API, - Chainhook, - Clarinet, - Clarity, - Hiro, - Js, - Ordinals, - Runes, - StacksIcon, -} from '@/components/ui/icon'; +import { API, Chainhook, Hiro, Ordinals, Runes, StacksIcon } from '@/components/ui/icon'; import heroImage from '@/public/stacks-hero.svg'; export default function HomePage() { @@ -66,13 +56,6 @@ export default function HomePage() {
- } - href="/tools/clarinet" - title="Clarinet" - description="Un entorno de desarrollo integral para construir y probar contratos inteligentes de Clarity." - /> - } href="/tools/chainhook" @@ -149,46 +132,23 @@ export default function HomePage() {

- Bibliotecas y SDKs + Recursos


} - 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." - /> */} - -
-
-

- - Recursos - -

-
- - } - 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} - - ); - } - ``` - - - - ### 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} -