Skip to content

Instantly share code, notes, and snippets.

@Juan-cc
Created January 18, 2019 15:22
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 Juan-cc/0ec1756ad7f012db255cbbd21eca3a74 to your computer and use it in GitHub Desktop.
Save Juan-cc/0ec1756ad7f012db255cbbd21eca3a74 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.5.2+commit.1df8f40c.js&optimize=false&gist=
# Voting with delegation.
# Information about voters
voters: public({
# weight is accumulated by delegation
weight: int128,
# if true, that person already voted (which includes voting by delegating)
voted: bool,
# person delegated to
delegate: address,
# index of the voted proposal, which is not meaningful unless 'voted' is True.
vote: int128
}[address])
# This is a type for a list of proposals.
proposals: public({
# short name (up to 32 bytes)
name: bytes32,
# int128ber of accumulated votes
vote_count: int128
}[int128])
voter_count: public(int128)
chairperson: public(address)
int128_proposals: public(int128)
@public
@constant
def delegated(addr: address) -> bool:
return self.voters[addr].delegate != ZERO_ADDRESS
@public
@constant
def directly_voted(addr: address) -> bool:
return self.voters[addr].voted and (self.voters[addr].delegate == ZERO_ADDRESS)
# Setup global variables
@public
def __init__(_proposalNames: bytes32[2]):
self.chairperson = msg.sender
self.voter_count = 0
for i in range(2):
self.proposals[i] = {
name: _proposalNames[i],
vote_count: 0
}
self.int128_proposals += 1
# Give a 'voter' the right to vote on this ballot.
# This may only be called by the 'chairperson'.
@public
def give_right_to_vote(voter: address):
# Throws if the sender is not the chairperson.
assert msg.sender == self.chairperson
# Throws if the voter has already voted.
assert not self.voters[voter].voted
# Throws if the voter's voting weight isn't 0.
assert self.voters[voter].weight == 0
self.voters[voter].weight = 1
self.voter_count += 1
# Used by 'delegate' below, and can be called by anyone.
@public
def forward_weight(delegate_with_weight_to_forward: address):
assert self.delegated(delegate_with_weight_to_forward)
# Throw if there is nothing to do:
assert self.voters[delegate_with_weight_to_forward].weight > 0
target: address = self.voters[delegate_with_weight_to_forward].delegate
for i in range(4):
if self.delegated(target):
target = self.voters[target].delegate
# The following effectively detects cycles of length <= 5,
# in which the delegation is given back to the delegator.
# This could be done for any int128ber of loops,
# or even infinitely with a while loop.
# However, cycles aren't actually problematic for correctness;
# they just result in spoiled votes.
# So, in the production version, this should instead be
# the responsibility of the contract's client, and this
# check should be removed.
assert target != delegate_with_weight_to_forward
else:
# Weight will be moved to someone who directly voted or
# hasn't voted.
break
weight_to_forward: int128 = self.voters[delegate_with_weight_to_forward].weight
self.voters[delegate_with_weight_to_forward].weight = 0
self.voters[target].weight += weight_to_forward
if self.directly_voted(target):
self.proposals[self.voters[target].vote].vote_count += weight_to_forward
self.voters[target].weight = 0
# To reiterate: if target is also a delegate, this function will need
# to be called again, similarly to as above.
# Delegate your vote to the voter 'to'.
@public
def delegate(to: address):
# Throws if the sender has already voted
assert not self.voters[msg.sender].voted
# Throws if the sender tries to delegate their vote to themselves or to
# the default address value of 0x0000000000000000000000000000000000000000
# (the latter might not be problematic, but I don't want to think about it).
assert to != msg.sender
assert to != ZERO_ADDRESS
self.voters[msg.sender].voted = True
self.voters[msg.sender].delegate = to
# This call will throw if and only if this delegation would cause a loop
# of length <= 5 that ends up delegating back to the delegator.
self.forward_weight(msg.sender)
# Give your vote (including votes delegated to you)
# to proposal 'proposals[proposal].name'.
@public
def vote(proposal: int128):
# can't vote twice
assert not self.voters[msg.sender].voted
# can only vote on legitimate proposals
assert proposal < self.int128_proposals
self.voters[msg.sender].vote = proposal
self.voters[msg.sender].voted = True
# transfer msg.sender's weight to proposal
self.proposals[proposal].vote_count += self.voters[msg.sender].weight
self.voters[msg.sender].weight = 0
# Computes the winning proposal taking all
# previous votes into account.
@public
@constant
def winning_proposal() -> int128:
winning_vote_count: int128 = 0
winning_proposal: int128 = 0
for i in range(2):
if self.proposals[i].vote_count > winning_vote_count:
winning_vote_count = self.proposals[i].vote_count
winning_proposal = i
return winning_proposal
# Calls winning_proposal() function to get the index
# of the winner contained in the proposals array and then
# returns the name of the winner
@public
@constant
def winner_name() -> bytes32:
return self.proposals[self.winning_proposal()].name
pragma solidity ^0.5.1;
import "./Owned.sol";
import "./KMToken.sol";
import "./TokenFactory.sol";
import "./Storage.sol";
contract BCFactory is Owned, Storage {
//event BCFactoryMsgSender(address indexed msgSender);
//event BCFactoryCompanyCreated(address companyAddress, string _companyName, string _phone, string _url);
//event BCFactoryPosition(uint8 position);
constructor(address deployer)
public
{
owner = deployer;
}
function createBCCompany(string memory _companyName, string memory _phone, string memory _url, string memory _did, address _uPortAddress)
public
// ownerOnly(msg.sender) // I won't control WHO because I want anybody to create companies.
returns (BC)
{
// emit BCFactoryMsgSender(msg.sender);
uint8 position = nextCompanyAvailablePosition();
require(MAX_OWNER_COMPANIES > position, "You can't create a new company. Max limit reached (5 companies).");
BC newCompany = new BC(msg.sender, _companyName, _phone, _url, _did, _uPortAddress);
companies[msg.sender][position] = address(newCompany);
//emit BCFactoryCompanyCreated(address(newCompany), _companyName, _phone, _url);
return newCompany;
}
function nextCompanyAvailablePosition()
internal
returns (uint8)
{
address[MAX_OWNER_COMPANIES] memory ownerCompanies = companies[msg.sender];
for (uint8 i = 0; i < MAX_OWNER_COMPANIES; i++) {
if (ownerCompanies[i] == EMPTY_ADDRESS){
//emit BCFactoryPosition(i);
return i; // This is the first available position.
}
}
return MAX_OWNER_COMPANIES; // No empty spot available.
}
}
contract BC is Owned {
mapping (address => bool) public admins;
string public name;
string public phone;
string public url;
string private did;
address private uPortAddress;
mapping (address => address[]) public tokens;
event BCCreated(address indexed companyAddress, string _companyName, string _phone, string _url);
event BCTokenAdded(address indexed tokenAdded);
event BCMsgSender(address indexed msgSender);
event BCTerminated(address indexed companyAddress, string _companyName, string _phone, string _url);
constructor(address _owner, string memory _companyName, string memory _phone, string memory _url, string memory _did, address _uPortAddress)
public
{
owner = _owner;
//emit BCMsgSender(msg.sender);
name = _companyName;
phone = _phone;
url = _url;
did = _did;
uPortAddress = _uPortAddress;
admins[owner] = true;
//emit BCCreated(address(this), _companyName, _phone, _url);
}
function terminateCompany(address newCompanyContract)
public
ownerOnly(msg.sender)
{
// TOTO: before selfdestruction delegate token ownership to newCompanyContract.
selfdestruct(msg.sender);
emit BCTerminated(address(this), name, phone, url);
}
}
pragma solidity ^0.5.1;
import "./IERC20_510.sol";
import "./SafeMath_510.sol";
/**
* @title Standard ERC20 token
*
* source https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts/token/ERC20
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit 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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
pragma solidity ^0.5.1;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*
* source https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts/token/ERC20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external 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.5.1;
import "./KMToken.sol";
import "./Owned.sol";
import "./BC.sol";
import "./TokenFactory.sol";
import "./Storage.sol";
contract KMP is Owned, Storage {
// Events
event KMPCompanyCreated(address company, string name, address owner);
event KMPTokenCreated(address _company, address _token, string _name, string _symbol, uint256 _initialAmount);
event KMMsgSender(address indexed msgSender);
event KMUserTokenBalance(address indexed user, uint256 balance);
event KMReturnedToken(KMToken returnToken);
event KMReturnedBC(BC returnBC);
event KMTokenAssigned(address _from, address _to, uint256 _amount);
constructor() public {
bcFactory = new BCFactory(msg.sender);
tkFactory = new TokenFactory(msg.sender);
}
function factoryOwnerUtil()
public
view
returns (address)
{
return bcFactory.owner();
}
function testCreateBC()
public
returns (BC)
{
address anAddress = 0xdA35deE8EDDeAA556e4c26268463e26FB91ff74f;
return createBCCompany("Company Name", "123456789", "www.google.com", "did:eth:0x2f3fcf4c3", anAddress);
}
function testCreateCompanyAndToken() public {
BC newCompany = testCreateBC();
testCreateToken(address(newCompany));
}
function testCreateToken(address anAddress) public{
createTokenForBCCompany(anAddress, "Tokenzito", "TKZT", 1000);
}
function getUserTokenBalance(address _company, address _token, address _user)
public
returns (uint256 aBalance)
{
require(msg.sender == findBCowner(_company), "Only company owner can query token balances.");
require(EMPTY_ADDRESS != findBCToken(_company, _token));
bytes memory payload = abi.encodeWithSignature("balanceOf(address)", _user);
(bool result, bytes memory returnData) = _token.staticcall(payload);
if (result) {
emit KMMsgSender(msg.sender);
aBalance = abi.decode(returnData, (uint256));
return aBalance;
}
}
function createBCCompany(string memory _companyName, string memory _phone, string memory _url, string memory _did, address _uPortAddress)
public
// ownerOnly(msg.sender) I want anybody to be able to create a new BC on my platform.
returns(BC){
(bool companyCreated, bytes memory returnData) = address(bcFactory).delegatecall(
abi.encodeWithSignature("createBCCompany(string,string,string,string,address)",
_companyName, _phone, _url, _did, _uPortAddress));
if (companyCreated){
(BC newCompany) = abi.decode(returnData, (BC));
emit KMPCompanyCreated(address(newCompany), newCompany.name(), newCompany.owner());
return newCompany;
}
revert("Unfortunately your company was not created correctly. Please contact KMP Support. Reverting state changes.");
}
function findBCownerUtil(address company) // Util methods are for development purposes only.
public
view
//ownerOnly(msg.sender)
returns (address)
{
return findBCowner(company);
}
function findBCowner(address aCompany)
internal
view
returns (address)
{
address[MAX_OWNER_COMPANIES] memory ownerCompanies = companies[msg.sender];
for (uint8 i = 0; i < MAX_OWNER_COMPANIES; i++) {
if (ownerCompanies[i] == aCompany){
return BC(ownerCompanies[i]).owner();
}
}
revert("Company address not found.");
}
function tokenInBC(address aCompany, address aToken)
public
returns (bool)
{
require(msg.sender == findBCowner(aCompany), "Only company owner can search for tokens.");
address[MAX_COMPANY_TOKENS] memory companyTokens = tokens[aCompany];
for (uint8 i = 0; i < MAX_COMPANY_TOKENS; i++) {
if (companyTokens[i] == aToken){
return true; // Token found.
}
}
return false; // Token not found.
}
function findBCToken(address aCompany, address aToken)
public
returns (address)
{
if (tokenInBC(aCompany, aToken)){
return aToken;
}
return EMPTY_ADDRESS;
}
function createTokenForBCCompany(address _bcCompany, string memory _name, string memory _symbol, uint256 _initialAmount)
public
//ownerOnly(companies[bcCompany].owner()) // Only Company owner can create tokens.
returns(KMToken){
require (msg.sender == findBCowner(_bcCompany), "Only company owner can create tokens.");
(bool tokenCreated, bytes memory returnData) = address(tkFactory).delegatecall(
abi.encodeWithSignature("createTokenForBCCompany(address,string,string,uint256)",
_bcCompany, _name, _symbol, _initialAmount));
if (tokenCreated){
(KMToken newToken) = abi.decode(returnData, (KMToken));
emit KMPTokenCreated(_bcCompany, address(newToken), _name, _symbol, _initialAmount);
return newToken;
}
revert("Unfortunately your token was not created correctly. Please contact KMP Support. Reverting state changes.");
}
function getTotalSupply(address token)
public
view
returns (uint256)
{
return KMToken(token).totalSupply();
}
function getUserBalance(address token, address user)
public
returns (uint256)
{
return KMToken(token).balanceOf(user);
}
function kmpOwner()
public
view
returns (address)
{
return owner;
}
}
pragma solidity ^0.5.1;
//import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
//import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/math/SafeMath.sol";
//import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "./SafeMath_510.sol";
import "./ERC20_510.sol";
import "./IERC20_510.sol";
import "./Owned.sol";
contract KMToken is ERC20, Owned {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
address tokenFactory;
string public symbol;
string public name;
uint8 public decimals = 0; // We wont work with fractions of a token.
address private company;
event KMTokenMsgSender(address msgSender);
event KMTokenValue(uint256 value);
event KMTokenFromToValor(address from, address to,uint256 value,uint256 _balanceFrom);
/*constructor()
public
{
init(msg.sender, "TokenZito", "TKN", 1000);
}*/
constructor (address _company, address _owner, string memory tokenName, string memory tokenSymbol, uint256 initialSupply)
public
{
tokenFactory = msg.sender;
owner = _owner;
company = _company;
_balances[owner] = initialSupply;
_totalSupply = initialSupply;
symbol = tokenSymbol;
name = tokenName;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit 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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
emit KMTokenFromToValor(from, to, value, _balances[from]);
//_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
pragma solidity ^0.5.1;
contract Owned{
/* TODO: Can be changed for Ownable from zepellin*/
address public owner;
constructor() public{
owner = msg.sender;
}
modifier ownerOnly(address _owner){
require(owner == _owner, "Access denied. Company owner only.");
_;
}
function modifyOwner(address _owner)
public
ownerOnly(msg.sender)
{
owner = _owner;
}
}
pragma solidity ^0.5.1;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*
* source https://github.com/OpenZeppelin/openzeppelin-solidity/tree/master/contracts/math/SafeMath.sol
*/
library SafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.4.24;
contract SimpleContract {
uint256 public values = 15;
function addItem(string _name, uint _price) public {
values += _price;
}
function returnValue() public returns (bool) {
}
}
pragma solidity ^0.5.1;
import "./BC.sol";
import "./TokenFactory.sol";
contract Storage {
// Shared storage
uint8 constant internal MAX_OWNER_COMPANIES = 5; // 1 owner could register up to 5 companies.
uint8 constant internal MAX_COMPANY_TOKENS = 10; // 1 company could register up to 10 tokens.
address constant internal EMPTY_ADDRESS = address(0);
mapping (address => address[MAX_OWNER_COMPANIES]) internal companies; // (owner => companies[5])
mapping (address => address[10]) internal tokens; // (company => token[]))
BCFactory internal bcFactory;
TokenFactory internal tkFactory;
}
pragma solidity ^0.4.23;
contract SupplyChain {
/* set owner */
address public owner;
/* Add a variable called skuCount to track the most recent sku # */
uint public skuCount;
/* Add a line that creates a public mapping that maps the SKU (a number) to an Item.
Call this mappings items
*/
mapping (uint => Item) public items;
/* Add a line that creates an enum called State. This should have 4 states
ForSale
Sold
Shipped
Received
(declaring them in this order is important for testing)
*/
enum State {ForSale, Sold, Shipped, Received}
/* Create a struct named Item.
Here, add a name, sku, price, state, seller, and buyer
We've left you to figure out what the appropriate types are,
if you need help you can ask around :)
*/
struct Item{
string name;
uint sku;
uint price;
State state;
address seller;
address buyer;
}
/* Create 4 events with the same name as each possible State (see above)
Each event should accept one argument, the sku*/
event ForSale(uint indexed sku);
event Sold(uint indexed sku);
event Shipped(uint indexed sku);
event Received(uint indexed sku);
/* Create a modifer that checks if the msg.sender is the owner of the contract */
modifier isOwner(){
require(msg.sender == owner, "Only owner's allowed.");
_;
}
modifier verifyCaller (address _address) { require (msg.sender == _address); _;}
modifier paidEnough(uint _price) { require(msg.value >= _price); _;}
modifier checkValue(uint _sku) {
//refund them after pay for item (why it is before, _ checks for logic before func)
_;
uint _price = items[_sku].price;
uint amountToRefund = msg.value - _price;
items[_sku].buyer.transfer(amountToRefund);
}
/* For each of the following modifiers, use what you learned about modifiers
to give them functionality. For example, the forSale modifier should require
that the item with the given sku has the state ForSale. */
modifier forSale(uint sku){
require(items[sku].state == State.ForSale, "Item not for sale.");
_;
}
modifier sold(uint sku){
require(items[sku].state == State.Sold, "Item is not sold.");
_;
}
modifier shipped(uint sku){
require(items[sku].state == State.Shipped, "Item has not been shipped.");
_;
}
modifier received(uint sku){
require(items[sku].state == State.Received, "Item has not been received.");
_;
}
constructor() public {
/* Here, set the owner as the person who instantiated the contract
and set your skuCount to 0. */
owner = msg.sender;
skuCount = 0;
}
function addItem(string _name, uint _price) public {
skuCount += 1;
items[skuCount] = Item({name: _name, sku: skuCount, price: _price, state: State.ForSale, seller: msg.sender, buyer: 0});
emit ForSale(skuCount);
}
/* Add a keyword so the function can be paid. This function should transfer money
to the seller, set the buyer as the person who called this transaction, and set the state
to Sold. Be careful, this function should use 3 modifiers to check if the item is for sale,
if the buyer paid enough, and check the value after the function is called to make sure the buyer is
refunded any excess ether sent. Remember to call the event associated with this function!*/
function buyItem(uint sku)
public
payable
forSale(sku)
paidEnough(items[sku].price)
checkValue(sku)
{
Item storage item = items[sku];
item.seller.transfer(item.price);
item.buyer = msg.sender;
item.state = State.Sold;
emit Sold(sku);
}
/* Add 2 modifiers to check if the item is sold already, and that the person calling this function
is the seller. Change the state of the item to shipped. Remember to call the event associated with this function!*/
function shipItem(uint sku)
public
sold(sku)
verifyCaller(items[sku].seller)
{
items[sku].state = State.Shipped;
emit Shipped(sku);
}
/* Add 2 modifiers to check if the item is shipped already, and that the person calling this function
is the buyer. Change the state of the item to received. Remember to call the event associated with this function!*/
function receiveItem(uint sku)
public
shipped(sku)
verifyCaller(items[sku].buyer)
{
items[sku].state = State.Received;
emit Received(sku);
}
/* We have these functions completed so we can run tests, just ignore it :) */
function fetchItem(uint _sku) public view returns (string name, uint sku, uint price, uint state, address seller, address buyer) {
name = items[_sku].name;
sku = items[_sku].sku;
price = items[_sku].price;
state = uint(items[_sku].state);
seller = items[_sku].seller;
buyer = items[_sku].buyer;
return (name, sku, price, state, seller, buyer);
}
}
pragma solidity >=0.4.0 <0.6.0;
import "remix_tests.sol"; // this import is automatically injected by Remix.
// file name has to end with '_test.sol'
contract test_1 {
function beforeAll() public {
// here should instantiate tested contract
Assert.equal(uint(4), uint(3), "error in before all function");
}
function check1() public {
// use 'Assert' to test the contract
Assert.equal(uint(2), uint(1), "error message");
Assert.equal(uint(2), uint(2), "error message");
}
function check2() public view returns (bool) {
// use the return value (true or false) to test the contract
return true;
}
}
contract test_2 {
function beforeAll() public {
// here should instantiate tested contract
Assert.equal(uint(4), uint(3), "error in before all function");
}
function check1() public {
// use 'Assert' to test the contract
Assert.equal(uint(2), uint(1), "error message");
Assert.equal(uint(2), uint(2), "error message");
}
function check2() public view returns (bool) {
// use the return value (true or false) to test the contract
return true;
}
}
pragma solidity ^0.4.24;
//import "./ThrowProxy.sol";
import "./SimpleContract.sol";
contract TestSimpleContract {
uint256 public values = 15;
ThrowProxy proxy;
SimpleContract simple = new SimpleContract();
function returnValue() public returns (uint256) {
return values;
}
function testThrowProxy() public {
proxy = new ThrowProxy(address(simple));
SimpleContract(address(proxy)).returnValue();
}
}
// Proxy contract for testing throws
contract ThrowProxy {
address public target;
bytes data;
constructor(address _target) public {
target = _target;
}
//prime the data using the fallback function.
function() public {
data = msg.data;
}
function execute() public returns (bool){
return target.call(data);
}
}
pragma solidity ^0.4.13;
//import "github.com/trufflesuite/truffle/truffle-core/lib/testing/Assert.sol";
//import "truffle/Assert.sol";
//import "truffle/DeployedAddresses.sol";
import "./SupplyChain.sol";
import "./ThrowProxy.sol";
import "./SimpleContract.sol";
contract TestSupplyChain {
// Truffle looks for `initialBalance` when it compiles the test suite
// and funds this test contract with the specified amount on deployment.
//uint public initialBalance = 10 ether;
SupplyChain supplyChain = new SupplyChain();
SimpleContract simple = new SimpleContract();
ThrowProxy proxy;
// TODO Juan - Refactor needed
function pirulo() public{
proxy = new ThrowProxy(address(simple));
// Adding one item as part of the setup.
SimpleContract(address(proxy)).returnValue();
bool r = proxy.execute.gas(200000)();
// Assert.isTrue(r, "We are not able to add items.");
}
}
pragma solidity ^0.4.24;
// Proxy contract for testing throws
contract ThrowProxy {
address public target;
bytes data;
constructor(address _target) public payable {
target = _target;
}
//prime the data using the fallback function.
function() external {
data = msg.data;
}
function execute() public returns (bool) {
(bool result,) = address(target).call(data);
return result;
}
}
pragma solidity ^0.5.1;
import "./Owned.sol";
import "./BC.sol";
import "./KMToken.sol";
import "./Storage.sol";
contract TokenFactory is Owned, Storage {
//event TokenFactoryMsgSender(address msgSender);
//event TokenFactoryTokenCreated(address _bcCompany, address _token, string _name, string _symbol, uint256 _initialAmount);
//event TokenFactoryPositionAvailable(uint8 position);
constructor(address deployer)
public
{
owner = deployer;
}
function createTokenForBCCompany(address _bcCompany, string memory _name, string memory _symbol, uint256 _initialAmount)
public
returns (KMToken)
{
// emit TokenFactoryMsgSender(msg.sender);
require(msg.sender == findBCowner(_bcCompany)); // 2nd time checking correct ownership.
KMToken newToken = new KMToken(_bcCompany, msg.sender, _name, _symbol, _initialAmount);
tokens[_bcCompany][1] = address(newToken);
//emit TokenFactoryTokenCreated(_bcCompany, address(newToken), _name, _symbol, _initialAmount);
return newToken;
}
function findBCowner(address aCompany)
internal
view
returns (address)
{
address[MAX_OWNER_COMPANIES] memory ownerCompanies = companies[msg.sender];
for (uint8 i = 0; i < MAX_OWNER_COMPANIES; i++) {
if (ownerCompanies[i] == aCompany){
return BC(ownerCompanies[i]).owner();
}
}
revert("Company address not found.");
}
function nextTokenAvailablePosition(address aCompany)
internal
returns (uint8)
{
require(msg.sender == findBCowner(aCompany), "Only company owner can search for tokens.");
address[MAX_COMPANY_TOKENS] memory companyTokens = tokens[aCompany];
for (uint8 i = 0; i < MAX_COMPANY_TOKENS; i++) {
if (companyTokens[i] == EMPTY_ADDRESS){
//emit TokenFactoryPositionAvailable(i);
return i; // This is the first available position.
}
}
return MAX_COMPANY_TOKENS; // No empty spot available.
}
}
pragma solidity ^0.5.0;
import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/release-v2.1.0-solc-0.5/contracts/token/ERC20/ERC20Detailed.sol";
contract Samples{
function something() public returns(string memory){
return string(abi.decode(1));
}
}
pragma solidity ^0.5.2;
contract Test{
struct Something {
string greeting;
string name;
}
mapping ( uint8 => Something) internal aMap;
function testAccess() external returns (string memory) {
Something memory aSomething = Something("Hello", "Kreaan Singh");
aMap[1] = aSomething;
return aMap[1].name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment