- 第 1 章 区块链
- 第 2 章 以太坊
- 第 3 章 以太坊私链入门
- 第 4 章 以太坊网络
- 第 5 章 geth v1.8.16 命令详解
- 第 6 章 Wallet
- 第 7 章 Token
- 第 8 章 智能合约语言 Solidity v0.5.0
- 第 9 章 Truffle v4.1.8 开发框架
- 第 10 章 web3.js - 1.0.0
- 第 11 章 web3j v3.4.0 - Jave Client
- 11.2. 启动以太坊
- 11.3. Maven pom.xml 文件
- 11.4. Java 与 Solidity 数据类型映射关系
- 11.5. 常量
- 11.6. 连接到服务器获取版本号
- 11.7. 获得以太坊状态信息
- 11.8. 单位转换
- 11.9. 账号管理
- 11.10. Credentials
- 11.11. 交易
- 11.12. 钱包
- 11.13. 智能合约
- 11.14. ERC20合约
- 11.15. Infura
- 11.16. 助记词
- 11.17. 过滤器 (Filter)
- 11.18. Subscription
- 11.19. 解锁账号
- 11.20. IBAN (International Bank Account Number)
- 11.21. Springboot with Ethereum (web3j)
- 第 12 章 web3.py - A python interface for interacting with the Ethereum blockchain and ecosystem.
- 第 14 章 Ethereum Developer APIs
- 第 15 章 infura
- 第 16 章 以太坊案例
- 第 17 章 FAQ
- 17.3. Error: authentication needed: password or unlock
- 17.4. 新增节点后不生效
- 17.5. Unhandled rejection Error: Returned error: The method personal_unlockAccount does not exist/is not available
- 17.6. Error: exceeds block gas limit
- 17.7. Migrations.sol:11:3: Warning: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(…) { … }" instead.
- 17.8. Exception in thread "main" rx.exceptions.OnErrorNotImplementedException: Invalid response received: okhttp3.internal.http.RealResponseBody@6c25e6c4
- 17.9. 旧版本 Remix(browser-solidity) 本地安装
- 第 18 章 Hyperledger Fabric v2.0.0
- 第 19 章 Hyperledger Fabric 运维
- 第 20 章 Chaincode 链码(智能合约)
- 第 21 章 Hyperledger Fabric Client SDK for Node.js
- 第 22 章 fabric-sdk-java
- 第 24 章 已知 Hyperledger 落地案例
- 第 25 章 Fabric Command
- 第 26 章 Fabric FAQ
- 第 27 章 IPFS(InterPlanetary File System,星际文件系统)
- 第 28 章 IPFS 命令
- 第 29 章 IPFS WebUI
- 第 30 章 IPFS 集群配置
- 第 31 章 IPFS API
- 第 32 章 IPFS Faq
- 第 33 章 EOS
- 第 34 章 EOS 安装
- 第 35 章 CLEOS
- 第 36 章 智能合约开发
- 第 37 章 EOS Dapp 开发
- 第 38 章 FAQ
- 第 39 章 BaaS (Blockchain as a Service) 平台
- 第 40 章 BitCoin
- 第 41 章 其他区块链相关
- 附录 1. 附录
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
8.16. solidity example
8.16. solidity example
8.16.1. Voting
pragma solidity ^0.4.25; //author: netkiller <netkiller@msn.com> //homepage: http://www.netkiller.cn contract Voting { mapping (bytes32 => uint8) public votesReceived; // 存储候选人名字的数组 bytes32[] public candidateList; // 构造函数 初始化候选人名单 function Voting(bytes32[] candidateNames) public { candidateList = candidateNames; } // 查询某个候选人的总票数 function totalVotesFor(bytes32 candidate) public constant returns (uint8) { require(validCandidate(candidate) == true); // 或者 // assert(validCandidate(candidate) == true); return votesReceived[candidate]; } // 为某个候选人投票 function voteForCandidate(bytes32 candidate) public{ assert(validCandidate(candidate) == true); votesReceived[candidate] += 1; } // 检索投票的姓名是不是候选人的名字 function validCandidate(bytes32 candidate) public constant returns (bool) { for(uint i = 0; i < candidateList.length; i++) { if (candidateList[i] == candidate) { return true; } } return false; } }
8.16.2. MetaCoin
pragma solidity ^0.4.25; contract MetaCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); function MetaCoin() public { balances[tx.origin] = 10000; } function sendCoin(address receiver, uint amount) public returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; Transfer(msg.sender, receiver, amount); return true; } function getBalance(address addr) public view returns(uint) { return balances[addr]; } }
8.16.3. Anonymous voting on Ethereum without a tally authority. Protocol from this paper
https://github.com/stonecoldpat/anonymousvoting
8.16.4. Ballot
pragma solidity ^0.4.0; contract Ballot { struct Voter { uint weight; bool voted; uint8 vote; address delegate; } struct Proposal { uint voteCount; } address chairperson; mapping(address => Voter) voters; Proposal[] proposals; /// Create a new ballot with $(_numProposals) different proposals. function Ballot(uint8 _numProposals) public { chairperson = msg.sender; voters[chairperson].weight = 1; proposals.length = _numProposals; } /// Give $(toVoter) the right to vote on this ballot. /// May only be called by $(chairperson). function giveRightToVote(address toVoter) public { if (msg.sender != chairperson || voters[toVoter].voted) return; voters[toVoter].weight = 1; } /// Delegate your vote to the voter $(to). function delegate(address to) public { Voter storage sender = voters[msg.sender]; // assigns reference if (sender.voted) return; while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender) to = voters[to].delegate; if (to == msg.sender) return; sender.voted = true; sender.delegate = to; Voter storage delegateTo = voters[to]; if (delegateTo.voted) proposals[delegateTo.vote].voteCount += sender.weight; else delegateTo.weight += sender.weight; } /// Give a single vote to proposal $(toProposal). function vote(uint8 toProposal) public { Voter storage sender = voters[msg.sender]; if (sender.voted || toProposal >= proposals.length) return; sender.voted = true; sender.vote = toProposal; proposals[toProposal].voteCount += sender.weight; } function winningProposal() public constant returns (uint8 _winningProposal) { uint256 winningVoteCount = 0; for (uint8 prop = 0; prop < proposals.length; prop++) if (proposals[prop].voteCount > winningVoteCount) { winningVoteCount = proposals[prop].voteCount; _winningProposal = prop; } } }
8.16.5. Conference
pragma solidity ^0.4.25; contract Conference { address public organizer; mapping (address => uint) public registrantsPaid; uint public numRegistrants; uint public quota; event Deposit(address _from, uint _amount); // so you can log these events event Refund(address _to, uint _amount); function Conference() public{ // Constructor organizer = msg.sender; quota = 500; numRegistrants = 0; } function buyTicket() public payable returns (bool success) { if (numRegistrants >= quota) { return false; } registrantsPaid[msg.sender] = msg.value; numRegistrants++; Deposit(msg.sender, msg.value); return true; } function changeQuota(uint newquota) public { if (msg.sender != organizer) { return; } quota = newquota; } function refundTicket(address recipient, uint amount) public { if (msg.sender != organizer) { return; } if (registrantsPaid[recipient] == amount) { address myAddress = this; if (myAddress.balance >= amount) { recipient.transfer(amount); registrantsPaid[recipient] = 0; numRegistrants--; Refund(recipient, amount); } } } function destroy() public{ // so funds not locked in contract forever if (msg.sender == organizer) { selfdestruct(organizer); // send funds to organizer } } }
控制台调试
var contract; Conference.deployed().then(function(instance){contract=instance;}); contract.buyTicket();
测试程序
neo@MacBook-Pro ~/ethereum/Conference % cat test/conference.js var Conference = artifacts.require("./Conference.sol"); contract('Conference', function(accounts) { console.log(accounts); var owner_account = accounts[0]; var sender_account = accounts[1]; it("Initial conference settings should match", function(done) { Conference.deployed({from: owner_account}).then(function(conference) { conference.quota.call().then(function(quota) { assert.equal(quota, 100, "Quota doesn't match!"); }).then(function() { return conference.numRegistrants.call(); }).then(function(num) { assert.equal(num, 0, "Registrants doesn't match!"); return conference.organizer.call(); }).then(function(organizer) { assert.equal(organizer, owner_account, "Owner doesn't match!"); done(); }).catch(done); }).catch(done); }); it("Should update quota", function(done) { Conference.deployed({from: owner_account}).then(function(conference) { conference.quota.call().then( function(quota) { assert.equal(quota, 100, "Quota doesn't match!"); }).then( function() { return conference.changeQuota(300); }).then( function() { return conference.quota.call() }).then( function(quota) { assert.equal(quota, 300, "New quota is not correct!"); done(); }).catch(done); }).catch(done); }); it("Should let you buy a ticket", function(done) { Conference.deployed({ from: accounts[0] }).then(function(conference) { var ticketPrice = web3.toWei(.05, 'ether'); var initialBalance = web3.eth.getBalance(conference.address).toNumber(); conference.buyTicket({ from: accounts[1], value: ticketPrice }).then( function() { var newBalance = web3.eth.getBalance(conference.address).toNumber(); var difference = newBalance - initialBalance; assert.equal(difference, ticketPrice, "Difference should be what was sent"); return conference.numRegistrants.call(); }).then( function(num) { assert.equal(num, 1, "there should be 1 registrant"); return conference.registrantsPaid.call(sender_account); }).then( function(amount) { assert.equal(amount.toNumber(), ticketPrice, "Sender's paid but is not listed as paying"); return web3.eth.getBalance(conference.address); }).then( function(bal) { assert.equal(bal.toNumber(), ticketPrice, "Final balance mismatch"); done(); }).catch(done); }).catch(done); }); it("Should issue a refund by owner only", function(done) { Conference.deployed({ from: accounts[0] }).then(function(conference) { var ticketPrice = web3.toWei(.05, 'ether'); var initialBalance = web3.eth.getBalance(conference.address).toNumber(); conference.buyTicket({ from: accounts[1], value: ticketPrice }).then( function() { var newBalance = web3.eth.getBalance(conference.address).toNumber(); var difference = newBalance - initialBalance; assert.equal(difference, ticketPrice, "Difference should be what was sent"); // Now try to issue refund as second user - should fail return conference.refundTicket(accounts[1], ticketPrice, {from: accounts[1]}); }).then( function() { var balance = web3.eth.getBalance(conference.address); assert.equal(balance, ticketPrice, "Balance should be unchanged"); // Now try to issue refund as organizer/owner return conference.refundTicket(accounts[1], ticketPrice, {from: accounts[0]}); }).then( function() { var postRefundBalance = web3.eth.getBalance(conference.address).toNumber(); assert.equal(postRefundBalance, initialBalance, "Balance should be initial balance"); done(); }).catch(done); }).catch(done); }); });
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论