Intro to Ether programming

合约方法

1
2
3
4
5
6
7
8
9
10
11
12
13
progma solidity ^0.4.0;
contract SimpleStorage{
uint storedData;
function set(uint x){
storedData = x;
}
function get() constant returns(uint){
return storedData;
}
}

写程序费用按照gas给挖矿者, gas != Ether
使得函数调用成本相对稳定

背景介绍

  • 传统的员工系统
  • 整型UINT/INT
    (不存在float,不支持)
  • 地址 Address
    • address.balance
    • address.transfer(value)
    • address.send(value)
    • address.call, address.callcode and address.delegatecall

设计

  1. 薪水将全部基于Ethereum
    • uint salary
    • address frank
      2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
contract Payroll {
uint salary = 1 ether;
address frank = sample_address;
uint constant Duration = 30 days;
uint lastPayday = now;
<!-- function test(){
payDuration = 1 days;
} -->
function addFund() payable return(uint){
return this.balance; // `this` is an address type
}
function calculateRunway() return(uint){
return this.balance / salary;
}
function hasEnoughFund() return(bool){
// return this.balance >= salary;
return calculateRunway() > 0;
// gas assumption is far less than this.calculateRunway() (use msg)
}
function getPaid() {
if(msg.sender != bob){
revert();
}
uint nextPayDay = lastPayday + payDuration;
if (nextPayDay > now){
revert();// instead of throw
}
lastPayday = nextPayDay;
frank.transfer(salary);
// change interval variable => transfer money (to avoid re-enter attack)
// no compiler optimization yet
// scope of local defined variable is global
}
}

ETHER unit (只是方便ti数字替代)

  • wei
  • szabo = 10^12 wei
  • find
  • ether = 10^18 wei

e.g. 1 wei == 1
时间单位

h2.Block

  • block.blockhash
  • block.coinbase
  • block.difficulty(uint)
  • block.

h2.Message

  • msg.data
  • msg.gas(uint)
  • msg.sender(address)
  • msg.sig
  • msg.value(uint)

如何发放薪水
(函数被动调用)

  • 定时器?
  • Bob send money to Alice by contract
  • How to prevent Bob from not giving Alice the money
  • Save money in smart contract, and Alice get money every 30 days
    • function addFund
    • function calculateRunway
    • function hasEnoughFund
    • function getPaid