✅Getting Started
Overview
What is a LINK token?
The LINK token is an ERC677 token that inherits functionality from the ERC20 token standard and allows token transfers to contain a data payload. It is used to pay node operators for retrieving data for smart contracts and also for deposits placed by node operators as required by contract creators.
Any wallet that handles ERC20 tokens can store LINK tokens. The ERC677 token standard that the LINK token implements still retains all functionality of ERC20 tokens.
What are oracles?
Oracles provide a bridge between the real-world and on-chain smart contracts by being a source of data that smart contracts can rely on, and act upon.
Oracles play a critical role in facilitating the full potential of smart contract utility. Without a reliable connection to real-world conditions, smart contracts cannot effectively serve the real-world.
How do smart contracts use oracles?
Oracles are most popularly used with Data Feeds. DeFi platforms like AAVE and Synthetix use Chainlink data feed oracles to obtain accurate real-time asset prices in their smart contracts.
Chainlink data feeds are sources of data aggregated from many independent Chainlink node operators. Each data feed has an on-chain address and functions that enable contracts to read from that address. For example, the ETH / USD feed.
Smart contracts also use oracles to get other capabilities on-chain:
Generate Verifiable Random Numbers (VRF): Use Chainlink VRF to consume randomness in your smart contracts.
Call External APIs (Any API): Request & Receive data from any API using the Chainlink contract library.
Automate Smart Contract Functions (Automation): Automating smart contract functions and regular contract maintenance.
Consuming Data Feeds
When you connect a smart contract to real-world services or off-chain data, you create a hybrid smart contract. For example, you can use Chainlink Data Feeds to connect your smart contracts to asset pricing data like the ETH / USD feed. These data feeds use the data aggregated from many independent Chainlink node operators. Each price feed has an on-chain address and functions that enable contracts to read pricing data from that address.
The code for reading Data Feeds is the same across all EVM-compatible blockchains and Data Feed types. You choose different types of feeds for different uses, but the request and response format are the same.
Examine the sample contract
This example contract obtains the latest price answer from the BTC / USD feed on the Sepolia testnet, but you can modify it to read any of the different Types of Data Feeds.
The contract has the following components:
The
import
line imports an interface namedAggregatorV3Interface
. Interfaces define functions without their implementation, which leaves inheriting contracts to define the actual implementation themselves. In this case,AggregatorV3Interface
defines that all v3 Aggregators have the functionlatestRoundData
. You can see the complete code for theAggregatorV3Interface
on GitHub.The
constructor() {}
initializes an interface object namedpriceFeed
that usesAggregatorV3Interface
and connects specifically to a proxy aggregator contract that is already deployed at0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43
. The interface allows your contract to run functions on that deployed aggregator contract.The
getLatestPrice()
function calls yourpriceFeed
object and runs thelatestRoundData()
function. When you deploy the contract, it initializes thepriceFeed
object to point to the aggregator at0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43
, which is the proxy address for the Sepolia BTC / USD data feed. Your contract connects to that address and executes the function. The aggregator connects with several oracle nodes and aggregates the pricing data from those nodes. The response from the aggregator includes several variables, butgetLatestPrice()
returns only theprice
variable.
Get Random Numbers
In this guide, you will learn about generating randomness on blockchains. This includes learning how to implement a Request and Receive cycle with Chainlink oracles and how to consume random numbers with Chainlink VRF in smart contracts.
How is randomness generated on blockchains? What is Chainlink VRF?
Randomness is very difficult to generate on blockchains. This is because every node on the blockchain must come to the same conclusion and form a consensus. Even though random numbers are versatile and useful in a variety of blockchain applications, they cannot be generated natively in smart contracts. The solution to this issue is Chainlink VRF, also known as Chainlink Verifiable Random Function.
What is the Request and Receive cycle?
The previous guide explained how to consume Chainlink Data Feeds, which consist of reference data posted on-chain by oracles. This data is stored in a contract and can be referenced by consumers until the oracle updates the data again.
Randomness, on the other hand, cannot be reference data. If the result of randomness is stored on-chain, any actor could retrieve the value and predict the outcome. Instead, randomness must be requested from an oracle, which generates a number and a cryptographic proof. Then, the oracle returns that result to the contract that requested it. This sequence is known as the Request and Receive cycle.
What is the payment process for generating a random number?
VRF requests receive funding from subscription accounts. The Subscription Manager lets you create an account and pre-pay for VRF requests, so that funding of all your application requests are managed in a single location. To learn more about VRF requests funding, see Subscriptions limits.
How can I use Chainlink VRF?
To see a basic implementation of Chainlink VRF, see Get a Random Number. In this section, you will create an application that uses Chainlink VRF to generate randomness. The contract used in this application will have a Game of Thrones theme.
The contract will request randomness from Chainlink VRF. The result of the randomness will transform into a number between 1 and 20, mimicking the rolling of a 20 sided die. Each number represents a Game of Thrones house. If the dice land on the value 1, the user is assigned house Targaryan, 2 for Lannister, and so on. A full list of houses can be found here.
When rolling the dice, it will accept an address
variable to track which address is assigned to each house.
The contract will have the following functions:
rollDice
: This submits a randomness request to Chainlink VRFfulfillRandomWords
: The function that the Oracle uses to send the result backhouse
: To see the assigned house of an address
Note: to jump straight to the entire implementation, you can open the VRFD20.sol contract in remix.
Create and fund a subscription
Chainlink VRF requests receive funding from subscription accounts. The Subscription Manager lets you create an account and pre-pay your use of Chainlink VRF requests. For this example, create a new subscription on the Sepolia testnet as explained here.
Importing VRFConsumerBaseV2
and VRFCoordinatorV2Interface
VRFConsumerBaseV2
and VRFCoordinatorV2Interface
Chainlink maintains a library of contracts that make consuming data from oracles easier. For Chainlink VRF, you will use:
VRFConsumerBaseV2
that must be imported and extended from the contract that you create.VRFCoordinatorV2Interface
that must be imported to communicate with the VRF coordinator.
Contract variables
This example is adapted for Sepolia testnet but you can change the configuration and make it run for any supported network.
uint64 s_subscriptionId
: The subscription ID that this contract uses for funding requests. Initialized in theconstructor
.address vrfCoordinator
: The address of the Chainlink VRF Coordinator contract.bytes32 s_keyHash
: The gas lane key hash value, which is the maximum gas price you are willing to pay for a request in wei. It functions as an ID of the off-chain VRF job that runs in response to requests.uint32 callbackGasLimit
: The limit for how much gas to use for the callback request to your contract’sfulfillRandomWords
function. It must be less than themaxGasLimit
on the coordinator contract. Adjust this value for larger requests depending on how yourfulfillRandomWords
function processes and stores the received random values. If yourcallbackGasLimit
is not sufficient, the callback will fail and your subscription is still charged for the work done to generate your requested random values.uint16 requestConfirmations
: How many confirmations the Chainlink node should wait before responding. The longer the node waits, the more secure the random value is. It must be greater than theminimumRequestBlockConfirmations
limit on the coordinator contract.uint32 numWords
: How many random values to request. If you can use several random values in a single callback, you can reduce the amount of gas that you spend per random value. In this example, each transaction requests one random value.
To keep track of addresses that roll the dice, the contract uses mappings. Mappings are unique key-value pair data structures similar to hash tables in Java.
s_rollers
stores a mapping between therequestID
(returned when a request is made), and the address of the roller. This is so the contract can keep track of who to assign the result to when it comes back.s_results
stores the roller and the result of the dice roll.
Initializing the contract
The coordinator and subscription id must be initialized in the constructor
of the contract. To use VRFConsumerBaseV2
properly, you must also pass the VRF coordinator address into its constructor. The address that creates the smart contract is the owner of the contract. the modifier onlyOwner()
checks that only the owner is allowed to do some tasks.
rollDice
function
rollDice
functionThe rollDice
function will complete the following tasks:
Check if the roller has already rolled since each roller can only ever be assigned to a single house.
Request randomness by calling the VRF coordinator.
Store the
requestId
and roller address.Emit an event to signal that the dice is rolling.
You must add a ROLL_IN_PROGRESS
constant to signify that the dice has been rolled but the result is not yet returned. Also add a DiceRolled
event to the contract.
Only the owner of the contract can execute the rollDice
function.
fulfillRandomWords
function
fulfillRandomWords
functionfulfillRandomWords
is a special function defined within the VRFConsumerBaseV2
contract that our contract extends from. The coordinator sends the result of our generated randomWords
back to fulfillRandomWords
. You will implement some functionality here to deal with the result:
Change the result to a number between 1 and 20 inclusively. Note that
randomWords
is an array that could contain several random values. In this example, request 1 random value.Assign the transformed value to the address in the
s_results
mapping variable.Emit a
DiceLanded
event.
house
function
house
functionFinally, the house
function returns the house of an address.
To have a list of the house's names, create the getHouseName
function that is called in the house
function.
You have now completed all necessary functions to generate randomness and assign the user a Game of Thrones house. We’ve added a few helper functions in there to make using the contract easier and more flexible. You can deploy and interact with the complete contract in Remix.
Last updated