
Ethereum, tokens & smart contracts.
Notes on getting started : Part 11. Some intermediate considerations.
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.
Part 6. Tokens & Inheritance.
Part 7. ERC20 Token Standard.
Part 8. Crowdfunding and ICOs.
Part 9. Dapps & MetaMask.
Part 10. Remix, Truffle, TestRPC.
So now that we have gotten to the metaphorical peak on understanding and getting started developing for the Ethereum ecosystem, I would like to finish wth a few intermediate subjects in this notes and some advanced ones in the next one to set you in the right path in case you want an opinionated path on where to go next, there’s also some high level and faq type considerations, let’s start.
Working with solidity function parameters in web3
For more complex contracts, sending and receiving parameters/arguments to your contract methods can be hard to grasp at first, let’s try with a set/get array contract:
pragma solidity ^0.4.0;contract SetGetArray { uint[] someNumbers; function getArray() public constant returns (uint[]) {
return someNumbers;
} function setArray(uint[] setNumbers) public { someNumbers = setNumbers; }}txHash:0x1cc74caab5c64c493a67cf8e3a8de656ba0db1d6f59c634e3c68e27a41afe7bf
Successfully deployed Contract with address: 0x1e1300614978efe2bf5c4b532daef69441314205
Let’s try now setting and getting the array through web3,this will require you to send an array as a parameter.
// File Setter.jsconsole.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./SetGetArray.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("0x1e1300614978efe2bf5c4b532daef69441314205");
var receiverAddress = '0x1e1300614978efe2bf5c4b532daef69441314205';var setNumbers = [5,2,4,1];
var setData = contract.setArray.getData(setNumbers);// console.log(setData);var gasEstimate = web3.eth.estimateGas({
from: web3.eth.coinbase,
to: receiverAddress,
data: setData
});var gasPrice = web3.eth.gasPrice;console.log('gas Price: ' + gasPrice);
console.log('Estimated Transaction gas: ' + gasEstimate);console.log('unlocking Coinbase account');
const password = "yourPassword";
try {
web3.personal.unlockAccount(web3.eth.coinbase, password);
} catch(e) {
console.log(e);
return;
}console.log ('sending Transaction to the contract');const transaction = {
from: web3.eth.coinbase,
to:receiverAddress,
value: '0x00',
gas: gasEstimate + 1,
gasPrice: gasPrice + 1,
data: setData
}web3.eth.sendTransaction( 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:
// 0x591ab8bf4b1fe6a81721d6ecab3b99b85248cd4302134c5a5674d9421a8612f6
And calling:
// File Caller.jsconsole.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./SetGetArray.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("0x1e1300614978efe2bf5c4b532daef69441314205");console.log ('calling contract');
var getArray = contract.getArray();
console.log('Get Array : ' + getArray);// Get Array : 5,2,4,1
// getArray[2] = 4See: https://ethereum.stackexchange.com/questions/8362/passing-an-array-as-a-parameter-from-javascrpt-web3-to-a-solidity-function for further discussion.
This example uses the getData() web3 method to convert the contract call (setArray) into bytecode with the array and other parameters, this is then used to a) estimate gas, and b) used as data when forming the transaction, importantly we don’t need to use the setArray method explicitly, just sendTransaction, the data: field tells the contract to use setArray.
Error handling: assert, require,revert,throw.
pragma solidity ^0.4.0;contract ErrorHandler { uint hundred = 100;
uint ten = 10;
uint[] testvals = [0,1,2,3]; function testAssert() public view returns (uint) {
assert(hundred > ten);
return testvals[1];
}
function testRequire() public view returns (uint) {
require(hundred > ten);
return testvals[2];
}}
The above code shows a simple example of assert and require, under the test condition (hundred > ten) both testAssert and testRequire return testvals (1,2). But when the test condition is false ( hundred < ten ), both fail, that is the line return testvals doesn’t get to execute, so you can use both to test for bugs inside of your contract logic.
There is a subtle difference in how both work, require is mostly for validating conditions, while assert tests for fringe cases you should fix.
Revert & Throw:When a transaction reverts, the state goes back to it’s original state, and ideally returns unused gas, you can also use it ( although it might be bad design beyond testing) to force the condition, throw; is the now deprecated version of revert(), but you might still see it here and there.
Can you kill a contract ?
In one word, no, contracts once added to the blockchain will remain there until the blockchain exists,what if you want to discontinue a contract ? you have a couple of options, change the internals so the contact no longer works, this would unfortunately make it into a black hole contract where Ether sent to it will remain there ( see the black hole contract in part 8.) but there is also another way, by adding a kill function ( experiment with it before deploying to mainnet to make sure it does what you want) :
function kill() {
if (msg.sender == creator)
suicide(creator);
}
// kills this contract and sends remaining funds back to creator
How to update a contract ?
So you have a token or other type of contract released in the blockchain, what if you discover a bug, want to add features or upgrade it, are you stuck with it forever? Well yes and no, the first thing you need to do is plan ahead and include some way to update your contract or reroute it or stop it should a bug be discovered, there is not a single way, some require the use of interfaces, while others depend on a Relay to forward calls, which in turn becomes problematic due to complexities in calling a contract from another contract, There is also storage and gas considerations, oh boy. I personally think that unless you are building something very complex, in which case I would question the need of a smart contract, you should refine your logic to account for updates and upgrades, consider the following case:
You are building a contract that tells you this seasons hottest color, a first try would maybe look like this:
pragma solidity ^0.4.0;contract season1 {string color = "Purple Haze"; function seasonColor() view public returns(string) {
return color;
}}// calling season1 seasonColor... Purple Haze.
When season 2 comes around, you could make a new contract…
pragma solidity ^0.4.0;contract season2 {string color = "Gunmetal Pink"; function seasonColor() view public returns(string) {
return color;
}}// calling season2 seasonColor... Gunmetal Pink.
The issue with this approach is that you will be required to change the address every season, this might not be an issue, but you could also try redesigning the contract for all upcoming seasons before going for one of the more complex solutions mentioned above…
pragma solidity ^0.4.0;contract seasons { string color;
address owner;
function seasons() public {
owner = msg.sender;
}function seasonColor() view public returns(string) {
return color;
}
function setSeasonColor(string newSeasonColor) public{
require(msg.sender == owner);
color = newSeasonColor;
}}
The above contract solves the problem by requiring the owner to set the new season color, minor modifications could be done to include a season number and to remember previous seasons, so the contract itself is not upgradable, but the information is.
Contract to contract interaction.
Like updating contracts, contract to contract interactions can either be a simple but limited affair or a complex situation, let’s explore a couple of ways contracts can interact between themselves.
- Sending ether from one contract to another : Using transfer()
pragma solidity ^0.4.0;contract TransferableEther{address owner;function TransferableEther() public{
owner = msg.sender;
}function transferEther(address forwardAddress, uint amount) public {
require(msg.sender == owner);
forwardAddress.transfer(amount);}function () public payable {}}// Deployed Contract: 0x522f9a0ccd60d46bcb143f16ba39425b408112c9

