fuels-contract 0.7.1

Fuel Rust SDK contracts.
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
use crate::abi_decoder::ABIDecoder;
use crate::abi_encoder::ABIEncoder;
use crate::errors::Error;
use crate::parameters::{CallParameters, TxParameters};
use crate::script::Script;
use anyhow::Result;
use fuel_asm::Opcode;
use fuel_gql_client::client::FuelClient;
use fuel_tx::{
    AssetId, ContractId, Input, Output, Receipt, StorageSlot, Transaction, UtxoId, Witness,
};
use fuel_types::{Bytes32, Immediate12, Salt, Word};
use fuel_vm::consts::{REG_CGAS, REG_RET, REG_ZERO, VM_TX_MEMORY};
use fuel_vm::prelude::Contract as FuelContract;
use fuels_core::{
    constants::DEFAULT_COIN_AMOUNT, constants::WORD_SIZE, Detokenize, Selector, Token,
};
use fuels_core::{constants::NATIVE_ASSET_ID, ParamType};
use fuels_signers::provider::Provider;
use fuels_signers::{LocalWallet, Signer};
use std::marker::PhantomData;

#[derive(Debug, Clone, Default)]
pub struct CompiledContract {
    pub raw: Vec<u8>,
    pub salt: Salt,
}

/// Contract is a struct to interface with a contract. That includes things such as
/// compiling, deploying, and running transactions against a contract.
/// The contract has a wallet attribute, used to pay for transactions and sign them.
/// It allows doing calls without passing a wallet/signer each time.
pub struct Contract {
    pub compiled_contract: CompiledContract,
    pub wallet: LocalWallet,
}

/// CallResponse is a struct that is returned by a call to the contract. Its value field
/// holds the decoded typed value returned by the contract's method. The other field
/// holds all the receipts returned by the call.
#[derive(Debug)]
pub struct CallResponse<D> {
    pub value: D,
    pub receipts: Vec<Receipt>,
}

impl Contract {
    pub fn new(compiled_contract: CompiledContract, wallet: LocalWallet) -> Self {
        Self {
            compiled_contract,
            wallet,
        }
    }

    pub fn compute_contract_id(compiled_contract: &CompiledContract) -> ContractId {
        let fuel_contract = FuelContract::from(compiled_contract.raw.clone());
        let root = fuel_contract.root();
        fuel_contract.id(
            &compiled_contract.salt,
            &root,
            &FuelContract::default_state_root(),
        )
    }

