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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use super::{
    block::Header,
    scalars::{
        Address,
        Bytes32,
        HexString,
        MessageId,
        TransactionId,
        U64,
    },
};
use crate::{
    database::Database,
    query::MessageProofData,
    state::IterDirection,
};
use anyhow::anyhow;
use async_graphql::{
    connection::{
        self,
        Connection,
        Edge,
        EmptyFields,
    },
    Context,
    Object,
};
use fuel_core_interfaces::{
    common::{
        fuel_storage::StorageAsRef,
        fuel_tx,
        fuel_types,
    },
    db::{
        FuelBlocks,
        KvStoreError,
        Messages,
        Receipts,
        SealedBlockConsensus,
        Transactions,
    },
    model::{
        self,
        FuelBlockConsensus,
    },
    not_found,
    txpool::TransactionStatus,
};
use itertools::Itertools;
use std::borrow::Cow;

pub struct Message(pub(crate) model::Message);

#[Object]
impl Message {
    async fn message_id(&self) -> MessageId {
        self.0.id().into()
    }

    async fn amount(&self) -> U64 {
        self.0.amount.into()
    }

    async fn sender(&self) -> Address {
        self.0.sender.into()
    }

    async fn recipient(&self) -> Address {
        self.0.recipient.into()
    }

    async fn nonce(&self) -> U64 {
        self.0.nonce.into()
    }

    async fn data(&self) -> HexString {
        self.0.data.clone().into()
    }

    async fn da_height(&self) -> U64 {
        self.0.da_height.as_u64().into()
    }

    async fn fuel_block_spend(&self) -> Option<U64> {
        self.0.fuel_block_spend.map(|v| v.into())
    }
}

#[derive(Default)]
pub struct MessageQuery {}

#[Object]
impl MessageQuery {
    async fn messages(
        &self,
        ctx: &Context<'_>,
        #[graphql(desc = "address of the owner")] owner: Option<Address>,
        first: Option<i32>,
        after: Option<String>,
        last: Option<i32>,
        before: Option<String>,
    ) -> async_graphql::Result<Connection<MessageId, Message, EmptyFields, EmptyFields>>
    {
        let db = ctx.data_unchecked::<Database>().clone();

        connection::query(
            after,
            before,
            first,
            last,
            |after: Option<MessageId>, before: Option<MessageId>, first, last| {
                async move {
                    let (records_to_fetch, direction) = if let Some(first) = first {
                        (first, IterDirection::Forward)
                    } else if let Some(last) = last {
                        (last, IterDirection::Reverse)
                    } else {
                        (0, IterDirection::Forward)
                    };

                    if (first.is_some() && before.is_some())
                        || (after.is_some() && before.is_some())
                        || (last.is_some() && after.is_some())
                    {
                        return Err(anyhow!("Wrong argument combination"))
                    }

                    let start = if direction == IterDirection::Forward {
                        after
                    } else {
                        before
                    };

                    let (mut messages, has_next_page, has_previous_page) =
                        if let Some(owner) = owner {
                            let mut message_ids = db.owned_message_ids(
                                &owner.0,
                                start.map(Into::into),
                                Some(direction),
                            );
                            let mut started = None;
                            if start.is_some() {
                                // skip initial result
                                started = message_ids.next();
                            }
                            let message_ids = message_ids.take(records_to_fetch + 1);
                            let message_ids: Vec<fuel_types::MessageId> =
                                message_ids.try_collect()?;
                            let has_next_page = message_ids.len() > records_to_fetch;

                            let messages: Vec<model::Message> = message_ids
                                .iter()
                                .take(records_to_fetch)
                                .map(|msg_id| {
                                    db.storage::<Messages>()
                                        .get(msg_id)
                                        .transpose()
                                        .ok_or(not_found!(Messages))?
                                        .map(|f| f.into_owned())
                                })
                                .try_collect()?;
                            (messages, has_next_page, started.is_some())
                        } else {
                            let mut messages =
                                db.all_messages(start.map(Into::into), Some(direction));
                            let mut started = None;
                            if start.is_some() {
                                // skip initial result
                                started = messages.next();
                            }
                            let messages: Vec<model::Message> =
                                messages.take(records_to_fetch + 1).try_collect()?;
                            let has_next_page = messages.len() > records_to_fetch;
                            let messages =
                                messages.into_iter().take(records_to_fetch).collect();
                            (messages, has_next_page, started.is_some())
                        };

                    // reverse after filtering next page test record to maintain consistent ordering
                    // in the response regardless of whether first or last was used.
                    if direction == IterDirection::Forward {
                        messages.reverse();
                    }

                    let mut connection =
                        Connection::new(has_previous_page, has_next_page);

                    connection.edges.extend(
                        messages.into_iter().map(|message| {
                            Edge::new(message.id().into(), Message(message))
                        }),
                    );

                    Ok::<Connection<MessageId, Message>, anyhow::Error>(connection)
                }
            },
        )
        .await
    }

    async fn message_proof(
        &self,
        ctx: &Context<'_>,
        transaction_id: TransactionId,
        message_id: MessageId,
    ) -> async_graphql::Result<Option<MessageProof>> {
        let data = MessageProofContext(ctx.data_unchecked());
        Ok(
            crate::query::message_proof(&data, transaction_id.into(), message_id.into())
                .await?
                .map(MessageProof),
        )
    }
}

pub struct MessageProof(pub(crate) model::MessageProof);

#[Object]
impl MessageProof {
    async fn proof_set(&self) -> Vec<Bytes32> {
        self.0
            .proof_set
            .iter()
            .cloned()
            .map(Bytes32::from)
            .collect()
    }

    async fn proof_index(&self) -> U64 {
        self.0.proof_index.into()
    }

    async fn sender(&self) -> Address {
        self.0.sender.into()
    }

    async fn recipient(&self) -> Address {
        self.0.recipient.into()
    }

    async fn nonce(&self) -> Bytes32 {
        self.0.nonce.into()
    }

    async fn amount(&self) -> U64 {
        self.0.amount.into()
    }

    async fn data(&self) -> HexString {
        self.0.data.clone().into()
    }

    async fn signature(&self) -> super::scalars::Signature {
        self.0.signature.into()
    }

    async fn header(&self) -> Header {
        Header(self.0.header.clone())
    }
}

struct MessageProofContext<'a>(&'a Database);

impl MessageProofData for MessageProofContext<'_> {
    fn receipts(
        &self,
        transaction_id: &fuel_core_interfaces::common::prelude::Bytes32,
    ) -> Result<Vec<fuel_core_interfaces::common::prelude::Receipt>, KvStoreError> {
        Ok(self
            .0
            .storage::<Receipts>()
            .get(transaction_id)?
            .map(Cow::into_owned)
            .unwrap_or_else(|| Vec::with_capacity(0)))
    }

    fn transaction(
        &self,
        transaction_id: &fuel_core_interfaces::common::prelude::Bytes32,
    ) -> Result<Option<fuel_tx::Transaction>, KvStoreError> {
        Ok(self
            .0
            .storage::<Transactions>()
            .get(transaction_id)?
            .map(Cow::into_owned))
    }

    fn transaction_status(
        &self,
        transaction_id: &fuel_core_interfaces::common::prelude::Bytes32,
    ) -> Result<Option<TransactionStatus>, KvStoreError> {
        Ok(self.0.get_tx_status(transaction_id)?)
    }

    fn transactions_on_block(
        &self,
        block_id: &fuel_core_interfaces::common::prelude::Bytes32,
    ) -> Result<Vec<fuel_core_interfaces::common::prelude::Bytes32>, KvStoreError> {
        Ok(self
            .0
            .storage::<FuelBlocks>()
            .get(block_id)?
            .map(|block| block.into_owned().transactions)
            .unwrap_or_else(|| Vec::with_capacity(0)))
    }

    fn signature(
        &self,
        block_id: &fuel_core_interfaces::common::prelude::Bytes32,
    ) -> Result<Option<fuel_core_interfaces::common::fuel_crypto::Signature>, KvStoreError>
    {
        match self
            .0
            .storage::<SealedBlockConsensus>()
            .get(block_id)?
            .map(Cow::into_owned)
        {
            // TODO: https://github.com/FuelLabs/fuel-core/issues/816
            Some(FuelBlockConsensus::Genesis(_)) => Ok(Default::default()),
            Some(FuelBlockConsensus::PoA(c)) => Ok(Some(c.signature)),
            None => Ok(None),
        }
    }

    fn block(
        &self,
        block_id: &fuel_core_interfaces::common::prelude::Bytes32,
    ) -> Result<Option<model::FuelBlockDb>, KvStoreError> {
        Ok(self
            .0
            .storage::<FuelBlocks>()
            .get(block_id)?
            .map(Cow::into_owned))
    }
}