How to Create a Fungible Token on Flow
This guide is an in-depth tutorial on launching a Fungible Token contract from scratch. To launch in 2 minutes using a tool check out Toucans
What are Fungible Tokens?
Fungible tokens are digital assets that are interchangeable and indistinguishable with other tokens of the same type. This means that each token is identical in specification to every other token in circulation. Think of them like traditional money; every dollar bill has the same value as every other dollar bill. Fungible tokens play a crucial role in web3 ecosystems, serving as both a means of payment and an incentive for network participation. They can take on various roles including currencies, structured financial instruments, shares of index funds, and even voting rights in decentralized autonomous organizations.
Vaults on Flow
On the Flow blockchain and in the Cadence programming language, fungible tokens are stored in structures called resources. Resources are objects in Cadence that store data, but have special restrictions about how they can be stored and transferred, making them perfect for representing digital objects with real value.
You can learn more about resources in the Cadence documentation and tutorials.
For fungible tokens specifically, tokens are represented by a resource type called a Vault
:
Think of a Vault
as a digital piggy bank.
Users who own fungible tokens store vault objects that track their balances
directly in their account storage. This is opposed to languages
that track user balances in a central ledger smart contract.
When you transfer tokens from one vault to another:
- The transferor's vault creates a temporary vault holding the transfer amount.
- The original vault's balance decreases by the transfer amount.
- The recipient's vault receives the tokens from the temporary vault and adds the temporary vault's balance to the its own balance.
- The temporary vault is then destroyed.
This process ensures secure and accurate token transfers on the Flow blockchain.
Fungible Token Standard
The Fungible Token Standard defines how a fungible token should behave on Flow. Wallets and other platforms need to recognize these tokens, so they adhere to a specific interface, which defines fields like balance, totalSupply, withdraw functionality, and more. This interface ensures that all fungible tokens on Flow have a consistent structure and behavior. Clink the link to the fungible token standard to see the full standard and learn about specific features and requirements.
Learn more about interfaces here.
Setting Up a Project
To start creating a Fungible Token on the Flow blockchain, you'll first need some tools and configurations in place.
Installing Flow CLI
The Flow CLI (Command Line Interface) provides a suite of tools that allow developers to interact seamlessly with the Flow blockchain.
If you haven't installed the Flow CLI yet and have Homebrew installed,
you can run brew install flow-cli
. If you don’t have Homebrew,
please follow the installation guide here.
Initializing a New Project
💡 Note: Here is a link to the completed code if you want to skip ahead or reference as you follow along.
Once you have the Flow CLI installed, you can set up a new project
using the flow setup
command. This command initializes
the necessary directory structure and a flow.json
configuration file
(a way to configure your project for contract sources, deployments, accounts, and more):
Upon execution, the command will generate the following directory structure:
Now, navigate into the project directory:
In our configuration file, called flow.json
, for the network we want to use,
we are going to state the address the FungibleToken
contract is deployed
to via aliases
in a new contracts
section. Since it is a standard contract,
it has already been deployed to the emulator, a tool that runs and emulates
a local development version of the Flow Blockchain, for us.
You can find addresses for other networks, like Testnet and Mainnet, on the Fungible Token Standard repo.
We'll also need to add the addresses for ViewResolver
, MetadataViews
,
and FungibleTokenMetadataViews
, which are other important contracts to use.
These contracts are deployed to the Flow emulator by default,
so there is not need to copy their code into your repo.
The addresses below are the addresses in the emulator that your contract
will import them from.
Writing Our Token Contract
Next let's create a FooToken
contract at cadence/contract/FooToken.cdc
using the boilerplate generate
command from the Flow CLI:
This will create a new file called FooToken.cdc
in the contracts
directory. Let's open it up and add some code.
In this contract file, we want to import our FungibleToken
contract that we've defined in flow.json
.
In this same file, let's create our contract which implements the FungibleToken
contract interface (it does so by setting it following the FooToken:
).
We'll also include fields for standard storage and public paths
for our resource definitions.
In our init
— which runs on the contract's first deployment and is used to set initial values — let’s set an starting total supply of 1,000 tokens for this example.
Creating a Vault
Inside of this contract, we'll need to create a resource for a Vault
.
The FungibleToken
standard requires that your vault implements the FungibleToken.Vault
interface.
This interface inherits from many other interfaces
which enforce different functionality that you can learn about in the standard.
In order to give an account a vault, we need to create a function
that creates a vault of our FooToken type and returns it to the account.
This function takes a vaultType: Type
argument that allows the caller
to specify which type of Vault
they want to create.
Contracts that implement multiple Vault
types can use this argument,
but since your contract is only implementing one Vault
type,
it can ignore the argument.
A simpler version of this function with no parameter
should also be added to your Vault
implementation.
Inside our Vault
resource, we also need a way to withdraw balances.
To do that, we need to add a withdraw()
function that returns a new vault
with the transfer amount and decrements the existing balance.
As you can see, this function has an access(FungibleToken.Withdraw)
access modifier.
This is an example of entitlements in Cadence.
Entitlements
are a way for developers to restrict access to privileged fields and functions
in a composite type like a resource when a reference is created for it.
In this example, the withdraw()
function is always accessible to code that
controls the full Vault
object, but if a reference is created for it,
the withdraw()
function can only be called if the reference
is authorized by the owner with FungibleToken.Withdraw
,
which is a standard entitlement
defined by the FungibleToken contract:
Entitlements are important to understand because they are what protects privileged functionality in your resource objects from being accessed by third-parties. It is recommended to read the entitlements documentation to understand how to use the feature properly.
References can be freely up-casted and down-casted in Cadence, so it is important for privileged functionality to be protected by an entitlement so that it can only be accessed if it is authorized.
In addition to withdrawing, the vault also needs a way to deposit. We'll typecast to make sure we are dealing with the correct token, update the vault balance, and destroy the vault. Add this code to your resource:
Many projects rely on events the signal when withdrawals, deposits, or burns happen.
Luckily, the FungibleToken
standard handles the definition and emission
of events for projects, so there is no need for you to add any events
to your implementation for withdraw, deposit, and burn.
Here are the FungibleToken
event definitions:
These events are emitted by the Vault
interface
in the FungibleToken
contract whenever the relevant function is called on any implementation.
One important piece to understand about the Burned
event in particular
is that in order for it to be emitted when a Vault
is burned, it needs to
be burnt via the Burner
contract's burn()
method.
This will call the resource's burnCallback()
function, which emits the event.
You'll need to also add this function to your token contract now:
If you ever need to destroy a Vault
with a non-zero balance,
you should destroy it via the Burner.burn
method so this important function can be called.
There are three other utility methods that need to be added to your Vault
to get various information:
Adding Support for Metadata Views
The Fungible Token standard also enforces that implementations provide functionality to return a set of standard views about the tokens via the ViewResolver and FungibleTokenMetadataViews definitions. (You will need to add these imports to your contract now) These provide developers with standard ways of representing metadata about a given token such as supply, token symbols, website links, and standard account paths and types that third-parties can access in a standard way. You can see the metadata views documentation for a more thorough guide using a NFT contract as an example.
For now, you can add this code to your contract to support the important metadata views:
Creating a Minter
Let's create a minter resource which is used to mint vaults that have tokens in them. We can keep track of tokens we are minting with totalSupply
If we want the ability to create new tokens, we'll need a way to mint them. To do that, let's create another resource on the FooToken
contract. This will have a mintToken
function which can increase the total supply of the token.
We also want to decide which account/s we want to give this ability to. In our example, we'll give it to the account where the contract is deployed. We can set this in the contract init function below the setting of total supply so that when the contract is created the minter is stored on the same account.
After each of these steps, your FooToken.cdc
contract file should now look like this:
Deploying the Contract
In order to use the contract, we need to deploy it to the network we want to use it on. In our case we are going to deploy it to emulator while developing.
Back in our flow.json
, let's add our FooToken
to the contracts
after FungibleToken
with the path of the source code:
Let's also add a new deployments
section to flow.json
with the network
we want to deploy it to, emulator
, the account we want it deployed to emulator-account
,
and the list of contracts we want deployed in the array.
Next, using the Flow CLI, we will start the emulator. As mentioned, this will give us a local development environment for the Flow Blockchain.
Open a new terminal and run the following to deploy your project:
Congrats, you've deployed your contract to the Flow Blockchain emulator. To read more about deploying your project to other environments, see the CLI docs.
Reading the Token’s Total Supply
Let's now check that our total supply was initialized with 1,000 FooTokens. Go ahead and create a script called get_total_supply.cdc
using the generate
command.
In cadence/scripts/get_total_supply.cdc
(which was just created), let's add this code which will log the totalSupply
value from the FooToken
contract:
To run this using the CLI, enter this in your terminal:
In the terminal where you started the emulator, you should see Result: 1000.0
To learn more about running scripts using Flow CLI, see the docs.
Giving Accounts the Ability to Receive Tokens
On Flow, newly created accounts cannot receive arbitrary assets.
They need to be initialized to receive resources.
In our case, we want to give accounts tokens and we’ll need to create
a Vault
(which acts as a receiver) on each account that we want
to have the ability to receive tokens. To do this, we'll need to run a transaction
which will create the vault and set it in their storage
using the createEmptyVault()
function we created earlier on the contract.
Let's first create the file at cadence/transactions/setup_ft_account.cdc
using the generate
command:
Then add this code to it.
This will call the createEmptyVault
function, save it in storage,
and create a capability for the vault which will later allow us to read from it
(To learn more about capabilities, see the Cadence docs here).
There are also examples of generic transactions that you can use to setup an account for ANY fungible token using metadata views! You should check those out and try to use generic transactions whenever it is possible.
Next let's create a new emulator account using the CLI. We'll use this account to create a new vault and mint tokens into it. Run:
Let's call it test-acct
and select "Emulator" for the network:
This will have added a new account, called test-acct
to your flow.json
.
To call our setup account transaction from the CLI, we'll run the following:
To learn more about running transactions using CLI, see the docs.
Reading a Vault’s Balance
Let's now read the balance of the newly created account (test-acct
) to check it's zero.
Create this new script file cadence/scripts/get_footoken_balance.cdc
:
Add this code which attempts to borrow the capability from the account requested and logs the vault balance if permitted:
To run this script using the CLI, enter the following in your terminal.
Note: you'll need to replace 123
with the address created by CLI
in your flow.json
for the test-acct
address.
You should see a balance of zero logged.
Minting More Tokens
Now that we have an account with a vault, let's mint some tokens into it using the Minter we created on the contract account.
To do this, let's create a new transaction file cadence/transactions/mint_footoken.cdc
:
Next, let's add the following code to the mint_footoken.cdc
file.
This code will attempt to borrow the minting capability
and mint 20 new tokens into the receivers account.
To run this transaction, enter this in your terminal.
Note: 123
should be replaced with address of test-acct
found in your flow.json
.
This command also states to sign with our emulator-account
on the Emulator network.
Let's go ahead and read the vault again. Remember to replace 123
with the correct address.
It should now say 20 tokens are in the vault.
Transferring Tokens Between Accounts
The final functionality we'll add is the ability to transfer tokens from one account to another.
To do that, create a new cadence/transactions/transfer_footoken.cdc
transaction file:
Let's add the code which states that the signer of the transaction will withdraw from their vault and put it into the receiver's vault which will be passed as a transaction argument.
To send our tokens, we'll need to create a new account to send them to. Let's make one more account on emulator. Run:
And pick the name:
Make sure to select Emulator as the network.
Don't forget the new account will need a vault added, so let's run the following transaction to add one:
Now, let's send 1 token from our earlier account to the new account. Remember to replace 123
with account address of test-acct-2
.
After that, read the balance of test-acct-2
(replace the address 123
).
You should now see 1 token in test-acct-2
account!
The transfer transaction also has a generic version that developers are encouraged to use!