diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ace276f --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +.idea/vcs.xml +.idea/workspace.xml +Lesson-4/assignment/payroll/payroll.iml +Lesson-4/assignment/payroll/.idea/misc.xml +Lesson-4/assignment/payroll/.idea/modules.xml +Lesson-4/assignment/payroll/.idea/workspace.xml +Lesson-5/orgin/orgin.iml +Lesson-5/orgin/package-lock.json +Lesson-5/orgin/.idea/misc.xml +Lesson-5/orgin/.idea/modules.xml +Lesson-5/orgin/.idea/workspace.xml +Lesson-5/assignment/payroll/orgin.iml +Lesson-5/assignment/payroll/package-lock.json +Lesson-5/assignment/payroll/.idea/misc.xml +Lesson-5/assignment/payroll/.idea/modules.xml +Lesson-5/assignment/payroll/.idea/workspace.xml +Lesson-6/orgin/orgin.iml +Lesson-6/orgin/package-lock.json +Lesson-6/orgin/.idea/misc.xml +Lesson-6/orgin/.idea/modules.xml +Lesson-6/orgin/.idea/workspace.xml +Lesson-6/assignment/payroll/orgin.iml +Lesson-6/assignment/payroll/package-lock.json +Lesson-6/assignment/payroll/.idea/misc.xml +Lesson-6/assignment/payroll/.idea/modules.xml +Lesson-6/assignment/payroll/.idea/workspace.xml diff --git a/Lesson-1/assignment/yours.sol b/Lesson-1/assignment/yours.sol index dfdb2c4..eabdb76 100644 --- a/Lesson-1/assignment/yours.sol +++ b/Lesson-1/assignment/yours.sol @@ -1 +1,51 @@ /*作业请提交在这个目录下*/ +pragma solidity ^0.4.14; + +contract Payroll { + uint constant payDuration = 10 seconds; + + address owner; + uint salary; + address employee; + uint lastPayday; + + function Payroll() { + owner = msg.sender; + } + + function updateEmployeeAddress(address e) { + require(msg.sender == owner); + + employee = e; + lastPayday = now; + } + + function updateEmployeeSalary(uint s) { + require(msg.sender == owner); + + salary = s * 1 ether; + lastPayday = now; + } + + function addFund() payable returns (uint) { + return this.balance; + } + + function calculateRunway() returns (uint) { + return this.balance / salary; + } + + function hasEnoughFund() returns (bool) { + return calculateRunway() > 0; + } + + function getPaid() { + require(msg.sender == employee); + + uint nextPayday = lastPayday + payDuration; + assert(nextPayday < now); + + lastPayday = nextPayday; + employee.transfer(salary); + } +} \ No newline at end of file diff --git a/Lesson-2/README.md b/Lesson-2/README.md new file mode 100644 index 0000000..1fdc5b3 --- /dev/null +++ b/Lesson-2/README.md @@ -0,0 +1,16 @@ +## 硅谷live以太坊智能合约频道官方地址 + +### 第二课《智能合约设计进阶-多员工薪酬系统》 + +目录结构 +
| +
|--orgin 课程初始代码 +
| +
|--assignment 课程作业提交代码 +
+### 本节知识点 +第2课:智能合约设计进阶-多员工薪酬系统 +- 动态静态数组的不同 +- 函数输入参数检查 revert +- 循环与遍历的安全性 +- 程序运行错误检查和容错:assert与require diff --git a/Lesson-2/assignment/Gas Usage Record.txt b/Lesson-2/assignment/Gas Usage Record.txt new file mode 100644 index 0000000..83bd95b --- /dev/null +++ b/Lesson-2/assignment/Gas Usage Record.txt @@ -0,0 +1,29 @@ +| Version 1 | | | +|-----------|------------------|----------------| +| Employee | transaction cost | execution cost | +|-----------|------------------|----------------| +| 1 | 22971 | 1699 | +| 2 | 23759 | 2487 | +| 3 | 24547 | 3275 | +| 4 | 25335 | 4063 | +| 5 | 26123 | 4851 | +| 6 | 26911 | 5639 | +| 7 | 27699 | 6427 | +| 8 | 28487 | 7215 | +| 9 | 29275 | 8003 | +| 10 | 30063 | 8791 | + +| Version 2 | | | +|-----------|------------------|----------------| +| Employee | transaction cost | execution cost | +|-----------|------------------|----------------| +| 1 | 22122 | 850 | +| 2 | 22122 | 850 | +| 3 | 22122 | 850 | +| 4 | 22122 | 850 | +| 5 | 22122 | 850 | +| 6 | 22122 | 850 | +| 7 | 22122 | 850 | +| 8 | 22122 | 850 | +| 9 | 22122 | 850 | +| 10 | 22122 | 850 | diff --git a/Lesson-2/assignment/README.md b/Lesson-2/assignment/README.md new file mode 100644 index 0000000..a1fa2d0 --- /dev/null +++ b/Lesson-2/assignment/README.md @@ -0,0 +1,10 @@ +## 硅谷live以太坊智能合约 第二课作业 +这里是同学提交作业的目录 + +### 第二课:课后作业 +完成今天的智能合约添加100ETH到合约中 +- 加入十个员工,每个员工的薪水都是1ETH +每次加入一个员工后调用calculateRunway这个函数,并且记录消耗的gas是多少?Gas变化么?如果有 为什么? +- 如何优化calculateRunway这个函数来减少gas的消耗? +提交:智能合约代码,gas变化的记录,calculateRunway函数的优化 + diff --git a/Lesson-2/assignment/yours.sol b/Lesson-2/assignment/yours.sol new file mode 100644 index 0000000..1a113ca --- /dev/null +++ b/Lesson-2/assignment/yours.sol @@ -0,0 +1,125 @@ +pragma solidity ^0.4.14; + +contract Payroll { + struct Employee { + address id; + uint salary; + uint lastPayday; + } + + uint constant payDuration = 10 seconds; + + address owner; + Employee[] employees; + uint totalSalary; + + function Payroll() { + owner = msg.sender; + } + + function _partialPaid(Employee employee) private { + if (employee.id != 0x0) { + uint payment = employee.salary * (now - employee.lastPayday) / payDuration; + employee.id.transfer(payment); + } + } + + function _findEmployee(address e) private constant returns (Employee, uint) { + for(uint i = 0; i < employees.length; i++) { + if(employees[i].id == e) { + return (employees[i], i); + } + } + } + + //For debug only + function getAllEmployees() returns (address[], uint[], uint[]){ + require(msg.sender == owner); + address[] memory addrs = new address[](employees.length); + uint[] memory salays = new uint[](employees.length); + uint[] memory lastpds = new uint[](employees.length); + for (uint i = 0; i < employees.length; i++) { + Employee storage employee = employees[i]; + addrs[i] = employee.id; + salays[i] = employee.salary; + lastpds[i] = employee.lastPayday; + } + return (addrs, salays, lastpds); + } + //For debug only + function getBalance() constant returns (uint){ + require(msg.sender == owner); + return this.balance; + } + //For debug only + function getTotalSalary() constant returns (uint){ + require(msg.sender == owner); + return totalSalary; + } + + + function addEmployee(address e, uint s) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id == 0x00); + employees.push(Employee(e, s * 1 ether, now)); + + totalSalary += s * 1 ether; + } + + function removeEmployee(address e) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id != 0x00); + delete employees[index]; + employees[index] = employees[employees.length-1]; + employees.length--; + + totalSalary -= employee.salary; + + _partialPaid(employee); + } + + function updateEmployee(address e, uint s) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id != 0x00); + + uint delta_salary = employee.salary - s * 1 ether; + + employees[index].id = e; + employees[index].salary = s * 1 ether; + employees[index].lastPayday = now; + + totalSalary -= delta_salary; + + _partialPaid(employee); + } + + function addFund() payable returns (uint) { + return this.balance; + } + + function calculateRunway() constant returns (uint) { + // uint totalSalary = 0; + // for (uint i = 0; i < employees.length; i++) { + // totalSalary += employees[i].salary; + // } + return this.balance / totalSalary; + } + + function hasEnoughFund() constant returns (bool) { + return calculateRunway() > 0; + } + + function getPaid() { + var (employee, index) = _findEmployee(msg.sender); + assert(employee.id != 0x00); + + uint nextPayday = employee.lastPayday + payDuration; + assert(nextPayday < now); + + employees[index].lastPayday = nextPayday; + employees[index].id.transfer(employees[index].salary); + } +} diff --git a/Lesson-2/assignment/yours_ver1.sol b/Lesson-2/assignment/yours_ver1.sol new file mode 100644 index 0000000..dbc3b78 --- /dev/null +++ b/Lesson-2/assignment/yours_ver1.sol @@ -0,0 +1,104 @@ +pragma solidity ^0.4.14; + +contract Payroll { + struct Employee { + address id; + uint salary; + uint lastPayday; + } + + uint constant payDuration = 10 seconds; + + address owner; + Employee[] employees; + + function Payroll() { + owner = msg.sender; + } + + function _partialPaid(Employee employee) private { + if (employee.id != 0x0) { + uint payment = employee.salary * (now - employee.lastPayday) / payDuration; + employee.id.transfer(payment); + } + } + + function _findEmployee(address e) private returns (Employee, uint) { + for(uint i = 0; i < employees.length; i++) { + if(employees[i].id == e) { + return (employees[i], i); + } + } + } + + function getAllEmployees() returns (address[], uint[], uint[]){ + require(msg.sender == owner); + address[] memory addrs = new address[](employees.length); + uint[] memory salays = new uint[](employees.length); + uint[] memory lastpds = new uint[](employees.length); + + for (uint i = 0; i < employees.length; i++) { + Employee storage employee = employees[i]; + addrs[i] = employee.id; + salays[i] = employee.salary; + lastpds[i] = employee.lastPayday; + } + + return (addrs, salays, lastpds); + } + + function addEmployee(address e, uint s) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id == 0x00); + employees.push(Employee(e, s * 1 ether, now)); + } + + function removeEmployee(address e) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id != 0x00); + delete employees[index]; + employees[index] = employees[employees.length-1]; + employees.length--; + } + + function updateEmployee(address e, uint s) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id != 0x00); + + employees[index].id = e; + employees[index].salary = s * 1 ether; + employees[index].lastPayday = now; + + _partialPaid(employee); + } + + function addFund() payable returns (uint) { + return this.balance; + } + + function calculateRunway() returns (uint) { + uint totalSalary = 0; + for (uint i = 0; i < employees.length; i++) { + totalSalary += employees[i].salary; + } + return this.balance / totalSalary; + } + + function hasEnoughFund() returns (bool) { + return calculateRunway() > 0; + } + + function getPaid() { + var (employee, index) = _findEmployee(msg.sender); + assert(employee.id != 0x00); + + uint nextPayday = employee.lastPayday + payDuration; + assert(nextPayday < now); + + employees[index].lastPayday = nextPayday; + employees[index].id.transfer(employees[index].salary); + } +} diff --git a/Lesson-2/assignment/yours_ver2.sol b/Lesson-2/assignment/yours_ver2.sol new file mode 100644 index 0000000..1a113ca --- /dev/null +++ b/Lesson-2/assignment/yours_ver2.sol @@ -0,0 +1,125 @@ +pragma solidity ^0.4.14; + +contract Payroll { + struct Employee { + address id; + uint salary; + uint lastPayday; + } + + uint constant payDuration = 10 seconds; + + address owner; + Employee[] employees; + uint totalSalary; + + function Payroll() { + owner = msg.sender; + } + + function _partialPaid(Employee employee) private { + if (employee.id != 0x0) { + uint payment = employee.salary * (now - employee.lastPayday) / payDuration; + employee.id.transfer(payment); + } + } + + function _findEmployee(address e) private constant returns (Employee, uint) { + for(uint i = 0; i < employees.length; i++) { + if(employees[i].id == e) { + return (employees[i], i); + } + } + } + + //For debug only + function getAllEmployees() returns (address[], uint[], uint[]){ + require(msg.sender == owner); + address[] memory addrs = new address[](employees.length); + uint[] memory salays = new uint[](employees.length); + uint[] memory lastpds = new uint[](employees.length); + for (uint i = 0; i < employees.length; i++) { + Employee storage employee = employees[i]; + addrs[i] = employee.id; + salays[i] = employee.salary; + lastpds[i] = employee.lastPayday; + } + return (addrs, salays, lastpds); + } + //For debug only + function getBalance() constant returns (uint){ + require(msg.sender == owner); + return this.balance; + } + //For debug only + function getTotalSalary() constant returns (uint){ + require(msg.sender == owner); + return totalSalary; + } + + + function addEmployee(address e, uint s) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id == 0x00); + employees.push(Employee(e, s * 1 ether, now)); + + totalSalary += s * 1 ether; + } + + function removeEmployee(address e) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id != 0x00); + delete employees[index]; + employees[index] = employees[employees.length-1]; + employees.length--; + + totalSalary -= employee.salary; + + _partialPaid(employee); + } + + function updateEmployee(address e, uint s) { + require(msg.sender == owner); + var (employee, index) = _findEmployee(e); + assert(employee.id != 0x00); + + uint delta_salary = employee.salary - s * 1 ether; + + employees[index].id = e; + employees[index].salary = s * 1 ether; + employees[index].lastPayday = now; + + totalSalary -= delta_salary; + + _partialPaid(employee); + } + + function addFund() payable returns (uint) { + return this.balance; + } + + function calculateRunway() constant returns (uint) { + // uint totalSalary = 0; + // for (uint i = 0; i < employees.length; i++) { + // totalSalary += employees[i].salary; + // } + return this.balance / totalSalary; + } + + function hasEnoughFund() constant returns (bool) { + return calculateRunway() > 0; + } + + function getPaid() { + var (employee, index) = _findEmployee(msg.sender); + assert(employee.id != 0x00); + + uint nextPayday = employee.lastPayday + payDuration; + assert(nextPayday < now); + + employees[index].lastPayday = nextPayday; + employees[index].id.transfer(employees[index].salary); + } +} diff --git a/Lesson-2/orgin/README.md b/Lesson-2/orgin/README.md new file mode 100644 index 0000000..0309d94 --- /dev/null +++ b/Lesson-2/orgin/README.md @@ -0,0 +1,3 @@ +## 硅谷live以太坊智能合约 第二课《智能合约设计进阶-多员工薪酬系统》 + +这里是每一课的初始代码,有需要的同学可以参考 diff --git a/Lesson-2/orgin/payroll.sol b/Lesson-2/orgin/payroll.sol new file mode 100644 index 0000000..62e380e --- /dev/null +++ b/Lesson-2/orgin/payroll.sol @@ -0,0 +1,50 @@ +pragma solidity ^0.4.14; + +contract Payroll { + struct Employee { + address id; + uint salary; + uint lastPayday; + } + + uint constant payDuration = 10 seconds; + + address owner; + Employee[] employees; + + function Payroll() { + owner = msg.sender; + } + + function _partialPaid(Employee employee) private { + } + + function _findEmployee(address employeeId) private returns (Employee, uint) { + } + + function addEmployee(address employeeId, uint salary) { + } + + function removeEmployee(address employeeId) { + } + + function updateEmployee(address employeeId, uint salary) { + } + + function addFund() payable returns (uint) { + } + + function calculateRunway() returns (uint) { + uint totalSalary = 0; + for (uint i = 0; i < employees.length; i++) { + totalSalary += employees[i].salary; + } + return this.balance / totalSalary; + } + + function hasEnoughFund() returns (bool) { + } + + function getPaid() { + } +} diff --git a/Lesson-3/README.md b/Lesson-3/README.md new file mode 100644 index 0000000..ba26ced --- /dev/null +++ b/Lesson-3/README.md @@ -0,0 +1,16 @@ +## 硅谷live以太坊智能合约频道官方地址 + +### 第三课《智能合约后端优化和产品化》 + +目录结构 +
| +
|--orgin 课程初始代码 +
| +
|--assignment 课程作业提交代码 +
+### 本节知识点 +第3课:智能合约后端优化和产品化 +- 如何通过数据结构优化降低合约执行成本 +- 合约的继承 +- 巧用modifier +- 以太坊函数库的使用和基本介绍 diff --git a/Lesson-3/assignment/Ownable.sol b/Lesson-3/assignment/Ownable.sol new file mode 100644 index 0000000..b79c5fd --- /dev/null +++ b/Lesson-3/assignment/Ownable.sol @@ -0,0 +1,41 @@ +pragma solidity ^0.4.18; + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} diff --git a/Lesson-3/assignment/README.md b/Lesson-3/assignment/README.md new file mode 100644 index 0000000..34f52f9 --- /dev/null +++ b/Lesson-3/assignment/README.md @@ -0,0 +1,56 @@ +## 硅谷live以太坊智能合约 第三课作业 +这里是同学提交作业的目录 + +### 第三课:课后作业 +- 第一题:完成今天所开发的合约产品化内容,使用Remix调用每一个函数,提交函数调用截图 +- 第二题:增加 changePaymentAddress 函数,更改员工的薪水支付地址,思考一下能否使用modifier整合某个功能 +- 第三题(加分题):自学C3 Linearization, 求以下 contract Z 的继承线 +- contract O +- contract A is O +- contract B is O +- contract C is O +- contract K1 is A, B +- contract K2 is A, C +- contract Z is K1, K2 + + +### 回答 +- 第一题 & 第二题 调用截图顺序为: + - 1. addEmployee1 (添加第一个员工) + - 2. addEmployee2 (添加第二个员工) + - 3. updateEmployee1 (更新第一个员工薪水) + - 4. calculateRunway (计算可支付薪水次数) + - 5. removeEmployee1 (删除第一个员工) + - 6. changePaymentAddress2 (更改第二个员工的收款地址) + - 7. updateEmployeeNew2 (按照第二个员工新的收款地址更新他的薪资) + - 8. getPaidNew2 (按照第二个员工新的收款地址获取薪资) + +- 第二题: + - 增加了isEmployee和isNotEmployee modifier用于统一判断特定地址是否属于员工集合 + +- 第三题: + - contract Z 的继承线是:[Z,K2,C,K1,B,A,O] + 因为: + L(O) := O + L(A) := [A]+merge(L(O), [O]) + = [A]+[O] + = [A,O] + L(B) := [B,O] + L(C) := [C,O] + L(K1) := [K1]+merge(L(B),L(A),[B,A]) + = [K1]+merge([B,O],[A,O],[B,A]) + = [K1,B]+merge([O],[A,O],[A]) + = [K1,B,A]+merge([O],[O]) + = [K1,B,A]+[O] + = [K1,B,A,O] + L(K2) := [K2,C,A,O] + L(Z) := [Z]+merge(L(K2),L(K1),[K2,K1]) + = [Z]+merge([K2,C,A,O],[K1,B,A,O],[K2,K1]) + = [Z,K2]+merge([C,A,O],[K1,B,A,O],[K1]) + = [Z,K2,C]+merge([A,O],[K1,B,A,O],[K1]) + = [Z,K2,C,K1]+merge([A,O],[B,A,O]) + = [Z,K2,C,K1,B]+merge([A,O],[A,O]) + = [Z,K2,C,K1,B,A]+merge([O],[O]) + = [Z,K2,C,K1,B,A,O] + + diff --git a/Lesson-3/assignment/SafeMath.sol b/Lesson-3/assignment/SafeMath.sol new file mode 100644 index 0000000..788797e --- /dev/null +++ b/Lesson-3/assignment/SafeMath.sol @@ -0,0 +1,48 @@ +pragma solidity ^0.4.18; + + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} diff --git a/Lesson-3/assignment/q3_test.sol b/Lesson-3/assignment/q3_test.sol new file mode 100644 index 0000000..ac96f48 --- /dev/null +++ b/Lesson-3/assignment/q3_test.sol @@ -0,0 +1,30 @@ +pragma solidity ^0.4.18; + +contract O { + uint public a = 1; +} + +contract A is O { + uint public a = 3; +} + +contract B is O { + uint public a = 4; +} + +contract C is O { + uint public a = 5; +} + +contract K1 is A,B { + uint public a = 6; +} + +contract K2 is A,C { + uint public a = 7; +} + +contract Z is K1,K2 { + +} + diff --git a/Lesson-3/assignment/screenshots/1.addEmployee1.png b/Lesson-3/assignment/screenshots/1.addEmployee1.png new file mode 100644 index 0000000..a05e919 Binary files /dev/null and b/Lesson-3/assignment/screenshots/1.addEmployee1.png differ diff --git a/Lesson-3/assignment/screenshots/2.addEmployee2.png b/Lesson-3/assignment/screenshots/2.addEmployee2.png new file mode 100644 index 0000000..d3d1d91 Binary files /dev/null and b/Lesson-3/assignment/screenshots/2.addEmployee2.png differ diff --git a/Lesson-3/assignment/screenshots/3.updateEmployee1.png b/Lesson-3/assignment/screenshots/3.updateEmployee1.png new file mode 100644 index 0000000..5e569d5 Binary files /dev/null and b/Lesson-3/assignment/screenshots/3.updateEmployee1.png differ diff --git a/Lesson-3/assignment/screenshots/4.calculateRunway.png b/Lesson-3/assignment/screenshots/4.calculateRunway.png new file mode 100644 index 0000000..8176974 Binary files /dev/null and b/Lesson-3/assignment/screenshots/4.calculateRunway.png differ diff --git a/Lesson-3/assignment/screenshots/5.removeEmployee1.png b/Lesson-3/assignment/screenshots/5.removeEmployee1.png new file mode 100644 index 0000000..566deaa Binary files /dev/null and b/Lesson-3/assignment/screenshots/5.removeEmployee1.png differ diff --git a/Lesson-3/assignment/screenshots/6.changePaymentAddress2.png b/Lesson-3/assignment/screenshots/6.changePaymentAddress2.png new file mode 100644 index 0000000..d18c671 Binary files /dev/null and b/Lesson-3/assignment/screenshots/6.changePaymentAddress2.png differ diff --git a/Lesson-3/assignment/screenshots/7.updateEmployeeNew2.png b/Lesson-3/assignment/screenshots/7.updateEmployeeNew2.png new file mode 100644 index 0000000..422ed91 Binary files /dev/null and b/Lesson-3/assignment/screenshots/7.updateEmployeeNew2.png differ diff --git a/Lesson-3/assignment/screenshots/8.getPaidNew2.png b/Lesson-3/assignment/screenshots/8.getPaidNew2.png new file mode 100644 index 0000000..530e6ca Binary files /dev/null and b/Lesson-3/assignment/screenshots/8.getPaidNew2.png differ diff --git a/Lesson-3/assignment/yours.sol b/Lesson-3/assignment/yours.sol new file mode 100644 index 0000000..aeee2f2 --- /dev/null +++ b/Lesson-3/assignment/yours.sol @@ -0,0 +1,106 @@ +pragma solidity ^0.4.18; + +import "./Ownable.sol"; +import "./SafeMath.sol"; + +contract Payroll is Ownable { + using SafeMath for uint; + + struct Employee { + address id; + uint salary; + uint lastPayday; + } + + mapping(address=>Employee) employees; + uint constant payDuration = 10 seconds; + uint totalSalary; + + modifier isEmployee(address e) { + var employee = employees[e]; + assert(employee.id != 0x00); + _; + } + + modifier isNotEmployee(address e) { + var employee = employees[e]; + assert(employee.id == 0x00); + _; + } + + function _partialPaid(Employee employee) private { + if (employee.id != 0x0) { + uint payment = employee.salary.mul((now.sub(employee.lastPayday)).div(payDuration)); + employee.id.transfer(payment); + } + } + + function _partialPaidByAddr(address e) isEmployee(e) private { + var employee = employees[e]; + uint payment = employee.salary.mul((now.sub(employee.lastPayday)).div(payDuration)); + employee.id.transfer(payment); + } + + //For debug only + function getEmployee(address e) returns (address id, uint salary, uint lastPayday) { + return (employees[e].id,employees[e].salary,employees[e].lastPayday); + } + //For debug only + function getBalance() onlyOwner constant returns (uint) { + return this.balance; + } + //For debug only + function getTotalSalary() onlyOwner constant returns (uint) { + return totalSalary; + } + + function addEmployee(address e, uint s) onlyOwner isNotEmployee(e) { + employees[e] = Employee(e, s * 1 ether, now); + + totalSalary = totalSalary.add(s * 1 ether); + } + + function removeEmployee(address e) onlyOwner isEmployee(e) { + var employee = employees[e]; + _partialPaidByAddr(e); + totalSalary = totalSalary.sub(employee.salary); + delete employees[e]; + } + + function updateEmployee(address e, uint s) onlyOwner isEmployee(e) { + var employee = employees[e]; + _partialPaidByAddr(e); + totalSalary = totalSalary.add(s * 1 ether).sub(employee.salary); + employee.salary = s * 1 ether; + employee.lastPayday = now; + } + + function changePaymentAddress(address new_e) isEmployee(msg.sender) isNotEmployee(new_e) { + var employee = employees[msg.sender]; + _partialPaidByAddr(msg.sender); + employees[new_e] = Employee(new_e, employee.salary, now); + delete employees[msg.sender]; + } + + function addFund() payable returns (uint) { + return this.balance; + } + + function calculateRunway() constant returns (uint) { + return this.balance.div(totalSalary); + } + + function hasEnoughFund() constant returns (bool) { + return calculateRunway() > 0; + } + + function getPaid() isEmployee(msg.sender) { + var employee = employees[msg.sender]; + + uint nextPayday = employee.lastPayday + payDuration; + assert(nextPayday < now); + + employee.lastPayday = nextPayday; + employee.id.transfer(employee.salary); + } +} diff --git a/Lesson-3/orgin/README.md b/Lesson-3/orgin/README.md new file mode 100644 index 0000000..6106ea1 --- /dev/null +++ b/Lesson-3/orgin/README.md @@ -0,0 +1,3 @@ +## 硅谷live以太坊智能合约 第三课 + +这里是每一课的初始代码,有需要的同学可以参考 diff --git a/Lesson-3/orgin/payroll.sol b/Lesson-3/orgin/payroll.sol new file mode 100644 index 0000000..e69de29 diff --git a/Lesson-4/README.md b/Lesson-4/README.md new file mode 100644 index 0000000..34bf0bb --- /dev/null +++ b/Lesson-4/README.md @@ -0,0 +1,16 @@ +## 硅谷live以太坊智能合约频道官方地址 + +### 第四课《使用Truffle架构进行前后端交互,测试,部署》 + +目录结构 +
| +
|--orgin 课程初始代码 +
| +
|--assignment 课程作业提交代码 +
+### 本节知识点 +第4课:使用Truffle架构进行前后端交互,测试,部署 +- 为什么要用Truffle,Truffle的基本概念 +- Truffle 的command line 功能 +- 初始化项目与Truffle项目目录结构 +- 编译部署合约到testrpc diff --git a/Lesson-4/assignment/README.md b/Lesson-4/assignment/README.md new file mode 100644 index 0000000..a2d433a --- /dev/null +++ b/Lesson-4/assignment/README.md @@ -0,0 +1,39 @@ +## 硅谷live以太坊智能合约 第四课作业 +这里是同学提交作业的目录 + +### 第四课:课后作业 +- 将第三课完成的payroll.sol程序导入truffle工程 +- 在test文件夹中,写出对如下两个函数的单元测试: +- function addEmployee(address employeeId, uint salary) onlyOwner +- function removeEmployee(address employeeId) onlyOwner employeeExist(employeeId) +- 思考一下我们如何能覆盖所有的测试路径,包括函数异常的捕捉 +- (加分题,选作) +- 写出对以下函数的基于solidity或javascript的单元测试 function getPaid() employeeExist(msg.sender) +- Hint:思考如何对timestamp进行修改,是否需要对所测试的合约进行修改来达到测试的目的? + + +### 回答 + - 导入Payroll.sol等contract文件后在truffle development环境中调用web3和payrollInstance测试payroll功能正常。 + + - addEmployee函数测试路径为: + - 新添加一个员工 + - 非owner添加员工 + - 添加一个已经存在的员工 + - 再添加一个员工 + - 获取total是否满足 + + - removeEmployee函数测试路径为: + - 添加一个员工 + - 非owner删除员工 + - 删除不存在的员工 + - 删除存在的员工 + - 获取total是否满足 + + - getPaid函数测试路径为: + - 添加10 ether给contract + - 添加一个员工 + - 员工在发薪日前不能获得报酬 + - 员工在发薪酬日后可以获得报酬 + - 非员工不能获得报酬 + + 时间修改使用了助教提示的evm_increaseTime和evm_mine消息。 \ No newline at end of file diff --git a/Lesson-4/assignment/payroll/.gitignore b/Lesson-4/assignment/payroll/.gitignore new file mode 100644 index 0000000..b5ecb53 --- /dev/null +++ b/Lesson-4/assignment/payroll/.gitignore @@ -0,0 +1,17 @@ +# See http://help.github.com/ignore-files/ for more about ignoring files. + +# dependencies +node_modules + +# testing +coverage + +# production +build +build_webpack + +# misc +.DS_Store +.env +npm-debug.log +.truffle-solidity-loader diff --git a/Lesson-4/assignment/payroll/README.md b/Lesson-4/assignment/payroll/README.md new file mode 100644 index 0000000..cf635ef --- /dev/null +++ b/Lesson-4/assignment/payroll/README.md @@ -0,0 +1,55 @@ +# React Truffle Box + +This box comes with everything you need to start using smart contracts from a react app. This is as barebones as it gets, so nothing stands in your way. + +## Installation + +1. Install truffle and an ethereum client. For local development, try EthereumJS TestRPC. + ```javascript + npm install -g truffle // Version 3.0.5+ required. + npm install -g ethereumjs-testrpc + ``` + +2. Download box. + ```javascript + truffle unbox react + ``` + +3. Compile and migrate the contracts. + ```javascript + truffle compile + truffle migrate + ``` + +4. Run the webpack server for front-end hot reloading. For now, smart contract changes must be manually recompiled and migrated. + ```javascript + npm run start + ``` + +5. Jest is included for testing React components and Truffle's own suite is incldued for smart contracts. Be sure you've compile your contracts before running jest, or you'll receive some file not found errors. + ```javascript + // Runs Jest for component tests. + npm run test + + // Runs Truffle's test suite for smart contract tests. + truffle test + ``` + +6. To build the application for production, use the build command. A production build will be in the build_webpack folder. + ```javascript + npm run build + ``` + +## FAQ + +* __Why is there both a truffle.js file and a truffle-config.js file?__ + + Truffle requires the truffle.js file be named truffle-config on Windows machines. Feel free to delete the file that doesn't correspond to your platform. + +* __Where is my production build?__ + + The production build will be in the build_webpack folder. This is because Truffle outputs contract compilations to the build folder. + +* __Where can I find more documentation?__ + + All truffle boxes are a marriage of [Truffle](http://truffleframework.com/) and a React setup created with [create-react-app](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). Either one would be a great place to start! diff --git a/Lesson-4/assignment/payroll/box-img-lg.png b/Lesson-4/assignment/payroll/box-img-lg.png new file mode 100644 index 0000000..60c1996 Binary files /dev/null and b/Lesson-4/assignment/payroll/box-img-lg.png differ diff --git a/Lesson-4/assignment/payroll/box-img-sm.png b/Lesson-4/assignment/payroll/box-img-sm.png new file mode 100644 index 0000000..466e709 Binary files /dev/null and b/Lesson-4/assignment/payroll/box-img-sm.png differ diff --git a/Lesson-4/assignment/payroll/config/env.js b/Lesson-4/assignment/payroll/config/env.js new file mode 100644 index 0000000..5d0ab7b --- /dev/null +++ b/Lesson-4/assignment/payroll/config/env.js @@ -0,0 +1,28 @@ +// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be +// injected into the application via DefinePlugin in Webpack configuration. + +var REACT_APP = /^REACT_APP_/i; + +function getClientEnvironment(publicUrl) { + var processEnv = Object + .keys(process.env) + .filter(key => REACT_APP.test(key)) + .reduce((env, key) => { + env[key] = JSON.stringify(process.env[key]); + return env; + }, { + // Useful for determining whether we’re running in production mode. + // Most importantly, it switches React into the correct mode. + 'NODE_ENV': JSON.stringify( + process.env.NODE_ENV || 'development' + ), + // Useful for resolving the correct path to static assets in `public`. + // For example, . + // This should only be used as an escape hatch. Normally you would put + // images into the `src` and `import` them in code to get their paths. + 'PUBLIC_URL': JSON.stringify(publicUrl) + }); + return {'process.env': processEnv}; +} + +module.exports = getClientEnvironment; diff --git a/Lesson-4/assignment/payroll/config/jest/cssTransform.js b/Lesson-4/assignment/payroll/config/jest/cssTransform.js new file mode 100644 index 0000000..aa17d12 --- /dev/null +++ b/Lesson-4/assignment/payroll/config/jest/cssTransform.js @@ -0,0 +1,12 @@ +// This is a custom Jest transformer turning style imports into empty objects. +// http://facebook.github.io/jest/docs/tutorial-webpack.html + +module.exports = { + process() { + return 'module.exports = {};'; + }, + getCacheKey(fileData, filename) { + // The output is always the same. + return 'cssTransform'; + }, +}; diff --git a/Lesson-4/assignment/payroll/config/jest/fileTransform.js b/Lesson-4/assignment/payroll/config/jest/fileTransform.js new file mode 100644 index 0000000..927eb30 --- /dev/null +++ b/Lesson-4/assignment/payroll/config/jest/fileTransform.js @@ -0,0 +1,10 @@ +const path = require('path'); + +// This is a custom Jest transformer turning file imports into filenames. +// http://facebook.github.io/jest/docs/tutorial-webpack.html + +module.exports = { + process(src, filename) { + return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'; + }, +}; diff --git a/Lesson-4/assignment/payroll/config/paths.js b/Lesson-4/assignment/payroll/config/paths.js new file mode 100644 index 0000000..96c3dfb --- /dev/null +++ b/Lesson-4/assignment/payroll/config/paths.js @@ -0,0 +1,46 @@ +var path = require('path'); +var fs = require('fs'); + +// Make sure any symlinks in the project folder are resolved: +// https://github.com/facebookincubator/create-react-app/issues/637 +var appDirectory = fs.realpathSync(process.cwd()); +function resolveApp(relativePath) { + return path.resolve(appDirectory, relativePath); +} + +// We support resolving modules according to `NODE_PATH`. +// This lets you use absolute paths in imports inside large monorepos: +// https://github.com/facebookincubator/create-react-app/issues/253. + +// It works similar to `NODE_PATH` in Node itself: +// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders + +// We will export `nodePaths` as an array of absolute paths. +// It will then be used by Webpack configs. +// Jest doesn’t need this because it already handles `NODE_PATH` out of the box. + +// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. +// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. +// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 + +var nodePaths = (process.env.NODE_PATH || '') + .split(process.platform === 'win32' ? ';' : ':') + .filter(Boolean) + .filter(folder => !path.isAbsolute(folder)) + .map(resolveApp); + +// config after eject: we're in ./config/ +module.exports = { + // Changed from build to build_webpack so smart contract compilations are not overwritten. + appBuild: resolveApp('build_webpack'), + appPublic: resolveApp('public'), + appHtml: resolveApp('public/index.html'), + appIndexJs: resolveApp('src/index.js'), + appPackageJson: resolveApp('package.json'), + appSrc: resolveApp('src'), + yarnLockFile: resolveApp('yarn.lock'), + testsSetup: resolveApp('src/setupTests.js'), + appNodeModules: resolveApp('node_modules'), + ownNodeModules: resolveApp('node_modules'), + nodePaths: nodePaths +}; diff --git a/Lesson-4/assignment/payroll/config/polyfills.js b/Lesson-4/assignment/payroll/config/polyfills.js new file mode 100644 index 0000000..7e60150 --- /dev/null +++ b/Lesson-4/assignment/payroll/config/polyfills.js @@ -0,0 +1,14 @@ +if (typeof Promise === 'undefined') { + // Rejection tracking prevents a common issue where React gets into an + // inconsistent state due to an error, but it gets swallowed by a Promise, + // and the user has no idea what causes React's erratic future behavior. + require('promise/lib/rejection-tracking').enable(); + window.Promise = require('promise/lib/es6-extensions.js'); +} + +// fetch() polyfill for making API calls. +require('whatwg-fetch'); + +// Object.assign() is commonly used with React. +// It will use the native implementation if it's present and isn't buggy. +Object.assign = require('object-assign'); diff --git a/Lesson-4/assignment/payroll/config/webpack.config.dev.js b/Lesson-4/assignment/payroll/config/webpack.config.dev.js new file mode 100644 index 0000000..821743a --- /dev/null +++ b/Lesson-4/assignment/payroll/config/webpack.config.dev.js @@ -0,0 +1,242 @@ +var autoprefixer = require('autoprefixer'); +var webpack = require('webpack'); +var HtmlWebpackPlugin = require('html-webpack-plugin'); +var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); +var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); +var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); +var getClientEnvironment = require('./env'); +var paths = require('./paths'); + + + +// Webpack uses `publicPath` to determine where the app is being served from. +// In development, we always serve from the root. This makes config easier. +var publicPath = '/'; +// `publicUrl` is just like `publicPath`, but we will provide it to our app +// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. +// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz. +var publicUrl = ''; +// Get environment variables to inject into our app. +var env = getClientEnvironment(publicUrl); + +// This is the development configuration. +// It is focused on developer experience and fast rebuilds. +// The production configuration is different and lives in a separate file. +module.exports = { + // You may want 'eval' instead if you prefer to see the compiled output in DevTools. + // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343. + devtool: 'cheap-module-source-map', + // These are the "entry points" to our application. + // This means they will be the "root" imports that are included in JS bundle. + // The first two entry points enable "hot" CSS and auto-refreshes for JS. + entry: [ + // Include an alternative client for WebpackDevServer. A client's job is to + // connect to WebpackDevServer by a socket and get notified about changes. + // When you save a file, the client will either apply hot updates (in case + // of CSS changes), or refresh the page (in case of JS changes). When you + // make a syntax error, this client will display a syntax error overlay. + // Note: instead of the default WebpackDevServer client, we use a custom one + // to bring better experience for Create React App users. You can replace + // the line below with these two lines if you prefer the stock client: + // require.resolve('webpack-dev-server/client') + '?/', + // require.resolve('webpack/hot/dev-server'), + require.resolve('react-dev-utils/webpackHotDevClient'), + // We ship a few polyfills by default: + require.resolve('./polyfills'), + // Finally, this is your app's code: + paths.appIndexJs + // We include the app code last so that if there is a runtime error during + // initialization, it doesn't blow up the WebpackDevServer client, and + // changing JS code would still trigger a refresh. + ], + output: { + // Next line is not used in dev but WebpackDevServer crashes without it: + path: paths.appBuild, + // Add /* filename */ comments to generated require()s in the output. + pathinfo: true, + // This does not produce a real file. It's just the virtual path that is + // served by WebpackDevServer in development. This is the JS bundle + // containing code from all our entry points, and the Webpack runtime. + filename: 'static/js/bundle.js', + // This is the URL that app is served from. We use "/" in development. + publicPath: publicPath + }, + resolve: { + // This allows you to set a fallback for where Webpack should look for modules. + // We read `NODE_PATH` environment variable in `paths.js` and pass paths here. + // We use `fallback` instead of `root` because we want `node_modules` to "win" + // if there any conflicts. This matches Node resolution mechanism. + // https://github.com/facebookincubator/create-react-app/issues/253 + fallback: paths.nodePaths, + // These are the reasonable defaults supported by the Node ecosystem. + // We also include JSX as a common component filename extension to support + // some tools, although we do not recommend using it, see: + // https://github.com/facebookincubator/create-react-app/issues/290 + extensions: ['.js', '.json', '.jsx', ''], + alias: { + // Support React Native Web + // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ + 'react-native': 'react-native-web' + } + }, + + module: { + // First, run the linter. + // It's important to do this before Babel processes the JS. + preLoaders: [ + { + test: /\.(js|jsx)$/, + loader: 'eslint', + include: paths.appSrc, + } + ], + loaders: [ + // Default loader: load all assets that are not handled + // by other loaders with the url loader. + // Note: This list needs to be updated with every change of extensions + // the other loaders match. + // E.g., when adding a loader for a new supported file extension, + // we need to add the supported extension to this loader too. + // Add one new line in `exclude` for each loader. + // + // "file" loader makes sure those assets get served by WebpackDevServer. + // When you `import` an asset, you get its (virtual) filename. + // In production, they would get copied to the `build` folder. + // "url" loader works like "file" loader except that it embeds assets + // smaller than specified limit in bytes as data URLs to avoid requests. + // A missing `test` is equivalent to a match. + { + exclude: [ + /\.html$/, + /\.(js|jsx)$/, + /\.css$/, + /\.json$/, + /\.woff$/, + /\.woff2$/, + /\.(ttf|svg|eot)$/ + ], + loader: 'url', + query: { + limit: 10000, + name: 'static/media/[name].[hash:8].[ext]' + } + }, + // Process JS with Babel. + { + test: /\.(js|jsx)$/, + include: paths.appSrc, + loader: 'babel', + query: { + + // This is a feature of `babel-loader` for webpack (not Babel itself). + // It enables caching results in ./node_modules/.cache/babel-loader/ + // directory for faster rebuilds. + cacheDirectory: true + } + }, + // "postcss" loader applies autoprefixer to our CSS. + // "css" loader resolves paths in CSS and adds assets as dependencies. + // "style" loader turns CSS into JS modules that inject