    /// Calls an already-deployed contract code.
    /// Note that this is a "generic" call to a contract
    /// and it doesn't, yet, call a specific ABI function in that contract.
    /// We need a wallet to pay for the transaction fees (even though they are 0 right now)
    #[allow(clippy::too_many_arguments)] // We need that many arguments for now
    pub async fn call(
        contract_id: ContractId,
        encoded_selector: Option<Selector>,
        encoded_args: Option<Vec<u8>>,
        fuel_client: &FuelClient,
        tx_parameters: TxParameters,
        call_parameters: CallParameters,
        maturity: Word,
        compute_calldata_offset: bool,
        external_contracts: Option<Vec<ContractId>>,
        wallet: LocalWallet,
    ) -> Result<Vec<Receipt>, Error> {
        // The script len is defined by the 6 Opcodes in the `script`, which is `24`
        // plus `asset_id_offset`, which is `32`, totalling 56.
        let script_len = 56;
        let script_data_offset = VM_TX_MEMORY + Transaction::script_offset() + script_len;
        let script_data_offset = script_data_offset as Immediate12;

        // The offset that locates the asset ID in the script data.
        // It goes from the beginning of `script_data` to `32`.
        let asset_id_offset = 32;

        // Script to call the contract. The offset that points to the `script_data` is loaded at the
        // register `0x12`. Note that we're picking `0x12` simply because it could be any
        // non-reserved register. Then, we use the Opcode to call a contract: `CALL` pointing at the
        // register that we loaded the `script_data` at.
        #[allow(clippy::iter_cloned_collect)]
        let script = vec![
            // Setting `0x10` to point to the 32-byte asset ID of the amount to forward.
            Opcode::ADDI(0x10, REG_ZERO, asset_id_offset),
            // Setting `0x11` to hold the amount of of coins to forward.
            Opcode::ADDI(0x11, REG_ZERO, call_parameters.amount as Immediate12),
            // Setting `0x12` to the `script_data`, defined down below but
            // we already know its length.
            Opcode::ADDI(0x12, REG_ZERO, script_data_offset),
            Opcode::CALL(0x12, 0x11, 0x10, REG_CGAS),
            Opcode::RET(REG_RET),
            Opcode::NOOP,
        ]
        .iter()
        .copied()
        .collect::<Vec<u8>>();

        assert_eq!(
            script.len(),
            script_len - asset_id_offset as usize,
            "Script length *must* be 24"
        );

        // `script_data` consists of:
        // 1. Asset ID to be forwarded
        // 2. Contract ID (ContractID::LEN);
        // 3. Function selector (1 * WORD_SIZE);
        // 4. Calldata offset, if it has structs as input,
        // computed as `script_data_offset` + ContractId::LEN
        //                                  + 2 * WORD_SIZE;
        // 5. Encoded arguments.
        let mut script_data: Vec<u8> = vec![];

        script_data.extend(call_parameters.asset_id.to_vec());

        // Insert contract_id
        script_data.extend(contract_id.as_ref());

        // Insert encoded function selector, if any
        if let Some(e) = encoded_selector {
            script_data.extend(e)
        }

        // If the method call takes custom inputs or has more than
        // one argument, we need to calculate the `call_data_offset`,
        // which points to where the data for the custom types start in the
        // transaction. If it doesn't take any custom inputs, this isn't necessary.
        if compute_calldata_offset {
            // Offset of the script data relative to the call data
            let call_data_offset = script_data_offset as usize + ContractId::LEN + 2 * WORD_SIZE;
            let call_data_offset = call_data_offset as Word;

            script_data.extend(&call_data_offset.to_be_bytes());
        }

        // Insert encoded arguments, if any
        if let Some(e) = encoded_args {
            script_data.extend(e)
        }

        let mut inputs: Vec<Input> = vec![];
        let mut outputs: Vec<Output> = vec![];

        let self_contract_input = Input::contract(
            UtxoId::new(Bytes32::zeroed(), 0),
            Bytes32::zeroed(),
            Bytes32::zeroed(),
            contract_id,
        );
        inputs.push(self_contract_input);

        let spendables = wallet
            .get_spendable_coins(&AssetId::default(), DEFAULT_COIN_AMOUNT as u64)
            .await
            .unwrap();

        for coin in spendables {
            let input_coin = Input::coin(
                UtxoId::from(coin.utxo_id),
                coin.owner.into(),
                coin.amount.0,
                AssetId::default(),
                0,
                0,
                vec![],
                vec![],
            );

            inputs.push(input_coin);
        }

        let n_inputs = inputs.len();

        let self_contract_output = Output::contract(0, Bytes32::zeroed(), Bytes32::zeroed());
        outputs.push(self_contract_output);

        let change_output = Output::change(wallet.address(), 0, AssetId::default());
        outputs.push(change_output);

        // Add external contract IDs to Input/Output pair, if applicable.
        if let Some(external_contract_ids) = external_contracts {
            for (idx, external_contract_id) in external_contract_ids.iter().enumerate() {
                // We must associate the right external contract input to the corresponding external
                // output index (TXO). We add the `n_inputs` offset because we added some inputs
                // above.
                let output_index: u8 = (idx + n_inputs) as u8;
                let external_contract_input = Input::contract(
                    UtxoId::new(Bytes32::zeroed(), output_index),
                    Bytes32::zeroed(),
                    Bytes32::zeroed(),
                    *external_contract_id,
                );

                inputs.push(external_contract_input);

                let external_contract_output =
                    Output::contract(output_index, Bytes32::zeroed(), Bytes32::zeroed());

                outputs.push(external_contract_output);
            }
        }

        let mut tx = Transaction::script(
            tx_parameters.gas_price,
            tx_parameters.gas_limit,
            tx_parameters.byte_price,
            maturity,
            script,
            script_data,
            inputs,
            outputs,
            vec![Witness::from(vec![0u8, 0u8])],
        );
        wallet.sign_transaction(&mut tx).await?;

        let script = Script::new(tx);

        script.call(fuel_client).await
    }

