The Fuel Book
The Fuel Book
Fuel is the fastest modular execution layer, delivering maximum security and highest flexible
throughput.
Alpha
Follow Fuel Labs on Twitter for all the alpha.
Follow Sway, our Rust-based DSL and start writing smart contracts on Fuel.
Join the Fuel discord where you can ask questions, build with others, and hear about
developments first.
Check out this page to learn about upcoming events, read articles, listen to podcasts, and view
presentations on Fuel.
Apply for a grant to build on Fuel.
Fuel in the wild
Learn
Getting Started
Why Fuel?
What is Fuel?
Fuel toolchain
The Modular Movement
Monolithic Blockchains
Fuel Configurations
Fuel as a rollup
Fuel as an L1
Fuel as a state channel
Fuel as a side chain
Technology
Parallel Transaction Execution
Fraud Proofs
The FuelVM
Contract and Call Model
Memory Model
Multiple Native Assets
VS EVM
The Sway Language
Design Philosophy
Safety
Build
Developer Quickstart
For Developers
Node
Sway Language
Typescript SDK
Rust SDK
Indexer
Coming Soon
Modular Blockchains
Modular Blockchain Stack
What is a Modular Execution Layer
The FuelVM
VS Move
VS Solana
Glossary
Developer Quickstart
This guide will walk developers through writing a smart contract in Sway, a simple test, deploying to
Fuel, and building a frontend.
Before we begin, it may be helpful to understand the terminology that will be used throughout the
docs and how they relate to each other:
contract
predicate
script
library
Contracts, predicates, and scripts can produce artifacts usable on the blockchain, while a library is
simply a project designed for code reuse and is not directly deployable.
The main features of a smart contract that differentiate it from scripts or predicates are that it is
callable and stateful.
A script is runnable bytecode on the chain which can call contracts to perform some task. It does not
represent ownership of any resources and it cannot be called by a contract.
deployable on the can have callable on the designed for
blockchain: state: blockchain: code reuse:
contract ✅ ✅ ✅ ❌
predicate ✅ ❌ ❌ ❌
script ❌ ❌ ❌ ❌
✅ (via a contract
library ❌ ❌ ✅
or predicate)
Installation
Start by installing the Rust toolchain.
Make sure you have the latest version of fuelup by running the following command:
Then run fuelup toolchain install beta-2 to install the beta-2 toolchain.
Finally, set the beta-2 toolchain as your default distribution with the following command:
$ fuelup default beta-2
default toolchain set to 'beta-2-aarch64-apple-darwin'
You can check your current toolchain anytime by running fuelup show .
Having problems with this part? Post your question on our forum https://forum.fuel.network/.
To help you as efficiently as possible, include the output of this command in your post: fuelup
show.
Then with forc installed, create a contract project inside of your fuel-project folder:
$ cd fuel-project
$ forc new counter-contract
To compile, use `forc build`, and to run tests use `forc test`
----
Report Bugs:
- Sway Issues: https://github.com/FuelLabs/sway/issues/new
$ tree counter-contract
counter-contract
├── Forc.toml
└── src
└── main.sw
Forc.toml is the manifest file (similar to Cargo.toml for Cargo or package.json for Node) and
defines project metadata such as the project name and dependencies.
Open your project in a code editor and delete the boilerplate code in src/main.sw so that you start
with an empty file.
Every Sway file must start with a declaration of what type of program the file contains; here, we've
declared that this file is a contract.
contract;
Next, we'll define a storage value. In our case, we have a single counter that we'll call counter of
type 64-bit unsigned integer and initialize it to 0.
storage {
counter: u64 = 0,
}
ABI
An ABI defines an interface, and there is no function body in the ABI. A contract must either define
or import an ABI declaration and implement it. It is considered best practice to define your ABI in a
separate library and import it into your contract because this allows callers of the contract to import
and use the ABI in scripts to call your contract.
For simplicity, we will define the ABI directly in the contract file.
abi Counter {
#[storage(read, write)]
fn increment();
#[storage(read)]
fn count() -> u64;
}
#[storage(read, write)] is an annotation which denotes that this function has permission to read
and write values in storage.
fn increment(); - We're introducing the functionality to increment and denoting it shouldn't return
any value.
#[storage(read)] is an annotation which denotes that this function has permission to read values
in storage.
fn counter() -> u64; - We're introducing the functionality to increment the counter and denoting
the function's return value.
Implement ABI
Below your ABI definition, you will write the implementation of the functions defined in your ABI.
#[storage(read, write)]
fn increment() {
storage.counter = storage.counter + 1;
}
}
In fn increment() , we read the variable counter from storage and increment its value by one. We
then store the new value back in counter .
fn increment() {
storage.counter = storage.counter + 1;
}
contract;
storage {
counter: u64 = 0,
}
abi Counter {
#[storage(read, write)]
fn increment();
#[storage(read)]
fn count() -> u64;
}
#[storage(read, write)]
fn increment() {
storage.counter = storage.counter + 1;
}
}
From inside the fuel-project/counter-contract directory, run the following command to build
your contract:
$ forc build
Compiled library "core".
Compiled library "std".
Compiled contract "counter-contract".
Bytecode size is 232 bytes.
Let's have a look at the content of the counter-contract folder after building:
$ tree .
.
├── Forc.lock
├── Forc.toml
├── out
│ └── debug
│ ├── counter-contract-abi.json
│ ├── counter-contract-contract-id
│ ├── counter-contract-storage_slots.json
│ └── counter-contract.bin
└── src
└── main.sw
We now have an out directory that contains our build artifacts such as the JSON representation of
our ABI and the contract bytecode.
$ cd counter-contract
changed directory into `counter-countract`
$ cargo install cargo-generate
Updating crates.io index...
installed package `cargo-generate v0.17.3`
Note: You can learn more about cargo generate by visiting its repository.
Now, let's generate the default test harness with the following:
$ tree .
.
├── Cargo.toml
├── Forc.lock
├── Forc.toml
├── out
│ └── debug
│ ├── counter-contract-abi.json
│ ├── counter-contract-contract-id
│ ├── counter-contract-storage_slots.json
│ └── counter-contract.bin
├── src
│ └── main.sw
└── tests
└── harness.rs
The Cargo.toml is the manifest for our new test harness and specifies the required
dependencies including fuels the Fuel Rust SDK.
The tests/harness.rs contains some boilerplate test code to get us started, though doesn't
call any contract methods just yet.
Now that we have our default test harness, let's add some useful tests to it.
At the bottom of test/harness.rs , define the body of can_get_contract_id() . Here is what your
code should look like to verify that the value of the counter did get incremented:
File: tests/harness.rs
#[tokio::test]
async fn can_get_contract_id() {
let (instance, _id) = get_contract_instance().await;
Run cargo test in the terminal. If all goes well, the output should look as follows:
$ cargo test
...
running 1 test
test can_get_contract_id ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished
in 0.11s
In order to deploy a contract, you need to have a wallet to sign the transaction and coins to pay for
gas. First, we'll create a wallet.
Install the Wallet CLI
After typing in a password, be sure to save the mnemonic phrase that is output.
With this, you'll get a fuel address that looks something like this:
fuel1efz7lf36w9da9jekqzyuzqsfrqrlzwtt3j3clvemm6eru8fe9nvqj5kar8 . Save this address as you'll
need it to sign transactions when we deploy the contract.
With your account address in hand, head to the testnet faucet to get some coins sent to your wallet.
Deploy To Testnet
Now that you have a wallet, you can deploy with forc deploy and passing in the testnet endpoint
like this:
Note: We set the gas price to 1. Without this flag, the gas price is 0 by default and the
transaction will fail.
The terminal will ask for the address of the wallet you want to sign this transaction with, paste in the
address you saved earlier, it looks like this:
fuel1efz7lf36w9da9jekqzyuzqsfrqrlzwtt3j3clvemm6eru8fe9nvqj5kar8
The terminal will output a message to sign and prompt you for a signature. Open a new terminal
tab and view your accounts by running forc wallet list . If you followed these steps, you'll notice
you only have one account, 0 .
Grab the message to sign from your other terminal and sign with your account by running the
following command:
forc wallet sign` + `[message to sign, without brackets]` + `[the account number,
without brackets]`
Enter your password when prompted, and you'll get back a signature . Save that signature, and
return to your other terminal window, and paste that in where its prompting you to provide a
signature for this transaction .
Finally, you will get back a TransactionId to confirm your contract was deployed. With this ID, you
can head to the block explorer and view your contract.
Note You should prefix your TransactionId with 0x to view it in the block explorer
Create a Frontend to Interact with Contract
Now we are going to
To split better our project let's create a new folder frontend and initialize our project inside it.
In the terminal, go back up one directory and initialize a react project using Create React App .
$ cd ..
$ npx create-react-app frontend --template typescript
Success! Created frontend at Fuel/fuel-project/frontend
You should now have your outer folder, fuel-project , with two folders inside: counter-contract
and frontend
Install the fuels SDK dependencies
1. fuels : The umbrella package that includes all the main tools; Wallet , Contracts , Providers
and more.
2. fuelchain : Fuelchain is the ABI TypeScript generator.
3. typechain-target-fuels : The Fuelchain Target is the specific interpreter for the ABI spec.
ABI stands for Application Binary Interface. ABI's inform the application the interface to interact
with the VM, in other words, they provide info to the APP such as what methods a contract has,
what params, types it expects, etc...
Install
$ cd frontend
$ npm install [email protected] --save
added 65 packages, and audited 1493 packages in 4s
$ npm install [email protected] [email protected] --save-dev
added 33 packages, and audited 1526 packages in 2s
To make it easier to interact with our contract we use fuelchain to interpret the output ABI JSON
from our contract. This JSON was created on the moment we executed the forc build to compile
our Sway Contract into binary.
If you see the folder fuel-project/counter-contract/out you will be able to see the ABI JSON
there. If you want to learn more, read the ABI spec.
Now you should be able to find a new folder fuel-project/frontend/src/contracts . This folder
was auto-generated by our fuelchain command, this files abstract the work we would need to do
to create a contract instance, and generate a complete TypeScript interface to the Contract, making
easy to develop.
For interacting with the fuel network we have to submit signed transactions with enough funds to
cover network fees. The Fuel TS SDK don't currently support Wallet integrations, requiring us to have
a non-safe wallet inside the WebApp using a privateKey.
Note: This should be done only for development purpose. Never expose a web app with a
private key inside. The Fuel Wallet is in active development, follow the progress here.
In the root of the frontend project create a file named createWallet.js and add the following code:
File: ./frontend/createWallet.js
console.log("address", wallet.address.toString());
console.log("private key", wallet.privateKey);
Note: You should use the generated address and private key.
Save the private key, you will need this later to set it as a string value for a variable WALLET_SECRET
in your App.tsx file. More on that below.
First, take the address of your wallet and use it to get some coins from the testnet faucet.
Note: The team is working to simplify the process of creating a wallet, and eliminate the need
to create a wallet twice. Keep an eye out for these updates.
Inside the frontend/src folder let's add code that interacts with our contract. Read the comments
to help you understand the App parts. Change the file fuel-project/frontend/src/App.tsx to:
File: ./frontend/src/App.tsx
import React, { useEffect, useState } from "react";
import { Wallet } from "fuels";
import "./App.css";
// Import the contract factory -- you can find the name in index.ts.
// You can also do command + space and the compiler will suggest the correct name.
import { CounterContractAbi__factory } from "./contracts";
function App() {
const [counter, setCounter] = useState(0);
const [loading, setLoading] = useState(false);
useEffect(() => {
async function main() {
// Executes the counter function to query the current contract state
// the `.get()` is read-only, because of this it don't expand coins.
const { value } = await contract.functions.count().get();
setCounter(Number(value));
}
main();
}, []);
return (
<div className="App">
<header className="App-header">
<p>Counter: {counter}</p>
<button disabled={loading} onClick={increment}>
{loading ? "Incrementing..." : "Increment"}
</button>
</header>
</div>
);
}
export default App;
Now it's time to have fun, run the project in your browser.
Local: http://localhost:3001
On Your Network: http://192.168.4.48:3001
Here is the repo for this project. If you run into any problems, a good first step is to compare your
code to this repo and resolve any differences.
Tweet us @fuellabs_ letting us know you just built a dapp on Fuel, you might get invited to a private
group of builders, be invited to the next Fuel dinner, get alpha on the project, or something 👀.
If you make changes to your contract, here are the steps you should take to get your frontend and
contract back in sync:
Need Help?
Get help from the team by posting your question in the Fuel Forum.
Getting Started
Why Fuel?
What is Fuel?
Fuel Toolchain
Why Fuel
Fuel’s optimization for fraud proofs is the use of the UTXO model, which in turn means Fuel has no
global state tree or account trees. If you wanted to apply the general construction of a fraud proof to
a chain that uses the account model like Ethereum, the cost could be unbound, making it extremely
expensive to produce a fraud proof. In this general construction of a fraud proof, given a pre-state
and a state transition, you locally execute the transition and compare the output to the post-state
produced by the block producer. If these differ, the post-state by the block producer was invalid. If
you apply this general fraud proof model to Ethereum today, someone could create a transaction
that calls many different contracts, and those contracts could each have up to 24kb of bytecode. In
order to locally re-execute, you need to provide all the bytecode for all the contracts that were
interacted with.
Unlike EVM which was designed without a language from the start, the FuelVM is built alongside its
companion language, Sway, ensuring it has handy and efficient ops, such as getting specific parts of
a tx. Sway is a Rust-based DSL created specifically to leverage a blockchain VM without needlessly
verbose boilerplate. Sway leverages Rust’s safety and catches errors and bugs at compile-time,
giving developers peace of mind. Read more about Sway here.
Fuel Labs has also developed the Fuel Toolchain: the full stack of tools for enabling/assisting the Fuel
application development experience. Read more about the Fuel Toolchain here.
Parallel Execution
Fuel brings scale to Ethereum without sacrificing decentralization.The FuelVM is designed to reduce
wasteful processing of traditional blockchain virtual machine architectures, while vastly increasing
the potential design space for developers. The FuelVM can use all the threads and cores of your CPU
to validate transactions.
Fuel Configurations
As a Modular Execution Layer, Fuel can function in any one of these categories. Developers can
configure Fuel as-needed by switching out a few modules in the client.
Improved VM
The Ethereum community has suggested many implementation improvements to improve EVM
performance. Unfortunately, many of these improvement proposals haven’t been implemented
because they would break backward compatibility.
Execution layers built on Ethereum give us a new opportunity to build something better. Designs
don’t need to be backward compatible and in fact, can do whatever is necessary to deliver global
throughput and adoption for Ethereum. The FuelVM is the EVM greatly improved. Check out this
non-exhaustive list of EIPs (Ethereum Improvement Proposals) implemented in the FuelVM here.
The FuelVM and EVM have a lot of overlap. Here's how they're different, view a
more complete list at FuelVM vs. EVM
The FuelVM has a globally shared memory architecture instead of context-local memory
The FuelVM has a globally shared memory architecture. Instead of every contract call having its own
separate memory space, call data, and return data, all contract call frames share global memory.
This chunk of memory is shared amongst all call frames and is globally readable. This allows you to
pass data around between contracts without expensive storage and pass chunks of data without
having to serialize, copy from call data to memory, etc. Read more about the FuelVM memory model
here.
The EVM is a complicated machine to construct fraud proofs for. It usually requires a second layer
such as WASM or MIPS to be interpreted into a fraud provable system. Check out User Sovereignty
with Fraud Proofs and how fraud proofs unlock key functionality.
In Ethereum, the only native asset is Ether. It’s the only one that gets first-class treatment in terms of
cost and ability to be pushed and pulled through a call. In Fuel, any contract can mint its UTXO-based
native asset using a set of easy asset opcodes. All of which can gain the benefits of native-level call
and optimization. Read more about support for multiple native assets in the Sway docs, and here.
Today, Fuel is the fastest modular execution layer. Fuel delivers the highest security and flexible
throughput, with a focus on a superior developer experience.
With the EVM, it is difficult to know if, and where there are dependencies between transactions, so
you are forced to execute transactions sequentially.
The FuelVM uses the UTXO model, enabling parallel transaction execution by identifying transaction
dependencies through what is known as state access lists. With the FuelVM, Fuel full nodes identify
the accounts that a transaction touches, mapping out dependencies before execution.
FuelVM
The FuelVM learns from the Ethereum ecosystem, implementing improvements that were suggested
to the Ethereum VM (EVM) for many years but couldn’t be implemented due to the need to maintain
backward compatibility.
Here are some EIP that have been implemented in the FuelVM:
Sway was created alongside the FuelVM and designed for the high-compute Fuel environment.
Check out the Sway docs here.
Developer Tooling
Fuel Labs is developing a suite of developer tooling to create a seamless developer experience. By
creating everything in-house, Fuel Labs guarantees the maintenance of the toolchain, avoiding the
pitfalls of a fragmented developer ecosystem.
Fuel provides a powerful and sleek developer experience with our own domain-specific language,
called Sway, and a supportive toolchain, called Forc (the Fuel Orchestrator). Our development
environment retains the benefits of smart contract languages like Solidity, while adopting the
paradigms introduced in the Rust tooling ecosystem. Now, developers can have a completely
vertically-integrated experience where every component from the virtual machine through to the CLI
works in harmony.
The Fuel Toolchain: Forc: build, run tests, launch a local instance of a block explorer, format.
Coming Soon: A suite of auditing facilities, from fuzzing and formal verification to code coverage
and runtime gating.
The Fuel Toolchain
The full stack of tools designed and built by Fuel Labs for enabling/assisting the Fuel application
development experience.
Tooling Overview:
For more specific documentation on the toolchain, check out the Sway docs here.
Building on Fuel
Developers can get everything they need to start creating Sway applications for the Fuel VM with a
single toolchain, blessed by the same teams that create the FuelVM and Sway language.
One common issue developers face when working within the Ethereum ecosystem is how to choose
a set of tools to get started. Historically, Ethereum's founders have been particularly focused on the
low-level details of the protocol, the EVM and to a lesser extent Solidity, leaving the job of creating
accessible, high-level tooling to the community. As a result, many disparate projects have appeared
from different 3rd parties that aim to provide these high-level solutions such as truffle, dapptools,
hard hat, foundry and many more. It can be difficult for new Ethereum developers to navigate this
space and to feel comfortable knowing they're making the right choice in selecting one of these
toolchains.
To clarify, the goal is not at all to discourage 3rd parties from extending the fuel ecosystem. Rather,
we aim to make the official tool-chain so good as to inspire contributions upstream and to
collaborate under one unified developer ecosystem. For those cases where our tooling falls short
and additions or extensions are required, we provide an extensible plugin system through forc ,
enabling community creativity in a manner that is easily-shareable and familiar to fellow Fuel devs.
The Sway VS Code plugin is a great example of our vision for a unified developer experience. The
plugin interacts with the Sway language server, a forc plugin that communicates directly with the
Sway compiler and shares much of its code-base. The plugin also allows for spinning up a Fuel node,
displaying its status in real-time and (in the near future) interact with your smart contracts via the
TypeScript SDK. A complete solution from entirely within the plugin, from one team with a shared
vision.
You can start experimenting with the Fuel toolchain by following the Fuelup Quickstart Guide.
Modular Movement
Although L2s have opened up a margin of cost reduction for access to the Ethereum ecosystem, the
total throughput increase has been modest at best (with both optimistic and ZK approaches). And in
times of high traffic on Ethereum, L2s have failed to keep costs low, often rising to several dollars
per transaction.
As a community, if we want to achieve true global access to blockchain technology, we cannot settle
for a modest reduction in fees. We need dramatic change. Change that not only reduces waste and
inefficiency but opens up new use cases never before seen in the blockchain space.
There is an ongoing colossal shift happening in layer-1 (L1) blockchain architectures. We are moving
away from a monolithic design, where consensus, data availability, and execution are tightly coupled
(e.g. today's Ethereum), to a modular future, where execution is separated from data availability and
consensus (e.g. tomorrow's Eth2, or Celestia). This separation allows for specialization at the base
layer, delivering a significant increase in bandwidth capacity.
Why Modular?
A modular blockchain architecture does not inherently enable scaling. The properties that are
derived as a result are what make this possible. Fuel was built for fraud proofs, enabling trust-
minimized light clients, enabling high security without requiring high resource usage.
Security vs. Resource Requirements
In a monolithic architecture, users must choose between high security and high computational
resource usage and trusted security and low computational resource usage. For example, Ethereum
was designed to allow consumer-grade hardware to be able to run a full node, a type of node that
offers maximum security by downloading and verifying every single transaction. By running a full
node, users don’t have to trust that the chain is valid and can instead verify themselves. However,
running a full node requires a lot of disk space and non-negligible CPU allocation and can take days
to sync the blockchain from genesis.
Alternatively, a user can run a light client, also known as an honest majority light client. Instead of
downloading all blocks to verify transactions, light clients only download block headers and check
their proof-of-work (PoW), assuming the heaviest chain is valid. Honest majority light-clients that
trust that a majority of validators are honest and will reject fraudulent transactions.
The amount of computational resources and storage needed to run a light client is lower than a full
node by several orders of magnitude.
An easy way to remember the difference: An honest majority light client is only secure if most
validators are honest. A full node is honest even if all validators are not honest.
By running a full node, you get the maximum security of verifying transactions but also have to
spend a lot of computational resources to achieve this. Because a light client doesn’t need to run
24/7 and doesn’t interact directly with the chain, the computational requirement is much lower, but
you also get low security.
Trust-Minimized Light Clients
Fuel’s design lets light clients say that blocks are valid through fraud proofs. This eliminates the need
for a trusted party while maintaining low resource requirements and achieving high security. For
monolithic chains like Ethereum, there is an ideological incentive to keep the computation
requirements for full nodes low to allow users to be truly sovereign.
Because Fuel was built for fraud proofs, the resource requirements for full nodes can be higher, thus
increasing bandwidth capacity while still allowing users to verify the chain through trust-minimized
light clients.
Monolithic Architecture
Blockchains as we know them have four functions. In no particular order:
Monolithic blockchains are a type of blockchain architecture that handle all four functions, at the
same time, on this single layer.
Challenges with Monolithic
Some constraints and challenges with a monolithic architecture:
Costly and inefficient transaction verification
In order to verify the validity of transactions in the chain, full nodes must download the entire chain
and execute each transaction locally.
Resource constraints
The blockchain is bound by the resource capacity of its nodes. Throughput is constrained by the
resource requirements of a single node since the blockchain is replicated, not distributed, across
nodes.
Shared resources
In a monolithic architecture, the four functions of the chain operate on the same finite set of
compute resources. For example, using a node's capacity for execution means that there's less
capacity left over for data availability.
Scalability
With a modular execution layer, users can run an off-chain light client, allowing users to
validate the chain without running a full node.
A modular execution layer is not tightly coupled to a specific layer 1, allowing for greater
flexibility.
Light Clients
One of the core characteristics of a modular execution layer is related to the trust model of the
system. A modular execution layer has all the properties of a rollup, and the ability to run a light
client. This allows you to have trust-minimized infrastructure. Read more about light clients here.
Flexibility
Another core property of a modular execution layer is that it is not tightly coupled to a specific layer
1. This offers flexibility that allows Fuel to be deployed. Read more about Fuel's flexibility here.
Fuel Configurations
Fuel is a modular architecture and is designed to operate in multiple different configurations.
Fuel Configurations
Defining Rollups
A layer-2 is a term used to describe a set of scaling solutions. A rollup is an off-chain network built on
top of the layer-1 that executes transactions off-chain, bundles these transactions, and posts the
bundled transactions as a single transaction on the layer-1 chain.
Check out this resource to learn more about rollups and layer-2s.
Layer-2s and rollups are primarily designed for monolithic blockchain stacks, which means they are
typically not optimized for large amounts of layer-1 bandwidth potential unlike Fuel, which is
uniquely configured to handle this potential.
Fuel Configurations
Defining a Layer-1
A layer-1 is a blockchain network responsible for handling all functions of a chain including
settlement, execution, data availability, and consensus. This has been colloquially named a layer-1
because rollups, or layer-2s, sit on top of these chains.
Fuel as a Layer-1
The Fuel technology includes all the components to run as a complete layer-1 solution. These
components include consensus, data availability, settlement, and transaction execution. The
common configurations for running in this mode would be proof of authority and a proof of stake
via a Tendermint-BFT style.
While Fuel can run in this configuration, we do not promote or support this outside of testing, as the
broader mission of Fuel is to enhance existing blockchains such as Ethereum as a high-performance
execution layer.
Fuel Configurations
While we do not ship a channel configuration of the Fuel technology out of the box, the FuelVM is
perfectly situated to handle this particular use case.
Fuel Configurations
Defining Sidechain
A sidechain is a blockchain with a one-way trust-minimized bridge from the base chain.
Fuel as a Sidechain
The Fuel technology can also run as a sidechain to an existing layer-1. This means there is a message
passing bridge between the layer-1 and Fuel. In this configuration, data availability would be handled
by the side chain, while settlement is handled by the layer-1.
There would also be an option to run it in a semi-provable configuration, whereby fraud proofs can
be used to ensure better validity guarantees using the layer-1 as an arbitrator.
Technology
Parallel Transaction Execution
Fraud Proofs
Parallel Transaction Execution
Ethereum processes transactions sequentially (i.e. one after the other). With modern processors
becoming increasingly multi-threaded but stalling on single-core speedups, being able to execute
transactions in parallel (i.e. multiple transactions at once) is a highly desirable property.
Without a mechanism for determining and handling dependencies between transactions, executing
transactions in parallel is a race condition and would result in non-deterministic execution. There
have been attempts to add optimistic concurrent execution logic to Ethereum, but show inconsistent
performance benefits and moreover only work in non-adversarial conditions.
EIP-648 proposed to add access lists to transactions, i.e. a list of shared state that would be touched
by each transaction. With such a list, clients can partition transactions into sets with disjoint access
lists and execute transactions across each set in parallel. However, the EIP was never implemented,
in part due to implementation and design inefficiencies that resulted in state accesses being the
bottleneck rather than compute.
Access lists are implemented with UTXOs. UTXOs give other nice properties, but for the purposes of
parallel transaction execution serve simply as strict access lists.
Fraud Proofs
Fraud proofs are a blockchain verification mechanism whereby a claim on a new block is accepted
unless a proof the claim is invalid is provided within some configurable time window. This allows
trust-minimized light clients to be secure under the assumption only a single honest full node is
available in the network to produce fraud proofs. Both the Fuel protocol and the FuelVM are
designed to be fraud-provable in restrictive environments such as the Ethereum Virtual Machine.
State-transition fraud proofs are a general-purpose fraud proof mechanism, but come with the
downside of requiring a global state tree—an inherently sequential bottleneck. UTXO fraud proofs
avoid this bottleneck; they simply require each spend of a UTXO to "point" to the creation of the
UTXO. Proving the pointer is invalid, or that whatever is being pointed to doesn't match whatever is
being spent, are sufficient for exhaustively proving fraud.
The Fuel transaction format and validation logic are fraud-provable with UTXO fraud proofs. The
FuelVM relies on an Interactive Verification Game protocol, whereby an execution trace is bisected
until a single step must be executed to check for a mismatch. The FuelVM instruction set is
specifically designed to be both expressive yet fraud-provable within the Ethereum Virtual Machine.
The FuelVM
Contract and Call Model
Memory Model
Multiple Native Assets
Transactions may initiate contract calls. Ethereum transactions may call a single contract directly.
Fuel transactions instead execute a script (arbitrary bytecode attached to the transaction), which
may call any number of contracts.
Memory Model
The EVM uses a linear memory (i.e. starting at zero and growing), without a defined limit. Allocating
memory costs a quadratic amount of gas, which severely limits the amount of memory usable in a
single context (i.e. contract call).
In addition, the EVM has a separate memory space per context. Contexts may communicate with
each other by copying data to call data and returning data buffers.
The FuelVM uses a single share memory block per transaction. Memory is allocated statically with a
known upper bound, allowing for straightforward implementation of heap types such as vectors.
Memory in the FuelVM is globally readable across contexts, but locally writable. Each context may
only write to portions of the stack and the heap which it has ownership over.
Multiple Native Assets
Fuel supports multiple native assets as first-class citizens. Any single asset may be forwarded with a
CALL . Contracts have a balance of all possible assets instead of only the base asset.
Note that only the base asset is usable to pay for gas fees.
FuelVM vs. EVM, Explained
FuelVM learns from the EVM, Solana, WASM, Bitcoin, and Cosmos.
This page is meant to outline the ways the FuelVM differs compared to the EVM in simple terms.
The FuelVM has a globally shared memory architecture. Instead of every contract call having its own
separate memory space, call data, and return data, all contract call frames share global memory.
This chunk of memory is shared amongst all call frames and is globally readable. This allows you to
pass data around between contracts without expensive storage and pass chunks of data without
having to serialize, copy from call data to memory, etc. Read more about the FuelVM memory model
here.
The EVM is a complicated machine to construct fraud proofs for. It usually requires a second layer
such as WASM or MIPS to be interpreted into a fraud provable system. Check out User Sovereignty
with Fraud Proofs and how fraud proofs unlock key functionality.
FuelVM has multiple native assets
In Ethereum, the only native asset is Ether. It’s the only one that gets first-class treatment in terms of
cost and ability to be pushed and pulled through a call. In Fuel, any contract can mint its UTXO-based
native asset using a set of easy asset opcodes. All of which can gain the benefits of native-level call
and optimization. Read more about support for multiple native assets in the Sway docs, and here.
Modern processors have 64-bit registers, and all of the instruction set operates on 64 bits. Those are
the most efficient instructions, and when you deal with 256 bits, you’re dealing with big numbers,
and since modern processors aren't made to handle those numbers natively, it means you have to
do more in the software.
Register-based VMs typically require fewer instructions to do the same work than stack-based VMs.
Because every operation is priced, optimizing to reduce the number of operations needed to do the
same amount of work has outsized benefits.
The FuelVM is built with an atomic UTXO paradigm from the start
Fuel uses a system of UTXOs which enable a more efficient system fo transfer and ownership of
assets, where the accounts tree doesn't have to be rebuilt every time funds are transferred.
The FuelVM removes the need for approve/transferFrom UX with scripts. Unlike the EVM, the FuelVM
has scripts, which allow many actions to happen from an origin sender without a contract being
deployed. Read more here.
EIPs Implemented in Fuel
The FuelVM implements several EIPs that have been suggested and supported by the community
but couldn't be implemented due to the need to maintain backward compatibility. Check out a non-
exhaustive list, also available here:
In addition to robust documentation, tooling, clear error messages, and more – Sway brings the
notion of static auditing to smart contracts. The compiler will catch things that one would typically
hire an auditing firm to catch. This is particularly unique. In addition, Sway is highly performant and
has extensible optimization passes and a modular backend for targeting different blockchain
architectures.
From Rust, we took the prioritizations of performance, control, and safety. In Rust, this means the
borrow checker, safe parallelism (send and sync), annotated unsafety, etc., mainly to save the
programmer from referencing freed memory, shared mutable state, and undesirable memory
management. This is great for a general-purpose language model. Sway, however, is not general
purpose. Sway targets a blockchain VM environment, where execution is not indefinite, and memory
allocation and management are less concerned. Instead, we need to optimize for gas costs and
contract-level safety. We applied the philosophy of performance, control, and safety and interpreted
it in this new context. This is where Sway gets compile time checks of state mutability, namespacing
of state variables, static analysis passes, and gas profiling/optimization.
Sway Safety
Sway provides multiple layers of safety. For one, we provide canonical tooling and "one right way" to
do things. This results in less ambiguity and more correct/helpful tools. This tooling ships a
debugger, gas profiler, testing framework, SDK, formatter, and more. These tools ensure the
programmer has nothing between them and the algorithm they are trying to implement. Safety
comes from the foundation of a comfortable and ergonomic environment.
In addition, Sway has implemented static analysis checks like a Checks, Effects, Interactions checker,
state and storage purity checking, immutable-by-default semantics, and other static compile-time
audits to promote safety.
For Developers
Connecting to Testnet
Sway Language
TypeScript SDK
Rust SDK
Indexer
Wallet and Faucet
Fuelup
Sway Application Examples
Developers are encouraged to reference the sway-applications repo for examples for common
patterns and functionality. This repository contains smart contracts that are written in Sway in order
to demonstrate what can be built, and offer forkable code for others to build on.
Airdrop is a token distribution program where users are able to claim tokens given a valid
merkle proof.
Automated Market Maker (AMM) is a decentralized exchange protocol that manages liquidity
pools supplied by its users and determines prices algorithmically while exchanging assets.
Decentralized Autonomous Organization (DAO) is an organization where users get to vote on
governance proposals using governance tokens.
English Auction is an auction where users bid up the price of an asset until the bidding period
has ended or a reserve has been met.
Escrow is a third party that keeps an asset on behalf of multiple parties. Fundraiser is a
program allowing users to pledge towards a goal.
Multi-Signature Wallet is a wallet that requires multiple signatures to execute a transaction.
Name-Registry allows users to perform transactions with human readable names instead of
addresses.
Non-Fungible Token (NFT) is a token contract which provides unique collectibles, identified and
differentiated by token IDs, where tokens contain metadata giving them distinctive
characteristics.
Oracle is a smart contract that provides off-chain data to on-chain applications. OTC Swap
Predicate is a predicate that can be used to propose and execute an atomic swap between two
parties without requiring any on-chain state.
Please note all projects currently use forc 0.31.1, and fuel-core 0.14.1.
Networks
On this page, you'll find information on the different testnet networks.
beta-1 testnet
The beta-1 network is the first public Fuel testnet, shared by all developers and users that interact
with it. Developers may deploy contracts to it at will—no permission or whitelisting required—and
users may interact with deployed contracts as well. Read more about beta-1 here.
beta-2 testnet
The beta-2 network is launched with a bridge to Ethereum's Goerli test network. With this network,
developers are able to build and test cross-chain dapps, laying the foundations for projects building
on Fuel to tap into Ethereum's massive liquidity and existing user base. Read more about beta-2
here.
The beta-1 testnet
The beta-1 network is the first public Fuel testnet, shared by all developers and users that interact
with it. Developers may deploy contracts to it at will—no permission or whitelisting required—and
users may interact with deployed contracts as well.
🚰 Faucet - Use the faucet to get test ETH to deploy contracts with or to interact with contracts.
Available here: https://faucet-beta-1.fuel.network.
📃 GraphQL endpoint - The Fuel Core node uses GraphQL instead of JSON RPC. A playground for the
public GraphQL endpoint for beta-1 is available at https://node-beta-1.fuel.network/playground.
Join the Fuel Labs Discord and head to the 🧪︱testnet-beta-1 channel to get support from our
team.
SDK Versioning
Version 0.17.0 is the recommended version of the TS SDK on beta-1 .
Version 0.30.0 is the recommended version for the Rusk SDK on beta-1 ,
Toolchain Configuration
To configure the optimal toolchain for beta-1 , ensure you have fuelup installed, then run the
following command:
$ fuelup toolchain install beta-1
Downloading: forc forc-wallet fuel-core
Installed:
- forc 0.26.0
- forc-wallet 0.1.2
- fuel-core 0.10.1
forc 0.26.0
forc-wallet 0.1.2
fuel-core 0.10.1
The beta-2 testnet
The beta-2 network is launched with a bridge to Ethereum's Goerli test network. With this network,
developers are able to build and test cross-chain dapps, laying the foundations for projects building
on Fuel to tap into Ethereum's massive liquidity and existing user base. Read more about beta-2
here.
"FuelMessagePortal": 0x4c7181fff2053D232Fc74Ff165b83FE8Dcb65910
"BinaryMerkleTreeLib": 0x40Ab53ba8BEEe302539f417eCC6C5FBb99F3B7Cd
"FuelSidechainConsensus": 0xF712e555ce59858f680890DA7dc2B51eD048580d
"L1ERC20Gateway": 0x96c53cd98B7297564716a8f2E1de2C83928Af2fe
🚰 Faucet - Use the faucet to get test ETH to deploy contracts with or to interact with contracts.
Available here: https://faucet-beta-2.fuel.network/.
📃 GraphQL endpoint - The Fuel Core node uses GraphQL instead of JSON RPC. A playground for the
public GraphQL endpoint for beta-1 is available at https://node-beta-2.fuel.network/playground.
SDK Versioning
Version 0.21.0 is the recommended version of the TS SDK on beta-2 .
Version 0.30.0 is the recommended version for the Rusk SDK on beta-2 .
Toolchain Configuration
To configure the optimal toolchain for beta-2 , ensure you have fuelup installed, then run the
following command:
$ fuelup self update
Fetching binary from
https://github.com/FuelLabs/fuelup/releases/download/v0.12.0/fuelup-0.12.0-aarch64-
apple-darwin.tar.gz
Downloading component fuelup without verifying checksum
Unpacking and moving fuelup to
/var/folders/tp/0l8zdx9j4s9_n609ykwxl0qw0000gn/T/.tmplX61Ng
Moving /var/folders/tp/0l8zdx9j4s9_n609ykwxl0qw0000gn/T/.tmplX61Ng/fuelup to
/Users/camiinthisthang/.fuelup/bin/fuelup
`$ fuelup toolchain install beta-2.`
Downloading: forc forc-explore forc-wallet fuel-core
forc 0.31.1
forc-explore 0.28.1
forc-wallet 0.1.2
fuel-core 0.14.1
Predicate
Messages intended for contracts use a pre-defined predicate as the message recipient. This
predicate allows anyone to relay the message to the target contract and only the target contract.
Once the contract receives the message it can see who originated it along with any special message
payload and processes it accordingly. Since anyone can relay the message using this predicate it
opens up possibilities for automated message processing as a service.
Check out the Developer Quickstart to see a working example of how to deploy a contract to beta-
1.
For more information on versioning, tooling, and resources, check out the beta-1 page.
For more information on versioning, tooling, and resources, check out the beta-2 page.
Sway Language 🌴
Resources to get started with Sway:
Need Help?
Head to the Fuel discord for help from the team.
Typescript SDK
The Fuel TS SDK is a toolkit for build dapps on The fuel network. You can use the SDK to execute
scripts, interact with contracts, list transactions, balances and more.
SDK Docs
TS Quickstart Guide
TS SDK Repo
Need Help?
Head to the Fuel discord for help from the team.
Rust SDK
Rust SDK for Fuel. It can be used for a variety of things, including but not limited to:
Need Help?
Head to the Fuel discord for help from the team.
Fuel Indexer
The Fuel Indexer is a standalone binary that can be used to index various components of the
blockchain. These indexable components include blocks, transactions, and receipts and state within
a Fuel network, allowing for high-performance read-only access to the blockchain for advanced dApp
use-cases.
Events can be indexed by the Fuel Indexer by using WASM modules, as described in the Hello World
example.
Indexer Docs
Need Help?
Head to the Fuel discord for help from the team.
Faucet and Block Explorer
Beta-1 Facuet
Assets for the Testnet node can be obtained from the faucet at https://faucet-beta-1.fuel.network/.
Beta-2 Faucet
Assets for the Testnet node can be obtained from the faucet at https://faucet-beta-2.fuel.network/.
Block Explorer
The block explorer for both testnets can be found here.
Fuel Wallet
Fuel has a beta wallet extension that can be downloaded. Keep in mind this is an alpha version. For
now, it isn't possible to download the extension directly from Chrome Extensions Store. For
instructions on how to download the extension, check out the docs here.
Fuels is an SDK that allows developers to let users interact with the Fuel node via the Fuel wallet.
Check out the API reference here.
Unsigned Transactions
You can deploy a contract to a local fuel instance without signing with a wallet by running the
following command:
To deploy a contract to the testnet, you'll need a Fuel wallet. You can initialize a wallet and an
account for your wallet to sign transactions.
Check out the documentation for a step-by-step guide to initializing a wallet and creating an account.
Fuelup
fuelup is the official package manager for Fuel that installs the Fuel Toolchain from the official
release channels, enabling you to easily switch between different toolchains and keep them
updated. It makes building and maintaining Sway applications simpler with forc and fuel-core for
common platforms.
Fuelup Docs
Need Help?
Head to the Fuel discord for help from the team.
Fuel Glossary
Address
An address is a cryptographic hash representing an identity of a wallet or a predicate root.
AssetId
An asset ID is a unique identifier for an on-chain asset. It is derived from the root of the bytecode of
the contract minting the asset.
Base Asset
The base asset is the underlying asset needed to perform any transactions on a blockchain. It is used
to pay gas for transactions. On Ethereum, the base asset is ETH.
Block
A block is a record of many transactions, that are grouped together and cryptographically hashed.
The linked blocks form a chain, also called a blockchain.
Block Explorer
A block explorer is an interface for block and transaction data produced by a blockchain. You can
use a block explorer to explore and verify addresses, contracts, and transaction histories.
Block Height
The block height refers to the total number of valid blocks produced in the history of a blockchain,
starting with the genesis block.
Block ID
A block ID is a unique identifier for a particular block.
Bridge
A bridge is a mechanism that allows the transfer of data or assets from one blockchain to another.
Bytecode
Bytecode is machine-readable code, usually generated from a compiler.
Chain
Another name for a blockchain.
ChainId
A unique ID for a blockchain.
Client
The Fuel client refers to the software that runs the Fuel Virtual Machine. It can be used to validate
and produce blocks, and send transactions.
Coinbase
Coinbase refers to the validators paying themselves for processing a block from the transaction fees.
Having a coinbase transaction on each block makes this process transparent to all users.
Consensus
The consensus layer defines the state and validates that all nodes on the blockchain have the same
state.
Consensus Parameters
Consensus parameters are the rules used by clients to determine the validity of and finalize a block.
Contract Call
Calling a contract means invoking a function from a smart contract that has been deployed to the
blockchain.
Contract ID
The contract ID is a unique identifier for a contract derived from the root of the contract bytecode.
Data Availability
The data availability layer ensures that block data has been published to the network.
EIP
EIP stands for Ethereum Improvement Proposal. It refers to a proposal to upgrade the core software
powering the Ethereum blockchain.
EOA
EOA stands for Externally Owned Account. It refers to a wallet address that is not controlled by a
contract.
EVM
EVM stands for Ethereum Virtual Machine, which is the virtual machine used for the Ethereum
network.
Execution
Execution refers to the processing of transactions by nodes in a network.
Faucet
A faucet is a service that provides free tokens for a testnet.
Forc
Forc is short for Fuel Orchestrator. Similar to Cargo for Rust, Forc is the build system and package
manager for Sway. It is used to build, test, and deploy Sway contracts.
Fraud Proof
Fraud proofs are a blockchain verification mechanism whereby a claim on a new block is accepted
unless a proof the claim is invalid is provided within some configurable time window. Both the Fuel
protocol and the FuelVM are designed to be fraud-provable in restrictive environments such as the
Ethereum Virtual Machine.
Fuel
The Fuel blockchain.
Fuels
Fuels is the name of the Fuel Rust and Typescript SDKs used to interact with a contract, similar to
ethers.js or web3.js
Fuelup
Fuelup is the official toolchain and package manager for the Fuel toolchain.
FuelVM
The FuelVM is the virtual machine powering the Fuel blockchain.
Fuel Core
fuel-core is the name of the Fuel client implementation.
Gas
Gas is a variable fee charged by a node to process a transaction that is executed on-chain.
Indexer
An indexer is a program that watches and organizes blockchain data so it can be easily queried.
Input
An input refers to a transaction input, which is a UTXO consumed by a transaction.
Layer 1 (L1)
Also called a level 1, this refers to a base layer blockchain that is not built on top of any other
blockchain.
Layer 2 (L2)
Also called a level 2, this is a blockchain that is built on top of another blockchain. Layer 2 networks
can offer unique benefits like allowing for cheaper transactions or sovereign rollups that can fork
without forking the base layer.
Light Client
A light client is a client that doesn't validate blocks and transactions but still offers some functionality
to send transactions.
Locked Wallet
A locked wallet is a wallet that can only interact with read-only smart contract methods.
Mainnet
Mainnet refers to the main network of a blockchain, as opposed to a testnet.
Merkle Tree
A Merkle tree is a data structure which uses a cryptographic hash function recursively to condense a
set of data into a single value, called the root. It allows efficient proofs that a given element is part of
the set.
Message
A type of input that only includes specific metadata, and is often used for bridging.
Mint
Minting refers to the creation of new coins.
Modular
Referring to a blockchain architecture that allows for execution, settlement, consensus, and data
availability to run on separate layers.
Monolithic
Referring to a blockchain architecture that handles execution, settlement, consensus, and data
availability all at the same time on a single layer.
Native Asset
With Fuel any contract can make its own native asset. On Ethereum, the only native asset is ETH. This
allows for much cheaper token transactions because it doesn't require any contract state changes. It
also allows you to directly forward any asset in a transaction call, avoiding the need for the approve
and transferFrom mechanisms.
Network
Another name for a blockchain.
Node
A client that validates and produces blocks for the network.
Optimistic Rollup
An optimistic rollup is a sidechain that uses fraud proofs to verify transactions instead of relying on a
majority of validators to be honest.
Output
An output refers to a transaction output, or which UTXOs are output by a transaction.
Parallel Transactions
Parallel transactions refers to the ability of the FuelVM to process multiple transactions in parallel.
Predicate
A predicate is a pure function that can return true or false, and is sent inside a transaction as
bytecode and checked at transaction validity time. If it evaluates to false the transaction will not be
processed, and no gas will be used. If it evaluates to true , any coins belonging to the address equal
to the Merkle root of the predicate bytecode may be spent by the transaction.
Private Key
A cryptographic key that is used to prove ownership by producing a digital signature. It should be
kept private (or secret) as it can grant access to a wallet.
Public Key
A cryptographic key that is generated from its associated private key and can be shared publicly.
Addresses are derived from public keys.
Receipt
A receipt is a data object that is emitted during a transaction and contains information about that
transaction.
Re-entrancy attack
A type of attack in which the attacker is able to recursively call a contract function so that the
function is exited before it is fully executed. This can result in the attacker being able to withdraw
more funds than intended from a contract.
Rollup
A rollup is a scaling solution for layer 1 blockchains that "rolls up" or batches transactions as
calldata.
Script
A script is runnable bytecode that executes once on-chain to perform some task. It does not
represent ownership of any resources and it cannot be called by a contract. A script can return a
single value of any type.
Settlement
Settlement refers to how and where on-chain disputes are resolved or settled.
Sidechain
A sidechain is a blockchain that runs independently but is connected to another blockchain (often
Ethereum Mainnet) by a two-way bridge.
Signature
A cryptographic signature from a wallet, usually in reference to a signature for a message.
Smart Contract
Also referred to as a contract, a smart contract is a set of programming functions with persistent
state that is deployed on a blockchain. Once deployed, the contract code can never be changed or
deleted, and anyone can access public functions without permission.
State Channel
State channels allow for users to conduct any number of off-chain transactions while only submitting
two on-chain transactions to open and close the channel. This reduces the number of on-chain
transactions needed, which reduces the cost and saves time.
Sway
Sway is the official programming language for Fuel. It is a domain-specific language crafted for the
FuelVM and inspired by Rust.
Testnet
Testnet is short for test network. You can use a testnet to deploy and test contracts for free.
Toolchain
A toolchain is a set of related tools. The Fuel toolchain includes fuelup , forc , fuel-core , and
fuels .
Transaction
A transaction is any interaction with the blockchain, for example sending coins from one address to
another.
Unlocked Wallet
An unlocked wallet can interact with both read and write smart contract methods.
UTXO
UTXO stands for unspent transaction output.
UTXO Model
A UTXO model is a blockchain model that doesn't keep track of account balances. Instead, it uses
inputs and outputs to manage state, which allows for fast parallel transactions.
Validator
A validator refers to a network validator or node. Validators help validate transactions and produce
blocks.
Witness
A witness refers to the cryptographic signatures from actors involved in authorizing a transaction,
including the transaction signers, contract callers, and block producers.
Zero-Knowledge Proof
A method that allows for the verification of secret information without revealing the secret.
Zero-Knowledge Rollup
A rollup that uses zero-knowledge proofs to verify transactions. In ZK rollups, each rollup block
posted to the contract must be accompanied by a validity proof (a succinct proof that the block is
valid), which is also verified by the contract. Blocks are thus finalized immediately, and withdrawals
can be processed in the same Ethereum block.