{"id":28897426,"url":"https://github.com/whisdev/bitcoin-toolbox","last_synced_at":"2026-04-21T16:36:03.427Z","repository":{"id":242709598,"uuid":"810259066","full_name":"whisdev/bitcoin-toolbox","owner":"whisdev","description":"This is Rune ToolBox that provide etching, minting, airdrop, multi-transfer, etc. And also provide ordinal recursive inscription based on PSBT and UTXO model","archived":false,"fork":false,"pushed_at":"2024-08-13T06:09:35.000Z","size":134,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-06-21T06:08:21.293Z","etag":null,"topics":["airdrop","bitcoin","bitcoinjs","etching","minting","psbt","rbf","rune","utxo"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/whisdev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-06-04T10:58:36.000Z","updated_at":"2025-06-10T20:40:35.000Z","dependencies_parsed_at":null,"dependency_job_id":"be04a70a-ae54-4cf0-b7c5-5e8f9dc7ecf7","html_url":"https://github.com/whisdev/bitcoin-toolbox","commit_stats":null,"previous_names":["ptc-bink/bitcoinjs-toolbox","ptc-bink/bitcoin-toolbox","whisdev/bitcoin-toolbox"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/whisdev/bitcoin-toolbox","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whisdev%2Fbitcoin-toolbox","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whisdev%2Fbitcoin-toolbox/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whisdev%2Fbitcoin-toolbox/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whisdev%2Fbitcoin-toolbox/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/whisdev","download_url":"https://codeload.github.com/whisdev/bitcoin-toolbox/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whisdev%2Fbitcoin-toolbox/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32100487,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-21T11:25:29.218Z","status":"ssl_error","status_checked_at":"2026-04-21T11:25:28.499Z","response_time":128,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["airdrop","bitcoin","bitcoinjs","etching","minting","psbt","rbf","rune","utxo"],"created_at":"2025-06-21T06:08:21.424Z","updated_at":"2026-04-21T16:36:03.420Z","avatar_url":"https://github.com/whisdev.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# UTXO Management Project\n\nThis guide provides explaining how to utilize them effectively for managing UTXOs (Unspent Transaction Outputs) in a Bitcoin-based application.\n\n## Scripts Description\n\n\n### `npm run split`\n\n- **Purpose**: Splits a larger UTXO into multiple 546 sats UTXOs. This is useful for transaction privacy and for creating denominations that are easier to split UTXO accurately.\n- **Usage**: Run `npm run split` to divide a large UTXO into small ones according to specified criteria.\n\n### `npm run merge`\n\n- **Purpose**: Designed to merge multiple UTXOs into a single UTXO, which can be beneficial for simplifying wallet management and reducing the cost of future transactions.\n- **Usage**: Execute `npm run merge` to combine several small UTXOs into one.\n\n### `npm run send`\n\n- **Purpose**: Facilitates the sending of Bitcoins from one address to another. This script likely handles the creation and broadcasting of the transaction to the Bitcoin network.\n- **Usage**: Use `npm run send` to specify the details (e.g., recipient's address) and send the UTXO.\n\n## Installation\n\nTo set up and run this project locally, follow these steps:\n\n1. **Clone the Repository**: First, clone this repository to your local machine using:\n   ```bash\n   git clone https://github.com/bitmapers/utxo-management.git\n   ```\n\n2. **Install Dependencies**: Navigate into your project directory and install the required dependencies:\n   ```bash\n   cd utxo-management\n   npm install\n   ```\n\n3. **Setup Environment Variables**: Copy the `.env.example` file to `.env` and fill in the necessary Bitcoin network details and key management options.\n   ```bash\n   cp .env.example .env\n   ```\n\n4. **Run Scripts**: Use the npm run commands listed above to perform different operations like merging, sending, or splitting UTXOs.\n\n## Dependencies\n\n- **External Modules**:\n  - `axios`: For making HTTP requests.\n  - `bip32`, `bip39`: For generating Bitcoin wallet addresses from a hierarchical deterministic (HD) path.\n  - `bitcoinjs-lib`: A library for Bitcoin protocol functions.\n  - `dotenv`: Loads environment variables from a `.env` file.\n  - `ecpair`: Represents an elliptic curve pair.\n  - `tiny-secp256k1`: For elliptic curve cryptography operations.\n\n- **Development Modules**:\n  - `@types/node`: TypeScript type definitions for Node.js.\n  - `ts-node`: TypeScript execution environment and REPL for Node.js.\n  - `typescript`: The TypeScript compiler.\n\n\n## File Structure\nBriefly describe the folder and file structure.\n```plaintext\n/ - Root directory\n|__ /utils - Utility scripts\n   |__ utxo.ts - Fetch UTXOs for a given address.\n   |__ wallet.ts - Represents a Bitcoin wallet functionality.\n|__ config.ts - Configuration including to Bitcoin network.\n|__ index.ts - Main script for executing transactions.\n|__ sendUTXO.ts - Send UTXO to other bitcoin address.\n|__ splitUTXO.ts - Split UTXO into smaller UTXOs with big UTXO.\n|__ mergeUTXO.ts - Merge UTXO into one big UTXO with small UTXOs.\n```\n\n\n## Utils Functions\n\n### Interfaces\n\n- **IUtxo:** Interface for Unspent Transaction Outputs which include:\n  - **txid:** Transaction ID.\n  - **vout:** Output number in the transaction.\n  - **value:** Value of the output in satoshis.\n\n### Functions\n\n#### getScriptPubkey(tx: string, address: string): Promise\u003cstring\u003e\n\nFetches the script pubkey associated with a specific output address in a transaction.\n\n**Parameters:**\n- `tx`: The transaction ID as a string.\n- `address`: The Bitcoin address as a string.\n\n**Returns:** A promise that resolves to the script pubkey as a string.\n\n#### getUtxos(address: string): Promise\u003cIUtxo[]\u003e\n\nRetrieves all UTXOs for a given Bitcoin address.\n\n**Parameters:**\n- `address`: The Bitcoin address as a string.\n\n**Returns:** A promise that resolves to an array of UTXOs.\n\n#### pushBTCpmt(rawtx: any): Promise\u003cstring\u003e\n\nPushes a raw Bitcoin transaction to the network.\n\n**Parameters:**\n- `rawtx`: The raw transaction data.\n\n**Returns:** A promise that resolves to the transaction ID.\n\n#### postData(url: string, json: any, content_type?: string, apikey?: string): Promise\u003cstring | undefined\u003e\n\nGeneral function to send POST requests. Handles error retries related to specific blockchain-related errors.\n\n**Parameters:**\n- `url`: The API endpoint.\n- `json`: The JSON payload for the post request.\n- `content_type`: (Optional) Content type of the request, defaults to `\"text/plain\"`.\n- `apikey`: (Optional) API key for authenticated requests.\n\n**Returns:** A promise that resolves to the response data as a string or undefined in case of specific errors.\n\n### Usage Example\n\n#### Getting UTXOs for a Bitcoin Address\n\n```typescript\nimport { getUtxos } from './path_to_module';\n\nasync function displayUtxos() {\n  const address = 'bitcoin_address_here';\n  const utxos = await getUtxos(address);\n  console.log(utxos);\n}\n\ndisplayUtxos();\n```\n\n#### Pushing a Bitcoin Transaction\n\n```typescript\nimport { pushBTCpmt } from './path_to_module';\n\nasync function sendTransaction() {\n  const rawTransaction = 'raw_transaction_data_here';\n  const txid = await pushBTCpmt(rawTransaction);\n  console.log(`Transaction ID: ${txid}`);\n}\n\nsendTransaction();\n```\n\n\n\n## Calculation Fee Function: `calculateTxFee`\n\n#### Purpose:\n\nCalculates the estimated transaction fee for a given PSBT and fee rate. The fee rate is typically expressed in satoshis per byte.\n\n#### Parameters:\n\n- `psbt` (Bitcoin.Psbt): The partially signed Bitcoin transaction.\n- `feeRate` (number): The fee rate in satoshis per byte.\n\n#### Implementation Details:\n\n1. **Mock Output Script Creation**:\n   - A dummy output script (`MOCK_OUTPUT_SCRIPT`) and value (`MOCK_OUTPUT_VALUE`) are used to mimic a real transaction condition by adding an additional output. This helps in more accurately estimating the size of the final transaction.\n\n2. **Transaction Construction**:\n   - A new Bitcoin transaction is instantiated.\n   - Inputs and their corresponding witness data from the PSBT are added to this new transaction.\n   - All outputs (from the PSBT and the mock output) are added to the transaction.\n\n3. **Size Calculation and Fee Estimation**:\n   - The virtual size of the transaction is calculated. The virtual size is a more accurate measure for fee calculation as it considers the weight of witness data.\n   - The transaction's virtual size is multiplied by the provided fee rate to estimate the fee in satoshis.\n\n#### Returns:\n\n- (number): The calculated transaction fee in satoshis.\n\n### Example Usage\n\n```javascript\nconst feeRate = 1; // 1 satoshi per byte\nconst estimatedFee = calculateTxFee(psbt, feeRate);\nconsole.log(`Estimated Transaction Fee: ${estimatedFee} satoshis`);\n```\n\n\n## Send UTXO Function\n\n`main(sendToAddress: string)`: this asynchronous function takes a single parameter, `sendToAddress`, which is the Bitcoin address where the funds will be sent.\n\n#### Detailed Workflow\n\n1. **Wallet Initialization**\n    - Create an instance of the `Wallet` from the `utils/wallet` module.\n    - Log the wallet's address to the console.\n\n2. **UTXO Retrieval**\n    - Fetch UTXOs (Unspent Transaction Outputs) associated with the wallet’s address using the `getUtxos` function from `utils/utxo`.\n    - Find a suitable UTXO that has a value greater than 10,000 satoshis. If no such UTXO is found, the function throws an error.\n\n3. **PSBT Creation**\n    - Initialize a new PSBT (Partially Signed Bitcoin Transaction) specifying the Bitcoin testnet.\n    - Add the selected UTXO as an input to the PSBT.\n    - Define the transaction outputs:\n        - One output sending the intended amount (UTXO value minus initial fee) to `sendToAddress`.\n        - Another output to send the remaining balance (initial fee minus calculated transaction fee) back to the wallet's address as a change.\n\n4. **Transaction Fee Calculation**\n    - Calculate the transaction fee using the transaction’s virtual size and a predefined testnet fee rate.\n\n5. **Transaction Signing**\n    - Sign the PSBT using the wallet’s private keys.\n\n6. **Transaction Extraction and Broadcast**\n    - Extract the signed transaction from the PSBT.\n    - Convert the transaction to its hexadecimal representation.\n    - Broadcast the transaction to the Bitcoin testnet using the `pushBTCpmt` function.\n\n    \n## Split UTXO Function\n\n`main()`: this asynchronous function with no parameter\n\n#### Detailed Workflow\n\n1. **Create Wallet Instance**: \n   - Instantiate a new wallet, which will autogenerate a new address and keypair.\n\n2. **Fetch UTXOs**:\n   - Retrieve all available UTXOs for the wallet address that have a balance greater than a specified amount (10,000 satoshis in this script).\n\n3. **Transaction Construction**:\n   - Create a new `Psbt` (Partially Signed Bitcoin Transaction).\n   - Add inputs and outputs to the `Psbt`. Each output sends a fixed amount (546 satoshis in this example) to the wallet address.\n   - Calculate and subtract the transaction fees and send the remaining balance back to the wallet address.\n\n4. **Signing the Transaction**:\n   - The transaction is signed using the wallet's private key.\n\n5. **Broadcast Transaction**:\n   - The transaction, once signed, is converted to hexadecimal format and broadcasted to the network, returning a transaction ID.\n\n\n\n## Merge UTXO Function\n\n`main()`: this asynchronous function with no parameter\n\n#### Detailed Workflow\n\n1. **Initialize Wallet**:\n   - Creates a new wallet instance which will be used to gather UTXOs and sign the transaction.\n   \n2. **Fetch UTXOs**:\n   - Calls `getUtxos` to retrieve UTXOs for the wallet address.\n\n3. **Prepare Partially Signed Bitcoin Transaction (PSBT)**:\n   - Initializes a PSBT object specific to the Bitcoin testnet.\n   - Adds inputs for each retrieved UTXO including the necessary details like wallet public key for taproot spend.\n\n4. **Calculate Transaction Fee**:\n   - Uses a mock output and fee rate to calculate an appropriate transaction fee based on the virtual size of the transaction.\n\n5. **Add Output**:\n   - Adds an output to the transaction, subtracting the calculated fee from the total input value to set the output value.\n\n6. **Sign PSBT**:\n   - The wallet signs the PSBT.\n\n7. **Broadcast Transaction**:\n   - Extracts the full transaction from PSBT, converts it to hexadecimal, and pushes it to the Bitcoin testnet using `pushBTCpmt`.\n   \n\n# Conclusion\n\nThe UTXO Management Project is designed to provide a comprehensive suite of utilities to facilitate efficient handling of Bitcoin transactions, ideally suited for developers and organizations involved in cryptocurrency management. By utilizing the `split`, `merge`, and `send` scripts, users can optimize their transaction processes, whether for enhancing privacy, simplifying wallet management, or executing precise fund transfers.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwhisdev%2Fbitcoin-toolbox","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwhisdev%2Fbitcoin-toolbox","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwhisdev%2Fbitcoin-toolbox/lists"}