设置钱包 (Setting up a wallet)

设置 SDK 钱包 (Setting up an SDK wallet)

相关导入 (Relevant imports)

通用导入 (General imports)

// namada_sdk::Namada is a high level interface in order to interact with the Namada SDK
use namada_sdk::Namada;
// The NamadaImpl provides convenient implementations to frequently used Namada SDK interactons
use namada_sdk::NamadaImpl;

钱包特定导入 (Wallet specific imports)

// SecretKey, common and SchemeType give access to Namada cryptographic keys and their relevant implementations. Namada supports ED25519 and SECP256K1 keys.
use namada_sdk::core::types::key::common::SecretKey;
use namada_sdk::core::types::key::{common, SchemeType};
// Filesystem wallet utilities (stores the path of the wallet on the filesystem)
use namada_sdk::wallet::fs::FsWalletUtils;


从助记词创建钱包 (Creating a wallet from a mnemonic)

SDK 可以从助记词短语创建钱包。助记词短语是一个24个单词的短语,可用于恢复钱包。

let mnemonic = Mnemonic::from_phrase(MNEMONIC_CODE, namada_sdk::bip39::Language::English)
// Assuming a cometbft node is running on localhost:26657
let http_client = HttpClient::new("http://localhost:26657").unwrap();
// Assuming wallet.toml exists in the current directory
let mut wallet = FsWalletUtils::new(PathBuf::from("wallet.toml"));
// The key can be generated from the wallet by passing in the mnemonic phrase
let (_key_alias, sk) = NamadaImpl::new(&http_client, &mut wallet, &mut shielded_ctx, &NullIo)
            .wallet_mut()
            .await
            .derive_key_from_user_mnemonic_code(
                SchemeType::Ed25519,
                Some(alias),
                false,
                Some(derivation_path),
                Some((mnemonic.clone(), Zeroizing::new("".to_owned()))),
                None,
            )
            .expect("unable to derive key from mnemonic code")
            .unwrap();

在上述函数的第二部分,密钥是从助记词短语中派生出来的。alias是将存储在钱包中的密钥的名称。derivation_path 是 HD 钱包中密钥的路径。mnemonic 是之前生成的助记词短语。shielded_ctx 是隐私交易的上下文。NullIo 是钱包的 IO 上下文。


生成新钱包并将其保存到文件系统 (Generating a new wallet and saving it to the filesystem)

也可以从头开始创建 sdk 钱包。这更为复杂,因为它需要为钱包生成一个新的存储区。

use std::path::PathBuf;
 
use namada::{
    sdk::wallet::{
        alias::Alias, ConfirmationResponse, GenRestoreKeyError, Store, StoredKeypair, Wallet,
        WalletUtils,
    },
    types::{
        address::Address,
        key::{common::SecretKey, PublicKeyHash},
    },
};
use rand::rngs::OsRng;
 
pub struct SdkWallet {
    pub wallet: Wallet<SdkWalletUtils>,
}
 
impl SdkWallet {
    pub fn new(sk: SecretKey, nam_address: Address) -> Self {
        let store = Store::default();
        let mut wallet = Wallet::new(PathBuf::new(), store);
        let stored_keypair = StoredKeypair::Raw(sk.clone());
        let pk_hash = PublicKeyHash::from(&sk.to_public());
        let alias = "alice".to_string();
        wallet.insert_keypair(alias, stored_keypair, pk_hash, true);
        wallet.add_address("nam", nam_address, true);
        Self { wallet }
    }
}
 
pub struct SdkWalletUtils {}
 
impl WalletUtils for SdkWalletUtils {
    type Storage = PathBuf;
 
    type Rng = OsRng;
 
    fn read_decryption_password() -> zeroize::Zeroizing<std::string::String> {
        panic!("attempted to prompt for password in non-interactive mode");
    }
 
    fn read_encryption_password() -> zeroize::Zeroizing<std::string::String> {
        panic!("attempted to prompt for password in non-interactive mode");
    }
 
    fn read_alias(_prompt_msg: &str) -> std::string::String {
        panic!("attempted to prompt for alias in non-interactive mode");
    }
 
    fn read_mnemonic_code() -> std::result::Result<namada::bip39::Mnemonic, GenRestoreKeyError> {
        panic!("attempted to prompt for mnemonic in non-interactive mode");
    }
 
    fn read_mnemonic_passphrase(_confirm: bool) -> zeroize::Zeroizing<std::string::String> {
        panic!("attempted to prompt for mnemonic in non-interactive mode");
    }
 
    fn show_overwrite_confirmation(
        _alias: &Alias,
        _alias_for: &str,
    ) -> namada::sdk::wallet::store::ConfirmationResponse {
        // Automatically replace aliases in non-interactive mode
        ConfirmationResponse::Replace
    }
}

上述代码现在允许我们通过简单地传入一个密钥和 NAM 代币的地址来构造 SdkWallet 的任何实例。如果我们希望进行其他代币的转账,我们需要添加那些地址。

Last updated