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:
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 */asyncfunctiongetUTXOs( addresses:string[], rpcUrl:string, requiredAmount:bigint):Promise<UTXO[]> {// Initialize the provider for the OP_NET RPCconstprovider=newOPNetLimitedProvider(rpcUrl);// Specify UTXO fetching settingsconstutxoSetting: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 addressesconstutxos=awaitprovider.fetchUTXOMultiAddr(utxoSetting);// Handle case where no UTXOs are foundif (!utxos.length) {thrownewError("No UTXOs found"); }return utxos; // Return the UTXOs that meet the criteria}// Example usage:asyncfunctionmain() {constwalletWif="your-wallet-private-key-in-wif-format"; // Replace with your WIF private keyconstnetwork=bitcoinjs.networks.regtest; // Define the Bitcoin network (e.g., regtest, mainnet)constwalletGet=Wallet.fromWif(walletWif, network); // Import wallet using WIF formatconstrpcUrl="https://regtest.opnet.org"; // Define the OP_NET RPC URLconstrequiredAmount=100_000n; // Define the required amount of satoshis for the transaction// Fetch UTXOs for the wallet addresses and log the resultsconstutxos=awaitgetUTXOs(walletGet.addresses, rpcUrl, requiredAmount); // Pass wallet addressesconsole.log(utxos);}main();