Skip to content

Instantly share code, notes, and snippets.

@ulerdogan
Created May 23, 2020 14:14
Show Gist options
  • Save ulerdogan/857cb1bcbc8e353815154c89e4ac168e to your computer and use it in GitHub Desktop.
Save ulerdogan/857cb1bcbc8e353815154c89e4ac168e 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.6.6+commit.6c089d02.js&optimize=false&gist=
pragma solidity >=0.4.22 <0.7.0;
/**
* @title Storage
* @dev Store & retreive 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 retreive() 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;
}
}
pragma solidity >=0.4.22 <0.7.0;
import "remix_tests.sol"; // this import is automatically injected by Remix.
import "./3_Ballot.sol";
contract BallotTest {
bytes32[] proposalNames;
Ballot ballotToTest;
function beforeAll () public {
proposalNames.push(bytes32("candidate1"));
ballotToTest = new Ballot(proposalNames);
}
function checkWinningProposal () public {
ballotToTest.vote(0);
Assert.equal(ballotToTest.winningProposal(), uint(0), "proposal at index 0 should be the winning proposal");
Assert.equal(ballotToTest.winnerName(), bytes32("candidate1"), "candidate1 should be the winner name");
}
function checkWinninProposalWithReturnValue () public view returns (bool) {
return ballotToTest.winningProposal() == 0;
}
}
pragma solidity ^0.5.13;
contract DebuggerExample {
uint public myUint;
function setMyUint(uint _myUint) public {
myUint = _myUint;
}
}
pragma solidity ^0.5.11;
contract EventExample {
mapping(address => uint) public tokenBalance;
event TokensSent(address _from, address _to, uint _amount);
constructor() public {
tokenBalance[msg.sender] = 100;
}
function sendToken(address _to, uint _amount) public returns(bool) {
require(tokenBalance[msg.sender] >= _amount, "Not enough tokens");
assert(tokenBalance[_to] + _amount >= tokenBalance[_to]);
assert(tokenBalance[msg.sender] - _amount <= tokenBalance[msg.sender]);
tokenBalance[msg.sender] -= _amount;
tokenBalance[_to] += _amount;
emit TokensSent(msg.sender, _to, _amount);
return true; //only Js VM can return a booL
}
}
pragma solidity ^0.5.13;
contract ExceptionExample {
mapping(address => uint64) public balanceReceived;
function receiveMoney() public payable {
assert(balanceReceived[msg.sender] + uint64(msg.value) >= balanceReceived[msg.sender]);
balanceReceived[msg.sender] += uint64(msg.value);
}
function withdrawMoney(address payable _to, uint64 _amount) public {
require(_amount <= balanceReceived[msg.sender], "Not enough money!");
assert(balanceReceived[msg.sender] >= balanceReceived[msg.sender] - _amount);
balanceReceived[msg.sender] -= _amount;
_to.transfer(_amount);
}
}
pragma solidity ^0.5.13;
contract FunctionExamples {
mapping(address => uint) public balanceReceived;
address payable owner;
//constructors are being setted on deploying and no changes
constructor() public {
owner = msg.sender;
}
//view function just viewed
function getOwner() public view returns(address){
return owner;
}
//pure functions not interact with any storage vars
function convertWeiToEther(uint _amountInWei) public pure {
_amountInWei / 1 ether; // 1 ether = 10^18 wei
}
function destroySmartContract() public{
require(msg.sender == owner, "You're not the owner!");
selfdestruct(owner);
}
function receiveMoney() public payable{
assert(balanceReceived[msg.sender] + msg.value >= balanceReceived[msg.sender]);
balanceReceived[msg.sender] += msg.value;
}
function withdrawMoney(address payable _to, uint _amount) public {
require(_amount <= balanceReceived[msg.sender], "Not enough fund!");
assert(balanceReceived[msg.sender] >= balanceReceived[msg.sender] - _amount);
balanceReceived[msg.sender] -= _amount;
_to.transfer(_amount);
}
//sending money to smart contract, fall back function without name -- always external
function () external payable {
receiveMoney();
}
}
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/math/SafeMath.sol";
contract LibariesExample {
using SafeMath for uint;
mapping(address => uint) public tokenBalance;
constructor() public {
tokenBalance[msg.sender] = tokenBalance[msg.sender].add(1);
}
function sendToken(address _to, uint _amount) public returns(bool){
tokenBalance[msg.sender] = tokenBalance[msg.sender].sub(_amount);
tokenBalance[_to] = tokenBalance[_to].add(_amount);
return true;
}
}
pragma solidity >=0.4.16 <0.7.0;
library Search {
function indexOf(uint[] storage self, uint value) public view returns (uint) {
for (uint i = 0; i < self.length; i++)if (self[i] == value) return i;
return uint(-1);
}
}
contract UsingForExample {
using Search for uint[];
uint[] data;
function append(uint value) public {
data.push(value);
}
function replace(uint _old, uint _new) public {
// This performs the library function call
uint index = data.indexOf(_old);
if (index == uint(-1))data.push(_new);
else data[index] = _new;
}
}
pragma solidity ^0.6.0;
contract MappingExamples {
//uint to bool, then publicty and var name
mapping(uint=>bool) public myMapping;
mapping(address=>bool) public myAddressMapping;
//fonksiyonda işlem gören sayılar true çıkarıyor
function setValue(uint _index) public {
myMapping[_index] = true;
}
function setMyAddress() public{
myAddressMapping[msg.sender] = true;
}
}
pragma solidity ^0.5.13;
contract MappingStructsExample {
struct Payment {
uint amount;
uint timestamps;
}
struct Balance {
uint totalBalance;
uint numPayments;
mapping(uint => Payment) payments;
}
mapping(address => Balance) public balanceReceived;
function getBalance() public view returns(uint){
return address(this).balance;
}
function sendMoney() public payable {
balanceReceived[msg.sender].totalBalance += msg.value;
Payment memory payment = Payment(msg.value, now);
balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment;
balanceReceived[msg.sender].numPayments++;
}
function withdrawMoney(address payable _to, uint _amount) public {
require(balanceReceived[msg.sender].totalBalance >= _amount, "Not enough money!" );
balanceReceived[msg.sender].totalBalance -= _amount;
_to.transfer(_amount);
}
function withdrawAllMoney(address payable _to) public {
uint balanceToSend = balanceReceived[msg.sender].totalBalance;
balanceReceived[msg.sender].totalBalance = 0;
_to.transfer(balanceToSend);
}
}
pragma solidity ^0.5.11;
//import from the same directory
import "./Owned.sol";
contract InheritanceModifierExample is Owned{ //extend the functions of Owned --inheritence
mapping(address => uint) public tokenBalance;
uint tokenPrice = 1 ether;
constructor() public {
tokenBalance[owner] = 100;
}
function createNewToken() public onlyOwner{
require(msg.sender == owner, "You are not allowed");
tokenBalance[owner]++;
}
function burnToken() public onlyOwner{
tokenBalance[owner]--;
}
function purchaseToken() public payable {
require((tokenBalance[owner] * tokenPrice) / msg.value > 0, "not enough tokens");
tokenBalance[owner] -= msg.value / tokenPrice;
tokenBalance[msg.sender] += msg.value / tokenPrice;
}
function sendToken(address _to, uint _amount) public {
require(tokenBalance[msg.sender] >= _amount, "Not enough tokens");
assert(tokenBalance[_to] + _amount >= tokenBalance[_to]);
assert(tokenBalance[msg.sender] - _amount <= tokenBalance[msg.sender]);
tokenBalance[msg.sender] -= _amount;
tokenBalance[_to] += _amount;
}
}
pragma solidity ^0.5.13;
contract MoneyExamples {
uint public balanceReceived;
//kontrata para yatırma
function receiveMoney() public payable {
balanceReceived += msg.value;
}
//bakiye sorgulama
function getBalance() public view returns(uint) {
return address(this).balance;
}
// para çekme
function withdrawMoney() public{
address payable to = msg.sender;
to.transfer(this.getBalance());
}
//belli hesaba para yatır
function withdrawMoneyTo(address payable _to) public{
_to.transfer(this.getBalance());
}
}
pragma solidity ^0.5.11;
contract MyContract {
string public mystring = "Hello World!";
}
pragma solidity ^0.5.11;
contract Owned {
address owner;
constructor() public {
owner = msg.sender;
}
//modifier needs _ on end
modifier onlyOwner() {
require(msg.sender == owner, "You are not allowed");
_;
}
}
pragma solidity >=0.5.15 <0.7.0;
contract A {
uint someUint;
function fun() public virtual {
someUint = 5;
}
}
pragma solidity >=0.5.15 <=0.6.0;
/**
* https://solidity.readthedocs.io/en/v0.6.0/060-breaking-changes.html#explicitness-requirements
* Functions can now only be overridden when they are either marked with the virtual keyword or
* defined in an interface. Functions without implementation outside an interface have to be marked virtual.
* When overriding a function or modifier, the new keyword override must be used. When overriding a function
* or modifier defined in multiple parallel bases, all bases must be listed in parentheses after the keyword
* like so: override(Base1, Base2).
*
* */
/**
* Works in Solidity 0.5.15
*
* *
contract A {
event MyEvent(string _myString);
function funA() public {
emit MyEvent("from A");
}
}
contract B {
function funA() public {
//does nothing
}
}
contract C is B,A {
function funA() public {
emit MyEvent("from B");
super.funA();
}
}
/**/
/**
* works in 0.6.0
* */
contract A {
event MyEvent(string _myString);
function funA() public virtual {
emit MyEvent("from A");
}
}
contract B {
function funA() public virtual {
//does nothing
}
}
contract C is A,B {
function funA() public override(B,A) {
emit MyEvent("from B");
super.funA();
}
}
/**
* */
pragma solidity >=0.5.15 <=0.6.0;
/**
* https://solidity.readthedocs.io/en/v0.6.0/060-breaking-changes.html#explicitness-requirements
* Member-access to length of arrays is now always read-only, even for storage arrays. It is no
* longer possible to resize storage arrays assigning a new value to their length.
* Use push(), push(value) or pop() instead, or assign a full array, which will of
* course overwrite existing content. The reason behind this is to prevent storage
* collisions by gigantic storage arrays.
*
* */
/**
* works in 0.5.15
* *
contract MyContract {
uint[] public myUintArray;
function add(uint _num) public {
myUintArray.length++;
myUintArray[myUintArray.length - 1] = _num;
}
function removeElement() public {
myUintArray.length--;
}
}
/* */
/**
* works in 0.5.15 AND 0.6.0
* */
contract MyContract {
uint[] public myUintArray;
function add(uint _num) public {
myUintArray.push(_num);
}
function removeElement() public {
myUintArray.pop();
}
}
/* */
pragma solidity >=0.5.15 <=0.6.0;
/**
* https://solidity.readthedocs.io/en/v0.6.0/060-breaking-changes.html#explicitness-requirements
* State variable shadowing is now disallowed.
* A derived contract can only declare a state variable x,
* if there is no visible state variable with the same name in any of its bases.
*/
/**
* works in 0.5.14
* *
contract A {
uint x = 123;
}
contract B is A {
uint x = 234;
}
/**/
/**
* works in 0.6.0
* */
contract A {
uint private x = 123;
}
contract B is A {
uint x = 234;
}
/**/
pragma solidity ^0.6.0;
/**
* New Fallback Function and Receive function
* for 0.6.0 only
* */
contract A {
event SomeEvent(address _addr, uint _amount);
/**
* Will be called when (fallback) is used in Remix
*/
receive() external payable {
emit SomeEvent(msg.sender, msg.value);
}
/**
* Will be called when msg.data is not empty or when receive() doesn't exist
*
* If not payable => assert-style error on msg.value not empty
* */
fallback () external {
}
}
pragma solidity ^0.6.0;
contract ContractA {
function funARequireFailure() public pure {
require(false, "This is an error String");
}
function funBRevertFailure() public pure {
revert("Error from Contract A");
}
function funCAssertFailure() public pure {
assert(false);
}
}
contract B {
ContractA instA;
event Error(string _reason);
event LowLevelError(bytes _reason);
constructor() public {
instA = new ContractA();
}
function testRequireTryCatch() public returns(bool) {
try instA.funCAssertFailure() {
return true;
} catch Error(string memory reason) {
// This is executed in case
// revert was called inside getData
// and a reason string was provided.
emit Error(reason);
return false;
} catch (bytes memory lowLevelData) {
// This is executed in case revert() was used
// or there was a failing assertion, division
// by zero, etc. inside getData.
emit LowLevelError(lowLevelData);
return false;
}
}
}
pragma solidity ^0.5.13;
contract StartStopUpdateExample {
address owner;
bool public paused;
constructor() public{
owner = msg.sender;
}
function sendMoney() public payable{
}
function setPaused(bool _paused) public{
require(msg.sender == owner, "You're not the owner!");
paused = _paused;
}
// tüm bakiyeyi çekme fonksiyonu. eğer koşul eklemezsek herkes müdahale edebilri.
// require(if,else) şeklinde kullan
function withdrawAllMoney(address payable _to) public {
require(msg.sender == owner, "You're not the owner!");
require(paused == false, "The contract has paused!");
_to.transfer(address(this).balance);
}
//smart contract yok etme
function destroyTheSmartContract(address payable _to) public{
require(msg.sender == owner, "You're not the owner!");
selfdestruct(_to); // msg.sender da labilr
}
}
pragma solidity ^0.5.13;
contract Variables {
//(u)int's defaults're 0.
uint256 public myUint;
function setMyUint(uint _myUint) public {
myUint = _myUint;
}
//boolean default'u false
bool public myBool;
function setMyBool(bool _myBool) public {
myBool = _myBool;
}
// uint'ler sarmal oluşturur. üst sınırına ulaştıktan sonra 0'a geri döner.
uint8 public my8 = 255;
function incMy() public{
my8++;
}
function decMy() public{
my8--;
}
//addressses, default is 0x00...00 view -just reading funct-
address public myAddress;
function setMyAddress(address _address) public{
myAddress = _address;
}
function getBalanceOfMyAddress() public view returns(uint){
return myAddress.balance;
}
//strings
string public myString;
function setMyString(string memory _myString) public{
myString = _myString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment