James Bachini

Solidity Token Factory Contract Walkthrough

Solidity Token Factory Contract

A token factory contract is used to deploy tokens from a parent contract within Solidity. In this simple example we will be deploying an ERC20 token from our factory contract.

James On YouTube

Full source code below and on Github: https://github.com/jamesbachini/Token-Factory-Tutorial

We start with a standard ERC20 token using the OpenZeppelin library. The entire circulating supply of the token is minted to the deployer of the contract via the _mint command in the constructor argument.

The factory contract is a second separate contract which deploys the token. Because the initial mint goes to the factory contract, essentially the contract will own all the tokens, we need to transfer them to the end user that calls the contract.

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.16;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract Token is ERC20 {
    constructor(string memory _name, string memory _ticker, uint256 _supply) ERC20(_name, _ticker) {
      _mint(msg.sender, _supply);
    }
}

contract Factory {
    address[] public tokens;
    uint256 public tokenCount;
    event TokenDeployed(address tokenAddress);

    function deployToken(string calldata _name, string calldata _ticker, uint256 _supply) public returns (address) {
        Token token = new Token(_name, _ticker, _supply);
        token.transfer(msg.sender, _supply);
        tokens.push(address(token));
        tokenCount += 1;
        emit TokenDeployed(address(token));
        return address(token);
    }
}

Get The Blockchain Sector Newsletter, binge the YouTube channel and connect with me on Twitter

The Blockchain Sector newsletter goes out a few times a month when there is breaking news or interesting developments to discuss. All the content I produce is free, if you’d like to help please share this content on social media.

Thank you.

James Bachini

Disclaimer: Not a financial advisor, not financial advice. The content I create is to document my journey and for educational and entertainment purposes only. It is not under any circumstances investment advice. I am not an investment or trading professional and am learning myself while still making plenty of mistakes along the way. Any code published is experimental and not production ready to be used for financial transactions. Do your own research and do not play with funds you do not want to lose.