Created
September 13, 2018 16:54
-
-
Save Fallenstedt/3b8440c2a9475783771088649de24f03 to your computer and use it in GitHub Desktop.
An example of solidity. Copy and paste code into http://remix.ethereum.org/ and use a JavaScript VM runtime environment.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.4.24; | |
contract HelloWorld { | |
string public message; | |
int256 public myNumber; | |
address public owner; | |
constructor(string initialMessage) public { | |
message = initialMessage; | |
myNumber = 42; | |
owner = msg.sender; | |
} | |
/* | |
* Function modifiers are used to conveniently modify function behavior. | |
* This modifier makes it so a function can only be called by the contract owner | |
*/ | |
modifier onlyowner() { | |
require(msg.sender == owner, "You are not the owner of this contract"); | |
_; | |
} | |
/* | |
* Functions that modify the state of a contract cost gas. | |
*/ | |
function setMessage(string newMessage) public { | |
message = newMessage; | |
} | |
/* | |
* View functions promise to only view state but not modify it. | |
* notice how the modifier is also restricting access to this function. | |
*/ | |
function getHalfOfMyNumber() onlyowner public view returns(int256) { | |
return myNumber / 2; | |
} | |
// Functions can be declared pure in which case they promise not to read from or modify the state. | |
function getTheNumberSeven() public pure returns(int32) { | |
return 7; | |
} | |
// Functions that are payable hold value in "msg.value". The contract then holds the balance | |
function sendContractSomeMoney() public payable { | |
require(msg.value > 0, "You must pay more than 0 wei"); | |
} | |
// We can read the balance of a contract and return it in Wei | |
function contractBalance() public view returns (uint256) { | |
uint256 balance = address(this).balance; | |
return balance; | |
} | |
// We can take money out of the contract too. | |
function recieveContractMoney() public payable { | |
uint256 balance = address(this).balance; | |
require(balance > 0, "Contract will not send you 0 wei"); | |
msg.sender.transfer(balance); | |
} | |
// This is how you lose money | |
function badSendMoney() public payable { | |
uint256 balance = address(this).balance; | |
require(balance > 0, "Contract has no money"); | |
address badAddress = 0x123abc; | |
badAddress.transfer(balance); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment