Skip to content

Instantly share code, notes, and snippets.

@darshjain
Created June 4, 2020 08:25
Show Gist options
  • Save darshjain/6e12bcc081880d9903135476cee0d3f2 to your computer and use it in GitHub Desktop.
Save darshjain/6e12bcc081880d9903135476cee0d3f2 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.5.17+commit.d19bba13.js&optimize=false&gist=
pragma solidity ^0.5.9;
contract Auction {
// Data
//Structure to hold details of the item
struct Item {
uint itemId; // id of the item
uint[] itemTokens; //tokens bid in favor of the item
}
//Structure to hold the details of a persons
struct Person {
uint remainingTokens; // tokens remaining with bidder
uint personId; // it serves as tokenId as well
address addr;//address of the bidder
}
mapping(address => Person) tokenDetails; //address to person
Person [4] bidders;//Array containing 4 person objects
Item [3] public items;//Array containing 3 item objects
address[3] public winners;//Array for address of winners
address public beneficiary;//owner of the smart contract
uint bidderCount = 0;//counter
//functions
constructor() public payable{ //constructor
//Part 1 Task 1. Initialize beneficiary with address of smart contract’s owner
//Hint. In the constructor,"msg.sender" is the address of the owner.
// ** Start code here. 1 line approximately. **/
beneficiary = msg.sender;
//** End code here. **/
uint[] memory emptyArray;
items[0] = Item({itemId:0, itemTokens:emptyArray});
//Part 1 Task 2. Initialize two items with at index 1 and 2.
// ** Start code here. 2 lines approximately. **/
items[1] = Item({itemId:1, itemTokens:emptyArray});
items[2] = Item({itemId:2, itemTokens:emptyArray});
//** End code here**/
}
function register() public payable{
bidders[bidderCount].personId = bidderCount;
//Part 1 Task 3. Initialize the address of the bidder
/*Hint. Here the bidders[bidderCount].addr should be initialized with address of the registrant.*/
// ** Start code here. 1 line approximately. **/
bidders[bidderCount].addr = msg.sender;
//** End code here. **
bidders[bidderCount].remainingTokens = 5; // only 5 tokens
tokenDetails[msg.sender] = bidders[bidderCount];
bidderCount++;
}
function bid(uint _itemId, uint _count) public payable {
/*
Bids tokens to a particular item.
Arguments:
_itemId -- uint, id of the item
_count -- uint, count of tokens to bid for the item
*/
/*
Part 1 Task 4. Implement the three conditions below.
4.1 If the number of tokens remaining with the bidder is < count of tokens bidded, revert.
4.2 If there are no tokens remaining with the bidder, revert.
4.3 If the id of the item for which bid is placed, is greater than 2, revert.
Hint: "tokenDetails[msg.sender].remainingTokens" gives the details of the number of tokens remaining with the bidder.
*/
// ** Start code here. 2 lines approximately. **/
if (tokenDetails[msg.sender].remainingTokens < _count || _itemId > 2)
revert();
//** End code here. **
/*Part 1 Task 5. Decrement the remainingTokens by the number of tokens bid and store the value in balance variable.
Hint. "tokenDetails[msg.sender].remainingTokens" should be decremented by "_count". */
// ** Start code here. 1 line approximately. **
uint balance = tokenDetails[msg.sender].remainingTokens - _count;
//** End code here. **
tokenDetails[msg.sender].remainingTokens = balance;
bidders[tokenDetails[msg.sender].personId].remainingTokens = balance;//updating the same balance in bidders map.
Item storage bidItem = items[_itemId];
for(uint i = 0; i < _count; i++) {
bidItem.itemTokens.push(tokenDetails[msg.sender].personId);
}
}
// Part 2 Task 1. Create a modifier named "onlyOwner" to ensure that only owner is allowed to reveal winners
//Hint : Use require to validate if "msg.sender" is equal to the "beneficiary".
modifier onlyOwner {
// ** Start code here. 2 lines approximately. **
require(msg.sender == beneficiary);
_;
//** End code here. **
}
function revealWinners() public onlyOwner {
/*
Iterate over all the items present in the auction.
If at least on person has placed a bid, randomly select the winner */
for (uint id = 0; id < 3; id++) {
Item storage currentItem = items[id];
if (currentItem.itemTokens.length != 0) {
// generate random# from block number
uint randomIndex = (block.number / currentItem.itemTokens.length) % currentItem.itemTokens.length;
// Obtain the winning tokenId
uint winnerId = currentItem.itemTokens[randomIndex];
/* Part 1 Task 6. Assign the winners.
Hint." bidders[winnerId] " will give you the person object with the winnerId.
you need to assign the address of the person obtained above to winners[id] */
// ** Start coding here *** 1 line approximately.
winners[id] = bidders[winnerId].addr;
//** end code here*
}
}
}
//Miscellaneous methods: Below methods are used to assist Grading. Please DONOT CHANGE THEM.
function getPersonDetails(uint id) public view returns(uint, uint, address){
return (bidders[id].remainingTokens, bidders[id].personId, bidders[id].addr);
}
}
pragma solidity >=0.4.22 <0.6.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.
constructor(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 view 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;
}
}
}
import "remix_tests.sol"; // this import is automatically injected by Remix.
import "./ballot.sol";
contract test3 {
Ballot ballotToTest;
function beforeAll () public {
ballotToTest = new Ballot(2);
}
function checkWinningProposal () public {
ballotToTest.vote(1);
Assert.equal(ballotToTest.winningProposal(), uint(1), "1 should be the winning proposal");
}
function checkWinninProposalWithReturnValue () public view returns (bool) {
return ballotToTest.winningProposal() == 1;
}
}
pragma solidity ^0.5.9;
contract Ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
// address delegate;
}
struct Proposal {
uint voteCount; // could add other data about proposal
}
address chairperson;
mapping(address => Voter) voters;
Proposal[] proposals;
/// Create a new ballot with $(_numProposals) different proposals.
constructor(uint8 _numProposals) public {
chairperson = msg.sender;
voters[chairperson].weight = 2;
proposals.length = _numProposals;
}
/// Give $(toVoter) the right to vote on this ballot.
/// May only be called by $(chairperson).
function register(address toVoter) public {
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
voters[toVoter].voted = false;
}
/// 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 view 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;
}
}
}
pragma solidity ^0.5.9;
contract Ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
//address delegate;
}
struct Proposal {
uint voteCount;
}
enum Stage {Init,Reg, Vote, Done}
Stage public stage = Stage.Init;
address chairperson;
mapping(address => Voter) voters;
Proposal[] proposals;
event votingCompleted();
uint startTime;
//modifiers
modifier validStage(Stage reqStage)
{ require(stage == reqStage);
_;
}
/// Create a new ballot with $(_numProposals) different proposals.
constructor(uint8 _numProposals) public {
chairperson = msg.sender;
voters[chairperson].weight = 2; // weight is 2 for testing purposes
proposals.length = _numProposals;
stage = Stage.Reg;
startTime = now;
}
/// Give $(toVoter) the right to vote on this ballot.
/// May only be called by $(chairperson).
function register(address toVoter) public validStage(Stage.Reg) {
//if (stage != Stage.Reg) {return;}
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
voters[toVoter].voted = false;
if (now > (startTime+ 30 seconds)) {stage = Stage.Vote; }
}
/// Give a single vote to proposal $(toProposal).
function vote(uint8 toProposal) public validStage(Stage.Vote) {
// if (stage != Stage.Vote) {return;}
Voter storage sender = voters[msg.sender];
if (sender.voted || toProposal >= proposals.length) return;
sender.voted = true;
sender.vote = toProposal;
proposals[toProposal].voteCount += sender.weight;
if (now > (startTime+ 30 seconds)) {stage = Stage.Done; emit votingCompleted();}
}
function winningProposal() public validStage(Stage.Done) view returns (uint8 _winningProposal) {
//if(stage != Stage.Done) {return;}
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
}
assert (winningVoteCount > 0);
}
}
pragma solidity ^0.5.9;
contract Ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
}
struct Proposal {
uint voteCount;
}
enum Stage {Init,Reg, Vote, Done}
Stage public stage = Stage.Init;
address chairperson;
mapping(address => Voter) voters;
Proposal[] proposals;
uint startTime;
/// Create a new ballot with $(_numProposals) different proposals.
constructor(uint8 _numProposals) public {
chairperson = msg.sender;
voters[chairperson].weight = 2; // weight is 2 for testing purposes
proposals.length = _numProposals;
stage = Stage.Reg;
startTime = now;
}
/// Give $(toVoter) the right to vote on this ballot.
/// May only be called by $(chairperson).
function register(address toVoter) public {
if (stage != Stage.Reg) {return;}
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
voters[toVoter].voted = false;
if (now > (startTime+ 10 seconds)) {stage = Stage.Vote; startTime = now;}
}
/// Give a single vote to proposal $(toProposal).
function vote(uint8 toProposal) public {
if (stage != Stage.Vote) {return;}
Voter storage sender = voters[msg.sender];
if (sender.voted || toProposal >= proposals.length) return;
sender.voted = true;
sender.vote = toProposal;
proposals[toProposal].voteCount += sender.weight;
if (now > (startTime+ 10 seconds)) {stage = Stage.Done;}
}
function winningProposal() public view returns (uint8 _winningProposal) {
if (stage != Stage.Done) {return _winningProposal;}
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
}
}
}
pragma solidity ^0.5.9;
contract Bidder {
string public name = "Buffalo";
uint public bidAmount;
bool public eligible;
uint constant minBid = 1000;
function setName(string memory nm) public {
name = nm;
}
function setBidAmount(uint x) public {
bidAmount = x;
}
function determineEligibility() public {
if (bidAmount >= minBid ) eligible = true;
else eligible = false;
}
}
pragma solidity ^0.5.9;
contract Bidder {
string public name;
uint public bidAmount = 20000;
bool public eligible;
uint constant minBid = 1000;
}
Major Changes
current version: 0.5.3
1. Constructor function declaration
- from function [contract name]() public {}
- to constructor() public {}
2. Keyword 'constant' is deprecated
- use 'view` instead of 'constant'
3. Invoking events without 'emit' prefix is deprecated
- add 'emit' keyword before invoking events
4. Data location function parameter must be explicitly specified
- from function set(string name)...
- to function set(string memory name) ...
pragma solidity ^0.5.9;
contract Coin {
// The keyword "public" makes those variables
// readable from outside.
address public minter;
mapping (address => uint) public balances;
// Events allow light clients to react on
// changes efficiently.
event Sent(address from, address to, uint amount);
// This is the constructor whose code is
// run only when the contract is created.
constructor() public{
minter = msg.sender;
}
function mint(address receiver, uint amount) public {
if (msg.sender != minter) return;
balances[receiver] += amount;
}
function send(address receiver, uint amount) public {
if (balances[msg.sender] < amount) return;
balances[msg.sender] -= amount;
balances[receiver] += amount;
emit Sent(msg.sender, receiver, amount);
}
}
pragma solidity ^0.5.9;
contract Greeter {
string public yourName; // data
/* This runs when the contract is executed */
constructor() public {
yourName = "World";
}
function set(string memory name) public {
yourName = name;
}
function hello() view public returns (string memory) {
return yourName;
}
}
pragma solidity ^0.5.9;
contract Coin {
// The keyword "public" makes those variables
// readable from outside.
address public minter;
mapping (address => uint) public balances;
// Events allow light clients to react on
// changes efficiently.
event Sent(address from, address to, uint amount);
// This is the constructor whose code is
// run only when the contract is created.
constructor() public{
minter = msg.sender;
}
function mint(address receiver, uint amount) public {
if (msg.sender != minter) return;
balances[receiver] += amount;
}
function send(address receiver, uint amount) public {
if (balances[msg.sender] < amount) return;
balances[msg.sender] -= amount;
balances[receiver] += amount;
emit Sent(msg.sender, receiver, amount);
}
}
pragma solidity ^0.5.9;
// Imagine a big integer that the whole world could share
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() view public returns (uint) {
return storedData;
}
function increment (uint n) public {
storedData = storedData + n;
return;
}
function decrement (uint n) public {
storedData = storedData - n;
return;
}
}
pragma solidity ^0.5.9;
contract StateTransV2 {
enum Stage {Init, Reg, Vote, Done}
Stage public stage;
uint startTime;
uint public timeNow;
constructor() public {
stage = Stage.Init;
startTime = now;
}
//Assuming the Stage change has to be enacted APPROX every 1 mintute
//timeNow variable is defined for underatanding the process, you can simply use
// "now" Solidity defined varaible
// Of course, time duration for the Stages may depend on your application
//1 minutes is set to illustrate the working
function advanceState () public {
timeNow = now;
if (timeNow > (startTime + 1 minutes)) {
startTime = timeNow;
if (stage == Stage.Init) {stage = Stage.Reg; return;}
if (stage == Stage.Reg) {stage = Stage.Vote; return;}
if (stage == Stage.Vote) {stage = Stage.Done; return;}
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment