Commit graph

155 commits

Author SHA1 Message Date
Daniel Frederico Lins Leite
384f46f61d
Contract self impl (#7275)
## Description

Continuation of https://github.com/FuelLabs/sway/pull/7030.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: hey-ewan <ewanretorokugbe@gmail.com>
Co-authored-by: ewan ✦ <66304707+hey-ewan@users.noreply.github.com>
Co-authored-by: IGI-111 <igi-111@protonmail.com>
2025-07-11 11:02:37 +00:00
Cameron Carstens
d6804729c9
Introduce the Time Library (#7206)
Some checks failed
CI / forc-fmt-check-panic (push) Has been cancelled
CI / check-sdk-harness-test-suite-compatibility (push) Has been cancelled
CI / build-mdbook (push) Has been cancelled
CI / cargo-test-sway-lsp (push) Has been cancelled
CI / build-forc-doc-sway-lib-std (push) Has been cancelled
CI / build-forc-test-project (push) Has been cancelled
CI / cargo-build-workspace (push) Has been cancelled
CI / cargo-clippy (push) Has been cancelled
CI / cargo-toml-fmt-check (push) Has been cancelled
CI / cargo-fmt-check (push) Has been cancelled
CI / cargo-test-forc (push) Has been cancelled
CI / cargo-run-e2e-test-evm (push) Has been cancelled
CI / cargo-test-lib-std (push) Has been cancelled
CI / forc-run-benchmarks (push) Has been cancelled
CI / forc-pkg-fuels-deps-check (push) Has been cancelled
CI / cargo-test-workspace (push) Has been cancelled
CI / cargo-unused-deps-check (push) Has been cancelled
CI / pre-publish-check (push) Has been cancelled
CI / verifications-complete (push) Has been cancelled
CI / cargo-run-e2e-test (push) Has been cancelled
CI / cargo-run-e2e-test-release (push) Has been cancelled
CI / cargo-test-forc-debug (push) Has been cancelled
CI / cargo-test-forc-client (push) Has been cancelled
CI / cargo-test-forc-node (push) Has been cancelled
CI / notify-slack-on-failure (push) Has been cancelled
CI / publish (push) Has been cancelled
CI / build-publish-master-image (push) Has been cancelled
CI / publish-sway-lib-std (push) Has been cancelled
CI / build-publish-release-image (push) Has been cancelled
CI / Build and upload forc binaries to release (push) Has been cancelled
## Description

This PR introduces a comprehensive UNIX time handling library to the
Sway standard library, providing essential time manipulation
capabilities for smart contracts.

Time operations are fundamental for many smart contract use cases:
- Token vesting schedules
- Auction deadlines
- Time-locked transactions
- Subscription renewals
- Staking periods

Currently, Sway lacks standardized time utilities, forcing developers
to:

- Handle time conversions manually
- Implement custom time logic in every contract
- Risk errors in critical time calculations

This library solves these problems with a robust, well-tested time
abstraction.

### Duration Handling

```sway
// Create durations using natural units
let lock_period = Duration::days(90);
let auction_extension = Duration::minutes(15);

// Convert between units
log(lock_period.as_weeks()); // ≈12.857 weeks
log(auction_extension.as_seconds()); // 900 seconds

// Duration arithmetic
let total_lock = lock_period + Duration::weeks(2);
```
### Blockchain Time Operations

```sway
// Get current block time
let now = Time::now();

// Create future/past timestamps
let unlock_time = now.add(Duration::days(30));
let vesting_start = now.subtract(Duration::weeks(12));

// Measure time differences
let time_elapsed = now.duration_since(vesting_start).unwrap();
```

### TAI64 ↔ UNIX Conversion

Support for the existing TAI64 `timestamp()` functionality is
maintained.

```sway
// Native TAI64 from blockchain
let tai_timestamp = timestamp();

// Convert to UNIX time
let unix_time = Time::from_tai64(tai_timestamp);

// Convert back to TAI64
let converted_tai = unix_time.as_tai64();
assert(tai_timestamp == converted_tai);
```

### Benefits 

- Safety: Prevents common time calculation errors
- Accuracy: Properly handles TAI64/UNIX conversion
- Productivity: Reduces boilerplate for time operations
- Consistency: Standardized approach across contracts
- Readability: Natural time unit expressions

### Future Extensions

Once support between different types for `Add`, `Subtract`, `Multiply`,
etc are implemented, we may be able to do the following:

```sway
let now = Time::now();
let future = now + Duration::DAY;

let three_weeks = Duration::WEEK * 3;
```

Closes https://github.com/FuelLabs/sway/issues/3945

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2025-05-30 19:03:23 +10:00
SwayStar123
a5d9d2835f
Merge std and core libraries (#6729)
## Description
Merges the two libraries. They were initially separate to separate the
core logic and fuel vm specific functionality, but that separation is no
longer maintained so having a merged library is better.

Closes #6708

## Checklist

- [ ] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [ ] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [ ] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Sophie <47993817+sdankel@users.noreply.github.com>
Co-authored-by: Igor Rončević <ironcev@hotmail.com>
2025-03-12 23:52:38 +01:00
Cameron Carstens
b03c76e482
Introduce crypto module and expand cryptographic functions (#6837)
## Description

This PR replaces https://github.com/FuelLabs/sway/pull/5747 and intends
to introduce the crypto module.

> Note: https://github.com/FuelLabs/sway/pull/6832 will also use the
crypto module.

The std-lib currently contains the `ecr.sw` and `vm/evm/ecr.sw` files
which have the following functions:

- ec_recover()
- ec_recover_r1()
- ed_verify()
- ec_recover_address()
- ec_recover_address_r1()
- ec_recover_evm_address()

There are a number of issues with this including no type safety for
signatures from different elliptic curves, functions split across
multiple files, poor naming, and generic arguments. All of these are
resolved by this PR which deprecates both `ecr.sw` files and replaces
them with a crypto module which syntactically matches Rust.

The following new types are introduced:

* `PublicKey` - An Asymmetric public key, supporting both 64 and 32-byte
public keys
* `Message` - Hashed message authenticated by a signature type that
handles variable lengths
* `Secp256k1` - A secp256k1 signature
* `Secp256r1` - A secp256r1 signature
* `Ed25519` -  An ed25519 signature
* `Signature` - An ECDSA signature

All original functionality is retained with the new module:

* `Secp256k1::recover()` - Recovers a public key.
* `Secp256r1::recover()` - Recovers a public key.
* `Secp256k1::address()` - Recovers an address.
* `Secp256r1::address()` - Recovers an address.
* `Secp256k1::evm_address()` - Recovers an EVM address.
* `Ed25519::verify()` - Verify that a signature matches the given public
key.

The following new functionality has been added:

* `Secp256k1::verify()` - Verify that a signature matches the given
public key.
* `Secp256r1::verify()` - Verify that a signature matches the given
public key.
* `Secp256k1::verify_address()` - Verify that a signature matches the
given address.
* `Secp256r1::verify_address()` - Verify that a signature matches the
given address.
* `Secp256k1::verify_evm_address()` - Verify that a signature matches
the given EVM address.
* `Secp256r1::verify_evm_address()` - Verify that a signature matches
the given EVM address.
* `Secp256r1::evm_address()` - Recovers an EVM address.

The following functions have been deprecated: 

- `std::ecr::ec_recover()`
- `std::ecr::ec_recover_r1()`
- `std::ecr::ed_verify()`
- `std::ecr::ec_recover_address()`
- `std::ecr::ec_recover_address_r1()`
- `std::vm::evm::ecr::ec_recover_evm_address()`

Example of changes for recovering a public key:
```sway
// Before
fn foo(signature: B512, message: b256) {
     let recovered_public_key: B512 = ec_recover(signature, message).unwrap();
}

// After
fn bar(signature: Signature, message: Message) {
     let recovered_public_key: PublicKey = signature.recover(message).unwrap();
}
```

Example of changes for recovering an Address:
```sway
// Before
fn foo(signature: B512, message: b256) {
     let recovered_address: Address = ec_recover_address(signature, message).unwrap();
}

// After
fn bar(signature: Signature, message: Message) {
     let recovered_address: Address = signature.address(message).unwrap();
}
```

Complete recovery example using the `Signature` type:

```sway
use std::crypto::{Message, PublicKey, Secp256r1, Signature};

fn foo() {
    let secp256r1_signature = Signature::Secp256r1(Secp256r1::from((
        0xbd0c9b8792876712afadbff382e1bf31c44437823ed761cc3600d0016de511ac,
        0x44ac566bd156b4fc71a4a4cb2655d3da360c695edb27dc3b64d621e122fea23d,
    )));
    let signed_message = Message::from(0x1e45523606c96c98ba970ff7cf9511fab8b25e1bcd52ced30b81df1e4a9c4323);
    
    // A recovered public key pair.
    let secp256r1_public_key = secp256r1_signature.recover(signed_message);
    assert(secp256r1_public_key.is_ok());
    assert(
        secp256r1_public_key
            .unwrap() == PublicKey::from((
            0xd6ea577a54ae42411fbc78d686d4abba2150ca83540528e4b868002e346004b2,
            0x62660ecce5979493fe5684526e8e00875b948e507a89a47096bc84064a175452,
        )),
    );
}
```

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2025-01-25 23:23:40 +01:00
Igor Rončević
4fe687094e
Implement Iterator for StorageVec (#6821)
## Description

This PR implements `Iterator` for `StorageVec`.

Iterating over a `StorageVec` via `for` loop should now be the preferred
option. Compared to the traversal via `while` loop and incrementing
index, the `for` loop is:
- more performant. `for` loop eliminates the redundant boundary checks
done in every `get()` call in the `while` loop.
- more idiomatic and convenient.

Closes #6796.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: bitzoic <bitzoic.eth@gmail.com>
2025-01-14 16:18:16 +01:00
Igor Rončević
23576769d1
Refactor swayfmt to support arbitrary lexed trees (#6806)
## Description

This PR refactors `swayfmt` to be able generate code from arbitrary
lexed trees. Arbitrary means a lexed tree that can be fully or partially
created in-memory by manipulating the tree structure in code. It does
not need to necessarily be backed by source code. This is needed to be
able to reuse `swayfmt` for generating source code from tools that
analyze and modify Sway code, as explained in #6779.

This PR makes the `swayfmt` independent of spans backed by the source
code, by doing the following changes:
- Keywords are rendered by using theirs `AS_STR` associated constants.
- The `Token` trait is extended with the `AS_STR` associated constant,
and tokens are rendered by using that constant.
- `Ident`s are rendered by using theirs `as_str()` methods. This method
takes the textual implementation from `Ident::name_override_opt` if it
is provided, and ignores the span in that case.
- `Literal`s are rendered based on the literal value and not their
spans. The exception are numeric literals that do not have empty spans.
Those are considered to be backed by source code and are rendered as
written in code, e.g., `1_000_000u64`.

The PR also fixes some existing bugs in `swayfmt`:
- `use path::{single_import,};` will be formatted as `use
path::single_import;`
- `use path::{a,b,};` will be formatted as `use path::{a, b};`
- partial addresses #6802 by rendering annotations for final values.
- partial addresses #6805 by properly rendering final values, but still
not using the expected field alignment.

The PR also removes the `path` parameter from the `parse_file`. It was
used only to provide an unnecessary dummy `source_id` which was always
pointing to the package root file.

Closes #6779.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2025-01-07 12:55:03 +01:00
jjcnn
2b6fd7a535
Fix module visibility check (#6685)
## Description

Fixes #6673.

The module visibility check has been broken for some time. 

In some cases, like the one described in #6673, this has resulted in
modules being mistakenly regarded as inaccessible, even though they
ought to be accessible.

In other cases, private modules were mistakenly regarded as accessible.
For examples see the updated tests in the PR.

The check has now been fixed, and all tests have been updated
accordingly.

This bugfix can be regarded as a breaking change, because some modules
that were deemed accessible before may now be deemed inaccessible and
will require the addition of a `pub` keyword in front of the module
declaration.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
Co-authored-by: IGI-111 <igi-111@protonmail.com>
2024-11-15 05:59:45 +01:00
IGI-111
e9cdaacaf1
Remove support for namespace attribute (#6279)
## Description
Namespace annotation is no longer supported and has been replaced by
namespacing syntax.


## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2024-07-19 13:53:59 +02:00
Call Delegation
5e435fcd35
docs: Fix nightly storage docs (#6172)
## Description

https://vercel.com/fuel-labs/docs-hub/5r9LvMoawPA5PmVPTqX4p4FFcP8Q?filter=errors

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2024-06-24 13:58:17 +10:00
Cameron Carstens
2984831f5f
Add primitive conversions submodules to the prelude (#6105)
## Description

As part of https://github.com/FuelLabs/sway/pull/6087, it was revealed
that the current `use std::primitive_conversions::*;` line in the
prelude does not import anything which a developer can use. To use any
of the submodules in the primitive conversions library, users would need
to import the individual submodule regardless of the prelude.

This PR adds the submodules as an import to the prelude to stay
consistent with the original intent. Both the core's and std-lib's
primitive conversions modules are imported. Conversions between
primitive types should not require additional imports.

Example before:
```sway
use std::primitive_conversions::u32::*;

fn foo() {
    let my_u8 = 1_u8;
    let my_u16 = 1_u16;
    let my_u64 = 1_u64;

    let u32_1 = u32::from(my_u8);
    let u32_2 = u32::from(my_u16);
    let u32_3 = u32::try_from(my_u64);
}
```

Example after:
```sway
fn foo() {
    let my_u8 = 1_u8;
    let my_u16 = 1_u16;
    let my_u64 = 1_u64;

    let u32_1 = u32::from(my_u8);
    let u32_2 = u32::from(my_u16);
    let u32_3 = u32::try_from(my_u64);
}
```

Closes https://github.com/FuelLabs/sway/issues/6088

Dependent on https://github.com/FuelLabs/sway/pull/6087

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2024-06-11 05:13:39 +04:00
Cameron Carstens
5389aa85c0
Add examples on how to import storage types to the book (#6051)
## Description

A [recent issue on the
forum](https://forum.fuel.network/t/no-method-push-found/5342)
demonstrated the lack of examples on how to import storage types to the
book. Specifically, they require the glob operator to be used properly.
A note on this has been added.

## Checklist

- [ ] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2024-05-27 12:04:44 +08:00
Cameron Carstens
954a81b626
Introduce Self::zero and self::is_zero() for 13 types (#5973)
## Description

Introduces the following functions to be implemented:
- `zero()`
- `is_zero()`

This falls inline with what we see in [Rust's Zero
Trait](https://docs.rs/num/latest/num/traits/trait.Zero.html), making
the language feel and look more like Rust.

This PR also deprecates the following:
- `ZERO_B256` -> `b256::zero()`
- `ZERO_U256` -> `u256::zero()`

To define a `u256` or `b256` zero address, the following should be used:

```sway
let zero_b256 = b256::zero();
let zero_u256 = u256::zero();
```

A common use of the `ZERO_B256` was to define the zero addresses and
contract id`:
```sway
let zero_address = Address::from(ZERO_B256);
let zero_contract = ContractId::from(ZERO_B25);
```
The following is now possible:
```sway
let zero_address = Address::zero();
let zero_contract = ContractId::zero();
```

The following types now implement the `Zero` trait:

- `u8`
- `u16`
- `u32`
- `u64`
- `u256`
- `b256`
- `SubId`
- `AssetId`
- `ContractId`
- `Address`
- `EvmAddress`
- `U128`
- `B512`

Closes #5830 

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: K1-R1 <77465250+K1-R1@users.noreply.github.com>
2024-05-22 14:13:15 +04:00
Sophie Dankel
f8e8d356be
ci: fixing typos programmatically (#5975)
## Description

Adds a CI check for typos and fixes all* typos in code, comments, and
docs.

*found by [typos-cli](https://github.com/crate-ci/typos)

`typos` doesn't catch everything, but it seems to work better than
codespell and cargo-spellcheck (fewer false positives).

## Checklist

- [ ] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [ ] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [ ] I have requested a review from the relevant team or maintainers.
2024-05-09 10:21:32 +10:00
Sarah Schwartz
474d654c9d
docs: add external code doc (#5840)
## Description

This PR adds a page for external code execution in the Sway book.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Sophie Dankel <47993817+sdankel@users.noreply.github.com>
Co-authored-by: IGI-111 <igi-111@protonmail.com>
2024-05-08 20:23:42 +01:00
Daniel Frederico Lins Leite
1aec319e31
set new encoding as true by default and allow it to be disabled (#5915)
## Description

This PR sets the "new encoding" (from now on will be called "encoding
v1") as the default. We can still disable it using `no_encoding_v1`,
which switches back to "encoding v0".

Actions that needs to be done after this being merged will exist in
https://github.com/FuelLabs/sway/issues/5727

New features
  - ABI Super traits;
  - AbiEncode buffer dynamic sizing;

Bugs Fixed
- `ContractCall` intrinsic interaction effect was not set correctly;

Fixing warnings and error messages
- Better error message when core-lib is not available for
scripts/contracts/predicates;
- Better error message when main inputs/outputs are unknown or error
types;
- Better error message when main inputs/outputs do not implement
AbiEncode/AbiDecode;
- Don't warn impurity attributes on the "__entry" fn;
- Don't warn CEI on the "__entry" fn. Our CEI analysis, currently, does
not recognize `Never`. This means it does not realize it is impossible
to call two contract functions;

Test Disabled (needs to be enabled again in the future)
- should_pass/language/name_resolution_after_monomorphization
- should_pass/language/shadowing/shadowed_glob_imports
- should_pass/language/name_resolution_inside_intrinsics
- sdk-harness/external_proxy test is not working. I am assuming it is
the LDC bug that is already fixed on version 0.25. What is happening is
that the literal "double_value" has the correct length, but some random
data. Which makes the method selector fails. Only after we call LDC. The
proxy contract is working.

Test generating more warnings than before
- should_pass/dca/contract/superabi_contract_calls
What happens here is that when we implement a trait for `Contract`, we
actually generate two functions: one prefixed `__contract_entry` that is
called by the method selector; and another one normal, that can be
called freely. So, if the trait method is never called manually, it is
marked as dead.
- should_pass/dca/contract/abi_fn_params
I actually think the new warning is correct and nothing here needs to be
done.

Test with fewer warnings than before
- should_pass/dca/unused_fields
auto-impl is making all fields being used. so no dead code warnings are
being generated. We need to fix this.

Changes to std-lib
- Functions that return data about call context changed the semantic.
`first_param` and `second_param` return the value as the VM sees them.
We now have `called_method` and `called_args`. This means that we can
change the protocol later and still keep these four functions always
working and with meaningful names.
- 
- predicate_data also was updated to use encoding v1 protocol.

ICE
- increase_buffer_if_needed implementation is a little bit strange
because does not work as a method inside `Buffer`. For some reason, it
is generating an ICE. I need to create an issue so we can fix, and
improve the implementation here.
- `Buffer` used by AbiEncode needs a `push_bytes` so we can be more
efficient when encoding Bytes and others.

## Checklist

- [ ] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [ ] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [ ] I have requested a review from the relevant team or maintainers.
2024-04-25 20:37:50 +04:00
Cameron Carstens
dbdcd62c8b
Simplify Asset Transfer and Mint Functions (#5891)
## Description

There are currently multiple functions for the same functionality:

Transfer:
- `transfer()`
- `force_transfer_to_contract()`
- `transfer_to_address()`

Mint:
- `mint()`
- `mint_to()`
- `mint_to_contract()`
- `mint_to_address()`

This be reduced to just `transfer()`, `mint()`, `mint_to()`. Specific
functions for separately minting and transferring to contracts and
addresses are legacy code left over from before the `Identity` type was
introduced and now only adds additional complexity.

## Changes:

- `force_transfer_to_contract()` is now private
- `transfer_to_address()` is now private
- `mint_to_contract()` removed
- `mint_to_address()` removed
- Removed newlines in inline docs for better `forc doc` compatibility
- Updated `burn()` inline docs

## Breaking Changes:

- `force_transfer_to_contract()` is now private
- `transfer_to_address()` is now private
- `mint_to_contract()` removed
- `mint_to_address()` removed

## Closes

- Closes #5773 

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: K1-R1 <77465250+K1-R1@users.noreply.github.com>
2024-04-25 18:39:21 +04:00
Cameron Carstens
11f9c0ebf7
Use GM opcode to fetch the base_asset_id (#5806)
## Description

The Base asset ID is no longer a constant. It is now stored in memory
and retrieved using the `GM` opcode. More information can be found
[here](https://github.com/FuelLabs/fuel-specs/blob/master/src/fuel-vm/instruction-set.md#gm-get-metadata).

## Breaking Changes

- The `BASE_ASSET_ID` constant has been removed.
- `AssetId::base_asset_id()` is now `AssetId::base()`.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2024-04-19 12:43:49 +00:00
Cameron Carstens
3f47df8682
Remove contract_id() in favor of ContractId::this() (#5867)
## Description

We currently support 2 methods of getting the contract id of a contract
in an internal context:

- `contract_id()`
- `ContractId::this()`

The `this()` associated function is a constructor that returns `Self`
and should be the primary method of getting the contract id. This
idiomatically follows Rust's syntax and `contract_id()` has been
removed.

The same syntax is followed with `AssetId::base()`.

Closes #5834 

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: SwayStar123 <46050679+SwayStar123@users.noreply.github.com>
2024-04-18 14:24:01 +00:00
Cameron Carstens
a386e7be4d
Expand Native Asset Docs (#5808)
## Description

- Additional docs covering Native Assets including:
     - EVM vs FuelVM Assets
     - What `AssetId` is
     - How to use `AssetId`
     - What `SubId` is
     - What the default asset is
     - How to mint coins
     - How to burn coins
     - How to transfer coins
     - How to check contract balances
     - How to check transaction values
     - How to receive assets in contracts
     - ERC-20 equivalent example
     - ERC-1155 equivalent example
- The Liquidity Pool example has been moved to its own section in
examples

These changes were originally included in
https://github.com/FuelLabs/sway/pull/5806 but have been pulled out into
a separate PR

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: K1-R1 <77465250+K1-R1@users.noreply.github.com>
2024-04-09 07:54:18 +09:00
IGI-111
98d8f4cadb
Bump to v0.52.0 (#5791) 2024-03-27 13:22:13 +04:00
Cameron Carstens
aa23d5e9d4
Advanced Storage Docs (#5715)
## Description

There have been a number of questions on the forum regarding storage and
the section needed and update. The following changes have been made:

- Simplified basic storage examples
- Added examples that include structs
- Added basic examples that include `StorageMap`
- Added basic examples that include `StorageVec`
- Added basic examples that include `StorageString`
- Added basic examples that include `StorageBytes`
- Added advanced nested examples using `StorageVec` and `StorageMap`
- Added advanced nested examples using `StorageString` and `StorageMap`
- Added advanced nested examples using `StorageBytes` and `StorageVec`
- ~~Added table of contents~~ Removed due to CI errors not accepting TOB
format
- Fixed inline docs on `StorageString`
- Fixed inline docs on `StorageBytes`
- Fixed inline docs on `StorageKey`

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Sarah Schwartz <58856580+sarahschwartz@users.noreply.github.com>
2024-03-13 11:09:55 +09:00
Sarah Schwartz
1589c8f5a2
docs: add type conversions page (#5708)
This PR adds a Type Conversions page to make it easier for developers to
quickly find a solution to converting a type.
2024-03-11 17:29:18 +00:00
Cameron Carstens
d5b8cb8f99
Encapsulation for std-lib (#5658)
## Description

Merges the staging branch into master from the following PRs:

https://github.com/FuelLabs/sway/pull/5640
https://github.com/FuelLabs/sway/pull/5630
https://github.com/FuelLabs/sway/pull/5621
https://github.com/FuelLabs/sway/pull/5613

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: IGI-111 <igi-111@protonmail.com>
Co-authored-by: Sophie Dankel <47993817+sdankel@users.noreply.github.com>
2024-03-03 09:48:17 +04:00
IGI-111
18bde0ff7a
Storage namespace annotation (#5601)
## Description

Add a `#[namespace(my_namespace)]` annotation to allow developers to
avoid storage slot collisions when loading contract code using LDC.

Fixes #5490


## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2024-02-19 13:03:16 +11:00
Igor Rončević
8320c1ba12
Struct field privacy (#5508)
## Description

This PR makes struct fields private by default and introduces explicit
public struct fields:

```
pub struct Struct {
    pub public_field: u8,
    private_field: u8,    
}
```

Private fields can be accessed only withing the module in which their
struct is declared.

Error messages are properly orchestrated so that no conflicting or
duplicated messages are emitted. Since the change is a breaking change,
relevant suggestion on how to fix the particular issue are given.

To avoid an abrupt breaking change, the errors are temporarily turned
into warnings. These warnings will become errors in the upcoming
versions of Sway. The demo section below demonstrate how the errors will
look like, and how a one warning equivalent looks now.

Standard library structs like `Vec` or `String`, are adapted where
needed by adding the `pub` keyword to the fields that are accessed
outside of the struct declaration module. Some of these fields should
very likely remain public, but some, like e.g., `RawBytes::ptr` or
`Vec::buf` should be private. Adjusting the standard library to properly
utilize private fields is out of scope of this PR and will be done
separately. I expect breaking changes in the STD once we start modeling
structs keeping encapsulation in mind.

In addition, the PR:
- migrates
[annotate_snippets](https://github.com/rust-lang/annotate-snippets-rs)
crate to its latest version (breaking changes)
- removes a redundant non-existing field error and orchestrates
non-existing field error with privacy errors
- replaces an invalid and misleading error when accessing fields on
storage elements that are not structs

Closes #4692.

## Known limitations

There is an issue in displaying multi-line code snippets, which is
independent of these changes, but wasn't apparent before. The issue is
visible in the demo section below, where the struct bodies are sometimes
not fully shown, and they should be. This issue is reported in #5499 and
will be solved in a separate PR.

## Demo (an excerpt 😄)

### Private struct field is inaccessible

![Private struct field is
inaccessible](8ac07c2b-8135-470b-ad7a-820a4934f232)

![Private struct field is
inaccessible](ca944a7a-e6c4-4b6f-97f1-18000e649452)

### Struct cannot be instantiated

![Struct cannot be instantiated due to inaccessible private
fields](05993416-91d6-4f58-8fd6-8c35c23595f8)

![Struct cannot be instantiated due to inaccessible private
fields](655c17df-a520-45a0-8af4-f1e424ddf085)

### Struct pattern must ignore inaccessible private fields

![Struct pattern must ignore inaccessible private
fields](90396d14-de63-4b08-9f22-e260f406542d)

### Struct pattern has missing fields

![Struct pattern has missing
fields](0ddf44e8-7598-461a-b85b-48006670b0ca)

### Errors temporarily turned into warnings

![Error turned into
warning](ba235248-740f-4fd2-b1fa-29fc35ee8c84)

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2024-01-30 17:15:24 +04:00
Cameron Carstens
d4c12dd813
Remove Subcurrency from examples (#5475)
## Description

As a continuation of https://github.com/FuelLabs/sway/pull/5461 and
improving the clarity of Native Assets on Fuel vs tokens, the legacy
Subcurrency example has been removed.

The Subcurrency example showed an implementation of a token using a
`StorageMap` to store addresses to balances. This sort of implementation
should not be promoted in Sway as it is a counterproductive example and
takes away from Native Assets on Fuel.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2024-01-18 02:06:10 +00:00
Cameron Carstens
c72934deb7
Formalize Asset and Coin Terminology in the std-lib (#5461)
## Description

We currently use the following terminology in the standard library when
discussing native assets on Fuel:
 - Asset
 - Coin
 - Token

This can be incredibly confusing for new developers. A naming convention
that is consistent across the standard library, docs, and examples is
critical for clarity.
 
In the following PR I formalize the use of the words "Asset" and "Coin".

- An "Asset" is a Native Asset on Fuel and has the associated `AssetId`
type. Assets are distinguishable from one another.
- A "Coin" represents a singular unit of an Asset. Coins of the same
Asset are not distinguishable from one another.

The changes made reflect the distinction that Fuel does not use tokens
like other ecosystems such as Ethereum and uses Native Assets with a
UTXO design instead.

The Asset and Coin terminology is also consistent the fuel-vm's input
and outputs types. This is already seen in the `input.sw` file with the
`Input::Coin` enum and `output.sw`'s `Output::Coin` enum in the standard
library respectively.

## Breaking Changes

Imports using the `token` import should now use the `asset` import.

Before:
```sway
use std::token::mint;
```
After:
```sway
use std::asset::mint;
```

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2024-01-15 10:04:35 +07:00
César D. Rodas
61c260c10c
Run forc fmt on std-lib (#5404)
## Description

Run `forc fmt` on the std-lib

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2024-01-03 11:41:32 -03:00
César D. Rodas
d3533713ca
Improve forc-fmt to format std lib and core (#5410)
## Description

Changes needed to build #5404 and #5405 

## Improvements
1. Use byte-offset instead of chars offset
2. Enhanced `asm` formatting

## Better output when tests fail


![image](9b884167-a242-4a81-8858-5eff7e9bb7c1)


## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Cesar Rodas <cesar@Cesars-MacBook-Pro-2.local>
2023-12-21 23:57:27 +00:00
Cesar
18bf4930a1
Improve inline arguments formatting (#5283)
## Description

Improve breaking method calls into multiple lines following Rust rules.

A two parts method call is never broken into multiple lines, longer
chains are broken if they are long enough (counting their arguments).

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2023-11-15 23:32:25 -08:00
Cameron Carstens
37b0a7069f
Introduce the DEFAULT_SUB_ID constant (#5246)
## Description

The following pull request does two things:
1. Introduces the `DEFAULT_SUB_ID` constant. This is equivalent to the
`ZERO_B256` constant. This constant makes the Sway code easier to read
and comprehend improving the developer's UX. The actual value of the
default is something the developer no longer needs to think about.

Before:
```sway
let my_asset = AssetId::new(my_contract, ZERO_B256);
```
Now:
```sway
let my_asset = AssetId::new(my_contract, DEFAULT_SUB_ID);
```

2. Removes the `ContractId` argument from the `AssetId::default()`
function. In 90% of cases `default()` is used within the contract that
issued the token, making this an unnecessary argument. This function now
fetches the contract id of the contract it's called in, thus eliminating
the need to import another function and add additional arguments. In the
case a developer needs the default of another contract, the
`DEFAULT_SUB_ID` can be used instead making the distinction more legible
and apparent.

Before:
```sway
use std::call_frames::contract_id;

fn foo(other_contract: ContractId) {
     let other_asset = AssetId::default(other_contract);
     let my_asset = AssetId::default(contract_id());
}
```
After:
```sway
fn foo(other_contract: ContractId) {
     let other_asset = AssetId::new(other_contract, DEFAULT_SUB_ID);
     let my_asset = AssetId::default();
}
```

## Checklist

- [ ] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: SwayStar123 <46050679+SwayStar123@users.noreply.github.com>
2023-11-08 07:22:29 +00:00
Chris-san
c32934b9c2
bug: Update swayfmt::Config & remove partial implementations (#5193)
Closes #3472 

What this does:
- Removes use of `Config` options that were partially implemented
- Fixes the default implementations for `Config`. This removes the match
arms in the implementations of the `CurlyBrace` trait and just handles
the default, eg `ItemBraceStyle::SameLineWhere`
- Adds tests for items with `where` clauses, ie `ItemImpl`,
`ItemStruct`, `ItemTrait`, which weren't being tested thoroughly enough
- Updates to code quality in the `Config`, and documentation for the
default config's options
2023-10-31 20:39:19 -07:00
Cesar
d9de68d4c5
Attempt to break long expressions into multiple lines (#5207)
Fixes #3474

## Description

Breaks long expressions (focusing into chained methods calls but will
cover all expressions) into multiple lines

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2023-10-27 22:12:48 -03:00
Daniel Frederico Lins Leite
f88bbf42d9
String slices (#4996)
## Description

This PR introduces `string slices`.

The basic usage is at `test/src/ir_generation/tests/str_slice.sw`:

```sway
let a: str = "ABC";
```

Before this PR `a` would be of type `str[3]`, a string array.

Now both `string slices` and `string arrays` exist. This PR contains a
new intrinsic that converts from string literals to arrays.

```sway
let a: str = "ABC";
let b: str[3] = __to_str_array("ABC");
```

Runtime conversions can be done using 

```sway
let a = "abcd";
let b: str[4] = a.try_as_str_array().unwrap();
let c = from_str_array(b);
```

string slices to string arrays can fail, so they return
`Option<str[N]>`; and because of this `try_as_str_array` lives in `std`.
The inverse, `from_str_array` only fails if `alloc` fails and lives in
`core`.

At this PR `string slices` are forbidden at `configurable`, `storage`,
`const`, and main arguments and returns. The reason for these
limitations is the internal structure of `string slices` having a `ptr`.

The optimized IR for initializing the slice is:

```
v0 = const string<3> "abc"
v1 = ptr_to_int v0 to u64, !2
v2 = get_local ptr { u64, u64 }, __anon_0, !2
v3 = const u64 0
v4 = get_elem_ptr v2, ptr u64, v3
store v1 to v4, !2

v5 = const u64 1
v6 = get_elem_ptr v2, ptr u64, v5
v7 = const u64 3
store v7 to v6, !2

v8 = get_local ptr slice, __anon_1, !2
mem_copy_bytes v8, v2, 16
```

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2023-09-11 13:24:41 +00:00
SwayStar123
159a2402ab
Introduce the AssetId type (#4955)
## Description
Change AssetId from alias to struct. Allows implementing of methods.
Also moved the helper functions into the struct as methods.

## Checklist

- [ ] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [ ] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [ ] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Cameron Carstens <54727135+bitzoic@users.noreply.github.com>
Co-authored-by: Braqzen <103777923+Braqzen@users.noreply.github.com>
2023-09-06 12:57:09 +00:00
Marcos Henrich
4f760014e7
Adds Hash trait and Hasher struct to std lib. (#4701)
## Description

Implements Hash trait for builtin types and for some std lib types.

This is required to have a proper hashing that does not change in case
the internal memory representation of type changes.

Current hashing functions are hashing the types in memory directly, as
this representation might change in future versions of the VM and
compiler we want to have a more reliable way of getting hashes that
won't change in future versions of the compiler and std lib.

Replaces use of sha256 function with Hasher in storage_map and
storage_vec.

Adds intrinsic __check_str_type.

__check_str_type returns an error at compile time in case the provided
generic type is not a str.

This is used to guarantee that `Hasher` `write_str` is not called with
non str types.

Closes #3835.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2023-08-21 10:15:29 +01:00
Green Baneling
e6f8925f98
An upgrade to fuel-core v0.20.3 (#4821)
This pull request is an upgrade to a `fuel-core 0.20.1` release.

The biggest changes coming from this new release is a rework of how
AssetId is structured to support [granular asset
minting](https://github.com/FuelLabs/fuel-specs/pull/491). This means a
contract can mint and burn multiple AssetId's, and the ContractId !=
AssetId.

---------

Co-authored-by: bitzoic <bitzoic.eth@gmail.com>
Co-authored-by: Cameron Carstens <54727135+bitzoic@users.noreply.github.com>
Co-authored-by: Sophie Dankel <47993817+sdankel@users.noreply.github.com>
Co-authored-by: Brandon Kite <brandonkite92@gmail.com>
Co-authored-by: Sophie <sophiedankel@gmail.com>
2023-08-14 11:19:40 +02:00
Anton Trunov
d2c1f03548
SuperABIs for ABIs (#4272) 2023-07-27 08:45:50 +04:00
Cameron Carstens
5d27e25779
Remove dependency on external library for Ownership example (#4832)
## Description

It was noted that in the case of a breaking change to the std-lib, the
external Ownership library would need to be updated, which depended on
the std-lib creating a circular dependency.

The external library has been removed from the example and a skeleton of
its implementation has been added with a link to the actual
implementation.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

Co-authored-by: bitzoic <bitzoic.eth@gmail.com>
2023-07-19 14:59:30 +00:00
Cameron Carstens
9195d633f3
Update Sway Book and ownership example to use ownership library and src-5 standard (#4751)
## Description

The Sway Book's ownership example and documentation is outdated and does
not include the ownership library. It now links to the SRC-5 Ownership
standard, ownership library, and includes additional examples.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: bitzoic <bitzoic.eth@gmail.com>
Co-authored-by: SwayStar123 <46050679+SwayStar123@users.noreply.github.com>
2023-07-18 18:21:28 +00:00
Nick
461f679b48
Doc storage read unwrap_or clarification. (#4736)
## Description
Document clarification around ensuring .unwrap_or(0) is used for storage
read examples.

---------

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2023-07-04 12:52:41 +10:00
Emily Herbert
9e559ab66a
Adding documentation for generic traits and trait constraints on free functions. (#4620)
## Description

- closes #3296
- closes #3297

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2023-06-09 09:42:24 +10:00
Chris-san
bbe746dafa
feat(forc doc): Add impl_trait representation to ItemBody (#4389)
## Description
Adds a trait implementation section to item declarations & fixes CSS for
required methods on traits.



https://user-images.githubusercontent.com/57543709/236067329-11bb66bd-b7b9-4a46-81d6-520d0e2ece83.mov



## Checklist

- [x] I have linked to any relevant issues. Closes #3972 
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Sophie Dankel <47993817+sdankel@users.noreply.github.com>
2023-05-04 10:18:26 -05:00
IGI-111
6a3fba19d4
Add Option and Result variants in prelude (#4504)
## Description

This also handles ambiguities in cases where a lone ident is either a
variable or a variant; or a variable declaration or an enum scrutinee.

Fix #4480

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2023-04-28 09:58:54 +00:00
Call Delegation
af5f536101
Added to msg_sender to prelude and removed from swayfiles (#4483)
## Description
Fixes #4478

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Kin Chan <calldelegation@calldelegation.local>
2023-04-27 17:05:37 -04:00
Mohammad Fawaz
1db8385158
Replace old storage API with the new one explained in the StorageKey RFC (#4464)
## Description
Implement https://github.com/FuelLabs/sway-rfcs/pull/23

Closes https://github.com/FuelLabs/sway/issues/3419 (technically via the
RFC)
Closes https://github.com/FuelLabs/sway/issues/3202
Closes https://github.com/FuelLabs/sway/issues/3043
Closes https://github.com/FuelLabs/sway/issues/2639
Closes https://github.com/FuelLabs/sway/issues/2465
Closes https://github.com/FuelLabs/sway/issues/4304

This is a big one but mostly removes stuff. It's hard to review but the
summary of changes below should be sufficient. Most of the changes here
are things that I just had to do to make CI pass.

- Removed the `--experimental-storage` flag and made its
[behavior](https://github.com/FuelLabs/sway/pull/4297) the default. Also
removed everything that was required for the previous storage APIs in
favour of the new ones.
- Break down the `std::storage` into multiple submodules:
 - `storage_key` implements the API for `std::core::StorageKey`
- `storage_api` implements the free functions `read` (previously `get`),
`write` (previously `store`), and `clear`.
- 4 more modules for the dynamic storage types which now use the new
`StorageKey` API.
- `#[storage(write)]` now allows reading from storage as well. This is
needed because the way we pack structs in storage now requires that we
sometimes read from storage first if we were to write a portion of a
slot.
- Removed the "storage only types" checks and the corresponding tests.
- Removed the `__get_storage_key` intrinsic and the `get_storage_key` IR
instruction and all corresponding tests. Also removed the `state_index`
metadata as it is no longer required.
- Added tests and example to showcase nested storage maps and nested
storage vectors.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2023-04-21 07:36:40 -04:00
IGI-111
30f869a3a8
Implement OR match pattern (#4348)
## Description

Allow users to specify match patters such as:

```sway
let x = 1;
match x {
  0 | 1 => true,
  _ => false
}
```

We also check that all patterns in a disjunction declare the same set of
variables (not doing so is an error).

Fix https://github.com/FuelLabs/sway/issues/769

This requires a change in the pattern matching analysis to remove the
assumption that a specialized matrix of a vector pattern is always a
vector, which is now no longer true because or patterns can generate
multiple branches and therefore multiple rows.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2023-04-18 22:08:17 +00:00
bing
032cd3b3b7
refactor: deprecate ConfigTimeConstants (#4298)
## Description

Closes #3681 

I meant to tackle #3077 first, but tackling #3681 first cleans up a lot
of the code needed to make #3077 easier.

This PR is mostly cleanup:
- Completely removes usage of `ConfigTimeConstant` everywhere (in
forc-pkg, sway-core, sway-type)
- **(BREAKING)** Completely removes support for `[constants]` table in
the manifest, which was using the `ConfigTimeConstant` struct. This
change is breaking for app devs ([open
issue](https://github.com/FuelLabs/sway-applications/issues/375)) and
from a [quick
search](https://github.com/FuelLabs/sway-applications/search?l=TOML&q=%5Bconstants%5D)
on our sway-applications repo, there's a number of manifests still using
the old version of configuration time constants.

Consequentially, the above change also allowed us to cut down on other
constructs like `ConstInjectMap` within forc-pkg, since the only thing
we need to inject now are const CONTRACT_IDs - this cuts down quite a
bit of now-redundant code.

- As a result of the removal of `ConfigTimeConstant`, a few tests using
that feature were also deleted.
- Also updated the `configurable` example to be known as
`configurable_constants` instead of `config_time_constant`.


**This PR does not:**
- Fix the manual creation of `CONTRACT_ID` const. To create the const,
we still undergo manual parsing and type-checking and finally inserting
into a `SymbolMap` manually. This will be handled in a separate PR to
tackle #3077

Other than removal of a lot of code to do with CTC, the main change here
that allows contract dependencies to still work here is instead of
relying on the `ConstInjectMap` which we used to inject both constants
and contract dependencies, there is now only a single contract ID value
that we require (this is abstracted as `ContractIdConst`) to inject into
the contract for tests.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
2023-03-17 01:15:55 +00:00
Kaya Gökalp
f4cffba1c4
feat: multi contract calls in unit tests for contracts (#4156)
## Description
closes #3571.
closes #4162.

This PR adds the ability of calling multiple contracts from sway unit
tests if they are added as `[contract-dependencies]`. This is limited
with contracts currently but I will be having a follow-up which builds
upon this to introduce this support to scripts as well.

As these contracts are already declared under `[contract-dependencies]`
their contract ids are injected into their namespace by `forc-pkg`. A
bug related to this step is fixed in #4159.

<img width="787" alt="image"
src="https://user-images.githubusercontent.com/20915464/224345002-92dc2bcb-823d-4971-9041-31111cf85e77.png">

### Follow-ups
- #4161
- ~#4162~
 
## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Kaya Gokalp <kayagokalp@fuel.sh>
2023-03-16 10:01:16 +00:00
Mohammad Fawaz
2ffb034eb8
Implementing basic type aliases (#4151) 2023-03-16 00:58:30 +00:00