Skip to content

Instantly share code, notes, and snippets.

@lyhistory
Created December 28, 2018 03:25
Show Gist options
  • Save lyhistory/a67e4b40f31e294678a1ccf93337fa36 to your computer and use it in GitHub Desktop.
Save lyhistory/a67e4b40f31e294678a1ccf93337fa36 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.17+commit.bdeb9e52.js&optimize=false&gist=
pragma solidity >=0.4.16 <0.6.0;
contract Oracle{
struct Request{
bytes data;
function(uint) external callback;
}
Request[] requests;
event NewRequest(uint);
event Reply(uint);
function query(bytes memory data, function(uint) external callabck)
public {
requests.push(Request(data,callabck));
NewRequest(requests.length-1);
reply(requests.length-1, 100);
}
function reply(uint requestID, uint response) public{
requests[requestID].callback(response);
Reply(requestID);
}
}
contract OracleUser{
Oracle constant oracle = Oracle(0x1c0ec5e2c07b55effe5a2058a3c5b5e581d9dee8); // known contract
uint exchangeRate;
function buySomething() public{
oracle.query("USD", this.oracleResponse);
}
function oracleResponse(uint response) public{
require(msg.sender == address(oracle));
//,"Only oracle can call this.");
exchangeRate = response;
}
function getExchangeRate() public returns(uint){
return exchangeRate;
}
}
//Write your own contracts here. Currently compiles using solc v0.4.15+commit.bbb8e64f.
pragma solidity >=0.4.16 <0.6.0;
contract Selector{
function f() public view returns(bytes4){
return this.f.selector;
}
}
pragma solidity >=0.4.16 <0.6.0;
library ArrayUtils {
// internal functions can be used in internal library functions because
// they will be part of the same code context
function map(uint[] memory self, function (uint) pure returns (uint) f)
internal pure returns (uint[] memory r){
r = new uint[](self.length);
for(uint i=0; i<self.length; i++){
r[i] = f(self[i]);
}
}
function reduce(uint[] memory self, function (uint, uint) pure returns (uint) f)
internal pure returns (uint r){
r = self[0];
for(uint i=1; i<self.length; i++){
r = f(r, self[i]);
}
}
function range(uint length)
internal pure returns (uint[] memory r){
r = new uint[](length);
for(uint i=0; i<r.length; i++){
r[i] = i;
}
}
}
contract Pyramid{
using ArrayUtils for *;
function pyramid(uint l) public pure returns(uint){
return ArrayUtils.range(l).map(square).reduce(sum);
}
function square(uint x) internal pure returns(uint){
return x*x;
}
function sum(uint x, uint y) internal pure returns(uint){
return x+y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment