Prototype a Crypto Smart Contract in 10 Minutes (In Solidity)
Want to build your own cryptocurrency? Want to have your own initial code offering? Here’s how to get up and running with a Solidity IDE for starters to know how to set up the logic in a smart contract.
Solidity is a “smart-contract oriented” programming language. A 4-year-old language designed to aide in the development of smart contracts for Ethereum based tokens. Basic understanding of object oriented concepts will help.
This should be the best source for learning Solidity: solidity.readthedocs.io
We’re building a smart contract.
Smart contracts have an address similar to how users can and can eventually be added to the Ethereum blockchain (and stay there forever!). This project is basically an Ethereum bank.
- Head to http://remix.ethereum.org and make a new project
2.
Usually in serious projects there would be a interface to inherit from, but for now we’ll build something rudimentary from scratch.
First, declare the source file compiler version the make your contract. It’s basically a class.
pragma solidity ^0.4.11; // Put this at the top. Version number.contract MyEthBank { // Essentially a class // Fill me with instance variables!
}
Coming up are some of the biggest power moves we can code. We are going to have to build instance variables for our contract.
- Declare the state variables outside functions, they persist throughout the life of contract
pragma solidity ^0.4.11;contract MyEthBank { mapping (address => uint) private balances; // Solidity's dictionary declaration. Below, this maps addresses to balances (unsigned integers) address public owner; // Address of the owner. 'public' makes externally readable (not writeable) by users or contracts uint constant totalSupply = 10**4; // 10,000 Eth Bank}
3.
Let’s make our constructor. A few things:
- msg provides details about the message that’s sent to the contract.
- msg.sender is contract caller (address of contract creator).
- We give the owner all the tokens.
- Add the payable keyword because Eth will be transfered.
When our contract is instantiated, we’re setting the total supply to the owner.
pragma solidity ^0.4.11;
contract MyEthBank {
mapping (address => uint) private balances;
address owner;
uint constant totalSupply = 10**4;function MyEthBank() public payable {
balances[msg.sender] = totalSupply;
owner = msg.sender;
}
}
4.
Let’s build functions that lets people pay in and get paid for working with our bank. (Basically, people can send us Ethereum to the contract, and we can send Ethereum to anyone of our choosing).
- Using the “payable” keyword is extremely important rather than building a function that takes a number of Ethereum. Payable reminds me of a decorator in the sense of automatically letting the function take an Ethereum amount and in the background handling insufficient balances and other mishaps.
- Anything in a payable method is atomic. It either happens completely, or doesn’t happen at all…
- The require keyword is a needed guard, rather than just building a conventional if guard…
The
require
function should be used to ensure valid conditions, such as inputs, or contract state variables are met, or to validate return values from calls to external contracts. If used properly, analysis tools can evaluate your contract to identify the conditions and function calls which will reach a failingassert
. Properly functioning code should never reach a failing assert statement; if this happens there is a bug in your contract which you should fix.
We do not need the payable keyword in our “send” method that withdraws. In this send method, we can choose the destination wallet and the amount we send Eth to.
pragma solidity ^0.4.11;
contract MyEthBank {
mapping (address => uint) private balances;
address owner;
uint constant totalSupply = 10**4;function MyEthBank() public payable {
balances[msg.sender] = totalSupply;
owner = msg.sender;
}
function deposit() public payable { // How Eth is received by bank
balances[owner] -= msg.value; // owner is bank
balances[msg.sender] += msg.value;
}
function send(uint amount, address addr) public { // How Eth is sent
if(amount >= 0) {
/* It is important to set this to zero because the recipient can call this function again as part of the receiving call before `transfer` returns (see the remark above about conditions -> effects -> interaction). */ addr.transfer(amount);
}
}
}
Test it!
In remix.ethereum.org, hit the compile tab and compile.
In the run tab, select Javascript VM. Hit the drop down for value, select Ether, and click create to make a mock address. I put 10 as a sample value.
Hit deposit and watch the account balance drop accordingly. In turn, the contract address will gain the 10 Eth.
If you hit Send, go to the dropdown, and choose another Account wallet, hit the copy icon to copy any other address to the clip board.
I put 10000000 wei, “0x14723a09acff6d2a60dcdf7aa4aff308fddc160c” (note the quotation marks).
The reason I put 10000000 in is because the default unit is wei, an absurd subdivision of Ethereum to several decimal places.
When you hit send, it’ll populate the recipient Remix address with Ethereum!
See code here: https://gist.github.com/NatuMyers/d4465cc25ec6a7e9b6dd05b5461b628a
Issues With Making this Production Ready
- Use the Checks-Effects-Interacts Pattern!
In the withdraw method I simply wrote:
require(amount <= this.balance);
addr.transfer(amount);
The withdrawal pattern is common. The issue is that a contracts can interact with contracts as well. A malicious contract that deliberately fails can prevent our contracted from working as desired.
2. Bad practice to have one owner who has all the money!
Problems with this approach is that it’s usually good to have one individual address with all the tokens, especially in a decentralized setting. For illustrative purposes, this can be seen as a potential way some people who fund raise for initial coin offerings can escape with funds. In future, breaking down the ownership of tokens to different variables is a good start.
Subscribe to this publication to keep up-to-date in how to build your own cryptocurrency by subscribing and clapping!
Get the notes I got from the silicon valley sent to you:
I’m freely giving out a hefty package of notes from Silicon Valley CEOs, to MBA’s on how to start a startup.
Over 50 Docs of Notes! (How to Market, Pitch and More in 50+documents)
Author: Natu Myers
(Website: Natumyers.com) (eBook: NatuBook.com)