@(135- Block Chain| 区块链)

Introduction

  • 如何通过数据结构优化降低合约执行成本
  • 合约的继承
  • 巧用modifier
  • 以太坊函数库的使用和基本介绍

如何减少gas 消耗?
(本质为节约计算资源,降低时间复杂度的问题)
数组越大,遍历所需资源越多
遍历数组 traverse array——> 映射 Mapping

1 Mapping in Solidity

类比map(c++),dict(python)
Hash table
Key - Value

  • types of Key in solidity
    (bool,int ,address,string)

  • types of Value in solidity
    (any type)
  • usage
    mapping (address=>Employee)employees
  • mapping只能作为合约的成员变量,而不能做本地局部变量

    2 Mapping底层实现

  • 不使用数组+链表,不需要扩容
  • hash函数为keccak256hash(keccak 即SHA- 3)
  • 在storage 上存储,理论上为无限大的hash表
    *** 无法naive地遍历整个mapping**
  • 赋值 employees[key] = value
  • 取值 value = employees[key]
  • value 是引用,在storage上存储,可以直接修改
  • 当key 不存在,value = type's default // 不会抛出异常

3 函数返回进阶

  • 命名参数返回
  • 命名返回参数直接赋值

1.命名参数返回

    function checkEmployee(address employeeId) returns(uint salary,uint lastPayday){ //quary the information of employees//name the returned parameter 命名参数返回 

OUTPUT

"0": "uint256: salary 1000000000000000000",
"1": "uint256: lastPayday 1530411588"
}

2.命名返回参数直接赋值

等效代码

        // return (employee.salary,employee.lastPayday);salary = employee.salary;lastPayday = employee.lastPayday;

4 可视度

4.1 可视度

  • public :谁都可见
  • external:只有“外部调用”可见(特殊可视度)
  • internal:外部调用不可见,内部和子类可见(类比c++,protected)
  • private:只有当前合约可见

4.2 变量与可见度

  • 状态变量:public,internal,private

    • 默认:internal
    • public:自动定义取值函数
    • private:不代表别人无法看到,只代表别的区块链智能合约无法看到

合约的所有成员变量都是肉眼可见的!!!

  • 函数 :public,external,internal,private

    • 默认public

5 继承

5.1 继承-基本语法

private 对继承类不可见

5.2 继承-抽象合约

contract Parent{function someFunc() returns (uint);
}
contract Child is Parent{function someFunc() returns (uint){return 1;}
}

5.3 继承-interface

  • 类比 Java 相似
    只是一个告诉之后程序员的一个框架
pragma solidity ^0.4.0;
interface Parent{
//不可继承其他合约或Interface
//没有构造函数
//没有状态变量
//没有struct
//没有enum
//简单来说,只有function定义,啥都没有function someFunc() returns (uint);
}contract Child is Parent{function someFunc() returns (uint){return 1;}
}

5.4 多继承

  • 重名函数的override 次序
contract Base1{function func1(){}
}contract Base2{function func1(){}
}contract Final is Base1,Base2 {
}contract test{Final f = new Final();f.func1();//Base2 的function1被调用(从后往前,由于先继承base1,再继承base2)
}
  • Super:动态绑定上级函数
contract foundation{function func1{//do stuff}
}contract Base1 is foundation{function func1(){super.func1();}
}contract Base2 is foundation{function func1(){super.func1();}
}contract Final is Base1,Base2{Final f = new Final();f.func1();
}//调用顺序:Base2.func1,Base1.func1,foundation.func1

多继承 Method Resolution Order使用O3 Linearization

  • 与python 相同
  • 不能成环路

6 Modifier

pragma solidity ^0.4.0
contract Parent {uint public a=2;modifier someModifier(){_;a = 1;}function parentFunc2(uint value) someModifer public returns(uint){a = value;//下划线等效加入一句 modify a=1;return a;}
}

7 Safe Math 和 Library

7.1 加减乘除在solidity中很危险

contract Test {uint8 public a = 0;function set(){a -= 100;}
}OUTPUT:整型溢出
a: uint8: 156

手动解决方法_silly

contract Test {uint8 public a = 0;function set(){uint c = a - 100;assert(c<a);a = c;}
}

库函数 Zppelin-solidity

  • 工程师——学习代码重用
  • 不要重复造轮子
solidity ^0.4.0;import './SafeMath.sol'; //local file,download from githubcontract Test {using SafeMath for uint8;uint8 public a = 0;function set(){a = a.sub(100);//a = SafeMath.sub(a,100);}
}

8 Code in Remix (Solidity IDE)

pragma solidity ^0.4.14;import './SafeMath.sol';
import './Ownable.sol'; //Github - Zppelin-soliditycontract Payroll{using SafeMath for uint;struct Employee{address id;uint salary;uint lastPayday;}// uint constant payDuration = 30 days;uint constant payDuration = 10 seconds;//for test:10 secondsuint totalSalary;address owner;mapping(address => Employee)public employees;// function Payroll(){//construction function// owner = msg.sender; // in ownable.sol// }// modifier onlyOwner{ //in Ownable.sol//     require(msg.sender == owner);//     _; //represent the function been modified, 除了return之外的语句// }modifier employeeExist(address employeeId){var employee = employees[employeeId];assert(employee.id != 0x0);//confirm that exist_;}function _partialPaid(Employee employee) private{uint payment = employee.salary * (now - employee.lastPayday) /payDuration;//if exist , calculate payment注意整除employee.id.transfer(payment);}function addEmployee(address employeeId,uint salary)onlyOwner{// require(msg.sender == owner);//whether is onwnervar employee = employees[employeeId];//var - any typeassert(employee.id == 0x0);//confirm that existtotalSalary += salary *1 ether;employees[employeeId] = Employee(employeeId,salary* 1 ether,now);}function removeEmployee(address employeeId)onlyOwner employeeExist(employeeId){// require(msg.sender == owner);//whether is onwner//  var (employee,index) = _findEmloyee(employeeId); var employee = employees[employeeId];_partialPaid(employee);totalSalary -=employees[employeeId].salary;delete employees[employeeId];//left with a blank in the array,wasteful
}function updateEmployee(address employeeId,uint salary)onlyOwner employeeExist(employeeId){//require(msg.sender == owner);//Equivalently 等效 // if (msg.sender != owner){//avoid employee cheating//     revert();// }var employee = employees[employeeId];_partialPaid(employee);totalSalary -= employees[employeeId].salary;employees[employeeId].salary = salary *1 ether;totalSalary += employees[employeeId].salary;employees[employeeId].lastPayday = now;     }function addFund() payable returns(uint){return this.balance;//address.balance}function calculateRunway()returns(uint){ //how many times left to payreturn this.balance / totalSalary; }function hasEnoughFund() returns(bool){// return this.balance >=salary;//return this.calculateRunway() > 0; //this方法 使用的gas 较多,不推荐return calculateRunway() > 0; //vm jump 操作,使用gas较少,推荐}function checkEmployee(address employeeId) returns(uint salary,uint lastPayday){ //quary the information of employees//name the returned parameter 命名参数返回 var employee = employees[employeeId];// return (employee.salary,employee.lastPayday);salary = employee.salary;lastPayday = employee.lastPayday;}function getPaid() employeeExist(msg.sender){var employee = employees[msg.sender];//assert(employee.id != 0x0);//confirm that existuint nextPayday = employee.lastPayday + payDuration;//每一次运算都是真金白银~//原则:不重复运算!——省gasassert(nextPayday < now);// if( nextPayday > now){//     revert();//throw or revert//throw: 所有的gas 均会被消耗殆尽//revert:回滚,return没有消耗的gas// }employees[msg.sender].lastPayday = nextPayday;//原则:先修改内部变量,再给钱——》之后会讲,安全问题employee.id.transfer(employee.salary);}
}

参考阅读:老董-以太坊智能合约全栈开发

转载于:https://www.cnblogs.com/Neo007/p/9249843.html

135.003 智能合约后端优化和产品化相关推荐

  1. 135.001 智能合约设计-——单员工薪酬系统

    @(135- Block Chain| 区块链) Introduction 参考阅读:老董-以太坊智能合约全栈开发 课程导读 1. 最终产品Demo 员工系统--人员管理+工资发放 大公司如何发工资? ...

  2. 135.002 智能合约设计-——多员工薪酬系统

    @(135- Block Chain| 区块链) Introduciton 可调整地址和薪水的单员工系统 address neo -> address employee funtion upda ...

  3. 郑重告之:智能合约开发实训营第4期学员招募正式启动!

    各位同学,抱歉久等了- 这是终于到来的<以太坊智能合约全栈开发>实战特训营第四期的正式招募通知. <以太坊智能合约全栈开发>实战特训营是由硅谷密探和 celer network ...

  4. 如何成为智能合约开发者

    如今成为一名智能合约开发者成了一种非常具有吸引力的职业选择,从有机会使用为世界带来变革性影响的技术到人才市场对智能合约开发者的巨大需求等多种因素导致这样的结果. 另外,智能合约开发技能正变得越来越重要 ...

  5. Solidity优化 - 减少智能合约gas消耗

    1. 首选数据类型 尽量使用 256 位的变量,例如 uint256 和 bytes32!乍一看,这似乎有点违反直觉,但是当你更仔细地考虑以太坊虚拟机(EVM)的运行方式时,这完全有意义.每个存储插槽 ...

  6. 白皮书 | 以太坊 (Ethereum ):下一代智能合约和去中心化应用平台

    当中本聪在2009年1月启动比特币区块链时,他同时向世界引入了两种未经测试的革命性的新概念.第一种就是比特币(bitcoin),一种去中心化的点对点的网上货币,在没有任何资产担保.内在价值或者中心发行 ...

  7. 临界Hashgard:读懂智能合约与虚拟机,看这一篇就够了!

    什么是虚拟机,为什么在区块链的世界里,它如此重要? 本次,临界 (Hashgard) 旗下的研究机构Hashgard Labs与BKFUND研究院共同完成了一篇研究报告,对虚拟机进行了深度分析. 智能 ...

  8. 智能合约(Smart contract)

    一.简介 概念:是指一份能自动执行本需要手动才能完成任务的协议.智能合约就是任何能自动执行部分功能的协议.例如,一份能自动计算合同当事人待付金额,并安排支付这笔金额的合约.智能合约将减少协议执行过程中 ...

  9. 「跨链互连智能合约」解读

    Moonbeam正在通过跨链互连合约为下一代去中心化应用奠定基础.此次发展结合了众多区块链的功能并使Moonbeam上的开发者可以访问这些功能,从而改变开发者和用户的原有使用区块链技术的思考模式. 通 ...

最新文章

  1. 1365. How Many Numbers Are Smaller Than the Current Number 有多少小于当前数字的数字
  2. 折线图表android,Android 折线图表MPAndroidChart的实现
  3. mysql 窗口函数最新一条_MySQL 8.0 窗口函数(window functions)
  4. springMVC的流程
  5. python中print不显示结果_Python中的print()函数
  6. Oracle ——概述 CBO 优化器
  7. python装饰器详解-这是我见过最全面的Python装饰器详解!没有学不会这种说法!...
  8. maven安装本地jar到本地仓库
  9. 坑杀全球顶级量化大佬的经典案例:价值投资就是看财务指标吗?
  10. 阿里 vs. 腾讯,谁的收购更有眼光?
  11. win的反义词_小学英语常见的120对反义词大全,聪明的小升初家长快来收藏学习...
  12. 苹果官网iPad mini滚动动画实现原理探究
  13. 【转】 NET 下的简繁互换
  14. 64位处理器_32位和64位Windows系统差别在哪里
  15. 计算机技能测试题五,计算机基本技能测试题(第五套
  16. ThinkPad E420/E520 Win10 开机慢的问题
  17. Node.js笔记--Day5
  18. 奥的斯3100电气图纸_奥的斯OTIS 电梯电气原理图分析
  19. bashrc java_Linux下配置环境变量—— .bashrc 和 /etc/profile
  20. 京麦消息中心业务模型分析(京东)

热门文章

  1. GIT:本地有更改,但强制作远程仓库里作更新
  2. swift基础--变量
  3. NSURL 基本方法 absoluteString
  4. Ubuntu 14.04.1 安装 python mysqldb
  5. 设计模式 2014-12-19
  6. 微软(MICROSOFT)试用版企业软件下载地址
  7. Xenapp安装后手动更改XML Service端口,以便使用不同于 IIS 的端口
  8. RIP协议的问题解决方案
  9. oracle 错误解决
  10. SpringCloud微服务注册中心如何承载大型系统的千万级访问?源码及原理分析