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

🐛 fixed outdated instructions #2345

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -441,22 +441,15 @@ rustup target add wasm32-unknown-unknown
//This includes all methods and types needed
use ic_cdk::api::management_canister::http_request::{
http_request, CanisterHttpRequestArgument, HttpHeader, HttpMethod, HttpResponse, TransformArgs,
TransformContext,
TransformContext, TransformFunc,
};

use ic_cdk_macros::{self, query, update};
use serde::{Serialize, Deserialize};
use serde_json::{self, Value};
use ic_cdk_macros::{query, update};

// This struct is legacy code and is not really used in the code.
#[derive(Serialize, Deserialize)]
struct Context {
bucket_start_time_index: usize,
closing_price_index: usize,
}

//Update method using the HTTPS outcalls feature
#[ic_cdk::update]
#[update]
async fn get_icp_usd_exchange() -> String {
//2. SETUP ARGUMENTS FOR HTTP GET request

Expand All @@ -467,10 +460,7 @@ async fn get_icp_usd_exchange() -> String {
let host = "api.pro.coinbase.com";
let url = format!(
"https://{}/products/ICP-USD/candles?start={}&end={}&granularity={}",
host,
start_timestamp.to_string(),
start_timestamp.to_string(),
seconds_of_time.to_string()
host, start_timestamp, start_timestamp, seconds_of_time
);

// 2.2 prepare headers for the system http_request call
Expand All @@ -486,31 +476,30 @@ async fn get_icp_usd_exchange() -> String {
},
];


// This struct is legacy code and is not really used in the code. Need to be removed in the future
// The "TransformContext" function does need a CONTEXT parameter, but this implementation is not necessary
// the TransformContext(transform, context) below accepts this "context", but it does nothing with it in this implementation.
// bucket_start_time_index and closing_price_index are meaninglesss
let context = Context {
bucket_start_time_index: 0,
closing_price_index: 4,
};

//note "CanisterHttpRequestArgument" and "HttpMethod" are declared in line 4
let request = CanisterHttpRequestArgument {
url: url.to_string(),
method: HttpMethod::GET,
body: None, //optional for request
max_response_bytes: None, //optional for request
transform: Some(TransformContext::new(transform, serde_json::to_vec(&context).unwrap())),
transform: Some(TransformContext {
// The "method" parameter needs to the same name as the function name of your transform function
function: TransformFunc(candid::Func {
principal: ic_cdk::api::id(),
method: "transform".to_string(),
}),
// The "TransformContext" function does need a context parameter, it can be empty
context: vec![],
}),
headers: request_headers,
};

//3. MAKE HTTPS REQUEST AND WAIT FOR RESPONSE

//Note: in Rust, `http_request()` already sends the cycles needed
//so no need for explicit Cycles.add() as in Motoko
match http_request(request).await {
//Note: in Rust, `http_request()` needs to pass cycles if you are using ic_cdk: ^0.9.0
let cycles = 230_949_972_000;

match http_request(request, cycles).await {
//4. DECODE AND RETURN THE RESPONSE

//See:https://docs.rs/ic-cdk/latest/ic_cdk/api/management_canister/http_request/struct.HttpResponse.html
Expand All @@ -526,8 +515,6 @@ async fn get_icp_usd_exchange() -> String {
//To do this:
// 1. Call `String::from_utf8()` on response.body
// 3. You use a switch to explicitly call out both cases of decoding the Blob into ?Text
let str_body = String::from_utf8(response.body)
.expect("Transformed response is not UTF-8 encoded.");

//The API response will looks like this:

Expand All @@ -545,9 +532,8 @@ async fn get_icp_usd_exchange() -> String {
// ],
// ]


//Return the body as a string and end the method
str_body
String::from_utf8(response.body).expect("Transformed response is not UTF-8 encoded.")
}
Err((r, m)) => {
let message =
Expand All @@ -559,11 +545,9 @@ async fn get_icp_usd_exchange() -> String {
}
}


// Strips all data that is not needed from the original response.
#[query]
fn transform(raw: TransformArgs) -> HttpResponse {

let headers = vec![
HttpHeader {
name: "Content-Security-Policy".to_string(),
Expand All @@ -590,17 +574,14 @@ fn transform(raw: TransformArgs) -> HttpResponse {
value: "nosniff".to_string(),
},
];


let mut res = HttpResponse {
status: raw.response.status.clone(),
body: raw.response.body.clone(),
headers,
..Default::default()
};

if res.status == 200 {

if res.status == 200u64 {
res.body = raw.response.body;
} else {
ic_cdk::api::print(format!("Received an error from coinbase: err = {:?}", raw));
Expand Down Expand Up @@ -637,12 +618,9 @@ edition = "2021"
crate-type = ["cdylib"]

[dependencies]
candid = "0.8.2"
ic-cdk = "0.6.0"
ic-cdk-macros = "0.6.0"
serde = "1.0.152"
serde_json = "1.0.93"
serde_bytes = "0.11.9"
candid = "0.10.2"
ic-cdk = "0.12.1"
ic-cdk-macros = "0.8.4"
```

- #### Step 5: Test the dapp locally.
Expand Down