How can I call external APIs from the chain then use that data to implement further logic
2 Answers
To add to Sam's post:
It should be noted that Offchain Workers are very often misunderstood. It is not trivial just to write some random http request as part of pallet development and expect it to work. The runtime's state transition function must be completely deterministic, and the use of Offchain Workers introduces non-determinism. So you must go much deeper into what this tool is, what it is not, and how to correctly use it.
From the docs:
Note that the results from off-chain workers are not subject to regular transaction verification. A verification mechanism (e.g. voting, averaging, checking sender signatures, or simply "trusting") should be implemented to determine what information gets into the chain.
The Off-chain worker was introduced directly to solve this problem. You can see a full guide on how to do GET/POST requests here
Some sample code
// We want to keep the offchain worker execution time reasonable, so we set a hard-coded
// deadline to 2s to complete the external call.
// You can also wait indefinitely for the response, however you may still get a timeout
// coming from the host machine.
let deadline = sp_io::offchain::timestamp().add(Duration::from_millis(2_000));
// Initiate an external HTTP GET request.
let request = http::Request::get("https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD");
let pending = request.deadline(deadline).send().map_err(|_| http::Error::IoError)?;
let response = pending.try_wait(deadline).map_err(|_| http::Error::DeadlineReached)??;
// Let's check the status code before we proceed to reading the response.
if response.code != 200 {
log::warn!("Unexpected status code: {}", response.code);
return Err(http::Error::Unknown)
}
-
4It should be noted that Offchain Workers are very often misunderstood. It is not trivial just to write some random http request as part of pallet development and expect it to work. The runtime's state transition function must be completely deterministic, and the use of Offchain Workers introduces non-determinism. So you must go much deeper into what this tool is, what it is not, and how to correctly use it.– Shawn Tabrizi ♦Feb 9, 2022 at 12:40