Ethereum, tokens & smart contracts.

Notes on getting started : Part 12. Some advanced 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.
Part 11. Some intermediate considerations.

You made it ! this is the last set of notes on getting started with ehereum, tokens & smart contracts, before leaving I would like to touch on a few more advanced topics, some are somehow abstract and part of the business part and some are code, let’s look at them.

What the heck is an oracle ?

An oracle is a provider of external data to smart contracts, let’s say you want to have a smart contract release some funds or perform some other action when something in the external world happens ( a stock price, a business event, life ). Your first option is to manually signal the contract by calling a method or changing a variable:

// A child is born, so a nurse in the hospital calls a registry contract(pseudo code):
stKenosHospitalBirthRegistryContract.newBaby.call(name, weight, DOB, etc...);
// The contracts newBaby method could then transfer or allocate funds to a healthcare plan, a university plan and a life insurance plan for some bumper to bumper coverage.

Another option is to have a data service contract, we already made such a contract in the previous notes, (the contract that tells you this seasons hottest fashion color). Another example would be a government contract that sets the minimum and maximum price of gas, other contracts could watch this one to adjust their behavior and prices:

// A government sets a gas price(pseudo Code):
governmentGasPriceSetter.set.call($1);
// And other contracts watching:
if gasPrice >= $1 
taxiFarePriceSetter.setMinimumRide.call($20);
// In order to watch a contract you would need web3, events and filters or another complex interaction in between contracts.

A data service is currently considered an Oracle when the source of the data is a 3rd party that has arrived to it by some form of consensus, a simple example would be a vote :

//  1,000 fish go to the polls and vote via a smart contract that tallies the numbers:
400 - Patrick Star
300 - Sandy Cheeks
100 - Spongebob SquarePants
100 - Squidward tentacles
100 - Plankton and Karen
// And another one would then release some funds to the winner by reading the results.
campaign.payWinner.call(poll.winner, payout);

An oracle is not yet fully defined and it can mean different things to different people, but the above are usually considered common ground.

Further reading:

Time in Solidity:

Time in solidity is measured with timestamps:

pragma solidity ^0.4.0;
contract timeGetter {

function getBlockTime() public constant returns (uint) {
return block.timestamp;
}

function getNow() public constant returns (uint) {
return now; // an alias for block.timestamp
}
}
// getBlockTime() 1509561096
// getNow() 1509561096
// Both are UNIX Timestamps: https://www.unixtimestamp.com

In order to measure time periods or future dates, solidity has Time Units baked in:

pragma solidity ^0.4.0;
contract futureTime {

function getNow() public constant returns (uint) {
return now;
}

function getDayAfter() public constant returns (uint) {
return now + 1 days;
}

function getWeekAfter() public constant returns (uint) {
return now + 1 weeks;
}

}
// GetNow      1509603281
// getDayAfter 1509689682
// getWeekAfter1510208083

Solidity has no human readable timestamp converters ( arguably they are not needed since a contract can define and make operations with timestamps internally ) , so to make sense of the timestamp you would need to convert them yourself in your language of choice or use a contract library like (ethereum-datetime).

Note/Caveats: Miners can manipulate timestamps to a certain degree, ( in the seconds range ). Additionally there is no calendar time, so you would need to use an external library or oracle.

Distributing Tokens:

By far one of the most popular questions I’ve seen is how to distribute tokens or do mass operations with contracts.

The first options is to simply use a send, transfer or transferFrom transaction in one of your contracts or token:

// From the DOG Token in previous notes:
transfer(address, amount);
The cost is in between 50,000 - 80,000 wei, which translates to  about $0.015 - $0.023 per transfer. Transfers for 1,000 users using the high end would be around $23 for 10,000 $230 and so on at current (late 2017) prices.

You can further automate the transfers via an airdrop:

contract Airdrop {
function drop(ERC20 token, address[] recipients, uint256[] values) public {
for (uint256 i = 0; i < recipients.length; i++) {
token.transfer(recipients[i], values[i]);
}
}
}
// But your costs are the same if not slightly higher.

The ethereum recommended way is to delegate the responsability/costs to your users via the withdrawal pattern:

