Skip to content

Instantly share code, notes, and snippets.

@ecancino
Last active June 27, 2021 05:42
Show Gist options
  • Save ecancino/772e18096793a5175a46b0cfc8cc1df3 to your computer and use it in GitHub Desktop.
Save ecancino/772e18096793a5175a46b0cfc8cc1df3 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.5.17+commit.d19bba13.js&optimize=false&runs=200&gist=
pragma solidity ^0.4.4;
contract Account {}
pragma solidity ^0.4.25;
contract AddressType {
address public owner;
uint public initialBalance;
function test(address addr) public returns (uint) {
owner = addr;
initialBalance = owner.balance;
return initialBalance;
}
}
pragma solidity >=0.4.24;
contract ArraysContract {
// Elementary type array in storage
// Static Array with size 3 of type int
int[3] staticIntArray = [1,2]; // Last element set to 0
// Dynamic array of type int8
int8[] dynamicIntArray;
// Dynamic array of type bool
bool[] dynamicBoolArray;
function testArray() public {
// Allocate memory for 8 elements to the dynamic bool storage array
dynamicBoolArray = new bool[](8);
// Allocate memory and initialize elements in the int array
// Explicit conversion is needed from uint8 to int8
dynamicIntArray = [int8(1),2,3];
// This will work fine, since we are inside a function
uint8[] memory memoryArray; // A Dynamic memory array
// Allocation with assignment not allowed for dynamic memory arrays
// memoryArray = [1,2,3];
uint8[] memory dynamicMemoryArray; // A Dynamic memory array
// Assignment of dynamic NOT allowed
//dynamicMemoryArray = [uint8(1),2];
memoryArray = new uint8[](8);
// push() not allowed for memory array
// memoryArray.push(1);
// memoryArray.length=6;
/** Examples of array initialization with assignment below */
// Static storage array assignment is OK
// Compile time size check is carried out
// so assignment to [1,2,3,4] will fail below
staticIntArray = [1,2,3];
// Static memory array
uint[2] memory staticMemoryArray;
// This is allowed - make sure the type is matching
// staticMemoryArray is of type uint
staticMemoryArray = [uint(1),2];
// This is allowed
staticMemoryArray[0] = 0;
staticMemoryArray[1] = 1;
dynamicMemoryArray[0] = 1;
dynamicMemoryArray[1] = 2;
}
}
pragma solidity ^0.4.4;
import "./Account.sol";
contract CreditAccount is Account {
}
pragma solidity >=0.4.24;
contract EnumsContract {
// Create an Enumeration
enum names {Joe, Brandy, Rachna, Jessica}
// get the value at specified index
function getNames(uint8 arg) public pure returns (string memory){
if(arg == uint8(names.Joe)) return "Joe";
if(arg == uint8(names.Brandy)) return "Brandy";
if(arg == uint8(names.Rachna)) return "Rachna";
if(arg == uint8(names.Jessica)) return "Jessica";
}
}
pragma solidity >=0.4.24;
contract ERC20Interface {
// string public constant name;
// string public constant symbol = "EZZ";
// uint8 public constant decimals = 18; // 18 is the most common number of decimal places
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function transfer(address to, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
}
pragma solidity >=0.4.24;
contract EventsContract {
// Represents the time when the bidding will end
uint biddingEnds = now + 5 days;
struct HighBidder {
address bidder;
string bidderName;
uint bid;
}
// Variable of type HighBidder
HighBidder public highBidder;
// Events emitted by contract
// Whenever a high bid is received
event NewHighBid(address indexed who, string name, uint howmuch);
// High bid preceded by this event
event BidFailed(address indexed who, string name, uint howmuch);
// Ensures that bid can be received i.e, auction not ended
modifier timed {
if(now < biddingEnds){
_;
} else {
/**throw an exception */
revert("Throw an exception");
}
}
constructor() public {
// Starts the bidding at 1 ether
highBidder.bid = 1 ether;
}
// Payable since ether should be coming along
// Timed, we need to end this bidding in 5 days
function bid(string memory bidderName) public payable timed {
if(msg.value > highBidder.bid) {
highBidder.bidder = msg.sender;
highBidder.bidderName = bidderName;
highBidder.bid = msg.value;
// Received a high bid - emit event
emit NewHighBid(msg.sender, bidderName, msg.value);
} else {
// Received bid less than high bid emit event
emit BidFailed(msg.sender, bidderName, msg.value);
// throwing exception would return the ethers
revert("Throw an exception");
}
}
}
pragma solidity >=0.4.24;
contract ExceptionsContract {
// Public variable lastCaller, with a value of none
string public lastCaller = "none";
// Function revertBehavior that takes in a name as an argument,
//and sets the lastCaller variable to this argument received
function revertBehavior(string memory name) public returns (bool) {
lastCaller = name;
// Check if length of the string is zero
// If the argument received has zero length, it throws an exception...
// Once an exception is thrown, the variable lastCaller rolls back to its initial value
if (bytes(name).length == 0) {
revert("The length of the string is zero");
}
// This is the same thing...just using require to check the length of the input string.
// The code will only be exceuted if the length is greater than 0
// The above lines of code may be replaced with this
require(bytes(name).length > 0, "The length of the string is zero");
return true;
}
}
// So, what is going on is that in the function revertBehavior
// lastCaller is being changed to the input argument
// and then an exception is thrown, and the lastCaller reverts back
// to its orginial value, thus nullifying the effect
pragma solidity >=0.4.24;
contract FunctionsContract {
string ownerName;
uint8 ownerAge;
// Constructor
constructor (string memory name, uint8 age) public {
ownerName = name;
ownerAge = age;
}
// We are changing the owner name and age
function setOwnerInfo(string memory name, uint8 age) public {
ownerName = name;
ownerAge = age;
}
function secretFunction() private pure {
// Not available outside this contract
}
// Get owner name and age
function getOwnerInfo() public view returns (string memory name, uint8 age){
name = ownerName;
age = ownerAge;
}
// Get the name
// 2 ways to return values from a function
function getOwnerName() public view returns (string memory) {
return ownerName;
}
// Get the age
function getOwnerAge() public view returns (uint8 age){
age = ownerAge;
}
}
pragma solidity >=0.4.24;
contract GlobalVariables {
string public lastCaller = "not-set";
// Demonstrates the use of the ether subdenominations
function etherUnitsTest() public pure returns(bool) {
// True
bool value = (1 ether == 1000 finney);
return value;
}
// Demonstrates the use of the time units
function timeUnits() public view returns (uint) {
uint timeNow = now; //storing current time using now
//returns block time in seconds since 1970
if (timeNow == 1000 days) { // converting 1000 literal to days, using the suffix days
return timeNow;
}
}
// Demonstrates the use of block object
function getBlockInformation() public view returns (uint number, bytes32 hash, address coinbase, uint difficulty) {
number = block.number; // Previous block
hash = blockhash(number - 1); // -1 because excluding current...same as block.blockhash()
// Current block
coinbase = block.coinbase;
difficulty = block.difficulty;
}
// Demonstrates the use of the msg object
function getMsgInformation() public view returns (bytes memory data, bytes4 sig, address sender) {
data = msg.data;
sig = msg.sig;
sender = msg.sender;
}
}
pragma solidity >=0.4.24;
import "./MainContract.sol";
// We have an ContractInterface, that has a function
// sendmoney...but there is no function body
interface ContractInterface {
function sendMoney (uint amount, address _address) external returns (bool);
}
// This is a BaseContract, that has its constructor, and deposit and withdraw functions...
contract BaseContract {
uint public value;
// Anytime base contract has a constructor, we will need to initialize this using
// the derived contracts constructor function
constructor (uint amount) public {
value = amount;
}
function deposit (uint amount) public {
value += amount;
}
function withdraw (uint amount) public {
value -= amount;
}
}
// This shows multiple inheritance
// This will give an error...since baseContract has a constructor that we need to initialize
// contract myContract is baseContract, interfaceContract {
contract InheritanceContract is BaseContract(100), ContractInterface, MainContract(100) {
string public contractName;
constructor (string memory _n) public {
contractName = _n;
}
function getValue () public view returns (uint) {
return value;
}
// Function that allows you to convert an address into a payable address
function _make_payable(address x) internal pure returns (address) {
return address(uint160(x));
}
// This function has to be implemented, since it is unimplemented in the interfaceContract
function sendMoney (uint amount, address _address) public returns (bool) {
_make_payable(_address).transfer(amount);
}
}
pragma solidity >=0.4.24;
contract MainContract {
uint internal value;
constructor (uint amount) public {
value = amount;
}
function deposit (uint amount) public {
value += amount;
}
function withdraw (uint amount) public {
value -= amount;
}
}
pragma solidity >=0.4.24;
contract MappingsContract {
// Creates in Storage
mapping(string => string) relations;
// Add a relation
function addRelation(string memory name, string memory relation) public {
// Store the relation
relations[name] = relation;
}
// Returns a Relation
function getRelation(string memory name) public view returns (string memory){
return relations[name];
}
// Remove the key value pair from the mapping
function removeRelation(string memory name) public {
delete(relations[name]);
}
}
pragma solidity ^0.5.0;
contract Modifiers {
uint public biddingAmount = 100;
modifier minimumBidding {
require(
msg.value >= biddingAmount,
"Only valid bids allowed."
);
_;
}
function bid() payable public minimumBidding returns(bool) {
return true;
}
}
pragma solidity ^0.5.0;
contract Owned {
constructor() public { owner = msg.sender; }
address payable owner;
// This contract only defines a modifier but does not use
// it: it will be used in derived contracts.
// The function body is inserted where the special symbol
// `_;` in the definition of a modifier appears.
// This means that if the owner calls this function, the
// function is executed and otherwise, an exception is
// thrown.
modifier onlyOwner {
require(
msg.sender == owner,
"Only owner can call this function."
);
_;
}
}
contract Mortal is Owned {
// This contract inherits the `onlyOwner` modifier from
// `owned` and applies it to the `close` function, which
// causes that calls to `close` only have an effect if
// they are made by the stored owner.
function close() public onlyOwner {
selfdestruct(owner);
}
}
contract Priced {
// Modifiers can receive arguments:
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}
}
contract Register is Priced, Owned {
mapping (address => bool) registeredAddresses;
uint price;
constructor(uint initialPrice) public { price = initialPrice; }
// It is important to also provide the
// `payable` keyword here, otherwise the function will
// automatically reject all Ether sent to it.
function register() public payable costs(price) {
registeredAddresses[msg.sender] = true;
}
function changePrice(uint _price) public onlyOwner {
price = _price;
}
}
contract Mutex {
bool locked;
modifier noReentrancy() {
require(
!locked,
"Reentrant call."
);
locked = true;
_;
locked = false;
}
/// This function is protected by a mutex, which means that
/// reentrant calls from within `msg.sender.call` cannot call `f` again.
/// The `return 7` statement assigns 7 to the return value but still
/// executes the statement `locked = false` in the modifier.
function f() public noReentrancy returns (uint) {
(bool success,) = msg.sender.call("");
require(success);
return 7;
}
}
pragma solidity >=0.4.24;
contract StringBytes {
// Static byte arrays, Both declarations will create array with 3 byte elements
byte[3] fixedByteArray; // The type byte[] is an array of bytes, but due to padding rules,
//it wastes 31 bytes of space for each element (except in storage).
//It is better to use the bytes type instead.
bytes3 bytes3Array;
// Dynamic bytes arrays
byte[] dynamicByteArray;
bytes bytesArray;
// String variable
string string1 = "testing";
// Converts the bytes type to string type
function conversionTest() public pure returns(string memory) {
bytes memory string2 = "Udacity"; // dynamic memory bytes type
string memory converted = string(string2);
return converted;
}
// Retrieves the element at specified index
// Cannot do with strings, hence converting to bytes
function getElementAt(uint index) public view returns(byte) {
// Convert string to bytes
bytes memory bytesData = bytes(string1);
// Get the element at the specified index
byte element = bytesData[index];
return element;
}
function testing() internal pure {
// uint8 need to be explicitly converted to byte type
// Converting to byte type, since fixedByteArray
// is a byte type array
// Assignment NOT allowed as bytes3 Array is a static Array
// is readonly
// bytes3Array[0] = 1;
// Memory dynamic bytes Array
bytes memory memoryBytes; // dynamic memory array
memoryBytes = new bytes(20); //allocating memory
memoryBytes[0] = "a";
// Push will give compiler error as push() allowed for storage only
//memoryBytes.push('c');
}
function stringExamples() public pure returns(string memory) {
string memory string3 = "abcde"; // string array in memory
return string3;
}
}
pragma solidity >=0.4.24;
contract StringsContract {
function getElementAt(string name, uint index) public pure returns(byte) {
bytes memory bytesData = bytes(name);
return bytesData[index];
}
}
pragma solidity >=0.4.24;
contract StructsContract {
// Family
struct Family {
bytes32 lastName;
uint8 houseNo;
uint16 age;
}
// Creating an array of type family..which is a struct
Family[] myFamily;
// Getting a lastName, and returning complete
// family details
// We cannot compare 2 strings in solidity...
function getName(bytes32 name) public view returns (bytes32, uint8, uint16) {
// Search the array
for(uint8 i = 0; i < myFamily.length; i++){
if(name == myFamily[i].lastName) {
return (myFamily[i].lastName,uint8(myFamily[i].houseNo), myFamily[i].age);
}
}
}
// Structs Cannot be passed as argument so we are passing all elements/attributes of struct as args
function addName(bytes32 _lastName, uint8 _value, uint16 _age) public returns (bool) {
// Declare the struct variable in memory...
Family memory newFamily;
// use the . notation to access members of a struct
newFamily.lastName = _lastName;
newFamily.houseNo = _value;
newFamily.age = _age;
// Push the newFamily struct...into our myFamily array
myFamily.push(newFamily);
return true;
}
}
pragma solidity >=0.4.24;
contract ADRI {
string public constant name = "Adriana Token";
string public constant symbol = "ADRI";
uint8 public constant decimals = 18; // 18 is the most common number of decimal places
uint _totalSupply;
// Balances for each account stored using a mapping
mapping(address => uint256) balances;
// Owner of the account approves the allowance of another account
// Create an allowance mapping
// The first key is the owner of the tokens
// In the 2nd mapping, its says who can spend on your behalf, and how many
// So, we are creating a mapping, where the kep is an address,
// The value is further a mapping of address to amount
mapping(address => mapping (address => uint256)) allowance;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
// Called automatically when contract is initiated
// Sets to total initial _totalSupply, as per the input argument
// Also gives the initial supply to msg.sender...who creates the contract
constructor(uint amount) public {
require(amount > 0, 'Starting amount should be at least 1');
_totalSupply = amount;
balances[msg.sender] = amount;
}
// Returns the total supply of tokens
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
// Get the token balance for account `tokenOwner`
// Anyone can query and find the balance of an address
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// Transfer the balance from owner's account to another account
// Decreases the balance of "from" account
// Increases the balance of "to" account
// Emits Transfer event
function transfer(address to, uint tokens) public returns (bool success) {
require(tokens > 0, 'Transfer amount should be at least 1');
require(tokens <= balances[msg.sender], 'Insufficient funds on from account');
balances[msg.sender] = balances[msg.sender] - tokens;
balances[to] = balances[to] + tokens;
emit Transfer(msg.sender, to, tokens);
return true;
}
// Send amount of tokens from address `from` to address `to`
// The transferFrom method is used to allow contracts to spend
// tokens on your behalf
// Decreases the balance of "from" account
// Decreases the allowance of "msg.sender"
// Increases the balance of "to" account
// Emits Transfer event
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(tokens > 0, 'Transfer amount should be at least 1');
require(tokens <= balances[from], 'Insufficient funds on from account');
require(tokens <= allowance[from][msg.sender], 'Insufficient funds on allowance');
balances[from] = balances[from] - tokens;
allowance[from][msg.sender] = allowance[from][msg.sender] - tokens;
balances[to] = balances[to] + tokens;
emit Transfer(from, to, tokens);
return true;
}
// Approves the `spender` to withdraw from your account, multiple times, up to the `tokens` amount.
// So the msg.sender is approving the spender to spend these many tokens
// from msg.sender's account
// Setting up allowance mapping accordingly
// Emits approval event
function approve(address spender, uint tokens) public returns (bool success) {
require(tokens <= allowance[msg.sender][spender], 'Not allowed to spend token amount');
allowance[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment