Skip to content

Instantly share code, notes, and snippets.

@yoitsyoung
Created December 13, 2020 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoitsyoung/f909a265102da19d00d44ed6f5bbe6a9 to your computer and use it in GitHub Desktop.
Save yoitsyoung/f909a265102da19d00d44ed6f5bbe6a9 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.12+commit.27d51765.js&optimize=false&runs=200&gist=
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.8.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;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.8.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() {
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;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.8.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) {
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.6.0;
import "./SupplyChain.sol";
contract ItemContract{
uint public priceInWei;
uint public paidWei;
uint public index;
/* THIS MEM ALLOCATION IS IMPORTANT */
Management parentContract;
constructor(Management _parentContract, uint _priceInWei, uint _index) public{
priceInWei = _priceInWei;
index = _index;
parentContract = _parentContract;
}
receive() external payable{
require(msg.value == priceInWei, "Partial payments not supported");
require(paidWei == 0, "Item is already paid");
paidWei += msg.value;
//For low level functions, you MUST return t/f value or you cannot catch any error
(bool success, ) = address(parentContract).call{value:msg.value}(abi.encodeWithSignature("triggerPayment(uint256)", index));
require(success, "Delivery failed at low level function");
}
fallback() external{
}
}
pragma solidity ^0.7.4;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
library HelperFunctions{
using SafeMath for uint;
function SumArray(uint[] memory _array )
public
returns(uint)
{
uint ArraySum;
for(uint i=0; i<_array.length; i++){
ArraySum.add(_array[i]);
return(ArraySum);
}
}
}
contract Libraries{
//all SafeMath functions are now USABLE for unsigned integers
using SafeMath for uint;
using HelperFunctions for uint[];
uint[] public data;
uint public constant tokenRate = 2;
mapping(address => uint) public tokenBalance;
constructor() payable {
tokenBalance[msg.sender] = msg.value.div(tokenRate);
}
function totalBalance(uint[] memory _balances) public returns(uint){
return(_balances.SumArray());
}
}
pragma solidity ^0.5.13;
contract Mapping{
struct Profile{
string name;
uint timestamps;
//assume a profile has multiple wallets
mapping(uint => address) myWallets;
}
mapping(address => bool) public AddressToBool;
mapping(address => uint) public BalanceReceived;
function allowAddress(address _allowed) public{
AddressToBool[_allowed]= true;
}
function setMyAddress() public{
AddressToBool[msg.sender] = true;
}
}
pragma solidity ^0.5.12;
contract SendMoney{
uint256 public Balance ;
function receiveMoney() public payable{
Balance = address(this).balance;
}
function getBalance() public view returns(uint){
return address(this).balance;
}
function withdraw(uint _myWithdrawal) public{
// use payable to make an address payable....
address payable sender = msg.sender;
sender.transfer(_myWithdrawal);
}
function withdrawMoneyTo(address payable _myAddress) public{
_myAddress.transfer(this.getBalance());
}
//attempt at exchanging
function exchangeMoney(address payable _myCounterparty,uint amountSent, uint amountReceived) public{
address payable _myAddress = msg.sender;
// smart contract needs to receive both amounts.....
_myCounterparty.transfer(amountSent);
_myAddress.transfer(amountReceived);
}
}
pragma solidity ^0.7.4;
import './2_Owner.sol';
contract Treasury is Owner{
address private _owner;
uint private conversionRate;
uint public TotalAmount;
constructor(){
_owner = msg.sender;
conversionRate = 2;
}
struct Payment{
uint timestamp;
uint amount;
}
struct Profile{
uint id ;
string name;
uint profileValue;
mapping(uint => Payment) myPayments;
}
mapping(address => Profile) public myProfile;
event Wallet(uint indexed id, address _owner, uint totalAmount);
event UpdateMessage(uint indexed id, string message, uint value);
modifier logger(){
Update
}
function deposit() payable public{
require(_owner == msg.sender, "Only those who deployed have access.");
assert(msg.value + TotalAmount > TotalAmount);
TotalAmount += msg.value;
}
//not sure what indexed does
fallback() external{
wow = data;
emit UpdateMessage(1, myProfile[msg.sender].name, 0);
}
}
pragma solidity ^0.6.0;
/* Wallet where a central party can:
Deposit Money (Any Amount)
Approve request to withdraw
Users can only:
Request to withdraw money (any amount)
*/
//This is bad practice.
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
contract Permissions{
address private sysAdmin;
address[] public memberList;
struct addressStruct{
bool isMember;
string name;
uint numWithdraws;
uint amount;
}
mapping(address => addressStruct) public addressDetails;
constructor() public{
sysAdmin = msg.sender;
}
modifier AdminOnly{
require(msg.sender == sysAdmin, "You do not have rights to this function");
_;
}
modifier MemberOnly{
require(addressDetails[msg.sender].isMember == true, "You're not yet a member");
_;
}
function AddMember(address _member) AdminOnly public{
addressDetails[_member].isMember = true;
}
}
contract WalletInteractions is Permissions{
using SafeMath for uint;
uint public totalWalletBalance;
struct withdrawalRequest{
address withdrawerAddress;
uint amount;
bool isFulfilled;
}
withdrawalRequest[] public withdrawalList;
event BalanceUpdate(string action, address indexed actionAddress, uint amount, uint balanceLeft);
function deposit() payable external AdminOnly{
totalWalletBalance.add(msg.value);
emit BalanceUpdate("Deposit", msg.sender, msg.value, totalWalletBalance);
}
function requestWithdraw(uint _amount) external MemberOnly returns (uint rowNumber) {
require(_amount >0 , "Please input a positive value");
withdrawalRequest memory newRequest;
newRequest = withdrawalRequest(msg.sender, _amount, false);
//push doesn't work here. no idea why
withdrawalList.push(newRequest);
return withdrawalList.length -1;
}
function approveWithdraw(uint _index) external AdminOnly{
uint requestAmount = withdrawalList[_index].amount;
address payable requestAddress = payable(withdrawalList[_index].withdrawerAddress);
assert(addressDetails[requestAddress].isMember == true);
assert(totalWalletBalance - requestAmount <= totalWalletBalance);
totalWalletBalance.sub(requestAmount);
// I suppose pop is a vulnerability. So instead of deleting from your array list, you'd rather change boolean of whether the withdrawal is fulfilled
withdrawalList[_index].isFulfilled = true;
requestAddress.transfer(requestAmount);
emit BalanceUpdate("Withdraw", requestAddress, requestAmount, totalWalletBalance);
}
}
pragma solidity ^0.5.13;
//This is about authority control
//Save owner of address during deployment
contract StartStopUpdate{
//notice how they are not public
address owner;
bool paused;
//Constructors are called ONLY ONCE
constructor() public{
owner = msg.sender;
}
function togglePause() public{
require(owner == msg.sender,"You are not an owner");
paused = !paused;
}
function withdrawAllMoney(address payable _to) public{
require(owner == msg.sender,"You are not an owner");
require(!paused, "Contract is not functioning");
_to.transfer(address(this).balance);
}
//destroy smart Contract
function destroySmartContract(address payable _to) public{
require(owner == msg.sender, "Only owner can destroy");
//selfdestruct takes a address to send a fund to
selfdestruct(_to);
}
}
pragma solidity ^0.5.13;
contract StructPractice{
struct Payment{
uint amount;
uint timestamp;
}
struct Balance{
uint amount;
uint numPayments;
mapping(uint => Payment) payments;
}
mapping(address => Balance) public AddressBalance;
address public Owner;
constructor() public{
Owner = msg.sender;
}
function sendMoney() payable public{
//make sure balance variable cannot be
AddressBalance[msg.sender].amount += msg.value;
AddressBalance[msg.sender].payments[AddressBalance[msg.sender].numPayments] = Payment(msg.value, now);
AddressBalance[msg.sender].numPayments++;
}
function withdrawMoney(address payable _to, uint amount) public{
require(AddressBalance[msg.sender].amount >= amount, "Not enough funds");
//notice the difference, even though they appear like similar logic
assert(AddressBalance[msg.sender].amount > AddressBalance[msg.sender].amount -amount);
AddressBalance[msg.sender].amount -= amount;
AddressBalance[msg.sender].payments[AddressBalance[msg.sender].numPayments] = Payment(amount, now);
AddressBalance[msg.sender].numPayments++;
_to.transfer(amount);
}
function fallback() payable external returns(string){
// Handle contract execution
require(msg.data.length == 0);
// So that only money is sent, no malicious data
string memory data = msg.data;
return data;
}
//receive transaction without calling function... deprecated?
receive () external payable{
}
//assuming you only want to call this internally, within this smart contract
function sum(int _amount1, int _amount2) internal pure returns(int){
return amount1+amount2;
}
}
pragma solidity ^0.5.13;
contract StructTest{
struct Balance{
uint value;
mapping(uint => Payment) Payments;
}
struct Payment{
uint value;
uint time;
mapping(uint => address) paidTo;
}
mapping(address => Balance) public addressWallets;
address public owner;
//set initial wallet owner
//Use constructor
constructor() public{
owner = msg.sender;
}
function viewWallets() public view returns (uint){
require(owner == msg.sender, "You must be the owner of this contract to view your wallet");
return(addressWallets[msg.sender].value);
}
function sendMoney(uint amount, address payable _to) public {
require(owner == msg.sender, "You must be the owner of this contract to view your wallet");
Payment memory payment = Payment(amount, now);
payment.paidTo[0] = _to;
}
}
pragma solidity ^0.6.0;
import './ItemContracts.sol';
contract Management{
//enums is a subspace of values.... it is a pointer in itself that can point to any of the values it can take, as defined below. An enum defines a type, where all its values are its members
enum SupplyChainState{CREATED, PAID, DELIVERED}
struct Item{
ItemContract _ItemContract;
string identifier;
uint index;
uint price;
Management.SupplyChainState state;
}
//You could literally create an itemContract embedded within each Item Structure..... this is how consumers can simply interact with one address to
//pay for an item.
mapping(uint => Item) public items;
//Use an index variable to track the index? Is there a more elegant way?
uint itemIndex;
event ItemStep(uint itemIndex, uint SupplyChainState);
function createItem(string memory _identifier, uint _price) public{
//Notice how you initialize a new contract , with parameter parentfunction, as defined in Intemcontracts.sol;
ItemContract _newItemContract = new ItemContract(this, _price,itemIndex);
Item memory newItem = Item(_newItemContract, _identifier, itemIndex, _price, SupplyChainState.CREATED);
items[itemIndex] = newItem;
emit ItemStep(itemIndex, uint(newItem.state));
//remember to increment
itemIndex++;
}
function triggerPayment(uint _itemIndex) payable public{
require(_itemIndex<=itemIndex, "Your index is out of range of values");
require(items[_itemIndex].price == msg.value);
require(items[_itemIndex].state == SupplyChainState.CREATED, "Item is not at CREATED step of the supply chain");
items[_itemIndex].state = SupplyChainState.PAID;
emit ItemStep(_itemIndex,uint(items[_itemIndex].state));
}
function triggerDelivery(uint _itemIndex) public{
require(_itemIndex<=itemIndex, "Your index is out of range of values");
require(items[_itemIndex].state == SupplyChainState.PAID, "Item is not at PAID step of the supply chain");
items[_itemIndex].state = SupplyChainState.DELIVERED;
emit ItemStep(_itemIndex,uint(items[_itemIndex].state));
}
}
pragma solidity >=0.7.0;
import "./2_Owner.sol";
contract TokenContract is Owner{
uint public Circulation ;
address public Contractor ;
uint public EthTokenRate;
uint public ReserveBalance;
constructor() {
Contractor = msg.sender;
Circulation = 1000000000000000;
EthTokenRate = 2;
}
event TokenExchanged(address _from, uint amount, uint indexed _id);
modifier onlyHighValue(){
require(msg.value >= 10000, "value too low!");
_;
}
function ethToToken(uint eth) public view returns(uint){
return eth/EthTokenRate;
}
function exchange() payable external onlyHighValue isOwner{
uint mintAmount;
mintAmount = ethToToken(msg.value);
ReserveBalance -= mintAmount;
emit TokenExchanged(msg.sender, mintAmount, 1);
}
fallback() payable external{
require(msg.data.length == 0, "only value allowed");
}
}
pragma solidity ^0.5.11;
// State change only happens with transaction + mining
contract WorkingWithVariables{
uint256 public myUint;
bool public myBool;
uint8 public myUint8;
string public myString;
address public myAddress;
//Setter function
function setmyUint(uint _myUint) public{
myUint = _myUint;
}
function setmyBool(bool _myBool) public{
myBool = _myBool;
}
function increment() public{
myUint8++;
}
function setmyString(string memory _myString) public{
myString = _myString;
}
function setAddress(address _myAddress) public{
myAddress = _myAddress;
}
function getAddressBalance() public view returns(uint){
return myAddress.balance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment