pub struct ElementsRpc { /* private fields */ }Expand description
Elements RPC client for blockchain operations
Implementations§
Source§impl ElementsRpc
impl ElementsRpc
Sourcepub fn new(url: String, username: String, password: String) -> Self
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 usernamepassword- 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.
Sourcepub fn from_env() -> Result<Self, AmpError>
pub fn from_env() -> Result<Self, AmpError>
Creates a new ElementsRpc client from environment variables
Expected environment variables:
ELEMENTS_RPC_URL: RPC endpoint URLELEMENTS_RPC_USER: RPC usernameELEMENTS_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();Sourcepub async fn get_network_info(&self) -> Result<NetworkInfo, AmpError>
pub async fn get_network_info(&self) -> Result<NetworkInfo, AmpError>
Sourcepub async fn get_blockchain_info(&self) -> Result<BlockchainInfo, AmpError>
pub async fn get_blockchain_info(&self) -> Result<BlockchainInfo, AmpError>
Sourcepub async fn wallet_passphrase(
&self,
passphrase: &str,
timeout: u64,
) -> Result<(), AmpError>
pub async fn wallet_passphrase( &self, passphrase: &str, timeout: u64, ) -> Result<(), AmpError>
Sourcepub async fn validate_connection(&self) -> Result<(), AmpError>
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");Sourcepub async fn get_node_status(
&self,
) -> Result<(NetworkInfo, BlockchainInfo), AmpError>
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);Sourcepub async fn list_unspent(
&self,
asset_id: Option<&str>,
) -> Result<Vec<Unspent>, AmpError>
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());Sourcepub async fn list_unspent_for_wallet(
&self,
wallet_name: &str,
asset_id: Option<&str>,
) -> Result<Vec<Unspent>, AmpError>
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 queryasset_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());Sourcepub async fn create_raw_transaction(
&self,
inputs: Vec<TxInput>,
outputs: HashMap<String, f64>,
assets: HashMap<String, String>,
) -> Result<String, AmpError>
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 outputsassets- 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?;Sourcepub async fn import_address(
&self,
wallet_name: &str,
address: &str,
label: Option<&str>,
rescan: Option<bool>,
) -> Result<(), AmpError>
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 walletaddress- The address to importlabel- Optional label for the addressrescan- 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?;Sourcepub async fn rescan_blockchain(
&self,
wallet_name: &str,
start_height: Option<u64>,
) -> Result<Value, AmpError>
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 rescanstart_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?;Sourcepub async fn create_wallet(
&self,
wallet_name: &str,
disable_private_keys: bool,
) -> Result<(), AmpError>
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 loaddisable_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?;Sourcepub async fn setup_watch_only_wallet(
&self,
wallet_name: &str,
address: &str,
label: Option<&str>,
) -> Result<(), AmpError>
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 createaddress- Address to import as watch-onlylabel- 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?;Sourcepub async fn send_raw_transaction(&self, hex: &str) -> Result<String, AmpError>
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);Sourcepub async fn get_transaction(
&self,
txid: &str,
) -> Result<TransactionDetail, AmpError>
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);Sourcepub 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>
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 useaddress_amounts- Map of addresses to amounts to sendasset_amounts- Map of addresses to asset IDs for each outputmin_conf- Minimum confirmations for inputs (default: 1)comment- Optional transaction commentsubtract_fee_from- Optional addresses to subtract fees fromreplaceable- 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);Sourcepub async fn wait_for_confirmations(
&self,
txid: &str,
min_confirmations: Option<u32>,
timeout_minutes: Option<u64>,
) -> Result<TransactionDetail, AmpError>
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 confirmationsmin_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);Sourcepub 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>
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
Sourcepub async fn reissueasset(
&self,
asset_id: &str,
amount: f64,
) -> Result<Value, AmpError>
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 reissueamount- 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"]);Sourcepub async fn list_issuances(
&self,
asset_id: Option<&str>,
) -> Result<Vec<Value>, AmpError>
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);
}
}Sourcepub async fn destroyamount(
&self,
asset_id: &str,
amount: f64,
) -> Result<String, AmpError>
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 burnamount- 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);Sourcepub async fn get_balance(
&self,
asset_id: Option<&str>,
) -> Result<Value, AmpError>
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);
}Sourcepub async fn select_utxos_for_amount(
&self,
wallet_name: &str,
asset_id: &str,
target_amount: f64,
estimated_fee: f64,
) -> Result<(Vec<Unspent>, f64), AmpError>
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:
- Filters UTXOs by asset ID and spendability
- Sorts UTXOs by amount (largest first) for efficiency
- Selects UTXOs until the target amount plus estimated fees is covered
§Arguments
asset_id- The asset ID to select UTXOs fortarget_amount- The total amount needed for distributionestimated_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);Sourcepub 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>
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:
- Selects appropriate UTXOs using
select_utxos_for_amount - Creates transaction inputs from selected UTXOs
- Creates outputs for distribution addresses
- Calculates and creates change output if necessary
- Builds the raw transaction using
create_raw_transaction
§Arguments
asset_id- The asset ID being distributedaddress_amounts- Map of recipient addresses to amountschange_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);Sourcepub async fn blind_raw_transaction(
&self,
wallet_name: &str,
raw_transaction: &str,
) -> Result<String, AmpError>
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 blindingraw_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
Sourcepub async fn sign_transaction(
&self,
unsigned_tx_hex: &str,
signer: &dyn Signer,
) -> Result<String, AmpError>
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:
- Validation of the unsigned transaction hex format
- Calling the signer’s
sign_transactionmethod - Validation of the signed transaction format and structure
- Proper error handling and context propagation
§Arguments
unsigned_tx_hex- The unsigned transaction in hexadecimal formatsigner- 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);Sourcepub async fn sign_and_broadcast_transaction(
&self,
unsigned_tx_hex: &str,
signer: &dyn Signer,
) -> Result<String, AmpError>
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 formatsigner- 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);Sourcepub async fn sign_and_broadcast_transaction_with_utxos(
&self,
unsigned_tx_hex: &str,
utxos: &[Unspent],
signer: &dyn Signer,
) -> Result<String, AmpError>
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 formatutxos- Vector of UTXOs being spent in the transactionsigner- 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
Sourcepub async fn collect_change_data(
&self,
asset_id: &str,
txid: &str,
node_rpc: &Self,
wallet_name: &str,
) -> Result<Vec<Unspent>, AmpError>
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 fortxid- 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());
}Sourcepub async fn list_unspent_with_blinding_data(
&self,
wallet_name: &str,
) -> Result<Vec<Unspent>, AmpError>
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);
}Sourcepub async fn create_elements_wallet(
&self,
wallet_name: &str,
) -> Result<(), AmpError>
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?;Sourcepub async fn get_new_address(
&self,
wallet_name: &str,
address_type: Option<&str>,
) -> Result<String, AmpError>
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 fromaddress_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);Sourcepub async fn get_confidential_address(
&self,
wallet_name: &str,
address: &str,
) -> Result<String, AmpError>
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 walletaddress- 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
Sourcepub async fn dump_private_key(
&self,
wallet_name: &str,
address: &str,
) -> Result<String, AmpError>
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 addressaddress- 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);Sourcepub async fn import_descriptor(
&self,
wallet_name: &str,
descriptor: &str,
) -> Result<(), AmpError>
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 intodescriptor- 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?;Sourcepub async fn import_descriptors(
&self,
wallet_name: &str,
receive_descriptor: &str,
change_descriptor: &str,
) -> Result<(), AmpError>
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 intoreceive_descriptor- The receive descriptorchange_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?;Sourcepub async fn setup_wallet_with_descriptors(
&self,
wallet_name: &str,
receive_descriptor: &str,
change_descriptor: &str,
) -> Result<(), AmpError>
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 walletreceive_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?;Sourcepub async fn dump_wallet(
&self,
wallet_name: &str,
file_path: &str,
) -> Result<(), AmpError>
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 exportfile_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?;Sourcepub async fn import_wallet(
&self,
wallet_name: &str,
file_path: &str,
) -> Result<(), AmpError>
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 intofile_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?;Sourcepub async fn dump_blinding_key(
&self,
wallet_name: &str,
address: &str,
) -> Result<String, AmpError>
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 addressaddress- 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);Sourcepub async fn import_blinding_key(
&self,
wallet_name: &str,
address: &str,
blinding_key: &str,
) -> Result<(), AmpError>
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 intoaddress- The confidential address to import the blinding key forblinding_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?;Sourcepub async fn get_unconfidential_address(
&self,
wallet_name: &str,
confidential_address: &str,
) -> Result<String, AmpError>
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 walletconfidential_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);Sourcepub async fn import_private_key(
&self,
wallet_name: &str,
private_key: &str,
label: Option<&str>,
rescan: Option<bool>,
) -> Result<(), AmpError>
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 intoprivate_key- The private key in WIF formatlabel- Optional label for the addressrescan- 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?;Sourcepub async fn list_descriptors(
&self,
wallet_name: &str,
private_keys: Option<bool>,
) -> Result<Vec<String>, AmpError>
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 walletprivate_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);
}Sourcepub async fn get_addresses_by_label(
&self,
wallet_name: &str,
label: &str,
) -> Result<Vec<String>, AmpError>
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 walletlabel- 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);
}Sourcepub async fn list_received_by_address(
&self,
wallet_name: &str,
min_conf: u32,
include_empty: bool,
) -> Result<Vec<ReceivedByAddress>, AmpError>
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 formin_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
impl Clone for ElementsRpc
Source§fn clone(&self) -> ElementsRpc
fn clone(&self) -> ElementsRpc
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more