Fuel Dev Rel
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully