Migrating the code

In Truffle, migration files are JavaScript files that help you deploy your contracts to a network, be it Ethereum's mainnet, a public testnet, or a personal test environment such as Ganache. For the purposes of our testing, we will be using Ganache, but later we will deploy our contracts to the Rinkeby public test network.

To connect with Ganache, we first have to download and install it from https://truffleframework.com/ganache. Once installed, running Ganache will create a local, in-memory blockchain instance for the purposes of testing.

Once Ganache is installed, we have to configure Truffle to be able to use it, and to do that we must edit the truffle.js file in the root of our project (Windows users must edit the accompanying truffle-config.js file instead). The following code tells Truffle how to communicate with Ganache. Note that it's possible Ganache will be configured with a different port, 7545, in which case the following port should be changed:

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

Before we can migrate our contracts, we must also add a further file to our project's migrations/ directory. When we initialized Truffle, a standard file called 1_initial_migration.js was generated, but this only provides a bootstrapping facility for the test framework.

We will create a new file, 2_deploy_contracts.js, and add the following code:

var PacktToken = artifacts.require('./PacktToken.sol');
var PacktTokenSale = artifacts.require('./PacktTokenSale.sol');

module.exports = function (deployer) {
deployer.deploy(PacktToken, 1000000).then(function () {
return deployer.deploy(
PacktTokenSale,
PacktToken.address,
1000000000000000);
});
};

This migration file takes the following actions:

  • It deploys the PacktToken contract, and passes in 1000000 as the total number of tokens to the constructor.
  • It then deploys the PacktTokenSale contract, and passes in the address of the token contract together with 1000000000000000 as the token price, in wei (this is equivalent to 0.001 ether per token).

We can now migrate our two contracts by running the following:

truffle migrate
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset