fuel-core-client 0.48.0

Tx client and schema specification.
Documentation
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
use self::schema::{
    block::ProduceBlockArgs,
    message::{
        MessageProofArgs,
        NonceArgs,
    },
};
#[cfg(feature = "subscriptions")]
use crate::client::types::StatusWithTransaction;
use crate::{
    client::{
        schema::{
            Tai64Timestamp,
            TransactionId,
            block::BlockByHeightArgs,
            coins::{
                ExcludeInput,
                SpendQueryElementInput,
            },
            contract::ContractBalanceQueryArgs,
            gas_price::EstimateGasPrice,
            message::MessageStatusArgs,
            relayed_tx::RelayedTransactionStatusArgs,
            tx::{
                DryRunArg,
                TxWithEstimatedPredicatesArg,
            },
        },
        types::{
            RelayedTransactionStatus,
            asset::AssetDetail,
            gas_price::LatestGasPrice,
            message::MessageStatus,
            primitives::{
                Address,
                AssetId,
                BlockId,
                ContractId,
                UtxoId,
            },
            upgrades::StateTransitionBytecode,
        },
    },
    reqwest_ext::FuelGraphQlResponse,
    transport::FailoverTransport,
};
use anyhow::{
    Context,
    anyhow,
};
#[cfg(feature = "subscriptions")]
use cynic::SubscriptionBuilder;
use cynic::{
    Id,
    MutationBuilder,
    Operation,
    QueryBuilder,
    QueryFragment,
    QueryVariables,
};
use fuel_core_types::{
    blockchain::header::{
        ConsensusParametersVersion,
        StateTransitionBytecodeVersion,
    },
    fuel_asm::{
        Instruction,
        Word,
    },
    fuel_tx::{
        BlobId,
        Bytes32,
        ConsensusParameters,
        Receipt,
        Transaction,
        TxId,
    },
    fuel_types::{
        self,
        BlockHeight,
        Nonce,
        canonical::Serialize,
    },
    services::executor::{
        StorageReadReplayEvent,
        TransactionExecutionStatus,
    },
};
#[cfg(feature = "subscriptions")]
use futures::{
    Stream,
    StreamExt,
};
use itertools::Itertools;
use pagination::{
    PageDirection,
    PaginatedResult,
    PaginationRequest,
};
use reqwest::Url;
use schema::{
    Bytes,
    ContinueTx,
    ContinueTxArgs,
    ConversionError,
    HexString,
    IdArg,
    MemoryArgs,
    RegisterArgs,
    RunResult,
    SetBreakpoint,
    SetBreakpointArgs,
    SetSingleStepping,
    SetSingleSteppingArgs,
    StartTx,
    StartTxArgs,
    U32,
    U64,
    assets::AssetInfoArg,
    balance::BalanceArgs,
    blob::BlobByIdArgs,
    block::BlockByIdArgs,
    coins::{
        CoinByIdArgs,
        CoinsConnectionArgs,
    },
    contract::{
        ContractBalancesConnectionArgs,
        ContractByIdArgs,
    },
    da_compressed::DaCompressedBlockByHeightArgs,
    gas_price::BlockHorizonArgs,
    storage_read_replay::{
        StorageReadReplay,
        StorageReadReplayArgs,
    },
    tx::{
        AssembleTxArg,
        TransactionsByOwnerConnectionArgs,
        TxArg,
        TxIdArgs,
    },
};
#[cfg(feature = "subscriptions")]
use std::future;
use std::{
    convert::TryInto,
    io::{
        self,
        ErrorKind,
    },
    net,
    str::{
        self,
        FromStr,
    },
    sync::{
        Arc,
        Mutex,
    },
};
use tai64::Tai64;
use tracing as _;
use types::{
    TransactionResponse,
    TransactionStatus,
    assemble_tx::{
        AssembleTransactionResult,
        RequiredBalance,
    },
};

#[cfg(feature = "subscriptions")]
use std::pin::Pin;

#[cfg(feature = "rpc")]
mod rpc_deps {
    pub use aws_config::{
        BehaviorVersion,
        default_provider::credentials::DefaultCredentialsChain,
    };
    pub use aws_sdk_s3::Client as AWSClient;
    pub use flate2::read::GzDecoder;
    pub use fuel_core_block_aggregator_api::{
        blocks::old_block_source::convertor_adapter::proto_to_fuel_conversions::fuel_block_from_protobuf,
        protobuf_types::{
            Block as ProtoBlock,
            BlockHeightRequest as ProtoBlockHeightRequest,
            BlockRangeRequest as ProtoBlockRangeRequest,
            BlockResponse,
            NewBlockSubscriptionRequest as ProtoNewBlockSubscriptionRequest,
            RemoteBlockResponse,
            RemoteS3Bucket,
            block_aggregator_client::BlockAggregatorClient as ProtoBlockAggregatorClient,
            block_response::Payload,
            remote_block_response::Location,
        },
    };
    pub use prost::Message;
    pub use std::{
        collections::HashMap,
        io::Read,
    };
    pub use tokio::sync::RwLock;
    pub use tonic::transport::Channel;
}
#[cfg(feature = "rpc")]
use rpc_deps::*;

pub mod pagination;
pub mod schema;
pub mod types;

type RegisterId = u32;

#[derive(Debug, derive_more::Display, derive_more::From)]
#[non_exhaustive]
/// Error occurring during interaction with the FuelClient
// anyhow::Error is wrapped inside a custom Error type,
// so that we can specific error variants in the future.
pub enum Error {
    /// Unknown or not expected(by architecture) error.
    #[from]
    Other(anyhow::Error),
}

/// Consistency policy for the [`FuelClient`] to define the strategy
/// for the required height feature.
#[derive(Debug)]
pub enum ConsistencyPolicy {
    /// Automatically fetch the next block height from the response and
    /// use it as an input to the next query to guarantee consistency
    /// of the results for the queries.
    Auto {
        /// The required block height for the queries.
        height: Arc<Mutex<Option<BlockHeight>>>,
    },
    /// Use manually sets the block height for all queries
    /// via the [`FuelClient::with_required_fuel_block_height`].
    Manual {
        /// The required block height for the queries.
        height: Option<BlockHeight>,
    },
}

impl Clone for ConsistencyPolicy {
    fn clone(&self) -> Self {
        match self {
            Self::Auto { height } => Self::Auto {
                // We don't want to share the same mutex between the different
                // instances of the `FuelClient`.
                height: Arc::new(Mutex::new(height.lock().ok().and_then(|h| *h))),
            },
            Self::Manual { height } => Self::Manual { height: *height },
        }
    }
}

#[derive(Debug, Default)]
struct ChainStateInfo {
    current_stf_version: Arc<Mutex<Option<StateTransitionBytecodeVersion>>>,
    current_consensus_parameters_version: Arc<Mutex<Option<ConsensusParametersVersion>>>,
}

impl Clone for ChainStateInfo {
    fn clone(&self) -> Self {
        Self {
            current_stf_version: Arc::new(Mutex::new(
                self.current_stf_version.lock().ok().and_then(|v| *v),
            )),
            current_consensus_parameters_version: Arc::new(Mutex::new(
                self.current_consensus_parameters_version
                    .lock()
                    .ok()
                    .and_then(|v| *v),
            )),
        }
    }
}

#[derive(Debug, Clone)]
pub struct FuelClient {
    transport: FailoverTransport,
    require_height: ConsistencyPolicy,
    chain_state_info: ChainStateInfo,
    #[cfg(feature = "rpc")]
    rpc_client: Option<ProtoBlockAggregatorClient<Channel>>,
    #[cfg(feature = "rpc")]
    aws_client: AWSClientManager,
}

#[cfg(feature = "rpc")]
#[derive(Debug, Clone)]
pub struct AWSClientManager {
    specific: Arc<RwLock<HashMap<Option<String>, AWSClient>>>,
}

#[cfg(feature = "rpc")]
impl AWSClientManager {
    pub fn new() -> Self {
        Self {
            specific: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    pub async fn get_client(&self, url: &Option<String>) -> Result<AWSClient, io::Error> {
        if let Some(existing) = self.specific.read().await.get(url).cloned() {
            return Ok(existing);
        }
        let client = FuelClient::new_aws_client(url).await;
        let mut guard = self.specific.write().await;
        let client = guard
            .entry(url.clone())
            .or_insert_with(|| client.clone())
            .clone();
        Ok(client)
    }
}

#[cfg(feature = "rpc")]
impl Default for AWSClientManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Normalizes a URL string by ensuring it has an http(s) scheme and the `/v1/graphql` path.
fn normalize_url(url_str: &str) -> anyhow::Result<Url> {
    let mut raw_url = url_str.to_string();
    if !raw_url.starts_with("http") {
        raw_url = format!("http://{raw_url}");
    }

    let mut url = reqwest::Url::parse(&raw_url)
        .map_err(anyhow::Error::msg)
        .with_context(|| format!("Invalid fuel-core URL: {url_str}"))?;
    url.set_path("/v1/graphql");

    Ok(url)
}

impl FromStr for FuelClient {
    type Err = anyhow::Error;

    fn from_str(str: &str) -> Result<Self, Self::Err> {
        let url = normalize_url(str)?;

        Ok(Self {
            transport: FailoverTransport::new(vec![url])?,
            require_height: ConsistencyPolicy::Auto {
                height: Arc::new(Mutex::new(None)),
            },
            chain_state_info: Default::default(),
            #[cfg(feature = "rpc")]
            rpc_client: None,
            #[cfg(feature = "rpc")]
            aws_client: AWSClientManager::new(),
        })
    }
}

impl<S> From<S> for FuelClient
where
    S: Into<net::SocketAddr>,
{
    fn from(socket: S) -> Self {
        format!("http://{}", socket.into())
            .as_str()
            .parse()
            .unwrap()
    }
}

pub fn from_strings_errors_to_std_error(errors: Vec<String>) -> io::Error {
    let e = errors
        .into_iter()
        .fold(String::from("Response errors"), |mut s, e| {
            s.push_str("; ");
            s.push_str(e.as_str());
            s
        });
    io::Error::other(e)
}

impl FuelClient {
    pub fn new(url: impl AsRef<str>) -> anyhow::Result<Self> {
        Self::from_str(url.as_ref())
    }

    #[cfg(feature = "rpc")]
    pub async fn new_with_rpc<G: AsRef<str>, R: AsRef<str>>(
        graph_ql_urls: impl Iterator<Item = G>,
        rpc_url: R,
    ) -> anyhow::Result<Self> {
        let urls: Vec<_> = graph_ql_urls
            .map(|str| normalize_url(str.as_ref()))
            .try_collect()?;
        let mut client = Self::with_urls(&urls)?;
        let mut raw_rpc_url = <R as AsRef<str>>::as_ref(&rpc_url).to_string();
        if !raw_rpc_url.starts_with("http") {
            raw_rpc_url = format!("http://{raw_rpc_url}");
        }
        let rpc_client = ProtoBlockAggregatorClient::connect(raw_rpc_url).await?;
        client.rpc_client = Some(rpc_client);
        client.aws_client = AWSClientManager::new();
        Ok(client)
    }

    pub fn with_urls(urls: &[impl AsRef<str>]) -> anyhow::Result<Self> {
        if urls.is_empty() {
            return Err(anyhow!("Failed to create FuelClient. No URL is provided."));
        }
        let urls = urls
            .iter()
            .map(|url| normalize_url(url.as_ref()))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self {
            transport: FailoverTransport::new(urls)?,
            require_height: ConsistencyPolicy::Auto {
                height: Arc::new(Mutex::new(None)),
            },
            chain_state_info: Default::default(),
            #[cfg(feature = "rpc")]
            rpc_client: None,
            #[cfg(feature = "rpc")]
            aws_client: AWSClientManager::new(),
        })
    }

    pub fn get_default_url(&self) -> &Url {
        self.transport.get_default_url()
    }
}

impl FuelClient {
    pub fn with_required_fuel_block_height(
        &mut self,
        new_height: Option<BlockHeight>,
    ) -> &mut Self {
        match &mut self.require_height {
            ConsistencyPolicy::Auto { height } => {
                *height.lock().expect("Mutex poisoned") = new_height;
            }
            ConsistencyPolicy::Manual { height } => {
                *height = new_height;
            }
        }
        self
    }

    pub fn use_manual_consistency_policy(
        &mut self,
        height: Option<BlockHeight>,
    ) -> &mut Self {
        self.require_height = ConsistencyPolicy::Manual { height };
        self
    }

    pub fn decode_response<R, E>(
        &self,
        response: FuelGraphQlResponse<R, E>,
    ) -> io::Result<R>
    where
        R: serde::de::DeserializeOwned + 'static,
    {
        if response
            .extensions
            .as_ref()
            .and_then(|e| e.fuel_block_height_precondition_failed)
            == Some(true)
        {
            return Err(io::Error::other("The required block height was not met"));
        }

        let response = response.response;

        match (response.data, response.errors) {
            (Some(d), _) => Ok(d),
            (_, Some(e)) => Err(from_strings_errors_to_std_error(
                e.into_iter().map(|e| e.message).collect(),
            )),
            _ => Err(io::Error::other("Invalid response")),
        }
    }

    pub fn required_block_height(&self) -> Option<BlockHeight> {
        match &self.require_height {
            ConsistencyPolicy::Auto { height } => height.lock().ok().and_then(|h| *h),
            ConsistencyPolicy::Manual { height } => *height,
        }
    }

    fn update_chain_state_info<R, E>(&self, response: &FuelGraphQlResponse<R, E>) {
        if let Some(current_sft_version) = response
            .extensions
            .as_ref()
            .and_then(|e| e.current_stf_version)
            && let Ok(mut c) = self.chain_state_info.current_stf_version.lock()
        {
            *c = Some(current_sft_version);
        }

        if let Some(current_consensus_parameters_version) = response
            .extensions
            .as_ref()
            .and_then(|e| e.current_consensus_parameters_version)
            && let Ok(mut c) = self
                .chain_state_info
                .current_consensus_parameters_version
                .lock()
        {
            *c = Some(current_consensus_parameters_version);
        }

        let inner_required_height = match &self.require_height {
            ConsistencyPolicy::Auto { height } => Some(height.clone()),
            ConsistencyPolicy::Manual { .. } => None,
        };

        if let Some(inner_required_height) = inner_required_height
            && let Some(current_fuel_block_height) = response
                .extensions
                .as_ref()
                .and_then(|e| e.current_fuel_block_height)
        {
            let mut lock = inner_required_height.lock().expect("Mutex poisoned");

            if current_fuel_block_height >= lock.unwrap_or_default() {
                *lock = Some(current_fuel_block_height);
            }
        }
    }

    /// Send the GraphQL query to the client.
    pub async fn query<ResponseData, Vars>(
        &self,
        q: Operation<ResponseData, Vars>,
    ) -> io::Result<ResponseData>
    where
        Vars: serde::Serialize + Clone + QueryVariables + Send + 'static,
        ResponseData: serde::de::DeserializeOwned + QueryFragment + Send + 'static,
    {
        let required_fuel_block_height = self.required_block_height();
        let response = self.transport.query(q, required_fuel_block_height).await?;

        self.update_chain_state_info(&response);
        self.decode_response(response)
    }

    #[tracing::instrument(skip_all)]
    #[cfg(feature = "subscriptions")]
    async fn subscribe<ResponseData, Variables>(
        &self,
        variables: Variables,
    ) -> io::Result<Pin<Box<impl futures::Stream<Item = io::Result<ResponseData>> + '_>>>
    where
        Variables: serde::Serialize + QueryVariables + Send + Clone + 'static,
        ResponseData: serde::de::DeserializeOwned
            + QueryFragment
            + SubscriptionBuilder<Variables>
            + 'static
            + Send,
    {
        let stream = self
            .transport
            .subscribe(variables, self.required_block_height())
            .await?;

        let client = self; // capture immutably
        Ok(Box::pin(stream.filter_map(move |result| {
            async move {
                match result {
                    Ok(resp) => {
                        client.update_chain_state_info(&resp);
                        Some(client.decode_response(resp))
                    }
                    Err(e) => Some(Err(e)), // pass through untouched
                }
            }
        })))
    }

    pub fn latest_stf_version(&self) -> Option<StateTransitionBytecodeVersion> {
        self.chain_state_info
            .current_stf_version
            .lock()
            .ok()
            .and_then(|value| *value)
    }

    pub fn latest_consensus_parameters_version(
        &self,
    ) -> Option<ConsensusParametersVersion> {
        self.chain_state_info
            .current_consensus_parameters_version
            .lock()
            .ok()
            .and_then(|value| *value)
    }

    pub async fn health(&self) -> io::Result<bool> {
        let query = schema::Health::build(());
        self.query(query).await.map(|r| r.health)
    }

    pub async fn node_info(&self) -> io::Result<types::NodeInfo> {
        let query = schema::node_info::QueryNodeInfo::build(());
        self.query(query).await.map(|r| r.node_info.into())
    }

    pub async fn latest_gas_price(&self) -> io::Result<LatestGasPrice> {
        let query = schema::gas_price::QueryLatestGasPrice::build(());
        self.query(query).await.map(|r| r.latest_gas_price.into())
    }

    pub async fn estimate_gas_price(
        &self,
        block_horizon: u32,
    ) -> io::Result<EstimateGasPrice> {
        let args = BlockHorizonArgs {
            block_horizon: Some(block_horizon.into()),
        };
        let query = schema::gas_price::QueryEstimateGasPrice::build(args);
        self.query(query).await.map(|r| r.estimate_gas_price)
    }

    #[cfg(feature = "std")]
    pub async fn connected_peers_info(
        &self,
    ) -> io::Result<Vec<fuel_core_types::services::p2p::PeerInfo>> {
        let query = schema::node_info::QueryPeersInfo::build(());
        self.query(query)
            .await
            .map(|r| r.node_info.peers.into_iter().map(Into::into).collect())
    }

    pub async fn chain_info(&self) -> io::Result<types::ChainInfo> {
        let query = schema::chain::ChainQuery::build(());
        self.query(query).await.and_then(|r| {
            let result = r.chain.try_into()?;
            Ok(result)
        })
    }

    pub async fn consensus_parameters(
        &self,
        version: i32,
    ) -> io::Result<Option<ConsensusParameters>> {
        let args = schema::upgrades::ConsensusParametersByVersionArgs { version };
        let query = schema::upgrades::ConsensusParametersByVersionQuery::build(args);

        let result = self
            .query(query)
            .await?
            .consensus_parameters
            .map(TryInto::try_into)
            .transpose()?;

        Ok(result)
    }

    pub async fn state_transition_byte_code_by_version(
        &self,
        version: i32,
    ) -> io::Result<Option<StateTransitionBytecode>> {
        let args = schema::upgrades::StateTransitionBytecodeByVersionArgs { version };
        let query = schema::upgrades::StateTransitionBytecodeByVersionQuery::build(args);

        let result = self
            .query(query)
            .await?
            .state_transition_bytecode_by_version
            .map(TryInto::try_into)
            .transpose()?;

        Ok(result)
    }

    pub async fn state_transition_byte_code_by_root(
        &self,
        root: Bytes32,
    ) -> io::Result<Option<StateTransitionBytecode>> {
        let args = schema::upgrades::StateTransitionBytecodeByRootArgs {
            root: HexString(Bytes(root.to_vec())),
        };
        let query = schema::upgrades::StateTransitionBytecodeByRootQuery::build(args);

        let result = self
            .query(query)
            .await?
            .state_transition_bytecode_by_root
            .map(TryInto::try_into)
            .transpose()?;

        Ok(result)
    }

    /// Default dry run, matching the exact configuration as the node
    pub async fn dry_run(
        &self,
        txs: &[Transaction],
    ) -> io::Result<Vec<TransactionExecutionStatus>> {
        self.dry_run_opt(txs, None, None, None).await
    }

    /// Dry run with options to override the node behavior
    pub async fn dry_run_opt(
        &self,
        txs: &[Transaction],
        // Disable utxo input checks (exists, unspent, and valid signature)
        utxo_validation: Option<bool>,
        gas_price: Option<u64>,
        at_height: Option<BlockHeight>,
    ) -> io::Result<Vec<TransactionExecutionStatus>> {
        let txs = txs
            .iter()
            .map(|tx| HexString(Bytes(tx.to_bytes())))
            .collect::<Vec<HexString>>();
        let query: Operation<schema::tx::DryRun, DryRunArg> =
            schema::tx::DryRun::build(DryRunArg {
                txs,
                utxo_validation,
                gas_price: gas_price.map(|gp| gp.into()),
                block_height: at_height.map(|bh| bh.into()),
            });
        let tx_statuses = self.query(query).await.map(|r| r.dry_run)?;
        tx_statuses
            .into_iter()
            .map(|tx_status| tx_status.try_into().map_err(Into::into))
            .collect()
    }

    /// Like `dry_run_opt`, but also returns the storage reads
    pub async fn dry_run_opt_record_storage_reads(
        &self,
        txs: &[Transaction],
        // Disable utxo input checks (exists, unspent, and valid signature)
        utxo_validation: Option<bool>,
        gas_price: Option<u64>,
        at_height: Option<BlockHeight>,
    ) -> io::Result<(Vec<TransactionExecutionStatus>, Vec<StorageReadReplayEvent>)> {
        let txs = txs
            .iter()
            .map(|tx| HexString(Bytes(tx.to_bytes())))
            .collect::<Vec<HexString>>();
        let query: Operation<schema::tx::DryRunRecordStorageReads, DryRunArg> =
            schema::tx::DryRunRecordStorageReads::build(DryRunArg {
                txs,
                utxo_validation,
                gas_price: gas_price.map(|gp| gp.into()),
                block_height: at_height.map(|bh| bh.into()),
            });
        let result = self
            .query(query)
            .await
            .map(|r| r.dry_run_record_storage_reads)?;
        let tx_statuses = result
            .tx_statuses
            .into_iter()
            .map(|tx_status| tx_status.try_into().map_err(Into::into))
            .collect::<io::Result<Vec<_>>>()?;
        let storage_reads = result
            .storage_reads
            .into_iter()
            .map(Into::into)
            .collect::<Vec<_>>();
        Ok((tx_statuses, storage_reads))
    }

    /// Get storage read replay for a block
    pub async fn storage_read_replay(
        &self,
        height: &BlockHeight,
    ) -> io::Result<Vec<StorageReadReplayEvent>> {
        let query: Operation<StorageReadReplay, StorageReadReplayArgs> =
            StorageReadReplay::build(StorageReadReplayArgs {
                height: (*height).into(),
            });
        Ok(self
            .query(query)
            .await
            .map(|r| r.storage_read_replay)?
            .into_iter()
            .map(Into::into)
            .collect())
    }

    /// Assembles the transaction based on the provided requirements.
    /// The return transaction contains:
    /// - Input coins to cover `required_balances`
    /// - Input coins to cover the fee of the transaction based on the gas price from `block_horizon`
    /// - `Change` or `Destroy` outputs for all assets from the inputs
    /// - `Variable` outputs in the case they are required during the execution
    /// - `Contract` inputs and outputs in the case they are required during the execution
    /// - Reserved witness slots for signed coins filled with `64` zeroes
    /// - Set script gas limit(unless `script` is empty)
    /// - Estimated predicates, if `estimate_predicates == true`
    ///
    /// Returns an error if:
    /// - The number of required balances exceeds the maximum number of inputs allowed.
    /// - The fee address index is out of bounds.
    /// - The same asset has multiple change policies(either the receiver of
    ///   the change is different, or one of the policies states about the destruction
    ///   of the token while the other does not). The `Change` output from the transaction
    ///   also count as a `ChangePolicy`.
    /// - The number of excluded coin IDs exceeds the maximum number of inputs allowed.
    /// - Required assets have multiple entries.
    /// - If accounts don't have sufficient amounts to cover the transaction requirements in assets.
    /// - If a constructed transaction breaks the rules defined by consensus parameters.
    #[allow(clippy::too_many_arguments)]
    pub async fn assemble_tx(
        &self,
        tx: &Transaction,
        block_horizon: u32,
        required_balances: Vec<RequiredBalance>,
        fee_address_index: u16,
        exclude: Option<(Vec<UtxoId>, Vec<Nonce>)>,
        estimate_predicates: bool,
        reserve_gas: Option<u64>,
    ) -> io::Result<AssembleTransactionResult> {
        let tx = HexString(Bytes(tx.to_bytes()));
        let block_horizon = block_horizon.into();

        let required_balances: Vec<_> = required_balances
            .into_iter()
            .map(schema::tx::RequiredBalance::try_from)
            .collect::<Result<Vec<_>, _>>()?;

        let fee_address_index = fee_address_index.into();

        let exclude_input = exclude.map(Into::into);

        let reserve_gas = reserve_gas.map(U64::from);

        let query_arg = AssembleTxArg {
            tx,
            block_horizon,
            required_balances,
            fee_address_index,
            exclude_input,
            estimate_predicates,
            reserve_gas,
        };

        let query = schema::tx::AssembleTx::build(query_arg);
        let assemble_tx_result = self.query(query).await.map(|r| r.assemble_tx)?;
        Ok(assemble_tx_result.try_into()?)
    }

    /// Estimate predicates for the transaction
    pub async fn estimate_predicates(&self, tx: &mut Transaction) -> io::Result<()> {
        let serialized_tx = tx.to_bytes();
        let query = schema::tx::EstimatePredicates::build(TxArg {
            tx: HexString(Bytes(serialized_tx)),
        });
        let tx_with_predicate = self.query(query).await.map(|r| r.estimate_predicates)?;
        let tx_with_predicate: Transaction = tx_with_predicate.try_into()?;
        *tx = tx_with_predicate;
        Ok(())
    }

    pub async fn submit(
        &self,
        tx: &Transaction,
    ) -> io::Result<types::primitives::TransactionId> {
        self.submit_opt(tx, None).await
    }

    pub async fn submit_opt(
        &self,
        tx: &Transaction,
        estimate_predicates: Option<bool>,
    ) -> io::Result<types::primitives::TransactionId> {
        let tx = tx.clone().to_bytes();
        let query = schema::tx::Submit::build(TxWithEstimatedPredicatesArg {
            tx: HexString(Bytes(tx)),
            estimate_predicates,
        });

        let id = self.query(query).await.map(|r| r.submit)?.id.into();
        Ok(id)
    }

    /// Similar to [`Self::submit_and_await_commit_opt`], but with default options.
    #[cfg(feature = "subscriptions")]
    pub async fn submit_and_await_commit(
        &self,
        tx: &Transaction,
    ) -> io::Result<TransactionStatus> {
        self.submit_and_await_commit_opt(tx, None).await
    }

    /// Submit the transaction and wait for it either to be included in
    /// a block or removed from `TxPool`.
    ///
    /// If `estimate_predicates` is set, the predicates will be estimated before
    /// the transaction is inserted into transaction pool.
    ///
    /// This will wait forever if needed, so consider wrapping this call
    /// with a `tokio::time::timeout`.
    #[cfg(feature = "subscriptions")]
    pub async fn submit_and_await_commit_opt(
        &self,
        tx: &Transaction,
        estimate_predicates: Option<bool>,
    ) -> io::Result<TransactionStatus> {
        let tx = tx.clone().to_bytes();
        let variables = TxWithEstimatedPredicatesArg {
            tx: HexString(Bytes(tx)),
            estimate_predicates,
        };

        let mut stream = self.subscribe(variables).await?.map(
            |r: io::Result<schema::tx::SubmitAndAwaitSubscription>| {
                let status: TransactionStatus = r?.submit_and_await.try_into()?;
                Result::<_, io::Error>::Ok(status)
            },
        );

        let status = stream.next().await.ok_or_else(|| {
            io::Error::other("Failed to get status from the submission")
        })??;

        Ok(status)
    }

    /// Similar to [`Self::submit_and_await_commit`], but the status also contains transaction.
    #[cfg(feature = "subscriptions")]
    pub async fn submit_and_await_commit_with_tx(
        &self,
        tx: &Transaction,
    ) -> io::Result<StatusWithTransaction> {
        self.submit_and_await_commit_with_tx_opt(tx, None).await
    }

    /// Similar to [`Self::submit_and_await_commit_opt`], but the status also contains transaction.
    #[cfg(feature = "subscriptions")]
    pub async fn submit_and_await_commit_with_tx_opt(
        &self,
        tx: &Transaction,
        estimate_predicates: Option<bool>,
    ) -> io::Result<StatusWithTransaction> {
        let tx = tx.clone().to_bytes();
        let variables = TxWithEstimatedPredicatesArg {
            tx: HexString(Bytes(tx)),
            estimate_predicates,
        };

        let mut stream = self.subscribe(variables).await?.map(
            |r: io::Result<schema::tx::SubmitAndAwaitSubscriptionWithTransaction>| {
                let status: StatusWithTransaction = r?.submit_and_await.try_into()?;
                Result::<_, io::Error>::Ok(status)
            },
        );

        let status = stream.next().await.ok_or_else(|| {
            io::Error::other("Failed to get status from the submission")
        })??;

        Ok(status)
    }

    /// Similar to [`Self::submit_and_await_commit`], but includes all intermediate states.
    #[cfg(feature = "subscriptions")]
    pub async fn submit_and_await_status(
        &self,
        tx: &Transaction,
    ) -> io::Result<impl Stream<Item = io::Result<TransactionStatus>> + '_> {
        self.submit_and_await_status_opt(tx, None, None).await
    }

    /// Similar to [`Self::submit_and_await_commit_opt`], but includes all intermediate states.
    #[cfg(feature = "subscriptions")]
    pub async fn submit_and_await_status_opt(
        &self,
        tx: &Transaction,
        estimate_predicates: Option<bool>,
        include_preconfirmation: Option<bool>,
    ) -> io::Result<impl Stream<Item = io::Result<TransactionStatus>> + '_> {
        use schema::tx::SubmitAndAwaitStatusArg;
        let tx = tx.clone().to_bytes();
        let variables = SubmitAndAwaitStatusArg {
            tx: HexString(Bytes(tx)),
            estimate_predicates,
            include_preconfirmation,
        };

        let stream = self.subscribe(variables).await?.map(
            |r: io::Result<schema::tx::SubmitAndAwaitStatusSubscription>| {
                let status: TransactionStatus = r?.submit_and_await_status.try_into()?;
                Result::<_, io::Error>::Ok(status)
            },
        );

        Ok(stream)
    }

    /// Requests all storage slots for the `contract_id`.
    #[cfg(feature = "subscriptions")]
    pub async fn contract_storage_slots(
        &self,
        contract_id: &ContractId,
    ) -> io::Result<impl Stream<Item = io::Result<(Bytes32, Vec<u8>)>> + '_> {
        use schema::storage::ContractStorageSlotsArgs;
        let variables = ContractStorageSlotsArgs {
            contract_id: (*contract_id).into(),
        };

        let stream = self.subscribe(variables).await?.map(
            |result: io::Result<schema::storage::ContractStorageSlots>| {
                let result: (Bytes32, Vec<u8>) = result?.contract_storage_slots.into();
                Result::<_, io::Error>::Ok(result)
            },
        );

        Ok(stream)
    }

    /// Requests all storage balances for the `contract_id`.
    #[cfg(feature = "subscriptions")]
    pub async fn contract_storage_balances(
        &self,
        contract_id: &ContractId,
    ) -> io::Result<impl Stream<Item = io::Result<schema::contract::ContractBalance>> + '_>
    {
        use schema::{
            contract::ContractBalance,
            storage::ContractStorageBalancesArgs,
        };
        let variables = ContractStorageBalancesArgs {
            contract_id: (*contract_id).into(),
        };

        let stream = self.subscribe(variables).await?.map(
            |result: io::Result<schema::storage::ContractStorageBalances>| {
                let result: ContractBalance = result?.contract_storage_balances;
                Result::<_, io::Error>::Ok(result)
            },
        );

        Ok(stream)
    }

    /// Returns a stream of new blocks.
    #[cfg(feature = "subscriptions")]
    pub async fn new_blocks_subscription(
        &self,
    ) -> io::Result<
        impl Stream<
            Item = io::Result<fuel_core_types::services::block_importer::ImportResult>,
        > + '_,
    > {
        let stream = self.subscribe(()).await?.map(
            |r: io::Result<schema::block::NewBlocksSubscription>| {
                let result: fuel_core_types::services::block_importer::ImportResult =
                    postcard::from_bytes(r?.new_blocks.0.0.as_slice()).map_err(|e| {
                        io::Error::other(format!(
                            "Failed to deserialize ImportResult: {e:?}"
                        ))
                    })?;
                Result::<_, io::Error>::Ok(result)
            },
        );

        Ok(stream)
    }

    /// Returns a stream of preconfirmations for all transactions.
    #[cfg(feature = "subscriptions")]
    pub async fn preconfirmations_subscription(
        &self,
    ) -> io::Result<impl Stream<Item = io::Result<TransactionStatus>> + '_> {
        let stream = self.subscribe(()).await?.map(
            |r: io::Result<schema::tx::PreconfirmationsSubscription>| {
                let status: TransactionStatus = r?.preconfirmations.try_into()?;
                Result::<_, io::Error>::Ok(status)
            },
        );

        Ok(stream)
    }

    pub async fn contract_slots_values(
        &self,
        contract_id: &ContractId,
        block_height: Option<BlockHeight>,
        requested_storage_slots: Vec<Bytes32>,
    ) -> io::Result<Vec<(Bytes32, Vec<u8>)>> {
        let query = schema::storage::ContractSlotValues::build(
            schema::storage::ContractSlotValuesArgs {
                contract_id: (*contract_id).into(),
                block_height: block_height.map(|b| (*b).into()),
                storage_slots: requested_storage_slots
                    .into_iter()
                    .map(Into::into)
                    .collect(),
            },
        );

        self.query(query)
            .await
            .map(|r| r.contract_slot_values.into_iter().map(Into::into).collect())
    }

    pub async fn contract_balance_values(
        &self,
        contract_id: &ContractId,
        block_height: Option<BlockHeight>,
        requested_storage_slots: Vec<AssetId>,
    ) -> io::Result<Vec<schema::contract::ContractBalance>> {
        let query = schema::storage::ContractBalanceValues::build(
            schema::storage::ContractBalanceValuesArgs {
                contract_id: (*contract_id).into(),
                block_height: block_height.map(|b| (*b).into()),
                assets: requested_storage_slots
                    .into_iter()
                    .map(Into::into)
                    .collect(),
            },
        );

        self.query(query)
            .await
            .map(|r| r.contract_balance_values.into_iter().collect())
    }

    pub async fn start_session(&self) -> io::Result<String> {
        let query = schema::StartSession::build(());

        self.query(query)
            .await
            .map(|r| r.start_session.into_inner())
    }

    pub async fn end_session(&self, id: &str) -> io::Result<bool> {
        let query = schema::EndSession::build(IdArg { id: id.into() });

        self.query(query).await.map(|r| r.end_session)
    }

    pub async fn reset(&self, id: &str) -> io::Result<bool> {
        let query = schema::Reset::build(IdArg { id: id.into() });

        self.query(query).await.map(|r| r.reset)
    }

    pub async fn execute(&self, id: &str, op: &Instruction) -> io::Result<bool> {
        let op = serde_json::to_string(op)?;
        let query = schema::Execute::build(schema::ExecuteArgs { id: id.into(), op });

        self.query(query).await.map(|r| r.execute)
    }

    pub async fn register(&self, id: &str, register: RegisterId) -> io::Result<Word> {
        let query = schema::Register::build(RegisterArgs {
            id: id.into(),
            register: register.into(),
        });

        Ok(self.query(query).await?.register.0 as Word)
    }

    pub async fn memory(&self, id: &str, start: u32, size: u32) -> io::Result<Vec<u8>> {
        let query = schema::Memory::build(MemoryArgs {
            id: id.into(),
            start: start.into(),
            size: size.into(),
        });

        let memory = self.query(query).await?.memory;

        Ok(serde_json::from_str(memory.as_str())?)
    }

    pub async fn set_breakpoint(
        &self,
        session_id: &str,
        contract: fuel_types::ContractId,
        pc: u64,
    ) -> io::Result<()> {
        let operation = SetBreakpoint::build(SetBreakpointArgs {
            id: Id::new(session_id),
            bp: schema::Breakpoint {
                contract: contract.into(),
                pc: U64(pc),
            },
        });

        let response = self.query(operation).await?;
        assert!(
            response.set_breakpoint,
            "Setting breakpoint returned invalid reply"
        );
        Ok(())
    }

    pub async fn set_single_stepping(
        &self,
        session_id: &str,
        enable: bool,
    ) -> io::Result<()> {
        let operation = SetSingleStepping::build(SetSingleSteppingArgs {
            id: Id::new(session_id),
            enable,
        });
        self.query(operation).await?;
        Ok(())
    }

    pub async fn start_tx(
        &self,
        session_id: &str,
        tx: &Transaction,
    ) -> io::Result<RunResult> {
        let operation = StartTx::build(StartTxArgs {
            id: Id::new(session_id),
            tx: serde_json::to_string(tx).expect("Couldn't serialize tx to json"),
        });
        let response = self.query(operation).await?.start_tx;
        Ok(response)
    }

    pub async fn continue_tx(&self, session_id: &str) -> io::Result<RunResult> {
        let operation = ContinueTx::build(ContinueTxArgs {
            id: Id::new(session_id),
        });
        let response = self.query(operation).await?.continue_tx;
        Ok(response)
    }

    pub async fn transaction(
        &self,
        id: &TxId,
    ) -> io::Result<Option<TransactionResponse>> {
        let query = schema::tx::TransactionQuery::build(TxIdArgs { id: (*id).into() });

        let transaction = self.query(query).await?.transaction;

        Ok(transaction.map(|tx| tx.try_into()).transpose()?)
    }

    /// Get the status of a transaction
    pub async fn transaction_status(&self, id: &TxId) -> io::Result<TransactionStatus> {
        let query =
            schema::tx::TransactionStatusQuery::build(TxIdArgs { id: (*id).into() });

        let status = self.query(query).await?.transaction.ok_or_else(|| {
            io::Error::new(
                ErrorKind::NotFound,
                format!("status not found for transaction {id} "),
            )
        })?;

        let status = status
            .status
            .ok_or_else(|| {
                io::Error::new(
                    ErrorKind::NotFound,
                    format!("status not found for transaction {id}"),
                )
            })?
            .try_into()?;
        Ok(status)
    }

    #[tracing::instrument(skip(self), level = "debug")]
    #[cfg(feature = "subscriptions")]
    /// Similar to [`Self::subscribe_transaction_status_opt`], but with default options.
    pub async fn subscribe_transaction_status(
        &self,
        id: &TxId,
    ) -> io::Result<impl futures::Stream<Item = io::Result<TransactionStatus>> + '_> {
        self.subscribe_transaction_status_opt(id, None).await
    }

    #[cfg(feature = "subscriptions")]
    /// Subscribe to the status of a transaction
    pub async fn subscribe_transaction_status_opt(
        &self,
        id: &TxId,
        include_preconfirmation: Option<bool>,
    ) -> io::Result<impl Stream<Item = io::Result<TransactionStatus>> + '_> {
        use schema::tx::{
            StatusChangeSubscription,
            StatusChangeSubscriptionArgs,
        };
        let tx_id: TransactionId = (*id).into();
        let variables = StatusChangeSubscriptionArgs {
            id: tx_id,
            include_preconfirmation,
        };

        tracing::debug!("subscribing");
        let stream = self
            .subscribe::<StatusChangeSubscription, StatusChangeSubscriptionArgs>(
                variables,
            )
            .await?
            .map(|tx| {
                tracing::debug!("received {tx:?}");
                let tx = tx?;
                let status = tx.status_change.try_into()?;
                Ok(status)
            });

        Ok(stream)
    }

    #[cfg(feature = "subscriptions")]
    /// Awaits for the transaction to be committed into a block
    ///
    /// This will wait forever if needed, so consider wrapping this call
    /// with a `tokio::time::timeout`.
    pub async fn await_transaction_commit(
        &self,
        id: &TxId,
    ) -> io::Result<TransactionStatus> {
        // skip until we've reached a final status and then stop consuming the stream
        // to avoid an EOF which the eventsource client considers as an error.
        let status_result = self
            .subscribe_transaction_status(id)
            .await?
            .skip_while(|status| {
                future::ready(status.as_ref().map_or(true, |status| !status.is_final()))
            })
            .next()
            .await;

        if let Some(Ok(status)) = status_result {
            Ok(status)
        } else {
            Err(io::Error::other(format!(
                "Failed to get status for transaction {status_result:?}"
            )))
        }
    }

    /// returns a paginated set of transactions sorted by block height
    pub async fn transactions(
        &self,
        request: PaginationRequest<String>,
    ) -> io::Result<PaginatedResult<TransactionResponse, String>> {
        let args = schema::ConnectionArgs::from(request);
        let query = schema::tx::TransactionsQuery::build(args);
        let transactions = self.query(query).await?.transactions.try_into()?;
        Ok(transactions)
    }

    /// Returns a paginated set of transactions associated with a txo owner address.
    pub async fn transactions_by_owner(
        &self,
        owner: &Address,
        request: PaginationRequest<String>,
    ) -> io::Result<PaginatedResult<TransactionResponse, String>> {
        let owner: schema::Address = (*owner).into();
        let args = TransactionsByOwnerConnectionArgs::from((owner, request));
        let query = schema::tx::TransactionsByOwnerQuery::build(args);

        let transactions = self.query(query).await?.transactions_by_owner.try_into()?;
        Ok(transactions)
    }

    pub async fn receipts(&self, id: &TxId) -> io::Result<Option<Vec<Receipt>>> {
        let query =
            schema::tx::TransactionStatusQuery::build(TxIdArgs { id: (*id).into() });

        let tx = self.query(query).await?.transaction.ok_or_else(|| {
            io::Error::new(ErrorKind::NotFound, format!("transaction {id} not found"))
        })?;

        let receipts = match tx.status {
            Some(status) => match status {
                schema::tx::TransactionStatus::SuccessStatus(s) => Some(
                    s.receipts
                        .into_iter()
                        .map(TryInto::<Receipt>::try_into)
                        .collect::<Result<Vec<Receipt>, ConversionError>>(),
                )
                .transpose()?,
                schema::tx::TransactionStatus::FailureStatus(s) => Some(
                    s.receipts
                        .into_iter()
                        .map(TryInto::<Receipt>::try_into)
                        .collect::<Result<Vec<Receipt>, ConversionError>>(),
                )
                .transpose()?,
                _ => None,
            },
            _ => None,
        };

        Ok(receipts)
    }

    #[cfg(feature = "test-helpers")]
    pub async fn all_receipts(&self) -> io::Result<Vec<Receipt>> {
        let query = schema::tx::AllReceipts::build(());
        let receipts = self.query(query).await?.all_receipts;

        let vec: Result<Vec<Receipt>, ConversionError> = receipts
            .into_iter()
            .map(TryInto::<Receipt>::try_into)
            .collect();

        Ok(vec?)
    }

    pub async fn produce_blocks(
        &self,
        blocks_to_produce: u32,
        start_timestamp: Option<u64>,
    ) -> io::Result<BlockHeight> {
        let query = schema::block::BlockMutation::build(ProduceBlockArgs {
            blocks_to_produce: blocks_to_produce.into(),
            start_timestamp: start_timestamp
                .map(|timestamp| Tai64Timestamp::from(Tai64(timestamp))),
        });

        let new_height = self.query(query).await?.produce_blocks;

        Ok(new_height.into())
    }

    pub async fn block(&self, id: &BlockId) -> io::Result<Option<types::Block>> {
        let query = schema::block::BlockByIdQuery::build(BlockByIdArgs {
            id: Some((*id).into()),
        });

        let block = self
            .query(query)
            .await?
            .block
            .map(TryInto::try_into)
            .transpose()?;

        Ok(block)
    }

    pub async fn block_by_height(
        &self,
        height: BlockHeight,
    ) -> io::Result<Option<types::Block>> {
        let query = schema::block::BlockByHeightQuery::build(BlockByHeightArgs {
            height: Some(U32(height.into())),
        });

        let block = self
            .query(query)
            .await?
            .block
            .map(TryInto::try_into)
            .transpose()?;

        Ok(block)
    }

    pub async fn da_compressed_block(
        &self,
        height: BlockHeight,
    ) -> io::Result<Option<Vec<u8>>> {
        let query = schema::da_compressed::DaCompressedBlockByHeightQuery::build(
            DaCompressedBlockByHeightArgs {
                height: U32(height.into()),
            },
        );

        Ok(self
            .query(query)
            .await?
            .da_compressed_block
            .map(|b| b.bytes.into()))
    }

    /// Retrieve a blob by its ID
    pub async fn blob(&self, id: BlobId) -> io::Result<Option<types::Blob>> {
        let query = schema::blob::BlobByIdQuery::build(BlobByIdArgs { id: id.into() });
        let blob = self.query(query).await?.blob.map(Into::into);
        Ok(blob)
    }

    /// Check whether a blob with ID exists
    pub async fn blob_exists(&self, id: BlobId) -> io::Result<bool> {
        let query = schema::blob::BlobExistsQuery::build(BlobByIdArgs { id: id.into() });
        Ok(self.query(query).await?.blob.is_some())
    }

    /// Retrieve multiple blocks
    pub async fn blocks(
        &self,
        request: PaginationRequest<String>,
    ) -> io::Result<PaginatedResult<types::Block, String>> {
        let args = schema::ConnectionArgs::from(request);
        let query = schema::block::BlocksQuery::build(args);

        let blocks = self.query(query).await?.blocks.try_into()?;

        Ok(blocks)
    }

    pub async fn coin(&self, id: &UtxoId) -> io::Result<Option<types::Coin>> {
        let query = schema::coins::CoinByIdQuery::build(CoinByIdArgs {
            utxo_id: (*id).into(),
        });
        let coin = self.query(query).await?.coin.map(Into::into);
        Ok(coin)
    }

    /// Retrieve a page of coins by their owner
    pub async fn coins(
        &self,
        owner: &Address,
        asset_id: Option<&AssetId>,
        request: PaginationRequest<String>,
    ) -> io::Result<PaginatedResult<types::Coin, String>> {
        let owner: schema::Address = (*owner).into();
        let asset_id = asset_id.map(|id| (*id).into());
        let args = CoinsConnectionArgs::from((owner, asset_id, request));
        let query = schema::coins::CoinsQuery::build(args);

        let coins = self.query(query).await?.coins.into();
        Ok(coins)
    }

    /// Retrieve coins to spend in a transaction
    pub async fn coins_to_spend(
        &self,
        owner: &Address,
        spend_query: Vec<(AssetId, u128, Option<u16>)>,
        // (Utxos, Messages Nonce)
        excluded_ids: Option<(Vec<UtxoId>, Vec<Nonce>)>,
    ) -> io::Result<Vec<Vec<types::CoinType>>> {
        let owner: schema::Address = (*owner).into();
        let spend_query: Vec<SpendQueryElementInput> = spend_query
            .iter()
            .map(|(asset_id, amount, max)| -> Result<_, ConversionError> {
                Ok(SpendQueryElementInput {
                    asset_id: (*asset_id).into(),
                    amount: (*amount).into(),
                    max: (*max).map(|max| max.into()),
                })
            })
            .try_collect()?;
        let excluded_ids: Option<ExcludeInput> = excluded_ids.map(Into::into);
        let args =
            schema::coins::CoinsToSpendArgs::from((owner, spend_query, excluded_ids));
        let query = schema::coins::CoinsToSpendQuery::build(args);

        let coins_per_asset = self
            .query(query)
            .await?
            .coins_to_spend
            .into_iter()
            .map(|v| v.into_iter().map(Into::into).collect::<Vec<_>>())
            .collect::<Vec<_>>();
        Ok(coins_per_asset)
    }

    pub async fn contract(&self, id: &ContractId) -> io::Result<Option<types::Contract>> {
        let query = schema::contract::ContractByIdQuery::build(ContractByIdArgs {
            id: (*id).into(),
        });
        let contract = self.query(query).await?.contract.map(Into::into);
        Ok(contract)
    }

    pub async fn contract_balance(
        &self,
        id: &ContractId,
        asset: Option<&AssetId>,
    ) -> io::Result<u64> {
        let asset_id: schema::AssetId = match asset {
            Some(asset) => (*asset).into(),
            None => schema::AssetId::default(),
        };

        let query =
            schema::contract::ContractBalanceQuery::build(ContractBalanceQueryArgs {
                id: (*id).into(),
                asset: asset_id,
            });

        let balance: types::ContractBalance =
            self.query(query).await?.contract_balance.into();
        Ok(balance.amount)
    }

    pub async fn balance(
        &self,
        owner: &Address,
        asset_id: Option<&AssetId>,
    ) -> io::Result<u128> {
        let owner: schema::Address = (*owner).into();
        let asset_id: schema::AssetId = match asset_id {
            Some(asset_id) => (*asset_id).into(),
            None => schema::AssetId::default(),
        };
        let query = schema::balance::BalanceQuery::build(BalanceArgs { owner, asset_id });
        let balance: types::Balance = self.query(query).await?.balance.into();
        Ok(balance.amount)
    }

    // Retrieve a page of balances by their owner
    pub async fn balances(
        &self,
        owner: &Address,
        request: PaginationRequest<String>,
    ) -> io::Result<PaginatedResult<types::Balance, String>> {
        let owner: schema::Address = (*owner).into();
        let args = schema::balance::BalancesConnectionArgs::from((owner, request));
        let query = schema::balance::BalancesQuery::build(args);

        let balances = self.query(query).await?.balances.into();
        Ok(balances)
    }

    pub async fn contract_balances(
        &self,
        contract: &ContractId,
        request: PaginationRequest<String>,
    ) -> io::Result<PaginatedResult<types::ContractBalance, String>> {
        let contract_id: schema::ContractId = (*contract).into();
        let args = ContractBalancesConnectionArgs::from((contract_id, request));
        let query = schema::contract::ContractBalancesQuery::build(args);

        let balances = self.query(query).await?.contract_balances.into();

        Ok(balances)
    }

    // Retrieve a message by its nonce
    pub async fn message(&self, nonce: &Nonce) -> io::Result<Option<types::Message>> {
        let query = schema::message::MessageQuery::build(NonceArgs {
            nonce: (*nonce).into(),
        });
        let message = self.query(query).await?.message.map(Into::into);
        Ok(message)
    }

    pub async fn messages(
        &self,
        owner: Option<&Address>,
        request: PaginationRequest<String>,
    ) -> io::Result<PaginatedResult<types::Message, String>> {
        let owner: Option<schema::Address> = owner.map(|owner| (*owner).into());
        let args = schema::message::OwnedMessagesConnectionArgs::from((owner, request));
        let query = schema::message::OwnedMessageQuery::build(args);

        let messages = self.query(query).await?.messages.into();

        Ok(messages)
    }

    pub async fn contract_info(
        &self,
        contract: &ContractId,
    ) -> io::Result<Option<types::Contract>> {
        let query = schema::contract::ContractByIdQuery::build(ContractByIdArgs {
            id: (*contract).into(),
        });
        let contract_info = self.query(query).await?.contract.map(Into::into);
        Ok(contract_info)
    }

    pub async fn message_status(&self, nonce: &Nonce) -> io::Result<MessageStatus> {
        let query = schema::message::MessageStatusQuery::build(MessageStatusArgs {
            nonce: (*nonce).into(),
        });
        let status = self.query(query).await?.message_status.into();

        Ok(status)
    }

    /// Request a merkle proof of an output message.
    pub async fn message_proof(
        &self,
        transaction_id: &TxId,
        nonce: &Nonce,
        commit_block_id: Option<&BlockId>,
        commit_block_height: Option<BlockHeight>,
    ) -> io::Result<types::MessageProof> {
        let transaction_id: TransactionId = (*transaction_id).into();
        let nonce: schema::Nonce = (*nonce).into();
        let commit_block_id: Option<schema::BlockId> =
            commit_block_id.map(|commit_block_id| (*commit_block_id).into());
        let commit_block_height = commit_block_height.map(Into::into);
        let query = schema::message::MessageProofQuery::build(MessageProofArgs {
            transaction_id,
            nonce,
            commit_block_id,
            commit_block_height,
        });
        let proof = self.query(query).await?.message_proof.try_into()?;
        Ok(proof)
    }

    pub async fn relayed_transaction_status(
        &self,
        id: &Bytes32,
    ) -> io::Result<Option<RelayedTransactionStatus>> {
        let query = schema::relayed_tx::RelayedTransactionStatusQuery::build(
            RelayedTransactionStatusArgs {
                id: id.to_owned().into(),
            },
        );
        let status = self
            .query(query)
            .await?
            .relayed_transaction_status
            .map(|status| status.try_into())
            .transpose()?;
        Ok(status)
    }

    pub async fn asset_info(
        &self,
        asset_id: &AssetId,
    ) -> io::Result<Option<AssetDetail>> {
        let query = schema::assets::AssetInfoQuery::build(AssetInfoArg {
            id: (*asset_id).into(),
        });
        let asset_info = self.query(query).await?.asset_details.map(Into::into);
        Ok(asset_info)
    }
}

#[cfg(any(test, feature = "test-helpers"))]
impl FuelClient {
    pub async fn transparent_transaction(
        &self,
        id: &TxId,
    ) -> io::Result<Option<types::TransactionType>> {
        let query = schema::tx::TransactionQuery::build(TxIdArgs { id: (*id).into() });

        let transaction = self.query(query).await?.transaction;

        Ok(transaction
            .map(|tx| {
                let response: TransactionResponse = tx.try_into()?;
                Ok::<_, ConversionError>(response.transaction)
            })
            .transpose()?)
    }
}

#[cfg(feature = "rpc")]
impl FuelClient {
    fn rpc_client(&self) -> io::Result<ProtoBlockAggregatorClient<Channel>> {
        self.rpc_client
            .clone()
            .ok_or(io::Error::other("RPC client not initialized"))
    }

    pub async fn get_block_range(
        &self,
        start: BlockHeight,
        end: BlockHeight,
    ) -> io::Result<
        impl Stream<
            Item = io::Result<(
                fuel_core_types::blockchain::block::Block,
                Vec<Vec<Receipt>>,
            )>,
        >,
    > {
        let request = ProtoBlockRangeRequest {
            start: *start,
            end: *end,
        };

        let stream = self
            .rpc_client()?
            .get_block_range(request)
            .await
            .map_err(io::Error::other)?
            .into_inner()
            .then(|res| {
                let maybe_aws_client = self.aws_client.clone();
                async move {
                    let maybe_aws_client = maybe_aws_client.clone();
                    let resp =
                        res.map_err(|e| io::Error::other(format!("RPC error: {:?}", e)))?;
                    Self::convert_block_response(resp, maybe_aws_client).await
                }
            });
        Ok(stream)
    }

    async fn convert_block_response(
        resp: BlockResponse,
        s3_client: AWSClientManager,
    ) -> io::Result<(fuel_core_types::blockchain::block::Block, Vec<Vec<Receipt>>)> {
        let payload = resp
            .payload
            .ok_or(io::Error::other("No RPC payload for `BlockResponse`"))?;
        match payload {
            Payload::Literal(_) => {
                // Should never happen, as we don't return blocks as literal payloads
                Err(io::Error::other("Literal payloads are not supported yet"))
            }
            Payload::Bytes(bytes) => {
                let proto_block =
                    ProtoBlock::decode(bytes.as_slice()).map_err(io::Error::other)?;
                fuel_block_from_protobuf(proto_block).map_err(|e| {
                    io::Error::other(format!(
                        "Failed to convert RPC block to internal block: {e:?}"
                    ))
                })
            }
            Payload::Remote(remote) => {
                let RemoteBlockResponse { location } = remote;
                match location {
                    Some(Location::S3(s3)) => {
                        let RemoteS3Bucket {
                            bucket,
                            key,
                            endpoint,
                            requester_pays,
                        } = s3;
                        let zipped_bytes = Self::get_block_from_s3_bucket(
                            s3_client,
                            &endpoint,
                            &bucket,
                            &key,
                            requester_pays,
                        )
                        .await?;

                        let block_bytes = Self::unzip_bytes(&zipped_bytes)?;
                        let block =
                            ProtoBlock::decode(block_bytes.as_slice()).map_err(|e| {
                                io::Error::other(format!("Failed to decode block: {e}"))
                            })?;
                        let (block, receipts) =
                            fuel_block_from_protobuf(block).map_err(|e| {
                                io::Error::other(format!(
                                    "Failed to convert RPC block to internal block: {e:?}"
                                ))
                            })?;
                        Ok((block, receipts))
                    }
                    _ => Err(io::Error::other("Remote blocks are not supported yet")),
                }
            }
        }
    }
    async fn get_block_from_s3_bucket(
        s3_client: AWSClientManager,
        url: &Option<String>,
        bucket: &str,
        key: &str,
        requester_pays: bool,
    ) -> io::Result<prost::bytes::Bytes> {
        use aws_sdk_s3::types::RequestPayer;
        tracing::debug!("getting block from bucket: {} with key {}", bucket, key);
        let mut req = s3_client
            .get_client(url)
            .await?
            .get_object()
            .bucket(bucket)
            .key(key);
        if requester_pays {
            req = req.request_payer(RequestPayer::Requester);
        }
        let obj = req.send().await.map_err(|e| {
            io::Error::other(format!("Failed to get object from S3: {e:?}"))
        })?;
        let bytes = obj
            .body
            .collect()
            .await
            .map_err(|e| {
                io::Error::other(format!("Failed to get object from S3: {e:?}"))
            })?
            .into_bytes();
        Ok(bytes)
    }

