learnxinyminutes-docs/solidity.html.markdown

751 lines
22 KiB
Markdown
Raw Normal View History

2015-11-23 21:02:00 +00:00
---
language: Solidity
filename: learnSolidity.sol
contributors:
- ["Nemil Dalal", "https://www.nemil.com"]
---
2015-12-28 22:11:00 +00:00
Solidity lets you program on [Ethereum](https://www.ethereum.org/), a
blockchain-based virtual machine that allows the creation and
computation of smart contracts, without needing centralized or trusted parties.
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
Solidity is a statically typed, contract programming language that has
similarities to Javascript and C. Like objects in OOP, each contract contains
state variables, functions, and common data types. Contract-specific features
include modifier (guard) clauses, event notifiers for listeners, and custom
global variables.
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
Some Ethereum contract examples include crowdfunding, voting, and blind auctions.
As Solidity and Ethereum are under active development, experimental or beta
features are explicitly marked, and subject to change. Pull requests welcome.
2015-11-23 21:02:00 +00:00
```javascript
2015-12-28 22:11:00 +00:00
// First, a simple Bank contract
// Allows deposits, withdrawals, and balance checks
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// simple_bank.sol (note .sol extension)
/* **** START EXAMPLE **** */
// Start with Natspec comment (the three slashes)
// used for documentation - and as descriptive data for UI elements/actions
/// @title SimpleBank
/// @author nemild
/* 'contract' has similarities to 'class' in other languages (class variables,
inheritance, etc.) */
contract SimpleBank { // CamelCase
// Declare state variables outside function, persist through life of contract
// dictionary that maps addresses to balances
2015-11-30 22:23:41 +00:00
mapping (address => uint) private balances;
2015-11-30 20:45:03 +00:00
2015-12-28 22:11:00 +00:00
// "private" means that other contracts can't directly query balances
// but data is still viewable to other parties on blockchain
2015-11-30 20:45:03 +00:00
address public owner;
2015-12-28 22:11:00 +00:00
// 'public' makes externally readable (not writeable) by users or contracts
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Events - publicize actions to external listeners
event DepositMade(address accountAddress, uint amount);
// Constructor, can receive one or many variables here; only one allowed
2015-11-23 21:02:00 +00:00
function AcmeBank() {
2015-12-28 22:11:00 +00:00
// msg provides contract messager's address and amount
// msg.sender is contract caller (address of contract creator)
owner = msg.sender;
2015-11-23 21:02:00 +00:00
}
2015-11-30 20:45:03 +00:00
2015-12-28 22:11:00 +00:00
/// @notice Deposit ether into bank
/// @return The balance of the user after the deposit is made
function deposit() public returns (uint) {
balances[msg.sender] += msg.value;
// no "this." or "self." required with state variable
// all values initialized to 0 by default
DepositMade(msg.sender, msg.value); // fire event
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
return balances[msg.sender];
2015-11-23 21:02:00 +00:00
}
2015-12-28 22:11:00 +00:00
/// @notice Withdraw ether from bank
/// @dev This does not return any excess ether sent to it
/// @param withdrawAmount amount you want to withdraw
/// @return The balance remaining for the user
function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
if(balances[msg.sender] >= withdrawAmount) {
balances[msg.sender] -= withdrawAmount;
2015-11-23 21:07:17 +00:00
2015-11-24 05:09:10 +00:00
if (!msg.sender.send(withdrawAmount)) {
2015-12-28 22:11:00 +00:00
balances[msg.sender] += withdrawAmount; // to be safe
2015-11-23 21:07:17 +00:00
}
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
return balances[msg.sender];
2015-11-23 21:02:00 +00:00
}
}
2015-12-28 22:11:00 +00:00
/// @notice Get balance
/// @return The balance of the user
// 'constant' prevents function from editing state variables;
// allows function to run locally/off blockchain
2015-12-11 18:07:01 +00:00
function balance() constant returns (uint) {
2015-12-28 22:11:00 +00:00
return balances[msg.sender];
2015-11-23 21:02:00 +00:00
}
2015-12-28 22:11:00 +00:00
// Fallback function - Called if other functions don't match call or
// sent ether without data
// Typically, called when invalid data is sent
// Added so ether sent to this contract is reverted if the contract fails
// otherwise, the sender's money is transferred to contract
function () {
throw; // throw reverts state to before call
}
2015-11-23 21:02:00 +00:00
}
2015-11-30 20:45:03 +00:00
// ** END EXAMPLE **
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Now, the basics of Solidity
2015-11-30 20:48:47 +00:00
// 1. DATA TYPES AND ASSOCIATED METHODS
2015-12-28 22:11:00 +00:00
// uint used for currency amount (there are no doubles
// or floats) and for dates (in unix time)
2015-11-30 20:45:03 +00:00
uint x;
// int of 256 bits, cannot be changed after instantiation
int constant a = 8;
2015-12-28 22:11:00 +00:00
// with 'constant', compiler replaces each occurrence with actual value
2015-11-30 21:01:51 +00:00
int256 constant a = 8; // same effect as line above, here the 256 is explicit
2015-12-11 18:07:01 +00:00
uint constant VERSION_ID = 0x123A1; // A hex constant
2015-11-30 20:45:03 +00:00
2015-12-28 22:11:00 +00:00
// Be careful that you don't overflow, and protect against attacks that do
// For int and uint, can explicitly set space in steps of 8 up to 256
// e.g., int8, int16, int24
2015-11-23 21:02:00 +00:00
uint8 b;
int64 c;
uint248 e;
2015-12-28 22:11:00 +00:00
// No random functions built in, use other contracts for randomness
2015-11-23 21:02:00 +00:00
// Type casting
2015-11-30 20:45:03 +00:00
int x = int(b);
2015-11-23 21:02:00 +00:00
bool b = true; // or do 'var b = true;' for inferred typing
2015-12-28 22:11:00 +00:00
// Addresses - holds 20 byte/160 bit Ethereum addresses
// No arithmetic allowed
address public owner;
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Types of accounts:
// Contract account: address set on create (func of creator address, num transactions sent)
// External Account: (person/external entity): address created from public key
// Add 'public' field to indicate publicly/externally accessible
// a getter is automatically created, but NOT a setter
// All addresses can be sent ether
2015-11-23 21:02:00 +00:00
owner.send(SOME_BALANCE); // returns false on failure
2015-12-28 22:11:00 +00:00
if (owner.send) {} // typically wrap in 'if', as contract addresses have
// functions have executed on send and can fail
// can override send by defining your own
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Can check balance
owner.balance; // the balance of the owner (user or contract)
// Bytes available from 1 to 32
2015-11-23 21:02:00 +00:00
byte a; // byte is same as bytes1
2015-12-28 22:11:00 +00:00
bytes2 b;
bytes32 c;
// Dynamically sized bytes
bytes m; // A special array, same as byte[] array (but packed tightly)
// More expensive than byte1-byte32, so use those when possible
2015-11-23 21:02:00 +00:00
// same as bytes, but does not allow length or index access (for now)
2015-12-28 22:11:00 +00:00
string n = "hello"; // stored in UTF8, note double quotes, not single
// string utility functions to be added in future
// prefer bytes32/bytes, as UTF8 uses more storage
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Type inferrence
2015-11-30 20:45:03 +00:00
// var does inferred typing based on first assignment,
2015-11-23 21:02:00 +00:00
// can't be used in functions parameters
var a = true;
2015-12-28 22:11:00 +00:00
// use carefully, inference may provide wrong type
// e.g., an int8, when a counter needs to be int16
// var can be used to assign function to variable
function a(uint x) returns (uint) {
return x * 2;
}
var f = a;
f(22); // call
2015-11-23 21:02:00 +00:00
// by default, all values are set to 0 on instantiation
2015-11-30 22:23:41 +00:00
// Delete can be called on most types
2015-12-28 22:11:00 +00:00
// (does NOT destroy value, but sets value to 0, the initial value)
2015-11-23 21:02:00 +00:00
uint x = 5;
2015-12-28 22:11:00 +00:00
// Destructuring/Tuples
(x, y) = (2, 7); // assign/swap multiple value
2015-11-23 21:02:00 +00:00
2015-11-30 20:48:47 +00:00
2015-11-23 21:02:00 +00:00
// 2. DATA STRUCTURES
// Arrays
2015-11-30 20:45:03 +00:00
bytes32[5] nicknames; // static array
bytes32[] names; // dynamic array
2015-11-23 21:02:00 +00:00
uint newLength = names.push("John"); // adding returns new length of the array
// Length
names.length; // get length
2015-12-28 22:11:00 +00:00
names.length = 1; // lengths can be set (for dynamic arrays in storage only)
// multidimensional array
uint x[][5]; // arr with 5 dynamic array elements (opp order of most languages)
2015-11-23 21:02:00 +00:00
// Dictionaries (any type to any other type)
2015-11-24 05:09:10 +00:00
mapping (string => uint) public balances;
2015-12-28 22:11:00 +00:00
balances["charles"] = 1;
console.log(balances["ada"]); // is 0, all non-set key values return zeroes
// 'public' allows following from another contract
contractName.balances("claude"); // returns 1
// 'public' created a getter (but not setter) like the following:
2015-11-23 21:02:00 +00:00
function balances(address _account) returns (uint balance) {
2015-12-28 22:11:00 +00:00
return balances[_account];
2015-11-23 21:02:00 +00:00
}
2015-12-28 22:11:00 +00:00
// Nested mappings
mapping (address => mapping (address => uint) balances) public custodians;
2015-11-23 21:02:00 +00:00
// To delete
2015-11-30 22:23:41 +00:00
delete balances["John"];
2015-12-28 22:11:00 +00:00
delete balances; // sets all elements to 0
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Unlike other languages, CANNOT iterate through all elements in
// mapping, without knowing source keys - can build data structure
// on top to do this
2015-11-23 21:02:00 +00:00
2015-11-30 20:45:03 +00:00
// Structs and enums
2015-12-28 22:11:00 +00:00
struct Bank {
address owner;
uint balance;
}
2015-11-23 21:02:00 +00:00
Bank b = Bank({
2015-12-28 22:11:00 +00:00
owner: msg.sender,
balance: 5
2015-11-23 21:02:00 +00:00
});
2015-12-28 22:11:00 +00:00
// or
Bank c = Bank(msg.sender, 5);
c.amount = 5; // set to new value
delete b;
// sets to initial value, set all variables in struct to 0, except mappings
2015-11-23 21:02:00 +00:00
// Enums
2015-12-28 22:11:00 +00:00
enum State { Created, Locked, Inactive }; // often used for state machine
2015-11-23 21:02:00 +00:00
State public state; // Declare variable from enum
state = State.Created;
2015-11-30 20:45:03 +00:00
// enums can be explicitly converted to ints
2015-12-28 22:11:00 +00:00
uint createdState = uint(State.Created); // 0
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Data locations: Memory vs. storage vs. stack - all complex types (arrays,
// structs) have a data location
2015-11-30 20:45:03 +00:00
// 'memory' does not persist, 'storage' does
2015-12-28 22:11:00 +00:00
// Default is 'storage' for local and state variables; 'memory' for func params
// stack holds small local variables
// for most types, can explicitly set which data location to use
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// 3. Simple operators
// Comparisons, bit operators and arithmetic operators are provided
// exponentiation: **
// exclusive or: ^
// bitwise negation: ~
2015-11-30 20:48:47 +00:00
2015-12-28 22:11:00 +00:00
// 4. Global Variables of note
2015-11-30 20:45:03 +00:00
// ** this **
2015-12-28 22:11:00 +00:00
this; // address of contract
// often used at end of contract life to send remaining balance to party
2015-11-30 20:45:03 +00:00
this.balance;
2015-12-28 22:11:00 +00:00
this.someFunction(); // calls func externally via call, not via internal jump
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// ** msg - Current message received by the contract ** **
msg.sender; // address of sender
msg.value; // amount of gas provided to this contract in wei
2015-11-30 20:45:03 +00:00
msg.data; // bytes, complete call data
msg.gas; // remaining gas
2015-11-23 21:02:00 +00:00
2015-11-30 20:45:03 +00:00
// ** tx - This transaction **
2015-12-28 22:11:00 +00:00
tx.origin; // address of sender of the transaction
tx.gasprice; // gas price of the transaction
// ** block - Information about current block **
now // current time (approximately), alias for block.timestamp (uses Unix time)
block.number; // current block number
block.difficulty; // current block difficulty
block.blockhash(1); // returns bytes32, only works for most recent 256 blocks
2015-11-30 20:45:03 +00:00
block.gasLimit();
2015-12-28 22:11:00 +00:00
// ** storage - Persistent storage hash **
2015-11-30 20:45:03 +00:00
storage['abc'] = 'def'; // maps 256 bit words to 256 bit words
2015-11-23 21:02:00 +00:00
2015-11-30 20:48:47 +00:00
2015-11-23 21:02:00 +00:00
// 4. FUNCTIONS AND MORE
// A. Functions
// Simple function
function increment(uint x) returns (uint) {
2015-12-28 22:11:00 +00:00
x += 1;
return x;
2015-11-23 21:02:00 +00:00
}
2015-12-28 22:11:00 +00:00
// Functions can return many arguments, and by specifying returned arguments
// name don't need to explicitly return
2015-11-23 21:02:00 +00:00
function increment(uint x, uint y) returns (uint x, uint y) {
2015-12-28 22:11:00 +00:00
x += 1;
y += 1;
2015-11-23 21:02:00 +00:00
}
2015-12-28 22:11:00 +00:00
// Call previous functon
2015-11-23 21:02:00 +00:00
uint (a,b) = increment(1,1);
2015-12-28 22:11:00 +00:00
// 'constant' indicates that function does not/cannot change persistent vars
// Constant function execute locally, not on blockchain
2015-11-23 21:02:00 +00:00
uint y;
function increment(uint x) constant returns (uint x) {
2015-12-28 22:11:00 +00:00
x += 1;
y += 1; // this line would fail
// y is a state variable, and can't be changed in a constant function
2015-11-23 21:02:00 +00:00
}
2015-12-28 22:11:00 +00:00
// 'Function Visibility specifiers'
// These can be placed where 'constant' is, including:
// public - visible externally and internally (default)
// external
2015-11-23 21:02:00 +00:00
// private - only visible in the current contract
2015-12-28 22:11:00 +00:00
// internal - only visible in current contract, and those deriving from it
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Functions hoisted - and can assign a function to a variable
2015-11-23 21:02:00 +00:00
function a() {
2015-12-28 22:11:00 +00:00
var z = b;
b();
2015-11-23 21:02:00 +00:00
}
function b() {
}
2015-12-28 22:11:00 +00:00
// Prefer loops to recursion (max call stack depth is 1024)
2015-11-23 21:02:00 +00:00
// B. Events
2015-12-28 22:11:00 +00:00
// Events are notify external parties; easy to search and
// access events from outside blockchain (with lightweight clients)
// typically declare after contract parameters
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Declare
event Sent(address from, address to, uint amount); // note capital first letter
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Call
Sent(from, to, amount);
// For an external party (a contract or external entity), to watch:
2015-11-23 21:02:00 +00:00
Coin.Sent().watch({}, '', function(error, result) {
if (!error) {
console.log("Coin transfer: " + result.args.amount +
" coins were sent from " + result.args.from +
" to " + result.args.to + ".");
console.log("Balances now:\n" +
"Sender: " + Coin.balances.call(result.args.from) +
"Receiver: " + Coin.balances.call(result.args.to));
}
}
2015-12-28 22:11:00 +00:00
// Common paradigm for one contract to depend on another (e.g., a
// contract that depends on current exchange rate provided by another)
2015-11-23 21:02:00 +00:00
// C. Modifiers
2015-12-28 22:11:00 +00:00
// Modifiers validate inputs to functions such as minimal balance or user auth;
// similar to guard clause in other languages
2015-11-30 20:45:03 +00:00
2015-12-28 22:11:00 +00:00
// '_' (underscore) often included as last line in body, and indicates
2015-11-23 21:02:00 +00:00
// function being called should be placed there
2015-12-11 18:07:01 +00:00
modifier onlyAfter(uint _time) { if (now <= _time) throw; _ }
modifier onlyOwner { if (msg.sender == owner) _ }
2015-12-28 22:11:00 +00:00
// commonly used with state machines
modifier onlyIfState (State currState) { if (currState != State.A) _ }
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Append right after function declaration
2015-11-30 20:45:03 +00:00
function changeOwner(newOwner)
2015-12-11 18:07:01 +00:00
onlyAfter(someTime)
onlyOwner()
2015-12-28 22:11:00 +00:00
onlyIfState(State.A)
2015-12-11 18:07:01 +00:00
{
2015-12-28 22:11:00 +00:00
owner = newOwner;
2015-11-23 21:02:00 +00:00
}
2015-12-28 22:11:00 +00:00
// underscore can be included before end of body,
// but explicitly returning will skip, so use carefully
modifier checkValue(uint amount) {
_
if (msg.value > amount) {
msg.sender.send(amount - msg.value);
}
}
2015-11-30 20:48:47 +00:00
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// 6. BRANCHING AND LOOPS
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// All basic logic blocks work - including if/else, for, while, break, continue
// return - but no switch
2015-11-30 20:45:03 +00:00
2015-12-28 22:11:00 +00:00
// Syntax same as javascript, but no type conversion from non-boolean
// to boolean (comparison operators must be used to get the boolean val)
2015-11-30 20:48:47 +00:00
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// 7. OBJECTS/CONTRACTS
// A. Calling external contract
2015-11-23 21:02:00 +00:00
contract infoFeed {
2015-12-28 22:11:00 +00:00
function info() returns (uint ret) { return 42; }
2015-11-23 21:02:00 +00:00
}
contract Consumer {
2015-12-28 22:11:00 +00:00
InfoFeed feed; // points to contract on blockchain
// Set feed to existing contract instance
function setFeed(address addr) {
// automatically cast, be careful; constructor is not called
feed = InfoFeed(addr);
}
// Set feed to new instance of contract
function createNewFeed() {
feed = new InfoFeed(); // constructor called
}
function callFeed() {
// final parentheses call contract, can optionally add
// custom ether value or gas
feed.info.value(10).gas(800)();
}
2015-11-23 21:02:00 +00:00
}
2015-11-30 20:45:03 +00:00
// B. Inheritance
2015-12-28 22:11:00 +00:00
// Order matters, last inherited contract (i.e., 'def') can override parts of
// previously inherited contracts
contract MyContract is abc, def("a custom argument to def") {
2015-11-30 20:45:03 +00:00
// Override function
2015-12-28 22:11:00 +00:00
function z() {
if (msg.sender == owner) {
def.z(); // call overridden function from def
super.z(); // call immediate parent overriden function
}
2015-11-30 20:45:03 +00:00
}
2015-12-28 22:11:00 +00:00
}
2015-11-30 20:45:03 +00:00
2015-12-28 22:11:00 +00:00
// abstract function
function someAbstractFunction(uint x);
// cannot be compiled, so used in base/abstract contracts
// that are then implemented
2015-11-30 20:45:03 +00:00
// C. Import
import "filename";
import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol";
2015-12-28 22:11:00 +00:00
// Importing under active development
// Cannot currently be done at command line
2015-11-23 21:02:00 +00:00
2015-12-28 22:13:20 +00:00
2015-12-28 22:11:00 +00:00
// 8. OTHER KEYWORDS
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// A. Throwing
2015-11-23 21:02:00 +00:00
// Throwing
2015-12-28 22:11:00 +00:00
throw; // reverts unused money to sender, state is reverted
// Can't currently catch
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Common design pattern is:
2015-11-23 21:02:00 +00:00
if (!addr.send(123)) {
2015-12-28 22:11:00 +00:00
throw;
2015-11-23 21:02:00 +00:00
}
2015-12-28 22:11:00 +00:00
// B. Selfdestruct
// selfdestruct current contract, sending funds to address (often creator)
selfdestruct(SOME_ADDRESS);
// removes storage/code from current/future blocks
// helps thin clients, but previous data persists in blockchain
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// Common pattern, lets owner end the contract and receive remaining funds
2015-11-30 20:45:03 +00:00
function remove() {
2015-12-28 22:11:00 +00:00
if(msg.sender == creator) { // Only let the contract creator do this
selfdestruct(creator); // Makes contract inactive, returns funds
}
2015-11-30 20:45:03 +00:00
}
2015-12-28 22:11:00 +00:00
// May want to deactivate contract manually, rather than selfdestruct
// (ether sent to selfdestructed contract is lost)
// 9. CONTRACT DESIGN NOTES
// A. Obfuscation
// Remember all variables are publicly viewable on blockchain, so
// anything that needs privacy needs to be obfuscated (e.g., hashed)
// Steps: 1. Commit to something, 2. Reveal commitment
sha3("some_bid_amount", "some secret"); // commit
// call contract's reveal function showing bid plus secret that hashes to SHA3
reveal(100, "mySecret");
// B. Storage optimization
// Writing to blockchain can be expensive, as data stored forever encourages
// smart ways to use memory (eventually, compilation will be better, but for now
// benefits to planning data structures - and storing min amount in blockchain)
// Cost can often be high for items like multidimensional arrays
// (cost is for storing data - not declaring unfilled variables)
// C. Cannot restrict human or computer from reading contents of
// transaction or transaction's state
// When 'private' specified, indicating that other *contracts* can't read
// the data directly - any other party can still read the data in blockchain
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// D. All data to start of time is stored in blockchain, so
// anyone can observe all previous data and changes
2015-11-30 20:48:47 +00:00
2015-12-28 22:11:00 +00:00
// E. Cron
// Contracts must be manually called to handle time-based scheduling; can create
// external code to do, or provide incentives (ether) for others to do for you
2015-11-30 20:45:03 +00:00
2015-12-28 22:11:00 +00:00
// F. State machines
// see example below for State enum and inState modifier
2015-12-28 22:13:20 +00:00
2015-12-28 22:11:00 +00:00
// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) ***
2015-11-30 20:45:03 +00:00
// ** START EXAMPLE **
2015-12-28 22:11:00 +00:00
// CrowdFunder.sol
/// @title CrowdFunder
/// @author nemild
contract CrowdFunder {
// Variables set on create by creator
address public creator;
address public fundRecipient; // creator may be different than recipient
uint public minimumToRaise; // required to tip, else everyone gets refund
string campaignUrl;
// Data structures
enum State {
Fundraising,
ExpiredRefundPending,
Successful,
ExpiredRefundComplete
}
struct Contribution {
uint amount;
address contributor;
2015-11-30 21:51:53 +00:00
}
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// State variables
State public state = State.Fundraising; // initialize on create
uint public totalRaised;
uint public raiseBy;
Contribution[] contributions;
event fundingReceived(address addr, uint amount, uint currentTotal);
event allRefundsSent();
event winnerPaid(address winnerAddress);
modifier inState(State _state) {
if (state != _state) throw;
_
}
2015-11-30 20:48:47 +00:00
2015-12-28 22:11:00 +00:00
modifier isCreator() {
if (msg.sender != creator) throw;
_
}
modifier atEndOfLifecycle() {
if(state != State.ExpiredRefundComplete && state != State.Successful) {
throw;
}
}
function CrowdFunder(
uint timeInHoursForFundraising,
string _campaignUrl,
address _fundRecipient,
uint _minimumToRaise)
{
creator = msg.sender;
fundRecipient = _fundRecipient;
campaignUrl = _campaignUrl;
minimumToRaise = _minimumToRaise;
raiseBy = now + (timeInHoursForFundraising * 1 hours);
}
function contribute()
public
inState(State.Fundraising)
{
contributions.push(
Contribution({
amount: msg.value,
contributor: msg.sender
}) // use array, so can iterate
);
totalRaised += msg.value;
fundingReceived(msg.sender, msg.value, totalRaised);
checkIfFundingCompleteOrExpired();
}
function checkIfFundingCompleteOrExpired() {
if (totalRaised > minimumToRaise) {
state = State.Successful;
payOut();
// could incentivize sender who initiated state change here
} else if ( now > raiseBy ) {
state = State.ExpiredRefundPending;
refundAll();
}
}
function payOut()
public
inState(State.Successful)
{
if(!fundRecipient.send(this.balance)) {
throw;
}
winnerPaid(fundRecipient);
}
function refundAll()
public
inState(State.ExpiredRefundPending)
{
uint length = contributions.length;
for (uint i = 0; i < length; i++) {
if(!contributions[i].contributor.send(contributions[i].amount)) {
throw;
}
}
allRefundsSent();
state = State.ExpiredRefundComplete;
}
function removeContract()
public
isCreator()
atEndOfLifecycle()
{
selfdestruct(msg.sender);
}
function () { throw; }
}
// ** END EXAMPLE **
2015-12-28 22:13:20 +00:00
2015-12-28 22:11:00 +00:00
// 10. OTHER NATIVE FUNCTIONS
2015-11-23 21:02:00 +00:00
// Currency units
2015-12-28 22:11:00 +00:00
// Currency is defined using wei, smallest unit of Ether
2015-11-23 21:02:00 +00:00
uint minAmount = 1 wei;
2015-12-28 22:11:00 +00:00
uint a = 1 finney; // 1 ether == 1000 finney
// Other units, see: http://ether.fund/tool/converter
2015-11-23 21:02:00 +00:00
// Time units
1 == 1 second
1 minutes == 60 seconds
2015-12-28 22:11:00 +00:00
// Can multiply a variable times unit, as units are not stored in a variable
2015-11-23 21:02:00 +00:00
uint x = 5;
(x * 1 days); // 5 days
2015-12-28 22:11:00 +00:00
// Careful about leap seconds/years with equality statements for time
// (instead, prefer greater than/less than)
2015-11-23 21:02:00 +00:00
// Cryptography
2015-12-28 22:11:00 +00:00
// All strings passed are concatenated before hash action
2015-11-23 21:02:00 +00:00
sha3("ab", "cd");
ripemd160("abc");
sha256("def");
2015-12-28 22:13:20 +00:00
// 11. LOW LEVEL FUNCTIONS
2015-12-28 22:11:00 +00:00
// call - low level, not often used, does not provide type safety
successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2');
2015-11-30 20:48:47 +00:00
2015-12-28 22:11:00 +00:00
// callcode - Code at target address executed in *context* of calling contract
// provides library functionality
someContractAddress.callcode('function_name');
2015-11-23 21:02:00 +00:00
2015-12-28 22:13:20 +00:00
2015-12-28 22:11:00 +00:00
// 12. STYLE NOTES
// Based on Python's PEP8 style guide
2015-11-23 21:02:00 +00:00
2015-12-28 22:11:00 +00:00
// 4 spaces for indentation
// Two lines separate contract declarations (and other top level declarations)
// Avoid extraneous spaces in parentheses
// Can omit curly braces for one line statement (if, for, etc)
// else should be placed on own line
2015-11-23 21:02:00 +00:00
2015-12-28 22:13:20 +00:00
2015-12-28 22:11:00 +00:00
// 13. NATSPEC comments - used for documentation, commenting, and external UIs
// Contract natspec - always above contract definition
/// @title Contract title
/// @author Author name
2015-11-24 05:09:10 +00:00
2015-12-28 22:11:00 +00:00
// Function natspec
/// @notice information about what function does; shown when function to execute
/// @dev Function documentation for developer
2015-11-30 20:45:03 +00:00
2015-12-28 22:11:00 +00:00
// Function parameter/return value natspec
/// @param someParam Some description of what the param does
/// @return Description of the return value
2015-11-23 21:02:00 +00:00
```
## Additional resources
- [Solidity Docs](https://ethereum.github.io/solidity/docs/home/)
- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide.
- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/)
- [Gitter Chat room](https://gitter.im/ethereum/go-ethereum)
2015-12-28 22:11:00 +00:00
- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/)
- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc))
2015-11-23 21:02:00 +00:00
2015-11-30 21:14:26 +00:00
## Sample contracts
2015-12-11 18:07:01 +00:00
- [Dapp Bin](https://github.com/ethereum/dapp-bin)
2015-11-30 21:14:26 +00:00
- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts)
- [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts)
2015-11-30 22:23:41 +00:00
- [State of Dapps](http://dapps.ethercasts.com/)
2015-11-30 21:14:26 +00:00
2015-11-30 20:45:03 +00:00
## Information purposefully excluded
- Libraries
2015-12-28 22:11:00 +00:00
- [Call keyword](http://solidity.readthedocs.org/en/latest/types.html)
## Style
- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy)
## Future To Dos
- New keywords: protected, inheritable
2015-11-30 20:45:03 +00:00
Feel free to send a pull request with any edits - or email nemild -/at-/ gmail