Skip to content

Instantly share code, notes, and snippets.

@Khunpisit
Created November 29, 2020 05:17
Show Gist options
  • Save Khunpisit/9e3e2fe82c6d4bc793fde870a61b2352 to your computer and use it in GitHub Desktop.
Save Khunpisit/9e3e2fe82c6d4bc793fde870a61b2352 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&runs=200&gist=
pragma solidity >=0.4.22 <0.7.0;
/**
* @title Storage
* @dev Store & retrieve value in a variable
*/
contract Storage {
uint256 number;
/**
* @dev Store value in variable
* @param num value to store
*/
function store(uint256 num) public {
number = num;
}
/**
* @dev Return value
* @return value of 'number'
*/
function retrieve() public view returns (uint256){
return number;
}
}
pragma solidity >=0.4.22 <0.7.0;
/**
* @title Owner
* @dev Set & change owner
*/
contract Owner {
address private owner;
// event for EVM logging
event OwnerSet(address indexed oldOwner, address indexed newOwner);
// modifier to check if caller is owner
modifier isOwner() {
// If the first argument of 'require' evaluates to 'false', execution terminates and all
// changes to the state and to Ether balances are reverted.
// This used to consume all gas in old EVM versions, but not anymore.
// It is often a good idea to use 'require' to check if functions are called correctly.
// As a second argument, you can also provide an explanation about what went wrong.
require(msg.sender == owner, "Caller is not owner");
_;
}
/**
* @dev Set contract deployer as owner
*/
constructor() public {
owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
emit OwnerSet(address(0), owner);
}
/**
* @dev Change owner
* @param newOwner address of new owner
*/
function changeOwner(address newOwner) public isOwner {
emit OwnerSet(owner, newOwner);
owner = newOwner;
}
/**
* @dev Return owner address
* @return address of owner
*/
function getOwner() external view returns (address) {
return owner;
}
}
pragma solidity >=0.4.22 <0.7.0;
/**
* @title Ballot
* @dev Implements voting process along with vote delegation
*/
contract Ballot {
struct Voter {
uint weight; // weight is accumulated by delegation
bool voted; // if true, that person already voted
address delegate; // person delegated to
uint vote; // index of the voted proposal
}
struct Proposal {
// If you can limit the length to a certain number of bytes,
// always use one of bytes1 to bytes32 because they are much cheaper
bytes32 name; // short name (up to 32 bytes)
uint voteCount; // number of accumulated votes
}
address public chairperson;
mapping(address => Voter) public voters;
Proposal[] public proposals;
/**
* @dev Create a new ballot to choose one of 'proposalNames'.
* @param proposalNames names of proposals
*/
constructor(bytes32[] memory proposalNames) public {
chairperson = msg.sender;
voters[chairperson].weight = 1;
for (uint i = 0; i < proposalNames.length; i++) {
// 'Proposal({...})' creates a temporary
// Proposal object and 'proposals.push(...)'
// appends it to the end of 'proposals'.
proposals.push(Proposal({
name: proposalNames[i],
voteCount: 0
}));
}
}
/**
* @dev Give 'voter' the right to vote on this ballot. May only be called by 'chairperson'.
* @param voter address of voter
*/
function giveRightToVote(address voter) public {
require(
msg.sender == chairperson,
"Only chairperson can give right to vote."
);
require(
!voters[voter].voted,
"The voter already voted."
);
require(voters[voter].weight == 0);
voters[voter].weight = 1;
}
/**
* @dev Delegate your vote to the voter 'to'.
* @param to address to which vote is delegated
*/
function delegate(address to) public {
Voter storage sender = voters[msg.sender];
require(!sender.voted, "You already voted.");
require(to != msg.sender, "Self-delegation is disallowed.");
while (voters[to].delegate != address(0)) {
to = voters[to].delegate;
// We found a loop in the delegation, not allowed.
require(to != msg.sender, "Found loop in delegation.");
}
sender.voted = true;
sender.delegate = to;
Voter storage delegate_ = voters[to];
if (delegate_.voted) {
// If the delegate already voted,
// directly add to the number of votes
proposals[delegate_.vote].voteCount += sender.weight;
} else {
// If the delegate did not vote yet,
// add to her weight.
delegate_.weight += sender.weight;
}
}
/**
* @dev Give your vote (including votes delegated to you) to proposal 'proposals[proposal].name'.
* @param proposal index of proposal in the proposals array
*/
function vote(uint proposal) public {
Voter storage sender = voters[msg.sender];
require(sender.weight != 0, "Has no right to vote");
require(!sender.voted, "Already voted.");
sender.voted = true;
sender.vote = proposal;
// If 'proposal' is out of the range of the array,
// this will throw automatically and revert all
// changes.
proposals[proposal].voteCount += sender.weight;
}
/**
* @dev Computes the winning proposal taking all previous votes into account.
* @return winningProposal_ index of winning proposal in the proposals array
*/
function winningProposal() public view
returns (uint winningProposal_)
{
uint winningVoteCount = 0;
for (uint p = 0; p < proposals.length; p++) {
if (proposals[p].voteCount > winningVoteCount) {
winningVoteCount = proposals[p].voteCount;
winningProposal_ = p;
}
}
}
/**
* @dev Calls winningProposal() function to get the index of the winner contained in the proposals array and then
* @return winnerName_ the name of the winner
*/
function winnerName() public view
returns (bytes32 winnerName_)
{
winnerName_ = proposals[winningProposal()].name;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/// @title Bank
/// @author nemild, kor, tot
/* 'contract' has similarities to 'class' in other languages (class variables,
inheritance, etc.) */
contract Bank { // CamelCase
// Declare state variables outside function, persist through life of contract
// dictionary that maps addresses to balances
mapping (address => uint256) private balances;
// Users in system
address[] accounts;
// Interest rate
uint256 rate = 3;
// Owner of the system
address public owner;
// 'public' makes externally readable (not writeable) by users or contracts
// Events - publicize actions to external listeners
event DepositMade(address indexed accountAddress, uint amount);
event WithdrawMade(address indexed accountAddress, uint amount);
event SystemDepositMade(address indexed admin, uint amount);
event SystemWithdrawMade(address indexed admin, uint amount);
// Constructor, can receive one or many variables here; only one allowed
constructor() public {
// msg provides details about the message that's sent to the contract
// msg.sender is contract caller (address of contract creator)
owner = msg.sender;
}
/// @notice Deposit ether into bank
/// @return The balance of the user after the deposit is made
function deposit() public payable returns (uint256) {
// Record account in array for looping
if (0 == balances[msg.sender]) {
accounts.push(msg.sender);
}
balances[msg.sender] = balances[msg.sender] + msg.value;
// no "this." or "self." required with state variable
// all values set to data type's initial value by default
// Broadcast deposit event
emit DepositMade(msg.sender, msg.value); // fire event
return balances[msg.sender];
}
/// @notice Withdraw ether from bank
/// @dev This does not return any excess ether sent to it
/// @param withdrawAmount amount you want to withdraw
/// @return remainingBal The balance remaining for the user
function withdraw(uint withdrawAmount) public returns (uint256 remainingBal) {
require(balances[msg.sender] >= withdrawAmount, "Balance is not enough");
balances[msg.sender] = balances[msg.sender] - withdrawAmount;
// Revert on failed
msg.sender.transfer(withdrawAmount);
// Broadcast withdraw event
emit WithdrawMade(msg.sender, withdrawAmount);
return balances[msg.sender];
}
/// @notice Get balance
/// @return The balance of the user
// 'constant' prevents function from editing state variables;
// allows function to run locally/off blockchain
function balance() public view returns (uint256) {
return balances[msg.sender];
}
/// @notice Calculate Interests given user
/// @dev Internal use only
/// @param user user address in the system
/// @param _rate interest rate
/// @return Interest earned
function calculateInterest(address user, uint256 _rate) private view returns(uint256) {
uint256 interest = balances[user] * _rate / 100;
return interest;
}
/// @notice Calculate Interests of all users combined
/// @dev Public, anyone can lookup
/// @return Interest earned of all users
function totalInterestPerYear() external view returns(uint256) {
uint256 total = 0;
for (uint256 i = 0; i < accounts.length; i++) {
address account = accounts[i];
uint256 interest = calculateInterest(account, rate);
total = total + interest;
}
return total;
}
/// @notice Give dividends to all users, caller must provide enough fund
/// @dev Only owner can use
function payDividendsPerYear() payable public {
require(owner == msg.sender, "You are not authorized");
uint256 totalInterest = 0;
for (uint256 i = 0; i < accounts.length; i++) {
address account = accounts[i];
uint256 interest = calculateInterest(account, rate);
balances[account] = balances[account] + interest;
totalInterest = totalInterest + interest;
}
require(msg.value == totalInterest, "Not enough interest to pay!!");
}
/// @notice Bank system balance
/// @return Balances of all users combined
function systemBalance() public view returns(uint256) {
return address(this).balance;
}
/// @notice Deposit ether into bank
/// @return The balance of the user after the deposit is made
function systemDeposit() public payable returns (uint256) {
require(owner == msg.sender, "You are not authorized");
// Broadcast deposit event
emit SystemDepositMade(msg.sender, msg.value); // fire event
return systemBalance();
}
/// @notice Withdraw ether from the system
/// @param withdrawAmount amount you want to withdraw
/// @return remainingBal The balance remaining for the system
function systemWithdraw(uint withdrawAmount) public returns (uint256 remainingBal) {
require(owner == msg.sender, "You are not authorized");
require(systemBalance() >= withdrawAmount, "System balance is not enough");
// Revert on failed
msg.sender.transfer(withdrawAmount);
// Broadcast system withdraw event
emit SystemWithdrawMade(msg.sender, withdrawAmount);
return systemBalance();
}
}
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol";
contract DeuceCoin is ERC20("Khunpisit", "Deuce") {
constructor() public {
_mint(msg.sender, 100000000);
}
}
pragma solidity ^0.7.0;
contract HelloWorld {
string public name = "Hello Sertis!";
uint256 age = 25;
function setName(string memory newName)
public
{
name = newName;
}
}
pragma solidity ^0.5.0;
interface InterestInterface {
function rate() external view returns (uint256);
function calculateInterest(
address account,
uint256 balance
) external view returns (uint256);
}
pragma solidity ^0.5.0;
import "./interestInterface.sol";
contract InterestRateModelA is InterestInterface {
uint256 public rate = 3;
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @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;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() 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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) public {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Standard ERC20 token
*
* @dev Implemantation of the basic standart token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) public {
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already revert() if this condition is not met
// if (_value > _allowance) revert();
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert("approve revert");
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint value);
event MintFinished();
bool public mintingFinished = false;
uint public totalSupply = 0;
modifier canMint() {
if(mintingFinished) revert();
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint _amount) public onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
if (paused) revert("it's paused");
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
if (!paused) revert("it's not paused");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/**
* Pausable token
*
* Simple ERC20 Token example, with pausable token creation
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint _value) public whenNotPaused {
super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
super.transferFrom(_from, _to, _value);
}
}
/**
* @title ERC20 Token
*/
contract ERC20Token is PausableToken, MintableToken {
using SafeMath for uint256;
string public name;
string public symbol;
uint public decimals;
constructor(string memory _name, string memory _symbol, uint _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
contract SimpleBank is Ownable {
using SafeMath for uint256;
mapping (address => uint256) private balances;
address[] accounts;
function deposit() public payable {
if (0 == balances[msg.sender]) {
accounts.push(msg.sender);
}
balances[msg.sender] = balances[msg.sender].add(msg.value);
}
function withdraw(uint256 amount) public {
require(balances[msg.sender] >= amount, "amount is not enough!");
balances[msg.sender] = balances[msg.sender].sub(amount);
msg.sender.transfer(amount);
}
function calculateInterest(address user, uint256 _rate)
private view returns(uint256) {
return balances[user].mul(_rate).div(100);
}
uint256 rate = 3;
// function increaseYear() public {
// for (uint256 i = 0; i < accounts.length; i++) {
// address account = accounts[i];
// uint256 interest = calculateInterest(account, rate);
// balances[account] = balances[account].add(interest);
// }
// }
function payDividendsPerYear() payable public onlyOwner {
// require(owner == msg.sender, "You are not authorized");
uint256 totalInterest = 0;
for (uint256 i = 0; i < accounts.length; i++) {
address account = accounts[i];
uint256 interest = calculateInterest(account, rate);
balances[account] = balances[account] + interest;
totalInterest = totalInterest + interest;
}
require(msg.value == totalInterest, "Not enough interest to pay!!");
}
function balance() public view returns (uint256) {
return balances[msg.sender];
}
function systemBalance() public view returns(uint256) {
return address(this).balance;
}
function systemDeposit()
public payable onlyOwner returns (uint256) {
return systemBalance();
}
function systemWithdraw(uint256 amount)
public onlyOwner returns (uint256) {
msg.sender.transfer(amount);
return systemBalance();
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
contract SimpleVoting {
string[] public candidateList;
mapping (string => uint256) votesReceived;
constructor(string[] memory candidateNames)
public {
candidateList = candidateNames;
}
function addCandidate(string memory candidateName)
public {
candidateList.push(candidateName);
}
function voteForCandidate(string memory condidate)
public {
if (votesReceived[condidate] == 0) {
votesReceived[condidate] += 1;
}
}
function totalVotesFor(string memory candidate)
public view returns (uint256) {
return votesReceived[candidate];
}
function candidateCount()
public view returns (uint256) {
return candidateList.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment