1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
 * ‌
 * Hedera Rust SDK
 * ​
 * Copyright (C) 2022 - 2023 Hedera Hashgraph, LLC
 * ​
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ‍
 */

use hedera_proto::services;
use hedera_proto::services::crypto_service_client::CryptoServiceClient;
use tonic::transport::Channel;

use crate::transaction::{
    AnyTransactionData,
    ChunkInfo,
    ToTransactionDataProtobuf,
    TransactionData,
    TransactionExecute,
};
use crate::{
    BoxGrpcFuture,
    Error,
    Hbar,
    LedgerId,
    ToProtobuf,
    Transaction,
    ValidateChecksums,
};

pub type PaymentTransaction = Transaction<PaymentTransactionData>;

#[derive(Debug, Clone, Default)]
pub struct PaymentTransactionData {
    amount: Option<Hbar>,
    max_amount: Option<Hbar>,
}

impl PaymentTransaction {
    pub(super) fn get_amount(&self) -> Option<Hbar> {
        self.data().amount
    }

    pub(super) fn amount(&mut self, amount: Hbar) -> &mut Self {
        self.data_mut().amount = Some(amount);
        self
    }

    pub(super) fn get_max_amount(&self) -> Option<Hbar> {
        self.data().max_amount
    }

    pub(super) fn max_amount(&mut self, amount: impl Into<Option<Hbar>>) -> &mut Self {
        self.data_mut().max_amount = amount.into();
        self
    }
}

impl TransactionData for PaymentTransactionData {}

impl TransactionExecute for PaymentTransactionData {
    // noinspection DuplicatedCode
    fn execute(
        &self,
        channel: Channel,
        request: services::Transaction,
    ) -> BoxGrpcFuture<'_, services::TransactionResponse> {
        Box::pin(async { CryptoServiceClient::new(channel).crypto_transfer(request).await })
    }
}

impl ValidateChecksums for PaymentTransactionData {
    fn validate_checksums(&self, _ledger_id: &LedgerId) -> Result<(), Error> {
        Ok(())
    }
}

impl ToTransactionDataProtobuf for PaymentTransactionData {
    #[allow(clippy::cast_possible_wrap)]
    fn to_transaction_data_protobuf(
        &self,
        chunk_info: &ChunkInfo,
    ) -> services::transaction_body::Data {
        let (transaction_id, node_account_id) = chunk_info.assert_single_transaction();

        let amount = self.amount.unwrap_or_default();

        services::transaction_body::Data::CryptoTransfer(services::CryptoTransferTransactionBody {
            token_transfers: Vec::new(),
            transfers: Some(services::TransferList {
                account_amounts: vec![
                    services::AccountAmount {
                        account_id: Some(node_account_id.to_protobuf()),
                        amount: amount.to_tinybars(),
                        is_approval: false,
                    },
                    services::AccountAmount {
                        account_id: Some(transaction_id.account_id.to_protobuf()),
                        amount: -(amount.to_tinybars()),
                        is_approval: false,
                    },
                ],
            }),
        })
    }
}

impl From<PaymentTransactionData> for AnyTransactionData {
    fn from(_transaction: PaymentTransactionData) -> Self {
        // NOTE: this should only be reached if we try to serialize a PaymentTransaction
        //  as this is a private type that we have no intention of serializing, we should be good
        unreachable!()
    }
}