1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use ic_kit::ic::call;
use ic_kit::{Principal, RejectionCode};

use crate::root::RootBucket;
use cap_common::{
    GetIndexCanistersResponse, GetTransactionResponse, GetTransactionsArg, GetTransactionsResponse,
    GetUserTransactionsArg, WithIdArg, WithWitnessArg,
};

/// A contract-specific bucket canister.
///
/// A bucket canister implements storage for its parent contract. The total storage for a given
/// contract is created using multiple bucket canisters, which are interconnected using a root bucket
/// and router system. Querying buckets also features pagination.
#[derive(Copy, Clone)]
pub struct Bucket(pub(crate) Principal);

impl Bucket {
    /// Returns the list of canisters which have different pages of data.
    pub async fn get_next_canisters(&self) -> Result<Vec<Bucket>, (RejectionCode, String)> {
        let result: (GetIndexCanistersResponse,) = call(
            self.0,
            "get_next_canisters",
            (WithWitnessArg { witness: false },),
        )
        .await?;

        Ok(result
            .0
            .canisters
            .iter()
            .map(|canister| Bucket(*canister))
            .collect())
    }

    /// Returns the transaction corresponding to the passed transaction ID.
    pub async fn get_transaction(
        &self,
        id: u64,
    ) -> Result<GetTransactionResponse, (RejectionCode, String)> {
        let result: (GetTransactionResponse,) = call(
            self.0,
            "get_transaction",
            (WithIdArg { id, witness: false },),
        )
        .await?;

        Ok(result.0)
    }

    /// Returns all of the transactions for this contract.
    pub async fn get_transactions(
        &self,
        page: Option<u32>,
    ) -> Result<GetTransactionsResponse, (RejectionCode, String)> {
        let result: (GetTransactionsResponse,) = call(
            self.0,
            "get_transactions",
            (GetTransactionsArg {
                page,
                witness: false,
            },),
        )
        .await?;

        Ok(result.0)
    }

    /// Returns all of the transactions associated with the given user.
    pub async fn get_user_transactions(
        &self,
        user: Principal,
        page: Option<u32>,
    ) -> Result<GetTransactionsResponse, (RejectionCode, String)> {
        let result: (GetTransactionsResponse,) = call(
            self.0,
            "get_user_transactions",
            (GetUserTransactionsArg {
                user,
                page,
                witness: false,
            },),
        )
        .await?;

        Ok(result.0)
    }
}

impl From<RootBucket> for Bucket {
    fn from(root: RootBucket) -> Self {
        Bucket(root.0)
    }
}