    /// Creates an ABI call based on a function selector and
    /// the encoding of its call arguments, which is a slice of Tokens.
    /// It returns a prepared ContractCall that can further be used to
    /// make the actual transaction.
    /// This method is the underlying implementation of the functions
    /// generated from an ABI JSON spec, i.e, this is what's generated:
    /// quote! {
    ///     #doc
    ///     pub fn #name(&self #input) -> #result {
    ///         Contract::method_hash(#tokenized_signature, #arg)
    ///     }
    /// }
    /// For more details see `code_gen/functions_gen.rs`.
    /// Note that this needs a wallet because the contract instance needs a wallet for the calls
    pub fn method_hash<D: Detokenize>(
        provider: &Provider,
        contract_id: ContractId,
        wallet: &LocalWallet,
        signature: Selector,
        output_params: &[ParamType],
        args: &[Token],
    ) -> Result<ContractCall<D>, Error> {
        let mut encoder = ABIEncoder::new();

        let encoded_args = encoder.encode(args).unwrap();
        let encoded_selector = signature;

        let tx_parameters = TxParameters::default();
        let call_parameters = CallParameters::default();

        let compute_calldata_offset = Contract::should_compute_call_data_offset(args);

        let maturity = 0;
        Ok(ContractCall {
            contract_id,
            encoded_args,
            tx_parameters,
            call_parameters,
            maturity,
            encoded_selector,
            fuel_client: provider.client.clone(),
            datatype: PhantomData,
            output_params: output_params.to_vec(),
            compute_calldata_offset,
            external_contracts: None,
            wallet: wallet.clone(),
        })
    }

    // Returns true if the method call takes custom inputs or has more than one argument. This is used to determine whether we need to compute the `call_data_offset`.
    fn should_compute_call_data_offset(args: &[Token]) -> bool {
        match args
            .iter()
            .any(|t| matches!(t, Token::Struct(_) | Token::Enum(_)))
        {
            true => true,
            false => args.len() > 1,
        }
    }

    /// Deploys a compiled contract to a running node
    /// To deploy a contract, you need a wallet with enough assets to pay for deployment. This
    /// wallet will also receive the change.
    pub async fn deploy(
        compiled_contract: &CompiledContract,
        provider: &Provider,
        wallet: &LocalWallet,
        params: TxParameters,
    ) -> Result<ContractId, Error> {
        let (mut tx, contract_id) =
            Self::contract_deployment_transaction(compiled_contract, wallet, params).await?;
        wallet.sign_transaction(&mut tx).await?;

        match provider.client.submit(&tx).await {
            Ok(_) => Ok(contract_id),
            Err(e) => Err(Error::TransactionError(e.to_string())),
        }
    }

    pub fn load_sway_contract(binary_filepath: &str, salt: Salt) -> Result<CompiledContract> {
        let bin = std::fs::read(binary_filepath)?;
        Ok(CompiledContract { raw: bin, salt })
    }

    /// Crafts a transaction used to deploy a contract
    pub async fn contract_deployment_transaction(
        compiled_contract: &CompiledContract,
        wallet: &LocalWallet,
        params: TxParameters,
    ) -> Result<(Transaction, ContractId), Error> {
        let maturity = 0;
        let bytecode_witness_index = 0;
        let storage_slots: Vec<StorageSlot> = vec![];
        let witnesses = vec![compiled_contract.raw.clone().into()];

        let static_contracts = vec![];

        let contract_id = Self::compute_contract_id(compiled_contract);

        let outputs: Vec<Output> = vec![
            Output::contract_created(contract_id, FuelContract::default_state_root()),
            // Note that the change will be computed by the node.
            // Here we only have to tell the node who will own the change and its asset ID.
            // For now we use the NATIVE_ASSET_ID constant
            Output::change(wallet.address(), 0, AssetId::from(NATIVE_ASSET_ID)),
        ];
        let inputs = wallet
            .get_asset_inputs_for_amount(AssetId::default(), DEFAULT_COIN_AMOUNT)
            .await?;

        let tx = Transaction::create(
            params.gas_price,
            params.gas_limit,
            params.byte_price,
            maturity,
            bytecode_witness_index,
            compiled_contract.salt,
            static_contracts,
            storage_slots,
            inputs,
            outputs,
            witnesses,
        );

        Ok((tx, contract_id))
    }
}

