Ethereum, tokens & smart contracts.

Notes on getting started Part 6. Tokens & Inheritance

Previous notes in case you are just joining us:
Part 1. Setting up.
Part 2. Web3.js/node.
Part 3. Solidity.
Part 4. Smart Contracts.
Part 5. Smarter Contracts.
// FILE : minimalToken.solpragma solidity ^0.4.0;contract minimalToken {/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* Initializes contract with initial supply tokens to the creator of the contract */
function minimalToken(uint256 initialSupply) {
balanceOf[msg.sender] = initialSupply;
}
/* Send coins */ function transfer(address _to, uint256 _value) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Check for overflows
balanceOf[msg.sender] -= _value;
// Subtract from the sender
balanceOf[_to] += _value;
// Add the same to the recipient
}
}
Note: As per out constructor we need to initialize the number of minimalTokens we have, so when deploying our contract we need to add that as a parameter:const contractInstance = contract.new(10000, {
data: '0x' + bytecode,
from: web3.eth.coinbase,
gasPrice: gasPrice + 1,
gas: gasEstimate + 1000000
}

Deploying contract...
txHash:0xdaad8e547848a6e04daeeb808aa328b309ea56bf1e8bcbe5a0ae4186f0893472
Successfully deployed Contract with address: 0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0
console.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./minimalToken.json");
console.log('Connecting');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log('Creating contract instance');
const contract = web3.eth.contract(contractABI);
var contractInstance = contract.at("0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0");
console.log ('calling contract');
var tokenBalance = contractInstance.balanceOf(web3.eth.coinbase);
console.log('Your tokens balance is :' + tokenBalance);
// Your tokens balance is :10000
FILE: callContractTransaction.jsconsole.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./minimalToken.json");
console.log('Connecting');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log('Creating contract instance');// Note the condensed contractInstance:var contract = web3.eth.contract(contractABI).at("0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0");
var receiverAddress = '0x00Ce6C92856A657979E7728005DBc9acD002Eb09';
// Dry run to estimate Gas:var callData = contract.transfer.getData(receiverAddress, 2000);var gasEstimate = web3.eth.estimateGas({
from: web3.eth.coinbase,
to: "0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0",
data: callData
});
var gasPrice = web3.eth.gasPrice;console.log('gas Price: ' + gasPrice);
console.log('Estimated Transaction gas: ' + gasEstimate);
console.log('unlocking Coinbase account');
const password = "your_password";
try {
web3.personal.unlockAccount(web3.eth.coinbase, password);
} catch(e) {
console.log(e);
return;
}
console.log ('sending Transaction to the contract');// For Real this time: const transaction = {
from: web3.eth.coinbase,
gas: gasEstimate + 1,
gasPrice: gasPrice + 1
}
contract.transfer.sendTransaction(receiverAddress, 2000, transaction, function(err, txHash) {
if (err != null) {
console.error("Error while sending transaction: " + err);
}
else{
console.log("Transaction Sent here's you txHash: " + txHash);
}
});
...Transaction Sent here's you  txHash:
0x8d0a0c35c45bb39d6d386b9d23216b85ad7bf86d237ab6e1acc58fcdc6133777

Inheritance in Solidity

// FILE: inheritContract.solpragma solidity ^0.4.0;contract animalContract {
function doSomething() returns (bytes32) {
return "eat, sleep";
}
}
contract catContract is animalContract{}
// abridged from compilerMK2.js:let input = fs.readFileSync(dir + '/inheritContract.sol');const bytecode = output.contracts[':catContract'].bytecode;
const abi = output.contracts[':catContract'].interface;
fs.writeFileSync(dir + "/catContract.json", abi)txHash:0x8b138df59cd99becd2b7966f43309f1bc0d1f067e5ec4aa5ce1845abe1204d1a
Successfully deployed Contract with address: 0xed1c09d2cc09098c1597b0864156be258852a506
FILE : callContractMK2.js:console.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./catContract.json");
console.log('Connecting');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log('Creating contract instance');
var contract = web3.eth.contract(contractABI).at("0xed1c09d2cc09098c1597b0864156be258852a506");
console.log ('calling contract');
var does = contract.doSomething.call();
console.log('Cat does : ' + web3.toAscii(does));
//calling contract
//Cat does : eat, sleep

Abstract Contracts:

//FILE: abstractContract.solpragma solidity ^0.4.0;contract animalContract {
function doSomething() returns (bytes32);
}
contract dogContract is animalContract {
function doSomething() returns (bytes32){
return "eat, sleep, woofs";
}
}
contract catContract is animalContract {
function doSomething() returns (bytes32){
return "eat, sleep, meows";
}
}

Interfaces:

pragma solidity ^0.4.0;interface animalContract {
function doSomething() returns (bytes32);
function isAlive() returns (bool);
}
contract dogContract is animalContract {
function doSomething() returns (bytes32){
return "eat, sleep, woofs";
}
function isAlive() returns (bool){
return true;
}
}contract catContract is animalContract {
function doSomething() returns (bytes32){
return "eat, sleep, meows";
}
function isAlive() returns (bool){
return true;
}
}

Few extra odds & ends:

external: Can be called by other contracts.public: (Default) Can be called internally or via messages. Public state variables automatically create a getter.internal:Visible within contract and derived contracts.private: Only visible within contract, not derived ones. Note: These visibility settings only affect contract to contract visibility.Temporary warning: You can also use the dreaded this to override behavior,but I would avoid it for now unless you know exactly what this is, to complicate matters more, this can refer to a function or a variable depending on context.
pragma solidity ^0.4.0;contract numbers {
uint number1 = 1;
uint public number2 = 2;
uint private number3 = 3;
uint internal number4 = 4;
}
contract myNumber is numbers{
function listNumber() returns (uint){
// return number1; // 1
// return number2; // 2
// return number3; unexpected identifier
// return number4; // 4
}
}
contract myNumber is numbers{
function listNumber() returns (uint){
return numbers.number1; // 1
}
}
Compiling ":myNumber"...
Successfully deployed Contract with address: 0x016e8ffa71c1a4e60109615318854aec1b9490ff
// call contract:// From uint public number2 = 2; var ListNumber = contract.number2();
console.log('Listing Number : ' + ListNumber);
// calling contract
// Listing Number : 2

Expression & control structures.

Now a book ! I repeat buy the book ! 😎If you are looking for an introduction to Ethereum, Solidity and Smart Contracts these notes were edited and revised into a convenient book with easy to run code included !Available in ebook and paperback here:https://www.amazon.com/dp/B078CQ8L7V

AI, Software Developer, Designer : www.k3no.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store