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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
 * ‌
 * 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 futures_core::future::BoxFuture;
use time::Duration;

use crate::execute::execute;
use crate::query::cost::QueryCost;
use crate::query::payment_transaction::PaymentTransaction;
use crate::{
    AccountId,
    Client,
    Error,
    Hbar,
    TransactionId,
    TransactionReceiptQuery,
};

mod any;
mod cost;
mod execute;
pub(super) mod payment_transaction;
mod protobuf;

pub(crate) use any::AnyQueryData;
pub use any::{
    AnyQuery,
    AnyQueryResponse,
};
pub(crate) use execute::{
    response_header,
    QueryExecute,
};
pub(crate) use protobuf::ToQueryProtobuf;

/// A query that can be executed on the Hedera network.
#[derive(Debug, Default)]
pub struct Query<D>
where
    D: QueryExecute,
{
    pub(crate) data: D,
    pub(crate) payment: PaymentTransaction,
}

impl<D> Query<D>
where
    D: QueryExecute + Default,
{
    /// Create a new query ready for configuration and execution.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl<D> Query<D>
where
    D: QueryExecute,
{
    /// Returns the account IDs of the nodes that this query may be submitted to.
    ///
    /// Defaults to the full list of nodes configured on the client; or, the node account IDs
    /// configured on the query payment transaction (if explicitly provided).
    #[must_use]
    pub fn get_node_account_ids(&self) -> Option<&[AccountId]> {
        self.payment.get_node_account_ids()
    }

    /// Sets the account IDs of the nodes that this query may be submitted to.
    ///
    /// Defaults to the full list of nodes configured on the client; or, the node account IDs
    /// configured on the query payment transaction (if explicitly provided).
    pub fn node_account_ids(&mut self, ids: impl IntoIterator<Item = AccountId>) -> &mut Self {
        self.payment.node_account_ids(ids);
        self
    }

    /// Returns the explicit payment amount for this query.
    ///
    /// The client will submit exactly this amount for the payment of this query. Hedera
    /// will not return any remainder (over the actual cost for this query).
    #[must_use]
    pub fn get_payment_amount(&self) -> Option<Hbar> {
        self.payment.get_amount()
    }

    /// Sets the explicit payment amount for this query.
    ///
    /// The client will submit exactly this amount for the payment of this query. Hedera
    /// will not return any remainder (over the actual cost for this query).
    pub fn payment_amount(&mut self, amount: Hbar) -> &mut Self {
        self.payment.amount(amount);
        self
    }

    /// Returns the maximum payment allowable for this query.
    #[must_use]
    pub fn get_max_amount(&self) -> Option<Hbar> {
        self.payment.get_max_amount()
    }

    /// Sets the maximum payment allowable for this query.
    ///
    /// When a query is executed without an explicit payment amount set,
    /// the client will first request the cost of the given query from the node it will be
    /// submitted to and attach a payment for that amount from the operator account on the client.
    ///
    /// If the returned value is greater than this value, a [`MaxQueryPaymentExceeded`](crate::Error::MaxQueryPaymentExceeded) error
    /// will be returned.
    ///
    /// Defaults to the maximum payment amount configured on the client.
    ///
    /// Sets to `None` to allow unlimited payment amounts.
    pub fn max_payment_amount(&mut self, max: impl Into<Option<Hbar>>) -> &mut Self {
        self.payment.max_amount(max);
        self
    }

    /// Returns the duration that the payment transaction is valid for, once finalized and signed.
    #[must_use]
    pub fn get_payment_transaction_valid_duration(&self) -> Option<Duration> {
        self.payment.get_transaction_valid_duration()
    }

    /// Sets the duration that the payment transaction is valid for, once finalized and signed.
    ///
    /// Defaults to 120 seconds (or two minutes).
    pub fn payment_transaction_valid_duration(&mut self, duration: Duration) -> &mut Self {
        self.payment.transaction_valid_duration(duration);
        self
    }

    /// Returns the maximum transaction fee the payer account is willing to pay
    /// for the query payment transaction.
    #[must_use]
    pub fn get_max_payment_transaction_fee(&self) -> Option<Hbar> {
        self.payment.get_max_transaction_fee()
    }

    /// Sets the maximum transaction fee the payer account is willing to pay for the query
    /// payment transaction.
    ///
    /// Defaults to 1 hbar.
    pub fn max_payment_transaction_fee(&mut self, fee: Hbar) -> &mut Self {
        self.payment.max_transaction_fee(fee);
        self
    }

    /// Returns the note / description that should be recorded in the transaction record for the payment transaction.
    #[must_use]
    pub fn get_payment_transaction_memo(&self) -> &str {
        self.payment.get_transaction_memo()
    }

    /// Sets a note / description that should be recorded in the transaction record for the payment transaction.
    ///
    /// Maximum length of 100 characters.
    pub fn payment_transaction_memo(&mut self, memo: impl AsRef<str>) -> &mut Self {
        self.payment.transaction_memo(memo);
        self
    }

    /// Returns the explicit transaction ID used to identify this query's payment transaction, if set
    /// .
    #[must_use]
    pub fn get_payment_transaction_id(&self) -> Option<TransactionId> {
        self.payment.get_transaction_id()
    }

    /// Sets an explicit transaction ID to use to identify the payment transaction
    /// on this query.
    ///
    /// Overrides payer account defined on this query or on the client.
    pub fn payment_transaction_id(&mut self, id: TransactionId) -> &mut Self {
        self.payment.transaction_id(id);
        self
    }

    /// Fetch the cost of this query.
    pub async fn get_cost(&self, client: &Client) -> crate::Result<Hbar> {
        self.get_cost_with_optional_timeout(client, None).await
    }

    pub(crate) async fn get_cost_with_optional_timeout(
        &self,
        client: &Client,
        timeout: Option<std::time::Duration>,
    ) -> crate::Result<Hbar> {
        if !self.data.is_payment_required() {
            return Ok(Hbar::ZERO);
        }

        QueryCost::new(self).execute(client, timeout).await
    }

    /// Fetch the cost of this query.
    pub async fn get_cost_with_timeout(
        &self,
        client: &Client,
        timeout: std::time::Duration,
    ) -> crate::Result<Hbar> {
        self.get_cost_with_optional_timeout(client, Some(timeout)).await
    }
}

impl<D> Query<D>
where
    D: QueryExecute,
{
    /// Execute this query against the provided client of the Hedera network.
    // todo:
    #[allow(clippy::missing_errors_doc)]
    pub async fn execute(&mut self, client: &Client) -> crate::Result<D::Response> {
        self.execute_with_optional_timeout(client, None).await
    }

    // eww long name
    pub(crate) async fn execute_with_optional_timeout(
        &mut self,
        client: &Client,
        timeout: Option<std::time::Duration>,
    ) -> crate::Result<D::Response> {
        fn recurse_receipt(
            transaction_id: &TransactionId,
            client: Client,
            timeout: Option<std::time::Duration>,
        ) -> BoxFuture<'_, ()> {
            Box::pin(async move {
                let _ = TransactionReceiptQuery::new()
                    .transaction_id(*transaction_id)
                    .execute_with_optional_timeout(&client, timeout)
                    .await;
            })
        }

        // hack: this is a TransactionRecordQuery, which means we need to run the receipt first.
        if let Some(transaction_id) = self.data.transaction_id() {
            if self.data.is_payment_required() {
                let client = client.clone();
                recurse_receipt(&transaction_id, client, timeout).await;
            }
        }

        if self.payment.get_amount().is_none() && self.data.is_payment_required() {
            // should this inherit the timeout?
            // payment is required but none was specified, query the cost
            let cost = QueryCost::new(self).execute(client, None).await?;

            if self.payment.get_max_amount().is_none() {
                // N.B. This can still be `None`.
                self.payment.max_amount(client.default_max_query_payment());
            }

            if let Some(max_amount) = self.payment.get_max_amount() {
                if cost > max_amount {
                    return Err(Error::MaxQueryPaymentExceeded {
                        query_cost: cost,
                        max_query_payment: max_amount,
                    });
                }
            }

            self.payment.amount(cost);
        }

        if self.data.is_payment_required() {
            self.payment.freeze_with(client)?;
        }

        execute(client, self, timeout).await
    }

    /// Execute this query against the provided client of the Hedera network.
    // todo:
    #[allow(clippy::missing_errors_doc)]
    pub async fn execute_with_timeout(
        &mut self,
        client: &Client,
        timeout: std::time::Duration,
    ) -> crate::Result<D::Response> {
        self.execute_with_optional_timeout(client, Some(timeout)).await
    }
}