### Example: Add OpenBazaar Account Source: https://github.com/stx-labs/stacks.js/wiki/Linking-your-OB-GUID An example of adding an OpenBazaar account using a specific Blockchain ID, GUID, and store URL. ```bash blockstack put_account "testregistration001.id" "openbazaar" "0123456789abcdef" "https://bazaarbay.org/@testregistration001" ``` -------------------------------- ### Install @stacks/stacking Source: https://github.com/stx-labs/stacks.js/blob/main/packages/stacking/README.md Install the @stacks/stacking library using npm. ```shell npm install @stacks/stacking ``` -------------------------------- ### Install @stacks/wallet-sdk Source: https://github.com/stx-labs/stacks.js/blob/main/packages/wallet-sdk/README.md Install the wallet SDK using NPM. This is the first step to integrating wallet functionalities into your application. ```bash npm install @stacks/wallet-sdk ``` -------------------------------- ### Install @stacks/storage Source: https://github.com/stx-labs/stacks.js/blob/main/packages/storage/README.md Install the @stacks/storage package using npm. ```bash npm install @stacks/storage ``` -------------------------------- ### Install @stacks/network Source: https://github.com/stx-labs/stacks.js/blob/main/packages/network/README.md Install the @stacks/network package using npm. ```bash npm install @stacks/network ``` -------------------------------- ### Install @stacks/cli Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Install the @stacks/cli package using npm. ```bash npm install @stacks/cli ``` -------------------------------- ### Install @stacks/transactions Source: https://github.com/stx-labs/stacks.js/blob/main/packages/transactions/README.md Install the @stacks/transactions package using npm. ```bash npm install @stacks/transactions ``` -------------------------------- ### Install @stacks/api Source: https://github.com/stx-labs/stacks.js/blob/main/packages/api/README.md Install the @stacks/api package using npm. ```bash npm install @stacks/api ``` -------------------------------- ### Install @stacks/auth Package Source: https://github.com/stx-labs/stacks.js/blob/main/packages/auth/README.md Install the @stacks/auth package using npm. This is the first step to using the authentication functionalities. ```bash npm install @stacks/auth ``` -------------------------------- ### Install @stacks/profile Package Source: https://github.com/stx-labs/stacks.js/blob/main/packages/profile/README.md Install the @stacks/profile package using npm. ```bash npm install @stacks/profile ``` -------------------------------- ### Install @stacks/bns Package Source: https://github.com/stx-labs/stacks.js/blob/main/packages/bns/README.md Install the BNS package using npm. ```bash npm install --save @stacks/bns ``` -------------------------------- ### Run an authentication endpoint Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Start an authentication server for owned names, specifying application and profile Gaia hub URLs. The server listens on a specified port. ```bash export BACKUP_PHRASE="oak indicate inside poet please share dinner monitor glow hire source perfect" export APP_GAIA_HUB="https://1.2.3.4" export PROFILE_GAIA_HUB="https://hub.blockstack.org" stx authenticator "$APP_GAIA_HUB" "$BACKUP_PHRASE" "$PROFILE_GAIA_HUB" 8888 Press Ctrl+C to exit Authentication server started on 8888 ``` -------------------------------- ### Initialize App Configuration and User Session Source: https://github.com/stx-labs/stacks.js/blob/main/packages/auth/README.md Configure your application's permissions and domain, then initialize a UserSession object. This setup is crucial for managing user authentication states. ```typescript const appDomain = 'https://www.myapp.com'; const appConfig = new AppConfig(['store_write'], appDomain); const userSession = new UserSession({ appConfig }); ``` -------------------------------- ### Install @stacks/common Source: https://github.com/stx-labs/stacks.js/blob/main/packages/common/README.md Install the @stacks/common package using npm. This package provides common utilities for Stacks.js. ```bash npm install @stacks/common ``` -------------------------------- ### Get File Source: https://github.com/stx-labs/stacks.js/blob/main/packages/storage/README.md Retrieve the content of a file from Gaia. ```typescript const fileContent = await storage.getFile('my_data.json'); console.log(fileContent); ``` -------------------------------- ### Get File with Options Source: https://github.com/stx-labs/stacks.js/blob/main/packages/storage/README.md Retrieve file content with options to disable decryption or verification. ```typescript const getFileOptions = { decrypt: false, // by default files stored are signed and can be verified for authenticity verify: false } const fileContent = await storage.getFile('my_data.json', getFileOptions); console.log(fileContent); ``` -------------------------------- ### Get Owner Keys and Addresses Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Generate a sequence of owner private keys and ID-addresses from a 12-word backup phrase. Specify an index to generate multiple keys. The output includes the private key, version, index, and ID-address. ```shell # get the first 3 owner keys and addresses for a backup phrase // Specify -t for testnet export BACKUP_PHRASE="soap fog wealth upon actual blossom neither timber phone exile monkey vocal" stx get_owner_keys "$BACKUP_PHRASE" 3 [ { "privateKey": "14b0811d5cd3486d47279d8f3a97008647c64586b121e99862c18863e2a4183501", "version": "v0.10-current", "index": 0, "idAddress": "ID-1ArdkA2oLaKnbNbLccBaFhEV4pYju8hJ82" }, { "privateKey": "1b3572d8dd6866828281ac6cf135f04153210c1f9b123743eccb795fd3095e4901", "version": "v0.10-current", "index": 1, "idAddress": "ID-18pR3UpD1KFrnk88a3MGZmG2dLuZmbJZ25" }, { "privateKey": "b19b6d62356db96d570fb5f08b78f0aa7f384525ba3bdcb96fbde29b8e11710d01", "version": "v0.10-current", "index": 2, "idAddress": "ID-1Gx4s7ggkjENw3wSY6bNd1CwoQKk857AqN" } ] ``` -------------------------------- ### Get Free Testnet STX Tokens Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Use the faucet command to obtain free Stacks Tokens (STX) on the testnet for a specified address. The output includes the transaction ID and a link to the transaction on the explorer. ```shell stx faucet ST3PWZ5M026785YW8YKKEH316DYPE4AC7NNTD9ADN { txid: '0xd33672dd4dbb0b88f733bc67b938359843123ca3be550ca87d487d067bd1b3c3', transaction: 'https://explorer.hiro.so/txid/0xd33672dd4dbb0b88f733bc67b938359843123ca3be550ca87d487d067bd1b3c3?chain=testnet' } ``` -------------------------------- ### Get Payment Private Key and Addresses Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Retrieve the payment private key from a 12-word backup phrase. This command also provides your Bitcoin (BTC) and Stacks (STX) token addresses. Use the '-t' flag for testnet. ```shell stx get_payment_key "soap fog wealth upon actual blossom neither timber phone exile monkey vocal" [ { "privateKey": "4023435e33da4aff0775f33e7b258f257fb20ecff039c919b5782313ab73afb401", "address": { "BTC": "1ybaP1gaRwRSWRE4f8JXo2W8fiTZmA4rV", "STACKS": "SP5B89ZJAQHBRXVYP15YB5PAY5E24FEW9K4Q63PE" }, "index": 0 } ] ``` -------------------------------- ### Get File from Gaia (Unencrypted) Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Retrieves an unencrypted and unsigned file from a user's Gaia hub. Prints the file data to standard output. ```shell script # Get an unencrypted, unsigned file stx gaia_getfile ryan.id http://public.ykliao.com statuses.json [{"id":0,"text":"Hello, Blockstack!","created_at":1515786983492}] ``` -------------------------------- ### Get BTC and STACKS Addresses from Private Key Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Retrieve the Bitcoin (BTC) and Stacks (STX) addresses associated with a given private key or a multisig private key bundle. Supports both single private keys and comma-separated lists for multisig. ```shell stx get_address f5185b9ca93bdcb5753fded3b097dab8547a8b47d2be578412d0687a9a0184cb01 { "BTC": "1JFhWyVPpZQjbPcXFtpGtTmU22u4fhBVmq", "STACKS": "SP2YM3J4KQK09V670TD6ZZ1XYNYCNGCWCVVKSDFWQ" } stx get_address 1,f5185b9ca93bdcb5753fded3b097dab8547a8b47d2be578412d0687a9a0184cb01,ff2ff4f4e7f8a1979ffad4fc869def1657fd5d48fc9cf40c1924725ead60942c01 { "BTC": "363pKBhc5ipDws1k5181KFf6RSxhBZ7e3p", "STACKS": "SMQWZ30EXVG6XEC1K4QTDP16C1CAWSK1JSWMS0QN" } ``` -------------------------------- ### Get Application Private Key for Gaia Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Derive the application private key from a 12-word backup phrase and a name or ID-address. This key is used for signing data in Gaia. It provides both 'keyInfo' and 'legacyKeyInfo' paths. ```shell export BACKUP_PHRASE="one race buffalo dynamic icon drip width lake extra forest fee kit" stx get_app_keys "$BACKUP_PHRASE" example.id.blockstack https://my.cool.dapp { "keyInfo": { "privateKey": "TODO", "address": "TODO" }, "legacyKeyInfo": { "privateKey": "90f9ec4e13fb9a00243b4c1510075157229bda73076c7c721208c2edca28ea8b", "address": "1Lr8ggSgdmfcb4764woYutUfFqQMjEoKHc" }, "ownerKeyIndex": 0 } ``` -------------------------------- ### Initiate Storage Client Source: https://github.com/stx-labs/stacks.js/blob/main/packages/storage/README.md Initialize a storage client using a UserSession object. Ensure the user is signed in before proceeding. ```typescript import { UserSession, AppConfig } from '@stacks/auth'; import { Storage } from '@stacks/storage'; const privateKey = '896adae13a1bf88db0b2ec94339b62382ec6f34cd7e2ff8abae7ec271e05f9d8'; const appConfig = new AppConfig(); const userSession = new UserSession({ appConfig }); userSession.store.getSessionData().userData = { appPrivateKey: privateKey, }; const storage = new Storage({ userSession }); ``` -------------------------------- ### List all stx commands Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md View all available commands and their general usage. ```bash stx ``` -------------------------------- ### Get Account Balance Source: https://github.com/stx-labs/stacks.js/blob/main/packages/stacking/README.md Retrieves the total STX balance for an account. The balance is returned in microSTX. ```typescript const responseBalanceInfo = await client.getAccountBalance(); // 800000000000 ``` -------------------------------- ### Get Burnchain Rewards Source: https://github.com/stx-labs/stacks.js/blob/main/packages/stacking/README.md Retrieve burnchain rewards for a given Bitcoin address. Requires network configuration and StackingClient initialization. ```typescript import { StacksTestnet, StacksMainnet } from '@stacks/network'; import { StackingClient } from '@stacks/stacking'; const address = 'myfTfju9XSMRusaY2qTitSEMSchsWRA441'; // for mainnet: const network = new StacksMainnet(); const network = new StacksTestnet(); const client = new StackingClient(address, network); const options = { limit: 2, offset: 0 }; const rewards = await client.getRewardsForBtcAddress(options); // { // limit: 2, // offset: 0, // results: [ // { // canonical: true, // burn_block_hash: '0x000000000000002083ca8303a2262d09a824cecb34b78f13a04787e4f05441d3', // burn_block_height: 2004622, // burn_amount: '0', // reward_recipient: 'myfTfju9XSMRusaY2qTitSEMSchsWRA441', // reward_amount: '20000', // reward_index: 0 // }, // { // canonical: true, // burn_block_hash: '0x000000000000002f72213de621f9daf60d76aed3902a811561d06373b2fa6123', // burn_block_height: 2004621, // burn_amount: '0', // reward_recipient: 'myfTfju9XSMRusaY2qTitSEMSchsWRA441', // reward_amount: '20000', // reward_index: 0 // } // ] // }; ``` -------------------------------- ### Initialize Environment Variables Source: https://github.com/stx-labs/stacks.js/blob/main/packages/profile/tests/testData/profiles/larry.verification.address.facebook.html Initializes environment variables, either by using `requireLazy` if available or by directly assigning to `window.Env`. This is useful for setting up application-wide configurations. ```javascript function envFlush(a){function b(c){for(var d in a)c[d]=a[d];}if(window.requireLazy){window.requireLazy(['Env'],b);}else{window.Env=window.Env||{};b(window.Env);}}envFlush({"ajaxpipe_token":"AXgXhbEPiR65jk11","lhsh":"qAQF_LY2-"});__DEV__=0;CavalryLogger=false; ``` -------------------------------- ### Get Stacking Status Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Retrieves the stacking status for a specified Stacks address. Use the -t flag for testnet addresses. ```shell // Use -t option for testnet adddress stx stacking_status SPZY1V53Z4TVRHHW9Z7SFG8CZNRAG7BD8WJ6SXD0 ``` -------------------------------- ### Create Stacks Network Instances Source: https://github.com/stx-labs/stacks.js/blob/main/packages/network/README.md Instantiate network objects for Stacks mainnet, testnet, or mocknet. ```typescript import { StacksMainnet, StacksTestnet, StacksMocknet } from '@stacks/network'; const network = new StacksMainnet(); const testnet = new StacksTestnet(); const mocknet = new StacksMocknet(); ``` -------------------------------- ### List Files Source: https://github.com/stx-labs/stacks.js/blob/main/packages/storage/README.md List all files in the user's Gaia hub and retrieve their content. The iteration can be stopped by returning false from the callback. ```typescript const files: Promise[] = []; const options = { decrypt: false }; await storage.listFiles((filename: string) => { if (filename === 'my_data.json') { files.push(storage.getFile(filename, options)); // return false to stop iterating through files return false; } else { // return true to continue iterating return true; } }); const fileContents = await Promise.all(files); ``` -------------------------------- ### Get Stacking Cycle Duration Source: https://github.com/stx-labs/stacks.js/blob/main/packages/stacking/README.md Retrieves the duration of a single stacking cycle in seconds. This is a constant value for the PoX protocol. ```typescript const cycleDuration = await client.getCycleDuration(); ``` -------------------------------- ### List stx subcommands Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Display a list of available subcommands for the stx CLI. ```bash stx help ``` -------------------------------- ### Get Account Balance Locked Source: https://github.com/stx-labs/stacks.js/blob/main/packages/stacking/README.md Retrieves the amount of STX currently locked for an account, typically for stacking. The balance is returned in microSTX. ```typescript const responseBalanceLockedInfo = await client.getAccountBalanceLocked(); // 40000000000 ``` -------------------------------- ### Get Seconds Until Stacking Deadline Source: https://github.com/stx-labs/stacks.js/blob/main/packages/stacking/README.md Calculates the remaining time in seconds until the deadline for submitting a stacking transaction for the current reward cycle. ```typescript const seconds = await client.getSecondsUntilStackingDeadline(); ``` -------------------------------- ### Get Burnchain Rewards Total Source: https://github.com/stx-labs/stacks.js/blob/main/packages/stacking/README.md Retrieve the total burnchain rewards for a given Bitcoin address. Requires network configuration and StackingClient initialization. ```typescript import { StacksTestnet, StacksMainnet } from '@stacks/network'; import { StackingClient } from '@stacks/stacking'; const address = 'myfTfju9XSMRusaY2qTitSEMSchsWRA441'; // for mainnet: const network = new StacksMainnet(); const network = new StacksTestnet(); const client = new StackingClient(address, network); const total = await client.getRewardsTotalForBtcAddress(); // { // reward_recipient: 'myfTfju9XSMRusaY2qTitSEMSchsWRA441', // reward_amount: '0' // } ``` -------------------------------- ### List Files in Gaia Hub Bucket Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Retrieves a list of all files within a Gaia hub bucket. Requires the private key for the bucket. The output includes each file name and a final count. ```shell export APP_KEY="3ac770e8c3d88b1003bf4a0a148ceb920a6172bdade8e0325a1ed1480ab4fb19" stx gaia_listfiles "https://hub.blockstack.org" "$APP_KEY" ``` -------------------------------- ### Get Account Stacking Status Source: https://github.com/stx-labs/stacks.js/blob/main/packages/stacking/README.md Checks the current stacking status of an account, indicating if it is actively stacking and providing details about the stacking configuration. ```typescript const stackingStatus = await client.getStatus(); // { // stacked: true, // details: { // first_reward_cycle: 18, // lock_period: 10, // unlock_height: 3020, // pox_address: { // version: '00', // hashbytes: '05cf52a44bf3e6829b4f8c221cc675355bf83b7d' // } // } // } ``` -------------------------------- ### TTFT Performance Milestone Recording Source: https://github.com/stx-labs/stacks.js/blob/main/packages/profile/tests/testData/profiles/ken.verification.twitter.html Defines functions to record performance milestones for Time to First Byte (TTFT) and to get the current high-resolution time. ```javascript !function(){function t(t,n){window.ttftData&&!window.ttftData\[t\]&&(window.ttftData\[t\]=n)}function n(){return o?Math.round(w.now()+w.timing.navigationStart):(new Date).getTime()}var w=window.performance,o=w&&w.now;window.ttft||(window.ttft=\{\}),window.ttft.recordMilestone||(window.ttft.recordMilestone=t),window.ttft.now||(window.ttft.now=n)}(); ``` -------------------------------- ### Get STX Address Source: https://github.com/stx-labs/stacks.js/blob/main/packages/wallet-sdk/README.md Retrieves the Stacks (STX) address for a given account on either the testnet or mainnet. Requires the account object and the transaction version. ```typescript import { getStxAddress } from '@stacks/wallet-sdk'; import { TransactionVersion } from '@stacks/transactions'; // get an account from the user's wallet const account = wallet.accounts[0]; const testnetAddress = getStxAddress({ account, transactionVersion: TransactionVersion.Testnet }); const mainnetAddress = getStxAddress({ account, transactionVersion: TransactionVersion.Mainnet }); ``` -------------------------------- ### Dump CLI Documentation Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Outputs the documentation for all available CLI commands in JSON format to standard output. ```shell script stx docs ``` -------------------------------- ### Get File for Other User Source: https://github.com/stx-labs/stacks.js/blob/main/packages/storage/README.md Retrieve public data saved by users other than the one with the active session. The user must have registered a username via BNS. ```typescript // Retrieve public data saved by users other than the one with the active session // User should have registered username via BNS const options = { username: 'yukan.id', // app: 'https://example.org', decrypt: false, }; // Set an additional app property within options to retrieve data for a user as saved by an app hosted at a separate domain const fileContent = await storage.getFile('my_data.json', options); console.log(fileContent); ``` -------------------------------- ### Deploy Clarity Smart Contract Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Deploys a Clarity smart contract to the network. Use the -t flag for testnet. The command outputs a transaction ID upon success. ```shell export PAYMENT="bfeffdf57f29b0cc1fab9ea197bb1413da2561fe4b83e962c7f02fbbe2b1cd5401" stx deploy_contract ./my_contract.clar my_contract 1 0 "$PAYMENT" { txid: '0x2e33ad647a9cedacb718ce247967dc705bc0c878db899fdba5eae2437c6fa1e1', transaction: 'https://explorer.hiro.so/txid/0x2e33ad647a9cedacb718ce247967dc705bc0c878db899fdba5eae2437c6fa1e1' } ``` -------------------------------- ### Get Various Stacks API URLs Source: https://github.com/stx-labs/stacks.js/blob/main/packages/network/README.md Retrieve specific API endpoint URLs from a Stacks network instance for different Stacks blockchain resources. ```typescript const txBroadcastUrl = network.getBroadcastApiUrl(); const feeEstimateUrl = network.getTransferFeeEstimateApiUrl(); const address = 'SP2BS6HD7TN34V8Z5BNF8Q2AW3K8K2DPV4264CF26'; const accountInfoUrl = network.getAccountApiUrl(address); const contractName = 'hello_world'; const abiUrl = network.getAbiApiUrl(address, contractName); const functionName = 'hello'; const readOnlyFunctionCallUrl = network.getReadOnlyFunctionCallApiUrl( address, contractName, functionName ); const nodeInfoUrl = network.getInfoUrl(); const blockTimeUrl = network.getBlockTimeInfoUrl(); const poxInfoUrl = network.getPoxInfoUrl(); ``` -------------------------------- ### Query account balance Source: https://github.com/stx-labs/stacks.js/blob/main/packages/cli/README.md Check the balance of an account for different token types. Balances are returned in the smallest units (e.g., satoshis for BTC, microStacks for Stacks). Use the -t flag for testnet addresses. ```bash stx -t balance ST3PWZ5M026785YW8YKKEH316DYPE4AC7NNTD9ADN { "balance": "499986820", "locked": "0", "unlock_height": 0, "nonce": 2 } ``` -------------------------------- ### Constructing Buffer Clarity Values Source: https://github.com/stx-labs/stacks.js/blob/main/packages/transactions/README.md Create a buffer Clarity value from a Uint8Array using `bufferCV()`. Ensure the input is properly encoded, for example, using `utf8ToBytes`. ```typescript import { bufferCV, } from '@stacks/transactions'; import { utf8ToBytes } from '@stacks/common'; // construct a buffer clarity value from an existing byte array const bytes = utf8ToBytes('foo'); // Uint8Array(3) [ 102, 111, 111 ] const bufCV = bufferCV(bytes); ``` -------------------------------- ### Create and Broadcast Smart Contract Deploy Source: https://github.com/stx-labs/stacks.js/blob/main/packages/transactions/README.md Deploys a smart contract to the Stacks blockchain using provided contract code and sender key. Requires specifying the network and reading contract code from a file. ```typescript import { makeContractDeploy, broadcastTransaction } from '@stacks/transactions'; import { StacksTestnet, StacksMainnet } from '@stacks/network'; import { readFileSync } from 'fs'; // for mainnet, use `StacksMainnet()` const network = new StacksTestnet(); const txOptions = { contractName: 'contract_name', codeBody: readFileSync('/path/to/contract.clar').toString(), senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01', network, }; const transaction = await makeContractDeploy(txOptions); const broadcastResponse = await broadcastTransaction(transaction, network); const txId = broadcastResponse.txid; ``` -------------------------------- ### Import Authentication Utilities Source: https://github.com/stx-labs/stacks.js/blob/main/packages/auth/README.md Import necessary components like UserSession, makeAuthRequest, and AppConfig from the @stacks/auth package for authentication flows. ```typescript import { UserSession, makeAuthRequest, AppConfig } from '@stacks/auth'; ``` -------------------------------- ### Get BNS Name Price Source: https://github.com/stx-labs/stacks.js/blob/main/packages/bns/README.md Use `getNamePrice` to retrieve the registration price of a BNS name in microstacks. Requires a fully qualified name and network configuration. ```typescript import { getNamePrice } from '@stacks/bns'; import { StacksTestnet, StacksMainnet } from '@stacks/network'; // for mainnet, use `StacksMainnet()` const network = new StacksTestnet(); const fullyQualifiedName = 'name.id'; const price = await getNamePrice({ fullyQualifiedName, network }); // price of name registration in microstacks ``` -------------------------------- ### Set Unsupported Browser Message Source: https://github.com/stx-labs/stacks.js/blob/main/packages/profile/tests/testData/profiles/ken.verification.linkedin.html Defines the message displayed to users with unsupported browsers, including a link to learn more. This helps guide users to compatible browsers. ```javascript (function(n, r, a) { r = window[n] = window[n] || {}; r['global_browser_unsupported_notice'] = 'Looks like you\'re using a browser that\'s not supported.