Skip to content

Commit

Permalink
Minor enhancements to the Sway Book (FuelLabs#2741)
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammadfawaz authored Sep 8, 2022
1 parent e514d2b commit 734ed89
Show file tree
Hide file tree
Showing 25 changed files with 84 additions and 151 deletions.
1 change: 0 additions & 1 deletion docs/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
- [Advanced Concepts](./advanced/index.md)
- [Generic Types](./advanced/generic_types.md)
- [Traits](./advanced/traits.md)
- [Trait Constraints](./advanced/trait_constraints.md)
- [Assembly](./advanced/assembly.md)
- [Common Collections](./common-collections/index.md)
- [Vectors on the Heap](./common-collections/vec.md)
Expand Down
8 changes: 4 additions & 4 deletions docs/src/advanced/generic_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ purely shorthand for the sake of ergonomics.

## Trait Constraints

> **Note** Trait constraints [have not yet been implemented](https://github.com/FuelLabs/sway/issues/970)
Important background to know before diving into trait constraints is that the `where` clause can be used to specify the required traits for the generic argument. So, when writing something like a `HashMap` you may
want to specify that the generic argument implements a `Hash` trait.

Expand All @@ -41,8 +43,6 @@ fn get_hashmap_key<T>(Key : T) -> b256
}
```

_`where` clauses are still [work-in-progress](https://github.com/FuelLabs/sway/issues/970), so some `where` statements shown may not be fully implemented._

Of course, our `noop()` function is not useful. Often, a programmer will want to declare functions over types which satisfy certain traits.
For example, let's try to implement the successor function, `successor()`, for all numeric types.

Expand All @@ -60,8 +60,8 @@ Run `forc build`, and you will get:
.. |
9 | where T: Add
10 | {
11 | argument + 1
| ^ Mismatched types: expected type "T" but saw type "u64"
11 | argument + 1
| ^ Mismatched types: expected type "T" but saw type "u64"
12 | }
13 |
```
Expand Down
3 changes: 0 additions & 3 deletions docs/src/advanced/trait_constraints.md

This file was deleted.

2 changes: 2 additions & 0 deletions docs/src/advanced/traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ fn play_game_with_deck<T>(a: Vec<T>) where T: Card {
}
```

> **Note** Trait constraints (i.e. using the `where` keyword) [have not yet been implemented](https://github.com/FuelLabs/sway/issues/970)
Now, if you want to use the function `play_game_with_deck` with your struct, you must implement `Card` for your struct. Note that the following code example assumes a dependency _games_ has been included in the `Forc.toml` file.

```sway
Expand Down
8 changes: 4 additions & 4 deletions docs/src/basics/comments_and_logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ The `Log` receipt is generated for _non-reference_ types, namely `bool`, `u8`, `
"is": 10352,
"pc": 10404,
"ra": 42,
"rb": 0,
"rb": 1018205,
"rc": 0,
"rd": 0
}
```

Note that `ra` will include the value being logged. The additional registers `rb` to `rd` will be zero when using `log(x)`.
Note that `ra` will include the value being logged. The additional registers `rc` and `rd` will be zero when using `log` while `rb` may include a non-zero value representing a unique ID for the `log` instance. The unique ID is not meaningful on its own but allows the Rust and the TS SDKs to know the type of the data being logged, by looking up the log ID in the JSON ABI file.

### `LogData` Receipt

Expand All @@ -69,8 +69,8 @@ Note that `ra` will include the value being logged. The additional registers `rb
"pc": 10444,
"ptr": 10468,
"ra": 0,
"rb": 0
"rb": 1018194
}
```

Note that `data` in the receipt above will include the value being logged as a hexadecimal.
Note that `data` in the receipt above will include the value being logged as a hexadecimal. Similarly to the `Log` receipt, additional registers are written: `ra` will always be zero when using `log`, while `rb` will contain a unique ID for the `log` instance.
2 changes: 0 additions & 2 deletions docs/src/basics/control_flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ Sway supports advanced pattern matching through exhaustive `match` expressions.
{{#include ../../../examples/match_statements/src/main.sw}}
```

In the example above, braces around the code block following `=>` in each match arm are not required unless the code block contains multiple statements. They are added in this example due to an [issue in the Sway formatter](https://github.com/FuelLabs/sway/issues/604).

## Loops

### `while`
Expand Down
27 changes: 0 additions & 27 deletions docs/src/basics/methods_and_associated_functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,30 +49,3 @@ and when called:
```sway
{{#include ../../../examples/ref_mut_params/src/main.sw:call_move_right}}
```

## Syntax Examples

```sway
enum Color {
Blue: (),
Green: (),
Red: (),
Silver: (),
Grey: (),
// etc...
}
enum Make {
Ford: (),
Toyota: (),
Mazda: (),
Chevrolet: (),
BMW: (),
// etc...
}
struct Car {
make: Make,
color: Color,
}
```
2 changes: 1 addition & 1 deletion docs/src/frontend/typescript_sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ The TypeScript SDK supports common tasks like:
- Building and sending transactions
- Encoding and decoding contract ABI

Refer [here](https://github.com/FuelLabs/fuels-ts) for full documentation.
Refer [here](https://fuellabs.github.io/fuels-ts) for full documentation.
2 changes: 1 addition & 1 deletion docs/src/introduction/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ Compiled library "core".

### Deploy the Contract

It's now time to deploy the contract and call it on a Fuel node. We will show how to do this using `forc` from the command line, but you can also do it using the [Rust SDK](https://github.com/FuelLabs/fuels-rs#deploying-a-sway-contract) or the [TypeScript SDK](https://github.com/FuelLabs/fuels-ts/#deploying-contracts)
It's now time to deploy the contract and call it on a Fuel node. We will show how to do this using `forc` from the command line, but you can also do it using the [Rust SDK](https://fuellabs.github.io/fuels-rs/master/getting-started/contracts.html) or the [TypeScript SDK](https://fuellabs.github.io/fuels-ts/#deploying-contracts)

### Spin Up a Fuel node

Expand Down
2 changes: 0 additions & 2 deletions docs/src/reference/known_issues_and_workarounds.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,3 @@
## General

* No compiler optimization passes have been implemented yet, therefore bytecode will be more expensive and larger than it would be in production. Note that eventually the optimizer will support zero-cost abstractions, avoiding the need for developers to go down to inline assembly to produce optimal code.

* Currently, we need to parse the Sway code before formatting it. Hence, **the formatter cannot work on Sway code that does not parse correctly**. This requirement may be changed in the future.
17 changes: 13 additions & 4 deletions docs/src/testing/testing-with-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ $ tree .
└── harness.rs
```

Note that this is also a Rust package, hence the existence of a `Cargo.toml` (Rust manifest file) in the project root directory. The `Cargo.toml` in the root directory contains necessary Rust dependencies to enable you to write Rust-based tests using our [Rust SDK](https://github.com/FuelLabs/fuels-rs), (`fuels-rs`).
Note that this is also a Rust package, hence the existence of a `Cargo.toml` (Rust manifest file) in the project root directory. The `Cargo.toml` in the root directory contains necessary Rust dependencies to enable you to write Rust-based tests using our [Rust SDK](https://fuellabs.github.io/fuels-rs/latest), (`fuels-rs`).

These tests can be run using `forc test` which will look for Rust tests under the `tests/` directory (created automatically with `forc new` and prepopulated with boilerplate code).

Expand All @@ -36,7 +36,16 @@ abigen!(TestContract, "out/debug/my-fuel-project-abi.json");
async fn get_contract_instance() -> (TestContract, ContractId) {
// Launch a local network and deploy the contract
let wallet = launch_provider_and_get_wallet().await;
let mut wallets = launch_custom_provider_and_get_wallets(
WalletsConfig::new(
Some(1), /* Single wallet */
Some(1), /* Single coin (UTXO) */
Some(1_000_000_000), /* Amount per coin */
),
None,
)
.await;
let wallet = wallets.pop().unwrap();
let id = Contract::deploy(
"./out/debug/my-fuel-project.bin",
Expand All @@ -49,9 +58,9 @@ async fn get_contract_instance() -> (TestContract, ContractId) {
.await
.unwrap();
let instance = TestContract::new(id.to_string(), wallet);
let instance = TestContractBuilder::new(id.to_string(), wallet).build();
(instance, id)
(instance, id.into())
}
#[tokio::test]
Expand Down
1 change: 1 addition & 0 deletions examples/counter/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ contract;
abi TestContract {
#[storage(write)]
fn initialize_counter(value: u64) -> u64;

#[storage(read, write)]
fn increment_counter(amount: u64) -> u64;
}
Expand Down
16 changes: 4 additions & 12 deletions examples/identity/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,8 @@ impl IdentityExample for Contract {
fn identity_to_contract_id(my_identity: Identity) {
// ANCHOR: identity_to_contract_id
let my_contract_id: ContractId = match my_identity {
Identity::ContractId(identity) => {
identity
},
_ => {
revert(0);
}
Identity::ContractId(identity) => identity,
_ => revert(0),
};
// ANCHOR_END: identity_to_contract_id
}
Expand All @@ -60,12 +56,8 @@ impl IdentityExample for Contract {

// ANCHOR: different_executions
match my_identity {
Identity::Address(identity) => {
transfer_to_output(amount, token_id, identity);
},
Identity::ContractId(identity) => {
force_transfer_to_contract(amount, token_id, identity);
},
Identity::Address(identity) => transfer_to_output(amount, token_id, identity),
Identity::ContractId(identity) => force_transfer_to_contract(amount, token_id, identity),
};
// ANCHOR_END: different_executions
}
Expand Down
6 changes: 3 additions & 3 deletions examples/liquidity_pool/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ abi LiquidityPool {
fn withdraw(recipient: Address);
}

const BASE_TOKEN: b256 = 0x9ae5b658754e096e4d681c548daf46354495a437cc61492599e33fc64dcdc30c;
const BASE_TOKEN = ~ContractId::from(0x9ae5b658754e096e4d681c548daf46354495a437cc61492599e33fc64dcdc30c);

impl LiquidityPool for Contract {
fn deposit(recipient: Address) {
assert(msg_asset_id() == ~ContractId::from(BASE_TOKEN));
assert(msg_asset_id() == BASE_TOKEN);
assert(msg_amount() > 0);

// Mint two times the amount.
Expand All @@ -42,6 +42,6 @@ impl LiquidityPool for Contract {
let amount_to_transfer = msg_amount() / 2;

// Transfer base token to recipient.
transfer_to_output(amount_to_transfer, ~ContractId::from(BASE_TOKEN), recipient);
transfer_to_output(amount_to_transfer, BASE_TOKEN, recipient);
}
}
48 changes: 12 additions & 36 deletions examples/match_statements/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -16,54 +16,30 @@ fn main() -> u64 {

// Match as an expression.
let a = match 8 {
7 => {
4
},
9 => {
5
},
8 => {
6
},
_ => {
100
},
7 => 4,
9 => 5,
8 => 6,
_ => 100,
};

// Match as a statement for control flow.
match x {
5 => {
foo()
},
_ => {
bar()
},
5 => foo(),
_ => bar(),
};

// Match an enum
let e = SomeEnum::A(42);
let v = match e {
SomeEnum::A(val) => {
val
},
SomeEnum::B(true) => {
1
},
SomeEnum::B(false) => {
0
},
_ => {
0
},
SomeEnum::A(val) => val,
SomeEnum::B(true) => 1,
SomeEnum::B(false) => 0,
_ => 0,
};

// Match as expression used for a return.
match 42 {
0 => {
24
},
foo => {
foo
},
0 => 24,
foo => foo,
}
}
4 changes: 2 additions & 2 deletions examples/msg_sender/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ abi MyOwnedContract {
fn receive(field_1: u64) -> bool;
}

const OWNER: b256 = 0x9ae5b658754e096e4d681c548daf46354495a437cc61492599e33fc64dcdc30c;
const OWNER = ~Address::from(0x9ae5b658754e096e4d681c548daf46354495a437cc61492599e33fc64dcdc30c);

impl MyOwnedContract for Contract {
fn receive(field_1: u64) -> bool {
let sender: Result<Identity, AuthError> = msg_sender();
if let Identity::Address(addr) = sender.unwrap() {
assert(addr.into() == OWNER);
assert(addr == OWNER);
} else {
revert(0);
}
Expand Down
8 changes: 2 additions & 6 deletions examples/ref_mut_params/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,8 @@ fn main() {
let mut color = Color::Red;
update_color(color, Color::Blue);
assert(match color {
Color::Blue => {
true
}
_ => {
false
}
Color::Blue => true,
_ => false,
}); // The function `update_color()` modifies the color to Blue
// ANCHOR_END: call_tuple_and_enum
// ANCHOR: call_move_right
Expand Down
1 change: 1 addition & 0 deletions examples/storage_example/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::storage::{get, store};
abi StorageExample {
#[storage(write)]
fn store_something(amount: u64);

#[storage(read)]
fn get_something() -> u64;
}
Expand Down
19 changes: 10 additions & 9 deletions examples/storage_map/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,24 @@ impl StorageMapExample for Contract {
// ANCHOR: storage_map_insert
#[storage(write)]
fn insert_into_storage_map() {
let addr1 = 0x0101010101010101010101010101010101010101010101010101010101010101;
let addr2 = 0x0202020202020202020202020202020202020202020202020202020202020202;
let addr1 = ~Address::from(0x0101010101010101010101010101010101010101010101010101010101010101);
let addr2 = ~Address::from(0x0202020202020202020202020202020202020202020202020202020202020202);

storage.map.insert(~Address::from(addr1), 42);
storage.map.insert(~Address::from(addr2), 77);
storage.map.insert(addr1, 42);
storage.map.insert(addr2, 77);
}
// ANCHOR_END: storage_map_insert

// ANCHOR: storage_map_get
#[storage(read, write)]
fn get_from_storage_map() {
let addr1 = 0x0101010101010101010101010101010101010101010101010101010101010101;
let addr2 = 0x0202020202020202020202020202020202020202020202020202020202020202;
let addr1 = ~Address::from(0x0101010101010101010101010101010101010101010101010101010101010101);
let addr2 = ~Address::from(0x0202020202020202020202020202020202020202020202020202020202020202);

storage.map.insert(~Address::from(addr1), 42);
storage.map.insert(~Address::from(addr2), 77);
storage.map.insert(addr1, 42);
storage.map.insert(addr2, 77);

let value1 = storage.map.get(~Address::from(addr1));
let value1 = storage.map.get(addr1);
}
// ANCHOR_END: storage_map_get
}
3 changes: 3 additions & 0 deletions examples/storage_variables/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ storage {
z: false,
},
}

// ANCHOR_END: storage_declaration
abi StorageExample {
#[storage(write)]
fn store_something();

#[storage(read)]
fn get_something() -> (u64, u64, b256, bool);
}
Expand All @@ -36,6 +38,7 @@ impl StorageExample for Contract {
storage.var2.z = true;
}
// ANCHOR_END: storage_write

// ANCHOR: storage_read
#[storage(read)]
fn get_something() -> (u64, u64, b256, bool) {
Expand Down
Loading

0 comments on commit 734ed89

Please sign in to comment.