Chapter 1
DappToken.solpragma solidity >=0.4.22 <0.7.0;
contract DappToken {
// Initialize the smart contract with number of tokens available.
// To do this:
// Constructor
// Set the total number of tokens
// Read the total number of tokens
uint256 public totalSupply;
constructor () public {
totalSupply = 1000000;
}
}
contract DappToken {
// Initialize the smart contract with number of tokens available.
// To do this:
// Constructor
// Set the total number of tokens
// Read the total number of tokens
uint256 public totalSupply;
constructor () public {
totalSupply = 1000000;
}
}
2_deploy_contracts.js
const DappToken = artifacts.require("DappToken");
module.exports = function(deployer) {
deployer.deploy(DappToken);
};
module.exports = function(deployer) {
deployer.deploy(DappToken);
};
Set the ganache url in truffle-config.js
Then run:
truffle migrate
Start truffle console:
truffle console
In the console run:
DappToken.deployed().then(function(i) { token=i; })
Use of then:
Because of asynchronous nature of our smart contracts, developing them relies heavily on javascript promises
This wont' work: var token = DappToken.deployed()
truffle(development)> token.address
'0xB929B577ab8cb59B28d396fD8Ac559cb62001785'
'0xB929B577ab8cb59B28d396fD8Ac559cb62001785'
truffle(development)> token.totalSupply().then(function(s) { totalSupply = s;})
undefined
truffle(development)> totalSupply
BN {
negative: 0,
words: [ 1000000, <1 empty item> ],
length: 1,
red: null
}
truffle(development)> totalSupply.toNumber()
1000000
# To exit
truffle(development)> .exit
undefined
truffle(development)> totalSupply
BN {
negative: 0,
words: [ 1000000, <1 empty item> ],
length: 1,
red: null
}
truffle(development)> totalSupply.toNumber()
1000000
# To exit
truffle(development)> .exit
Tests
Truffle use mocha testing framework and chai assertion library
DappToken.js
const DappToken = artifacts.require("DappToken");
contract("DappToken", function(accounts) {
it("sets the total supply upon deployment", function() {
return DappToken.deployed()
.then(function(instance) {
tokenInstance = instance;
return tokenInstance.totalSupply();
})
.then(function(totalSupply) {
assert.equal(totalSupply.toNumber(), 1000000, "sets the total supply to 1,000,000");
});
});
});
contract("DappToken", function(accounts) {
it("sets the total supply upon deployment", function() {
return DappToken.deployed()
.then(function(instance) {
tokenInstance = instance;
return tokenInstance.totalSupply();
})
.then(function(totalSupply) {
assert.equal(totalSupply.toNumber(), 1000000, "sets the total supply to 1,000,000");
});
});
});
truffle test
Try changing the value to 9000000 in test, an see that it will fail.