    async fn new_aws_client(url: &Option<String>) -> AWSClient {
        let credentials = DefaultCredentialsChain::builder().build().await;
        let mut config_builder = aws_config::defaults(BehaviorVersion::latest())
            .credentials_provider(credentials);
        if let Some(url) = url {
            config_builder = config_builder.endpoint_url(url);
        }
        let sdk_config = config_builder.load().await;
        let builder = aws_sdk_s3::config::Builder::from(&sdk_config);
        let config = builder.force_path_style(true).build();
        AWSClient::from_conf(config)
    }

    fn unzip_bytes(bytes: &[u8]) -> io::Result<Vec<u8>> {
        let mut decoder = GzDecoder::new(bytes);
        let mut output = Vec::new();
        decoder.read_to_end(&mut output).map_err(io::Error::other)?;
        Ok(output)
    }

    /// Used to get the synced height of the block aggregator,
    /// as it doesn't always match the latest block height
    pub async fn get_aggregated_height(&self) -> io::Result<BlockHeight> {
        let request = ProtoBlockHeightRequest {};
        let height = self
            .rpc_client()?
            .get_synced_block_height(request)
            .await
            .map_err(io::Error::other)?
            .into_inner()
            .height
            .ok_or(io::Error::other("No height in RPC response"))?;
        Ok(BlockHeight::from(height))
    }

    pub async fn new_block_subscription(
        &self,
    ) -> io::Result<
        impl Stream<
            Item = io::Result<(
                fuel_core_types::blockchain::block::Block,
                Vec<Vec<Receipt>>,
            )>,
        >,
    > {
        let request = ProtoNewBlockSubscriptionRequest {};
        let stream = self
            .rpc_client()?
            .new_block_subscription(request)
            .await
            .map_err(io::Error::other)?
            .into_inner()
            .then(|res| {
                let maybe_aws_client = self.aws_client.clone();
                async move {
                    let maybe_aws_client = maybe_aws_client.clone();
                    let resp =
                        res.map_err(|e| io::Error::other(format!("RPC error: {:?}", e)))?;
                    Self::convert_block_response(resp, maybe_aws_client).await
                }
            });
        Ok(stream)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn with_urls_normalizes_urls_to_graphql_endpoint() {
        // Given
        let urls = &["http://localhost:8080", "http://example.com:4000"];

        // When
        let client = FuelClient::with_urls(urls).expect("should create client");

        // Then
        assert_eq!(
            client.get_default_url().as_str(),
            "http://localhost:8080/v1/graphql"
        );
    }

    #[test]
    fn with_urls_adds_http_scheme_if_missing() {
        // Given
        let urls = &["localhost:8080"];

        // When
        let client = FuelClient::with_urls(urls).expect("should create client");

        // Then
        assert_eq!(
            client.get_default_url().as_str(),
            "http://localhost:8080/v1/graphql"
        );
    }

    #[test]
    fn with_urls_overwrites_existing_path() {
        // Given - URLs that already have some path
        let urls = &["http://localhost:8080/some/path", "http://example.com/api"];

        // When
        let client = FuelClient::with_urls(urls).expect("should create client");

        // Then - path should be normalized to /v1/graphql
        assert_eq!(
            client.get_default_url().as_str(),
            "http://localhost:8080/v1/graphql"
        );
    }

    #[test]
    fn new_and_with_urls_produce_same_url() {
        // Given
        let url = "http://localhost:8080";

        // When
        let client_new = FuelClient::new(url).expect("should create client via new");
        let client_with_urls =
            FuelClient::with_urls(&[url]).expect("should create client via with_urls");

        // Then
        assert_eq!(
            client_new.get_default_url().as_str(),
            client_with_urls.get_default_url().as_str()
        );
    }
}