Skip to content

Instantly share code, notes, and snippets.

@PatrickAlphaC
Last active May 12, 2020 20:28
Show Gist options
  • Save PatrickAlphaC/7239ab960831b505681b9446b76e68b3 to your computer and use it in GitHub Desktop.
Save PatrickAlphaC/7239ab960831b505681b9446b76e68b3 to your computer and use it in GitHub Desktop.
The simplest way to make an API call in solidity
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract GetData is ChainlinkClient {
uint256 public currentPrice;
address public owner;
// The address of an oracle
address ORACLE = 0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
// The address of the http get job
string constant JOB = "c179a8180e034cf5a341488406c32827";
// When you call a job, you have to make a payment in LINK token
// So be sure to send this contract's address some LINK
uint256 constant private ORACLE_PAYMENT = 1 * LINK;
// The constructor
constructor() public {
setPublicChainlinkToken();
owner = msg.sender;
}
// This is where the magic happens
// And it will be the big orange button on the side of remix
function requestEthereumPrice()
public
onlyOwner
{
// We build the API call to send to the node
// noting that the result will come back through the `fulfill` method
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(JOB), address(this), this.fulfill.selector);
// Here is where we enter the URL
req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
// The response is in JSON, and the value is in the USD keyword, so we add this path
req.add("path", "USD");
// Solidity can't handle decimals, so we have to multiply by 100 to get a whole number
req.addInt("times", 100);
// Then we send the request!
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
// When the URL finishes, the response is routed to this function
function fulfill(bytes32 _requestId, uint256 _price)
public
recordChainlinkFulfillment(_requestId)
{
currentPrice = _price;
}
// Don't worry about this for now
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// A helper funciton to make the string a bytes32
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly { // solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
// Allows the owner to withdraw their LINK on this contract
function withdrawLink() external onlyOwner() {
LinkTokenInterface _link = LinkTokenInterface(chainlinkTokenAddress());
require(_link.transfer(msg.sender, _link.balanceOf(address(this))), "Unable to transfer");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment