title | actions | requireLogin | material | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
The Callback Function |
|
true |
|
The caller contract logic is almost complete, but there's one more thing you should take care of.
As mentioned in the previous chapter, calling the Binance public API is an asynchronous operation. Thus, the caller smart contract must provide a callback
function which the oracle should call at a later time, namely when the ETH price is fetched.
Here's how the callback
function works:
-
First, you would want to make sure that the function can only be called for a valid
id
. For that, you'll use arequire
statement.Simply put, a
require
statement throws an error and stops the execution of the function if a condition isfalse
.Let's look at an example from the Solidity official documentation:
require(msg.sender == chairperson, "Only chairperson can give right to vote.");
The first parameter evaluates to
true
orfalse
. If it'sfalse
, the function execution will stop and the smart contract will throw an error- "Only chairperson can give right to vote." -
Once you know that the
id
is valid, you can go ahead and remove it from themyRequests
mapping.Note: To remove an element from a mapping, you can use something like the following:
delete myMapping[key]
; -
Lastly, your function should fire an event to let the front-end know the price was successfully updated.
We've gone ahead and declared a public
function called callback
. It takes two arguments of type uint256
: _ethPrice
and _id
.
-
After the line that declares your smart contract, create a
uint256
variable calledethPrice
. Let's make itprivate
and don't assign it to anything yet. -
Create an event called
PriceUpdatedEvent
. It takes two parameters:ethPrice
andid
. Both parameters are of typeuint256
.
Next, let's fill in the body of the callback
function.
-
The function should first check to make sure
myRequests[id]
istrue
. Use arequire
statement to do this. The first parameter should bemyRequests[id]
and the second parameter should be "This request is not in my pending list." -
Next, save the new ETH price (the one that comes from the function parameters) into the
ethPrice
variable. -
The function should then call
delete
to remove the currentid
from themyRequests
mapping. -
Lastly, let's fire the
PriceUpdatedEvent
. The arguments should come from the function arguments.
This was a lot of logic to implement, but there's still something you've left out. Can you guess what?
Give it a thought before moving to the next chapter.