metabox_sdk/metabox/
mod.rs

1use garcon::Delay;
2use ic_agent::Agent;
3use ic_agent::identity::Secp256k1Identity;
4use ic_agent::agent::http_transport::ReqwestHttpReplicaV2Transport;
5use candid::{Decode, Encode, Principal};
6mod metabox_did;
7use metabox_did::{CreateBoxArgs, CreateBoxResult, BoxMetadata, BoxInfo};
8use crate::metabox::metabox_did::BoxType;
9
10static MetaBox_CANISTER_ID_TEXT: &'static str = "zbzr7-xyaaa-aaaan-qadeq-cai";
11
12pub async fn create_data_box(pem_identity_path: &str, icp_amount: u64, box_name: String, is_private: bool) -> CreateBoxResult{
13    let canister_id = Principal::from_text(MetaBox_CANISTER_ID_TEXT).unwrap();
14    let agent = build_agent(pem_identity_path);
15    let user_principal = agent.get_principal().unwrap();
16    let args = CreateBoxArgs {
17        metadata: BoxMetadata {
18            is_private: is_private.clone(),
19            box_name: box_name.clone(),
20            box_type: BoxType::data_box,
21        },
22        install_args: Encode!(&user_principal).expect("encode install args failed"),
23        icp_amount: icp_amount.clone(),
24    };
25    let response_blob = agent
26        .update(&canister_id, "createBox")
27        .with_arg(Encode!(&args).expect("encode piece failed"))
28        .call_and_wait(get_waiter())
29        .await
30        .expect("response error");
31    Decode!(&response_blob, CreateBoxResult).unwrap()
32}
33
34pub async fn get_boxes(pem_identity_path: &str, who: candid::Principal) -> Vec<BoxInfo> {
35    let canister_id = Principal::from_text(MetaBox_CANISTER_ID_TEXT).unwrap();
36    let response_blob = build_agent(pem_identity_path)
37        .query(&canister_id, "getBoxes")
38        .with_arg(Encode!(&who).expect("encode piece failed"))
39        .call()
40        .await
41        .expect("response error");
42    Decode!(&response_blob, Vec<BoxInfo>).unwrap()
43}
44
45fn get_waiter() -> Delay {
46    let waiter = garcon::Delay::builder()
47        .throttle(std::time::Duration::from_millis(500))
48        .timeout(std::time::Duration::from_secs(60 * 5))
49        .build();
50    waiter
51}
52
53fn build_agent(pem_identity_path: &str) -> Agent {
54    let url = "https://ic0.app".to_string();
55    let identity = Secp256k1Identity::from_pem_file(String::from(pem_identity_path)).unwrap();
56    let transport = ReqwestHttpReplicaV2Transport::create(url).expect("transport error");
57    let agent = Agent::builder()
58        .with_transport(transport)
59        .with_identity(identity)
60        .build()
61        .expect("build agent error");
62    agent
63}