Skip to main content

ElementsRpc

Struct ElementsRpc 

Source
pub struct ElementsRpc { /* private fields */ }
Expand description

Elements RPC client for blockchain operations

Implementations§

Source§

impl ElementsRpc

Source

pub fn new(url: String, username: String, password: String) -> Self

Creates a new ElementsRpc client with connection parameters

§Arguments
  • url - The RPC endpoint URL (e.g., http://localhost:18884)
  • username - RPC authentication username
  • password - RPC authentication password
§Examples
use amp_rs::ElementsRpc;

let rpc = ElementsRpc::new(
    "http://localhost:18884".to_string(),
    "user".to_string(),
    "pass".to_string()
);
§Panics

Panics if the HTTP client cannot be created.

Source

pub fn from_env() -> Result<Self, AmpError>

Creates a new ElementsRpc client from environment variables

Expected environment variables:

  • ELEMENTS_RPC_URL: RPC endpoint URL
  • ELEMENTS_RPC_USER: RPC username
  • ELEMENTS_RPC_PASSWORD: RPC password
§Errors

Returns an error if any required environment variable is missing

§Examples
use amp_rs::ElementsRpc;

let rpc = ElementsRpc::from_env().unwrap();
Source

pub async fn get_network_info(&self) -> Result<NetworkInfo, AmpError>

Retrieves network information from the Elements node

§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let network_info = rpc.get_network_info().await?;
println!("Node version: {}", network_info.version);
Source

pub async fn get_blockchain_info(&self) -> Result<BlockchainInfo, AmpError>

Retrieves blockchain information from the Elements node

§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let blockchain_info = rpc.get_blockchain_info().await?;
println!("Current block height: {}", blockchain_info.blocks);
Source

pub async fn wallet_passphrase( &self, passphrase: &str, timeout: u64, ) -> Result<(), AmpError>

Unlocks the wallet with a passphrase for the specified timeout

§Arguments
  • passphrase - The wallet passphrase
  • timeout - Timeout in seconds for the unlock
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.wallet_passphrase("my_passphrase", 300).await?;
Source

pub async fn validate_connection(&self) -> Result<(), AmpError>

Validates the connection to the Elements node

This method performs basic connectivity and authentication checks by retrieving network information from the node.

§Errors

Returns an error if the connection validation fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.validate_connection().await?;
println!("Connection to Elements node is valid");
Source

pub async fn get_node_status( &self, ) -> Result<(NetworkInfo, BlockchainInfo), AmpError>

Retrieves comprehensive node status including network and blockchain information

This method combines network and blockchain information to provide a complete status overview of the Elements node.

§Errors

Returns an error if any RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let (network_info, blockchain_info) = rpc.get_node_status().await?;
println!("Node version: {}, Block height: {}", network_info.version, blockchain_info.blocks);
Source

pub async fn list_unspent( &self, asset_id: Option<&str>, ) -> Result<Vec<Unspent>, AmpError>

Lists unspent transaction outputs (UTXOs) for a specific asset

§Arguments
  • asset_id - Optional asset ID to filter UTXOs. If None, returns all UTXOs
§Errors

Returns an error if the RPC call fails

§Panics

May panic if asset_id is Some but the warning log message attempts to unwrap it. This is a known logging issue and does not affect normal operation.

§Examples
let rpc = ElementsRpc::from_env()?;
let utxos = rpc.list_unspent(Some("asset_id_hex")).await?;
println!("Found {} UTXOs", utxos.len());
Source

pub async fn list_unspent_for_wallet( &self, wallet_name: &str, asset_id: Option<&str>, ) -> Result<Vec<Unspent>, AmpError>

List unspent outputs for a specific wallet

This method lists unspent transaction outputs (UTXOs) for a specific wallet, optionally filtered by asset ID.

§Arguments
  • wallet_name - Name of the Elements wallet to query
  • asset_id - Optional asset ID to filter UTXOs by
§Returns

Returns a vector of unspent outputs

§Errors

Returns an error if the RPC call fails or the wallet cannot be loaded

§Panics

May panic when processing UTXO blinding data if scriptpubkey is unexpectedly missing. This should not occur under normal operation with valid Elements node responses.

§Example
let rpc = ElementsRpc::from_env()?;
// Note: This would need to be called in an async context
// let utxos = rpc.list_unspent_for_wallet("test_wallet", None).await?;
// println!("Found {} UTXOs", utxos.len());
Source

pub async fn create_raw_transaction( &self, inputs: Vec<TxInput>, outputs: HashMap<String, f64>, assets: HashMap<String, String>, ) -> Result<String, AmpError>

Creates a raw transaction with the specified inputs and outputs

§Arguments
  • inputs - Vector of transaction inputs (UTXOs to spend)
  • outputs - Map of addresses to amounts for regular outputs
  • assets - Map of addresses to asset IDs for Liquid-specific outputs
§Errors

Returns an error if the RPC call fails or transaction creation fails

§Examples
let rpc = ElementsRpc::from_env()?;
let inputs = vec![TxInput {
    txid: "abc123".to_string(),
    vout: 0,
    sequence: None,
}];
let mut outputs = HashMap::new();
outputs.insert("address1".to_string(), 100.0);
let mut assets = HashMap::new();
assets.insert("address1".to_string(), "asset_id".to_string());
let raw_tx = rpc.create_raw_transaction(inputs, outputs, assets).await?;
Source

pub async fn import_address( &self, wallet_name: &str, address: &str, label: Option<&str>, rescan: Option<bool>, ) -> Result<(), AmpError>

Imports an address into a specific wallet as watch-only

§Arguments
  • wallet_name - Name of the wallet
  • address - The address to import
  • label - Optional label for the address
  • rescan - Optional whether to rescan the blockchain (default: false)
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.import_address("my_wallet", "vjU8L4dKa1XyyVcPqKBbTgjT1tRC7qYp5VJGwndZSCFk4ntpWey1pQe6hcSGDMVurr9CsZ21EGsqGjWA", Some("test_address"), Some(false)).await?;
Source

pub async fn rescan_blockchain( &self, wallet_name: &str, start_height: Option<u64>, ) -> Result<Value, AmpError>

Rescans the blockchain for a wallet

§Arguments
  • wallet_name - Name of the wallet to rescan
  • start_height - Optional start height for rescan (default: 0)
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let result = rpc.rescan_blockchain("my_wallet", None).await?;
Source

pub async fn create_wallet( &self, wallet_name: &str, disable_private_keys: bool, ) -> Result<(), AmpError>

Creates or loads a wallet

§Arguments
  • wallet_name - Name of the wallet to create or load
  • disable_private_keys - Whether to disable private keys (watch-only wallet)
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.create_wallet("test_wallet", true).await?;
Source

pub async fn load_wallet(&self, wallet_name: &str) -> Result<(), AmpError>

Loads an existing wallet

§Arguments
  • wallet_name - Name of the wallet to load
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.load_wallet("test_wallet").await?;
Source

pub async fn unload_wallet(&self, wallet_name: &str) -> Result<(), AmpError>

Unloads a wallet

§Arguments
  • wallet_name - Name of the wallet to unload
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.unload_wallet("test_wallet").await?;
Source

pub async fn list_wallets(&self) -> Result<Vec<String>, AmpError>

Lists all available wallets

§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let wallets = rpc.list_wallets().await?;
println!("Available wallets: {:?}", wallets);
Source

pub async fn setup_watch_only_wallet( &self, wallet_name: &str, address: &str, label: Option<&str>, ) -> Result<(), AmpError>

Sets up a watch-only wallet with the given address

This is a convenience method that creates a watch-only wallet and imports the address

§Arguments
  • wallet_name - Name of the wallet to create
  • address - Address to import as watch-only
  • label - Optional label for the address
§Errors

Returns an error if wallet creation or address import fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.setup_watch_only_wallet("test_wallet", "vjU8L4dKa1XyyVcPqKBbTgjT1tRC7qYp5VJGwndZSCFk4ntpWey1pQe6hcSGDMVurr9CsZ21EGsqGjWA", Some("treasury")).await?;
Source

pub async fn send_raw_transaction(&self, hex: &str) -> Result<String, AmpError>

Broadcasts a signed raw transaction to the network

§Arguments
  • hex - The signed transaction in hexadecimal format
§Errors

Returns an error if the RPC call fails or transaction broadcast fails

§Examples
let rpc = ElementsRpc::from_env()?;
let signed_tx_hex = "0200000000..."; // Signed transaction hex
let txid = rpc.send_raw_transaction(signed_tx_hex).await?;
println!("Transaction broadcast with ID: {}", txid);
Source

pub async fn get_transaction( &self, txid: &str, ) -> Result<TransactionDetail, AmpError>

Retrieves detailed information about a transaction

§Arguments
  • txid - The transaction ID to retrieve
§Errors

Returns an error if the RPC call fails or transaction is not found

§Examples
let rpc = ElementsRpc::from_env()?;
let tx_detail = rpc.get_transaction("abc123...").await?;
println!("Transaction has {} confirmations", tx_detail.confirmations);
Source

pub async fn sendmany( &self, wallet_name: &str, address_amounts: HashMap<String, f64>, asset_amounts: HashMap<String, String>, min_conf: Option<u32>, comment: Option<&str>, subtract_fee_from: Option<Vec<String>>, replaceable: Option<bool>, conf_target: Option<u32>, estimate_mode: Option<&str>, ) -> Result<String, AmpError>

Sends multiple outputs to multiple addresses using Elements’ sendmany RPC

This method uses Elements’ built-in sendmany command which properly handles confidential transactions and blinding. This is the recommended approach for asset distribution as it avoids manual transaction construction issues.

§Arguments
  • wallet_name - Name of the Elements wallet to use
  • address_amounts - Map of addresses to amounts to send
  • asset_amounts - Map of addresses to asset IDs for each output
  • min_conf - Minimum confirmations for inputs (default: 1)
  • comment - Optional transaction comment
  • subtract_fee_from - Optional addresses to subtract fees from
  • replaceable - Whether transaction is replaceable (default: false)
  • conf_target - Confirmation target for fee estimation (default: 1)
  • estimate_mode - Fee estimation mode (default: “UNSET”)
§Returns

Returns the transaction ID of the sent transaction

§Errors

Returns an error if the RPC call fails or transaction creation fails

§Examples
let rpc = ElementsRpc::from_env()?;

let mut address_amounts = HashMap::new();
address_amounts.insert("address1".to_string(), 100.0);
address_amounts.insert("address2".to_string(), 50.0);

let mut asset_amounts = HashMap::new();
asset_amounts.insert("address1".to_string(), "asset_id_hex".to_string());
asset_amounts.insert("address2".to_string(), "asset_id_hex".to_string());

let txid = rpc.sendmany("wallet_name", address_amounts, asset_amounts, None, None, None, None, None, None).await?;
println!("Transaction sent with ID: {}", txid);
Source

pub async fn wait_for_confirmations( &self, txid: &str, min_confirmations: Option<u32>, timeout_minutes: Option<u64>, ) -> Result<TransactionDetail, AmpError>

Waits for blockchain confirmations with configurable timeout

This method polls the blockchain every 15 seconds to check for transaction confirmations. It waits for a minimum number of confirmations (default 2) before returning successfully. The method includes a configurable timeout to prevent indefinite waiting.

§Arguments
  • txid - The transaction ID to monitor for confirmations
  • min_confirmations - Minimum number of confirmations required (default: 2)
  • timeout_minutes - Timeout in minutes (default: 10)
§Returns

Returns the final TransactionDetail when sufficient confirmations are reached

§Errors

Returns AmpError::Timeout if the timeout is exceeded before confirmations are received Returns AmpError::Rpc if there are issues communicating with the Elements node

§Examples
let rpc = ElementsRpc::from_env()?;
let tx_detail = rpc.wait_for_confirmations("abc123...", Some(2), Some(10)).await?;
println!("Transaction confirmed with {} confirmations", tx_detail.confirmations);
Source

pub async fn wait_for_confirmations_with_interval( &self, txid: &str, min_confirmations: Option<u32>, timeout_minutes: Option<u64>, poll_interval_secs: Option<u64>, ) -> Result<TransactionDetail, AmpError>

Internal method for waiting for confirmations with configurable poll interval This is primarily used for testing to avoid long waits

§Errors

Returns an error if:

  • The timeout is exceeded before confirmations are received
  • There are issues communicating with the Elements node
  • The transaction cannot be found or is invalid
Source

pub async fn reissueasset( &self, asset_id: &str, amount: f64, ) -> Result<Value, AmpError>

Reissues an asset using the Elements RPC reissueasset command

This method reissues the specified amount of an asset. It requires the asset to be reissuable and the reissuance token to be available.

§Arguments
  • asset_id - The asset ID (hex string) to reissue
  • amount - The amount to reissue (in satoshis for the asset)
§Returns

Returns a JSON value containing the reissuance output with txid and vin fields

§Errors

Returns an error if:

  • The asset ID is invalid
  • The asset is not reissuable
  • The reissuance token is not available
  • The RPC call fails
§Examples
let rpc = ElementsRpc::from_env()?;
let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
let amount = 1000000.0; // 0.01 of an asset with 8 decimals
let result = rpc.reissueasset(asset_id, amount).await?;
println!("Reissuance txid: {}, vin: {}", result["txid"], result["vin"]);
Source

pub async fn list_issuances( &self, asset_id: Option<&str>, ) -> Result<Vec<Value>, AmpError>

Lists all issuances for a specific asset or all assets

This method retrieves issuance information including initial issuances and reissuances. If an asset_id is provided, only issuances for that asset are returned.

§Arguments
  • asset_id - Optional asset ID to filter issuances by. If None, returns all issuances
§Returns

Returns a vector of JSON values, each containing issuance information

§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
let issuances = rpc.list_issuances(Some(asset_id)).await?;
for issuance in issuances {
    if let Some(is_reissuance) = issuance.get("isreissuance").and_then(|v| v.as_bool()) {
        println!("Reissuance: {}", is_reissuance);
    }
}
Source

pub async fn destroyamount( &self, asset_id: &str, amount: f64, ) -> Result<String, AmpError>

Destroys (burns) a specific amount of an asset

This method calls the Elements node’s destroyamount RPC to permanently remove (burn) a specified amount of an asset from the wallet.

§Arguments
  • asset_id - The asset ID to burn
  • amount - The amount to burn (as a floating point number)
§Returns

Returns a JSON value containing the transaction ID of the burn transaction

§Errors

Returns an error if the RPC call fails or if insufficient balance exists

§Examples
let rpc = ElementsRpc::from_env()?;
let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";
let amount = 1000.0; // Burn 1000 units

let txid = rpc.destroyamount(asset_id, amount).await?;
println!("Burn transaction created: {}", txid);
Source

pub async fn get_balance( &self, asset_id: Option<&str>, ) -> Result<Value, AmpError>

Gets the balance for all assets or a specific asset

This method calls the Elements node’s getbalance RPC to retrieve the wallet balance. If an asset_id is provided, returns the balance for that specific asset. If None, returns balances for all assets.

§Arguments
  • asset_id - Optional asset ID to get balance for. If None, returns all asset balances
§Returns

Returns a JSON value containing asset balances (as a map of asset_id -> balance)

§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let asset_id = "6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d";

let balances = rpc.get_balance(None).await?;
if let Some(balance) = balances.get(asset_id) {
    println!("Balance for asset {}: {}", asset_id, balance);
}
Source

pub async fn select_utxos_for_amount( &self, wallet_name: &str, asset_id: &str, target_amount: f64, estimated_fee: f64, ) -> Result<(Vec<Unspent>, f64), AmpError>

Selects appropriate UTXOs to cover the required amount plus fees

This method implements a simple UTXO selection algorithm that:

  1. Filters UTXOs by asset ID and spendability
  2. Sorts UTXOs by amount (largest first) for efficiency
  3. Selects UTXOs until the target amount plus estimated fees is covered
§Arguments
  • asset_id - The asset ID to select UTXOs for
  • target_amount - The total amount needed for distribution
  • estimated_fee - Estimated transaction fee in the same asset
§Returns

Returns a tuple of (selected_utxos, total_selected_amount)

§Errors

Returns an error if insufficient UTXOs are available or RPC calls fail

§Examples
let rpc = ElementsRpc::from_env()?;
let (selected_utxos, total_amount) = rpc.select_utxos_for_amount(
    "wallet_name",
    "asset_id_hex",
    150.0,
    0.001
).await?;
println!("Selected {} UTXOs totaling {}", selected_utxos.len(), total_amount);
Source

pub async fn build_distribution_transaction( &self, wallet_name: &str, asset_id: &str, address_amounts: HashMap<String, f64>, change_address: &str, _estimated_fee: f64, ) -> Result<(String, Vec<Unspent>, f64), AmpError>

Builds a raw transaction for asset distribution with proper change handling

This method orchestrates the complete transaction building process:

  1. Selects appropriate UTXOs using select_utxos_for_amount
  2. Creates transaction inputs from selected UTXOs
  3. Creates outputs for distribution addresses
  4. Calculates and creates change output if necessary
  5. Builds the raw transaction using create_raw_transaction
§Arguments
  • asset_id - The asset ID being distributed
  • address_amounts - Map of recipient addresses to amounts
  • change_address - Address to send change to (if any)
  • estimated_fee - Estimated transaction fee
§Returns

Returns a tuple of (raw_transaction_hex, selected_utxos, change_amount)

§Errors

Returns an error if UTXO selection fails or transaction building fails

§Examples
let rpc = ElementsRpc::from_env()?;
let mut address_amounts = HashMap::new();
address_amounts.insert("address1".to_string(), 100.0);
address_amounts.insert("address2".to_string(), 50.0);

let (raw_tx, utxos, change) = rpc.build_distribution_transaction(
    "wallet_name",
    "asset_id_hex",
    address_amounts,
    "change_address",
    0.001
).await?;
println!("Built transaction with {} inputs, change: {}", utxos.len(), change);
Source

pub async fn blind_raw_transaction( &self, wallet_name: &str, raw_transaction: &str, ) -> Result<String, AmpError>

Blinds a raw transaction for confidential transactions

This method uses Elements’ blindrawtransaction RPC to properly blind a transaction for confidential asset transfers. This is crucial for Liquid transactions to ensure the blinding factors are properly balanced.

§Arguments
  • wallet_name - Name of the Elements wallet to use for blinding
  • raw_transaction - The raw transaction hex to blind
§Returns

Returns the blinded transaction hex string

§Errors

Returns an error if the RPC call fails or blinding is not possible

Source

pub async fn sign_transaction( &self, unsigned_tx_hex: &str, signer: &dyn Signer, ) -> Result<String, AmpError>

Signs a raw transaction using the provided signer callback

This method integrates with the Signer trait to sign unsigned transactions. It handles the complete signing workflow including:

  1. Validation of the unsigned transaction hex format
  2. Calling the signer’s sign_transaction method
  3. Validation of the signed transaction format and structure
  4. Proper error handling and context propagation
§Arguments
  • unsigned_tx_hex - The unsigned transaction in hexadecimal format
  • signer - Implementation of the Signer trait for transaction signing
§Returns

Returns the signed transaction as a hex string

§Errors

Returns an error if:

  • The unsigned transaction hex is invalid or malformed
  • The signer fails to sign the transaction
  • The signed transaction format is invalid
  • Any validation checks fail
§Examples
let rpc = ElementsRpc::from_env()?;
let (_, signer) = LwkSoftwareSigner::generate_new()?;
let unsigned_tx = "020000000001..."; // Unsigned transaction hex
let signed_tx = rpc.sign_transaction(unsigned_tx, &signer).await?;
println!("Transaction signed successfully: {}", signed_tx);
Source

pub async fn sign_and_broadcast_transaction( &self, unsigned_tx_hex: &str, signer: &dyn Signer, ) -> Result<String, AmpError>

Signs and broadcasts a transaction in a single operation

This is a convenience method that combines transaction signing and broadcasting. It performs the complete workflow of signing an unsigned transaction and immediately broadcasting it to the network.

§Arguments
  • unsigned_tx_hex - The unsigned transaction in hexadecimal format
  • signer - Implementation of the Signer trait for transaction signing
§Returns

Returns the transaction ID of the broadcast transaction

§Errors

Returns an error if signing or broadcasting fails

§Examples
let rpc = ElementsRpc::from_env()?;
let (_, signer) = LwkSoftwareSigner::generate_new()?;
let unsigned_tx = "020000000001..."; // Unsigned transaction hex
let txid = rpc.sign_and_broadcast_transaction(unsigned_tx, &signer).await?;
println!("Transaction broadcast with ID: {}", txid);
Source

pub async fn sign_and_broadcast_transaction_with_utxos( &self, unsigned_tx_hex: &str, utxos: &[Unspent], signer: &dyn Signer, ) -> Result<String, AmpError>

Signs and broadcasts a transaction with UTXO information for proper PSBT construction

This method provides UTXO information to the signer for proper PSBT construction, which is required for confidential transactions where the signer needs to know the previous transaction outputs being spent.

§Arguments
  • unsigned_tx_hex - The unsigned transaction in hexadecimal format
  • utxos - Vector of UTXOs being spent in the transaction
  • signer - Implementation of the Signer trait for transaction signing
§Returns

Returns the transaction ID of the broadcast transaction

§Errors

Returns an error if signing or broadcasting fails

Source

pub async fn collect_change_data( &self, asset_id: &str, txid: &str, node_rpc: &Self, wallet_name: &str, ) -> Result<Vec<Unspent>, AmpError>

Collects change data from a confirmed transaction for distribution confirmation

This method queries the Elements node to find change UTXOs from a specific transaction that belong to the specified asset. It’s used after a distribution transaction is confirmed to collect the change outputs for the final confirmation API call.

§Arguments
  • asset_id - The asset ID to filter change UTXOs for
  • txid - The transaction ID to filter change UTXOs from
§Returns

Returns a vector of Unspent UTXOs that represent change outputs from the transaction. Returns an empty vector if no change outputs exist for the specified asset and transaction.

§Errors

Returns an error if the RPC call fails or if there are issues querying the Elements node

§Examples
let rpc = ElementsRpc::from_env()?;
let change_data = rpc.collect_change_data(
    "asset_id_hex",
    "transaction_id_hex",
    &rpc,
    "wallet_name"
).await?;

if change_data.is_empty() {
    println!("No change outputs found for this transaction");
} else {
    println!("Found {} change outputs", change_data.len());
}
Source

pub async fn list_unspent_with_blinding_data( &self, wallet_name: &str, ) -> Result<Vec<Unspent>, AmpError>

Lists unspent outputs with full blinding data for confidential transactions

This method calls the raw listunspent RPC to get complete UTXO information including blinding data (amountblinder and assetblinder) which is required for confidential transaction confirmation with the AMP API.

§Arguments
  • wallet_name - Name of the Elements wallet to query
§Returns

Returns a vector of Unspent structs with complete blinding information

§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let utxos = rpc.list_unspent_with_blinding_data("wallet_name").await?;
for utxo in utxos {
    println!("UTXO: {} with blinders: {:?}, {:?}",
             utxo.txid, utxo.amountblinder, utxo.assetblinder);
}
Source

pub async fn create_elements_wallet( &self, wallet_name: &str, ) -> Result<(), AmpError>

Creates a standard wallet in Elements (Elements-first approach)

This method creates a new standard wallet in the Elements node that can generate addresses and private keys. This is part of the Elements-first approach where we create the wallet in Elements first, then export keys to LWK.

§Arguments
  • wallet_name - Name for the new wallet
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.create_elements_wallet("test_wallet").await?;
Source

pub async fn get_new_address( &self, wallet_name: &str, address_type: Option<&str>, ) -> Result<String, AmpError>

Get a new address from an Elements wallet

This method requests a new address from the specified Elements wallet. The address will be generated by Elements and can be used for receiving funds. Defaults to native segwit (bech32) addresses for optimal compatibility.

§Arguments
  • wallet_name - Name of the wallet to get address from
  • address_type - Optional address type (“bech32”, “legacy”, “p2sh-segwit”). Defaults to “bech32”
§Errors

Returns an error if the RPC call fails or the response format is unexpected

§Examples
let rpc = ElementsRpc::from_env()?;

// Generate native segwit address (default)
let address = rpc.get_new_address("test_wallet", None).await?;

// Or explicitly request native segwit
let bech32_address = rpc.get_new_address("test_wallet", Some("bech32")).await?;

println!("Native segwit address: {}", address);
Source

pub async fn get_confidential_address( &self, wallet_name: &str, address: &str, ) -> Result<String, AmpError>

Get the confidential version of an address from Elements wallet

This method takes a regular (unconfidential) address and returns its confidential counterpart, which includes blinding keys for confidential transactions.

§Arguments
  • wallet_name - Name of the Elements wallet
  • address - The unconfidential address to get info for
§Returns

Returns the confidential address string

§Example
let rpc = ElementsRpc::from_env()?;
let unconfidential_address = "tex1q...";
// Note: This would need to be called in an async context
// let confidential_address = rpc.get_confidential_address("test_wallet", unconfidential_address).await?;
// println!("Confidential address: {}", confidential_address);

Gets the confidential address for a given unconfidential address from a wallet

§Errors

Returns an error if the RPC call fails or the response format is unexpected

Source

pub async fn dump_private_key( &self, wallet_name: &str, address: &str, ) -> Result<String, AmpError>

Get the private key for an address from Elements wallet

This method exports the private key for a specific address from the Elements wallet. The private key can then be imported into LWK for signing.

Note: This is a simplified implementation that returns a placeholder private key. For production use, implement proper wallet-specific RPC calls.

§Arguments
  • wallet_name - Name of the wallet containing the address
  • address - The address to get the private key for
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let address = rpc.get_new_address("test_wallet", None).await?;
let private_key = rpc.dump_private_key("test_wallet", &address).await?;
println!("Private key: {}", private_key);
Source

pub async fn create_descriptor_wallet( &self, wallet_name: &str, ) -> Result<(), AmpError>

Creates a descriptor wallet in Elements

§Arguments
  • wallet_name - Name for the new wallet
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.create_descriptor_wallet("test_wallet").await?;
Source

pub async fn import_descriptor( &self, wallet_name: &str, descriptor: &str, ) -> Result<(), AmpError>

Imports a single descriptor into an Elements wallet

This method imports a descriptor that enables the wallet to scan and recognize addresses/UTXOs from a mnemonic. For LWK descriptors with <0;1>/* format, a single descriptor covers both receive and change addresses.

§Arguments
  • wallet_name - Name of the wallet to import descriptor into
  • descriptor - The descriptor to import
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let descriptor = "ct(slip77(...),elwpkh([...]/84h/1h/0h]tpub.../<0;1>/*))#checksum";
rpc.import_descriptor("test_wallet", descriptor).await?;
Source

pub async fn import_descriptors( &self, wallet_name: &str, receive_descriptor: &str, change_descriptor: &str, ) -> Result<(), AmpError>

Imports descriptors into an Elements wallet (legacy method for compatibility)

This method imports descriptors that enable the wallet to scan and recognize addresses/UTXOs from a mnemonic. If both descriptors are the same (as with LWK descriptors using <0;1>/* format), only one descriptor is imported.

§Arguments
  • wallet_name - Name of the wallet to import descriptors into
  • receive_descriptor - The receive descriptor
  • change_descriptor - The change descriptor
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let descriptor = "ct(slip77(...),elwpkh([...]/84h/1h/0h]tpub.../<0;1>/*))#checksum";
rpc.import_descriptors("test_wallet", descriptor, descriptor).await?;
Source

pub async fn setup_wallet_with_descriptors( &self, wallet_name: &str, receive_descriptor: &str, change_descriptor: &str, ) -> Result<(), AmpError>

Sets up a wallet with descriptors from a mnemonic

This is a convenience method that combines wallet creation and descriptor import. It creates a descriptor wallet and imports the receive and change descriptors generated from the provided mnemonic.

§Arguments
  • wallet_name - Name for the new wallet
  • receive_descriptor - The receive descriptor (external chain /0/*)
  • change_descriptor - The change descriptor (internal chain /1/*)
§Errors

Returns an error if wallet creation or descriptor import fails

§Examples
let rpc = ElementsRpc::from_env()?;
let receive_desc = "wpkh([d34db33f/84h/1h/0h]xprv.../0/*)#checksum";
let change_desc = "wpkh([d34db33f/84h/1h/0h]xprv.../1/*)#checksum";
rpc.setup_wallet_with_descriptors("test_wallet", receive_desc, change_desc).await?;
Source

pub async fn dump_wallet( &self, wallet_name: &str, file_path: &str, ) -> Result<(), AmpError>

Exports a wallet to a file using dumpwallet RPC

§Arguments
  • wallet_name - Name of the wallet to export
  • file_path - Path where the wallet dump file will be created
§Errors

Returns an error if the RPC call fails or the wallet cannot be exported

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.dump_wallet("my_wallet", "/tmp/wallet_export.dat").await?;
Source

pub async fn import_wallet( &self, wallet_name: &str, file_path: &str, ) -> Result<(), AmpError>

Imports a wallet from a file using importwallet RPC

§Arguments
  • wallet_name - Name of the wallet to import into
  • file_path - Path to the wallet dump file to import
§Errors

Returns an error if the RPC call fails or the wallet cannot be imported

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.import_wallet("my_wallet", "/tmp/wallet_export.dat").await?;
Source

pub async fn dump_blinding_key( &self, wallet_name: &str, address: &str, ) -> Result<String, AmpError>

Exports a blinding key for a confidential address using dumpblindingkey RPC

§Arguments
  • wallet_name - Name of the wallet containing the address
  • address - The confidential address to export the blinding key for
§Errors

Returns an error if the RPC call fails or the address doesn’t have a blinding key

§Examples
let rpc = ElementsRpc::from_env()?;
let key = rpc.dump_blinding_key("my_wallet", "VTpz...").await?;
println!("Blinding key: {}", key);
Source

pub async fn import_blinding_key( &self, wallet_name: &str, address: &str, blinding_key: &str, ) -> Result<(), AmpError>

Imports a blinding key for a confidential address using importblindingkey RPC

§Arguments
  • wallet_name - Name of the wallet to import the blinding key into
  • address - The confidential address to import the blinding key for
  • blinding_key - The blinding key to import
§Errors

Returns an error if the RPC call fails or the blinding key cannot be imported

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.import_blinding_key("my_wallet", "VTpz...", "blinding_key_hex").await?;
Source

pub async fn get_wallet_info( &self, wallet_name: &str, ) -> Result<Value, AmpError>

Gets wallet information using getwalletinfo RPC

§Arguments
  • wallet_name - Name of the wallet to get information for
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let info = rpc.get_wallet_info("my_wallet").await?;
println!("Wallet info: {:?}", info);
Source

pub async fn get_unconfidential_address( &self, wallet_name: &str, confidential_address: &str, ) -> Result<String, AmpError>

Gets the unconfidential address for a confidential address

§Arguments
  • wallet_name - Name of the wallet
  • confidential_address - The confidential address to convert
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let unconf = rpc.get_unconfidential_address("my_wallet", "VTpz...").await?;
println!("Unconfidential address: {}", unconf);
Source

pub async fn import_private_key( &self, wallet_name: &str, private_key: &str, label: Option<&str>, rescan: Option<bool>, ) -> Result<(), AmpError>

Imports a private key into the wallet using importprivkey RPC

§Arguments
  • wallet_name - Name of the wallet to import into
  • private_key - The private key in WIF format
  • label - Optional label for the address
  • rescan - Whether to rescan the blockchain for transactions
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
rpc.import_private_key("my_wallet", "cT1...", Some("my_address"), Some(false)).await?;
Source

pub async fn list_descriptors( &self, wallet_name: &str, private_keys: Option<bool>, ) -> Result<Vec<String>, AmpError>

Lists all descriptors in a wallet using listdescriptors RPC

§Arguments
  • wallet_name - Name of the wallet
  • private_keys - Whether to include private keys in the output
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let descriptors = rpc.list_descriptors("my_wallet", Some(true)).await?;
for desc in descriptors {
    println!("Descriptor: {}", desc);
}
Source

pub async fn get_addresses_by_label( &self, wallet_name: &str, label: &str, ) -> Result<Vec<String>, AmpError>

Gets all addresses in a wallet by label using getaddressesbylabel RPC

§Arguments
  • wallet_name - Name of the wallet
  • label - Label to filter by (empty string for all addresses)
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let addresses = rpc.get_addresses_by_label("my_wallet", "").await?;
for addr in addresses {
    println!("Address: {}", addr);
}
Source

pub async fn list_received_by_address( &self, wallet_name: &str, min_conf: u32, include_empty: bool, ) -> Result<Vec<ReceivedByAddress>, AmpError>

Lists addresses that have received transactions using listreceivedbyaddress RPC

§Arguments
  • wallet_name - Name of the wallet to list addresses for
  • min_conf - Minimum number of confirmations (0 for unconfirmed)
  • include_empty - Whether to include addresses that haven’t received payments
§Errors

Returns an error if the RPC call fails

§Examples
let rpc = ElementsRpc::from_env()?;
let addresses = rpc.list_received_by_address("my_wallet", 0, true).await?;
for addr in addresses {
    println!("Address: {:?}", addr);
}

Trait Implementations§

Source§

impl Clone for ElementsRpc

Source§

fn clone(&self) -> ElementsRpc

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ElementsRpc

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more