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
336
337
338
339
340
341
342
343
344
345
// this is the format cynic expects
#[allow(clippy::module_inception)]
pub mod schema {
    cynic::use_schema!("./assets/schema.sdl");
}

use fuel_core_types::fuel_tx;
use hex::FromHexError;
use std::{
    array::TryFromSliceError,
    fmt::{
        self,
        Debug,
    },
    io::ErrorKind,
    num::TryFromIntError,
};
use thiserror::Error;

pub use primitives::*;

pub mod balance;
pub mod block;
pub mod chain;
pub mod coin;
pub mod contract;
pub mod message;
pub mod node_info;
pub mod primitives;
pub mod resource;
pub mod tx;

#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema_path = "./assets/schema.sdl", graphql_type = "Query")]
pub struct Health {
    pub health: bool,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema_path = "./assets/schema.sdl", graphql_type = "Mutation")]
pub struct StartSession {
    pub start_session: cynic::Id,
}

#[derive(cynic::QueryVariables)]
pub struct IdArg {
    pub id: cynic::Id,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Mutation",
    variables = "IdArg"
)]
pub struct EndSession {
    #[arguments(id: $id)]
    pub end_session: bool,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Mutation",
    variables = "IdArg"
)]
pub struct Reset {
    #[arguments(id: $id)]
    pub reset: bool,
}

#[derive(cynic::QueryVariables)]
pub struct ExecuteArgs {
    pub id: cynic::Id,
    pub op: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Mutation",
    variables = "ExecuteArgs"
)]
pub struct Execute {
    #[arguments(id: $id, op: $op)]
    pub execute: bool,
}

#[derive(cynic::QueryVariables)]
pub struct RegisterArgs {
    pub id: cynic::Id,
    pub register: U64,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Query",
    variables = "RegisterArgs"
)]
pub struct Register {
    #[arguments(id: $id, register: $register)]
    pub register: U64,
}

#[derive(cynic::QueryVariables)]
pub struct MemoryArgs {
    pub id: cynic::Id,
    pub start: U64,
    pub size: U64,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Query",
    variables = "MemoryArgs"
)]
pub struct Memory {
    #[arguments(id: $id, start: $start, size: $size)]
    pub memory: String,
}

#[derive(cynic::QueryVariables, Debug)]
pub struct SetBreakpointArgs {
    pub id: cynic::Id,
    pub bp: Breakpoint,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Mutation",
    variables = "SetBreakpointArgs"
)]
pub struct SetBreakpoint {
    #[arguments(id: $id, breakpoint: $bp)]
    pub set_breakpoint: bool,
}

#[derive(cynic::InputObject, Debug)]
#[cynic(schema_path = "./assets/schema.sdl")]
pub struct Breakpoint {
    pub contract: ContractId,
    pub pc: U64,
}

#[derive(cynic::QueryVariables, Debug)]
pub struct SetSingleSteppingArgs {
    pub id: cynic::Id,
    pub enable: bool,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Mutation",
    variables = "SetSingleSteppingArgs"
)]
pub struct SetSingleStepping {
    #[arguments(id: $id, enable: $enable)]
    pub set_single_stepping: bool,
}

#[derive(cynic::QueryVariables, Debug)]
pub struct StartTxArgs {
    pub id: cynic::Id,
    pub tx: String,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Mutation",
    variables = "StartTxArgs"
)]
pub struct StartTx {
    #[arguments(id: $id, txJson: $tx)]
    pub start_tx: RunResult,
}

#[derive(cynic::QueryVariables, Debug)]
pub struct ContinueTxArgs {
    pub id: cynic::Id,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(
    schema_path = "./assets/schema.sdl",
    graphql_type = "Mutation",
    variables = "ContinueTxArgs"
)]
pub struct ContinueTx {
    #[arguments(id: $id)]
    pub continue_tx: RunResult,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema_path = "./assets/schema.sdl")]
pub struct RunResult {
    pub breakpoint: Option<OutputBreakpoint>,
    pub json_receipts: Vec<String>,
}

impl RunResult {
    pub fn receipts(&self) -> impl Iterator<Item = fuel_tx::Receipt> + '_ {
        self.json_receipts.iter().map(|r| {
            serde_json::from_str::<fuel_tx::Receipt>(r)
                .expect("Receipt deserialization failed, server/client version mismatch")
        })
    }
}

impl fmt::Display for RunResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let receipts: Vec<fuel_tx::Receipt> = self.receipts().collect();
        f.debug_struct("RunResult")
            .field("breakpoint", &self.breakpoint)
            .field("receipts", &receipts)
            .finish()
    }
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema_path = "./assets/schema.sdl")]
pub struct OutputBreakpoint {
    pub contract: ContractId,
    pub pc: U64,
}

/// Generic graphql pagination query args
#[derive(cynic::QueryVariables, Debug, Default)]
pub struct ConnectionArgs {
    /// Skip until cursor (forward pagination)
    pub after: Option<String>,
    /// Skip until cursor (backward pagination)
    pub before: Option<String>,
    /// Retrieve the first n items in order (forward pagination)
    pub first: Option<i32>,
    /// Retrieve the last n items in order (backward pagination).
    /// Can't be used at the same time as `first`.
    pub last: Option<i32>,
}

#[derive(cynic::QueryFragment, Debug)]
#[cynic(schema_path = "./assets/schema.sdl")]
pub struct PageInfo {
    pub end_cursor: Option<String>,
    pub has_next_page: bool,
    pub has_previous_page: bool,
    pub start_cursor: Option<String>,
}

/// Specifies the direction of a paginated query
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum PageDirection {
    Forward,
    Backward,
}

/// Used to parameterize paginated queries
#[derive(Clone, Debug)]
pub struct PaginationRequest<T> {
    /// The cursor returned from a previous query to indicate an offset
    pub cursor: Option<T>,
    /// The number of results to take
    pub results: usize,
    /// The direction of the query (e.g. asc, desc order).
    pub direction: PageDirection,
}

impl<T: Into<String>> From<PaginationRequest<T>> for ConnectionArgs {
    fn from(req: PaginationRequest<T>) -> Self {
        match req.direction {
            PageDirection::Forward => Self {
                after: req.cursor.map(Into::into),
                before: None,
                first: Some(req.results as i32),
                last: None,
            },
            PageDirection::Backward => Self {
                after: None,
                before: req.cursor.map(Into::into),
                first: None,
                last: Some(req.results as i32),
            },
        }
    }
}

pub struct PaginatedResult<T, C> {
    pub cursor: Option<C>,
    pub results: Vec<T>,
    pub has_next_page: bool,
    pub has_previous_page: bool,
}

#[derive(Error, Debug)]
#[non_exhaustive]
pub enum ConversionError {
    #[error("Field is required from the GraphQL response {0}")]
    MissingField(String),
    #[error("expected 0x prefix")]
    HexStringPrefixError,
    #[error("expected 32 bytes, received {0}")]
    HexString256LengthError(usize),
    #[error("hex parsing error {0}")]
    HexDecodingError(FromHexError),
    #[error("hex parsing error {0}")]
    HexError(String),
    #[error("failed integer conversion")]
    IntegerConversion,
    #[error("failed to deserialize transaction from bytes {0}")]
    TransactionFromBytesError(std::io::Error),
    #[error("failed to deserialize receipt from bytes {0}")]
    ReceiptFromBytesError(std::io::Error),
    #[error("failed to convert from bytes due to unexpected length")]
    BytesLength,
    #[error("Unknown variant of the {0} enum")]
    UnknownVariant(&'static str),
}

impl From<FromHexError> for ConversionError {
    fn from(hex_error: FromHexError) -> Self {
        Self::HexDecodingError(hex_error)
    }
}

impl From<ConversionError> for std::io::Error {
    fn from(e: ConversionError) -> Self {
        std::io::Error::new(ErrorKind::Other, e)
    }
}

impl From<TryFromIntError> for ConversionError {
    fn from(_: TryFromIntError) -> Self {
        ConversionError::IntegerConversion
    }
}

impl From<TryFromSliceError> for ConversionError {
    fn from(_: TryFromSliceError) -> Self {
        ConversionError::BytesLength
    }
}