构建转账 (Constructing transfers)

现在我们已经设置好钱包和客户端,我们可以创建构建转账所需的环境。这可能有点棘手,但下面的样板代码应该能解决问题。要生成转账,需要以下导入:

use namada_sdk::args::InputAmount;

在用户生成一个账户并创建了适当的结构后,构造和提交转账交易并不难。

let mut namada = NamadaImpl::new(&http_client, &mut wallet, &mut shielded_ctx, &NullIo)
        .await
        .expect("unable to construct Namada object")
        .chain_id(ChainId::from_str("public-testnet-14.5d79b6958580").unwrap());
// Transfer the given amount of native tokens from the source account to the
// destination account.
async fn gen_transfer<'a>(
    namada: &impl Namada<'a>,
    source: &Account,
    destination: &Account,
    amount: InputAmount,
) -> std::result::Result<ProcessTxResponse, namada_sdk::error::Error> {
    let mut transfer_tx_builder = namada
        .new_transfer(
            TransferSource::Address(Address::from(&source.public_key)),
            TransferTarget::Address(Address::from(&destination.public_key)),
            namada.native_token(),
            amount,
        )
        .signing_keys(vec![source.private_key.clone()]);
    let (mut transfer_tx, signing_data, _epoch) = transfer_tx_builder
        .build(namada)
        .await
        .expect("unable to build transfer");
    namada
        .sign(&mut transfer_tx, &transfer_tx_builder.tx, signing_data)
        .await
        .expect("unable to sign reveal pk tx");
    namada.submit(transfer_tx, &transfer_tx_builder.tx).await
}

其他交易可以以类似的方式构建。


隐蔽转账 (Shielded transfers)

为了使转账隐蔽,我们需要只是使用隐蔽地址和密钥,而不是透明的。

使用隐蔽的扩展SpendingKey作为源是很重要的。

use namada::types::masp::{ExtendedSpendingKey, PaymentAddress, TransferSource, TransferTarget};
 
// Make sure to replace 'secret-ex' with an actual Namada extended spending key
let source = ExtendedSpendingKey::from_str("secret-ex").unwrap();
// Make sure to replace "payment-addr-ex" with an actual Namada payment address
let destination = PaymentAddress::from_str("payment-addr-ex").unwrap();
let fee_payer = 
let mut transfer_tx_builder = namada
        .new_transfer(
            TransferSource::ExtendedSpendingKey(source),
            TransferTarget::Address(Address::from(&destination.public_key)),
            namada.native_token(),
            amount,
        )
        // Make sure to replace "transparent-address-ex" with an actual Namada transparent address
        .signing_keys(vec![Address::from_str("transparent-address-ex").ok()]);

Last updated