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
use std::io;
#[cfg(feature = "fuel-core")]
use fuel_core::service::{Config, FuelService};
use crate::{field, UniqueIdentifier};
use chrono::{DateTime, Duration, Utc};
use fuel_gql_client::{
client::{
schema::{
balance::Balance, block::TimeParameters as FuelTimeParameters,
contract::ContractBalance,
},
types::TransactionStatus,
FuelClient, PageDirection, PaginatedResult, PaginationRequest,
},
fuel_tx::{ConsensusParameters, Receipt, Transaction, TransactionFee},
fuel_types::AssetId,
interpreter::ExecutableTransaction,
};
use fuels_core::constants::{DEFAULT_GAS_ESTIMATION_TOLERANCE, MAX_GAS_PER_TX};
use fuels_types::{
bech32::{Bech32Address, Bech32ContractId},
block::Block,
chain_info::ChainInfo,
coin::Coin,
errors::Error,
message::Message,
message_proof::MessageProof,
node_info::NodeInfo,
resource::Resource,
transaction_response::TransactionResponse,
};
use std::collections::HashMap;
use thiserror::Error;
#[derive(Debug)]
pub struct TransactionCost {
pub min_gas_price: u64,
pub gas_price: u64,
pub gas_used: u64,
pub metered_bytes_size: u64,
pub total_fee: u64,
}
#[derive(Debug)]
pub struct TimeParameters {
pub start_time: DateTime<Utc>,
pub block_time_interval: Duration,
}
impl From<TimeParameters> for FuelTimeParameters {
fn from(time: TimeParameters) -> Self {
Self {
start_time: (time.start_time.timestamp() as u64).into(),
block_time_interval: (time.block_time_interval.num_seconds() as u64).into(),
}
}
}
#[derive(Debug, Error)]
pub enum ProviderError {
#[error(transparent)]
ClientRequestError(#[from] io::Error),
}
impl From<ProviderError> for Error {
fn from(e: ProviderError) -> Self {
Error::ProviderError(e.to_string())
}
}
#[derive(Debug, Clone)]
pub struct Provider {
pub client: FuelClient,
}
impl Provider {
pub fn new(client: FuelClient) -> Self {
Self { client }
}
pub async fn send_transaction<Tx>(&self, tx: &Tx) -> Result<Vec<Receipt>, Error>
where
Tx: ExecutableTransaction + field::GasLimit + field::GasPrice + Into<Transaction>,
{
let tolerance = 0.0;
let TransactionCost {
gas_used,
min_gas_price,
..
} = self.estimate_transaction_cost(tx, Some(tolerance)).await?;
if gas_used > *tx.gas_limit() {
return Err(Error::ProviderError(format!(
"gas_limit({}) is lower than the estimated gas_used({})",
tx.gas_limit(),
gas_used
)));
} else if min_gas_price > *tx.gas_price() {
return Err(Error::ProviderError(format!(
"gas_price({}) is lower than the required min_gas_price({})",
tx.gas_price(),
min_gas_price
)));
}
let (status, receipts) = self.submit_with_feedback(&tx.clone().into()).await?;
if let TransactionStatus::Failure { reason, .. } = status {
Err(Error::RevertTransactionError(reason, receipts))
} else {
Ok(receipts)
}
}
async fn submit_with_feedback(
&self,
tx: &Transaction,
) -> Result<(TransactionStatus, Vec<Receipt>), ProviderError> {
let tx_id = tx.id().to_string();
let status = self.client.submit_and_await_commit(tx).await?;
let receipts = self.client.receipts(&tx_id).await?;
Ok((status, receipts))
}
#[cfg(feature = "fuel-core")]
pub async fn launch(config: Config) -> Result<FuelClient, Error> {
let srv = FuelService::new_node(config).await.unwrap();
Ok(FuelClient::from(srv.bound_address))
}
pub async fn connect(url: impl AsRef<str>) -> Result<Provider, Error> {
let client = FuelClient::new(url)?;
Ok(Provider::new(client))
}
pub async fn chain_info(&self) -> Result<ChainInfo, ProviderError> {
Ok(self.client.chain_info().await?.into())
}
pub async fn consensus_parameters(&self) -> Result<ConsensusParameters, ProviderError> {
Ok(self.client.chain_info().await?.consensus_parameters.into())
}
pub async fn node_info(&self) -> Result<NodeInfo, ProviderError> {
Ok(self.client.node_info().await?.into())
}
pub async fn dry_run(&self, tx: &Transaction) -> Result<Vec<Receipt>, ProviderError> {
Ok(self.client.dry_run(tx).await?)
}
pub async fn dry_run_no_validation(
&self,
tx: &Transaction,
) -> Result<Vec<Receipt>, ProviderError> {
Ok(self.client.dry_run_opt(tx, Some(false)).await?)
}
pub async fn get_coins(
&self,
from: &Bech32Address,
asset_id: AssetId,
) -> Result<Vec<Coin>, ProviderError> {
let mut coins: Vec<Coin> = vec![];
let mut cursor = None;
loop {
let res = self
.client
.coins(
&from.hash().to_string(),
Some(&asset_id.to_string()),
PaginationRequest {
cursor: cursor.clone(),
results: 100,
direction: PageDirection::Forward,
},
)
.await?;
if res.results.is_empty() {
break;
}
coins.extend(res.results.into_iter().map(Into::into));
cursor = res.cursor;
}
Ok(coins)
}
pub async fn get_spendable_resources(
&self,
from: &Bech32Address,
asset_id: AssetId,
amount: u64,
) -> Result<Vec<Resource>, ProviderError> {
use itertools::Itertools;
let res = self
.client
.resources_to_spend(
&from.hash().to_string(),
vec![(format!("{:#x}", asset_id).as_str(), amount, None)],
None,
)
.await?
.into_iter()
.flatten()
.map(|resource| {
let resource: Result<Resource, _> = resource.try_into();
resource.map_err(ProviderError::ClientRequestError)
})
.try_collect()?;
Ok(res)
}
pub async fn get_asset_balance(
&self,
address: &Bech32Address,
asset_id: AssetId,
) -> Result<u64, ProviderError> {
self.client
.balance(&address.hash().to_string(), Some(&*asset_id.to_string()))
.await
.map_err(Into::into)
}
pub async fn get_contract_asset_balance(
&self,
contract_id: &Bech32ContractId,
asset_id: AssetId,
) -> Result<u64, ProviderError> {
self.client
.contract_balance(&contract_id.hash().to_string(), Some(&asset_id.to_string()))
.await
.map_err(Into::into)
}
pub async fn get_balances(
&self,
address: &Bech32Address,
) -> Result<HashMap<String, u64>, ProviderError> {
let pagination = PaginationRequest {
cursor: None,
results: 9999,
direction: PageDirection::Forward,
};
let balances_vec = self
.client
.balances(&address.hash().to_string(), pagination)
.await?
.results;
let balances = balances_vec
.into_iter()
.map(
|Balance {
owner: _,
amount,
asset_id,
}| (asset_id.to_string(), amount.try_into().unwrap()),
)
.collect();
Ok(balances)
}
pub async fn get_contract_balances(
&self,
contract_id: &Bech32ContractId,
) -> Result<HashMap<String, u64>, ProviderError> {
let pagination = PaginationRequest {
cursor: None,
results: 9999,
direction: PageDirection::Forward,
};
let balances_vec = self
.client
.contract_balances(&contract_id.hash().to_string(), pagination)
.await?
.results;
let balances = balances_vec
.into_iter()
.map(
|ContractBalance {
contract: _,
amount,
asset_id,
}| (asset_id.to_string(), amount.try_into().unwrap()),
)
.collect();
Ok(balances)
}
pub async fn get_transaction_by_id(
&self,
tx_id: &str,
) -> Result<Option<TransactionResponse>, ProviderError> {
Ok(self.client.transaction(tx_id).await?.map(Into::into))
}
pub async fn get_transactions(
&self,
request: PaginationRequest<String>,
) -> Result<PaginatedResult<TransactionResponse, String>, ProviderError> {
let pr = self.client.transactions(request).await?;
Ok(PaginatedResult {
cursor: pr.cursor,
results: pr.results.into_iter().map(Into::into).collect(),
has_next_page: pr.has_next_page,
has_previous_page: pr.has_previous_page,
})
}
pub async fn get_transactions_by_owner(
&self,
owner: &Bech32Address,
request: PaginationRequest<String>,
) -> Result<PaginatedResult<TransactionResponse, String>, ProviderError> {
let pr = self
.client
.transactions_by_owner(&owner.hash().to_string(), request)
.await?;
Ok(PaginatedResult {
cursor: pr.cursor,
results: pr.results.into_iter().map(Into::into).collect(),
has_next_page: pr.has_next_page,
has_previous_page: pr.has_previous_page,
})
}
pub async fn latest_block_height(&self) -> Result<u64, ProviderError> {
Ok(self.client.chain_info().await?.latest_block.header.height.0)
}
pub async fn produce_blocks(
&self,
amount: u64,
time: Option<TimeParameters>,
) -> io::Result<u64> {
let fuel_time: Option<FuelTimeParameters> = time.map(|t| t.into());
self.client.produce_blocks(amount, fuel_time).await
}
pub async fn block(&self, block_id: &str) -> Result<Option<Block>, ProviderError> {
let block = self.client.block(block_id).await?.map(Into::into);
Ok(block)
}
pub async fn get_blocks(
&self,
request: PaginationRequest<String>,
) -> Result<PaginatedResult<Block, String>, ProviderError> {
let pr = self.client.blocks(request).await?;
Ok(PaginatedResult {
cursor: pr.cursor,
results: pr.results.into_iter().map(Into::into).collect(),
has_next_page: pr.has_next_page,
has_previous_page: pr.has_previous_page,
})
}
pub async fn estimate_transaction_cost<Tx>(
&self,
tx: &Tx,
tolerance: Option<f64>,
) -> Result<TransactionCost, Error>
where
Tx: ExecutableTransaction + field::GasLimit + field::GasPrice,
{
let NodeInfo { min_gas_price, .. } = self.node_info().await?;
let tolerance = tolerance.unwrap_or(DEFAULT_GAS_ESTIMATION_TOLERANCE);
let mut dry_run_tx = Self::generate_dry_run_tx(tx);
let consensus_parameters = self.chain_info().await?.consensus_parameters;
let gas_used = self
.get_gas_used_with_tolerance(&dry_run_tx, tolerance)
.await?;
let gas_price = std::cmp::max(*tx.gas_price(), min_gas_price);
*dry_run_tx.gas_price_mut() = gas_price;
*dry_run_tx.gas_limit_mut() = gas_used;
let transaction_fee = TransactionFee::checked_from_tx(&consensus_parameters, &dry_run_tx)
.expect("Error calculating TransactionFee");
Ok(TransactionCost {
min_gas_price,
gas_price,
gas_used,
metered_bytes_size: tx.metered_bytes_size() as u64,
total_fee: transaction_fee.total(),
})
}
fn generate_dry_run_tx<Tx: field::GasPrice + field::GasLimit + Clone>(tx: &Tx) -> Tx {
let mut dry_run_tx = tx.clone();
*dry_run_tx.gas_limit_mut() = MAX_GAS_PER_TX;
*dry_run_tx.gas_price_mut() = 0;
dry_run_tx
}
async fn get_gas_used_with_tolerance<Tx: Into<Transaction> + Clone>(
&self,
tx: &Tx,
tolerance: f64,
) -> Result<u64, ProviderError> {
let gas_used = self.get_gas_used(&self.dry_run_no_validation(&tx.clone().into()).await?);
Ok((gas_used as f64 * (1.0 + tolerance)) as u64)
}
fn get_gas_used(&self, receipts: &[Receipt]) -> u64 {
receipts
.iter()
.rfind(|r| matches!(r, Receipt::ScriptResult { .. }))
.map(|script_result| {
script_result
.gas_used()
.expect("could not retrieve gas used from ScriptResult")
})
.unwrap_or(0)
}
pub async fn get_messages(&self, from: &Bech32Address) -> Result<Vec<Message>, ProviderError> {
let pagination = PaginationRequest {
cursor: None,
results: 100,
direction: PageDirection::Forward,
};
let res = self
.client
.messages(Some(&from.hash().to_string()), pagination)
.await?
.results
.into_iter()
.map(Into::into)
.collect();
Ok(res)
}
pub async fn get_message_proof(
&self,
tx_id: &str,
message_id: &str,
) -> Result<Option<MessageProof>, ProviderError> {
let proof = self
.client
.message_proof(tx_id, message_id)
.await?
.map(Into::into);
Ok(proof)
}
}