fuels-rs

Fuel Network Rust SDK

APACHE-2.0 License

Downloads
1.9M
Stars
44.7K
Committers
30

Bot releases are hidden (Show)

fuels-rs - v0.35.0

Published by digorithm over 1 year ago

What's Changed

New Contributors

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.34.0...v0.35.0

fuels-rs - v0.34.0

Published by digorithm over 1 year ago

What's Changed

New Contributors

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.33.0...v0.34.0

Breaking changes

New abigen! macro

This release includes a huge breaking change to how abigen! works and how users will interact with it. The main motivation for this change was a pretty big problem we recently discovered: what happens when you use a Sway library that shares types between contract A and contract B? You'd use a first abigen!() for the contract A and another abigen!() call for contract B. Since both contracts' JSON ABIs include the types coming from the library included... guess what? There's a conflict of generated types: the shared types in the library would be generated twice and, thus, be different types under the eyes of the Rust compiler. Not a good time!

To fix this, we've rebuilt the macro so that it's called only once, and it takes all necessary contracts, predicates, and scripts that you need. Now it looks like this:

abigen!(
    Contract(name="ContractA", abi="contract_a-abi.json"),
    Contract(name="ContractB", abi="contract_b-abi.json"),
    Script(name="SomeScript", abi="some_script-abi.json"),
    Predicate(name="SomePredicate", abi="some_predicate-abi.json"),
    // ...
);

Although it's a big breaking change, it's fairly easy to migrate:

abigen!(
    MyContract,
    "packages/fuels/tests/contracts/contract_test/out/debug/contract_test-abi.json"
);

Becomes

abigen!(
    Contract(name="MyContract", abi="packages/fuels/tests/contracts/contract_test/out/debug/contract_test-abi.json"),
);

Read the updated SDK book for more details about the new abigen!.

New setup_contract_test!

The new abigen! opened up the possibility of improving the old setup_contract_test! macro as well. Similarly to the old abigen! macro, if you had multiple contracts, you'd call setup_contract_test! multiple times, so you'd have many blocks like this:

setup_contract_test!(
    contract_instance,
    wallet,
    "packages/fuels/tests/contracts/contract_test"
);

Now, you can call setup_contract_test! just once, passing all your contracts, scripts, predicates, and deployments, all at once:

setup_contract_test!(
    Wallets("wallet"),
    Abigen(
        name = "TestContract",
        abi = "packages/fuels/tests/contracts/contract_test"
    ),
    Deploy(
        name = "contract_instance",
        contract = "TestContract",
        wallet = "wallet"
    ),
);

Generated types with non-unique names can now be accessed only by qualifying the type path (i.e., abigen_bindings::some_contract_a_mod::SomeNonUniqueType). For more details, read the updated SDK book.

Predicate new send and receive API

Before, transferring the funds to a predicate looked like this:

wallet.transfer(
    predicate_address,
    amount_to_predicate,
    asset_id,
    TxParameters::default(),
).await?;

It started from the wallet, taking the predicate_address. Now, it starts from the predicate itself:

predicate.receive(&wallet, amount_to_predicate, asset_id, None).await?;

Similarly, spending a predicate also started from the wallet, which never really made much sense:

wallet.spend_predicate(
    predicate_address,
    predicate_code,
    amount_to_predicate,
    asset_id,
    receiver.address(),
    Some(predicate_data),
    TxParameters::default(),
).await?;

Now, it's a lot simpler, and it starts from the predicate, with the addition of a new encode_data() that you can use to pass the arguments of a predicate:

predicate
    .encode_data(signatures) // This is a new method; it'll encode the arguments for you.
    .spend(&receiver, amount_to_predicate, asset_id, None)
    .await?;

For more details, check the updated predicates in the latest docs.

Logging from external contracts

If your contract method is calling other contracts you will have to add the appropriate Inputs and Outputs to your transaction. For your convenience, the SDK provides two methods that can set those input and outputs for you: set_contracts(&[&contract_instance, ...]) and set_contract_ids(&[&contract_id, ...]).