#[derive(Debug)]
#[must_use = "contract calls do nothing unless you `call` them"]
/// Helper for managing a transaction before submitting it to a node
pub struct ContractCall<D> {
    pub fuel_client: FuelClient,
    pub encoded_args: Vec<u8>,
    pub encoded_selector: Selector,
    pub contract_id: ContractId,
    pub tx_parameters: TxParameters,
    pub call_parameters: CallParameters,
    pub maturity: u64,
    pub datatype: PhantomData<D>,
    pub output_params: Vec<ParamType>,
    pub compute_calldata_offset: bool,
    pub wallet: LocalWallet,
    external_contracts: Option<Vec<ContractId>>,
}

impl<D> ContractCall<D>
where
    D: Detokenize,
{
    /// Sets external contracts as dependencies to this contract's call.
    /// Effectively, this will be used to create Input::Contract/Output::Contract
    /// pairs and set them into the transaction.
    /// Note that this is a builder method, i.e. use it as a chain:
    /// `my_contract_instance.my_method(...).set_contracts(&[another_contract_id]).call()`.
    pub fn set_contracts(mut self, contract_ids: &[ContractId]) -> Self {
        self.external_contracts = Some(contract_ids.to_vec());
        self
    }

    /// Sets the transaction parameters for a given transaction.
    /// Note that this is a builder method, i.e. use it as a chain:
    /// let params = TxParameters { gas_price: 100, gas_limit: 1000000, byte_price: 100 };
    /// `my_contract_instance.my_method(...).tx_params(params).call()`.
    pub fn tx_params(mut self, params: TxParameters) -> Self {
        self.tx_parameters = params;
        self
    }

    /// Sets the call parameters for a given contract call.
    /// Note that this is a builder method, i.e. use it as a chain:
    /// let params = CallParameters { amount: 1, asset_id: NATIVE_ASSET_ID };
    /// `my_contract_instance.my_method(...).call_params(params).call()`.
    pub fn call_params(mut self, params: CallParameters) -> Self {
        self.call_parameters = params;
        self
    }

    /// Call a contract's method. Return a Result<CallResponse, Error>.
    /// The CallResponse structs contains the method's value in its `value`
    /// field as an actual typed value `D` (if your method returns `bool`, it will
    /// be a bool, works also for structs thanks to the `abigen!()`).
    /// The other field of CallResponse, `receipts`, contains the receipts of the
    /// transaction
    pub async fn call(self) -> Result<CallResponse<D>, Error> {
        let mut receipts = Contract::call(
            self.contract_id,
            Some(self.encoded_selector),
            Some(self.encoded_args),
            &self.fuel_client,
            self.tx_parameters,
            self.call_parameters,
            self.maturity,
            self.compute_calldata_offset,
            self.external_contracts,
            self.wallet,
        )
        .await?;

        // If it's an ABI method without a return value, exit early.
        if self.output_params.is_empty() {
            return Ok(CallResponse {
                value: D::from_tokens(vec![])?,
                receipts,
            });
        }

        // Right now we only support methods with a single return type.
        // Soon we'll support tuple as a return type and we'll have to update the logic in here.
        let output_param = &self.output_params[0];

        // If the method's return type is bigger than a single `WORD`, the returned value
        // is stored in `ReturnData.data`, otherwise, it's stored in `Return.val`.
        // Here we're checking for that.
        let (encoded_value, index) = match output_param.bigger_than_word() {
            true => match receipts.iter().find(|&receipt| receipt.data().is_some()) {
                Some(r) => {
                    let index = receipts.iter().position(|elt| elt == r).unwrap();
                    (r.data().unwrap().to_vec(), Some(index))
                }
                None => (vec![], None),
            },
            false => match receipts.iter().find(|&receipt| receipt.val().is_some()) {
                Some(r) => {
                    let index = receipts.iter().position(|elt| elt == r).unwrap();
                    (r.val().unwrap().to_be_bytes().to_vec(), Some(index))
                }
                None => (vec![], None),
            },
        };

        if index.is_some() {
            receipts.remove(index.unwrap());
        }
        let mut decoder = ABIDecoder::new();
        let decoded_value = decoder.decode(&self.output_params, &encoded_value)?;
        Ok(CallResponse {
            value: D::from_tokens(decoded_value)?,
            receipts,
        })
    }
}