Fetching UTXOs on OP_NET

On OP_NET, every transaction requires UTXOs (Unspent Transaction Outputs) as inputs. UTXOs represent the leftover outputs from previous transactions that can be used in new transactions. Fetching these UTXOs is essential when sending tokens or interacting with smart contracts on the OP_NET metaprotocol.


Step 1: Install Required Packages

Ensure you have the following dependencies installed in your project:

npm install opnet bitcoinjs-lib
# or
yarn add opnet bitcoinjs-lib

Step 2: Fetch UTXOs

Here's an example of how to fetch UTXOs for a wallet address:

import {
  FetchUTXOParamsMultiAddress,
  OPNetLimitedProvider,
  Wallet,
} from "@btc-vision/transaction";
import * as bitcoinjs from "bitcoinjs-lib";
import { UTXO } from "opnet";

/**
 * Fetch UTXOs for multiple addresses
 *
 * @param addresses The array of Bitcoin addresses to fetch UTXOs for
 * @param rpcUrl The OP_NET RPC you're interacting with (e.g., regtest, testnet)
 * @param requiredAmount The minimum amount of Bitcoin required for the transaction
 * @returns UTXOs that meet or exceed the required amount
 */
async function getUTXOs(
  addresses: string[],
  rpcUrl: string,
  requiredAmount: bigint
): Promise<UTXO[]> {
  // Initialize the provider for the OP_NET RPC
  const provider = new OPNetLimitedProvider(rpcUrl);

  // Specify UTXO fetching settings
  const utxoSetting: FetchUTXOParamsMultiAddress = {
    addresses, // Array of Bitcoin addresses
    minAmount: 20_000n, // Minimum UTXO value to consider (satoshis)
    requestedAmount: requiredAmount, // The amount of UTXOs required for the transaction
    optimized: true, // Optimize UTXO selection for efficiency
  };

  // Fetch UTXOs for the provided wallet addresses
  const utxos = await provider.fetchUTXOMultiAddr(utxoSetting);

  // Handle case where no UTXOs are found
  if (!utxos.length) {
    throw new Error("No UTXOs found");
  }

  return utxos; // Return the UTXOs that meet the criteria
}

// Example usage:
async function main() {
  const walletWif = "your-wallet-private-key-in-wif-format"; // Replace with your WIF private key
  const network = bitcoinjs.networks.regtest; // Define the Bitcoin network (e.g., regtest, mainnet)
  const walletGet = Wallet.fromWif(walletWif, network); // Import wallet using WIF format
  const rpcUrl = "https://regtest.opnet.org"; // Define the OP_NET RPC URL
  const requiredAmount = 100_000n; // Define the required amount of satoshis for the transaction

  // Fetch UTXOs for the wallet addresses and log the results
  const utxos = await getUTXOs(walletGet.addresses, rpcUrl, requiredAmount); // Pass wallet addresses
  console.log(utxos);
}

main();

Last updated