Skip to content

Commit

Permalink
[tutorial] update rust tutorial with get_resource API
Browse files Browse the repository at this point in the history
  • Loading branch information
msmouse authored and gregnazario committed Apr 27, 2022
1 parent a09b93a commit c6163c2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,24 +85,31 @@ impl RestClient {
}

/// Returns all resources associated with the account
pub fn account_resources(&self, account_address: &str) -> serde_json::Value {
pub fn account_resource(
&self,
account_address: &str,
resource_type: &str,
) -> Option<serde_json::Value> {
let res = reqwest::blocking::get(format!(
"{}/accounts/{}/resources",
self.url, account_address
"{}/accounts/{}/resource/{}",
self.url, account_address, resource_type,
))
.unwrap();

if res.status() != 200 {
if res.status() == 404 {
None
} else if res.status() != 200 {
assert_eq!(
res.status(),
200,
"{} - {}",
res.text().unwrap_or("".to_string()),
account_address,
);
unreachable!()
} else {
Some(res.json().unwrap())
}

res.json().unwrap()
}
//<:!:section_3
//:!:>section_4
Expand Down Expand Up @@ -241,25 +248,10 @@ impl RestClient {
//:!:>section_5
/// Returns the test coin balance associated with the account
pub fn account_balance(&self, account_address: &str) -> Option<u64> {
self.account_resources(account_address)
.as_array()
.unwrap()
.iter()
.find(|x| {
x.get("type")
.map(|v| v.as_str().unwrap() == "0x1::TestCoin::Balance".to_string())
.unwrap_or(false)
})
.and_then(|coin| {
coin.get("data")
.unwrap()
.get("coin")
.unwrap()
.get("value")
.unwrap()
.as_str()
.and_then(|s| s.parse::<u64>().ok())
})
self.account_resource(account_address, "0x1::TestCoin::Balance")
.unwrap()["data"]["coin"]["value"]
.as_str()
.and_then(|s| s.parse::<u64>().ok())
}

/// Transfer a given coin amount from a given Account to the recipient's account address.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,10 @@ impl HelloBlockchainClient {
pub fn get_message(&self, contract_address: &str, account_address: &str) -> Option<String> {
let module_type = format!("0x{}::Message::MessageHolder", contract_address);
self.rest_client
.account_resources(account_address)
.as_array()
.unwrap()
.iter()
.find(|x| {
x.get("type")
.map(|v| v.as_str().unwrap() == module_type)
.unwrap_or(false)
})
.and_then(|coin| {
coin.get("data")
.unwrap()
.get("message")
.unwrap()
.as_str()
.and_then(|s| Some(s.to_string()))
})
.account_resource(account_address, &module_type)
.map(|value| value["data"]["message"].as_str().unwrap().to_string())
}

//<:!:section_2
//:!:>section_3
/// Potentially initialize and set the resource Message::MessageHolder::message
Expand Down

0 comments on commit c6163c2

Please sign in to comment.