function withdraw() {
uint amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
// Costs are hard to calculate, but if you update a mapping or address/amount pairs, you are looking at about $0.008 everytime you do it, but the big advantage is you can update thousands of addresses in one go very economically.

With this pattern, you are in charge of asking your users to call your contract to withdraw their tokens or funds as well as keeping the pendingWithdrawals current.

You can also mix and match distribution patterns in your contract to suit your needs and Dapp or project budget.It should be noted that althought we have been talking about tokens and ether withdrawals, any mass or bulk computation is subject to the same costs and can be approached with a suitable pattern.

Truffle Boxes !

Let’s now switch gears and look at what an advanced Truffle Dapp setup would look like, we’ll be using a bit of everything covered so far and also take a look at Truffle Boxes ( which are billed as contract/Dapp templates ) to build a Dapp, to add an extra degree of dificulty ( this is the advanced section after all ), we’ll be using Angular in the form of the Quintor/angular-truffle-box.

Installing a Truffle Box is easy enough, just follow the Instructions ( make sure you make a new folder though as to not pollute your directory ), once installed you will have a few directories with contracts migrations,dependencies and source files for your Dapp...
Running the Truffle Box had some issues in my case I needed to sort out: 
- I got caught in between versions of Truffle and at first it wouldn't compile, upgrading to the latest Truffle Version solved that problem.
- There was no blockchain specified, so truffle.js had to be modified to:
module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
gas: 4600000,
network_id: "*" // Match any network id
}
}
};
- Additionally, there were Gas Problems, the above gas line solved them by increasing it generously, but you should fine tune the amount for main net deployment.

Once this setup issues have been solved, it’s time to fire up the Dapp ( in the default case a token called metaCoin), to do this 3 instances of your shell should be used, testrpc,truffle and angular:

One last bit of setup is MetaMask in your browser, just point it to testRPC and log in...And voila:

Now for the cool part, in your source files you will find an angular app, it might not be the flavor or architecture you are used to, but the important part is that you can live reload this Dapp, if you change say the css your browser will update your Dapp, pretty convenient.

Whether to use boxes or not is up to you, I think a team would benefit as well as an intermediate developer that wants to test a Dapp quickly, you can even make your own Boxes with your favorite stack.

Open Zeppelin.

So far we have been using minimal and base standard contracts for learning purposes, but in reality contracts are fast becoming complex software pieces full of dependencies,libraries and components. The open zepellin project is a popular framework for building smart contracts and Dapps and an example of complex contracts, let’s have a look…

Installing Open-zeppelin was a bit challenging…this is what worked for me after some trial and error:

$ mkdir awesomeProject && cd awesomeProject
$ npm init
$ truffle init
$ npm install zeppelin-solidity
$ truffle compile

The result is a new folder under node_modules inside your awesomeProject with a ton of useful contracts, this is how you would use them:

pragma solidity ^0.4.0;
import "../node_modules/zeppelin-solidity/contracts/token/MintableToken.sol";
contract superToken is MintableToken {
}

After that you can compile & migrate with truffle as usual.

The contracts are a mix of utility and templating mostly geared towards tokens, for instance here’s a sampling of the 38 or so ( at the time of this writing ) contracts you can use:

- crowdsale contracts: Capped, refundable and other base tokens ready for a crowd sale.
- lifecycle: Super handy contracts for upgrading,pausing & destroying contracts for instance.
- math: utility for safe math operations.
- ownership: Added functionality related to ownership, things like claiming,contacting, etc.
- payment: Just a pull payment contract for now.
- Token: A number of token templates to choose from. 
- Other: interesting contracts for various other functionalities.

These contract are considered high quality, have been audited ( more on that later) and while using them is up to you they are a good read and tool for upping your solidity programming skills or creating a more complex project, they are also free/open source which while awesome also ties you to their architecture to some degree, but again they are highly recommended, especially for an intermediate advanced developer.

Auditing & Security

The security considerations of smart contracts became painfully relevant by the recent theft of about $30 million worth of tokens due to a few lines of code, the stakes are high and the responsability lies within developers to audit their tokens and smart contracts to make them resilient to existing and future bugs or exploits of the ethereum platform, there’s a couple of things you can do from the start:

  • Follow best practices
  • Limit & test the information and control exposed through your contracts to the outside, particularly sensitive functions.
  • Use already audited and tested contracts like the ones from open Zeppellin as the base for your project.
  • Keep up with the community, if some new bug happens you want to know as fast as posible how it affects your code, also check for existing bugs.
  • And test, test test.

And lastly, if you are releasing a sizeable project and have the means, hire someone else to audit your contracts, as an example of what to expect when auditing a contract, here’s one from the Numerai project :

https://github.com/numerai/contract/blob/master/security_audit.pdf

Parting Words:

I hope that these notes helped you get started developing for the Ethereum platform as well as your understanding of smart contracts & tokens ; it is an exciting time to be involved in this new technology ( tech in general actually) and new and useful applications will hopefully arise out it… I sincerely wish you success in your projects and hope you can bring new and better things to this world…

Final Recap :

  • 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: 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.
  • Notes part 12: Some advanced considerations ( This post ) This last set of notes covered some advanced topics: oracles, time in solidity, token distributing strategies, truffle boxes and the Open Zepellin contracts to round up an introduction to Ethereum, smart contract and tokens, thanks !
✨✨  Now a 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 to get you or your team 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