Prechádzať zdrojové kódy

Remove copy from ids

Cesar Rodas 1 rok pred
rodič
commit
e488382a65

+ 1 - 1
utxo/src/id.rs

@@ -10,7 +10,7 @@ pub enum Error {
 
 macro_rules! Id {
     ($id:ident, $suffix:expr) => {
-        #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize)]
+        #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize)]
         pub struct $id {
             bytes: [u8; 32],
         }

+ 4 - 4
utxo/src/ledger.rs

@@ -77,7 +77,7 @@ where
                         let to_spend_cents = to_spend_cents.abs();
                         let input = payments
                             .pop()
-                            .ok_or(Error::InsufficientBalance(account, asset.id))?;
+                            .ok_or(Error::InsufficientBalance(account.clone(), asset.id))?;
                         let split_input = Transaction::new(
                             "Exchange".to_owned(),
                             // Set the change transaction as settled. This is an
@@ -92,8 +92,8 @@ where
                             Status::Settled,
                             vec![input],
                             vec![
-                                (account, asset.new_amount(cents - to_spend_cents)),
-                                (account, asset.new_amount(to_spend_cents)),
+                                (account.clone(), asset.new_amount(cents - to_spend_cents)),
+                                (account.clone(), asset.new_amount(to_spend_cents)),
                             ],
                         )
                         .await?;
@@ -182,7 +182,7 @@ where
         reference: String,
     ) -> Result<Transaction, Error> {
         let mut transaction =
-            Transaction::new_external_deposit(reference, status, vec![(*account, amount)])?;
+            Transaction::new_external_deposit(reference, status, vec![(account.clone(), amount)])?;
         transaction.persist(&self.storage).await?;
         Ok(transaction)
     }

+ 1 - 1
utxo/src/payment.rs

@@ -1,7 +1,7 @@
 use crate::{AccountId, Amount, Status, TransactionId};
 use serde::Serialize;
 
-#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)]
+#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
 pub struct PaymentId {
     pub transaction: TransactionId,
     pub position: usize,

+ 2 - 2
utxo/src/sqlite/batch.rs

@@ -23,9 +23,9 @@ impl<'a> Batch<'a> {
 impl<'a> storage::Batch<'a> for Batch<'a> {
     async fn spend_payment(
         &mut self,
-        payment_id: PaymentId,
+        payment_id: &PaymentId,
         status: Status,
-        transaction_id: TransactionId,
+        transaction_id: &TransactionId,
     ) -> Result<(), Error> {
         let result = sqlx::query(
             r#"

+ 2 - 2
utxo/src/storage.rs

@@ -26,9 +26,9 @@ pub enum Error {
 pub trait Batch<'a> {
     async fn spend_payment(
         &mut self,
-        payment_id: PaymentId,
+        payment_id: &PaymentId,
         status: Status,
-        transaction_id: TransactionId,
+        transaction_id: &TransactionId,
     ) -> Result<(), Error>;
 
     async fn rollback(self) -> Result<(), Error>;

+ 33 - 0
utxo/src/tests/deposit.rs

@@ -17,6 +17,39 @@ pub async fn deposit(
 }
 
 #[tokio::test]
+async fn pending_deposit_and_failure() {
+    let source = "account1".parse::<AccountId>().expect("account");
+    let (assets, ledger) = get_instance().await;
+    let id = ledger
+        .deposit(
+            &source,
+            assets.amount(2, 3000).expect("amount"),
+            Status::Processing,
+            "Test".to_owned(),
+        )
+        .await
+        .expect("valid tx")
+        .id;
+
+    assert!(ledger
+        .get_balance(&source)
+        .await
+        .expect("balance")
+        .is_empty());
+
+    ledger
+        .change_status(&id, Status::Failed)
+        .await
+        .expect("valid tx");
+
+    assert!(ledger
+        .get_balance(&source)
+        .await
+        .expect("balance")
+        .is_empty());
+}
+
+#[tokio::test]
 async fn deposit_and_transfer() {
     let source = "account1".parse::<AccountId>().expect("account");
     let dest = "account2".parse::<AccountId>().expect("account");

+ 42 - 38
utxo/src/transaction/mod.rs

@@ -58,25 +58,26 @@ impl Transaction {
         }
 
         let id = TransactionId::new(hasher.finalize().into());
+        let create = pay_to
+            .into_iter()
+            .enumerate()
+            .map(|(position, (to, amount))| Payment {
+                id: crate::PaymentId {
+                    transaction: id.clone(),
+                    position,
+                },
+                to,
+                amount,
+                spent_by: None,
+                status: status.clone(),
+            })
+            .collect();
 
         Ok(Self {
             id,
             spend: vec![],
+            create,
             reference,
-            create: pay_to
-                .into_iter()
-                .enumerate()
-                .map(|(position, (to, amount))| Payment {
-                    id: crate::PaymentId {
-                        transaction: id,
-                        position,
-                    },
-                    to,
-                    amount,
-                    spent_by: None,
-                    status: status.clone(),
-                })
-                .collect(),
             is_external_deposit: true,
             status,
         })
@@ -100,38 +101,41 @@ impl Transaction {
         let id = TransactionId::new(hasher.finalize().into());
 
         for (i, input) in spend.iter().enumerate() {
-            if input.spent_by.is_some() && input.spent_by != Some(id) {
+            if input.spent_by.is_some() && input.spent_by.as_ref() != Some(&id) {
                 return Err(Error::SpentPayment(i));
             }
             if input.spent_by.is_none() && input.status != Status::Settled {
                 return Err(Error::InvalidPaymentStatus(i, input.status.clone()));
             }
         }
+        let spend = spend
+            .into_iter()
+            .map(|mut input| {
+                input.spent_by = Some(id.clone());
+                input
+            })
+            .collect();
+
+        let create = pay_to
+            .into_iter()
+            .enumerate()
+            .map(|(position, (to, amount))| Payment {
+                id: crate::PaymentId {
+                    transaction: id.clone(),
+                    position,
+                },
+                to,
+                amount,
+                spent_by: None,
+                status: status.clone(),
+            })
+            .collect();
 
         Ok(Self {
             id,
             reference,
-            spend: spend
-                .into_iter()
-                .map(|mut input| {
-                    input.spent_by = Some(id);
-                    input
-                })
-                .collect(),
-            create: pay_to
-                .into_iter()
-                .enumerate()
-                .map(|(position, (to, amount))| Payment {
-                    id: crate::PaymentId {
-                        transaction: id,
-                        position,
-                    },
-                    to,
-                    amount,
-                    spent_by: None,
-                    status: status.clone(),
-                })
-                .collect(),
+            spend,
+            create,
             is_external_deposit: false,
             status,
         })
@@ -177,7 +181,7 @@ impl Transaction {
         let mut credit = HashMap::<Asset, AmountCents>::new();
 
         for (i, input) in self.spend.iter().enumerate() {
-            if input.spent_by.is_some() && input.spent_by != Some(self.id) {
+            if input.spent_by.is_some() && input.spent_by.as_ref() != Some(&self.id) {
                 return Err(Error::SpentPayment(i));
             }
             if let Some(value) = debit.get_mut(input.amount.asset()) {
@@ -247,7 +251,7 @@ impl Transaction {
         batch.store_new_payments(&self.create).await?;
         for input in self.spend.iter_mut() {
             batch
-                .spend_payment(input.id, self.status.clone(), self.id)
+                .spend_payment(&input.id, self.status.clone(), &self.id)
                 .await?;
         }
         batch.commit().await?;