Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch BTC/USD price with http request of offchain worker #7

Closed
mzxyz opened this issue Oct 24, 2019 · 0 comments
Closed

Fetch BTC/USD price with http request of offchain worker #7

mzxyz opened this issue Oct 24, 2019 · 0 comments
Labels
completed enhancement New feature or request Feature New feature will add to the project

Comments

@mzxyz
Copy link
Contributor

mzxyz commented Oct 24, 2019

  1. Trying to use Http module in substrate/core/offchain
This module is composed of two structs: [`HttpApi`] and [`HttpWorker`]. Calling the [`http`]
function returns a pair of [`HttpApi`] and [`HttpWorker`] that share some state.

The [`HttpApi`] is (indirectly) passed to the runtime when calling an offchain worker, while
the [`HttpWorker`] must be processed in the background. The [`HttpApi`] mimicks the API of the
HTTP-related methods available to offchain workers.

The reason for this design is driven by the fact that HTTP requests should continue running
(i.e.: the socket should continue being processed) in the background even if the runtime isn't
actively calling any function.
  1. Reference for requesting code

  2. Using coinmarketcap api to request BTC/USD price, JS code sample

const rp = require('request-promise');
const requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?id=1',
  headers: {
    'X-CMC_PRO_API_KEY': '*****'
  },
  json: true,
  gzip: true
};

rp(requestOptions).then(response => {
  console.log('API call response:', response.data[1].quote.USD.price);
}).catch((err) => {
  console.log('API call error:', err.message);
});
  1. Temporary solution
 let uri = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?id=1";
        let api_key_value = "*****";
        let api_key = "X-CMC_PRO_API_KEY";

        let id: HttpRequestId = runtime_io::http_request_start("GET", uri, &[0]).unwrap();
	    match runtime_io::http_request_add_header(id, api_key, api_key_value) {
		    Err(_) => { debug("Add request header failed !!!") }
		    Ok(_) => {  debug("Add request header succeed") }
	    };

        let deadline = runtime_io::timestamp().add(Duration::from_millis(10_000));
        match runtime_io::http_response_wait(&[id], Some(deadline))[0] {
			HttpRequestStatus::Finished(200) => {debug("request succeed")},
			_ => {debug("request failed")}
		}

        let buffer_len = 2048;
        let mut buf = Vec::with_capacity(buffer_len as usize);
		buf.resize(buffer_len as usize, 0);
		let res = runtime_io::http_response_read_body(id, &mut buf, Some(deadline));
        match res {
            Ok(read) => { runtime_io::print_utf8(&buf[..read])}
            Err(_) => {debug("parse body failed")}
        }
@mzxyz mzxyz added enhancement New feature or request Feature New feature will add to the project labels Oct 24, 2019
@mzxyz mzxyz mentioned this issue Oct 25, 2019
mzxyz pushed a commit that referenced this issue Oct 26, 2019
@mzxyz mzxyz closed this as completed Feb 22, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
completed enhancement New feature or request Feature New feature will add to the project
Projects
None yet
Development

No branches or pull requests

1 participant