icrc-ledger-agent 0.2.0

Functions for interacting with DFINITY's implementation of the ICRC-1 fungible token standard.
Documentation
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use candid::{Decode, Encode, Nat, Principal};
use ic_agent::{
    Agent,
    hash_tree::{Label, LookupResult},
};
use ic_cbor::CertificateToCbor;
use ic_certification::{
    Certificate, HashTree,
    hash_tree::{HashTreeNode, SubtreeLookupResult},
};
use icrc_ledger_types::icrc::generic_value::Hash;
use icrc_ledger_types::icrc1::account::Account;
use icrc_ledger_types::icrc1::transfer::{BlockIndex, TransferArg, TransferError};
use icrc_ledger_types::icrc2::allowance::{Allowance, AllowanceArgs};
use icrc_ledger_types::icrc2::approve::{ApproveArgs, ApproveError};
use icrc_ledger_types::icrc2::transfer_from::{TransferFromArgs, TransferFromError};
use icrc_ledger_types::icrc3::archive::{ArchivedRange, QueryBlockArchiveFn};
use icrc_ledger_types::icrc3::blocks::ICRC3DataCertificate;
use icrc_ledger_types::icrc3::blocks::{GetBlocksRequest, GetBlocksResponse};
use icrc_ledger_types::{
    icrc::generic_metadata_value::MetadataValue as Value, icrc::metadata_key::MetadataKey,
    icrc3::blocks::BlockRange,
};

#[derive(Debug)]
pub enum Icrc1AgentError {
    AgentError(ic_agent::AgentError),
    CandidError(candid::Error),
    VerificationFailed(String),
}

impl From<ic_agent::AgentError> for Icrc1AgentError {
    fn from(e: ic_agent::AgentError) -> Self {
        Self::AgentError(e)
    }
}

impl From<candid::Error> for Icrc1AgentError {
    fn from(e: candid::Error) -> Self {
        Self::CandidError(e)
    }
}

impl std::fmt::Display for Icrc1AgentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl std::error::Error for Icrc1AgentError {}

pub enum CallMode {
    Query,
    Update,
}

/// An Agent to make calls to a [ICRC-1 Ledger](https://github.com/dfinity/ICRC-1).
///
/// Each query method in this agent takes in input
/// the mode to allow to either use a query call or
/// update calls.
#[derive(Debug, Clone)]
pub struct Icrc1Agent {
    pub agent: Agent,
    pub ledger_canister_id: Principal,
}

impl Icrc1Agent {
    async fn query<S: Into<String>>(
        &self,
        method_name: S,
        arg: &[u8],
    ) -> Result<Vec<u8>, Icrc1AgentError> {
        self.agent
            .query(&self.ledger_canister_id, method_name)
            .with_arg(arg)
            .call()
            .await
            .map_err(Icrc1AgentError::AgentError)
    }

    async fn update<S: Into<String>>(
        &self,
        method_name: S,
        arg: &[u8],
    ) -> Result<Vec<u8>, Icrc1AgentError> {
        self.agent
            .update(&self.ledger_canister_id, method_name)
            .with_arg(arg)
            .call_and_wait()
            .await
            .map_err(Icrc1AgentError::AgentError)
    }

    /// Returns the balance of the account given as argument.
    pub async fn balance_of(
        &self,
        account: Account,
        mode: CallMode,
    ) -> Result<Nat, Icrc1AgentError> {
        Ok(match mode {
            CallMode::Query => Decode!(
                &self.query("icrc1_balance_of", &Encode!(&account)?).await?,
                Nat
            )?,
            CallMode::Update => Decode!(
                &self.update("icrc1_balance_of", &Encode!(&account)?).await?,
                Nat
            )?,
        })
    }

    /// Returns the number of decimals the token uses (e.g., 8 means to divide the token amount by 100000000 to get its user representation).
    pub async fn decimals(&self, mode: CallMode) -> Result<u8, Icrc1AgentError> {
        Ok(match mode {
            CallMode::Query => Decode!(&self.query("icrc1_decimals", &Encode!()?).await?, u8)?,
            CallMode::Update => Decode!(&self.update("icrc1_decimals", &Encode!()?).await?, u8)?,
        })
    }

    /// Returns the name of the token (e.g., MyToken).
    pub async fn name(&self, mode: CallMode) -> Result<String, Icrc1AgentError> {
        Ok(match mode {
            CallMode::Query => Decode!(&self.query("icrc1_name", &Encode!()?).await?, String)?,
            CallMode::Update => Decode!(&self.update("icrc1_name", &Encode!()?).await?, String)?,
        })
    }

    /// Returns the list of metadata entries for this ledger
    pub async fn metadata(
        &self,
        mode: CallMode,
    ) -> Result<Vec<(MetadataKey, Value)>, Icrc1AgentError> {
        Ok(match mode {
            CallMode::Query => Decode!(
                &self.query("icrc1_metadata", &Encode!()?).await?,
                Vec<(MetadataKey, Value)>
            )?,
            CallMode::Update => Decode!(
                &self.update("icrc1_metadata", &Encode!()?).await?,
                Vec<(MetadataKey, Value)>
            )?,
        })
    }

    /// Returns the symbol of the token (e.g., ICP).
    pub async fn symbol(&self, mode: CallMode) -> Result<String, Icrc1AgentError> {
        Ok(match mode {
            CallMode::Query => Decode!(&self.query("icrc1_symbol", &Encode!()?).await?, String)?,
            CallMode::Update => Decode!(&self.update("icrc1_symbol", &Encode!()?).await?, String)?,
        })
    }

    /// Returns the balance of the account given as argument.
    pub async fn total_supply(&self, mode: CallMode) -> Result<Nat, Icrc1AgentError> {
        Ok(match mode {
            CallMode::Query => Decode!(&self.query("icrc1_total_supply", &Encode!()?).await?, Nat)?,
            CallMode::Update => {
                Decode!(&self.update("icrc1_total_supply", &Encode!()?).await?, Nat)?
            }
        })
    }

    // Returns the transfer fee.
    pub async fn fee(&self, mode: CallMode) -> Result<Nat, Icrc1AgentError> {
        Ok(match mode {
            CallMode::Query => Decode!(&self.query("icrc1_fee", &Encode!()?).await?, Nat)?,
            CallMode::Update => Decode!(&self.update("icrc1_fee", &Encode!()?).await?, Nat)?,
        })
    }

    // Returns the minting account if this ledger supports minting and burning tokens.
    pub async fn minting_account(
        &self,
        mode: CallMode,
    ) -> Result<Option<Account>, Icrc1AgentError> {
        Ok(match mode {
            CallMode::Query => Decode!(
                &self.query("icrc1_minting_account", &Encode!()?).await?,
                Option<Account>
            )?,
            CallMode::Update => Decode!(
                &self.update("icrc1_minting_account", &Encode!()?).await?,
                Option<Account>
            )?,
        })
    }

    /// Transfers amount of tokens from the account (caller, from_subaccount) to the account (to_principal, to_subaccount).
    pub async fn transfer(
        &self,
        args: TransferArg,
    ) -> Result<Result<Nat, TransferError>, Icrc1AgentError> {
        Ok(
            Decode!(&self.update("icrc1_transfer", &Encode!(&args)?).await?, Result<Nat, TransferError>)?,
        )
    }

    pub async fn approve(
        &self,
        args: ApproveArgs,
    ) -> Result<Result<Nat, ApproveError>, Icrc1AgentError> {
        Ok(
            Decode!(&self.update("icrc2_approve", &Encode!(&args)?).await?, Result<Nat, ApproveError>)?,
        )
    }

    /// Returns the allowance of the `spender` from the `account`.
    pub async fn allowance(
        &self,
        account: Account,
        spender: Account,
        mode: CallMode,
    ) -> Result<Allowance, Icrc1AgentError> {
        let args = AllowanceArgs { account, spender };
        Ok(match mode {
            CallMode::Query => Decode!(
                &self.query("icrc2_allowance", &Encode!(&args)?).await?,
                Allowance
            )?,
            CallMode::Update => Decode!(
                &self.update("icrc2_allowance", &Encode!(&args)?).await?,
                Allowance
            )?,
        })
    }

    pub async fn transfer_from(
        &self,
        args: TransferFromArgs,
    ) -> Result<Result<Nat, TransferFromError>, Icrc1AgentError> {
        Ok(
            Decode!(&self.update("icrc2_transfer_from", &Encode!(&args)?).await?, Result<Nat, TransferFromError>)?,
        )
    }

    pub async fn get_blocks(
        &self,
        args: GetBlocksRequest,
    ) -> Result<GetBlocksResponse, Icrc1AgentError> {
        Ok(Decode!(
            &self.query("get_blocks", &Encode!(&args)?).await?,
            GetBlocksResponse
        )?)
    }

    pub async fn get_blocks_from_archive(
        &self,
        archived_blocks: ArchivedRange<QueryBlockArchiveFn>,
    ) -> Result<BlockRange, Icrc1AgentError> {
        let args = GetBlocksRequest {
            start: archived_blocks.start,
            length: archived_blocks.length,
        };
        Ok(Decode!(
            &self
                .agent
                .query(
                    &archived_blocks.callback.canister_id,
                    &archived_blocks.callback.method
                )
                .with_arg(Encode!(&args)?)
                .call()
                .await
                .map_err(Icrc1AgentError::AgentError)?,
            BlockRange
        )?)
    }

    pub async fn icrc3_get_tip_certificate(&self) -> Result<ICRC3DataCertificate, Icrc1AgentError> {
        Decode!(
            &self.query("icrc3_get_tip_certificate", &Encode!()?).await?,
            Option<ICRC3DataCertificate>
        )?
        .ok_or(Icrc1AgentError::VerificationFailed(
            "ICRC3DataCertificate not found".to_string(),
        ))
    }

    /// The function performs the following checks:
    /// 1. Check whether the certificate is valid and has authority over ledger_canister_id.
    /// 2. Check whether the certified data at path ["canister", ledger_canister_id, "certified_data"] is equal to root_hash.
    pub async fn verify_root_hash(
        &self,
        certificate: &Certificate,
        root_hash: &Hash,
    ) -> Result<(), Icrc1AgentError> {
        self.agent
            .verify(certificate, self.ledger_canister_id)
            .map_err(Icrc1AgentError::AgentError)?;

        let certified_data_path: [Label<Vec<u8>>; 3] = [
            "canister".into(),
            self.ledger_canister_id.as_slice().into(),
            "certified_data".into(),
        ];

        let cert_hash = match certificate.tree.lookup_path(&certified_data_path) {
            LookupResult::Found(v) => v,
            _ => {
                return Err(Icrc1AgentError::VerificationFailed(format!(
                    "could not find certified_data for canister: {}",
                    self.ledger_canister_id
                )));
            }
        };

        if cert_hash != root_hash {
            return Err(Icrc1AgentError::VerificationFailed(
                "certified_data does not match the root_hash".to_string(),
            ));
        }
        Ok(())
    }

    /// Returns the hash of the last block in the chain and this block's index.
    /// Returns an error if the hash and/or the index do not pass validation against the IC certificate.
    /// Returns None if the blockchain has no blocks and this can be verified by the certificate.
    pub async fn get_certified_chain_tip(
        &self,
    ) -> Result<Option<(Hash, BlockIndex)>, Icrc1AgentError> {
        let ICRC3DataCertificate {
            certificate,
            hash_tree,
        } = self.icrc3_get_tip_certificate().await?;
        let certificate = match Certificate::from_cbor(certificate.as_slice()) {
            Ok(certificate) => certificate,
            Err(e) => {
                return Err(Icrc1AgentError::VerificationFailed(format!(
                    "Unable to deserialize CBOR encoded Certificate: {e}"
                )));
            }
        };
        let hash_tree: HashTree = match ciborium::de::from_reader(hash_tree.as_slice()) {
            Ok(hash_tree) => hash_tree,
            Err(e) => {
                return Err(Icrc1AgentError::VerificationFailed(format!(
                    "Unable to deserialize CBOR encoded hash_tree: {e}"
                )));
            }
        };
        self.verify_root_hash(&certificate, &hash_tree.digest())
            .await?;
        let last_block_index_encoded = match lookup_leaf(&hash_tree, "last_block_index")? {
            Some(last_block_index) => last_block_index,
            None => {
                return Ok(None);
            }
        };

        fn convert_block_hash(block_hash: Vec<u8>) -> Result<Hash, Icrc1AgentError> {
            block_hash
                .clone()
                .try_into()
                .or(Err(Icrc1AgentError::VerificationFailed(format!(
                "DataCertificate last_block_hash bytes: {}, cannot be decoded as last_block_hash",
                hex::encode(block_hash)
            ))))
        }

        // We use two different decoding strategies depending on the presence of the tip_hash in the hash_tree.
        match (
            lookup_leaf(&hash_tree, "tip_hash")?,
            lookup_leaf(&hash_tree, "last_block_hash")?,
        ) {
            (Some(tip_hash), _) => {
                let last_block_index_bytes: [u8; 8] = match last_block_index_encoded
                    .clone()
                    .try_into()
                {
                    Ok(last_block_index_bytes) => last_block_index_bytes,
                    Err(_) => {
                        return Err(Icrc1AgentError::VerificationFailed(format!(
                            "DataCertificate hash_tree bytes: {}, cannot be decoded as last_block_index",
                            hex::encode(last_block_index_encoded)
                        )));
                    }
                };
                let last_block_index = u64::from_be_bytes(last_block_index_bytes);
                Ok(Some((
                    convert_block_hash(tip_hash)?,
                    Nat::from(last_block_index),
                )))
            }
            (_, Some(last_block_hash_vec)) => {
                let mut decode_buf = std::io::Cursor::new(&last_block_index_encoded);
                let last_block_index = leb128::read::unsigned(&mut decode_buf).map_err(|e| {
                    Icrc1AgentError::VerificationFailed(format!(
                        "Unable to decode last_block_index: {e}"
                    ))
                })?;
                Ok(Some((
                    convert_block_hash(last_block_hash_vec)?,
                    Nat::from(last_block_index),
                )))
            }
            _ => Ok(None),
        }
    }
}

fn lookup_leaf(hash_tree: &HashTree, leaf_name: &str) -> Result<Option<Vec<u8>>, Icrc1AgentError> {
    match hash_tree.lookup_subtree([leaf_name.as_bytes()]) {
        SubtreeLookupResult::Found(tree) => match tree.as_ref() {
            HashTreeNode::Leaf(result) => Ok(Some(result.clone())),
            _ => Err(Icrc1AgentError::VerificationFailed(format!(
                "`{leaf_name}` value in the hash_tree should be a leaf"
            ))),
        },
        SubtreeLookupResult::Absent => Ok(None),
        _ => Err(Icrc1AgentError::VerificationFailed(format!(
            "`{leaf_name}` not found in the response hash_tree"
        ))),
    }
}