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
use std::{collections::HashMap, io};

use chrono::{DateTime, Duration, Utc};
#[cfg(feature = "fuel-core")]
use fuel_core::service::{Config, FuelService};
use fuel_core_client::client::{
    schema::{
        balance::Balance, block::TimeParameters as FuelTimeParameters, contract::ContractBalance,
    },
    types::TransactionStatus,
    FuelClient, PageDirection, PaginatedResult, PaginationRequest,
};
use fuel_tx::{AssetId, ConsensusParameters, Input, Receipt, TxPointer, UtxoId};
use fuel_types::MessageId;
use fuel_vm::state::ProgramState;
use fuels_types::{
    bech32::{Bech32Address, Bech32ContractId},
    block::Block,
    chain_info::ChainInfo,
    coin::Coin,
    constants::{BASE_ASSET_ID, DEFAULT_GAS_ESTIMATION_TOLERANCE, MAX_GAS_PER_TX},
    errors::{error, Error, Result},
    message::Message,
    message_proof::MessageProof,
    node_info::NodeInfo,
    resource::Resource,
    transaction::Transaction,
    transaction_response::TransactionResponse,
};
use itertools::Itertools;
use tai64::Tai64;
use thiserror::Error;

type ProviderResult<T> = std::result::Result<T, ProviderError>;

#[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)]
// ANCHOR: time_parameters
pub struct TimeParameters {
    // The time to set on the first block
    pub start_time: DateTime<Utc>,
    // The time interval between subsequent blocks
    pub block_time_interval: Duration,
}
// ANCHOR_END: time_parameters

impl From<TimeParameters> for FuelTimeParameters {
    fn from(time: TimeParameters) -> Self {
        Self {
            start_time: Tai64::from_unix(time.start_time.timestamp()).0.into(),
            block_time_interval: (time.block_time_interval.num_seconds() as u64).into(),
        }
    }
}

pub(crate) struct ResourceQueries {
    utxos: Vec<String>,
    messages: Vec<String>,
    asset_id: String,
    amount: u64,
}

impl ResourceQueries {
    pub fn new(
        utxo_ids: Vec<UtxoId>,
        message_ids: Vec<MessageId>,
        asset_id: AssetId,
        amount: u64,
    ) -> Self {
        let utxos = utxo_ids
            .iter()
            .map(|utxo_id| format!("{utxo_id:#x}"))
            .collect::<Vec<_>>();

        let messages = message_ids
            .iter()
            .map(|msg_id| format!("{msg_id:#x}"))
            .collect::<Vec<_>>();

        Self {
            utxos,
            messages,
            asset_id: format!("{asset_id:#x}"),
            amount,
        }
    }

    pub fn exclusion_query(&self) -> Option<(Vec<&str>, Vec<&str>)> {
        if self.utxos.is_empty() && self.messages.is_empty() {
            return None;
        }

        let utxos_as_str = self.utxos.iter().map(AsRef::as_ref).collect::<Vec<_>>();

        let msg_ids_as_str = self.messages.iter().map(AsRef::as_ref).collect::<Vec<_>>();

        Some((utxos_as_str, msg_ids_as_str))
    }

    pub fn spend_query(&self) -> Vec<(&str, u64, Option<u64>)> {
        vec![(self.asset_id.as_str(), self.amount, None)]
    }
}

// ANCHOR: resource_filter
pub struct ResourceFilter {
    pub from: Bech32Address,
    pub asset_id: AssetId,
    pub amount: u64,
    pub excluded_utxos: Vec<UtxoId>,
    pub excluded_message_ids: Vec<MessageId>,
}
// ANCHOR_END: resource_filter

impl ResourceFilter {
    pub fn owner(&self) -> String {
        self.from.hash().to_string()
    }

    pub(crate) fn resource_queries(&self) -> ResourceQueries {
        ResourceQueries::new(
            self.excluded_utxos.clone(),
            self.excluded_message_ids.clone(),
            self.asset_id,
            self.amount,
        )
    }
}

impl Default for ResourceFilter {
    fn default() -> Self {
        Self {
            from: Default::default(),
            asset_id: BASE_ASSET_ID,
            amount: Default::default(),
            excluded_utxos: Default::default(),
            excluded_message_ids: Default::default(),
        }
    }
}

#[derive(Debug, Error)]
pub enum ProviderError {
    // Every IO error in the context of Provider comes from the gql client
    #[error(transparent)]
    ClientRequestError(#[from] io::Error),
}

impl From<ProviderError> for Error {
    fn from(e: ProviderError) -> Self {
        Error::ProviderError(e.to_string())
    }
}

/// Encapsulates common client operations in the SDK.
/// Note that you may also use `client`, which is an instance
/// of `FuelClient`, directly, which provides a broader API.
#[derive(Debug, Clone)]
pub struct Provider {
    pub client: FuelClient,
}

impl Provider {
    pub fn new(client: FuelClient) -> Self {
        Self { client }
    }

    /// Sends a transaction to the underlying Provider's client.
    pub async fn send_transaction<T: Transaction + Clone>(&self, tx: &T) -> Result<Vec<Receipt>> {
        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,
                "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,
                "gas_price({}) is lower than the required min_gas_price({})",
                tx.gas_price(),
                min_gas_price
            ));
        }

        let chain_info = self.chain_info().await?;
        tx.check_without_signatures(
            chain_info.latest_block.header.height,
            &chain_info.consensus_parameters,
        )?;

        let (status, receipts) = self.submit_with_feedback(tx.clone()).await?;
        Self::if_failure_generate_error(&status, &receipts)?;

        Ok(receipts)
    }

    fn if_failure_generate_error(status: &TransactionStatus, receipts: &[Receipt]) -> Result<()> {
        if let TransactionStatus::Failure {
            reason,
            program_state,
            ..
        } = status
        {
            let revert_id = program_state
                .and_then(|state| match state {
                    ProgramState::Revert(revert_id) => Some(revert_id),
                    _ => None,
                })
                .expect("Transaction failed without a `revert_id`");

            return Err(Error::RevertTransactionError {
                reason: reason.to_string(),
                revert_id,
                receipts: receipts.to_owned(),
            });
        }

        Ok(())
    }

    async fn submit_with_feedback(
        &self,
        tx: impl Transaction,
    ) -> ProviderResult<(TransactionStatus, Vec<Receipt>)> {
        let tx_id = tx.id().to_string();
        let status = self.client.submit_and_await_commit(&tx.into()).await?;
        let receipts = self.client.receipts(&tx_id).await?;

        Ok((status, receipts))
    }

    #[cfg(feature = "fuel-core")]
    /// Launches a local `fuel-core` network based on provided config.
    pub async fn launch(config: Config) -> Result<FuelClient> {
        let srv = FuelService::new_node(config).await.unwrap();
        Ok(FuelClient::from(srv.bound_address))
    }

    /// Connects to an existing node at the given address.
    pub async fn connect(url: impl AsRef<str>) -> Result<Provider> {
        let client = FuelClient::new(url).map_err(|err| error!(InfrastructureError, "{err}"))?;
        Ok(Provider::new(client))
    }

    pub async fn chain_info(&self) -> ProviderResult<ChainInfo> {
        Ok(self.client.chain_info().await?.into())
    }

    pub async fn consensus_parameters(&self) -> ProviderResult<ConsensusParameters> {
        Ok(self.client.chain_info().await?.consensus_parameters.into())
    }

    pub async fn node_info(&self) -> ProviderResult<NodeInfo> {
        Ok(self.client.node_info().await?.into())
    }

    pub async fn dry_run<T: Transaction + Clone>(&self, tx: &T) -> Result<Vec<Receipt>> {
        let receipts = self.client.dry_run(&tx.clone().into()).await?;

        Ok(receipts)
    }

    pub async fn dry_run_no_validation<T: Transaction + Clone>(
        &self,
        tx: &T,
    ) -> Result<Vec<Receipt>> {
        let receipts = self
            .client
            .dry_run_opt(&tx.clone().into(), Some(false))
            .await?;

        Ok(receipts)
    }

    /// Gets all unspent coins owned by address `from`, with asset ID `asset_id`.
    pub async fn get_coins(
        &self,
        from: &Bech32Address,
        asset_id: AssetId,
    ) -> ProviderResult<Vec<Coin>> {
        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)
    }

    /// Get some spendable coins of asset `asset_id` for address `from` that add up at least to
    /// amount `amount`. The returned coins (UTXOs) are actual coins that can be spent. The number
    /// of coins (UXTOs) is optimized to prevent dust accumulation.
    pub async fn get_spendable_resources(
        &self,
        filter: ResourceFilter,
    ) -> ProviderResult<Vec<Resource>> {
        let queries = filter.resource_queries();

        let res = self
            .client
            .resources_to_spend(
                &filter.owner(),
                queries.spend_query(),
                queries.exclusion_query(),
            )
            .await?
            .into_iter()
            .flatten()
            .map(|resource| {
                resource
                    .try_into()
                    .map_err(ProviderError::ClientRequestError)
            })
            .try_collect()?;

        Ok(res)
    }

    /// Returns a vector consisting of `Input::Coin`s and `Input::Message`s for the given
    /// `ResourceFilter`. The `witness_index` is the position of the witness (signature)
    /// in the transaction's list of witnesses. In the validation process, the node will
    /// use the witness at this index to validate the coins returned by this method.
    pub async fn get_asset_inputs(
        &self,
        filter: ResourceFilter,
        witness_index: u8,
    ) -> Result<Vec<Input>> {
        let asset_id = filter.asset_id;
        Ok(self
            .get_spendable_resources(filter)
            .await?
            .iter()
            .map(|resource| match resource {
                Resource::Coin(coin) => self.create_coin_input(coin, asset_id, witness_index),
                Resource::Message(message) => self.create_message_input(message, witness_index),
            })
            .collect::<Vec<Input>>())
    }

    fn create_coin_input(&self, coin: &Coin, asset_id: AssetId, witness_index: u8) -> Input {
        Input::coin_signed(
            coin.utxo_id,
            coin.owner.clone().into(),
            coin.amount,
            asset_id,
            TxPointer::default(),
            witness_index,
            0,
        )
    }

    fn create_message_input(&self, message: &Message, witness_index: u8) -> Input {
        Input::message_signed(
            message.message_id(),
            message.sender.clone().into(),
            message.recipient.clone().into(),
            message.amount,
            message.nonce,
            witness_index,
            message.data.clone(),
        )
    }

    /// Get the balance of all spendable coins `asset_id` for address `address`. This is different
    /// from getting coins because we are just returning a number (the sum of UTXOs amount) instead
    /// of the UTXOs.
    pub async fn get_asset_balance(
        &self,
        address: &Bech32Address,
        asset_id: AssetId,
    ) -> ProviderResult<u64> {
        self.client
            .balance(&address.hash().to_string(), Some(&*asset_id.to_string()))
            .await
            .map_err(Into::into)
    }

    /// Get the balance of all spendable coins `asset_id` for contract with id `contract_id`.
    pub async fn get_contract_asset_balance(
        &self,
        contract_id: &Bech32ContractId,
        asset_id: AssetId,
    ) -> ProviderResult<u64> {
        self.client
            .contract_balance(&contract_id.hash().to_string(), Some(&asset_id.to_string()))
            .await
            .map_err(Into::into)
    }

    /// Get all the spendable balances of all assets for address `address`. This is different from
    /// getting the coins because we are only returning the numbers (the sum of UTXOs coins amount
    /// for each asset id) and not the UTXOs coins themselves
    pub async fn get_balances(
        &self,
        address: &Bech32Address,
    ) -> ProviderResult<HashMap<String, u64>> {
        // We don't paginate results because there are likely at most ~100 different assets in one
        // wallet
        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)
    }

    /// Get all balances of all assets for the contract with id `contract_id`.
    pub async fn get_contract_balances(
        &self,
        contract_id: &Bech32ContractId,
    ) -> ProviderResult<HashMap<String, u64>> {
        // We don't paginate results because there are likely at most ~100 different assets in one
        // wallet
        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,
    ) -> ProviderResult<Option<TransactionResponse>> {
        Ok(self.client.transaction(tx_id).await?.map(Into::into))
    }

    // - Get transaction(s)
    pub async fn get_transactions(
        &self,
        request: PaginationRequest<String>,
    ) -> ProviderResult<PaginatedResult<TransactionResponse, String>> {
        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,
        })
    }

    // Get transaction(s) by owner
    pub async fn get_transactions_by_owner(
        &self,
        owner: &Bech32Address,
        request: PaginationRequest<String>,
    ) -> ProviderResult<PaginatedResult<TransactionResponse, String>> {
        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) -> ProviderResult<u64> {
        Ok(self.chain_info().await?.latest_block.header.height)
    }

    pub async fn latest_block_time(&self) -> ProviderResult<Option<DateTime<Utc>>> {
        Ok(self.chain_info().await?.latest_block.header.time)
    }

    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
    }

    /// Get block by id.
    pub async fn block(&self, block_id: &str) -> ProviderResult<Option<Block>> {
        let block = self.client.block(block_id).await?.map(Into::into);
        Ok(block)
    }

    // - Get block(s)
    pub async fn get_blocks(
        &self,
        request: PaginationRequest<String>,
    ) -> ProviderResult<PaginatedResult<Block, String>> {
        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<T: Transaction + Clone>(
        &self,
        tx: &T,
        tolerance: Option<f64>,
    ) -> Result<TransactionCost> {
        let NodeInfo { min_gas_price, .. } = self.node_info().await?;

        let tolerance = tolerance.unwrap_or(DEFAULT_GAS_ESTIMATION_TOLERANCE);
        let 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);

        // Update the dry_run_tx with estimated gas_used and correct gas price to calculate the total_fee
        dry_run_tx
            .with_gas_price(gas_price)
            .with_gas_limit(gas_used);

        let transaction_fee = tx
            .fee_checked_from_tx(&consensus_parameters)
            .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(),
        })
    }

    // Remove limits from an existing Transaction to get an accurate gas estimation
    fn generate_dry_run_tx<T: Transaction + Clone>(tx: &T) -> T {
        // Simulate the contract call with MAX_GAS_PER_TX to get the complete gas_used
        tx.clone().with_gas_limit(MAX_GAS_PER_TX).with_gas_price(0)
    }

    // Increase estimated gas by the provided tolerance
    async fn get_gas_used_with_tolerance<T: Transaction + Clone>(
        &self,
        tx: &T,
        tolerance: f64,
    ) -> Result<u64> {
        let gas_used = self.get_gas_used(&self.dry_run_no_validation(tx).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) -> ProviderResult<Vec<Message>> {
        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,
    ) -> ProviderResult<Option<MessageProof>> {
        let proof = self
            .client
            .message_proof(tx_id, message_id)
            .await?
            .map(Into::into);
        Ok(proof)
    }
}