Skip to content

Instantly share code, notes, and snippets.

@rise2semi
Created November 8, 2022 17:45
Show Gist options
  • Save rise2semi/935a6f186d48a7d39c52ebc101de683d to your computer and use it in GitHub Desktop.
Save rise2semi/935a6f186d48a7d39c52ebc101de683d to your computer and use it in GitHub Desktop.
Implementing a simple blockchain oracle on Ethereum
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import "./TicketsFeedInterface.sol";
contract Conference {
TicketsFeedInterface ticketsFeed;
constructor(address _ticketsFeed) {
ticketsFeed = TicketsFeedInterface(_ticketsFeed);
}
function checkPrice(uint256 payment, uint256 price) internal pure {
require(payment == price, "Not enouth ETH to buy a ticket");
}
function buyTicket() public payable {
uint256 ticketsSold = ticketsFeed.getData();
if (ticketsSold < 10) { checkPrice(msg.value, 0.01 ether); }
else if (ticketsSold < 100) { checkPrice(msg.value, 0.1 ether); }
else { checkPrice(msg.value, 1 ether); }
// Ticket buying logic
}
}
const ethers = require('ethers');
// JSON of the compiled TicketsFeed contract
const TicketsFeed = require('./TicketsFeed.json');
// Address of the deployed TicketsFeed oracle contract
const TicketsFeedAddress = '0x';
const BLOCKCHAIN_NODE_URL = '';
const PRIVATE_KEY = '0x';
// The logic for calculating the number of sold tickets
function getTicketsSoldNumber() {
return 102;
}
async function main() {
// Get instances of provider and signer to be able to interact with the blockchain
const provider = new ethers.providers.JsonRpcProvider(BLOCKCHAIN_NODE_URL);
const signer = new ethers.Wallet(PRIVATE_KEY, provider);
// Create an instance of deployed oracle contract
const TicketsFeedContract = new ethers.Contract(TicketsFeedAddress, TicketsFeed.abi, signer);
// Retrieve data: it can be an API call, database query, etc.
const ticketsSold = getTicketsSoldNumber();
// Create setData transaction
const sendDataTx = await TicketsFeedContract.setData(ticketsSold);
// Wait for the transaction to be applied
await sendDataTx.wait();
}
main().catch((error) => {
console.error(error);
});
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./TicketsFeedInterface.sol";
contract TicketsFeed is Ownable, TicketsFeedInterface {
uint256 private ticketsSold;
function getData() public view returns (uint256) {
return ticketsSold;
}
function setData(uint256 _ticketsSold) external onlyOwner {
ticketsSold = _ticketsSold;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
interface TicketsFeedInterface {
function getData() external view returns(uint256);
function setData(uint256 ticketsSold) external;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment