Ethereum DApps: Compiling, Deploying, Testing TNS tokens

Share this article

Compile, Deploy, Test TNS tokens

In part 2 of this tutorial series on building DApps with Ethereum, we wrote the TNS token’s code. But we haven’t yet compiled it, deployed it, tested it or verified it. Let’s do all that in this part so that we’re ready for what comes next.

Compiling

At this point we have a file containing some Solidity code. But to make the Ethereum Virtual Machine understand it, we need to turn it into machine code. Additionally, in order to communicate with it from a web application, we need an ABI (application binary interface), which is a universally readable description of the functions that exist in a certain smart contract — be it a token or something more complex. We can create machine code for the EVM and the ABI all at once by using Truffle’s compiler.

In the project folder, run:

truffle compile

This command will look inside the contracts subfolder, compile them all and place their compiled version into the build subfolder. Note that if you used the alternative development flow from the last part, all the parent contracts from which our TNSToken contract is inheriting functionality will also be compiled one by one each in its own file.

Compiled contracts

Feel free to inspect the contents of the generated JSON files. Our TNSToken should have over 10000 lines of JSON code.

Deploying to Ganache

Now let’s see if we can deploy this to our simulated Ganache blockchain. If Ganache isn’t running already in a tab of your terminal or among your operating system’s applications, run it with:

ganache-cli

Or run the app to get a screen like this one:

Ganache UI

Then, back in the folder where we just compiled the contracts, we have to add a migration. Create the file migrations/2_deploy_tnstoken.js. If you’re not familiar with migrations in the Truffle ecosystem, see this guide.

Let’s put the following into that file:

var Migrations = artifacts.require("./Migrations.sol");
var TNSToken = artifacts.require("./TNSToken.sol");

module.exports = function(deployer, network, accounts) {
  deployer.deploy(TNSToken, {from: accounts[0]});
};

First the ability to do migrations at all is imported by requesting Migrations.sol. This is required in every migration. Next, deploying a token means we need to import its Solidity code, and we do this by pulling in TNSToken.sol, the code we wrote in the previous part. Finally, this is cookie cutter migrating with only the part between function(deployer, network, accounts) { and the last } changing.

In this case, we tell the deployer to deploy the TNSToken and pass in the from argument in order to set the initial token holder. The address used here is a random one generated by Ganache, but by using the accounts array automatically passed to the deployer, we make sure we have access to the list of accounts present in the running node (be it a live Geth node or Ganache). In my particular example, the account[0] address was 0xdFb659D556d926dd3585d0f18d4F8eD7939E8061, also evident in the screenshot above.

Let’s also not forget to configure a development environment in truffle.js:

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*"
    }
  }
};

Note: take care of the port and IP; yours might be different!

Finally, in the project folder, run truffle migrate. You should see something like this:

A successful migration

Notice the Ethereum address next to TNStoken: 0x3134bcded93e810e1025ee814e87eff252cff422. This is where our token was deployed. Now let’s see it in action.

Testing the Token

Automated tests are not necessary in this case. Token contracts are highly standardized and battle tested. If we had used some functionality that goes beyond the scope of a traditional token, then automated tests would have come in handy. As it is, though, testing it by sending it around to and from addresses is quite enough.

Open a wallet UI like MyEtherWallet and in the top right menu select a custom network. In the dialog, enter the information given to you by your private blockchain — either Ganache or an actual PoA blockchain, whichever you’re running based on part 1 of this tutorial series. In my example, that’s 127.0.0.1 for the address, and 7545 for the port.

Configuring the network in MEW

Open the wallet which you set as the from value in the deployment script. If you’re using Ganache, you’ll see its private key printed on screen in the Ganache UI or the ganache output in the terminal.

The private key is accessible in the Ganache UI

Finally, MEW needs to be told that this token exists. We do this by adding a custom token.

Adding a custom token in MEW

Immediately after having added the token, you’ll notice that the account now has a balance of 100 million of them, and that it’s able to send them in the currency dropdown selection menu. Let’s try sending some to another address.

Sending some tokens

Transaction is being prepared

Tokens have been received

Go ahead and send those back now to get the original account back to 100 million again. We’ve just made sure our token’s basic functionality works as intended.

Deploying to a Live Network

This wouldn’t be a real token test without also deploying it on a live network. Let’s not use the mainnet, though, but a testnet like Rinkeby.

In truffle.js, let’s add a new network — rinkeby — so that our file looks like this:

require('dotenv').config();
const WalletProvider = require("truffle-wallet-provider");
const Wallet = require('ethereumjs-wallet');
const Web3 = require("web3");
const w3 = new Web3();

const PRIVKEY = process.env["PRIVKEY"];
const INFURAKEY = process.env["INFURAKEY"];

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*"
    },
    rinkeby: {
      provider: function() {
        return new WalletProvider(
          Wallet.fromPrivateKey(
            Buffer.from(PRIVKEY, "hex")), "https://rinkeby.infura.io/"+INFURAKEY

        );
      },
      gas: 4600000,
      gasPrice: w3.utils.toWei("50", "gwei"),
      network_id: "3",
    },
  }
};

Yikes! What is all this now?

Let’s process it line by line.

The first few lines import some node modules so we can use the functions below. If you get a missing module message for any of those, just running npm install web3-wallet-provider truffle-wallet-provider web3 dotenv --save should fix things.

Next, we load the private key of the wallet from which we’re running the contract (so the wallet which will be getting the 100 million tokens; we can’t use the from value here) from a .env file in the root of the project folder. If it doesn’t exist, create it. That same file also has an Infura.io access key, which is a website that hosts Ethereum nodes and lets apps connect to them so developers don’t need to run full Ethereum nodes on their computers.

The .env file is hidden by default and can be ignored in .gitignore so there’s no danger of your private key ever leaking — a very important precaution! This is what the file contains:

PRIVKEY="YOUR_PRIVATE_KEY";
INFURAKEY="YOUR_INFURA_ACCESS_KEY";

You can get your Infura key by registering here. The private key can easily be obtained if you just install Metamask, switch it to Rinkeby, and go to Export Private Key. Any method will work, though, so choose whatever you like. You can also use Ganache’s private key. A single private key unlocks the same wallet on all Ethereum networks — testnet, rinkeby, mainnet, you name it.

Back to our config file. We have a new network entry: rinkeby. This is the name of the Ethereum testnet we’ll be deploying to and the code inside the provider is basically cookie-cutter copy paste telling Truffle “grab my private key, hex-encode it, make it into an unlocked wallet, and then talk to Infura through it”.

Lastly, we define the gas limit we want to spend on executing this contract (4.6 million is enough, which can be changed if needed), how much the gas will cost (50 Gwei is actually quite expensive, but the Ether we’re playing with is simulated so it doesn’t matter) and the network ID is set to 4 because that’s how the Rinkeby testnet is labeled.

There’s one more thing we need to do. The migration file we wrote earlier is targeting a from address, but the address for Rinkeby is different. Does this mean we need to change the deployment script depending on the network? Of course not! Let’s change the 2_deploy_tnstoken.js file to look like this:

var Migrations = artifacts.require("./Migrations.sol");
var TNSToken = artifacts.require("./TNSToken.sol");

module.exports = function(deployer, network, accounts) {
  if (network == "development") {
    deployer.deploy(TNSToken, {from: accounts[0});
  } else {
    deployer.deploy(TNSToken);
  }
};

As you can see, deployment scripts are simple JavaScript and the second parameter given to the deployer is always the network’s name — which is what we can use to differentiate between them.

If we try to run the migration now with truffle migrate --network rinkeby, it will fail if the address we used is new:

A failing migration

This is because the address has no Ether to spend on deploying the contract. That’s easy to solve, though. Just head over to the Rinkeby Faucet and ask for some. It’s free.

Asking for Rinkeby test ether

Now re-run the migration and the token contract will be deployed live on the Rinkeby network. It can be tested just like in the Ganache use case above. Everything should work exactly the same, only now you can also test it with your friends and colleagues. Progress!

Bonus: Verification and ENS

For extra trust points, it’s recommended that you verify the token on Etherscan and register an ENS domain for it.

Verification

Verification means submitting the source code of the token to Etherscan so it can compare it to what’s deployed on the network, thereby verifying it as backdoor-free. This is done on the Code tab of the token’s address. Since our token uses some third-party code and those can’t be easily pulled into the code window in the Verify screen, we need to flatten our contract. For that, we’ll use a tool called truffle-flattener:

npm install --global truffle-flattener

This tool will copy all the dependencies and the token’s source code into a single file. We can run it like this:

truffle-flattener contracts/TNSToken.sol >> ./contracts/TNSTokenFlat.sol

A new file should be present in the contracts folder now, virtually identical to our source code but with dependency code pasted in (so SafeMath.sol, for example, will be pasted at the top of the file).

Paste the contents of that new file into the code window of the Verify screen, set the compiler to whatever version you get by running truffle version, and set Optimization to No. Click Verify and Publish, and once the process completes, your token’s address screen will have new tabs: Read Contract and Write Contract, and the Code tab will have a green checkmark, indicating that the code has been verified. This gives you additional trust points with the community.

The token is now marked as trusted

ENS

The ENS is the Ethereum Name System. It’s used to give Ethereum addresses human-readable names so you don’t have to remember the 0xmumbojumbo strings and can instead remember addresses like bitfalls.eth. You can then even register subdomains like token.bitfalls.eth. The process of registering an ENS domain is not simple and it takes time, so if you’d like to do that I recommend you read this guide and follow the instructions here.

Conclusion

In this part we went through compiling and deploying a custom token. This token is compatible with all exchanges and can be used as a regular ERC20 token.

Bruno SkvorcBruno Skvorc
View Author

Bruno is a blockchain developer and technical educator at the Web3 Foundation, the foundation that's building the next generation of the free people's internet. He runs two newsletters you should subscribe to if you're interested in Web3.0: Dot Leap covers ecosystem and tech development of Web3, and NFT Review covers the evolution of the non-fungible token (digital collectibles) ecosystem inside this emerging new web. His current passion project is RMRK.app, the most advanced NFT system in the world, which allows NFTs to own other NFTs, NFTs to react to emotion, NFTs to be governed democratically, and NFTs to be multiple things at once.

DAppethereumethereum-hubethereum-tutorialsTNS token
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week