# Sway vs. Solidity ###### tags: `Writing` This guide is meant for developers who are somewhat familiar with Solidity and interested in learning Sway. It compares one-to-one examples of the syntax and common methdods used in Solidity and Sway contracts. You don't need to be a pro Solidity developer, but you should have some understanding of programming and blockchain basics. ## Hello World We can start with a "Hello World" example. Here is what this looks like in Solidity: **Solidity:** Contracts in Solidity always start with two things: 1. At the top of the file is a comment for the SDPX-License-Identifier for the contract. 2. Next, `pragma solidity` is used to define the compiler version number. To define a contract, you use the `contract` keyword followed by its name. Variables defined within a contract but outside of a contract function are stored in persistent storage. The `public` keyword tells the compiler to generate a getter function to read the value of `greeting`. String lengths are dynamic by default. **Sway:** All smart contracts in Sway start with the `contract` keyword. Because Sway also allows for scripts, libraries, and predicates, the first line is dedicated to specifying the file type. Next, in Sway you must also include an ABI, or application binary interface. This is simply a layout of all of the functions in the contract, including their input, return types, and special permissions (more about this later). The storage block is used to store any variables that should be persistently stored. A getter function to read the value storage variables must be explicity included, as they are not automatically generated. Strings must be a fixed length. | Sway | Solidity | | -------- | -------- | | Starts with `contract` | Starts with license and version number | | Must define the contract ABI. | Don't have to write an ABI. | | Variables in the storage block are persistent.| Variables outside of functions are persistent. | | Strings have a fixed length. | Strings have a dynamic length. | | Getter functions for state variables must be explicity included. | Getter functions are generated for public state variables. | > Note: The Solidity license and version number and the Sway `contract` keyword and ABI won't be included in the following examples to avoid repetition. ## Counter Contract Next we can look at a simple counter contract. This stores a variable called `counter` in persistent storage, and has two functions: `count` which reads the value of `counter`, and `increment` which adds 1 to the current value of the counter. **Solidity:** The most common number type used in Solidity is a `uint`, which is an alias for `uint256`, an unsigned integer that uses 256 bits. The `count` function uses the `view` keyword to denote read-only access to persistently-stored variables. Functions use the format `returns (<type>)` to define the return type of a function. Return variables can be optionally named. Inside a function, you use the `return <variable>;` format to return something. To read and return the value of `counter`, you simply need to use the `counter` variable name. State variables are available in all functions. In the `increment` function, you can directly update the value of `counter` by reassigning it. **Sway:** Functions use a skinny arrow `-> <type>` format to define its return type. Sway does not have named return types. Access to storage is denoted with `#[storage(read)]` for functions that read from storage, `#[storage(write)]` for functions that write to storage, and `#[storage(read, write)]` for functions that both read from and write to storage. Storage variables are accessed through the `storage` object, which helps prevent naming conflicts and more clearly shows when storage is being read or updated. To update a storage value, you can simply reassign it. | Sway | Solidity | | -------- | -------- | | State variables are accessed through the `storage` object | State variables are accessed directly | | Access to storage is specified with `#[storage(read)]`, `#[storage(write)]`, or `#[storage(read, write)]` | Access to storage is read & write by default. The `view` keyword indicates read-only. | | Functions use a skinny arrow `-> <type>` format for the return type | Functions use `returns (<type>)` format for the return type | | Function return types cannot be named | Function return types can optionally be named | | Functions use either `<variable>` or `return <varaible>;` format to return something | Functions use `return <varaible>;` format to return something | ## Events / Logging Solidity allows for custom events to be emitted, which, for example, can be organized by indexer to be easily queryable without having to use persistent storage in a contract. This example logs the number `42` and the string `Hello World!` whenever someone calls the `logger` function. **Solidity:** The `event` keyword is used to define and name a type of log. The event here is named `Log`. Within parentheses, the names and types of the log values are defined. Inside a function, you can use the `emit` keyword to create a log instance. The number `42` and the string `Hello World!` are used ad the values for `num` and `messge` respectively. **Sway:** The closest equivalent to emitting a Solidity `event` in Sway is the `log` method from the Sway standard library. The standard library is built-in to Sway, so you just need to import the method by using the `use` keyword. Logs cannot be named, and only one value can be logged at a time. | Sway | Solidity | | -------- | -------- | | Import the `log` method from the std-lib and call it to create a log instance | Define an `event` and use the `emit` keyword to create a log instance | | Log values are unnamed | Log values are named | | Can log one value at a time | Can log multiple values at a time | ## Persistent Storage Next, we can take a look at persistent storage, also known as state variables. This contract stores five types of state variables: a number, a string, a boolean, a map, and an array. It will also have functions to read and update their values. **Solidity:** In solidity all variables that are directly within the contract scope (i.e. not defined within a contract function) are persistently stored. They are defined using the `<type> <public|private> <name>` format. They can either be initialized to a certain value like `uint public number = 0;` or initialized to a default zero value like `uint public number;`. The `public` keyword generates a getter function for that variable, while the `private` keyword prevents the getter function from being generated. To define a map, you use the `mapping` keyword and the `mapping(<key> => <value>) <public|private> <name>` format. To define an. array, you use the `<type>[] <public|private> <name>` format. Array sizes are dynamic by default. Functions have read-write permissions by default. If a function reads from a state variable but does not change it, you can use the `view` keyword. If it does not read from or write to any state variable, you can use the `pure` keyword. To get a value for a certain key, you can use the `<mapName>[<key>]` format. You can use the same format to get the value of an array at a given index, `<arrayName>[<index>]`. You can update a map value for a certain key by reassinging it using the`<mapName>[<key>] = <value>;` format. To add a value to an array, you can use the `push` method. **Sway:** In Sway all variables that are in the storage block are persistently stored. They are defined using the `<name>: <type>` format. Storage variables must be initalized to a certain value. In Sway there are no equivalent `public` or `private` variables. All storage variables are private by default, and the getter functions to read the values must be written. Functions are pure by default. If a function reads or writes from a state variable you can use the `#[storage(read)]`, `#[storage(write)]`, or`#[storage(read, write)]` annotations. To define a map, you can use the `storageMap` a special type from the standard library that can only be used in a storage block. This type is already available without having to import it. In Sway (and Rust), a dynamic array is called a vector. A`storageVec` is another special storage block type from the standard library that is used to persistently store vectors. However, this type must be explicity imported. To get a value for a certain key, you can use the `get` method on the `storageMap`. You can also use a`get` method on the `storageVec` to get the value at a certain index in a storage vector. You can add or update a storage map value for a certain key by using the`insert` method. To update a storage vector, you can use the `push` method. | Sway | Solidity | | -------- | -------- | | Storage block holds all persistently stored variables | Persistent variables can be decalared anywhere outside a function | | Storage variables are "private" by default. Getter functions must be written | Uses `public` and `private` keywords to decide to generate getter functions | | Uses `storageMap` type to store a map | Uses `mapping` type to store a map | | Uses an array to store a dynamic array | Uses `storageVec` type to store a dynamic array | | Uses an array to store a dynamic array | Uses `storageVec` type to store a dynamic array | ## Conditionals This contract just includes some simple conditional logic. If-statements are almost identity in Sway and Solidity. The main stynax difference is that conditionas are not wrapped in parentheses in Sway. Sway also offers `match` statements. The match statement here is equivalent to "if x equals 0, return 1. For all other cases, return 2". ## Structs (ToDo Contract) This contract uses structs, or structures, in a simple Todo contract. The contract has a Todo struct, a persistent array of Todos, and functons to create a new Todo, get the value of one, and update an existing one. **Solidity:** **Sway:** You can update a struct either with an associated function, like `update_text` here, or be setting the field directly like `todo.completed = true`. You must use the `mut` keyword to update an instance of a struct. ## Throwing Errors **Solidity:** assert(bool condition): abort execution and revert state changes if condition is false (use for internal error) require(bool condition): abort execution and revert state changes if condition is false (use for malformed input or error in external component) require(bool condition, string memory message): abort execution and revert state changes if condition is false (use for malformed input or error in external component). Also provide error message. revert(): abort execution and revert state changes revert(string memory message): abort execution and revert state changes providing an explanatory string **Sway:** `assert`, a function that reverts the VM if the condition provided to it is false. `require`, a function that reverts the VM and logs a given value if the condition provided to it is false. `revert`, a function that reverts the VM. Panics in the FuelVM (called "reverts" in Solidity and the EVM) are global, i.e. they cannot be caught. A panic will completely and unconditionally revert the stateful effects of a transaction, minus gas used. ## Internal Functions **Solidity:** Public external internal keywords to denote if function can be externally called **Sway:** In Sway, all functions listed in the ABI are external. The only functions that can be used internally in the contract are functions defined outside of the ABI. ## Amounts **Solidity:** Solidity only has one base asset: ether. Ether can be divided into sub-units, with the smallest unit being wei. One ether is equal to 10<sup>18</sup> wei. Gwei is another common sub-unit of ether. One ether is equal to 10<sup>9</sup> (one billion) gwei. **Sway:** Sway contracts can be deployed to different blockchains with difference configurations. So the base asset is not locked into only one asset: it depends on the deployment context of the contract. The Sway Standard Library provides a variable for the Base Asset which is defined based on this deployment context. In Sway, Gwei is the smallet unit of Ether available, because the FuelVM uses 64-bits (while the EVM uses 256-bits). ## Message Info & Payable Functions **Solidity:** **Sway:** With Sway, there is a third method here to get the asset ID of the asset sent, because any asset can be sent in a transaction natively. ## Gas Price **Solidity:** **Sway:** ## Contract Info **Solidity:** **Sway:** ## Block Info **Solidity:** **Sway:** ## Transfering Assets **Solidity:** There are a few different ways you can transfer ether in Solidity: transfer (2300 gas, throws error) send (2300 gas, returns bool) call (forward all gas or set gas, returns bool) **Sway:** In Sway, you can choose to allow transfers to EOAs, contracts, or both. There are no methods transfer in Sway that are not recommended. **Sway:** There are no fallback or receive functions required for a Sway contract to be able to receive an asset. ## Minting Tokens **Solidity:** **Sway:** Fuel allows for native assets. You can create a ledger-based token ([example](https://fuellabs.github.io/sway/master/book/examples/subcurrency.html)), however it is not recommended. Token example: https://github.com/FuelLabs/sway/blob/master/examples/native_token/src/main.sw ## Hashing **Solidity:** Solidity provides hashing methods like `abi.encode` and `abi.encodePacked`. These methods are commonly used to reduce the cost of gas by reducing memory usage. **Sway:** The Sway Standard Library provides keccak256 and sha256 hashing functions. These functions return a `b256` type, which is a pointer to a 32-byte memory region containing the hash value. There is no Sway version of `abi.encode` or`abi.encodePacked` as it is generally not needed. The main reason to use this is to save memory, and is really a work around for the inefficiencies of Solidity & the EVM. ## EC Recover EC standands for elliptic curve cryptography, which is used in the creation of public/private key pairs. The EC recover method allows you to verify the public key that signed a given message. **Solidity:** **Sway:** ## Re-entrancy Guards **Solidity:** **Sway:** Transient storage is when data can persist across contract calls within a single transaction. It's a piece of memory that can be accessed from different contract calls in the same transaction. In the FuelVM, all contract call frames share the same memory, which allows for the FVM to do a re-entrancy guard check without using a storage slot. ## Major Differences There is no Sway equivalent of - constructor functions - fallback or receive functions - contract inheritance - modifiers - factory contracts But there are several workarounds for these. ## Start Building with Sway Ready to keep building? You can dive deeper into Sway and Fuel in the resources below: 🛝 [Try out the Sway Playground](https://sway-playground.org/) 🏃‍ [Follow the Fuel Quickstart](https://fuellabs.github.io/fuel-docs/master/developer-quickstart.html) 📘 [Read the Sway Book](https://fuellabs.github.io/sway) 📖 [See Example Sway Applications](https://github.com/FuelLabs/sway-applications) 🦀 [Write tests with the Rust SDK](https://fuellabs.github.io/fuels-rs/) ✨ [Build a frontend with the TypeScript SDK](https://fuellabs.github.io/fuels-ts/) 🔧 [Learn how to use Fuelup](https://fuellabs.github.io/fuelup/latest) ⚡️ [Learn about Fuel](https://fuellabs.github.io/fuel-docs/master/) 🐦 [Follow Sway Language on Twitter](https://twitter.com/SwayLang) 👾 [Join the Fuel Discord](http://discord.com/invite/xfpK4Pe)