drt_sc_snippets/
interactor_sender.rs

1use log::debug;
2use drt_sc_scenario::drt_sc::types::Address;
3use drt_sdk::{data::transaction::Transaction, wallet::Wallet};
4
5use crate::{address_h256_to_moars, Interactor};
6
7/// A user account that can sign transactions (a pem is present).
8pub struct Sender {
9    pub address: Address,
10    pub wallet: Wallet,
11    pub current_nonce: Option<u64>,
12}
13
14impl Interactor {
15    pub async fn recall_nonce(&self, address: &Address) -> u64 {
16        let moars_address = address_h256_to_moars(address);
17        let account = self
18            .proxy
19            .get_account(&moars_address)
20            .await
21            .expect("failed to retrieve account nonce");
22        account.nonce
23    }
24
25    pub(crate) async fn set_nonce_and_sign_tx(
26        &mut self,
27        sender_address: &Address,
28        transaction: &mut Transaction,
29    ) {
30        // read
31        let sender = self
32            .sender_map
33            .get(sender_address)
34            .expect("the wallet that was supposed to sign is not registered");
35
36        // recall
37        let nonce = self.recall_nonce(&sender.address).await;
38        println!("sender's recalled nonce: {nonce}");
39
40        // set tx nonce
41        transaction.nonce = nonce;
42        println!("-- tx nonce: {}", transaction.nonce);
43
44        // update
45        let sender = self
46            .sender_map
47            .get_mut(sender_address)
48            .expect("the wallet that was supposed to sign is not registered");
49        sender.current_nonce = Some(nonce + 1);
50
51        // sign
52        let signature = sender.wallet.sign_tx(transaction);
53        transaction.signature = Some(hex::encode(signature));
54        debug!("transaction {:#?}", transaction);
55    }
56}