In this example done with parity to illustrate transfers, the contracts owner instructs the Transferable Contract ( which we funded with 0.50 eth ) to send .40 eth to another contract, the Tip Jar Token from a few notes ago.
So who pays? Whoever submits the transaction, in this case it would be the contracts owner (K3NOKOVAN), even though this account didn't receive any eth.
- Same ABI different contract.
This example is considerably more complex, to start we have 2 contracts:
pragma solidity ^0.4.0;contract Base {
uint number = 72;
function getNumber() view public returns (uint){
return number;
}
}
This contracts job is simply to archive some data ( the number 72 in this case ), and has but one method: a getter for the number (getNumber()).
Our second contract will read from a deployed Base contract’s method:
pragma solidity ^0.4.0;import "./Base.sol";contract A {
function getNumberAddress(address keyAddress) public constant returns (uint) {
Base baseInstance = Base(keyAddress);
return baseInstance.getNumber();
}}
The Import keyword allows you to include a contract ABI, but since this is like a blueprint, we still need to create an instance: Base baseInstance ( type name) and assign it to a deployed contract: Base(keyAddress). Finally, we can then call the method of the Base contract with baseInstance.getNumber(),this is how it would look like in Remix:

The utility of this arrangement in case it’s not apparent, is that you could deploy many Base contracts each with a different number and given an address you could query them all with the A contract, you could also modify the base contract’s variables and the A contract would still be able to read them, a spoke hub pattern if you will.
call
,callcode
anddelegatecall
Are Currently the last resort for writting interactions in between contracts, they come with even more limitations and technicalities than the previous 2 example and could be considered advanced methods, for instance to return a string from another contracts method you would write something like this:
contractInstance.call(bytes4(keccak256("method()"))
As mentioned this was a mix bag of intemediate Ethereum development things you might encounter, most of them involve either questioning architecture using smart contracts or using language specific features and should give you an idea of where to start and how to solve problems when there is no tutorials left to read, in the next notes we’ll look even further into what could be considered advanced ethereum development and other concepts and frameworks you might encounter.
Look down the road traveled :
- Notes Part 1 : Setting up : Getting a wallet/client , connecting to a test Ethereum blockchain and getting some test ether.
- Notes Part 2: web3.js/node : Interacting with the blockchain through web3.js and node for more convenience and ease of development.
- Notes Part 3: Solidity : Installing solidity (Ethereums contract writing language ) , Creating a very basic contract, compiling it, deploying it to the blockchain ( the test one) and interacting with it.
- Notes Part 4: Smart Contracts : We modified our simple contract so we could store and retrieve information (making it smart), in the process we also covered how to watch the blockchain and contracts and finally we took a look at gas and how to estimate it.
- Notes Part 5: Smarter Contracts: In order to allow contracts more complex behavior (make them smarter) , we need to delve a bit deeper into contract creation via constructors and a few more complex types which we will use in making a token contract.
- Notes Part 6: Tokens & Inheritance : We made our first Token and interacted with it by transferring some of it from one account to another, we also briefly covered inheritance which is used in more complex contracts.
- Notes Part 7: ERC20 Token Standard : We made and deployed an erc20 token which can be considered the parting standard for working sub currencies. We examined the code and talked about transfers in between tokens.
- Notes Part 8: Crowdfunding and ICOs : We explored the subject of crowdfunding via smart contracts in the form of ICOs and the exchange of ether for tokens, we made contracts that can receive ether, collect ether and can be used for exchanging ether and creating an unlimited supply of tokens.
- Notes Part 9: Dapps & MetaMask : We looked into what a Dapp is and where we are in terms of development ( very early), we then introduced MetaMask which helps make Dapps accessible in the browser , we looked at various ways to interact with MetaMask via Javascript and we integrated them into a fully fledged test Dapp that uses our previously made token smart contract, we also touched on the future of Dapps and server implementations.
- Notes part 10: Remix/Truffle/TestRPC: A look into Ethereums current tooling ecosystem, Remix, which allows you to quickly validate contracts online, TestRPC which recreates an offline blockchain in your computer, and Truffle, which has a bit of a learning curve in exchange for complex testing and deploying options.
- Notes part 11: Some intermediate considerations (This post): Using some of the previous foundational knowledge I went over a few intermediate considerations, working with function parameters & web3, error handling, killing a contract, updating a contract (or not) and contract to contract interactions.

✨✨ Buy the Book ! ✨✨If you are looking for an introduction to Ethereum, Solidity and Smart Contracts these notes were edited and revised into a book, a super convenient way for you to get started!Available in ebook and paperback:https://www.amazon.com/dp/B078CQ8L7V 🙏 🙏 😊 🙏 🙏
Cheers !
Keno
About the Author :
Born Eugenio Noyola Leon (Keno) I am a Designer,Web Developer/programmer, Artist and Inventor, currently living in Mexico City, you can find me at www.k3no.com