This tutorial will walk you through the process of building your own digital token using Ethereum smart contracts. We will cover both fundamental and advanced functionalities to help you create a versatile and functional token.
What Is a Token?
A token is a type of digital currency implemented via smart contracts on the Ethereum blockchain. Developers can create custom cryptocurrencies by writing smart contract code.
Basic features you can implement include:
- Defining the token's name, total supply, and symbol.
- Enabling token transfers between users.
Advanced features allow for more complex use cases:
- Assigning an administrator to manage the contract.
- Implementing blacklists and whitelists to freeze specific accounts.
- Minting additional tokens beyond the initial supply.
- Setting up automatic exchange mechanisms between your token and other cryptocurrencies.
- Enabling automatic gas top-ups for users who hold your token but lack ETH.
Learning to implement these features will provide a solid foundation in smart contract development.
Implementing Basic Token Features
We'll start by creating a simple token with basic capabilities: defining the token and enabling transfers.
Smart contracts are written in a language similar to C or C++. The code below is a complete example you can deploy directly.
contract MyToken {
mapping (address => uint256) public balanceOf;
string public name;
string public symbol;
uint8 public decimals;
event Transfer(address indexed from, address indexed to, uint256 value);
function MyToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) {
balanceOf[msg.sender] = initialSupply;
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
}Deployment Using Mist Wallet
To deploy this contract, you can use the Mist Ethereum wallet. For testing, use an Ethereum testnet to avoid spending real funds.
- Navigate to the "CONTRACTS" section in Mist and click "DEPLOY NEW CONTRACT".
- Paste the code into the input field.
- From the dropdown, select "MyToken".
- Enter the initial supply, token name, number of decimals, and symbol.
- Click "DEPLOY". If successful, the contract will appear under "CONTRACTS" once confirmed.
You can now view token details, check balances for specific addresses, and execute transfers using the transfer function.
Implementing Advanced Token Features
Next, we enhance the token with advanced functionalities.
Creating a Contract Administrator
Even in a decentralized system, having an administrator can be useful for management.
Using inheritance, we define an owned contract:
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract MyToken is owned {
// ... existing code ...
function MyToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol, address centralMinter) {
if(centralMinter != 0) owner = msg.sender;
// ... rest of constructor ...
}
}The onlyOwner modifier restricts certain functions to the administrator.
Minting Additional Tokens
The administrator can mint new tokens, increasing the total supply.
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}This function adds tokens to a specified address and updates the total supply.
Implementing Blacklists and Whitelists
You can freeze accounts to prevent them from transacting.
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}Then, modify the transfer function to check if the sender is frozen:
function transfer(address _to, uint256 _value) {
if (frozenAccount[msg.sender]) throw;
// ... rest of transfer logic ...
}Enabling Automatic Token Exchange
Create functions to buy and sell tokens for ETH.
uint256 public sellPrice;
uint256 public buyPrice;
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() returns (uint amount) {
amount = msg.value / buyPrice;
if (balanceOf[this] < amount) throw;
balanceOf[msg.sender] += amount;
balanceOf[this] -= amount;
Transfer(this, msg.sender, amount);
return amount;
}
function sell(uint amount) returns (uint revenue) {
if (balanceOf[msg.sender] < amount) throw;
balanceOf[this] += amount;
balanceOf[msg.sender] -= amount;
revenue = amount * sellPrice;
msg.sender.send(revenue);
Transfer(msg.sender, this, amount);
return revenue;
}Note: These functions lack checks to ensure the contract has sufficient ETH or tokens to cover transactions. Implement additional safeguards for production use.
Automating Gas Top-Ups
Ensure users have enough ETH for transaction fees by automatically selling tokens for gas.
uint minBalanceForAccounts;
function setMinBalance(uint minimumBalanceInFinney) onlyOwner {
minBalanceForAccounts = minimumBalanceInFinney * 1 finney;
}
function transfer(address _to, uint256 _value) {
if (msg.sender.balance < minBalanceForAccounts) {
sell((minBalanceForAccounts - msg.sender.balance) / sellPrice);
}
// ... rest of transfer logic ...
}This checks the sender's ETH balance before proceeding and sells tokens if needed.
👉 Explore advanced smart contract strategies
Frequently Asked Questions
What is an Ethereum token?
An Ethereum token is a digital asset created using a smart contract on the Ethereum blockchain. It can represent various forms of value, such as currencies, points in a loyalty program, or ownership stakes.
How do I create my own token?
You need to write a smart contract in a language like Solidity, compile it, and deploy it to the Ethereum network. The contract defines the token's properties and behaviors, such as its name, supply, and transfer functions.
What is the difference between a token and a coin?
A coin like Ether (ETH) operates on its own native blockchain, while a token is built on top of an existing blockchain, like Ethereum, using smart contracts.
Why would I need an administrator for a decentralized token?
While decentralization is key, an administrator can handle essential functions like emergency freezes, minting new tokens for a specific purpose, or updating contract parameters, which can be crucial for managing a project.
Is it safe to implement automatic token exchange?
It requires careful coding. The contract must always have sufficient reserves of both ETH and the token to honor buy and sell requests. Without proper checks, the contract could become insolvent.
Can I make money from my token?
Potentially, by charging fees on transactions or through the appreciation of the token's value. However, this depends entirely on your token having utility and demand within its intended ecosystem.