Skip to main content

📝 Reading Beacon in Contract

This tutorial will guide you in having a contract read data from an active Nodary Beacon.

  • We will inherit DapiReader.sol in our contract in order to be able to call the needed functions to read data from a Nodary Beacon.

  • Import DapiReader.sol and inherit.

// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

import "@api3/airnode-protocol-v1/contracts/dapis/DapiReader.sol";

contract BeaconReaderExample is DapiReader {...}
  • We add _dapiServer in constructor since this is where the Beacons reside.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

import "@api3/airnode-protocol-v1/contracts/dapis/DapiReader.sol";

contract BeaconReaderExample is DapiReader {
constructor(address _dapiServer) DapiReader(_dapiServer) {}

...
}
  • Finally, add the functions readBeaconWithId, readBeaconValueWithId and beaconIdToReaderToWhitelistStatus.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;

import "@api3/airnode-protocol-v1/contracts/dapis/DapiReader.sol";

contract BeaconReaderExample is DapiReader {
constructor(address _dapiServer) DapiReader(_dapiServer) {}

function readBeaconWithId(bytes32 beaconId)
external
view
returns (int224 value, uint256 timestamp)
{
(value, timestamp) = IDapiServer(dapiServer).readDataFeedWithId(
beaconId
);
}

function readBeaconValueWithId(bytes32 beaconId)
external
view
returns (int224 value)
{
value = IDapiServer(dapiServer).readDataFeedValueWithId(beaconId);
}

function beaconIdToReaderToWhitelistStatus(
bytes32 beaconId,
address reader
)
external
view
returns (uint64 expirationTimestamp, uint192 indefiniteWhitelistCount)
{
return
IDapiServer(dapiServer).dataFeedIdToReaderToWhitelistStatus(
beaconId,
reader
);
}

}
Function NameWhat is returns
readBeaconWithIdReturns latest value and timestamp of the Beacon.
readBeaconValueWithIdReturns only the latest value of the Beacon.
beaconIdToReaderToWhitelistStatusReturns the whitelist status of the reader address.
  • Now you can do anything you want with the value you read from beacon.
...

function doSomething() {
int224 value = readBeaconValueWithId(beaconId);
...
}

...

caution

Make sure to whitelist your contract after deploying it. DapiServer addresses can be found here. You can use this guide to whitelist your contract.