Skip to content

Instantly share code, notes, and snippets.

@Kowsi
Created August 28, 2020 05:08
Show Gist options
  • Save Kowsi/b3f3b90c56e8a4b6bceb8a0b5c7e48d3 to your computer and use it in GitHub Desktop.
Save Kowsi/b3f3b90c56e8a4b6bceb8a0b5c7e48d3 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.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.5.0;
// @TODO: import the SafeMath library via Github URL
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/math/SafeMath.sol";
contract ArcadeToken {
// @TODO: add the "using SafeMath..." line here to link the library to all uint types
using SafeMath for uint;
address payable owner = msg.sender;
string public symbol;
uint public exchange_rate;
uint public fee_rate;
uint public reward_rate = 3;
mapping(address => uint) balances;
constructor (string memory _symbol, uint _exchange_rate, uint _fee_rate) public {
symbol = _symbol;
exchange_rate = _exchange_rate;
fee_rate = _fee_rate;
}
function balance() public view returns(uint) {
return balances[msg.sender];
}
function transfer(address recipient, uint value) public {
// @TODO: replace the following with the .sub function
balances[msg.sender] = balances[msg.sender].sub(value);
// @TODO: replace the following with the .add function
balances[recipient] = balances[recipient].add(value);
}
function purchase() public payable {
// @TODO: replace the following with the .mul function
uint amount = msg.value.mul(exchange_rate);
// @TODO: replace the following with the .add function
balances[msg.sender] = balances[msg.sender].add(amount);
owner.transfer(msg.value);
}
function mint(address recipient, uint value) public {
require(msg.sender == owner, "You do not have permission to mint tokens!");
// @TODO: replace the following with the .add function
balances[recipient] = balances[recipient].add(value);
}
}
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20Detailed.sol";
contract ArcadeToken is ERC20, ERC20Detailed {
address payable owner;
modifier onlyOwner {
require(msg.sender == owner, "You do not have permission to mint these tokens!");
_;
}
constructor(string memory name, string memory symbol, uint initial_supply) ERC20Detailed(name, symbol, 18) public {
owner = msg.sender;
_mint(owner, initial_supply);
}
function mint(address recipient, uint amount) public onlyOwner {
_mint(recipient, amount);
}
}
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20Detailed.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20Mintable.sol";
contract ArcadeToken is ERC20, ERC20Detailed, ERC20Mintable {
constructor(
string memory name,
string memory symbol
)
ERC20Detailed(name, symbol, 18)
public
{
//mint(msg.sender, initial_supply); // remove this line to prevent minting to the ArcadeTokenSaleDeployer
}
}
pragma solidity ^0.5.0;
// Import ArcadeTokenMintable
import "./ArcadeTokenMintable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/Crowdsale.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/emission/MintedCrowdsale.sol";
contract ArcadeTokenSale is Crowdsale, MintedCrowdsale {
// Build the constructor, passing in the parameters that Crowdsale needs
constructor(
uint rate,
address payable wallet,
ArcadeToken token
)
Crowdsale (rate, wallet, token) public{
}
}
contract ArcadeTokenSaleDeployer {
// Add public addresses to keep track of the token_address and arcade_sale_address
address public arcade_sale_address;
address public token_address;
constructor(
string memory name,
string memory symbol,
address payable wallet // this address will receive all Ether raised by the sale
)
public
{
// create the ArcadeToken and keep its address handy
ArcadeToken token = new ArcadeToken(name, symbol);
token_address = address(token);
// create the ArcadeTokenSale and tell it about the token, then keep its address handy
ArcadeTokenSale arcade_sale = new ArcadeTokenSale(1, wallet, token);
arcade_sale_address = address(arcade_sale);
// make the ArcadeTokenSale contract a minter, then have the ArcadeTokenSaleDeployer renounce its minter role
token.addMinter(arcade_sale_address);
token.renounceMinter();
}
}
pragma solidity ^0.5.0;
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/math/SafeMath.sol";
contract ArcadeTokenVulnerable {
using SafeMath for uint;
address payable owner = msg.sender;
string public symbol = "ARCD";
uint public exchange_rate = 100;
mapping(address => uint) private balances;
function balance() public view returns(uint) {
return balances[msg.sender];
}
function transfer(address recipient, uint value) public {
balances[msg.sender] = balances[msg.sender].sub(value);
balances[recipient] = balances[recipient].add(value);
}
function purchase() public payable {
uint amount = msg.value * exchange_rate;
balances[msg.sender] = balances[msg.sender].add(amount);
owner.transfer(msg.value);
}
function mint(address recipient, uint value) public {
require(msg.sender == owner, "You do not have permission to mint tokens!");
balances[recipient] = balances[recipient].add(value);
}
function withdrawBalance() public{
uint amount = balances[msg.sender];
balances[msg.sender] = 0;
(bool success, ) = msg.sender.call.value(amount)("");
if(!success ){
revert();
}
}
}
pragma solidity ^0.5.0;
import "github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/math/SafeMath.sol";
// lvl 1: equal split
contract AssociateProfitSplitter {
using SafeMath for uint;
// Create three payable addresses representing `employee_one`, `employee_two` and `employee_three`.
address payable employee_one;
address payable employee_two;
address payable employee_three;
address payable owner;
constructor(address payable _one, address payable _two, address payable _three) public {
employee_one = _one;
employee_two = _two;
employee_three = _three;
owner = msg.sender;
}
function balance() public view returns(uint) {
return address(this).balance;
}
function deposit() public payable {
// Ensuring that only the owner can call the function
require(msg.sender==owner, 'Only Owner has permission to Pay the Associate!');
// Split `msg.value` into three
uint amount = msg.value.div(3);
// Transfer the amount to each employee
employee_one.transfer(amount);
employee_two.transfer(amount);
employee_three.transfer(amount);
// Take care of a potential remainder by sending back to HR (`msg.sender`)
uint remaining_amt = msg.value - (amount * 3);
msg.sender.transfer(remaining_amt);
}
function() external payable {
// Enforce that the `deposit` function is called in the fallback function!
deposit();
}
}
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC721/ERC721Full.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/drafts/Counters.sol";
contract CryptoFax is ERC721Full {
constructor() ERC721Full("CryptoFax", "CARS") public { }
using Counters for Counters.Counter;
Counters.Counter token_ids;
struct Car {
string vin;
uint accidents;
}
// Stores token_id => Car
// Only permanent data that you would need to use in a smart contract later should be stored on-chain
mapping(uint => Car) public cars;
event Accident(uint token_id, string report_uri);
function registerVehicle(address owner, string memory vin, string memory token_uri) public returns(uint) {
token_ids.increment();
uint token_id = token_ids.current();
_mint(owner, token_id);
_setTokenURI(token_id, token_uri);
cars[token_id] = Car(vin, 0);
return token_id;
}
function reportAccident(uint token_id, string memory report_uri) public returns(uint) {
cars[token_id].accidents += 1;
// Permanently associates the report_uri with the token_id on-chain via Events for a lower gas-cost than storing directly in the contract's storage.
emit Accident(token_id, report_uri);
return cars[token_id].accidents;
}
}
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/drafts/Counters.sol";
import "../ICryptoRight.sol";
contract CryptoRight is ICryptoRight {
using Counters for Counters.Counter;
Counters.Counter copyright_ids;
// @TODO: Implement the copyrights mapping
mapping(uint =>IWork) public copyrights;
// @TODO: Implement the Copyright Event
event Copyright(uint copyright_id, address owner, string reference_uri);
// @TODO: Implement the OpenSource Event
event OpenSource(uint copyright_id, string reference_uri);
// @TODO: Implement the Transfer Event
event Transfer(uint copyright_id, address new_owner);
modifier onlyCopyrightOwner(uint copyright_id) {
// @TODO: Check if copyright owner is equal to msg.sender
require(copyrights[copyright_id].owner == msg.sender, "You do not have permission to alter this copyright!");
_;
}
function copyrightWork(string memory reference_uri) public {
// @TODO: Implement the copyrightWork function
copyright_ids.increment();
uint id = copyright_ids.current();
copyrights[id] = IWork(msg.sender, reference_uri);
emit Copyright(id, msg.sender, reference_uri);
}
function openSourceWork(string memory reference_uri) public {
copyright_ids.increment();
uint id = copyright_ids.current();
copyrights[id].uri = reference_uri;
// no need to set address(0) in the copyrights mapping as this is already the default for empty address types
emit OpenSource(id, reference_uri);
}
function transferCopyrightOwnership(uint copyright_id, address new_owner) public onlyCopyrightOwner(copyright_id) {
// Re-maps a given copyright_id to a new copyright owner.
copyrights[copyright_id].owner = new_owner;
emit Transfer(copyright_id, new_owner);
}
function renounceCopyrightOwnership(uint copyright_id) public onlyCopyrightOwner(copyright_id) {
// Re-maps a given copyright_id to the 0x0000000000000000000000000000000000000000
transferCopyrightOwnership(copyright_id, address(0));
emit OpenSource(copyright_id, copyrights[copyright_id].uri);
}
}
pragma solidity ^0.5.0;
contract DayTradingAccount {
// Initializes a payable address variable for the contract owner
address payable public owner;
uint public unlock_time;
// Initializes a uint timelock variable
// Constructor for setting the owner of the contract as the one who deploys the contract
constructor () public{
owner = msg.sender;
}
// Obtains the balance residing within the contract
function getBalance() public view returns(uint){
return address(this).balance;
}
// Withdraws the balance to a specified recipient
function withdraw(address payable recipient, uint amount) public payable{
require(recipient==owner, 'You are not the owner of this account. Permission denied.');
require (unlock_time < now, 'You need to wait at least 24 hours from the last withdrawal before making another one.');
require (address(this).balance - amount > 25000, 'Withdrawing this amount would put you below the day trading threshold of 25,000 wei.');
unlock_time = now + 24 hours;
recipient.transfer(amount);
}
// Makes a deposit to the contract
function deposit() public payable{
}
// Fallback function
function() external payable{
}
}
pragma solidity ^0.5.0;
// lvl 3: equity plan
contract DeferredEquityPlan {
address human_resources;
address payable employee; // bob
bool active = true; // this employee is active at the start of the contract
// Set the total shares and annual distribution
uint total_shares = 1000;
uint annual_distribution = 250;
uint start_time = now; // permanently store the time this contract was initialized
// Set the `unlock_time` to be 365 days from now
uint unlock_time = start_time + 365 days;
uint fakenow = now;
uint public distributed_shares; // starts at 0
constructor(address payable _employee) public {
human_resources = msg.sender;
employee = _employee;
}
function distribute() public {
require(msg.sender == human_resources || msg.sender == employee, "You are not authorized to execute this contract.");
require(active == true, "Contract not active.");
require(unlock_time<=fakenow, '`unlock_time` is less than or equal to `now`');
require(distributed_shares<total_shares, 'Not enough share to dsitribute!');
// Add 365 days to the `unlock_time`
unlock_time += 365 days;
// Calculate the shares distributed
distributed_shares = ((fakenow - start_time) / 365 days) * annual_distribution;
// double check in case the employee does not cash out until after 5+ years
if (distributed_shares > 1000) {
distributed_shares = 1000;
}
}
// human_resources and the employee can deactivate this contract at-will
function deactivate() public {
require(msg.sender == human_resources || msg.sender == employee, "You are not authorized to deactivate this contract.");
active = false;
}
//For "fast forward" time by 100 days
function fastforward() public {
fakenow += 365 days;
}
// Since we do not need to handle Ether in this contract, revert any Ether sent to the contract directly
function() external payable {
revert("Do not send Ether to this contract!");
}
}
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20Detailed.sol";
contract ErcArcade is ERC20, ERC20Detailed {
address payable owner;
modifier onlyOwner {
require(msg.sender == owner, 'You dont have permission to mint these tokens!');
_; // this underscore sends us back to the function that called this modifier
}
constructor(uint initial_supply) ERC20Detailed('ArcadeToken', 'ARCD', 18) public {
owner = msg.sender;
_mint(owner, initial_supply);
}
function mint(address recipient, uint amount) public onlyOwner {
_mint(recipient, amount);
}
}
pragma experimental ABIEncoderV2;
pragma solidity ^0.5.0;
interface ICryptoRight {
struct IWork {
address owner;
string uri;
}
event Copyright(uint copyright_id, address owner, string reference_uri);
event OpenSource(uint copyright_id, string reference_uri);
event Transfer(uint copyright_id, address new_owner);
function copyrights(uint copyright_id) external returns(IWork memory);
function copyrightWork(string calldata reference_uri) external;
function openSourceWork(string calldata reference_uri) external;
function renounceCopyrightOwnership(uint copyright_id) external;
function transferCopyrightOwnership(uint copyright_id, address new_owner) external;
}
pragma solidity ^0.5.0;
contract JointSavings {
address payable account_one; // = 0x6c215e0Cc4c7d78457f5E97e8f873a82cd8b26A0;
address payable account_two; //= 0xa0193811cC5d546562aE254462257bEb25Aa0347;
address public last_to_withdraw;
uint public last_withdraw_block;
uint public last_withdraw_amount;
address public last_to_deposit;
uint public last_deposit_block;
uint public last_deposit_amount;
uint unlock_time;
uint fakenow = now;
constructor (address payable _one, address payable _two) public{
account_one = _one;
account_two = _two;
}
function withdraw (uint amount) public payable{
//require (unlock_time < fakenow, 'Account locked!');
require (msg.sender==account_one || msg.sender==account_two, "You don't own the recipient");
if(last_to_withdraw != msg.sender){
last_to_withdraw = msg.sender;
}
last_withdraw_block = block.number;
last_withdraw_amount = msg.value;
if(amount > address(this).balance/3){
unlock_time = fakenow + 24 hours;
}
msg.sender.transfer(amount);
}
function fastforward() public {
fakenow += 100 days;
}
function deposit() public payable{
if(last_to_deposit != msg.sender){
last_to_deposit = msg.sender;
}
last_deposit_block = block.number;
last_deposit_amount = msg.value;
}
function () external payable{
}
}
/*
1. Use the `latest_trade.sol` file to create a contract named `LatestTrade` that contains:
* A string variable `coin` with the value `XRP` assigned to it.
* An unsigned integer variable `price`.
* A boolean variable `is_buy_price`.
2. Add a function named `updateTrade` to the `LatestTrade` contract as follows:
* Define a in-memory string variable `new_coin` as the first parameter.
* Define an unsigned integer variable `new_price` as the second parameter.
* Define a boolean variable `is_buy` as the third parameter.
* Into the body of the function, set the contract variables `coin`, `price`, and `is_buy_order` to the inputs of
the `updateTrade` function. This function will update the contract variables via the `updateTrade` function.
3. Add a public getter function `getTrade` and public function `setTrade` to the `LatestTrade` contract as follows.
* The `getTrade` function should return the `coin`, `price`, and `is_buy_order` variables of the `LatestTrade`
contract.
* The `setTrade` function should set the `coin`, `price`, and `is_buy_order` variables with the values of the
input parameters `new_coin`, `new_price`, and `is_buy`.
*/
pragma solidity ^0.5.0;
contract LatestTrade{
string coin = 'XRP';
uint price;
bool is_buy_price;
function updateTrade(string memory new_coin, uint new_price, bool is_buy) public{
coin = new_coin;
price = new_price;
is_buy_price = is_buy;
}
//View - wont cause any gas cost
function getTrade() public view returns (string memory, uint, bool){
return (coin, price, is_buy_price);
}
function setTrade(string memory new_coin, uint new_price, bool is_buy) public{
coin = new_coin;
price = new_price;
is_buy_price = is_buy;
}
}
contract TradeController{
uint previous_price;
string trade_type;
function makeTrade(uint current_price, bool buy_anyway) public{
if (current_price < previous_price || buy_anyway){
trade_type = 'Buy';
previous_price = current_price;
} else if (current_price > previous_price) {
trade_type = 'Sell';
previous_price = current_price;
} else {
trade_type = 'Hold';
}
}
}
pragma solidity >=0.4.22 <0.6.0;
contract MartianAuction {
address public deployer;
//track the beneficiary of the contract
address payable public beneficiary;
//keep track of the address of the current highest bidder
address public highestBidder;
uint public highestBid;
uint public minBid;
mapping (address => uint) pendingReturns;
bool public ended;
event HighestBidIncreased(address bidder, uint amount);
event AuctionEnded(address winner, uint amount);
// The following is a so-called natspec comment,
// recognizable by the three slashes.
// It will be shown when the user is asked to
// confirm a transaction.
/// Create a simple auction with `_biddingTime`
/// seconds bidding time on behalf of the
/// beneficiary address `_beneficiary`.
constructor(
address payable _beneficiary,
uint _minBid
) public {
deployer = msg.sender; // set as the MartianMarket
beneficiary = _beneficiary;
minBid = _minBid;
}
/// Bid on the auction with the value sent
/// together with this transaction.
/// The value will only be refunded if the
/// auction is not won.
function bid(address payable sender) public payable {
// If the bid is not higher, send the
// money back.
require(
msg.value > highestBid,
"There already is a higher bid."
);
require(!ended, "auctionEnd has already been called.");
if (highestBid != 0) {
// Sending back the money by simply using
// highestBidder.send(highestBid) is a security risk
// because it could execute an untrusted contract.
// It is always safer to let the recipients
// withdraw their money themselves.
pendingReturns[highestBidder] += highestBid;
}
highestBidder = sender;
highestBid = msg.value;
emit HighestBidIncreased(sender, msg.value);
}
/// Withdraw a bid that was overbid.
function withdraw() public returns (bool) {
uint amount = pendingReturns[msg.sender];
if (amount > 0) {
// It is important to set this to zero because the recipient
// can call this function again as part of the receiving call
// before `send` returns.
pendingReturns[msg.sender] = 0;
if (!msg.sender.send(amount)) {
// No need to call throw here, just reset the amount owing
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
function pendingReturn(address sender) public view returns (uint) {
return pendingReturns[sender];
}
/// End the auction and send the highest bid
/// to the beneficiary.
function auctionEnd() public {
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
// 1. Conditions
require(!ended, "auctionEnd has already been called.");
require(msg.sender == deployer, "You are not the auction deployer!");
// 2. Effects
ended = true;
emit AuctionEnded(highestBidder, highestBid);
// 3. Interaction
beneficiary.transfer(highestBid);
}
}
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC721/ERC721Full.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/ownership/Ownable.sol";
import "./MartianAuction.sol";
contract MartianMarket is ERC721Full, Ownable {
constructor() ERC721Full("MartianMarket", "MARS") public {}
using Counters for Counters.Counter;
Counters.Counter token_ids;
address payable foundation_address = msg.sender;
mapping(uint => MartianAuction) public auctions;
modifier landRegistered(uint token_id) {
require(_exists(token_id), "Land not registered!");
_;
}
function createAuction(uint token_id, uint minBid) public onlyOwner {
auctions[token_id] = new MartianAuction(foundation_address, minBid);
}
function registerLand(string memory uri, uint minBid) public payable onlyOwner {
token_ids.increment();
uint token_id = token_ids.current();
_mint(foundation_address, token_id);
_setTokenURI(token_id, uri);
createAuction(token_id, minBid);
}
function endAuction(uint token_id) public onlyOwner landRegistered(token_id) {
MartianAuction auction = auctions[token_id];
auction.auctionEnd();
safeTransferFrom(owner(), auction.highestBidder(), token_id);
}
function auctionEnded(uint token_id) public view landRegistered(token_id) returns(bool) {
MartianAuction auction = auctions[token_id];
return auction.ended();
}
function highestBid(uint token_id) public view landRegistered(token_id) returns(uint) {
MartianAuction auction = auctions[token_id];
return auction.highestBid();
}
function pendingReturn(uint token_id, address sender) public view landRegistered(token_id) returns(uint) {
MartianAuction auction = auctions[token_id];
return auction.pendingReturn(sender);
}
function bid(uint token_id) public payable landRegistered(token_id) {
MartianAuction auction = auctions[token_id];
auction.bid.value(msg.value)(msg.sender);
}
}
pragma solidity ^0.5.0;
contract MessageBoard {
string public message;
function setMessage(string memory newMessage) public {
message = newMessage;
}
}
pragma solidity ^0.5.0;
/*
4. Modify the `personal_savings.sol` starter file as follows:
* Define a public function `withdraw` with two input parameters. An unsigned integer `amount`,
and a payable address `recipient`.
* In the body of the `withdraw` function, set a return value the result of the `transfer` function on the
`recipient` address using the parametrized `amount`.
* Add a public payable function `deposit`.
* Add a payable fallback function.
*/
contract PersonalSavings {
address payable public public_savings = 0x6c215e0Cc4c7d78457f5E97e8f873a82cd8b26A0;
address payable private_savings = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;
string account_holder = "Jane Doe";
address last_to_withdraw;
uint last_withdraw_block;
uint last_withdraw_amount;
address last_to_deposit;
uint last_deposit_block;
uint last_deposit_amount;
function withdraw (uint amount) public{
require ((msg.sender == public_savings || msg.sender == private_savings), 'This is not your account');
require ((address(this).balance >= amount), "you don't have fund!");
if (last_to_withdraw != msg.sender){
last_to_withdraw = msg.sender;
}
last_withdraw_block = block.number;
last_withdraw_amount = amount;
msg.sender.transfer(amount);
}
function contractBalance() public view returns(uint) {
return(address(this).balance);
}
function deposit() public payable{
if (last_to_deposit != msg.sender){
last_to_deposit = msg.sender;
}
last_deposit_block = block.number;
last_deposit_amount = msg.value;
}
function () external payable{
}
}
pragma solidity ^0.5.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20Detailed.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/ERC20Mintable.sol";
contract PupperCoin is ERC20, ERC20Detailed, ERC20Mintable {
constructor(
string memory name,
string memory symbol,
uint8 initial_supply
)
ERC20Detailed(name, symbol, initial_supply)
public
{
}
}
pragma solidity ^0.5.0;
import "./PupperCoin.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/Crowdsale.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/emission/MintedCrowdsale.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/validation/CappedCrowdsale.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/validation/TimedCrowdsale.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/distribution/RefundablePostDeliveryCrowdsale.sol";
/* This PupperCoinCrowdsale contract will manage the entire process, allowing users to send ETH and get back PUP (PupperCoin).
This contract will mint the tokens automatically and distribute them to buyers in one transaction.
*/
// Inherit the Crowdsale, MintedCrowdsale, CappedCrowdsale, TimedCrowdsale, RefundablePostDeliveryCrowdsalecontracts
contract PupperCoinCrowdsale is Crowdsale, MintedCrowdsale, CappedCrowdsale, TimedCrowdsale, RefundablePostDeliveryCrowdsale{
uint fakenow;
constructor (
uint rate, // rate in TKNbits
//string memory name,
//string memory symbol,
address payable wallet,
PupperCoin token,
uint goal,
uint open,
uint close
)
PostDeliveryCrowdsale()
Crowdsale(rate, wallet, token)
CappedCrowdsale(goal)
//TimedCrowdsale(open = now, close = now + 1 minutes) in this case
//TimedCrowdsale(open = now, close = now + 24 weeks) in the original question
//TimedCrowdsale(fakenow, now + 1 minutes)
TimedCrowdsale(open, close)
RefundableCrowdsale(goal)
public
{
}
}
contract PupperCoinSaleDeployer {
address public token_sale_address;
address public token_address;
uint fakenow = now;
uint rate = 1; //5000000000000000000; //1 ETH to wei
constructor(
string memory name,
string memory symbol,
address payable wallet, // this address will receive all Ether raised by the sale
uint goal
)
public
{
// create the PupperCoin and keep its address handy
PupperCoin pupper_token = new PupperCoin(name, symbol, 18);
token_address = address(pupper_token);
// The PupperCoinSale and tell it about the token, set the goal, and set the open and close times to now and now + 24 weeks.
PupperCoinCrowdsale pupper_sale = new PupperCoinCrowdsale(rate, wallet, pupper_token, rate * goal, fakenow, now + 5 minutes);
//PupperCoinCrowdsale pupper_sale = new PupperCoinCrowdsale(rate, wallet, pupper_token, goal, now, now + 24 weeks);
token_sale_address = address (pupper_sale);
// make the PupperCoinSale contract a minter, then have the PupperCoinSaleDeployer renounce its minter role
pupper_token.addMinter(token_sale_address);
pupper_token.renounceMinter();
}
}
pragma solidity ^0.5.0;
contract SimpleCustomerAccount {
address owner;
bool is_new_account;
uint account_balance;
string customer_name;
function getInfo() public view returns(address, bool, uint, string memory) {
return (owner, is_new_account, account_balance, customer_name);
}
function setInfo(address newOwner, bool isNewAccount, uint newAccountBalance, string memory newCustomerName) public {
owner = newOwner;
is_new_account = isNewAccount;
account_balance = newAccountBalance;
customer_name = newCustomerName;
}
}
pragma solidity ^0.5.0;
// lvl 2: tiered split
contract TieredProfitSplitter {
address payable employee_one; // ceo
address payable employee_two; // cto
address payable employee_three; // bob
constructor(address payable _one, address payable _two, address payable _three) public {
employee_one = _one;
employee_two = _two;
employee_three = _three;
}
// Should always return 0! Use this to test your `deposit` function's logic
function balance() public view returns(uint) {
return address(this).balance;
}
function deposit() public payable {
uint points = msg.value / 100; // Calculates rudimentary percentage by dividing msg.value into 100 units
uint total = 0;
uint amount;
// Calculate and transfer the distribution percentage
amount = points * 60;
total += amount;
employee_one.transfer(amount);
amount = points * 25;
total += amount;
employee_two.transfer(amount);
amount = points * 15;
total += amount;
employee_three.transfer(amount);
employee_one.transfer(msg.value - total); // employee with the highest percentage gets the remaining wei
}
function() external payable {
deposit();
}
}
// Variables Declaration and Basic Operations
pragma solidity ^0.5.0;
// This is a comment - any code commented is not executed -
/*
This is a multi-line comment.
You can comment out many lines at once.
For the most part, you will see single-line comments, but it is good to see this.
As in single-line comments, any code contained within multi-line comments is not executed.
*/
contract TravelExpenses {
// 1. Create a public payable address variable named `corporate_account` and assign a valid Ethereum address to it.
address public payable corporate_account = 0x6c215e0Cc4c7d78457f5E97e8f873a82cd8b26A0;
// 2. Create payable address variable named `personal_account` and assign a valid Ethereum address to it
address payable personal_account = 0xa0193811cC5d546562aE254462257bEb25Aa0347;
// 3. Define and assign a string variable named "employee_name` that has your name.
string employee_name = 'Kowsalya';
// 4. Create a constant `256 bit` unsigned integer `daily_expenses_eth` with an initial value of `1`.
uint256 daily_expresses_eth = 1;
// 5. Create a `256 bit` unsigned integer named `current_expenses_wei` with an initial value of `0`.
uint current_expenses_wei = 0;
// 6. Create an unsigned integer `current_taxes_wei` with an initial value of `0`.
uint current_taxes_wei= 0;
// 7. Create a `16 bit` unsigned integer `expenses_count` and assign a value of `0`.
uint16 expenses_count = 0;
// 8. Create an unsigned `32 bit` integer `eth_usd_rate` and assign the current value in USD of `1 ETH` to it.
uint32 eth_usd_rate = 400;
// 9. Create a `256` unsigned integer constant `eth_wei_rate` and assign the number of Wei in one Ether.
uint256 eth_wei_rate = 1;
// 10. Create a new public unsigned `256 bit` integer variable named `daily_expenses_wei` and assign the value of
// `daily_expenses_eth` plus eth_wei_rate.
uint256 public daily_expenses_wei = daily_expenses_eth + eth_wei_rate;
function RecordExpense(uint32 new_net_expense_usd, uint tax_rate) public {
// 11. Create an unsigned `256 bit` integer `expense_usd_no_tax` and assign the value of the `new_expensed_usd`
// minus taxes.
uint256 expense_usd_no_tax = new_expensed_usd - taxes;
// 12. Create an unsigned `256 bit` integer `taxes_usd` and assign the taxes in USD from `new_net_expense_usd`.
uint256 taxes_usd = new_net_expense_usd;
// 13. Update the `current_expenses_wei` by adding the `expense_usd_no_tax` converted to Wei.
current_expenses_wei = expense_usd_no_tax +
// 14. Update the `current_taxes_wei` by adding the `taxes_usd` converted to Wei.
// 15. Increase `expenses_count` in one unit.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment