### Install Docker Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/docker/README.md Commands to download and install Docker on a Linux system. ```bash curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh ``` -------------------------------- ### Start the Node.js Express Server Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/README.md Run this command in the root of the generated project directory to start the Express server. Ensure all dependencies are installed via 'npm install'. ```bash npm start ``` -------------------------------- ### Run Server with Database Connectivity Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/docker/README.md Start the container with a specified DATABASE_URL for persistent storage. ```bash sudo docker run -d --env DATABASE_URL=postgres://postgres:trusted@127.0.0.1:15432/wallet -p 3000:80 mainnet/mainnet-rest ``` -------------------------------- ### Start Regtest Environment Source: https://github.com/mainnet-cash/mainnet-js/blob/master/CONTRIBUTING.md Use these commands to manage the regtest environment for testing. Start the environment with `yarn regtest:up` and shut it down with `yarn regtest:down`. ```bash yarn regtest:up ``` ```bash yarn regtest:down ``` -------------------------------- ### Run Server with Let's Encrypt SSL Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/docker/README.md Start the container with automatic SSL certificate generation. Requires a valid domain and root access. ```bash mkdir -p letsencrypt sudo docker run --rm -p 80:80 -p 443:443 -v $(pwd)/letsencrypt:/etc/letsencrypt -e LETSENCRYPT_EMAIL=admin@example.com -e DOMAIN=example.com mainnet/mainnet-rest ``` -------------------------------- ### Run Server with Custom SSL Certificates Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/docker/README.md Start the container using existing certificates placed in a local certs directory. ```bash mkdir -p certs sudo docker run --rm -p 80:80 -p 443:443 -v $(pwd)/certs:/etc/certs mainnet/mainnet-rest ``` -------------------------------- ### Run Server Locally (Unsecured) Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/docker/README.md Start the container for local development without SSL. ```bash sudo docker run --rm -p 3000:80 mainnet/mainnet-rest ``` -------------------------------- ### Start REST API Server Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Commands to initialize the REST API server using Docker or local yarn scripts. ```bash # Start REST server with Docker docker pull mainnet/mainnet-rest docker run -d -p 3000:80 mainnet/mainnet-rest # Or start locally yarn api:serve ``` -------------------------------- ### Install mainnet-js dependency Source: https://github.com/mainnet-cash/mainnet-js/blob/master/README.md Command to add the mainnet-js library to a webapp or Node.js project. ```bash yarn add mainnet-js ``` -------------------------------- ### Run Library Tests Source: https://github.com/mainnet-cash/mainnet-js/blob/master/CONTRIBUTING.md Execute the test suite for the mainnet-js library. This command automatically starts a Docker image with Bitcoin Cash Node and Fulcrum in regtest mode. ```bash yarn test ``` -------------------------------- ### UtxoItem to UtxoI Conversion Example Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt Illustrates the change in return type from `UtxoItem[]` to `UtxoI[]` for methods returning UTXOs. Use `toUtxoId` and `fromUtxoId` for conversion. ```json { "utxos": [ "txId": "abcd", "index": 0, "value": 1000 ] } ``` ```json [ "txid": "abcd", "vout": 0, "satoshis": 1000 ] ``` -------------------------------- ### Get All BCMR Registries Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Retrieve a list of all currently tracked BCMR registries. ```typescript import { BCMR } from "@mainnet-cash/bcmr"; // Get all tracked registries const registries = BCMR.getRegistries(); console.log(registries); ``` -------------------------------- ### Reset BCMR Registries Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Clear all loaded BCMR registries from the system. Use this to start with a clean slate or after testing. ```typescript import { BCMR } from "@mainnet-cash/bcmr"; // Reset all registries BCMR.resetRegistries(); ``` -------------------------------- ### Initialize and Create Wallets Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Demonstrates various methods to instantiate wallets, including random generation, seed phrases, WIF, private keys, and named persistence. ```typescript import { Wallet, TestNetWallet, RegTestWallet, HDWallet, NetworkType } from "mainnet-js"; // Create a new random mainnet wallet const wallet = await Wallet.newRandom(); console.log(wallet.cashaddr); // "bitcoincash:qp..." console.log(wallet.mnemonic); // "abandon abandon ... about" // Create wallet from seed phrase with custom derivation path const seedWallet = await Wallet.fromSeed( "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "m/44'/145'/0'/0/0" ); // Create wallet from WIF (Wallet Import Format) const wifWallet = await Wallet.fromWIF( "L1TnU2zbNaAqMoVh65Cyvmcjzbrj41Gs9iTLcWbpJCMynXuap6UN" ); // Create wallet from private key (hex) const pkWallet = await Wallet.fromPrivateKey( "0c28fca386c7a227600b2fe50b7cae11ec86d3bf1fbe471be89827e19d72aa1d" ); // Create named wallet (persisted to database) const namedWallet = await Wallet.named("my-savings"); // Create testnet wallet const testWallet = await TestNetWallet.newRandom(); // Create HD wallet with automatic address scanning const hdWallet = await HDWallet.fromSeed( "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" ); console.log(hdWallet.depositIndex); // Current deposit address index console.log(hdWallet.getDepositAddress()); // Get current deposit address ``` -------------------------------- ### Manage HD Wallet Operations Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Demonstrates creating an HD wallet from a seed, managing addresses, checking balances, and sending transactions. ```typescript import { HDWallet, TestNetHDWallet } from "mainnet-js"; // Create HD wallet from seed const hdWallet = await HDWallet.fromSeed( "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" ); // Get current addresses console.log(hdWallet.getDepositAddress()); // Current receive address console.log(hdWallet.getChangeAddress()); // Current change address console.log(hdWallet.depositIndex); // Current deposit index console.log(hdWallet.changeIndex); // Current change index // Get balance across all derived addresses const balance = await hdWallet.getBalance(); // Get all UTXOs from all addresses const utxos = await hdWallet.getUtxos(); // Send from HD wallet (automatically selects UTXOs) const response = await hdWallet.send([ { cashaddr: "bitcoincash:qp...", value: 5000n } ]); // Scan more addresses beyond default gap limit await hdWallet.scanMoreAddresses(40); // Scan 40 more addresses // Wait for wallet to update (new deposit or change) await hdWallet.waitForUpdate({ depositIndex: hdWallet.depositIndex + 1, timeout: 60000 }); // Get transaction history across all addresses const history = await hdWallet.getHistory(); // Stop HD wallet (cleanup subscriptions) await hdWallet.stop(); ``` -------------------------------- ### Monitor Wallet Activity with mainnet-js Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Set up real-time watchers for balance changes, new transactions, and token transactions. Includes methods to wait for specific balance thresholds or transactions, and to stop watching subscriptions. ```typescript import { Wallet } from "mainnet-js"; const wallet = await Wallet.fromWIF("cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"); // Watch for balance changes const cancelBalanceWatch = await wallet.watchBalance(async (balance) => { console.log(`New balance: ${balance} satoshis`); }); // Watch for new transactions const cancelTxWatch = await wallet.watchTransactions(async (tx) => { console.log(`New transaction: ${tx.txid}`); console.log(`Confirmations: ${tx.confirmations}`); }); // Watch for token transactions only const cancelTokenWatch = await wallet.watchTokenTransactions(async (tx) => { console.log(`Token transaction: ${tx.txid}`); }); // Wait for specific balance threshold const finalBalance = await wallet.waitForBalance(100000n); console.log(`Balance reached: ${finalBalance}`); // Wait for next transaction const txResponse = await wallet.waitForTransaction({ getTransactionInfo: true, getBalance: true }); console.log(txResponse.transactionInfo); console.log(txResponse.balance); // Watch for new blocks const cancelBlockWatch = await wallet.watchBlocks((header) => { console.log(`New block at height: ${header.height}`); }); // Stop watching (cleanup) await cancelBalanceWatch(); await cancelTxWatch(); await cancelBlockWatch(); // Stop all wallet subscriptions await wallet.stop(); ``` -------------------------------- ### Configure Custom Electrum Servers Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Set custom Electrum servers for mainnet and testnet by modifying `DefaultProvider.servers`. ```typescript import { DefaultProvider } from "mainnet-js"; // Configure custom Electrum servers DefaultProvider.servers.mainnet = ["wss://fulcrum.example.com:50004"]; DefaultProvider.servers.testnet = ["wss://chipnet.imaginary.cash:50004"]; ``` -------------------------------- ### Generate REST client Source: https://github.com/mainnet-cash/mainnet-js/blob/master/README.md Command to generate a client library for a specific language using the project's build script. ```bash yarn api:build:client ``` -------------------------------- ### Configure Default Derivation Path Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Set the default derivation path for newly created wallets using `Config.DefaultParentDerivationPath`. ```typescript import { Config } from "mainnet-js"; // Set default derivation path for new wallets Config.DefaultParentDerivationPath = "m/44'/145'/0'"; ``` -------------------------------- ### Run Individual Tests with Regtest Initialized Source: https://github.com/mainnet-cash/mainnet-js/blob/master/CONTRIBUTING.md When the regtest environment is already running, use this command to skip its initialization and run specific tests. This is useful for speeding up the testing cycle. ```bash SKIP_REGTEST_INIT=1 npx jest packages/mainnet-js/src/rate/ExchangeRate.test.t ``` -------------------------------- ### Run REST service with Docker Source: https://github.com/mainnet-cash/mainnet-js/blob/master/README.md Commands to pull and execute the mainnet-rest service container. ```bash docker pull mainnet/mainnet-rest docker run -d --env WORKERS=5 -p 127.0.0.1:3000:80 mainnet/mainnet-rest ``` -------------------------------- ### Build or Pull Docker Image Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/docker/README.md Build the image locally from the current directory or pull the pre-built image from Docker Hub. ```bash sudo docker build -t mainnet/mainnet-rest . ``` ```bash sudo docker pull mainnet/mainnet-rest ``` -------------------------------- ### Query Wallet Balance and Info Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Retrieves wallet balances in satoshis and fetches metadata including addresses and network configuration. ```typescript import { Wallet, TestNetWallet } from "mainnet-js"; // Get balance of a wallet const wallet = await Wallet.fromWIF("L1TnU2zbNaAqMoVh65Cyvmcjzbrj41Gs9iTLcWbpJCMynXuap6UN"); const balance = await wallet.getBalance(); console.log(`Balance: ${balance} satoshis`); // Balance: 1000000n satoshis (bigint) // Get maximum amount that can be sent (accounts for fees) const maxToSend = await wallet.getMaxAmountToSend(); console.log(`Max sendable: ${maxToSend} satoshis`); // Get wallet info including addresses and keys const info = wallet.getInfo(); console.log(info); // { // cashaddr: "bitcoincash:qp...", // tokenaddr: "bitcoincash:zp...", // network: "mainnet", // seed: "abandon...", // derivationPath: "m/44'/0'/0'/0/0", // publicKeyHash: "...", // walletId: "seed:mainnet:abandon..." // } ``` -------------------------------- ### Parse OpReturnData Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt Demonstrates the usage of `parse` and `parseBinary` methods for the `OpReturnData` class to handle OP_RETURN data. ```javascript const opReturnData = new OpReturnData(); // Use opReturnData.parse() or opReturnData.parseBinary() ``` -------------------------------- ### Build Unsigned Transactions for Watch-Only Wallets Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt Use the `buildUnsigned: true` option to create unsigned transactions. The `unsignedTransaction` will contain an empty unlocking bytecode, and `sourceOutputs` will provide input details for `libauth`. ```javascript const { unsignedTransaction, sourceOutputs } = await watchWallet.send({...}), { buildUnsigned: true }); ``` -------------------------------- ### Configure Browser ESM Initialization Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt Use this pattern to initialize the mainnet-js library in a browser environment after the DOM is loaded, ensuring the asynchronous promise is resolved. ```html ... ... ``` -------------------------------- ### Configure Chipnet Provider Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt Set the testnet provider to connect to the Chipnet network. ```javascript DefaultProvider.servers.testnet = ["wss://chipnet.imaginary.cash:50004"] ``` -------------------------------- ### Configure Chipnet Environment Variable Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt Set the environment variable for REST server connectivity to Chipnet. ```bash export ELECTRUM_TESTNET=wss://chipnet.imaginary.cash:50004 ``` -------------------------------- ### Wallet Creation from Seed Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt When creating a wallet from a seed, whitespace is trimmed and the input is transformed to lowercase. ```javascript const wallet = new Wallet(seed, config); // Whitespace trimmed and input lowercased ``` -------------------------------- ### Generate Self-Signed Certificate Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/docker/README.md Create a self-signed certificate for local testing purposes. ```bash mkdir -p certs openssl req -x509 -newkey rsa:4096 -out certs/fullchain.pem -keyout certs/privkey.pem -nodes -subj '/CN=localhost' ``` -------------------------------- ### Convert Units with mainnet-js Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Utilize the `convert` function for flexible unit conversions between BCH, satoshis, and fiat currencies. Simple synchronous conversions are also available via `toBch`, `toSat`, and `toCurrency`. ```typescript import { convert, toBch, toSat, toCurrency } from "mainnet-js"; // Convert between units const satoshis = await convert(1.5, "bch", "sat"); console.log(satoshis); // 150000000 const bch = await convert(100000000, "sat", "bch"); console.log(bch); // 1 // Simple synchronous conversions const bchValue = toBch(150000000n); console.log(bchValue); // 1.5 const satValue = toSat(1.5); console.log(satValue); // 150000000n // Convert to fiat currency (requires network call) const usdValue = await toCurrency(100000000n, "usd"); console.log(`1 BCH = $${usdValue}`); const eurValue = await convert(1, "bch", "eur"); console.log(`1 BCH = €${eurValue}`); ``` -------------------------------- ### Sign and Verify Messages with mainnet-js Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Sign messages using your wallet's private key and verify them using the public key or cashaddr. Supports standard Bitcoin Cash message signing formats compatible with Electron Cash. ```typescript import { Wallet, SignedMessage } from "mainnet-js"; const wallet = await Wallet.fromWIF("cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"); // Sign a message const signResult = wallet.sign("Hello, Bitcoin Cash!"); console.log(signResult); // { // signature: "H+Lq4...", // Base64-encoded recoverable signature // raw: { // ecdsa: "...", // Raw ECDSA signature // schnorr: "...", // Schnorr signature // der: "..." // DER-encoded signature // }, // details: { // recoveryId: 1, // compressed: true, // messageHash: "..." // } // } // Verify a message with recoverable signature (from cashaddr) const verifyResult = wallet.verify( "Hello, Bitcoin Cash!", signResult.signature, wallet.cashaddr ); console.log(verifyResult); // { // valid: true, // details: { // signatureValid: true, // signatureType: "recoverable", // publicKeyHashMatch: true // } // } // Static method for signing without wallet instance const staticSign = SignedMessage.sign("Test message", wallet.privateKey); // Verify with public key (for non-recoverable signatures) const verifyWithPubkey = SignedMessage.verify( "Test message", staticSign.raw.schnorr, undefined, wallet.publicKey ); ``` -------------------------------- ### Perform Wallet REST API Operations Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt HTTP requests for common wallet tasks like creating wallets, checking balances, and sending funds. ```bash # Create a new wallet curl -X POST http://localhost:3000/wallet/create \ -H "Content-Type: application/json" \ -d '{"type": "seed", "network": "testnet"}' # Response: {"walletId":"seed:testnet:abandon...", "cashaddr":"bchtest:qp...", "seed":"abandon..."} # Get wallet balance curl -X POST http://localhost:3000/wallet/balance \ -H "Content-Type: application/json" \ -d '{"walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"}' # Response: {"sat": "1000000"} # Get deposit address curl -X POST http://localhost:3000/wallet/deposit_address \ -H "Content-Type: application/json" \ -d '{"walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"}' # Response: {"cashaddr": "bchreg:qpttdv3qg2usm4nm7talhxhl05mlhms3ys43u76rn0"} # Send BCH curl -X POST http://localhost:3000/wallet/send \ -H "Content-Type: application/json" \ -d '{ "walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6", "to": [{"cashaddr": "bchreg:qp...", "value": 5000}] }' # Response: {"txId": "abc123...", "balance": "995000"} # Get max amount to send curl -X POST http://localhost:3000/wallet/max_amount_to_send \ -H "Content-Type: application/json" \ -d '{"walletId": "wif:testnet:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"}' # Response: {"sat": "994780"} # Get wallet UTXOs curl -X POST http://localhost:3000/wallet/utxo \ -H "Content-Type: application/json" \ -d '{"walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"}' ``` -------------------------------- ### Configure Caching with mainnet-js Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Control caching behavior by enabling `Config.UseLocalStorageCache`, `Config.UseIndexedDBCache`, or `Config.UseMemoryCache`. ```typescript import { Config } from "mainnet-js"; // Configure caching Config.UseLocalStorageCache = true; // Browser localStorage Config.UseIndexedDBCache = true; // Browser IndexedDB Config.UseMemoryCache = true; // In-memory cache ``` -------------------------------- ### Run Library Tests Without Regtest Initialization Source: https://github.com/mainnet-cash/mainnet-js/blob/master/CONTRIBUTING.md This command runs the library test suite while skipping the initialization of the regtest environment. It's useful when the regtest environment is already up and running. ```bash yarn test:skip ``` -------------------------------- ### Build REST Server from Specification Source: https://github.com/mainnet-cash/mainnet-js/blob/master/CONTRIBUTING.md This command regenerates the REST server stubs and updates data validation based on the OpenAPI specification. Ensure any new files added to the express server are listed in `.openapi-generator-ignore` to prevent them from being reverted. ```bash api:build:server ``` -------------------------------- ### Burn Tokens Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Use this endpoint to burn a specified amount of tokens from a wallet. Ensure the wallet ID and category are correct. ```bash curl -X POST http://localhost:3000/wallet/token_burn \ -H "Content-Type: application/json" \ -d '{ "walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6", "category": "abc123...", "amount": 50 }' ``` -------------------------------- ### Wallet Activity Monitoring Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Methods for subscribing to real-time wallet events and transaction updates. ```APIDOC ## GET wallet.watchBalance() ### Description Registers a callback for balance changes. ## GET wallet.watchTransactions() ### Description Registers a callback for new transactions. ## GET wallet.waitForBalance() ### Description Blocks until a specific balance threshold is reached. ### Parameters - **threshold** (bigint) - Required - The target balance. ``` -------------------------------- ### Add BCMR Registry from URI Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Register token metadata by providing a URI to a BCMR JSON file. An optional content hash can be provided for verification. ```typescript import { BCMR } from "@mainnet-cash/bcmr"; // Add registry from URI await BCMR.addMetadataRegistryFromUri( "https://example.com/registry.json", "abc123..." // Optional content hash for verification ); ``` -------------------------------- ### Build BCMR Authchain Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Construct an authchain for on-chain metadata verification using a transaction hash and network type. The `followToHead` option ensures the chain is traced to its origin. ```typescript import { BCMR } from "@mainnet-cash/bcmr"; // Build authchain for on-chain metadata const authchain = await BCMR.buildAuthChain( "abc123...", // Transaction hash "mainnet", { followToHead: true } ); console.log(authchain); // [{ txHash: "...", contentHash: "...", uris: ["ipfs://..."], httpsUrl: "..." }] ``` -------------------------------- ### Generate Node.js Express Server with OpenAPI Generator Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/README.md Use this command to generate a Node.js Express server from an OpenAPI specification file. Ensure you have Java and the OpenAPI Generator JAR file. ```java java -jar {path_to_jar_file} generate -g nodejs-express-server -i {openapi yaml/json file} -o {target_directory_where_the_app_will_be_installed} ``` -------------------------------- ### Configure Custom Exchange Rate Provider Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Provide a custom function to `Config.GetExchangeRateFn` to fetch exchange rates from an external API. ```typescript import { Config } from "mainnet-js"; // Custom exchange rate provider Config.GetExchangeRateFn = async (symbol: string) => { const response = await fetch(`https://api.example.com/rate/${symbol}`); const data = await response.json(); return data.rate; }; ``` -------------------------------- ### REST API - Wallet Endpoints Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt The REST API provides HTTP endpoints for all wallet operations. Run the server with Docker or yarn. ```APIDOC ## REST API - Wallet Endpoints The REST API provides HTTP endpoints for all wallet operations. Run the server with Docker or yarn. ### Start REST server ```bash # Start REST server with Docker docker pull mainnet/mainnet-rest docker run -d -p 3000:80 mainnet/mainnet-rest # Or start locally yarn api:serve ``` ### Create a new wallet #### Method POST #### Endpoint /wallet/create #### Request Body - **type** (string) - Required - Type of wallet to create (e.g., "seed", "wif"). - **network** (string) - Optional - Network to use (e.g., "mainnet", "testnet", "regtest"). Defaults to "mainnet". #### Response Example ```json { "walletId": "seed:testnet:abandon...", "cashaddr": "bchtest:qp...", "seed": "abandon..." } ``` ### Get wallet balance #### Method POST #### Endpoint /wallet/balance #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. #### Response Example ```json { "sat": "1000000" } ``` ### Get deposit address #### Method POST #### Endpoint /wallet/deposit_address #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. #### Response Example ```json { "cashaddr": "bchreg:qpttdv3qg2usm4nm7talhxhl05mlhms3ys43u76rn0" } ``` ### Send BCH #### Method POST #### Endpoint /wallet/send #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. - **to** (array) - Required - An array of objects specifying recipients and amounts. - **cashaddr** (string) - Required - The recipient's cashaddr. - **value** (number) - Required - The amount to send in satoshis. #### Response Example ```json { "txId": "abc123...", "balance": "995000" } ``` ### Get max amount to send #### Method POST #### Endpoint /wallet/max_amount_to_send #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. #### Response Example ```json { "sat": "994780" } ``` ### Get wallet UTXOs #### Method POST #### Endpoint /wallet/utxo #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. ``` -------------------------------- ### HD Wallet Support Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Hierarchical Deterministic wallets with automatic address scanning and gap limit management. ```APIDOC ## HD Wallet Support Hierarchical Deterministic wallets with automatic address scanning and gap limit management. ### Create HD wallet from seed ```typescript import { HDWallet, TestNetHDWallet } from "mainnet-js"; const hdWallet = await HDWallet.fromSeed( "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" ); ``` ### Get current addresses and indices ```typescript console.log(hdWallet.getDepositAddress()); // Current receive address console.log(hdWallet.getChangeAddress()); // Current change address console.log(hdWallet.depositIndex); // Current deposit index console.log(hdWallet.changeIndex); // Current change index ``` ### Get balance and UTXOs ```typescript const balance = await hdWallet.getBalance(); const utxos = await hdWallet.getUtxos(); ``` ### Send BCH ```typescript const response = await hdWallet.send([ { cashaddr: "bitcoincash:qp...", value: 5000n } ]); ``` ### Scan more addresses ```typescript await hdWallet.scanMoreAddresses(40); // Scan 40 more addresses ``` ### Wait for wallet update ```typescript await hdWallet.waitForUpdate({ depositIndex: hdWallet.depositIndex + 1, timeout: 60000 }); ``` ### Get transaction history ```typescript const history = await hdWallet.getHistory(); ``` ### Stop HD wallet ```typescript await hdWallet.stop(); ``` ``` -------------------------------- ### Set Custom IPFS Gateway Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Configure a custom IPFS gateway for accessing IPFS content by using `Config.setIpfsGateway()`. ```typescript import { Config } from "mainnet-js"; // Set custom IPFS gateway Config.setIpfsGateway("https://cloudflare-ipfs.com/ipfs/"); ``` -------------------------------- ### Perform CashToken REST API Operations Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt HTTP requests for managing CashTokens, including genesis, minting, and balance queries. ```bash # Create new token (genesis) curl -X POST http://localhost:3000/wallet/token_genesis \ -H "Content-Type: application/json" \ -d '{ "walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6", "amount": 1000000, "nft": {"capability": "minting", "commitment": "00"} }' # Response: {"txId": "abc123...", "categories": ["abc123..."]} # Mint new NFTs curl -X POST http://localhost:3000/wallet/token_mint \ -H "Content-Type: application/json" \ -d '{ "walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6", "category": "abc123...", "requests": [ {"nft": {"capability": "none", "commitment": "001"}, "value": 1000}, {"nft": {"capability": "none", "commitment": "002"}, "value": 1000} ] }' # Get token balance curl -X POST http://localhost:3000/wallet/get_token_balance \ -H "Content-Type: application/json" \ -d '{ "walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6", "category": "abc123..." }' # Response: {"balance": 1000000} # Get all token balances curl -X POST http://localhost:3000/wallet/get_all_token_balances \ -H "Content-Type: application/json" \ -d '{"walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"}' # Response: {"abc123...": 1000000, "def456...": 500} # Get token UTXOs curl -X POST http://localhost:3000/wallet/get_token_utxos \ -H "Content-Type: application/json" \ -d '{ "walletId": "wif:regtest:cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6", "category": "abc123..." }' ``` -------------------------------- ### Burn Fungible Tokens and NFTs with mainnet-js Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Use the `tokenBurn()` method to explicitly burn fungible tokens or NFTs. Specify the category, amount for fungible tokens, or NFT commitment details. An optional message can be included in the OP_RETURN. ```typescript import { Wallet, NFTCapability } from "mainnet-js"; const wallet = await Wallet.fromWIF("cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"); const category = "abc123..."; // Burn fungible tokens (partial burn) const burnResponse = await wallet.tokenBurn({ category: category, amount: 50n // Burn 50 fungible tokens }); // Burn all remaining fungible tokens const burnAllResponse = await wallet.tokenBurn({ category: category, amount: await wallet.getTokenBalance(category) }); // Burn specific NFT by commitment const nftBurnResponse = await wallet.tokenBurn({ category: category, nft: { capability: NFTCapability.none, commitment: "nft001" } }); // Burn with optional message in OP_RETURN const burnWithMessage = await wallet.tokenBurn( { category: category, amount: 25n }, "Burning tokens for charity" ); ``` -------------------------------- ### Sending Bitcoin Cash Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Demonstrates sending BCH to single or multiple recipients, including OP_RETURN data, max balance transfers, and building unsigned transactions. ```typescript import { Wallet, SendRequest, OpReturnData } from "mainnet-js"; const wallet = await Wallet.fromWIF("cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"); // Simple send to single recipient const response = await wallet.send([ new SendRequest({ cashaddr: "bitcoincash:qp2xak6h3vms5c8xzg95z26e4g3k4f4sm5qvf3thd2", value: 10000n // 10,000 satoshis }) ]); console.log(response.txId); // Transaction hash console.log(response.balance); // New wallet balance console.log(response.explorerUrl); // Block explorer URL // Send to multiple recipients const multiResponse = await wallet.send([ new SendRequest({ cashaddr: "bitcoincash:qp...", value: 5000n }), new SendRequest({ cashaddr: "bitcoincash:qq...", value: 3000n }), new SendRequest({ cashaddr: "bitcoincash:qr...", value: 2000n }) ]); // Send with OP_RETURN data const opReturnResponse = await wallet.send([ new SendRequest({ cashaddr: "bitcoincash:qp...", value: 1000n }), OpReturnData.fromString("Hello Bitcoin Cash!") ]); // Send maximum available balance const maxResponse = await wallet.sendMax("bitcoincash:qp2xak6h3vms5c8xzg95z26e4g3k4f4sm5qvf3thd2"); // Build unsigned transaction (for watch-only wallets or external signing) const unsignedTx = await wallet.send( [new SendRequest({ cashaddr: "bitcoincash:qp...", value: 1000n })], { buildUnsigned: true } ); console.log(unsignedTx.unsignedTransaction); // Hex-encoded unsigned transaction console.log(unsignedTx.sourceOutputs); // Source outputs for signing ``` -------------------------------- ### Generate QR Code for Bitcoin Cash Address Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt Utility function to convert a cashaddress into a base64-encoded SVG QR code. Requires the qrcode-svg library. ```typescript import QRCode from "qrcode-svg"; /** * qrAddress returns a qr code for a given cashaddress as raw utf-8 svg * @param {string} address * @param {} size=256 The width and height of the returned image * @returns Image */ export function qrAddress(address: string, size = 256) { const svg = new QRCode({ content: address, width: size, height: size, }).svg(); const svgB64 = btoa(svg); return { src: `data:image/svg+xml;base64,${svgB64}`, title: address, alt: "a Bitcoin Cash address QR Code", }; } ``` -------------------------------- ### Validate OpenAPI Specification Source: https://github.com/mainnet-cash/mainnet-js/blob/master/CONTRIBUTING.md Use this command to validate the OpenAPI specification locally. For more advanced validation, consider using a web editor. ```bash yarn api:validate ``` -------------------------------- ### CashTokens Genesis Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Create fungible tokens, NFTs, or hybrid tokens using the tokenGenesis method and verify balances. ```typescript import { Wallet, NFTCapability } from "mainnet-js"; const wallet = await Wallet.fromWIF("cNfsPtqN2bMRS7vH5qd8tR8GMvgXyL5BjnGAKgZ8DYEiCrCCQcP6"); // Create fungible tokens only const ftResponse = await wallet.tokenGenesis({ amount: 1000000n // 1 million fungible tokens }); const category = ftResponse.categories![0]; // Token category (txid of genesis) console.log(`Created token category: ${category}`); // Create NFT with minting capability const nftResponse = await wallet.tokenGenesis({ nft: { capability: NFTCapability.minting, // "none", "mutable", or "minting" commitment: "00112233" // Hex-encoded commitment data }, cashaddr: wallet.getTokenDepositAddress(), // Token-aware address value: 1000n // Satoshi value in the UTXO }); // Create hybrid token (fungible + NFT) const hybridResponse = await wallet.tokenGenesis({ amount: 500000n, nft: { capability: NFTCapability.minting, commitment: "deadbeef" } }); // Check token balances after genesis const ftBalance = await wallet.getTokenBalance(category); console.log(`Fungible token balance: ${ftBalance}`); const nftBalance = await wallet.getNftTokenBalance(category); console.log(`NFT balance: ${nftBalance}`); const allBalances = await wallet.getAllTokenBalances(); console.log(allBalances); // { "category1": 1000n, "category2": 500n, ... } ``` -------------------------------- ### Run Docker Container in Background Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/docker/README.md Use the -d flag to run the container in detached mode. ```bash sudo docker run .... ``` ```bash sudo docker run -d .... ``` -------------------------------- ### REST API - CashToken Endpoints Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt REST endpoints for CashToken operations including genesis, minting, burning, and balance queries. ```APIDOC ## REST API - CashToken Endpoints REST endpoints for CashToken operations including genesis, minting, burning, and balance queries. ### Create new token (genesis) #### Method POST #### Endpoint /wallet/token_genesis #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. - **amount** (number) - Required - The amount of tokens to genesis. - **nft** (object) - Optional - NFT details. - **capability** (string) - Optional - NFT capability (e.g., "minting", "mutable", "none"). - **commitment** (string) - Optional - NFT commitment. #### Response Example ```json { "txId": "abc123...", "categories": ["abc123..."] } ``` ### Mint new NFTs #### Method POST #### Endpoint /wallet/token_mint #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. - **category** (string) - Required - The token category ID. - **requests** (array) - Required - An array of minting requests. - **nft** (object) - Optional - NFT details. - **capability** (string) - Optional - NFT capability (e.g., "minting", "mutable", "none"). - **commitment** (string) - Optional - NFT commitment. - **value** (number) - Required - The amount of tokens to mint. ### Get token balance #### Method POST #### Endpoint /wallet/get_token_balance #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. - **category** (string) - Required - The token category ID. #### Response Example ```json { "balance": 1000000 } ``` ### Get all token balances #### Method POST #### Endpoint /wallet/get_all_token_balances #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. #### Response Example ```json { "abc123...": 1000000, "def456...": 500 } ``` ### Get token UTXOs #### Method POST #### Endpoint /wallet/get_token_utxos #### Parameters #### Request Body - **walletId** (string) - Required - The ID of the wallet. - **category** (string) - Required - The token category ID. ``` -------------------------------- ### Message Signing and Verification Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Cryptographic utilities for signing and verifying messages using Bitcoin Cash standards. ```APIDOC ## POST wallet.sign() ### Description Signs a message using the wallet's private key. ### Method POST ### Request Body - **message** (string) - Required - The text to sign. ## POST wallet.verify() ### Description Verifies a message signature. ### Method POST ### Request Body - **message** (string) - Required - The original message. - **signature** (string) - Required - The signature to verify. - **address** (string) - Required - The signer's address. ``` -------------------------------- ### Vue.js Faucet Application Source: https://github.com/mainnet-cash/mainnet-js/blob/master/packages/mainnet-cash/static/faucet.html This is the main Vue.js component for the faucet application. It handles user interactions, balance display, and API calls to the faucet service. Ensure the mainnet-js library is loaded. ```javascript var vm = new Vue({ el: '#app', data: { balance: 0, cashaddr: "", address: "", faucetCashaddr: "", metamaskError: false, }, template: `

