### Installing Dependencies and Building Packages (pnpm) - Shell Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command installs all project dependencies using pnpm and then builds the necessary packages. It's a prerequisite step for running any of the RGB++ SDK examples. ```shell pnpm install && pnpm build:packages ``` -------------------------------- ### Setting Up Environment for xUDT Examples (Shell) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/xudt-on-ckb/README.md This command navigates into the xUDT examples directory and copies the `.env.example` file to `.env`, which is a prerequisite for configuring environment variables required by the project scripts. ```shell cd examples/xudt && cp .env.example .env ``` -------------------------------- ### Installing @rgbpp-sdk/service via pnpm Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet demonstrates how to install the @rgbpp-sdk/service package using the pnpm package manager. pnpm is known for its efficient disk space usage and faster installations due to its content-addressable store. ```bash $ pnpm add @rgbpp-sdk/service ``` -------------------------------- ### Cloning RGB++ SDK Repository - Shell Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/apps/service/README.md This snippet provides commands to clone the rgbpp-sdk repository, install its dependencies using pnpm, and navigate into the service application directory. It's the initial step for local development setup. ```shell $ git clone https://github.com/ckb-cell/rgbpp-sdk.git $ pnpm install $ cd apps/service ``` -------------------------------- ### Copying Environment Configuration File - Shell Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command navigates to the `examples/rgbpp` directory and copies the `.env.example` file to `.env`. This is the first step in configuring the environment variables required for the RGB++ SDK examples. ```shell cd examples/rgbpp && cp .env.example .env ``` -------------------------------- ### Installing RGBPP SDK BTC Module Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Instructions for installing the `@rgbpp-sdk/btc` package using common Node.js package managers. This module is a prerequisite for constructing BTC/RGBPP transactions. ```bash $ npm i @rgbpp-sdk/btc ``` ```bash $ yarn add @rgbpp-sdk/btc ``` ```bash $ pnpm add @rgbpp-sdk/btc ``` -------------------------------- ### Installing @rgbpp-sdk/ckb Package (Bash) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/ckb/README.md This snippet provides the command-line instructions for installing the `@rgbpp-sdk/ckb` package using popular Node.js package managers such as npm, yarn, and pnpm. These commands add the SDK as a dependency to your project. ```bash $ npm i @rgbpp-sdk/ckb # or $ yarn add @rgbpp-sdk/ckb # or $ pnpm add @rgbpp-sdk/ckb ``` -------------------------------- ### Installing @rgbpp-sdk/service via yarn Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet demonstrates how to install the @rgbpp-sdk/service package using the yarn package manager. Yarn is an alternative to npm, often used for faster and more reliable dependency management. ```bash $ yarn add @rgbpp-sdk/service ``` -------------------------------- ### Running RGB++ SDK Service Locally - Shell Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/apps/service/README.md These commands initiate the RGB++ SDK Service in either development (debug) or production environments. `pnpm start:dev` is for active development with features like hot-reloading, while `pnpm start:prod` is for optimized production deployment. ```shell # Debug environment $ pnpm start:dev # Production environment $ pnpm start:prod ``` -------------------------------- ### Launching RGB++ xUDT Assets on BTC - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to launch RGB++ xUDT assets on the BTC network. It requires the `1-prepare-launch.ts` script to have been successfully run and its CKB transaction committed. Upon successful execution, the RGB++ Asset type script arguments will be displayed in the output. ```shell npx tsx xudt/launch/2-launch-rgbpp.ts ``` -------------------------------- ### Installing RGB++ SDK Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/rgbpp/README.md This snippet provides commands to install the RGB++ SDK package using popular Node.js package managers: npm, yarn, or pnpm. Users can choose their preferred tool to add the `rgbpp` dependency to their project. ```Shell $ npm i rgbpp # or $ yarn add rgbpp # or $ pnpm add rgbpp ``` -------------------------------- ### Creating RGB++ Spores with Cluster on BTC (Shell) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to create new RGB++ Spores on the Bitcoin network, leveraging a pre-existing cluster. It requires the `2-create-cluster.ts` script to have been successfully run and its outputs (`clusterId`, `clusterRgbppLockArgs`) to be configured as prerequisites. ```shell npx tsx spore/launch/3-create-spores.ts ``` -------------------------------- ### Example BTC Transaction ID in RGB++ Lock Args Format Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This snippet displays an example of a Bitcoin transaction ID as it appears in RGB++ lock arguments. This format uses the natural byte order, which is different from the reverse byte order typically displayed on block explorers or in Bitcoin Core. ```text 4abc778213bc4da692f93745c2b07410ef2bfaee70417784d4ee8969fb258001 ``` -------------------------------- ### Installing @rgbpp-sdk/service via npm Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet demonstrates how to install the @rgbpp-sdk/service package using the npm package manager. It is a common method for adding dependencies in JavaScript/TypeScript projects. ```bash $ npm i @rgbpp-sdk/service ``` -------------------------------- ### Transferring RGB++ Spore on BTC (Shell) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command initiates the transfer of an RGB++ Spore on the Bitcoin network, utilizing the Queue Service for transaction processing. It facilitates the movement of existing Spores between addresses on BTC. ```shell npx tsx spore/4-transfer-spore.ts ``` -------------------------------- ### Preparing CKB Cell for RGB++ xUDT Launch - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to create an empty CKB RGB++ lock cell. This cell serves as a prerequisite for launching RGB++ xUDT assets on the BTC network. Ensure the CKB private key in the `.env` file is correctly configured before running. ```shell npx tsx xudt/launch/1-prepare-launch.ts ``` -------------------------------- ### Configuring RGB++ SDK Environment Variables - YAML Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This YAML configuration block defines essential environment variables for the RGB++ SDK, including network settings (mainnet/testnet), CKB node and indexer URLs, CKB private key, BTC testnet type, BTC private key, BTC address type, and BTC service URLs and tokens. These parameters are crucial for connecting to the CKB and BTC networks and interacting with the RGB++ services. ```yaml # True for CKB and BTC Mainnet and false for CKB and BTC Testnet, the default value is false IS_MAINNET=false # CKB Variables # The CKB secp256k1 private key whose format is 32bytes hex string with 0x prefix CKB_SECP256K1_PRIVATE_KEY=0x-private-key # CKB node url which should match IS_MAINNET CKB_NODE_URL=https://testnet.ckb.dev/rpc # CKB indexer url which should match IS_MAINNET CKB_INDEXER_URL=https://testnet.ckb.dev/indexer # BTC Variables # The Bitcoin Testnet type including Testnet3 and Signet, default value is Signet # Testnet3: https://mempool.space/testnet # Signet: https://mempool.space/signet BTC_TESTNET_TYPE=Signet # The BTC private key whose format is 32bytes hex string without 0x prefix BTC_PRIVATE_KEY=private-key # The BTC address type to use, available options: P2WPKH or P2TR # The Native Segwit P2WPKH address will be generated with the BTC private key as default # Read more about P2WPKH in BIP141: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#p2wpkh BTC_ADDRESS_TYPE=P2WPKH # The BTC assets api url which should match IS_MAINNET and BTC_TESTNET_TYPE # The BTC Testnet Service url is: https://api.testnet.rgbpp.io # The BTC Signet Service url is: https://api.signet.rgbpp.io VITE_BTC_SERVICE_URL=https://api.signet.rgbpp.io # The BTC assets api token which should match IS_MAINNET and BTC_TESTNET_TYPE # To get an access token, please refer to https://github.com/ckb-cell/rgbpp-sdk/tree/develop/packages/service#get-an-access-token VITE_BTC_SERVICE_TOKEN= # The BTC assets api origin which should match IS_MAINNET and BTC_TESTNET_TYPE VITE_BTC_SERVICE_ORIGIN=https://btc-test.app ``` -------------------------------- ### Transferring All RGB++ xUDT on BTC via Queue Service - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to transfer all available RGB++ xUDT assets on the BTC network using a queue service. This is useful for consolidating or moving an entire balance of xUDT. ```shell npx tsx xudt/btc-transfer-all/1-btc-transfer-all.ts ``` -------------------------------- ### Transferring RGB++ xUDT on BTC via Queue Service - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to transfer RGB++ xUDT assets on the BTC network, utilizing a queue service for transaction processing. This facilitates efficient and reliable asset transfers on Bitcoin. ```shell npx tsx xudt/2-btc-transfer.ts ``` -------------------------------- ### Copying Environment Variables File - Shell Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/apps/service/README.md This command copies the example environment configuration file to the active .env file, which is necessary before updating specific service settings. It's a standard practice for managing application configurations. ```shell $ cp .env.example .env ``` -------------------------------- ### Starting RGB++ SDK Service with PM2 - Shell Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/apps/service/README.md This command uses PM2 to start the compiled RGB++ SDK Service application (`dist/src/main.js`) and assigns it a process name for easy management. PM2 ensures the service runs continuously and can be monitored. ```shell $ pm2 start dist/src/main.js --name rgbpp-sdk-service ``` -------------------------------- ### Installing PM2 Process Manager - Shell Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/apps/service/README.md This command globally installs PM2, a production process manager for Node.js applications. PM2 allows applications to run indefinitely, manage logs, and handle restarts, crucial for robust service deployment. ```shell $ npm install -g pm2 ``` -------------------------------- ### Configuring xUDT Environment Variables (YAML) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/xudt-on-ckb/README.md This YAML configuration block defines essential environment variables for connecting to the CKB network. It includes settings for mainnet/testnet selection, the CKB private key, and URLs for the CKB node and indexer, which are crucial for script execution. ```yaml # True for CKB Mainnet and false for CKB Testnet, the default value is false IS_MAINNET=false # The CKB secp256k1 private key whose format is 32bytes hex string with 0x prefix CKB_SECP256K1_PRIVATE_KEY=0x-private-key # CKB node url which should match IS_MAINNET CKB_NODE_URL=https://testnet.ckb.dev/rpc # CKB indexer url which should match IS_MAINNET CKB_INDEXER_URL=https://testnet.ckb.dev/indexer ``` -------------------------------- ### Leaping RGB++ xUDT from CKB to BTC - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to perform a cross-chain leap of RGB++ xUDT assets from the CKB network to the BTC network. This operation moves the asset's control from CKB to BTC. ```shell npx tsx xudt/1-ckb-leap-btc.ts ``` -------------------------------- ### Distributing RGB++ xUDT Assets on BTC - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to distribute RGB++ xUDT assets on the BTC network. It depends on the successful execution and commitment of transactions from `2-launch-rgbpp.ts`. The `xudtTypeArgs` parameter must be set to the RGB++ Asset type script arguments obtained from the previous launch step. ```shell npx tsx xudt/launch/3-distribute-rgbpp.ts ``` -------------------------------- ### Example BTC Transaction ID in Explorer Display Format Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This snippet illustrates the same Bitcoin transaction ID as it would be displayed on a block explorer or within Bitcoin Core. This format uses the reverse byte order, which is standard for external display and searching purposes. ```text 018025fb6989eed484774170eefa2bef1074b0c24537f992a64dbc138277bc4a ``` -------------------------------- ### Leaping Spore from CKB to BTC (Shell) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command facilitates the cross-chain leap of an RGB++ Spore from the CKB network back to the Bitcoin network. It reverses the previous leap operation, returning the Spore's control to the BTC chain. ```shell npx tsx spore/7-leap-spore-to-btc.ts ``` -------------------------------- ### Leaping RGB++ Spore from BTC to CKB (Shell) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to perform a cross-chain leap of an RGB++ Spore from the Bitcoin network to the CKB network. This process bridges the Spore's ownership and state between the two blockchains. ```shell npx tsx spore/5-leap-spore-to-ckb.ts ``` -------------------------------- ### Running RGB++ SDK Service with Docker Compose - Bash Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/apps/service/README.md This command starts the RGB++ SDK Service using Docker Compose, leveraging the provided `docker-compose.yml` file. Docker Compose orchestrates the service's containers, simplifying deployment and ensuring consistent environments. ```bash $ docker-compose up ``` -------------------------------- ### Issuing xUDT Assets on CKB (Shell) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/xudt-on-ckb/README.md This command executes the TypeScript script `1-issue-xudt.ts` using `npx tsx`, which is responsible for initiating the issuance process of xUDT assets on the CKB blockchain. ```shell npx tsx 1-issue-xudt.ts ``` -------------------------------- ### Leaping RGB++ xUDT from BTC to CKB via Queue Service - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to perform a cross-chain leap of RGB++ xUDT assets from the BTC network back to the CKB network, using a queue service. This operation moves the asset's control from BTC back to CKB. ```shell npx tsx xudt/3-btc-leap-ckb.ts ``` -------------------------------- ### Creating RGB++ Spore Cluster Cells on BTC - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md These commands execute TypeScript scripts to prepare and create an RGB++ Cluster cell on CKB with an RGB++ lock. The first command creates an empty RGB++ lock cell, and the second uses it to create the cluster. Both scripts require the same BTC UTXO and correct `.env` variables. Upon success, the `clusterId` and `cluster rgbpp lock args` will be outputted. ```shell npx tsx spore/launch/1-prepare-cluster.ts ``` ```shell npx tsx spore/launch/2-create-cluster.ts ``` -------------------------------- ### Minting/Transferring xUDT Assets on CKB (Shell) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/xudt-on-ckb/README.md This command runs the TypeScript script `2-transfer-xudt.ts` via `npx tsx`, enabling operations such as minting new xUDT assets or transferring existing ones on the CKB network. ```shell npx tsx 2-transfer-xudt.ts ``` -------------------------------- ### Transferring All RGB++ Asset Balance on BTC with buildRgbppTransferAllTxs (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/rgbpp/README.md This example illustrates how to use `buildRgbppTransferAllTxs` for bulk transfers of an RGB++ asset. It returns a list of transaction groups, each containing a CKB virtual transaction and a BTC isomorphic transaction. Users must sign all generated BTC PSBTs, send the corresponding BTC transactions, and then post all BTC transaction IDs and CKB virtual transaction results to the RGB++ Queue Service. The `summary` object provides an overview of the transfer details. ```TypeScript const { transactions, summary } = await buildRgbppTransferAllTxs({ ckb: { // The type script args of the target RGB++ xUDT xudtTypeArgs, // The collector that collects CKB live cells and transactions collector, // The CKB transaction fee rate, default value is 1100 feeRate, // (Optional) If the asset is compatible xUDT(not standard xUDT), the compatibleXudtTypeScript is required compatibleXudtTypeScript, }, btc: { // The list of BTC addresses to provide RGB++ xUDT assets // All available amounts of the target asset (specified by ckb.xudtTypeArgs) will be included in the transfers // However, if more than 40 cells are bound to the same UTXO, the amounts within those 40 cells are excluded assetAddresses, // The BTC address for paying all the transaction costs, but not provide any RGB++ xUDT assets fromAddress, // The BTC address for receiving all the RGB++ xUDT assets toAddress, // The data source for collecting Bitcoin-related info dataSource, // The public key of sender BTC address, must fill if the fromAddress is a P2TR address fromPubkey, // The map helps find the corresponding public key of a BTC address, // note that you must specify a pubkey for each P2TR address in assetAddresses/fromAddress pubkeyMap, // The BTC address to return change satoshi, default value is fromAddress changeAddress, // The fee rate of the BTC transactions, will use the fastest fee rate if not specified feeRate, }, // True is for BTC and CKB Mainnet, false is for BTC Testnet3/Signet and CKB Testnet isMainnet, }); // Sign BTC PSBTs with all the related BTC key pairs, and convert them to BTC transactions const signedGroups: RgbppTxGroup[] = transactions.map((group) => { const psbt = bitcoin.Psbt.fromHex(group.btc.psbtHex); signPsbt(psbt, keyPair); psbt.finalizeAllInputs(); return { ckbVirtualTxResult: JSON.stringify(group.ckb.virtualTxResult), btcTxHex: psbt.extractTransaction().toHex(), }; }); // Post the transaction groups to the RGB++ Queue Service const sentResult = await sendRgbppTxGroups({ txGroups: signedGroups, btcService: btcSource.service, }); // Review the summary of the transfer console.log(summary); ``` -------------------------------- ### Constructing Isomorphic RGBPP Transactions (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md This example illustrates the construction of an isomorphic RGBPP transaction using sendRgbppUtxos. It integrates a CKB virtual transaction (ckbVirtualTx) and handles paymaster details, commitment, and various optional parameters for managing UTXOs and fees. ```typescript import { sendRgbppUtxos, networkTypeToConfig, DataSource, Collector, NetworkType } from '@rgbpp-sdk/btc'; import { BtcAssetsApi } from '@rgbpp-sdk/service'; const networkType = NetworkType.TESTNET; const config = networkTypeToConfig(networkType); const service = BtcAssetsApi.fromToken('btc_assets_api_url', 'your_token'); const source = new DataSource(service, networkType); const ckbVirtualTx: RawTransaction = { // ... inputs: [ /* RgbppLock cells, and an optional paymaster cell */ ], outputs: [ /* RgbppLock/RgbppTimeLock cells, and an optional change cell */ ], } as any; const ckbCollector = new Collector({ ckbNodeUrl: 'ckb_node_url', ckbIndexerUrl: 'ckb_indexer_url', }); const psbt = await sendRgbppUtxos({ ckbVirtualTx, // a CKB virtual tx containing "L1 -> L1" or "L1 -> L2" action paymaster: { // if paymaster cell was included in the ckbVirtualTx, pay to paymaster address: 'paymaster_btc_address', value: 10000, }, commitment: 'rgbpp_tx_commitment', tos: [ // the address of the generating outputs, optional, default is "from" 'transfer_rgbpp_to_btc_address', ], source, ckbCollector, from: accounts.address, fromPubkey: account.publicKey, // if "from" is a P2TR address, "fromPubkey" is required changeAddress: 'address_to_return_change', // optional, where should the change satoshi be returned to minUtxoSatoshi: config.btcUtxoDustLimit, // optional, default to 1000 on the testnet, 1,0000 on the mainnet rgbppMinUtxoSatoshi: config.rgbppUtxoDustLimit, // optional, default to 546 on both testnet/mainnet onlyConfirmedUtxos: false, // optional, default to false, only confirmed utxos are allowed in the transaction feeRate: 1, // optional, default to 1 on the testnet, and it is a floating number on the mainnet }); ``` -------------------------------- ### Unlocking Spore BTC Time Cells on CKB (Shell) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command manually unlocks mature BTC time cells on the CKB network, which are typically handled by a cron job in the RGB++ Queue service. It is crucial to wait for at least 6 Bitcoin confirmation blocks after a Spore leap from BTC to CKB before executing this command. ```shell npx tsx spore/6-unlock-btc-time-cell.ts ``` -------------------------------- ### Manually Unlocking RGB++ xUDT BTC Time Cells on CKB - Shell/TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/examples/rgbpp/README.md This command executes a TypeScript script to manually unlock mature BTC time cells on CKB, which are typically handled by a cron job in the RGB++ Queue service. It's important to wait at least 6 BTC confirmation blocks after a BTC-to-CKB leap before attempting to unlock these cells. ```shell npx tsx xudt/4-unlock-btc-time.ts ``` -------------------------------- ### Initializing BtcAssetsApi in Browser Environment Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet shows how to initialize the BtcAssetsApi service in a browser environment. It imports the BtcAssetsApi class and uses its static `fromToken` method, providing the service URL and an access token to establish a connection. ```typescript import { BtcAssetsApi } from '@rgbpp-sdk/service'; const service = BtcAssetsApi.fromToken('https://api.testnet.rgbpp.io', 'your_access_token'); ``` -------------------------------- ### Initializing BtcAssetsApi in Node.js Environment Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet demonstrates initializing the BtcAssetsApi service in a Node.js environment. In addition to the service URL and access token, it requires an 'origin' property, which is crucial for verifying the token's corresponding domain and ensuring successful requests. ```typescript import { BtcAssetsApi } from '@rgbpp-sdk/service'; const service = BtcAssetsApi.fromToken('https://api.testnet.rgbpp.io', 'your_access_token', 'https://your_app.origin'); ``` -------------------------------- ### Transferring BTC UTXOs with Predefined Inputs/Outputs (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md This snippet demonstrates how to send Bitcoin UTXOs using the sendUtxos function from @rgbpp-sdk/btc. It shows how to define specific inputs and outputs, including an RGBPP commitment and a fixed-value output, and how to sign and broadcast the resulting PSBT. ```typescript import { sendUtxos, DataSource, NetworkType } from '@rgbpp-sdk/btc'; import { BtcAssetsApi } from '@rgbpp-sdk/service'; const service = BtcAssetsApi.fromToken('btc_assets_api_url', 'your_token'); const source = new DataSource(service, NetworkType.TESTNET); const psbt = await sendUtxos({ inputs: [ { txid: 'txid', vout: 1, value: 546, address: 'btc_address', addressType: AddressType.P2WPKH, scriptPk: 'script_publickey_hex', }, ], outputs: [ { data: Buffer.from('commentment_hex', 'hex'), // RGBPP commitment value: 0, fixed: true, // mark as fixed, so the output.value will not be changed }, { address: 'to_address', value: 546, fixed: true, minUtxoSatoshi: 546, // customize the dust limit of the output }, ], from: account.address, // provide fee to the transaction fromPubkey: account.publicKey, // optional, required if "from" is a P2TR address changeAddress: account.address, // optional, an address to return change, default to "from" onlyConfirmedUtxos: false, // optional, default to false, only confirmed utxos are allowed in the transaction feeRate: 1, // optional, default to 1 on the testnet, and it is a floating number on the mainnet source, }); // Sign & finalize inputs psbt.signAllInputs(account.keyPair); psbt.finalizeAllInputs(); // Broadcast transaction const tx = psbt.extractTransaction(); const res = await service.sendTransaction(tx.toHex()); console.log('txid:', res.txid); ``` -------------------------------- ### Transferring RGB++ Assets on BTC with buildRgbppTransferTx (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/rgbpp/README.md This code demonstrates how to use `buildRgbppTransferTx` to initiate an RGB++ asset transfer on BTC. It generates a CKB virtual transaction and a BTC PSBT, which then needs to be signed with a BTC key pair, sent to the Bitcoin network, and finally posted to the RGB++ Queue Service along with the CKB virtual transaction result to complete the isomorphic CKB transaction. The `ckb` and `btc` parameters define transaction specifics, including addresses, amounts, and fee rates. ```TypeScript const { ckbVirtualTxResult, btcPsbtHex } = await buildRgbppTransferTx({ ckb: { collector, xudtTypeArgs, rgbppLockArgsList, transferAmount, ckbFeeRate, // If the asset is compatible xUDT(not standard xUDT), the compatibleXudtTypeScript is required compatibleXudtTypeScript, }, btc: { fromBtcAddress, toBtcAddress, btcDataSource, fromPubkey, feeRate }, isMainnet, }); // Construct PSBT with btcPsbtHex to sign and send BTC transaction with the BTC key pair const psbt = bitcoin.Psbt.fromHex(btcPsbtHex); psbt.signAllInputs(btcKeyPair); psbt.finalizeAllInputs(); const btcTx = psbt.extractTransaction(); const { txid: btcTxId } = await btcService.sendBtcTransaction(btcTx.toHex()); // Post the BTC txId and ckbVirtualTxResult to the RGB++ Queue Service await btcService.sendRgbppCkbTransaction({ btc_txid: btcTxId, ckb_virtual_result: ckbVirtualTxResult }); ``` -------------------------------- ### Querying Bitcoin Address Balance with BtcAssetsApi Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet illustrates how to query the Bitcoin balance of a specific address using the initialized BtcAssetsApi service. It calls the `getBalance` method with the target address and logs the returned balance details, including satoshi, pending satoshi, and UTXO count, demonstrating basic interaction with the service. ```typescript // Query the balance of an address const res = await service.getBalance('tb1qm06rvrq8jyyckzc5v709u7qpthel9j4d9f7nh3'); console.log(res); // { // address: 'tb1qm06rvrq8jyyckzc5v709u7qpthel9j4d9f7nh3', // satoshi: 72921, // pending_satoshi: 0, // utxo_count: 5 // } ``` -------------------------------- ### Transferring BTC from P2WPKH Address (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Demonstrates how to construct and broadcast a Bitcoin transaction to transfer BTC from a P2WPKH (Pay-to-Witness-Public-Key-Hash) address using the `@rgbpp-sdk/btc` module. It involves initializing a `DataSource` with `BtcAssetsApi`, creating a PSBT, signing inputs with a key pair, and broadcasting the transaction to the network. ```typescript import { sendBtc, DataSource, NetworkType } from '@rgbpp-sdk/btc'; import { BtcAssetsApi } from '@rgbpp-sdk/service'; const service = BtcAssetsApi.fromToken('btc_assets_api_url', 'your_token'); const source = new DataSource(service, NetworkType.TESTNET); const psbt = await sendBtc({ from: account.address, // your P2WPKH address tos: [ { address: 'to_address', // destination btc address value: 1000, // transfer satoshi amount }, ], onlyConfirmedUtxos: false, // optional, default to false, only confirmed utxos are allowed in the transaction feeRate: 1, // optional, default to 1 on the testnet, and it is a floating number on the mainnet source, }); // Sign & finalize inputs psbt.signAllInputs(account.keyPair); psbt.finalizeAllInputs(); // Broadcast transaction const tx = psbt.extractTransaction(); const res = await service.sendTransaction(tx.toHex()); console.log('txid:', res.txid); ``` -------------------------------- ### Configuring RGB++ SDK Service Environment Variables - YML Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/apps/service/README.md This configuration block defines essential environment variables for the RGB++ SDK Service, including network type (testnet/mainnet), Bitcoin testnet type (Testnet3/Signet), CKB RPC URL, BTC service URL, token, and origin. These settings are crucial for connecting to the correct blockchain networks and APIs. ```yml # The network includes testnet and mainnet, the default value is testnet NETWORK=testnet # or mainnet # The Bitcoin Testnet type includs Testnet3 and Signet, the default value is Signet # Testnet3: https://mempool.space/testnet # Signet: https://mempool.space/signet BTC_TESTNET_TYPE=Signet # CKB node url which should match NETWORK CKB_RPC_URL=https://testnet.ckb.dev # The BTC assets api url which should match NETWORK and BTC_TESTNET_TYPE # The BTC Testnet Service url is: https://api.testnet.rgbpp.io # The BTC Signet Service url is: https://api.signet.rgbpp.io BTC_SERVICE_URL=hhttps://api.signet.rgbpp.io # The BTC assets api token which should match NETWORK and BTC_TESTNET_TYPE # To get an access token, please refer to https://github.com/ckb-cell/rgbpp-sdk/tree/develop/packages/service#get-an-access-token BTC_SERVICE_TOKEN= # The BTC assets api origin which should match `BTC_SERVICE_TOKEN` # JWT Debugger: https://jwt.io BTC_SERVICE_ORIGIN=https://btc-test.app ``` -------------------------------- ### Defining BaseApis Interface and Request Options in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet defines the `BaseApis` interface, outlining fundamental API methods like `request`, `post`, `generateToken`, and `init`. It also includes `BaseApiRequestOptions` for configuring API requests with parameters, HTTP method, token requirements, and 404 handling, along with `BtcAssetsApiToken` for token structure. ```typescript interface BaseApis { request(route: string, options?: BaseApiRequestOptions): Promise; post(route: string, options?: BaseApiRequestOptions): Promise; generateToken(): Promise; init(force?: boolean): Promise; } interface BaseApiRequestOptions extends RequestInit { params?: Record; method?: 'GET' | 'POST'; requireToken?: boolean; allow404?: boolean; } interface BtcAssetsApiToken { token: string; } ``` -------------------------------- ### Defining FeesRecommended Interface (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md This interface defines the recommended fee rates for transactions, providing different speed tiers: fastest, half-hour, hour, and a minimum fee. Each property represents a fee rate in a numerical format. ```TypeScript interface FeesRecommended { fastestFee: number; halfHourFee: number; hourFee: number; minimumFee: number; } ``` -------------------------------- ### Defining BtcAssetsApi Class in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet defines the `BtcAssetsApi` class, which extends `BtcAssetsApiBase` and implements `BtcApis` and `RgbppApis`. It includes a static factory method `fromToken` for convenient instantiation using a base URL, token, and optional origin. ```typescript declare class BtcAssetsApi extends BtcAssetsApiBase implements BtcApis, RgbppApis { static fromToken(baseUrl: string, token: string, origin?: string): BtcAssetsApi; } ``` -------------------------------- ### Executing Paymaster Cell Splitting via CLI (Bash) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/ckb/README.md This bash command navigates into the `packages/ckb` directory and executes the `splitCells` script using pnpm. This script, part of the `@rgbpp-sdk/ckb` SDK, is used to split multiple CKB cells, configurable by receiver address, capacity per cell, and the total number of cells. ```bash cd packages/ckb && pnpm splitCells ``` -------------------------------- ### Defining DataSource Interface in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Defines the `DataSource` interface, outlining methods for interacting with a BTC assets API, including fetching UTXOs, outputs, and collecting satoshis for transaction building. ```TypeScript interface DataSource { constructor(service: BtcAssetsApi, networkType: NetworkType): void; getUtxo(hex: string, number: number, requireConfirmed?: boolean): Promise; getOutput(hex: string, number: number, requireConfirmed?: boolean): Promise; getUtxos(address: string, params?: BtcAssetsApiUtxoParams): Promise; collectSatoshi(props: { address: string; targetAmount: number; minUtxoSatoshi?: number; allowInsufficient?: boolean; onlyNonRgbppUtxos?: boolean; onlyConfirmedUtxos?: boolean; noAssetsApiCache?: boolean; internalCacheKey?: string; excludeUtxos?: BaseOutput[]; }): Promise<{ utxos: Utxo[]; satoshi: number; exceedSatoshi: number; }>; } ``` -------------------------------- ### Transferring BTC from P2TR Address (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Illustrates the process of transferring BTC from a P2TR (Pay-to-Taproot) address. This snippet is similar to the P2WPKH transfer but specifically requires the public key (`fromPubkey`) and utilizes `tweakSigner` for signing, which is essential for Taproot addresses. ```typescript import { sendBtc, DataSource, NetworkType } from '@rgbpp-sdk/btc'; import { BtcAssetsApi } from '@rgbpp-sdk/service'; const service = BtcAssetsApi.fromToken('btc_assets_api_url', 'your_token'); const source = new DataSource(service, NetworkType.TESTNET); const psbt = await sendBtc({ from: account.address, // your P2TR address fromPubkey: account.publicKey, // your public key, this is required for P2TR tos: [ { address: 'to_address', // destination btc address value: 1000, // transfer satoshi amount }, ], onlyConfirmedUtxos: false, // optional, default to false, only confirmed utxos are allowed in the transaction feeRate: 1, // optional, default to 1 on the testnet, and it is a floating number on the mainnet source, }); // Create a tweaked signer const tweakedSigner = tweakSigner(account.keyPair, { network, }); // Sign & finalize inputs psbt.signAllInputs(tweakedSigner); psbt.finalizeAllInputs(); // Broadcast transaction const tx = psbt.extractTransaction(); const res = await service.sendTransaction(tx.toHex()); console.log('txid:', res.txid); ``` -------------------------------- ### Generating Virtual CKB Transaction for Spore Leap from BTC to CKB (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/ckb/README.md This snippet defines the `SporeLeapVirtualTxResult` interface, which describes the output of the virtual CKB transaction generation for RGB++ Spore leaping from BTC to CKB. It also includes the `genLeapSporeFromBtcToCkbVirtualTx` function, which generates this transaction, including necessary input/output cells and the RGB++ commitment for the BTC transaction's OP_RETURN. It requires a collector, spore lock arguments, spore type bytes, and a target CKB address, with optional parameters for network, witness size, fee rate, and BTC testnet type. ```TypeScript export interface SporeLeapVirtualTxResult { // CKB raw transaction ckbRawTx: CKBComponents.RawTransaction; // The rgbpp commitment to be inserted into BTC op_return commitment: Hex; // The spore cell from ckb-indexer sporeCell: IndexerCell; // The needPaymasterCell indicates whether a paymaster cell is required needPaymasterCell: boolean; // The sum capacity of the ckb inputs sumInputsCapacity: Hex; } /** * Generate the virtual ckb transaction for leaping spore from BTC to CKB * @param collector The collector that collects CKB live cells and transactions * @param sporeRgbppLockArgs The spore rgbpp cell lock script args whose data structure is: out_index | bitcoin_tx_id * @param sporeTypeBytes The spore type script serialized bytes * @param toCkbAddress The receiver ckb address * @param isMainnet True is for BTC and CKB Mainnet, false is for BTC and CKB Testnet(see btcTestnetType for details about BTC Testnet) * @param witnessLockPlaceholderSize(Optional) The WitnessArgs.lock placeholder bytes array size and the default value is 5000 * @param ckbFeeRate(Optional) The CKB transaction fee rate, default value is 1100 * @param btcTestnetType(Optional) The Bitcoin Testnet type including Testnet3 and Signet, default value is Testnet3 */ export const genLeapSporeFromBtcToCkbVirtualTx = async ({ collector, sporeRgbppLockArgs, sporeTypeBytes, toCkbAddress, isMainnet, witnessLockPlaceholderSize, ckbFeeRate, btcTestnetType }: LeapSporeFromBtcToCkbVirtualTxParams): Promise ``` -------------------------------- ### Defining Output Interface (TypeScript) Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md This interface extends `BaseOutput` by adding the value of the output and its script public key. It represents a more complete view of a transaction output, including its monetary value and locking script. ```TypeScript interface Output extends BaseOutput { value: number; scriptPk: string; } ``` -------------------------------- ### Defining TxBaseOutput Interface in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Defines the `TxBaseOutput` interface, providing common properties for transaction outputs such as `value`, `fixed`, `protected`, and `minUtxoSatoshi`. ```TypeScript interface TxBaseOutput { value: number; fixed?: boolean; protected?: boolean; minUtxoSatoshi?: number; } ``` -------------------------------- ### Defining TxScriptOutput Interface in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Defines the `TxScriptOutput` interface, extending `TxBaseOutput` and adding a `script` property (Buffer), representing a transaction output with a custom script. ```TypeScript interface TxScriptOutput extends TxBaseOutput { script: Buffer; } ``` -------------------------------- ### Defining SendUtxosProps Interface in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Defines the `SendUtxosProps` interface, specifying the properties required for sending transactions using specific UTXOs, including inputs, outputs, data source, and various optional parameters. It also notes experimental properties. ```TypeScript interface SendUtxosProps { inputs: Utxo[]; outputs: InitOutput[]; source: DataSource; from: string; feeRate?: number; fromPubkey?: string; changeAddress?: string; minUtxoSatoshi?: number; onlyConfirmedUtxos?: boolean; excludeUtxos?: BaseOutput[]; // EXPERIMENTAL: the below props are unstable and can be altered at any time skipInputsValidation?: boolean; pubkeyMap?: AddressToPubkeyMap; } ``` -------------------------------- ### Defining SendRgbppUtxosProps Interface in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Defines the `SendRgbppUtxosProps` interface, specifying the properties required for sending RGB++ UTXO transactions, including CKB transaction details, commitment, and various RGB++ specific parameters. It also notes experimental properties. ```TypeScript interface SendRgbppUtxosProps { ckbVirtualTx: RawTransaction; commitment: Hash; tos?: string[]; paymaster?: TxAddressOutput; ckbNodeUrl: string; rgbppLockCodeHash: Hash; rgbppTimeLockCodeHash: Hash; rgbppMinUtxoSatoshi?: number; source: DataSource; from: string; feeRate?: number; fromPubkey?: string; changeAddress?: string; minUtxoSatoshi?: number; onlyConfirmedUtxos?: boolean; excludeUtxos?: BaseOutput[]; // EXPERIMENTAL: the below props are experimental and can be altered at any time pubkeyMap?: AddressToPubkeyMap; } ``` -------------------------------- ### Defining BtcAssetsApiBase Class in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet defines the `BtcAssetsApiBase` class, which serves as a foundational class for `BtcAssetsApi` and implements the `BaseApis` interface, providing common API functionalities. ```typescript declare class BtcAssetsApiBase implements BaseApis {} ``` -------------------------------- ### Defining SendBtcProps Interface in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/btc/README.md Defines the `SendBtcProps` interface, specifying the properties required for sending BTC transactions, including sender, recipients, data source, and optional parameters like fee rate and change address. ```TypeScript interface SendBtcProps { from: string; tos: InitOutput[]; source: DataSource; feeRate?: number; fromPubkey?: string; changeAddress?: string; minUtxoSatoshi?: number; onlyConfirmedUtxos?: boolean; } ``` -------------------------------- ### Defining BtcApis Interface and Bitcoin-related Types in TypeScript Source: https://github.com/rgbplusplus/rgbpp-sdk/blob/develop/packages/service/README.md This snippet defines the `BtcApis` interface, which specifies a comprehensive set of methods for interacting with Bitcoin blockchain data, including retrieving blockchain info, blocks, transactions, UTXOs, and sending transactions. It also includes numerous associated data interfaces like `BtcApiBlockchainInfo`, `BtcApiBlock`, `BtcApiRecommendedFeeRates`, `BtcApiBalance`, `BtcApiUtxo`, and `BtcApiTransaction`, detailing the structure of data returned by these API calls. ```typescript interface BtcApis { getBtcBlockchainInfo(): Promise; getBtcBlockByHash(blockHash: string): Promise; getBtcBlockHeaderByHash(blockHash: string): Promise; getBtcBlockHashByHeight(blockHeight: number): Promise; getBtcBlockTransactionIdsByHash(blockHash: number): Promise; getBtcRecommendedFeeRates(): Promise; getBtcBalance(address: string, params?: BtcApiBalanceParams): Promise; getBtcUtxos(address: string, params?: BtcApiUtxoParams): Promise; getBtcTransactions(address: string, params?: BtcApiTransactionParams): Promise; getBtcTransaction(txId: string): Promise; sendBtcTransaction(txHex: string): Promise; } interface BtcApiBlockchainInfo { chain: string; blocks: number; bestblockhash: number; difficulty: number; mediantime: number; } interface BtcApiBlock { id: string; height: number; version: number; timestamp: number; tx_count: number; size: number; weight: number; merkle_root: string; previousblockhash: string; mediantime: number; nonce: number; bits: number; difficulty: number; } interface BtcApiBlockHash { hash: string; } interface BtcApiBlockHeader { header: string; } interface BtcApiBlockTransactionIds { txids: string[]; } interface BtcApiRecommendedFeeRates { fastestFee: number; halfHourFee: number; hourFee: number; economyFee: number; minimumFee: number; } interface BtcApiBalanceParams { min_satoshi?: number; no_cache?: boolean; } interface BtcApiBalance { address: string; // @deprecated Use available_satoshi instead satoshi: number; total_satoshi: number; available_satoshi: number; pending_satoshi: number; rgbpp_satoshi: number; dust_satoshi: number; utxo_count: number; } interface BtcApiUtxoParams { only_non_rgbpp_utxos?: boolean; only_confirmed?: boolean; min_satoshi?: number; no_cache?: boolean; } interface BtcApiUtxo { txid: string; vout: number; value: number; status: { confirmed: boolean; block_height: number; block_hash: string; block_time: number; }; } interface BtcApiSentTransaction { txid: string; } interface BtcApiTransactionParams { after_txid?: string; } interface BtcApiTransaction { txid: string; version: number; locktime: number; vin: { txid: string; vout: number; prevout: { scriptpubkey: string; scriptpubkey_asm: string; scriptpubkey_type: string; scriptpubkey_address: string; value: number; }; scriptsig: string; scriptsig_asm: string; witness: string[]; is_coinbase: boolean; sequence: number; }[]; vout: { scriptpubkey: string; scriptpubkey_asm: string; scriptpubkey_type: string; scriptpubkey_address: string; value: number; }[]; weight: number; size: number; fee: number; status: { confirmed: boolean; block_height: number; block_hash: string; block_time: number; }; } ```