set_contracts(&[&contract_instance, ...]) was changed and it now requires contract instances that were created using the abigen macro. When setting the external contracts with this method, logs and require revert errors originating from the external contract can be propagated and decoded by the calling contract. Here is an example:

let response = contract_caller_instance
    .methods()
    .increment_from_contract(lib_contract_id.into(), 42)
    .set_contracts(&[&lib_contract_instance])
    .call()
    .await?;

You can also have the old behavior where you used contact ids with the set_contract_ids(&[&contract_id, ...]) method. Please note that you will not get logs or require errors propagated if you use this approach. Here is an example:

let response = contract_caller_instance
        .methods()
        .increment_from_contract(lib_contract_id.into(), 42)
        .set_contract_ids(&[lib_contract_id.clone()])
        .call()
        .await?;

Better types importing experience

One piece of feedback we've received often is how hard it is to find and import fundamentals types exported by the fuels-rs crate. We're slowly addressing this by moving these types around to places where it makes sense for them to be.

In this release, we're re-exporting types in a single place — users will only care about this single place to pull types: fuels_types::core

fuels-rs - v0.33.0

Published by anton-trunov almost 2 years ago

What's Changed

New Contributors

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.32.2...v0.33.0

fuels-rs - v0.32.2

Published by mohammadfawaz almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.32.1...v0.32.2

fuels-rs - v0.32.1

Published by digorithm almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.32.0...v0.32.1

fuels-rs - v0.32.0

Published by digorithm almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.31.1...v0.32.0

New features and breaking changes

Custom block time

Adds an optional parameter to produce_blocks to set the start time and the interval of the produced blocks. Useful for testing conditions that require specific times for a block to be produced.

Breaking change

  • produce_blocks() now takes an additional parameter: Option<TimeParameters>.

Parsed and readable revert errors

Revert errors used to be hard to debug, as the SDK would simply dump the hex value of the error coming from the client. Now, this revert error is properly parsed, making debugging a lot easier.

Script arguments support

This release also includes supporting script arguments. I.e., your script main() functions can take arguments; now they're supported by the SDK. This is done through the new script_abigen! macro:

    script_abigen!(
        MyScript,
        "packages/fuels/tests/scripts/script_with_arguments/out/debug/script_with_arguments-abi.json"
    );
    let wallet = launch_provider_and_get_wallet().await;
    let bin_path =
        "../fuels/tests/scripts/script_with_arguments/out/debug/script_with_arguments.bin";
    let instance = MyScript::new(wallet, bin_path);

    let bim = Bimbam { val: 90 };
    let bam = SugarySnack {
        twix: 100,
        mars: 1000,
    };
    let result = instance.main(bim, bam).call().await?;
    let expected = Bimbam { val: 2190 };
    assert_eq!(result.value, expected);

Pay for transaction fees using Messages

Before, you could only use Coins to pay for tx fees; now, you can use Messages as well. Which is useful, e.g., if you want to spend ETH through bridging to pay for fees.

Logs for scripts

Logs can now be decoded when using scripts. The interface is similar to the contract's interface.

Breaking changes

Logs now are pulled through the response returned from a contract call. Instead of pulling them from the contract instance itself:

let contract_methods = contract_instance.methods();
let response = contract_methods.produce_logs_values().call().await?;

let log_u64 = contract_instance.logs_with_type::<u64>(&response.receipts)?;
let log_u32 = contract_instance.logs_with_type::<u32>(&response.receipts)?;
let log_u16 = contract_instance.logs_with_type::<u16>(&response.receipts)?;
let log_u8 = contract_instance.logs_with_type::<u8>(&response.receipts)?;

Pull the logs from the response:

let contract_methods = contract_instance.methods();
let response = contract_methods.produce_logs_values().call().await?;

let log_u64 = response.get_logs_with_type::<u64>()?;
let log_u32 = response.get_logs_with_type::<u32>()?;
let log_u16 = response.get_logs_with_type::<u16>()?;
let log_u8 = response.get_logs_with_type::<u8>()?;

Predicate data encoder

Instead of having to use the SDK's ABIEncoder directly and deal with Tokens directly in order to encode the predicate_data that you're passing to your predicate call, you can now simply use the new interface predicate.encode_data().

So, we're going from:

// Here we have some abstraction leakage. Having to go to `Token`-land in order to get the job done.
let arg = Token::U32(12345_u32);
let args: Vec<Token> = vec![arg];
let predicate_data = ABIEncoder::encode(&args).unwrap();

let amount_to_unlock = 500;

let _result = second_wallet
    .spend_predicate(
        predicate_address,
        predicate_code,
        amount_to_unlock,
        AssetId::default(),
        second_wallet.address(),
        Some(predicate_data),
        TxParameters::default(),
    )
    .await?;

To this:

// No need to deal with `Token`s, just pass whatever Rust's native data here. 
let predicate_data: Vec<u8> = predicate.encode_data(42_u64)?;

let amount_to_unlock = 500;
let _result = second_wallet
    .spend_predicate(
        predicate_address,
        predicate_code,
        amount_to_unlock,
        AssetId::default(),
        second_wallet.address(),
        Some(predicate_data),
        TxParameters::default(),
    )
    .await?;

Other breaking changes

Type rename: CallResponse -> FuelCallResponse

Type rename: Script -> ExecutableFuelCall

The method get_call_execution_script is now get_executable_call.

We also go from:

let script = multi_call_handler.get_call_execution_script().await?;
let receipts = script.call(provider).await.unwrap();

to:

let execution_script = multi_call_handler.get_executable_call().await?;
let receipts = execution_script.execute(provider).await.unwrap();
fuels-rs - v0.31.1

Published by digorithm almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.31.0...v0.31.1

fuels-rs - v0.31.0

Published by digorithm almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.30.0...v0.31.0

Breaking changes

Wallet's get_asset_inputs_for_amount now uses Resources instead of Coins

This means that if you want to cover fees of a transaction using any Resource, i.e., Coin and Message (if you're bridging to Ethereum, for instance) get_asset_inputs_for_amount will now consider Messages, which it didn't before.

fuels-rs - v0.30.0

Published by Voxelot almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.29.0...v0.30.0

fuels-rs - v0.29.0

Published by digorithm almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.28.0...v0.29.0

Breaking changes

All test helpers related to spinning up test nodes now take a Option<ChainConfig> parameter. This is useful for configuring things like gas limits of the test chain, etc. Most likely, you won't need it, which means all you have to do is add a None to that test helper method.

fuels-rs - v0.28.0

Published by digorithm almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.27.0...v0.28.0

fuels-rs - v0.27.0

Published by digorithm almost 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.26.0...v0.27.0

Breaking changes

Contract instance creation now takes a Bech32ContractId, not a string

This type-safety enforcement is needed to avoid many issues down the line. This also makes the UX a bit more friendly by not needing many conversions back and forth between strings, Bech32ContractId, and ContractId.

Once you deploy your contract using the SDK, the contract_id you receive back is already a Bech32ContractId, so the workflow looks like this:

let contract_id = Contract::deploy(
    "../../packages/fuels/tests/contracts/contract_test/out/debug/contract_test.bin",
    &wallet,
    TxParameters::default(),
    StorageConfiguration::default(),
)
.await?;

let contract_methods = MyContract::new(contract_id, wallet).methods(); // No need to call `.to_string()` on `contract_id`. 

New features

Variable output estimation

Instead of manually setting the exact number of variable output in your transaction (which sometimes includes guessing this number), the SDK now offers an estimate_tx_dependencies() that will do this guesswork for you and automatically update the transaction with the right value for variable output. E.g.:

let _ = contract_methods
        .mint_to_addresses(amount, addresses)
        .estimate_tx_dependencies(None) // It takes a limit of how many estimation/guesses it'll perform, `None` for no limits.
        .await?
        .call()
        .await?;

The same will be done for the contract input set through the same API (estimate_tx_dependencies()) in the next release.

Bits256 from strings

A new helper method to create Bits256 from strings is also included in this release: let bits256 = Bits256::from_hex_str(hex_str)?;

Query the balance from your contract through the contract_instance

It's very common to try and check the contract's balance. Before you had to use the Provider directly; now you can use the contract_instance itself: let contract_balances = contract_instance.get_balances().await?;.

fuels-rs - v0.26.0

Published by digorithm about 2 years ago

What's Changed

New Contributors

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.25.1...v0.26.0

Breaking changes

Option<Provider> on run_compiled_script

run_compiled_script now takes an Option<Provider>, this is a straightforward change; All you have to do to migrate is add a None or pass a provider, if desired, to your run_compiled_script call.

New features

Generate ParamTypes from your JSON ABI TypeApplications

This has a niche use, mostly for internal tooling development. All you have to do is use ParamType::try_from_type_application(&type_appl, &type_lookup). Here's an example:

let abi: ProgramABI = serde_json::from_str(&abi_file_contents)?;

let type_lookup = abi
    .types
    .into_iter()
    .map(|a_type| (a_type.type_id, a_type))
    .collect::<HashMap<_, _>>();

let a_fun = abi
    .functions
    .into_iter()
    .find(|fun| fun.name == "array_of_structs")
    .unwrap();

let inputs = a_fun
    .inputs
    .into_iter()
    .map(|type_appl| ParamType::try_from_type_application(&type_appl, &type_lookup))
    .collect::<Result<Vec<_>, _>>()?;

let selector = resolve_fn_selector(&a_fun.name, &inputs);

assert_eq!(selector, [0, 0, 0, 0, 39, 152, 108, 146,]);
fuels-rs - v0.25.1

Published by digorithm about 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.25.0...v0.25.1

fuels-rs - v0.25.0

Published by digorithm about 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.24.0...v0.25.0

New features

Logs and events parsing

The SDK can now parse logs and events with all types (including custom types), as opposed to only binary data.

We’ve introduced two ways to get these typed logs/events:

First, with type-specific log fetching, contract_instance.logs_with_type::<T>:

setup_contract_test!(
    contract_instance,
    wallet,
    "packages/fuels/tests/test_projects/logged_types"
);

let contract_methods = contract_instance.methods();
let response = contract_methods.produce_logs_values().call().await?;

let log_u64 = contract_instance.logs_with_type::<u64>(&response.receipts)?;
let log_u32 = contract_instance.logs_with_type::<u32>(&response.receipts)?;
let log_u16 = contract_instance.logs_with_type::<u16>(&response.receipts)?;
let log_u8 = contract_instance.logs_with_type::<u8>(&response.receipts)?;

This way, you’ll retrieve all logs that happened in that contract_instance that match the type <T>.

Second, if you want to retrieve all logs, in a stringified way, you can use fetch_logs():

let contract_methods = contract_instance.methods();
let response = contract_methods.produce_multiple_logs().call().await?;
let logs = contract_instance.fetch_logs(&response.receipts);

Vec support (input only)

The long waited Vec support is finally here, partially at least. You can now pass Vec to ABI methods that take dynamically-sized vectors. For instance:

let methods = contract_instance.methods();
{
    // vec of u32s
    let arg = vec![0, 1, 2];
    methods.u32_vec(arg).call().await?;
}
{
    // vec of vecs of u32s
    let arg = vec![vec![0, 1, 2], vec![0, 1, 2]];
    methods.vec_in_vec(arg.clone()).call().await?;
}
{
    // vec of structs
    let arg = vec![SomeStruct { a: 0 }, SomeStruct { a: 1 }];
    methods.struct_in_vec(arg.clone()).call().await?;
}

However, we don’t yet support Vec as return values; this will be coming up very soon!

New script crafting interface

Manually creating scripts just became a bit easier with the new API for crafting scripts:

ScriptBuilder::new()
        .set_gas_price(tx_parameters.gas_price)
        .set_gas_limit(tx_parameters.gas_limit)
        .set_maturity(tx_parameters.maturity)
        .set_script(script)
        .set_script_data(script_data)
        .set_inputs(inputs.to_vec())
        .set_outputs(outputs.to_vec())
        .set_amount(amount)
        .build(&wallet)
        .await?
        .call(wallet.get_provider()?)
        .await?;

Support for script’s main arguments are coming up soon.

Breaking changes

The new methods() interface

TLDR:

  1. Remove .build() from your contract instantiation statement (MyContractBuilder::new(…).build()MyContractBuilder::new(...))
  2. Chain .methods() before accessing the desired method from your contract (contract_instance.my_method().call()contract_instance.methods().my_method().call())

Longer explanation motivation behind this change:

Before this release, users relied on the builder .build() method when constructing a new contract instance. For instance:

let contract_instance = MyContractBuilder::new(contract_id.to_string(), wallet).build();

Access to contract_instance methods was done directly:

let transaction_cost = contract_instance
            .initialize_counter(42)
            .call()
            .await?;

This was causing one big problem: conflict between ABI methods and contract instance specific methods generated by the SDK (_get_wallet(), _get_contract_id(), and so on.)

Notice how, to mitigate the issue, the SDK was prepending _ before the method name, but this isn’t sustainable for too long.

To resolve this problem, we’ve removed the need to chain .build() when creating a contract instance, and now, when accessing ABI methods, you must chain .methods() to access all the ABI methods. To get SDK generated methods bound to the contract instance, you can do it directly. For instance:

abigen!(
        SimpleContract,
        "packages/fuels/tests/takes_ints_returns_bool-abi.json",
    );

    let wallet = launch_provider_and_get_wallet().await;

    // `SimpleContract` is the name of the contract.
    // No more `.build()` here.
    let contract_instance = SimpleContract::new(null_contract_id(), wallet);
	
		// `.methods()` before accessing the actual method. The rest
    // follows as usual.
    let call_handler = contract_instance.methods().takes_ints_returns_bool(42);
fuels-rs - v0.24.0

Published by digorithm about 2 years ago

What's Changed

New Contributors

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.23.0...v0.24.0

New features

Generics

We now offer full support to generic structs and enums. Nothing special needs to be done to make this work. Generic parameters are reflected identically from the generic parameters in your Sway code. E.g., struct Person<T> in your Sway code will be struct Person<T> in your Rust code.

Option and Result

Option and Result have full support now. The Option<T>s and Result<T, E>s, along with their generic parameters, in your Sway code will be identical in your Rust code. The generated Rust code uses the actual Rust's Option and Result.

InputMessage

As part of the initial support for the upcoming bridges, you can now use Messages to pay for transactions. Check out the official documentation on this for more details.

setup_contract_test

Setting up the test infrastructure for your tests has become a lot easier; instead of having to instantiate test wallets and nodes and deploy your contract binaries to the test node every time, all you have to do for simple use cases is this:

#[tokio::test]
async fn simple_test() -> Result<(), Error> {
    setup_contract_test!(
        contract_instance,
        wallet,
        "packages/fuels/tests/test_projects/contract_test"
    );

    let response = contract_instance
        .initialize_counter(42)
        .call()
        .await?;

    assert_eq!(42, response.value);
    Ok(())
}
fuels-rs - v0.23.0

Published by digorithm about 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.22.0...v0.23.0

Breaking changes

Update to theProvider::connect() method

Provider::connect() now takes a string instead of a SocketAddr. This simplifies the process of connecting to a given node address. All you have to do is change from:

// This is the address of a running node.
let server_address: SocketAddr = "127.0.0.1:4000"
    .parse()
    .expect("Unable to parse socket address");

// Create the provider using the client.
let provider = Provider::connect(server_address).await.unwrap();

to:

let address = "[<port>:<IP> | <URL>]"; // port:IP like "127.0.0.1:4000" or a URL like "https://my-node-address.com"
let provider = Provider::connect(address).await.unwrap();

New features

Automatic fee estimation for hand-crafted transactions

When hand-crafting transactions with the SDK, you can now use add_fee_coins() to automatically add the necessary coins to that transaction, based on an automatic estimation:

let wallet_config = add_fee_coins_wallet_config(1);
let wallet = launch_custom_provider_and_get_wallets(wallet_config, None)
    .await
    .pop()
    .unwrap();
let mut tx = Wallet::build_transfer_tx(&[], &[], TxParameters::default());

wallet.add_fee_coins(&mut tx, 0, 0).await?;

Check out the cost estimation section in the SDK book.

fuels-rs - v0.22.0

Published by digorithm about 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.21.0...v0.22.0

Breaking changes

This release drops the support for the old JSON ABI format. You may or may not have noticed that forc had been outputting two JSON ABI files: the regular one and a new one, with a different format, named <project_name>-flat-abi.json.

More recently, forc started outputting only the <project_name>-flat-abi.json. If the version of forc that you're using is outputting only this one, make sure to pass the <project_name>-flat-abi.json to the SDK's abigen! macro.

If the version of forc that you're using is outputting both files, from now on, with this SDK release, make sure to pass only the <project_name>-flat-abi.json.

The next forc release will likely turn <project_name>-flat-abi.json back into its original name <project_name>-abi.json, but now containing the new, flat-based JSON ABI. So, suppose you're using whatever version came after the date of this writing and release. In that case, you likely won't have to do anything: forc will output the JSON ABI with the same name as before, containing the new JSON ABI, and the SDK will be parsing it using the new parser.

fuels-rs - v0.21.0

Published by digorithm about 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.20.0...v0.21.0

Breaking changes

Disabled some functionalities to unblock other projects

As per https://github.com/FuelLabs/fuels-rs/pull/546:

if contracts are using either of these:

mint_to_address(amount_to_mint, recipient);
transfer_to_output(amount_to_transfer, ~ContractId::from(BASE_TOKEN), recipient);
msg_sender();

The SDK will not work properly.

These will work again in the subsequent release after the Sway/stdlib work is done to unblock this.

Wallet is now Wallet and WalletUnlocked

Wallets are now read-only and don't require a private key. If you want to alter the chain state (e.g., by signing a transaction), you'll need to pass a private key to Wallet's new unlock() method. This helps with security matters by reducing the scope of the default wallet. Read more here: https://github.com/FuelLabs/fuels-rs/pull/540.

New features

New JSON ABI format support

We're slowly migrating to a new JSON ABI file format, one that's flat-based instead of recursion-based. This will enable us to better support generics.

This release adds support for this new JSON ABI file format. However, we still support both file formats. If you want to try the new one, use the flat one outputted by the compiler.

Within the next weeks, we will drop the support for the old one.

fuels-rs - v0.20.0

Published by digorithm about 2 years ago

What's Changed

Full Changelog: https://github.com/FuelLabs/fuels-rs/compare/v0.19.0...v0.20.0

Breaking changes

wallet.get_coins now takes an AssetId

wallet.get_coins() used to take no arguments; now, it takes an AssetId.

New features

Change the underlying wallet of a contract instance

Now, changing the wallet being used in a contract instance is possible. This is useful for testing when you want to deploy with a given wallet and run multiple tests with different wallets:

contract_instance._with_wallet(wallet_2)?

All you need to do is attach _with_wallet(my_other_wallet) to your contract instance.