pub struct WalletUnlocked { /* private fields */ }
Expand description

A WalletUnlocked is equivalent to a Wallet whose private key is known and stored alongside in-memory. Knowing the private key allows a WalletUlocked to sign operations, send transactions, and more.

Examples

Signing and Verifying a message

The wallet can be used to produce ECDSA Signature objects, which can be then verified.

use fuel_crypto::Message;
use fuels::prelude::*;

async fn foo() -> Result<(), Error> {
  // Setup local test node
  let (provider, _) = setup_test_provider(vec![], vec![], None, None).await;

  // Create a new local wallet with the newly generated key
  let wallet = WalletUnlocked::new_random(Some(provider));

  let message = "my message";
  let signature = wallet.sign_message(message.as_bytes()).await?;

  // Lock the wallet when we're done, dropping the private key from memory.
  let wallet = wallet.lock();

  // Recover address that signed the message
  let message = Message::new(message);
  let recovered_address = signature.recover(&message).expect("Failed to recover address");

  assert_eq!(wallet.address().hash(), recovered_address.hash());

  // Verify signature
  signature.verify(&recovered_address, &message).unwrap();
  Ok(())
}

Implementations§

Lock the wallet by dropping the private key from memory.

Creates a new wallet with a random private key.

Creates a new wallet from the given private key.

Creates a new wallet from a mnemonic phrase. The default derivation path is used.

Creates a new wallet from a mnemonic phrase. It takes a path to a BIP32 derivation path.

Creates a new wallet and stores its encrypted version in the given path.

Encrypts the wallet’s private key with the given password and saves it to the given path.

Recreates a wallet from an encrypted JSON wallet given the provided path and password.

Add base asset inputs to the transaction to cover the estimated fee. The original base asset amount cannot be calculated reliably from the existing transaction inputs because the selected resources may exceed the required amount to avoid dust. Therefore we require it as an argument.

Requires contract inputs to be at the start of the transactions inputs vec so that their indexes are retained

Transfer funds from this wallet to another Address. Fails if amount for asset ID is larger than address’s spendable coins. Returns the transaction ID that was sent and the list of receipts.

Examples
use fuels::prelude::*;
use fuels::test_helpers::setup_single_asset_coins;
use fuels::tx::{Bytes32, AssetId, Input, Output, UtxoId};
use std::str::FromStr;
#[cfg(feature = "fuel-core-lib")]
use fuels_test_helpers::Config;

async fn foo() -> Result<(), Box<dyn std::error::Error>> {
 // Create the actual wallets/signers
 let mut wallet_1 = WalletUnlocked::new_random(None);
 let mut wallet_2 = WalletUnlocked::new_random(None).lock();

  // Setup a coin for each wallet
  let mut coins_1 = setup_single_asset_coins(wallet_1.address(),BASE_ASSET_ID, 1, 1);
  let coins_2 = setup_single_asset_coins(wallet_2.address(),BASE_ASSET_ID, 1, 1);
  coins_1.extend(coins_2);

  // Setup a provider and node with both set of coins
  let (provider, _) = setup_test_provider(coins_1, vec![], None, None).await;

  // Set provider for wallets
  wallet_1.set_provider(provider.clone());
  wallet_2.set_provider(provider);

  // Transfer 1 from wallet 1 to wallet 2
  let _receipts = wallet_1
       .transfer(&wallet_2.address(), 1, Default::default(), TxParameters::default())
       .await
       .unwrap();

  let wallet_2_final_coins = wallet_2.get_coins(BASE_ASSET_ID).await.unwrap();

  // Check that wallet two now has two coins
  assert_eq!(wallet_2_final_coins.len(), 2);
  Ok(())
}

Withdraws an amount of the base asset to an address on the base chain. Returns the transaction ID, message ID and the list of receipts.

Unconditionally transfers balance of type asset_id to the contract at to. Fails if balance for asset_id is larger than this wallet’s spendable balance. Returns the corresponding transaction ID and the list of receipts.

CAUTION !!!

This will transfer coins to a contract, possibly leading to the PERMANENT LOSS OF COINS if not used with care.

Methods from Deref<Target = Wallet>§

Returns a proper vector of Input::Coins for the given asset ID, amount, and witness index. The witness_index is the position of the witness (signature) in the transaction’s list of witnesses. Meaning that, in the validation process, the node will use the witness at this index to validate the coins returned by this method.

Returns a vector containing the output coin and change output given an asset and amount

Gets all coins of asset asset_id owned by the wallet, even spent ones (this is useful for some particular cases, but in general, you should use get_spendable_coins). This returns actual coins (UTXOs).

Get some spendable resources (coins and messages) of asset asset_id owned by the wallet that add up at least to amount amount. The returned coins (UTXOs) are actual coins that can be spent. The number of UXTOs is optimized to prevent dust accumulation.

Get the balance of all spendable coins asset_id for address address. This is different from getting coins because we are just returning a number (the sum of UTXOs amount) instead of the UTXOs.

Get all the spendable balances of all assets for the wallet. This is different from getting the coins because we are only returning the sum of UTXOs coins amount and not the UTXOs coins themselves.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Signs the hash of the provided message
Signs the transaction
Returns the signer’s Fuel Address

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

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

Calls U::from(self).

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

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more