mainnet.cash testnet faucet

BCH testnet

Faucet balances available

  • {{ balance }} tBCH
  • Your wallet will get refilled to 10000 testnet satoshi (BCH), if you have more than that - bad luck

    Requests are limited to one in 15 minutes from the same IP

    There is as well a global rate limit to prevent abuse

     

    Remember to return the tBCH back to the faucet or donate your own tBCH to {{ faucetCashaddr }}

    `, methods: { async fetch(url, body) { fetch(url, { method: "POST", body: JSON.stringify(body), headers: { "Content-type": "application/json; charset=UTF-8" } }).then(response => response.json()) .then((json) => { if (json.code >= 400) { throw new Error(json.message); } alert("Successfully got coins, txid "+(json.txId)); }).catch(error => alert(error)); }, async getBch() { await this.fetch("/faucet/get_testnet_bch", {cashaddr: toCashAddress(this.cashaddr)}); await this.update(); }, async update(first = false) { try { if (first) { const fetchopt = { method: "POST", headers: { "Content-type": "application/json; charset=UTF-8" } }; const result = await fetch("/faucet/get_addresses", fetchopt); const json = await result.json(); if (json.code >= 400) { throw new Error(json.message); } this.faucetCashaddr = json.bchtest; } await Promise.all([ new Promise(async () => { const wallet = await Wallet.fromCashaddr(this.faucetCashaddr); this.balance = await wallet.slpSemiAware().getBalance("bch"); }) ]); } catch (error) { alert(error.message); } } }, mounted: async function () { document.addEventListener("DOMContentLoaded", async (event) => { Object.assign(globalThis, await __mainnetPromise); this.update(true); }); } }); ``` -------------------------------- ### Add BCMR Registry Directly Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Manually add a BCMR registry object to the system. This is useful for testing or when the registry is available locally. ```typescript import { BCMR } from "@mainnet-cash/bcmr"; // Add registry directly BCMR.addMetadataRegistry({ "$schema": "https://cashtokens.org/bcmr-v2.schema.json", version: { major: 1, minor: 0, patch: 0 }, latestRevision: "2024-01-01T00:00:00.000Z", registryIdentity: { name: "My Token Registry" }, identities: { "abc123...": { // Token category "2024-01-01T00:00:00.000Z": { name: "My Token", description: "A cool token", symbol: "MTK", decimals: 8 } } } }); ``` -------------------------------- ### BCMR Metadata Retrieval Source: https://github.com/mainnet-cash/mainnet-js/blob/master/RELEASE_NOTES.txt Shows a more correct way to retrieve BCMR metadata, including adding extra outputs to the token genesis call. ```javascript // Add extra outputs to token genesis call ``` -------------------------------- ### Set Default Currency for Conversions Source: https://context7.com/mainnet-cash/mainnet-js/llms.txt Specify the default currency for unit conversions using `Config.DefaultCurrency`. ```typescript import { Config } from "mainnet-js"; // Set default currency for conversions Config.DefaultCurrency = "eur"; ```