o2-tools 0.1.17

Reusable tooling for trade account and order book contract interactions on Fuel
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
use crate::{
    order_book::DEFAULT_METHOD_GAS,
    utxo_manager::{
        FuelTxCoin,
        SharedUtxoManager,
    },
    wallet_ext::{
        BuilderData,
        SendResult,
        WalletExt,
    },
};
use fuel_core_client::client::{
    FuelClient,
    types::TransactionStatus,
};
use fuel_core_types::{
    blockchain::transaction::TransactionExt,
    fuel_tx::{
        Chargeable,
        Finalizable,
        Input,
        Output,
        Receipt,
        Script,
        Transaction,
        TxId,
        TxPointer,
        UniqueIdentifier,
    },
    fuel_types::ContractId,
    services::executor::TransactionExecutionResult,
};
use fuels::{
    accounts::ViewOnlyAccount,
    core::traits::{
        Parameterize,
        Tokenizable,
    },
    prelude::{
        CallHandler,
        Wallet,
    },
    programs::{
        calls::{
            traits::{
                ContractDependencyConfigurator,
                ResponseParser,
                TransactionTuner,
            },
            utils::find_ids_of_missing_contracts,
        },
        responses::CallResponse,
    },
    types::{
        BlockHeight,
        errors::{
            Error as FuelsError,
            Result as FuelsResult,
        },
        transaction_builders::VariableOutputPolicy,
        tx_status::TxStatus,
    },
};
use std::{
    collections::HashSet,
    fmt::Debug,
    future::Future,
};

pub trait CallHandlerExt<T> {
    fn almost_sync_call(
        self,
        builder_date: &BuilderData,
        utxo_manager: &SharedUtxoManager,
        tx_config: &Option<TransactionConfig>,
    ) -> impl Future<Output = FuelsResult<SendResult<FuelsResult<CallResponse<T>>>>>;
}

#[derive(Debug, Clone, Copy, Default)]
pub struct TransactionConfig {
    pub min_gas_limit: u64,
    pub estimate_gas_usage: bool,
    pub expiration_height: Option<BlockHeight>,
}

impl TransactionConfig {
    pub fn builder() -> TransactionConfigBuilder {
        TransactionConfigBuilder::new()
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct TransactionConfigBuilder {
    min_gas_limit: Option<u64>,
    estimate_gas_usage: Option<bool>,
    expiration_height: Option<BlockHeight>,
}

impl TransactionConfigBuilder {
    pub fn new() -> Self {
        TransactionConfigBuilder {
            min_gas_limit: None,
            estimate_gas_usage: None,
            expiration_height: None,
        }
    }

    pub fn with_min_gas_limit(&mut self, min_gas_limit: u64) -> &mut Self {
        self.min_gas_limit = Some(min_gas_limit);
        self
    }

    pub fn with_estimate_gas_usage(&mut self, estimate_gas_usage: bool) -> &mut Self {
        self.estimate_gas_usage = Some(estimate_gas_usage);
        self
    }

    pub fn min_gas_limit(&self) -> Option<u64> {
        self.min_gas_limit
    }

    pub fn estimate_gas_usage(&self) -> Option<bool> {
        self.estimate_gas_usage
    }

    pub fn with_expiration_height(
        &mut self,
        expiration_height: BlockHeight,
    ) -> &mut Self {
        self.expiration_height = Some(expiration_height);
        self
    }

    pub fn expiration_height(&self) -> Option<BlockHeight> {
        self.expiration_height
    }

    pub fn build(self) -> TransactionConfig {
        TransactionConfig {
            min_gas_limit: self.min_gas_limit.unwrap_or(DEFAULT_METHOD_GAS),
            estimate_gas_usage: self.estimate_gas_usage.unwrap_or(true),
            expiration_height: self.expiration_height,
        }
    }
}

impl<C, T> CallHandlerExt<T> for CallHandler<Wallet, C, T>
where
    C: ContractDependencyConfigurator + TransactionTuner + ResponseParser,
    T: Tokenizable + Parameterize + Debug,
{
    #[tracing::instrument(skip_all)]
    async fn almost_sync_call(
        self,
        builder_date: &BuilderData,
        utxo_manager: &SharedUtxoManager,
        tx_config: &Option<TransactionConfig>,
    ) -> FuelsResult<SendResult<FuelsResult<CallResponse<T>>>> {
        let tx_config = tx_config.unwrap_or_default();
        let consensus_parameters = &builder_date.consensus_parameters;
        let tb =
            self.transaction_builder_with_parameters(consensus_parameters, vec![])?;

        let owner = self.account.address();
        let secret_key = self.account.signer().secret_key();
        let base_asset_id = *consensus_parameters.base_asset_id();
        let chain_id = consensus_parameters.chain_id();

        let max_fee = builder_date.max_fee();

        let input_coins = {
            let mut utxo_manager = utxo_manager.lock().await;
            utxo_manager
                .guaranteed_extract_coins(owner, base_asset_id, max_fee as u128)
                .map_err(|e| FuelsError::Other(e.to_string()))
        }?;
        let coins_iter = input_coins.iter();
        let account = self.account.clone();

        let assemble_tx = async move {
            let witness_limit = crate::wallet_ext::SIGNATURE_MARGIN;

            let mut builder =
                fuel_core_types::fuel_tx::TransactionBuilder::<Script>::script(
                    tb.script,
                    tb.script_data,
                );
            builder
                .with_chain_id(consensus_parameters.chain_id())
                .max_fee_limit(max_fee)
                .witness_limit(witness_limit as u64);

            if let Some(expiration_height) = tx_config.expiration_height {
                builder.expiration(expiration_height);
            }

            for coin in coins_iter {
                builder.add_unsigned_coin_input(
                    secret_key,
                    coin.utxo_id,
                    coin.amount,
                    coin.asset_id,
                    TxPointer::default(),
                );
            }

            builder.add_output(Output::Change {
                to: owner,
                amount: 0,
                asset_id: base_asset_id,
            });

            for input in tb.inputs {
                if let fuels::types::input::Input::Contract { contract_id, .. } = input {
                    let contract_index = builder.inputs().len();
                    builder.add_input(Input::contract(
                        Default::default(),
                        Default::default(),
                        Default::default(),
                        Default::default(),
                        contract_id,
                    ));
                    builder.add_output(Output::contract(
                        contract_index as u16,
                        Default::default(),
                        Default::default(),
                    ));
                }
            }

            // Add variable output if policy is Exactly
            if let VariableOutputPolicy::Exactly(variable_outputs) =
                tb.variable_output_policy
            {
                for _ in 0..variable_outputs {
                    builder.add_output(Output::Variable {
                        to: Default::default(),
                        amount: 0,
                        asset_id: Default::default(),
                    });
                }
            }

            let dummy_script = builder.clone().finalize();
            let max_gas = dummy_script.max_gas(
                consensus_parameters.gas_costs(),
                consensus_parameters.fee_params(),
            ) + 1;
            let available_gas =
                consensus_parameters.tx_params().max_gas_per_tx() - max_gas;

            let (missing_contracts, used_gas) = if tx_config.estimate_gas_usage {
                builder.script_gas_limit(available_gas);

                let client = account.provider().client();
                let tx_to_dry_run = builder.clone().finalize().into();

                let result = client
                    .dry_run_opt(
                        &[tx_to_dry_run],
                        Some(false),
                        Some(builder_date.gas_price),
                        None,
                    )
                    .await?
                    .into_iter()
                    .next()
                    .ok_or_else(|| {
                        FuelsError::Other("Dry run failed to return a result".to_string())
                    })?;

                result.result.missing_contracts_and_used_gas()
            } else {
                (Default::default(), 0)
            };

            for contract_id in missing_contracts {
                let contract_index = builder.inputs().len();
                builder.add_input(Input::contract(
                    Default::default(),
                    Default::default(),
                    Default::default(),
                    Default::default(),
                    contract_id,
                ));

                builder.add_output(Output::contract(
                    contract_index as u16,
                    Default::default(),
                    Default::default(),
                ));
            }

            let gas_limit = std::cmp::max(
                tx_config.min_gas_limit,
                std::cmp::min(used_gas * 2 + 100_000, available_gas),
            );
            builder.script_gas_limit(gas_limit);

            Ok(builder.finalize_as_transaction())
        };

        let tx = match assemble_tx.await {
            Ok(tx) => tx,
            Err(e) => {
                // Return coins if tx assembly failed
                let mut utxo_manager = utxo_manager.lock().await;
                utxo_manager.load_from_coins_vec(input_coins);
                return Err(e);
            }
        };

        let tx_id = tx.id(&consensus_parameters.chain_id());

        maybe_return_coins(
            &self.account,
            &tx,
            tx_id,
            tx_config.expiration_height,
            utxo_manager,
        );

        let send_result =
            self.account
                .send_transaction(chain_id, &tx)
                .await
                .map_err(|e| {
                    FuelsError::Other(format!("Failed to send transaction {tx_id}: {e}"))
                })?;

        {
            let mut utxo_manager = utxo_manager.lock().await;
            utxo_manager.load_from_coins_vec(send_result.known_coins.clone());
            utxo_manager.load_from_coins_vec(send_result.dynamic_coins.clone());
        }

        let failure_logs = match &send_result.tx_status {
            TxStatus::Success(_)
            | TxStatus::PreconfirmationSuccess(_)
            | TxStatus::Submitted
            | TxStatus::SqueezedOut(_) => None,
            TxStatus::Failure(failure) | TxStatus::PreconfirmationFailure(failure) => {
                let result = self.log_decoder.decode_logs(&failure.receipts);
                tracing::error!(tx_id = %&send_result.tx_id, "Failed to process transaction: {result:?}");
                Some(result)
            }
        };

        let tx_status =
            self.get_response(send_result.tx_status)
                .map_err(|e: FuelsError| {
                    if let Some(failure_logs) = &failure_logs {
                        FuelsError::Other(format!(
                            "Transaction {tx_id} failed with logs: {failure_logs:?} and error: {e}"
                        ))
                    } else {
                        FuelsError::Other(format!(
                            "Failed to get transaction status {tx_id}: {e}"
                        ))
                    }
                });

        let result = SendResult {
            tx_id: send_result.tx_id,
            tx_status,
            known_coins: send_result.known_coins,
            dynamic_coins: send_result.dynamic_coins,
            preconf_rx_time: send_result.preconf_rx_time,
        };

        Ok(result)
    }
}

pub(crate) fn maybe_return_coins(
    account: &Wallet,
    tx: &Transaction,
    tx_id: TxId,
    expiration_height: Option<BlockHeight>,
    utxo_manager: &SharedUtxoManager,
) {
    if let Some(expiration_height) = expiration_height {
        let tx_inputs = tx.inputs().into_owned();
        let provider = account.provider().clone();
        let utxo_manager = utxo_manager.clone();

        tokio::spawn(async move {
            // Wait until we reach expiration_block_height + 1
            let target_height = expiration_height.succ().expect("shouldn't happen; qed");

            // The client should be unique to avoid required height for regular use
            let mut client = FuelClient::new(provider.url())
                .expect("The URL is correct because we send transactions before; qed");
            match client
                .with_required_fuel_block_height(Some(target_height))
                .transaction(&tx_id)
                .await
            {
                Ok(Some(tx_response)) => {
                    // Transaction exists, check its status
                    let status = tx_response.status;
                    match status {
                        TransactionStatus::Success { .. }
                        | TransactionStatus::Failure { .. } => {
                            // Transaction is confirmed or failed, don't return coins
                            tracing::debug!(
                                %tx_id,
                                "Transaction is confirmed/failed at height {}",
                                target_height
                            );
                        }
                        _ => {
                            // Transaction exists but not confirmed/failed, return coins
                            tracing::warn!(
                                %tx_id,
                                "Transaction not confirmed/failed at height {target_height:?}, returning coins",
                            );
                            let coins = tx_inputs
                                .iter()
                                .filter_map(|input| FuelTxCoin::try_from(input).ok());
                            let mut utxo_manager = utxo_manager.lock().await;
                            utxo_manager.load_from_coins_vec(coins.collect());
                        }
                    }
                }
                Ok(None) => {
                    // Transaction doesn't exist in fuel-core, return coins
                    tracing::warn!(
                        %tx_id,
                        "Transaction not found at height {target_height:?}, returning coins",
                    );
                    let coins = tx_inputs
                        .iter()
                        .filter_map(|input| FuelTxCoin::try_from(input).ok());
                    let mut utxo_manager = utxo_manager.lock().await;
                    utxo_manager.load_from_coins_vec(coins.collect());
                }
                Err(err) => {
                    tracing::error!(
                        %tx_id,
                        "Failed to get transaction status: {err:?} to return coins",
                    );
                }
            }
        });
    }
}

pub(crate) trait TransactionStatusExt {
    fn missing_contracts_and_used_gas(&self) -> (HashSet<ContractId>, u64);
}

impl TransactionStatusExt for TransactionExecutionResult {
    fn missing_contracts_and_used_gas(&self) -> (HashSet<ContractId>, u64) {
        let contracts = find_ids_of_missing_contracts(self.receipts());
        let used_gas = self
            .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);

        (contracts.into_iter().collect(), used_gas)
    }
}