Image for post
Image for post

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.

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.
// 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.
//  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);

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
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
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.

// 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.
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.
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.

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...
Image for post
Image for post
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.
Image for post
Image for post
One last bit of setup is MetaMask in your browser, just point it to testRPC and log in...And voila:
Image for post
Image for post

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…

$ mkdir awesomeProject && cd awesomeProject
$ npm init
$ truffle init
$ npm install zeppelin-solidity
$ truffle compile
pragma solidity ^0.4.0;import "../node_modules/zeppelin-solidity/contracts/token/MintableToken.sol";contract superToken is MintableToken {}
- 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.

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:

  • 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.

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 !
Image for post
Image for post
✨✨  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    🙏 🙏 😊 🙏 🙏

Written by

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