Skip to content

Instantly share code, notes, and snippets.

@ayinot
Created June 27, 2018 02:15
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 ayinot/9b55e16293dfed6d00e788b643112b0f to your computer and use it in GitHub Desktop.
Save ayinot/9b55e16293dfed6d00e788b643112b0f 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.4.21+commit.dfe3193c.js&optimize=false&gist=
pragma solidity ^0.4.23;
contract ArrayOfMap{
mapping(address => mapping(bytes32 => address[])) addressArray;
function pushAddress(bytes32 _key, address _address) internal constant{
addressArray[msg.sender][_key].push(_address);
}
// lookup address array length by key
function getAddressArrayLength(bytes32 _key) public view returns(uint) {
return addressArray[msg.sender][_key].length;
}
// lookup address array value by key and index
function getAddressArrayIndexValue(bytes32 _key, uint i) internal view returns(address) {
return addressArray[msg.sender][_key][i];
}
function setAddress(address _proxyAddress) public{
pushAddress(keccak256("Array"),_proxyAddress);
}
function getAddress(uint i) public view returns(address) {
return getAddressArrayIndexValue(keccak256("Array"),i);
}
}
pragma solidity ^0.4.22;
/// @title Voting with delegation.
contract Ballot {
// This declares a new complex type which will
// be used for variables later.
// It will represent a single voter.
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
}
// This is a type for a single proposal.
struct Proposal {
bytes32 name; // short name (up to 32 bytes)
uint voteCount; // number of accumulated votes
}
address public chairperson;
// This declares a state variable that
// stores a `Voter` struct for each possible address.
mapping(address => Voter) public voters;
// A dynamically-sized array of `Proposal` structs.
Proposal[] public proposals;
/// Create a new ballot to choose one of `proposalNames`.
constructor(bytes32[] proposalNames) public {
chairperson = msg.sender;
voters[chairperson].weight = 1;
// For each of the provided proposal names,
// create a new proposal object and add it
// to the end of the array.
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
}));
}
}
// Give `voter` the right to vote on this ballot.
// May only be called by `chairperson`.
function giveRightToVote(address voter) public {
// 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 == 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;
}
/// Delegate your vote to the voter `to`.
function delegate(address to) public {
// assigns reference
Voter storage sender = voters[msg.sender];
require(!sender.voted, "You already voted.");
require(to != msg.sender, "Self-delegation is disallowed.");
// Forward the delegation as long as
// `to` also delegated.
// In general, such loops are very dangerous,
// because if they run too long, they might
// need more gas than is available in a block.
// In this case, the delegation will not be executed,
// but in other situations, such loops might
// cause a contract to get "stuck" completely.
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.");
}
// Since `sender` is a reference, this
// modifies `voters[msg.sender].voted`
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;
}
}
/// Give your vote (including votes delegated to you)
/// to proposal `proposals[proposal].name`.
function vote(uint proposal) public {
Voter storage sender = voters[msg.sender];
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.
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;
}
}
}
// Calls winningProposal() function to get the index
// of the winner contained in the proposals array and then
// returns the name of the winner
function winnerName() public view
returns (bytes32 winnerName_)
{
winnerName_ = proposals[winningProposal()].name;
}
}
pragma solidity ^0.4.16;
pragma experimental "v0.5.0";
pragma experimental "ABIEncoderV2";
library Bits {
uint constant internal ONE = uint(1);
uint constant internal ONES = uint(~0);
// Sets the bit at the given 'index' in 'self' to '1'.
// Returns the modified value.
function setBit(uint self, uint8 index) internal pure returns (uint) {
return self | ONE << index;
}
// Sets the bit at the given 'index' in 'self' to '0'.
// Returns the modified value.
function clearBit(uint self, uint8 index) internal pure returns (uint) {
return self & ~(ONE << index);
}
// Sets the bit at the given 'index' in 'self' to:
// '1' - if the bit is '0'
// '0' - if the bit is '1'
// Returns the modified value.
function toggleBit(uint self, uint8 index) internal pure returns (uint) {
return self ^ ONE << index;
}
// Get the value of the bit at the given 'index' in 'self'.
function bit(uint self, uint8 index) internal pure returns (uint8) {
return uint8(self >> index & 1);
}
// Check if the bit at the given 'index' in 'self' is set.
// Returns:
// 'true' - if the value of the bit is '1'
// 'false' - if the value of the bit is '0'
function bitSet(uint self, uint8 index) internal pure returns (bool) {
return self >> index & 1 == 1;
}
// Checks if the bit at the given 'index' in 'self' is equal to the corresponding
// bit in 'other'.
// Returns:
// 'true' - if both bits are '0' or both bits are '1'
// 'false' - otherwise
function bitEqual(uint self, uint other, uint8 index) internal pure returns (bool) {
return (self ^ other) >> index & 1 == 0;
}
// Get the bitwise NOT of the bit at the given 'index' in 'self'.
function bitNot(uint self, uint8 index) internal pure returns (uint8) {
return uint8(1 - (self >> index & 1));
}
// Computes the bitwise AND of the bit at the given 'index' in 'self', and the
// corresponding bit in 'other', and returns the value.
function bitAnd(uint self, uint other, uint8 index) internal pure returns (uint8) {
return uint8((self & other) >> index & 1);
}
// Computes the bitwise OR of the bit at the given 'index' in 'self', and the
// corresponding bit in 'other', and returns the value.
function bitOr(uint self, uint other, uint8 index) internal pure returns (uint8) {
return uint8((self | other) >> index & 1);
}
// Computes the bitwise XOR of the bit at the given 'index' in 'self', and the
// corresponding bit in 'other', and returns the value.
function bitXor(uint self, uint other, uint8 index) internal pure returns (uint8) {
return uint8((self ^ other) >> index & 1);
}
// Gets 'numBits' consecutive bits from 'self', starting from the bit at 'startIndex'.
// Returns the bits as a 'uint'.
// Requires that:
// - '0 < numBits <= 256'
// - 'startIndex < 256'
// - 'numBits + startIndex <= 256'
function bits(uint self, uint8 startIndex, uint16 numBits) internal pure returns (uint) {
require(0 < numBits && startIndex < 256 && startIndex + numBits <= 256);
return self >> startIndex & ONES >> 256 - numBits;
}
// Computes the index of the highest bit set in 'self'.
// Returns the highest bit set as an 'uint8'.
// Requires that 'self != 0'.
function highestBitSet(uint self) internal pure returns (uint8 highest) {
require(self != 0);
uint val = self;
for (uint8 i = 128; i >= 1; i >>= 1) {
if (val & (ONE << i) - 1 << i != 0) {
highest += i;
val >>= i;
}
}
}
// Computes the index of the lowest bit set in 'self'.
// Returns the lowest bit set as an 'uint8'.
// Requires that 'self != 0'.
function lowestBitSet(uint self) internal pure returns (uint8 lowest) {
require(self != 0);
uint val = self;
for (uint8 i = 128; i >= 1; i >>= 1) {
if (val & (ONE << i) - 1 == 0) {
lowest += i;
val >>= i;
}
}
}
}
pragma solidity ^0.4.21;
contract BlindAuction {
struct Bid {
bytes32 blindedBid;
uint deposit;
}
address public beneficiary;
uint public biddingEnd;
uint public revealEnd;
bool public ended;
mapping(address => Bid[]) public bids;
address public highestBidder;
uint public highestBid;
// Allowed withdrawals of previous bids
mapping(address => uint) pendingReturns;
event AuctionEnded(address winner, uint highestBid);
/// Modifiers are a convenient way to validate inputs to
/// functions. `onlyBefore` is applied to `bid` below:
/// The new function body is the modifier's body where
/// `_` is replaced by the old function body.
modifier onlyBefore(uint _time) { require(now < _time); _; }
modifier onlyAfter(uint _time) { require(now > _time); _; }
function BlindAuction(
uint _biddingTime,
uint _revealTime,
address _beneficiary
) public {
beneficiary = _beneficiary;
biddingEnd = now + _biddingTime;
revealEnd = biddingEnd + _revealTime;
}
/// Place a blinded bid with `_blindedBid` = keccak256(value,
/// fake, secret).
/// The sent ether is only refunded if the bid is correctly
/// revealed in the revealing phase. The bid is valid if the
/// ether sent together with the bid is at least "value" and
/// "fake" is not true. Setting "fake" to true and sending
/// not the exact amount are ways to hide the real bid but
/// still make the required deposit. The same address can
/// place multiple bids.
function bid(bytes32 _blindedBid)
public
payable
onlyBefore(biddingEnd)
{
bids[msg.sender].push(Bid({
blindedBid: _blindedBid,
deposit: msg.value
}));
}
/// Reveal your blinded bids. You will get a refund for all
/// correctly blinded invalid bids and for all bids except for
/// the totally highest.
function reveal(
uint[] _values,
bool[] _fake,
bytes32[] _secret
)
public
onlyAfter(biddingEnd)
onlyBefore(revealEnd)
{
uint length = bids[msg.sender].length;
require(_values.length == length);
require(_fake.length == length);
require(_secret.length == length);
uint refund;
for (uint i = 0; i < length; i++) {
var bid = bids[msg.sender][i];
var (value, fake, secret) =
(_values[i], _fake[i], _secret[i]);
if (bid.blindedBid != keccak256(value, fake, secret)) {
// Bid was not actually revealed.
// Do not refund deposit.
continue;
}
refund += bid.deposit;
if (!fake && bid.deposit >= value) {
if (placeBid(msg.sender, value))
refund -= value;
}
// Make it impossible for the sender to re-claim
// the same deposit.
bid.blindedBid = bytes32(0);
}
msg.sender.transfer(refund);
}
// This is an "internal" function which means that it
// can only be called from the contract itself (or from
// derived contracts).
function placeBid(address bidder, uint value) internal
returns (bool success)
{
if (value <= highestBid) {
return false;
}
if (highestBidder != 0) {
// Refund the previously highest bidder.
pendingReturns[highestBidder] += highestBid;
}
highestBid = value;
highestBidder = bidder;
return true;
}
/// Withdraw a bid that was overbid.
function withdraw() public {
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 `transfer` returns (see the remark above about
// conditions -> effects -> interaction).
pendingReturns[msg.sender] = 0;
msg.sender.transfer(amount);
}
}
/// End the auction and send the highest bid
/// to the beneficiary.
function auctionEnd()
public
onlyAfter(revealEnd)
{
require(!ended);
emit AuctionEnded(highestBidder, highestBid);
ended = true;
beneficiary.transfer(highestBid);
}
}
pragma solidity ^0.4.24;
contract Bytes1 {
function checkBytes(uint64 _value,uint8 index) public view returns(uint8) {
return bit(uint(bytes8(_value)),uint8(index));
}
function checkWhich(uint64 _value,uint8 index) public view returns(uint8) {
return bit(uint(whichByte(_value)),uint8(index));
}
// Get the value of the bit at the given 'index' in 'self'.
function bit(uint self, uint8 index) internal pure returns (uint8) {
return uint8(self >> index & 1);
}
function whichByte(uint64 _value) public view returns(bytes1){
bytes8 value= bytes8(_value);
return value[7];
}
function which(uint64 _value) public view returns(bytes8) {
return bytes8(_value);
}
}
import "github.com/Arachnid/solidity-stringutils/strings.sol";
contract C {
using strings for *;
string public s;
function foo(string s1, string s2) {
s = s1.toSlice().concat(s2.toSlice());
}
}
pragma solidity ^0.4.18;
//Title : This contract is the implementation of the business logic as functions
//Author: Toniya Sundaram
contract Callee {
uint[] public values;
function storeValues(uint _arg1) {
values.push(_arg1);
}
function getLength() view returns(uint){
return values.length;
}
function getValue(uint _value) public view returns(uint) {
return ( _value+150);
}
}
pragma solidity ^0.4.18;
contract CalleeInterface {
function storeValues(uint _value) {}
function getValues() returns(uint) {}
function getValue(uint) returns(uint){}
}
pragma solidity ^0.4.18;
contract Caller {
function someAction(address _addr) public view returns(uint) {
Callee c = Callee(_addr);
return c.getValue(100);
}
function storeAction(address _addr,uint _value) public view returns(uint){
Callee c = Callee(_addr);
c.storeValues(_value);
return c.getValues();
}
function someUnsafeAction(address _addr) public returns(uint) {
_addr.call(bytes4(keccak256("storeValues(uint256)")),100);
}
}
contract Callee {
function getValue(uint initialValue) returns(uint);
function storeValues(uint value);
function getValues() returns(uint);
}
pragma solidity ^0.4.24;
contract ClientReceipt {
event Deposit(
address indexed _from,
bytes32 indexed _id,
uint _value
);
function deposit(bytes32 _id) public payable {
// Events are emitted using `emit`, followed by
// the name of the event and the arguments
// (if any) in parentheses. Any such invocation
// (even deeply nested) can be detected from
// the JavaScript API by filtering for `Deposit`.
Deposit(msg.sender, _id, msg.value);
}
}
pragma solidity ^0.4.18;
import "./Memory.sol";
contract Concat {
function strConcat(string _a, string _b) public returns (string){
bytes memory _aa = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory ab = new bytes(_aa.length + _bb.length-2);
uint l = _aa.length;
//uint blen = _bb.length;
assembly{
mstore(add(ab,32),mload(add(_aa,32)))
mstore(add(add(ab,32),l),mload(add(_bb,34)))
}
return string(ab);
}
// function strConcat(string memory _a, string memory _b) public returns (bytes){
// bytes memory _aa = bytes(_a);
// bytes memory _bb = bytes(_b);
// bytes memory ab = new bytes(_aa.length + _bb.length);
// assembly{
// mstore(add(ab,32),mload(add(_aa,32)))
// mstore(add(add(ab,32),2),mload(add(_bb,32)))
// }
// return ab;
// }
function stringToHex(string x) returns(bytes b) {
b = new bytes(32);
assembly {
mstore(add(b,32),mload(add(x,32)))
}
return b;
// b = bytes(x);
// return b;
}
function compareStringsbyBytes(string s1, string s2) public pure returns(bool)
{
bytes memory s1bytes = bytes(s1);
bytes memory s2bytes = bytes(s2);
if(s1bytes.length!=s2bytes.length) {
return false;
}
else{
for(uint i = 0;i<s1bytes.length;i++)
{
if(s1bytes[i] != s2bytes[i])
return false;
}
return true;
}
}
function substr(bytes memory self, uint startIndex) public returns (bytes memory) {
require(startIndex <= self.length);
var len = self.length - startIndex;
var addr = Memory.dataPtr(self);
return Memory.toBytes(addr + startIndex, len);
}
// Copies a section of a 'bytes32' starting at the provided 'startIndex'.
// Returns the copied bytes (padded to the right) as a new 'bytes32'.
// Requires that 'startIndex < 32'
// function substr(bytes32 self, uint8 startIndex) internal returns (bytes32) {
// require(startIndex < 32);
// return bytes32(uint(self) << startIndex*8);
// }
}
pragma solidity ^0.4.0;
contract Cont {
uint c;
function func(uint a) returns (uint b) {
assembly {
b := mul(a, sload(c_slot)) // the offset is ignored, it is zero
}
}
}
contract Contract {
bytes32 public Name;
function Contract (bytes32 name) {
Name = name;
}
}
pragma solidity ^0.4.18;
import "./UniversalStorage.sol";
import "../ContractStorage.sol";
library ContractV1Lib {
function getBalance(UniversalStorage self, address _account) public view returns (uint256) {
return self.getUint256(keccak256("balances", _account));
}
function getAllowance(UniversalStorage self, address _account, address _spender) public view returns (uint256) {
return self.getUint256(keccak256("allowance", _account, _spender));
}
function getTotalSupply(UniversalStorage self) public view returns (uint256) {
return self.getUint256(keccak256("total_supply"));
}
}
pragma solidity ^0.4.23;
pragma experimental ABIEncoderV2;
import "./RLPEncode.sol";
import "./SafeMath.sol";
contract Encode {
bytes public contractAdd;
function createAddress(bytes creator, bytes nonce) internal returns(bytes){
//SomeBody help me writing this part
//return sha3(rlp.encode([normalize_address(sender), nonce]))[12:]
//return RLPEncode.encodeList(creator,nonce);
}
// function testAdd() returns(bytes memory, address addrs) {
// bytes memory result = new bytes(64);
// addressToBytes(msg.sender, result);
// return (result, msg.sender);
// }
function toBytes(address a) internal constant returns (bytes b){
assembly {
let m := mload(0x40)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
return RLPEncode.encodeBytes(b);
}
function uinttoBytes(uint256 x) internal returns (bytes b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
return RLPEncode.encodeBytes(b);
}
function encodeMe(bytes[] arg1) public returns(address) {
return address(sha3(RLPEncode.encodeList(arg1)));
}
function returnAdd() public view returns(address) {
return address(this);
}
function createAddress(address creator,uint8 nonce)public constant returns (address) {
if (nonce < 127)
return address(keccak256(0xd6, 0x94, creator, nonce));
else if(nonce < 257)
return address(keccak256(0xd7, 0x94, creator, 0x81, nonce));
}
// function findContractAdd(address sender, uint8 nonce) public constant returns(address) {
// nonce = uint8(nonce);
// address contractAddress= address(keccak256(0xd6, 0x94, sender,nonce));
// return contractAddress;
// }
// function hashIt(bytes h) public returns(bytes32) {
// return keccak256(0x81af2544772bea342457a7911cacabb03575327c79ef5c3a504717bc5a8217f5);
// }
}
pragma solidity ^0.4.1;
/// Title: This contract makes sure data schema changes can be implemented without requiring upgrades to storage contract
/// author: Toniya Sundaram
contract EternalStorage {
mapping (bytes32 => uint) uintStorage;
function getUint (bytes32 record) constant returns (uint) {
return uintStorage[record];
}
function setUint(bytes32 record,uint value) {
uintStorage[record] = value;
}
mapping (bytes32 => string) stringStorage;
function getString (bytes32 record) constant returns(string) {
return stringStorage[record];
}
function setString (bytes32 record, string value) {
stringStorage[record] = value;
}
mapping (bytes32 => address) addressStorage;
function getAddress (bytes32 record) constant returns(address) {
return addressStorage[record];
}
function setAddress(bytes32 record, address value) {
addressStorage[record] = value;
}
mapping (bytes32 => bytes32) bytesStorage;
function getBytes (bytes32 record) constant returns (bytes32) {
return bytesStorage[record];
}
function setBytes (bytes32 record, bytes32 value) {
bytesStorage[record] = value;
}
mapping (bytes32 => bool) booleanStorage;
function getBoolean (bytes32 record) constant returns (bool) {
return booleanStorage[record];
}
function setBoolean (bytes32 record, bool value) {
booleanStorage[record] = value;
}
mapping (bytes32 => int) intStorage;
function getInt (bytes32 record) constant returns (int) {
return intStorage[record];
}
function setInt (bytes32 record, int value) {
intStorage[record] = value;
}
}
pragma solidity ^0.4.16;
contract Foo {
function baz(uint32 x, bool y) public pure returns (bool r) { r = x > 32 || y; }
function hash(string _name) public returns(bytes32) {
return keccak256(_name);
}
event Print(uint);
function multiply(uint input) {
Print(input * 7);
}
function f(uint amount,uint32[] name,bytes10 sName,bytes myJob) public view returns(uint){
return amount;
}
// function parseData(bytes _txnData) public view returns (byte) {
// uint length = _txnData.length;
// bytes32 result;
// uint j=10;
// for(uint i=0;i<length-10;i++) {
// result[i] = _txnData[j];
// j++;
// }
// }
}
pragma solidity ^0.4.23;
import "./SafeMath.sol";
contract globalPermission {
function globalPermBit(uint _bitIndex,uint64 _value) public view returns (uint globalPermBit) {
uint whichByte = SafeMath.div(_bitIndex, 8);
whichByte = SafeMath.sub(7,whichByte);
uint8 byteIndex;
if (whichByte > 0){
byteIndex = uint8(_bitIndex % 8);
} else {
byteIndex = uint8(_bitIndex);
}
bytes1 globalPermBitByte = bytes8(_value)[whichByte]; // get the proper byte to find our permission bit
return globalPermBit = bit(uint(globalPermBitByte), byteIndex); // get the bit value at the given index
}
// Get the value of the bit at the given 'index' in 'self'.
function bit(uint self, uint8 index) internal pure returns (uint8) {
return uint8(self >> index & 1);
}
}
pragma solidity ^0.4.18;
contract Hashing {
mapping(bytes32 => string) myName;
function setName(bytes32 key,string value) internal{
myName[key] = value;
}
function getName(bytes32 key) internal view returns(string) {
return myName[key];
}
function storeName(string name_) {
setName(keccak256("name","myName","0xca35b7d915458ef540ade6068dfe2f44e8fa733c"),name_);
}
function retrieveName() public view returns (string){
return getName(keccak256("name","myName","0xca35b7d915458ef540ade6068dfe2f44e8fa733c"));
}
function just() returns(bytes4) {
return bytes4(keccak256("storeValues(uint256)"));
}
}
contract HelloWorld {
event Print(string out);
function() { Print("Hello, World!"); }
}
pragma solidity ^0.4.18;
contract HexCon {
bytes4 public selector;
function uinttoBytes(uint256 x) returns (bytes b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
selector = this.uinttoBytes.selector;
return b;
}
function f() returns (bytes4) {
return this.f.selector;
}
function addToHex(address x) returns(bytes b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
selector = this.addToHex.selector;
return b;
}
// function stringToHex(string x) returns(bytes b) {
// b = new bytes(32);
// assembly {
// mstore(add(b,32),mload(add(x,32)))
// }
// return b;
// b = bytes(x);
// return b;
// }
function assemblyt(bytes arg1) returns(bytes){
assembly {
mstore(arg1,32)
}
return arg1;
}
function boolToHex(bool x) returns(bytes b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
selector = this.boolToHex.selector;
return b;
}
function bytesToHex(bytes32 x) returns(bytes32 b) {
// b = new bytes(32);
// assembly { mstore(add(b, 32), x) }
selector = this.bytesToHex.selector;
return x;
}
function strConcat(string memory _a, string memory _b) public returns (string memory){
bytes memory _aa = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory ab = new bytes(_aa.length + _bb.length);
uint i = 0;
/*for (i = 0; i < _aa.length; i++) {
ab[i] = _aa[i];
}
for (i = _aa.length; i < (_aa.length + _bb.length); i++) {
ab[i] = _bb[i-_aa.length];
}*/
assembly{
mstore(add(ab,32),mload(add(_aa,32)))
mstore(add(add(ab,32),2),mload(add(_bb,32)))
}
return string(ab);
}
function compareStringsbyBytes(string s1, string s2) public pure returns(bool)
{
bytes memory s1bytes = bytes(s1);
bytes memory s2bytes = bytes(s2);
if(s1bytes.length!=s2bytes.length) {
return false;
}
else{
for(uint i = 0;i<s1bytes.length;i++)
{
if(s1bytes[i] != s2bytes[i])
return false;
}
return true;
}
}
}
pragma solidity ^0.4.18;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function balanceOf(address _owner) public view returns (uint256);
function allowance(address _owner, address _spender) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.4.19;
contract Interchain {
bytes public selector;
bytes public destHash;
function withdrawal(bytes32 destHash) returns(bytes4){
return this.withdrawal.selector;
}
function parse(bytes _selector, bytes _destHash) returns (bytes b){
selector = _selector;
destHash = _destHash;
b = strConcat(_selector,_destHash);
}
function strConcat(bytes _a, bytes _b) public returns (bytes){
bytes memory _aa = _a;
bytes memory _bb = _b;
bytes memory ab = new bytes(_aa.length + _bb.length);
uint l = _aa.length;
assembly{
mstore(add(ab,32),mload(add(_aa,32)))
mstore(add(add(ab,32),l),mload(add(_bb,32)))
}
bytes memory b = new bytes(36);
assembly { mstore(add(b, 32), mload(add(ab,32))) }
return b;
}
}
pragma solidity ^0.4.14;
/// Title: This contract is an interface for the tokenLedger which implements decoupling
contract ITokenLedger {
//abstract functions
function generateTokens(uint _amount) {}
}
//This contract is an implementation of ITokenLedger
contract TokenLedger {
uint256 totalSupply;
mapping (address => uint256) balances;
//This function generates the tokens and adds the amount to the Senders balance.
function generateTokens (uint _amount) {
if(_amount ==0) throw; //amount should not be null
if(totalSupply+_amount < _amount) throw; // amount should be greater than the totalSupply because only when ther is amount more than totalSupply they can use it issue tokens
totalSupply += _amount;
balances[msg.sender] +=_amount;
}
}
pragma solidity ^0.4.18;
contract KeyValueStorage {
mapping(address => mapping(bytes32 => uint256)) _uintStorage;
mapping(address => mapping(bytes32 => address)) _addressStorage;
mapping(address => mapping(bytes32 => bool)) _boolStorage;
/**** Get Methods ***********/
function getAddress(bytes32 key) public view returns (address) {
return _addressStorage[msg.sender][key];
}
function getUint(bytes32 key) public view returns (uint) {
return _uintStorage[msg.sender][key];
}
function getBool(bytes32 key) public view returns (bool) {
return _boolStorage[msg.sender][key];
}
/**** Set Methods ***********/
function setAddress(bytes32 key, address value) public {
_addressStorage[msg.sender][key] = value;
}
function setUint(bytes32 key, uint value) public {
_uintStorage[msg.sender][key] = value;
}
function setBool(bytes32 key, bool value) public {
_boolStorage[msg.sender][key] = value;
}
/**** Delete Methods ***********/
function deleteAddress(bytes32 key) public {
delete _addressStorage[msg.sender][key];
}
function deleteUint(bytes32 key) public {
delete _uintStorage[msg.sender][key];
}
function deleteBool(bytes32 key) public {
delete _boolStorage[msg.sender][key];
}
}
contract LiveFactory {
function deployCode(bytes _code) returns (address deployedAddress) {
assembly {
deployedAddress := create(0, add(_code, 0x20), mload(_code))
// jumpi(invalidJumpLabel, iszero(extcodesize(deployedAddress))) // jumps if no code at addresses
}
ContractDeployed(deployedAddress);
}
event ContractDeployed(address deployedAddress);
}
contract TheContractFactory is LiveFactory {
function uploadCode(string identifier, bytes o_code)
onlyOrNone(deployer[identifierHash(identifier)])
returns (bytes32) {
bytes32 h = identifierHash(identifier);
code[h] = o_code;
deployer[h] = msg.sender;
NewCode(identifier);
return h;
}
function deploy(string identifier) {
bytes c = code[identifierHash(identifier)];
if (c.length == 0) throw;
NewContract(deployCode(c), msg.sender, identifier);
}
function identifierHash(string identifier) returns (bytes32) {
return sha3(identifier);
}
modifier onlyOrNone(address x) {
if (x != 0x0 && x != msg.sender) throw;
_;
}
mapping (bytes32 => address) public deployer;
mapping (bytes32 => bytes) public code;
event NewContract(address x, address indexed owner, string identifier);
event NewCode(string identifier);
}
pragma solidity ^0.4.16;
pragma experimental "v0.5.0";
pragma experimental "ABIEncoderV2";
library Memory {
// Size of a word, in bytes.
uint internal constant WORD_SIZE = 32;
// Size of the header of a 'bytes' array.
uint internal constant BYTES_HEADER_SIZE = 32;
// Address of the free memory pointer.
uint internal constant FREE_MEM_PTR = 0x40;
// Compares the 'len' bytes starting at address 'addr' in memory with the 'len'
// bytes starting at 'addr2'.
// Returns 'true' if the bytes are the same, otherwise 'false'.
function equals(uint addr, uint addr2, uint len) internal pure returns (bool equal) {
assembly {
equal := eq(keccak256(addr, len), keccak256(addr2, len))
}
}
// Compares the 'len' bytes starting at address 'addr' in memory with the bytes stored in
// 'bts'. It is allowed to set 'len' to a lower value then 'bts.length', in which case only
// the first 'len' bytes will be compared.
// Requires that 'bts.length >= len'
function equals(uint addr, uint len, bytes memory bts) internal pure returns (bool equal) {
require(bts.length >= len);
uint addr2;
assembly {
addr2 := add(bts, /*BYTES_HEADER_SIZE*/32)
}
return equals(addr, addr2, len);
}
// Allocates 'numBytes' bytes in memory. This will prevent the Solidity compiler
// from using this area of memory. It will also initialize the area by setting
// each byte to '0'.
function allocate(uint numBytes) internal pure returns (uint addr) {
// Take the current value of the free memory pointer, and update.
assembly {
addr := mload(/*FREE_MEM_PTR*/0x40)
mstore(/*FREE_MEM_PTR*/0x40, add(addr, numBytes))
}
uint words = (numBytes + WORD_SIZE - 1) / WORD_SIZE;
for (uint i = 0; i < words; i++) {
assembly {
mstore(add(addr, mul(i, /*WORD_SIZE*/32)), 0)
}
}
}
// Copy 'len' bytes from memory address 'src', to address 'dest'.
// This function does not check the or destination, it only copies
// the bytes.
function copy(uint src, uint dest, uint len) internal pure {
// Copy word-length chunks while possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
dest += WORD_SIZE;
src += WORD_SIZE;
}
// Copy remaining bytes
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
// Returns a memory pointer to the provided bytes array.
function ptr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := bts
}
}
// Returns a memory pointer to the data portion of the provided bytes array.
function dataPtr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// This function does the same as 'dataPtr(bytes memory)', but will also return the
// length of the provided bytes array.
function fromBytes(bytes memory bts) internal pure returns (uint addr, uint len) {
len = bts.length;
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// Creates a 'bytes memory' variable from the memory address 'addr', with the
// length 'len'. The function will allocate new memory for the bytes array, and
// the 'len bytes starting at 'addr' will be copied into that new memory.
function toBytes(uint addr, uint len) internal pure returns (bytes memory bts) {
bts = new bytes(len);
uint btsptr;
assembly {
btsptr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
copy(addr, btsptr, len);
}
// Get the word stored at memory address 'addr' as a 'uint'.
function toUint(uint addr) internal pure returns (uint n) {
assembly {
n := mload(addr)
}
}
// Get the word stored at memory address 'addr' as a 'bytes32'.
function toBytes32(uint addr) internal pure returns (bytes32 bts) {
assembly {
bts := mload(addr)
}
}
/*
// Get the byte stored at memory address 'addr' as a 'byte'.
function toByte(uint addr, uint8 index) internal pure returns (byte b) {
require(index < WORD_SIZE);
uint8 n;
assembly {
n := byte(index, mload(addr))
}
b = byte(n);
}
*/
}
pragma solidity ^0.4.18;
import "./ShrimpCoin.sol";
contract MintableTokenDelegate is TokenDelegate {
modifier onlyOwner {
require(msg.sender == _storage.getAddress("owner"));
_;
}
modifier canMint() {
require(!_storage.getBool("mintingFinished"));
_;
}
function mint(address to, uint256 amount) onlyOwner canMint public returns (bool) {
addSupply(amount);
addBalance(to, amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
_storage.setBool("mintingFinished", true);
return true;
}
}
pragma solidity ^0.4.24;
contract MsgSender {
function calMe() public returns(address){
return msg.sender;
}
}
contract caller {
function callee() returns(address){
MsgSender msg = new MsgSender();
address msgSender = msg.calMe();
return msgSender;
}
function max(uint8 n) public returns(bool){
if(n<1000){
return true;
}
}
function checkGas(uint n) {
uint256 a = uint256(n);
uint256 c = 12+a;
}
function me256(uint256 n) {
uint256 c = 12+n;
}
}
pragma solidity ^0.4.23;
contract MsgValue {
uint MINIMUM_STAKE = 10**19;
uint c;
// function addStake()payable {
// require(msg.value > MINIMUM_STAKE,"less than MINIMUM_STAKE");
// c = 15+15;
// }
// function testPublicKey(bytes32 _pubKey) public view returns(bytes32){
// // require(address() == msg.sender, "pubKey does not match msg.sender");
// bytes32 name= keccak256(abi.encodePacked(_pubKey));
// return name;
// }
// function sendStake(uint amount) payable public {
// msg.sender.transfer(amount);
// }
// /// Withdraw a bid that was overbid.
// function withdraw() public {
// uint amount = 5;
// 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 `transfer` returns (see the remark above about
// // conditions -> effects -> interaction)
// msg.sender.transfer(amount);
// }
// }
function MsgValue (){
}
function sendEthers() payable {}
uint balance=5;
function getBalance() constant returns (uint) {
return address(this).balance;
}
function getEthers() {
msg.sender.transfer(5*10**18);
}
}
pragma solidity ^0.4.23;
contract Number {
function test1() public returns(int n1, int n2, int n3,int n4,int n5,int n6,int n7,int n8,int n9,
int n10,int n11,int n12,int n13,int n14){
n1 = 1;
n2 = 1;
n3 = 1;
n4 =1;
n5 =1;
n6 =1;
n7 =1;
n8 =1;
n9 =1;
n10 =1;
n11 = 1;
n12 = 1;
n13 = 1;
n14 =1;
}
function test2() public returns(int n1, int n2, int n3,int n4,int n5,int n6,int n7,int n8,int n9,
int n10,int n11,int n12,string n13){
n1 = 1;
n2 = 1;
n3 = 1;
n4 =1;
n5 =1;
n6 =1;
n7 =1;
n8 =1;
n9 =1;
n10 =1;
n11 = 1;
n12 = 1;
n13 = "1";
//n14 = "1";
}
function test3() public returns(bytes32 a1,bytes32 a2,bytes32 a3,bytes32 a4,bytes32 a5,bytes32 a6,bytes32 a7,
bytes32 a11,bytes32 a12,bytes32 a13,bytes32 a14,bytes32 a15,bytes32 a16,bytes32 a17) {
a1 = "Terry Wilkinson";
a2 = "Terry Wilkinson";
a3 = "Terry Wilkinson";
a4 = "Terry Wilkinson";
a5 = "Terry Wilkinson";
a6 = "Terry Wilkinson";
a7 = "Terry Wilkinson";
}
function test4() public returns(bytes a1,bytes a2,bytes a3,bytes a4,bytes a5,bytes a6,bytes a7) {
a1 = "Terry Wilkinson and Terry Wilkinson and Terry Wilkinson Terry Wilkinson and Terry Wilkinson and Terry Wilkinson";
a2 = "Terry Wilkinson and Terry Wilkinson and Terry Wilkinson Terry Wilkinson and Terry Wilkinson and Terry Wilkinson";
a3 = "Terry Wilkinson and Terry Wilkinson and Terry Wilkinson Terry Wilkinson and Terry Wilkinson and Terry Wilkinson";
a4 = "Terry Wilkinson and Terry Wilkinson and Terry Wilkinson Terry Wilkinson and Terry Wilkinson and Terry Wilkinson";
a5 = "Terry Wilkinson and Terry Wilkinson and Terry Wilkinson Terry Wilkinson and Terry Wilkinson and Terry Wilkinson";
a6 = "Terry Wilkinson and Terry Wilkinson and Terry Wilkinson Terry Wilkinson and Terry Wilkinson and Terry Wilkinson";
a7 = "Terry Wilkinson and Terry Wilkinson and Terry Wilkinson Terry Wilkinson and Terry Wilkinson and Terry Wilkinson";
}
function test5() public returns(uint8,bytes,uint,uint64,uint64,bytes32,bytes32,uint8){
}
}
pragma solidity ^0.4.1;
import "./ITokenLedger.sol";
// Title: This contract interacts with the token ledger
// Author: Toniya Sundaram
contract Organisation {
ITokenLedger public tokenLedger;
//This is a constructor which by default deployes the implementation of a contract.
function Organisation(address _tokenledger) {
tokenLedger = ITokenLedger(_tokenledger);
}
//If we want to change the implementation of the originally delpoyed contract then we can use this function to redirect to new implementation
function setTokenLedgerAddress(address tokenLedgerAddress) {
tokenLedger = ITokenLedger(tokenLedgerAddress);
}
function generateTokens(uint256 _amount) {
tokenLedger.generateTokens(_amount);
}
}
pragma solidity ^0.4.18;
/**
* @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;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() 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 {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity ^0.4.20;
import "./Number.sol";
contract Parent {
Number num;
function createContract () public returns(address){
num = new Number();
return num;
}
}
contract Parsing {
function convertBytes(bytes destHash, bytes byteCode, bytes4 methodSig, bytes data) {
}
function equal(bytes32 arg1, bytes32 arg2) returns(bool){
// bytes memory arg1 = _arg1;
// bytes memory arg2 = _arg2;
if(arg1 == arg2) {
return true;
}
return false;
}
}
pragma solidity ^0.4.18;
import './IERC20.sol';
import './PolyToken.sol';
import './SafeMath.sol';
import './Ownable.sol';
/**
* @title POLY token initial distribution
*
* @dev Distribute purchasers, airdrop, reserve, and founder tokens
*/
contract PolyDistribution is Ownable {
using SafeMath for uint256;
PolyToken public POLY;
uint256 private constant decimalFactor = 10**uint256(18);
enum AllocationType { PRESALE, FOUNDER, AIRDROP, ADVISOR, RESERVE, BONUS1, BONUS2, BONUS3 }
uint256 public constant INITIAL_SUPPLY = 1000000000 * decimalFactor;
uint256 public AVAILABLE_TOTAL_SUPPLY = 1000000000 * decimalFactor;
uint256 public AVAILABLE_PRESALE_SUPPLY = 230000000 * decimalFactor; // 100% Released at Token Distribution (TD)
uint256 public AVAILABLE_FOUNDER_SUPPLY = 150000000 * decimalFactor; // 33% Released at TD +1 year -> 100% at TD +3 years
uint256 public AVAILABLE_AIRDROP_SUPPLY = 10000000 * decimalFactor; // 100% Released at TD
uint256 public AVAILABLE_ADVISOR_SUPPLY = 20000000 * decimalFactor; // 100% Released at TD +7 months
uint256 public AVAILABLE_RESERVE_SUPPLY = 513116658 * decimalFactor; // 6.8% Released at TD +100 days -> 100% at TD +4 years
uint256 public AVAILABLE_BONUS1_SUPPLY = 39053330 * decimalFactor; // 100% Released at TD +1 year
uint256 public AVAILABLE_BONUS2_SUPPLY = 9354408 * decimalFactor; // 100% Released at TD +2 years
uint256 public AVAILABLE_BONUS3_SUPPLY = 28475604 * decimalFactor; // 100% Released at TD +3 years
uint256 public grandTotalClaimed = 0;
uint256 public startTime;
// Allocation with vesting information
struct Allocation {
uint8 AllocationSupply; // Type of allocation
uint256 endCliff; // Tokens are locked until
uint256 endVesting; // This is when the tokens are fully unvested
uint256 totalAllocated; // Total tokens allocated
uint256 amountClaimed; // Total tokens claimed
}
mapping (address => Allocation) public allocations;
// List of admins
mapping (address => bool) public airdropAdmins;
// Keeps track of whether or not a 250 POLY airdrop has been made to a particular address
mapping (address => bool) public airdrops;
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || airdropAdmins[msg.sender]);
_;
}
event LogNewAllocation(address indexed _recipient, AllocationType indexed _fromSupply, uint256 _totalAllocated, uint256 _grandTotalAllocated);
event LogPolyClaimed(address indexed _recipient, uint8 indexed _fromSupply, uint256 _amountClaimed, uint256 _totalAllocated, uint256 _grandTotalClaimed);
/**
* @dev Constructor function - Set the poly token address
* @param _startTime The time when PolyDistribution goes live
*/
function PolyDistribution(uint256 _startTime) public {
require(_startTime >= now);
require(AVAILABLE_TOTAL_SUPPLY == AVAILABLE_PRESALE_SUPPLY.add(AVAILABLE_FOUNDER_SUPPLY).add(AVAILABLE_AIRDROP_SUPPLY).add(AVAILABLE_ADVISOR_SUPPLY).add(AVAILABLE_BONUS1_SUPPLY).add(AVAILABLE_BONUS2_SUPPLY).add(AVAILABLE_BONUS3_SUPPLY).add(AVAILABLE_RESERVE_SUPPLY));
startTime = _startTime;
POLY = new PolyToken(this);
}
/**
* @dev Allow the owner of the contract to assign a new allocation
* @param _recipient The recipient of the allocation
* @param _totalAllocated The total amount of POLY available to the receipient (after vesting)
* @param _supply The POLY supply the allocation will be taken from
*/
function setAllocation (address _recipient, uint256 _totalAllocated, AllocationType _supply) onlyOwner public {
require(allocations[_recipient].totalAllocated == 0 && _totalAllocated > 0);
require(_supply >= AllocationType.PRESALE && _supply <= AllocationType.BONUS3);
require(_recipient != address(0));
if (_supply == AllocationType.PRESALE) {
AVAILABLE_PRESALE_SUPPLY = AVAILABLE_PRESALE_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.PRESALE), 0, 0, _totalAllocated, 0);
} else if (_supply == AllocationType.FOUNDER) {
AVAILABLE_FOUNDER_SUPPLY = AVAILABLE_FOUNDER_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.FOUNDER), startTime + 1 years, startTime + 3 years, _totalAllocated, 0);
} else if (_supply == AllocationType.ADVISOR) {
AVAILABLE_ADVISOR_SUPPLY = AVAILABLE_ADVISOR_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.ADVISOR), startTime + 209 days, 0, _totalAllocated, 0);
} else if (_supply == AllocationType.RESERVE) {
AVAILABLE_RESERVE_SUPPLY = AVAILABLE_RESERVE_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.RESERVE), startTime + 100 days, startTime + 4 years, _totalAllocated, 0);
} else if (_supply == AllocationType.BONUS1) {
AVAILABLE_BONUS1_SUPPLY = AVAILABLE_BONUS1_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.BONUS1), startTime + 1 years, startTime + 1 years, _totalAllocated, 0);
} else if (_supply == AllocationType.BONUS2) {
AVAILABLE_BONUS2_SUPPLY = AVAILABLE_BONUS2_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.BONUS2), startTime + 2 years, startTime + 2 years, _totalAllocated, 0);
} else if (_supply == AllocationType.BONUS3) {
AVAILABLE_BONUS3_SUPPLY = AVAILABLE_BONUS3_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.BONUS3), startTime + 3 years, startTime + 3 years, _totalAllocated, 0);
}
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(_totalAllocated);
LogNewAllocation(_recipient, _supply, _totalAllocated, grandTotalAllocated());
}
/**
* @dev Add an airdrop admin
*/
function setAirdropAdmin(address _admin, bool _isAdmin) public onlyOwner {
airdropAdmins[_admin] = _isAdmin;
}
/**
* @dev perform a transfer of allocations
* @param _recipient is a list of recipients
*/
function airdropTokens(address[] _recipient) public onlyOwnerOrAdmin {
require(now >= startTime);
uint airdropped;
for(uint256 i = 0; i< _recipient.length; i++)
{
if (!airdrops[_recipient[i]]) {
airdrops[_recipient[i]] = true;
require(POLY.transfer(_recipient[i], 250 * decimalFactor));
airdropped = airdropped.add(250 * decimalFactor);
}
}
AVAILABLE_AIRDROP_SUPPLY = AVAILABLE_AIRDROP_SUPPLY.sub(airdropped);
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(airdropped);
grandTotalClaimed = grandTotalClaimed.add(airdropped);
}
/**
* @dev Transfer a recipients available allocation to their address
* @param _recipient The address to withdraw tokens for
*/
function transferTokens (address _recipient) public {
require(allocations[_recipient].amountClaimed < allocations[_recipient].totalAllocated);
require(now >= allocations[_recipient].endCliff);
require(now >= startTime);
uint256 newAmountClaimed;
if (allocations[_recipient].endVesting > now) {
// Transfer available amount based on vesting schedule and allocation
newAmountClaimed = allocations[_recipient].totalAllocated.mul(now.sub(startTime)).div(allocations[_recipient].endVesting.sub(startTime));
} else {
// Transfer total allocated (minus previously claimed tokens)
newAmountClaimed = allocations[_recipient].totalAllocated;
}
uint256 tokensToTransfer = newAmountClaimed.sub(allocations[_recipient].amountClaimed);
allocations[_recipient].amountClaimed = newAmountClaimed;
require(POLY.transfer(_recipient, tokensToTransfer));
grandTotalClaimed = grandTotalClaimed.add(tokensToTransfer);
LogPolyClaimed(_recipient, allocations[_recipient].AllocationSupply, tokensToTransfer, newAmountClaimed, grandTotalClaimed);
}
// Returns the amount of POLY allocated
function grandTotalAllocated() public view returns (uint256) {
return INITIAL_SUPPLY - AVAILABLE_TOTAL_SUPPLY;
}
// Allow transfer of accidentally sent ERC20 tokens
function refundTokens(address _recipient, address _token) public onlyOwner {
require(_token != address(POLY));
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(this);
require(token.transfer(_recipient, balance));
}
}
pragma solidity ^0.4.18;
import './IERC20.sol';
import './SafeMath.sol';
/*
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract PolyToken is IERC20 {
using SafeMath for uint256;
// Poly Token parameters
string public name = 'Polymath';
string public symbol = 'POLY';
uint8 public constant decimals = 18;
uint256 public constant decimalFactor = 10 ** uint256(decimals);
uint256 public constant totalSupply = 1000000000 * decimalFactor;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Constructor for Poly creation
* @dev Assigns the totalSupply to the PolyDistribution contract
*/
function PolyToken(address _polyDistributionContractAddress) public {
require(_polyDistributionContractAddress != address(0));
balances[_polyDistributionContractAddress] = totalSupply;
Transfer(address(0), _polyDistributionContractAddress, totalSupply);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that 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 uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @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, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @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 uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
pragma solidity ^0.4.18;
import "./EternalStorage.sol";
//Title : This contract enables a user to add a proposal to EternalStorage
//Author: Toniya Sundaram
library ProposalLibrary {
function getProposalCount (address _storageContract) constant returns(uint256){
return EternalStorage(_storageContract).getUint(keccak256("proposalCount"));
}
function addProposal(address _storageContract,bytes32 _name) {
var idx = getProposalCount(_storageContract);
EternalStorage(_storageContract).setBytes(keccak256("proposal_name",idx),_name);
EternalStorage(_storageContract).setUint(keccak256("proposal_eth",idx),0);
EternalStorage(_storageContract).setUint(keccak256("proposal_count"),idx+1);
}
}
pragma solidity ^0.4.18;
import "./Ownable.sol";
contract Proxy is Ownable {
event Upgraded(address indexed implementation);
address internal _implementation;
function implementation() public view returns (address) {
return _implementation;
}
function upgradeTo(address impl) public onlyOwner {
require(_implementation != impl);
_implementation = impl;
Upgraded(impl);
}
function () payable public {
address _impl = implementation();
require(_impl != address(0));
bytes memory data = msg.data;
assembly {
let result := delegatecall(gas, _impl, add(data, 0x20), mload(data), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
pragma solidity ^0.4.24;
contract ReturnAdd {
uint public args;
constructor(uint _args) public {
args = (_args+55)/100;
checMe(args);
}
function checMe(uint args) internal pure returns(bytes32) {
return keccak256(abi.encodePacked(args));
}
}
pragma solidity ^0.4.23;
contract ReturnArray {
function test(address[] names) public view returns(address){
return names[0];
}
}
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
contract ReturnStruct {
struct student {
uint id;
uint age;
string name;
}
function setStudent() public constant returns(student) {
return (student({id:1,age:12,name:"name"}));
}
struct Person {
string name;
uint funds;
}
mapping(address => Person) people;
function getBryn()
public
returns (Person)
{
return Person({ name: "Bryn", funds: 123 });
}
function getPerson(address id)
public
returns (Person)
{
return people[id];
}
function getv() public view returns(Person){
return getBryn();
}
}
/// @title RLP Encoding Library for Solidity
/// @author Sam Mayo (sammayo888@gmail.com)
/// @dev Library for rlp encoding arbitrary bytes or lists.
library RLPEncode {
uint8 constant STRING_SHORT_PREFIX = 0x80;
uint8 constant STRING_LONG_PREFIX = 0xb7;
uint8 constant LIST_SHORT_PREFIX = 0xc0;
uint8 constant LIST_LONG_PREFIX = 0xf7;
/// @dev Rlp encodes a bytes
/// @param self The bytes to be encoded
/// @return The rlp encoded bytes
function encodeBytes(bytes memory self) public constant returns (bytes) {
bytes memory encoded;
if(self.length == 1 && uint(self[0]) < 0x80) {
encoded = new bytes(1);
encoded = self;
} else {
encoded = encode(self, STRING_SHORT_PREFIX, STRING_LONG_PREFIX);
}
return encoded;
}
/// @dev Rlp encodes a bytes[]. Note that the items in the bytes[] will not automatically be rlp encoded.
/// @param self The bytes[] to be encoded
/// @return The rlp encoded bytes[]
function encodeList(bytes[] memory self) internal constant returns (bytes) {
bytes memory list = flatten(self);
bytes memory encoded = encode(list, LIST_SHORT_PREFIX, LIST_LONG_PREFIX);
return encoded;
}
function encode(bytes memory self, uint8 prefix1, uint8 prefix2) public constant returns (bytes) {
uint selfPtr;
assembly { selfPtr := add(self, 0x20) }
bytes memory encoded;
uint encodedPtr;
uint len = self.length;
uint lenLen;
uint i = 0x1;
while(len/i != 0) {
lenLen++;
i *= 0x100;
}
if(len <= 55) {
encoded = new bytes(len+1);
// length encoding byte
encoded[0] = byte(prefix1+len);
// string/list contents
assembly { encodedPtr := add(encoded, 0x21) }
memcpy(encodedPtr, selfPtr, len);
} else {
// 1 is the length of the length of the length
encoded = new bytes(1+lenLen+len);
// length of the length encoding byte
encoded[0] = byte(prefix2+lenLen);
// length bytes
for(i=1; i<=lenLen; i++) {
encoded[i] = byte((len/(0x100**(lenLen-i)))%0x100);
}
// string/list contents
assembly { encodedPtr := add(add(encoded, 0x21), lenLen) }
memcpy(encodedPtr, selfPtr, len);
}
return encoded;
}
function flatten(bytes[] memory self) private constant returns (bytes) {
if(self.length == 0) {
return new bytes(0);
}
uint len;
for(uint i=0; i<self.length; i++) {
len += self[i].length;
}
bytes memory flattened = new bytes(len);
uint flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i=0; i<self.length; i++) {
bytes memory item = self[i];
uint selfPtr;
assembly { selfPtr := add(item, 0x20)}
memcpy(flattenedPtr, selfPtr, item.length);
flattenedPtr += self[i].length;
}
return flattened;
}
/// This function is from Nick Johnson's string utils library
function memcpy(uint dest, uint src, uint len) private {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
pragma solidity 0.4.18;
import "./contract/Ownable.sol";
/// @title The primary persistent storage for Rocket Pool
/// @author David Rugendyke
contract RocketStorage {
/**** Storage Types *******/
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/*** Modifiers ************/
/// @dev Only allow access from the latest version of a contract in the Rocket Pool network after deployment
modifier onlyLatestRocketNetworkContract() {
// The owner is only allowed to set the storage upon deployment to register the initial contracts, afterwards their direct access is disabled
if (msg.sender == owner) {
require(boolStorage[keccak256("contract.storage.initialised")] == false);
} else {
// Make sure the access is permitted to only contracts in our Dapp
require(addressStorage[keccak256("contract.address", msg.sender)] != 0x0);
}
_;
}
/**** Get Methods ***********/
/// @param _key The key for the record
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/// @param _key The key for the record
function getUint(bytes32 _key) external view returns (uint) {
return uIntStorage[_key];
}
/// @param _key The key for the record
function getString(bytes32 _key) external view returns (string) {
return stringStorage[_key];
}
/// @param _key The key for the record
function getBytes(bytes32 _key) external view returns (bytes) {
return bytesStorage[_key];
}
/// @param _key The key for the record
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/// @param _key The key for the record
function getInt(bytes32 _key) external view returns (int) {
return intStorage[_key];
}
/**** Set Methods ***********/
/// @param _key The key for the record
function setAddress(bytes32 _key, address _value) onlyLatestRocketNetworkContract external {
addressStorage[_key] = _value;
}
/// @param _key The key for the record
function setUint(bytes32 _key, uint _value) onlyLatestRocketNetworkContract external {
uIntStorage[_key] = _value;
}
/// @param _key The key for the record
function setString(bytes32 _key, string _value) onlyLatestRocketNetworkContract external {
stringStorage[_key] = _value;
}
/// @param _key The key for the record
function setBytes(bytes32 _key, bytes _value) onlyLatestRocketNetworkContract external {
bytesStorage[_key] = _value;
}
/// @param _key The key for the record
function setBool(bytes32 _key, bool _value) onlyLatestRocketNetworkContract external {
boolStorage[_key] = _value;
}
/// @param _key The key for the record
function setInt(bytes32 _key, int _value) onlyLatestRocketNetworkContract external {
intStorage[_key] = _value;
}
/**** Delete Methods ***********/
/// @param _key The key for the record
function deleteAddress(bytes32 _key) onlyLatestRocketNetworkContract external {
delete addressStorage[_key];
}
/// @param _key The key for the record
function deleteUint(bytes32 _key) onlyLatestRocketNetworkContract external {
delete uIntStorage[_key];
}
/// @param _key The key for the record
function deleteString(bytes32 _key) onlyLatestRocketNetworkContract external {
delete stringStorage[_key];
}
/// @param _key The key for the record
function deleteBytes(bytes32 _key) onlyLatestRocketNetworkContract external {
delete bytesStorage[_key];
}
/// @param _key The key for the record
function deleteBool(bytes32 _key) onlyLatestRocketNetworkContract external {
delete boolStorage[_key];
}
/// @param _key The key for the record
function deleteInt(bytes32 _key) onlyLatestRocketNetworkContract external {
delete intStorage[_key];
}
}
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity ^0.4.23;
// pragma experimental "v0.5.0";
// pragma experimental "ABIEncoderV2";
contract SetBit {
// Sets the bit at the given 'index' in 'self' to '1'.
// Returns the modified value.
function setBit(uint self, uint8 index) public pure returns (uint) {
return self | 1 << index;
}
// Check if the bit at the given 'index' in 'self' is set.
// Returns:
// 'true' - if the value of the bit is '1'
// 'false' - if the value of the bit is '0'
function bitSet(uint self, uint8 index) public pure returns (bool) {
return self >> index & 1 == 1;
}
}
pragma solidity ^0.4.18;
import "./Proxy.sol";
import "./SafeMath.sol";
contract KeyValueStorage {
mapping(address => mapping(bytes32 => uint256)) _uintStorage;
mapping(address => mapping(bytes32 => address)) _addressStorage;
mapping(address => mapping(bytes32 => bool)) _boolStorage;
/**** Get Methods ***********/
function getAddress(bytes32 key) public view returns (address) {
return _addressStorage[msg.sender][key];
}
function getUint(bytes32 key) public view returns (uint) {
return _uintStorage[msg.sender][key];
}
function getBool(bytes32 key) public view returns (bool) {
return _boolStorage[msg.sender][key];
}
/**** Set Methods ***********/
function setAddress(bytes32 key, address value) public {
_addressStorage[msg.sender][key] = value;
}
function setUint(bytes32 key, uint value) public {
_uintStorage[msg.sender][key] = value;
}
function setBool(bytes32 key, bool value) public {
_boolStorage[msg.sender][key] = value;
}
}
contract StorageStateful {
KeyValueStorage _storage;
}
contract StorageConsumer is StorageStateful {
function StorageConsumer(KeyValueStorage storage_) public {
_storage = storage_;
}
}
contract DetailedToken {
string public name;
string public symbol;
uint8 public decimals;
}
contract ShrimpCoin is StorageConsumer, Proxy, DetailedToken {
function ShrimpCoin(KeyValueStorage storage_)
public
StorageConsumer(storage_)
{
name = "ShrimpCoin";
symbol = "SHRMP";
decimals = 18;
}
}
contract TokenDelegate is StorageStateful {
using SafeMath for uint256;
function transfer(address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= getBalance(msg.sender));
subBalance(msg.sender, value);
addBalance(to, value);
return true;
}
function balanceOf(address owner) public view returns (uint256 balance) {
return getBalance(owner);
}
function getBalance(address balanceHolder) public view returns (uint256) {
return _storage.getUint(keccak256("balances", balanceHolder));
}
function totalSupply() public view returns (uint256) {
return _storage.getUint("totalSupply");
}
function addSupply(uint256 amount) internal {
_storage.setUint("totalSupply", totalSupply().add(amount));
}
function addBalance(address balanceHolder, uint256 amount) internal {
setBalance(balanceHolder, getBalance(balanceHolder).add(amount));
}
function subBalance(address balanceHolder, uint256 amount) internal {
setBalance(balanceHolder, getBalance(balanceHolder).sub(amount));
}
function setBalance(address balanceHolder, uint256 amount) internal {
_storage.setUint(keccak256("balances", balanceHolder), amount);
}
}
pragma solidity ^0.4.10;
import './SafeMath.sol';
interface ERC20 {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20 {
using SafeMath for uint;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
uint256 internal _totalSupply;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
function StandardToken(string name, string symbol, uint8 decimals, uint256 totalSupply) public {
_symbol = symbol;
_name = name;
_decimals = decimals;
_totalSupply = totalSupply;
balances[msg.sender] = totalSupply;
}
function name()
public
view
returns (string) {
return _name;
}
function symbol()
public
view
returns (string) {
return _symbol;
}
function decimals()
public
view
returns (uint8) {
return _decimals;
}
function totalSupply()
public
view
returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = SafeMath.sub(balances[_from], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
pragma solidity ^0.4.18;
import "./KeyValueStorage.sol";
contract StorageStateful {
KeyValueStorage _storage;
}
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <arachnid@notdot.net>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
pragma solidity ^0.4.14;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string self) internal pure returns (slice) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice self) internal pure returns (slice) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice self) internal pure returns (string) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice self, slice other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice self, slice other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice self, slice rune) internal pure returns (slice) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice self) internal pure returns (slice ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice self, slice needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice self, slice needle) internal pure returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, length), sha3(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice self, slice needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice self, slice needle) internal pure returns (slice) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
event log_bytemask(bytes32 mask);
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := sha3(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := sha3(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := sha3(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice self, slice needle) internal pure returns (slice) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice self, slice needle) internal pure returns (slice) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice self, slice needle, slice token) internal pure returns (slice) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice self, slice needle) internal pure returns (slice token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice self, slice needle, slice token) internal pure returns (slice) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice self, slice needle) internal pure returns (slice token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice self, slice needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice self, slice needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice self, slice other) internal pure returns (string) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice self, slice[] parts) internal pure returns (string) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
pragma solidity ^0.4.23;
contract Structs {
struct User {
uint256 age;
bytes32 name;
}
mapping(uint256 => User) users;
function setUser() public{
users[1].age = 18;
users[1].name = "Toniya";
}
function getUser() public view returns(uint256) {
return users[1].age;
}
}
pragma solidity ^0.4.23;
contract Test {
bytes public result;
function saveArgs(uint arg1,bool arg2, string arg3, address arg4) public returns(bytes4){
return this.saveArgs.selector;
}
function encodeMe(bytes4 selector, uint arg1,bool arg2, string arg3, address arg4) returns(bytes){
result = abi.encodeWithSelector(selector,arg1,arg2,arg3,arg4);
return result;
}
function compare(bytes arg1, bytes arg2) public returns (bool){
//bytes memory s1bytes = arg1;
// bytes memory s2bytes = arg2;
if(arg1.length!=arg2.length) {
return false;
}
else{
for(uint i = 0;i<arg1.length;i++)
{
if(arg1[i] != arg2[i])
return false;
}
return true;
}
}
function check(bytes a) public returns (bytes) {
return a;
}
}
pragma solidity ^0.4.18;
contract Test {
function concat(bytes32[] str1, bytes32[] str2) {
// bytes memory bs1 = bytes(str1);
// bytes memory bs2 = bytes(str2);
uint len1 = str1.length;
uint len2 = str2.length;
string memory temp = new string(len1 + len2);
bytes memory result = bytes(temp);
// uint index = 0;
// for (uint i = 0; i < len1; i++) {
// result[index++] = bs1[i];
// }
// for (i = 0; i < len2; i++) {
// result[index++] = bs2[i];
// }
// return string(result);
// }
}
}
pragma solidity ^0.4.2;
import "./Contract.sol";
contract TestCaller {
Contract newContract;
function createContract (bytes32 name) public returns(address){
newContract = new Contract(name);
return newContract;
}
}
import "./Contract.sol";
contract TestMe {
function Test(address newContract) public view returns(bytes32){
Contract con = Contract(newContract);
return con.Name();
}
}
pragma solidity ^0.4.18;
import "./Proxy.sol";
contract Thing is Proxy {
uint256 num;
string name ="Toniya";
}
contract ThingDelegate {
uint256 n;
function incrementNum() public {
n= n+1;
}
}
pragma solidity ^0.4.4;
contract Token {
//@ returns the total amount of tokens
function totalSupply() constant returns(uint256 supply){ }
// This funciton checks the balance of the owner
//@Param _owner is the address from whihch the balance will be retreived
//@return balance returns the balance
function balanceOf(address _owner) constant returns (uint256 balance){ }
//@notice send '_value' token to '_to' from msg.sender
//@Param _to is the address of the receiver
//@Param _value is the amount of the token to be transferred
//@return whether the transfer was successfull or not
function transfer(address _to,uint256 _value)returns (bool success){ }
//@notice sends the '_value' token from '_from' address to '_to' address on the condition it is approved by _from
//@Param _value is the amount of the token to be transferred
//@Param _from is the address of the sender
//@Param _to address of the receiver of the tokens
//@return whether the trans is successfull or not
function transferFrom (address _from, address _to, uint256 _value) returns(bool success){ }
//@notice msg.sender should approve to spend _value tokens from the address _spender
//@Param _spender is the address from which the tokens is transferred
//@Param _value is the amount of wei needs to be approved for transferred
//@return whether the apprval is successfull or not
function approve(address _spender, uint256 _value)returns (bool success){ }
//@Param _owner is the address of the account owning the tokens
//@Param _spender is the address of the account able to transfer tokens
//@return amount of remaining tokens left to spend
function allowance(address _owner,address _spender)constant returns (uint256 remaining) { }
event Transfer(address indexed _from, address indexed _to,uint256 _value);
event Approval(address indexed _owner, address indexed _spender,uint256 _value);
}
contract StandardToken is Token {
// Mapping the balances to thier address
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance){
return balances[_owner];
}
function transfer(address _to,uint256 _value) returns (bool success){
//Default assumes totalSupply can't exceed (2^256-1)
// We will issue tokens which is always less than the totalSupply
if(balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -=_value;
balances[_to] +=_value;
Transfer(msg.sender,_to,_value);
return true;
}else {
return false;
}
}
function transferFrom(address _from, address _to,uint256 _value) returns(bool success) {
//By default we assume that the totalSupply should not exceed (2^256 -1)
//We will now mention the fromaddress which may or may not be the sender
if(allowed[msg.sender][_from] >= _value && _value > 0){
balances[_from] -=_value;
balances[_to] +=_value;
allowed[_from][msg.sender] -=_value;
Transfer(_from,_to,_value);
return true;
}else{
return false;
}
}
function approve(address _spender, uint256 _value)returns (bool success){
allowed[msg.sender][_spender] = _value;
Approval(msg.sender,_spender,_value);
return true;
}
function allowance(address _owner,address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract ToniyaCoin is StandardToken {
string public tokenName; // tokenName
uint8 public decimals; // How many deceimal places to show . standard 18
string public symbol; // An identifier eg: BTC, ETH
string public version= "T1.0";
uint256 public uintOneEthCanBuy; // How many units of your coin can be bought by 1ETH
uint256 public totalEthinWei; //Wei is the smallest uint of eth We'll store the total ETH raised via our ICO here.
address public fundsWallet; // where should the raised ICO go
// A constructor which gives all initial tokens to the creater.
function ToniyaCoin () {
balances[msg.sender] = 1000000000000000000;
totalSupply = 1000000000000000000; // update the tototalSupply to the initialcoins [U CAN CHANGE THIS]
tokenName = "ToniyaCoin"; // Set the name for display purpose [U CAN CHANGE THIS]
decimals=18; // [U CAN CHANGE THIS]
symbol = "TCN"; // [U CAN CHANGE THIS]
uintOneEthCanBuy = 10; // Set the price of your tokenName [U CAN CHANGE THIS]
fundsWallet = msg.sender; // The owner of the ETH [U CAN CHANGE THIS]
}
function () payable {
totalEthinWei = totalEthinWei+msg.value;
uint256 amount = msg.value *uintOneEthCanBuy;
if(balances[fundsWallet] < amount) {
return;
}
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] +amount;
Transfer(fundsWallet, msg.sender,amount); // Broadcast the message to the blockchain
//Transfer funds to Eth wallet
fundsWallet.transfer(msg.value);
}
// // Approves and calls the receiving contract
// function approveAndCall(address _spender,address _to,uint256 _value, bytes _extraData) returns(bool success){
// allowed[msg.sender][_spender]= _value;
// Approval(msg.sender,_spender,_value);
// //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
// if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
// return true;
// }
}
pragma solidity ^0.4.18;
// We have to specify what version of compiler this code will compile with
contract Voting {
/* mapping field below is equivalent to an associative array or hash.
The key of the mapping is candidate name stored as type bytes32 and value is
an unsigned integer to store the vote count
*/
mapping (bytes32 => uint8) public votesReceived;
/* Solidity doesn't let you pass in an array of strings in the constructor (yet).
We will use an array of bytes32 instead to store the list of candidates
*/
bytes32[] public candidateList;
/* This is the constructor which will be called once when you
deploy the contract to the blockchain. When we deploy the contract,
we will pass an array of candidates who will be contesting in the election
*/
function Voting(bytes32[] candidateNames) public {
candidateList = candidateNames;
}
// This function returns the total votes a candidate has received so far
function totalVotesFor(bytes32 candidate) view public returns (uint8) {
require(validCandidate(candidate));
return votesReceived[candidate];
}
// This function increments the vote count for the specified candidate. This
// is equivalent to casting a vote
function voteForCandidate(bytes32 candidate) public {
require(validCandidate(candidate));
votesReceived[candidate] += 1;
}
function validCandidate(bytes32 candidate) view public returns (bool) {
for(uint i = 0; i < candidateList.length; i++) {
if (candidateList[i] == candidate) {
return true;
}
}
return false;
}
}
pragma solidity ^0.4.24;
contract Voting1 {
address[] candidatelist;
mapping( address => uint) totalVotes;
uint count=1;
constructor(address[] _candidates) {
candidatelist = _candidates;
}
function voteForCandiate(address _name) {
require(checkCandidate(_name)== true,"The candiate is not valid");
totalVotes[_name] += count;
}
function totalVotesReceived(address _name) public view returns(uint) {
require(checkCandidate(_name)== true,"The candiate is not valid");
return totalVotes[_name];
}
function checkCandidate(address _name) returns(bool){
for(uint i=0;i<candidatelist.length;i++){
if(_name == candidatelist[i])
return true;
}
return false;
}
}
pragma solidity ^0.4.4;
import "./strings.sol";
contract XFinance {
using strings for *;
address addr;
uint coin;
Shipment shipment;
function XFinance(uint balance) {
coin=balance;
shipment=new Shipment();
}
function changeShipmentStatus(string shipmentId,string st,address driverAddress){
shipment.setShipmentId(shipmentId);
shipment.setStatusOfShipment(st);
processPayment(driverAddress);
}
function processPayment(address driverAddress){
string currentStatus=shipment.getStatusOfShipment();
if(currentStatus.toSlice().equals('RAP'.toSlice())){
shipment.setAddressOfDiver1(driverAddress);
sendPayment(driverAddress);
}
else if(currentStatus.toSlice().equals('DAL'.toSlice())){
shipment.setAddressOfDiver2(driverAddress);
sendPayment(driverAddress);
}
else
if(currentStatus.toSlice().equals('ATD'.toSlice())){
shipment.setAddressOfDriver3(driverAddress);
sendPayment(driverAddress);
}
}
function sendPayment(address beneficiary) payable returns(bool success) {
if(msg.value==0) throw;
if(!beneficiary.send(msg.value)) throw;
return true;
}
function getBalance() returns(uint){
return coin;
}
function getStatus() returns(string){
return shipment.statusOfShipment;
}
function getAddress() returns(address){
return addr;
}
}
contract Shipment{
string public shipmentId;
string public statusOfShipment;
address public driver1;
address public driver2;
address public driver3;
function Shipment(){}
function setShipmentId(string shId){
shipmentId=shId;
}
function getShipmentId() returns(string){
return shipmentId;
}
function setStatusOfShipment(string st){
statusOfShipment=st;
}
function getStatusOfShipment() returns(string){
return statusOfShipment;
}
function setAddressOfDriver1(address d1){
driver1=d1;
}
function getAddressOfDriver1() returns(address){
return driver1;
}
function setAddressOfDriver2(address d2){
driver2=d2;
}
function getAddressOfDriver2() returns(address){
return driver2;
}
function setAddressOfDriver3(address d3){
driver3=d3;
}
function getAddressOfDriver3() returns(address){
return driver3;
}
}
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'YANG' token contract
//
// Deployed to : 0x25D769a1b3bcAF7216b0cea17C056130fe1720cf
// Symbol : YNN
// Name : YANG
// Total supply: 25000000000000000000000000000
// Decimals : 18
//
// Enjoy.
//
// (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract YANG is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function YANG() public {
symbol = "YNN";
name = "YANG";
decimals = 18;
_totalSupply = 25000000000000000000000000000;
balances[0xca35b7d915458ef540ade6068dfe2f44e8fa733c] = _totalSupply;
Transfer(address(0), 0x25D769a1b3bcAF7216b0cea17C056130fe1720cf, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
@ayinot
Copy link
Author

ayinot commented Jun 27, 2018

Remix files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment