Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions examples/wallets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,31 @@ mod tests {
Ok(())
}


#[tokio::test]
async fn create_and_store_mnemonic_wallet_with_address_named_keystore() -> Result<()> {
// ANCHOR: create_and_store_mnemonic_wallet_with_address_named_keystore
use fuels::prelude::*;

let dir = std::env::temp_dir();

let phrase =
"oblige salon price punch saddle immune slogan rare snap desert retire surprise";

// Use the test helper to setup a test provider.
let provider = setup_test_provider(vec![], vec![], None, None).await?;

// Create first account from mnemonic phrase.
let wallet = WalletUnlocked::new_from_mnemonic_phrase(phrase, Some(provider))?;

let password = "my_master_password";

// Encrypts and stores it on disk. Can be recovered using `Wallet::load_keystore`.
let _uuid = wallet.encrypt_with_name(&dir, password, wallet.clone().address())?;
// ANCHOR_END: create_and_store_mnemonic_wallet_with_address_named_keystore
Ok(())
}

#[tokio::test]
async fn wallet_transfer() -> Result<()> {
// ANCHOR: wallet_transfer
Expand Down
14 changes: 14 additions & 0 deletions packages/fuels-accounts/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,20 @@ impl WalletUnlocked {
.map_err(|e| error!(Other, "{e}"))
}

/// Encrypts the wallet's private key with the given password and saves it
/// to the given path named with given name.
pub fn encrypt_with_name<P, S>(&self, dir: P, password: S, name: &str) -> Result<String>
where
P: AsRef<Path>,
S: AsRef<[u8]>,
{
let mut rng = rand::thread_rng();

eth_keystore::encrypt_key(dir, &mut rng, *self.private_key, password, name)
.map_err(|e| error!(Other, "{e}"))
}


/// Recreates a wallet from an encrypted JSON wallet given the provided path and password.
pub fn load_keystore<P, S>(keypath: P, password: S, provider: Option<Provider>) -> Result<Self>
where
Expand Down