ic-query 0.6.5

Internet Computer query library for NNS, SNS, ICRC, and related public network metadata
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Module: icrc::ledger
//!
//! Responsibility: shared live ICRC ledger wire types, query helpers, and metadata conversion.
//! Does not own: CLI parsing, command-specific reports, SNS lookup, or text rendering.
//! Boundary: keeps reusable ICRC ledger mechanics independent from report DTOs.

use crate::hex::hex_bytes;
use candid::{CandidType, Deserialize, Encode, Int, Nat, Principal, types::reference::Func};
use ic_agent::Agent;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;

const ICRC_LOGO_METADATA_KEY: &str = "icrc1:logo";

///
/// IcrcLedgerError
///
/// Error adapter implemented by command families that issue ICRC ledger calls.
///

pub trait IcrcLedgerError: Sized {
    fn agent_build(endpoint: &str, reason: String) -> Self;

    fn invalid_principal(field: &'static str, reason: String) -> Self;

    fn candid_encode(message: &'static str, reason: String) -> Self;

    fn agent_call(method: &'static str, reason: String) -> Self;

    fn candid_decode(message: &'static str, reason: String) -> Self;
}

///
/// IcrcLedgerTokenMetadata
///
/// Raw ICRC-1 token metadata fetched from one ledger canister.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcrcLedgerTokenMetadata {
    pub token_name: String,
    pub token_symbol: String,
    pub decimals: u8,
    pub transfer_fee: String,
    pub total_supply: String,
    pub minting_account_owner: Option<String>,
    pub minting_account_subaccount_hex: Option<String>,
    pub supported_standards: Vec<IcrcLedgerStandardRow>,
    pub metadata: Vec<IcrcLedgerMetadataRow>,
}

///
/// IcrcLedgerStandardRow
///
/// Generic row for one ICRC standard supported by a ledger.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcrcLedgerStandardRow {
    pub name: String,
    pub url: String,
}

///
/// IcrcLedgerMetadataRow
///
/// Generic row for one ICRC ledger metadata key/value pair.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IcrcLedgerMetadataRow {
    pub key: String,
    pub value_type: String,
    pub value: JsonValue,
}

///
/// IcrcAccount
///
/// Candid ICRC account argument used by ledger balance calls.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct IcrcAccount {
    pub owner: Principal,
    pub subaccount: Option<Vec<u8>>,
}

///
/// IcrcMetadataValue
///
/// Candid ICRC metadata value returned by ledgers.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub enum IcrcMetadataValue {
    Nat(Nat),
    Int(Int),
    Text(String),
    Blob(Vec<u8>),
}

///
/// IcrcAllowanceArgs
///
/// Candid ICRC-2 allowance request argument.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct IcrcAllowanceArgs {
    pub account: IcrcAccount,
    pub spender: IcrcAccount,
}

///
/// IcrcAllowance
///
/// Candid ICRC-2 allowance response.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct IcrcAllowance {
    pub allowance: Nat,
    pub expires_at: Option<u64>,
}

///
/// GetIndexPrincipalResult
///
/// Candid result returned by ICRC-106 index discovery.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub enum GetIndexPrincipalResult {
    Ok(Principal),
    Err(GetIndexPrincipalError),
}

///
/// GetIndexPrincipalError
///
/// Candid error returned by ICRC-106 index discovery.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub enum GetIndexPrincipalError {
    IndexPrincipalNotSet,
    GenericError {
        error_code: Nat,
        description: String,
    },
}

///
/// Icrc3Value
///
/// Candid ICRC-3 generic block value.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) enum Icrc3Value {
    Blob(Vec<u8>),
    Text(String),
    Nat(Nat),
    Int(Int),
    Array(Vec<Self>),
    Map(BTreeMap<String, Self>),
}

///
/// Icrc3GetBlocksRequest
///
/// Candid ICRC-3 block range request.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3GetBlocksRequest {
    pub(in crate::icrc) start: Nat,
    pub(in crate::icrc) length: Nat,
}

///
/// Icrc3BlockWithId
///
/// Candid ICRC-3 block paired with its block log id.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3BlockWithId {
    pub(in crate::icrc) id: Nat,
    pub(in crate::icrc) block: Icrc3Value,
}

///
/// Icrc3ArchiveCallback
///
/// Candid ICRC-3 archive callback function reference.
///
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3ArchiveCallback(pub(in crate::icrc) Func);

impl CandidType for Icrc3ArchiveCallback {
    fn _ty() -> candid::types::Type {
        candid::func!((Vec<Icrc3GetBlocksRequest>) -> (Icrc3GetBlocksResult) query)
    }

    fn idl_serialize<S>(&self, serializer: S) -> Result<(), S::Error>
    where
        S: candid::types::Serializer,
    {
        self.0.idl_serialize(serializer)
    }
}

///
/// Icrc3ArchivedBlocks
///
/// Candid ICRC-3 archive callback and ranges returned for non-local blocks.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3ArchivedBlocks {
    pub(in crate::icrc) args: Vec<Icrc3GetBlocksRequest>,
    pub(in crate::icrc) callback: Icrc3ArchiveCallback,
}

///
/// Icrc3GetBlocksResult
///
/// Candid ICRC-3 block range response.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3GetBlocksResult {
    pub(in crate::icrc) log_length: Nat,
    pub(in crate::icrc) blocks: Vec<Icrc3BlockWithId>,
    pub(in crate::icrc) archived_blocks: Vec<Icrc3ArchivedBlocks>,
}

///
/// Icrc3GetArchivesArgs
///
/// Candid ICRC-3 archive discovery request.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3GetArchivesArgs {
    pub(in crate::icrc) from: Option<Principal>,
}

///
/// Icrc3ArchiveInfo
///
/// Candid ICRC-3 archive range information.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3ArchiveInfo {
    pub(in crate::icrc) canister_id: Principal,
    pub(in crate::icrc) start: Nat,
    pub(in crate::icrc) end: Nat,
}

///
/// Icrc3SupportedBlockType
///
/// Candid ICRC-3 supported block type row.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3SupportedBlockType {
    pub(in crate::icrc) block_type: String,
    pub(in crate::icrc) url: String,
}

///
/// Icrc3DataCertificate
///
/// Candid ICRC-3 data certificate for the certified ledger tip.
///
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub(in crate::icrc) struct Icrc3DataCertificate {
    pub(in crate::icrc) certificate: Vec<u8>,
    pub(in crate::icrc) hash_tree: Vec<u8>,
}

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
struct IcrcSupportedStandard {
    name: String,
    url: String,
}

pub fn ic_agent<E>(endpoint: &str) -> Result<Agent, E>
where
    E: IcrcLedgerError,
{
    Agent::builder()
        .with_url(endpoint)
        .build()
        .map_err(|err| E::agent_build(endpoint, err.to_string()))
}

pub fn principal_from_text<E>(value: &str, field: &'static str) -> Result<Principal, E>
where
    E: IcrcLedgerError,
{
    Principal::from_text(value).map_err(|err| E::invalid_principal(field, err.to_string()))
}

pub async fn fetch_icrc1_token_metadata<E>(
    agent: &Agent,
    ledger_canister: &Principal,
) -> Result<IcrcLedgerTokenMetadata, E>
where
    E: IcrcLedgerError,
{
    let token_name = query_ledger(agent, ledger_canister, "icrc1_name").await?;
    let token_symbol = query_ledger(agent, ledger_canister, "icrc1_symbol").await?;
    let decimals = query_ledger(agent, ledger_canister, "icrc1_decimals").await?;
    let transfer_fee: Nat = query_ledger(agent, ledger_canister, "icrc1_fee").await?;
    let total_supply: Nat = query_ledger(agent, ledger_canister, "icrc1_total_supply").await?;
    let minting_account: Option<IcrcAccount> =
        query_ledger(agent, ledger_canister, "icrc1_minting_account").await?;
    let supported_standards = fetch_icrc_supported_standards(agent, ledger_canister).await?;
    let metadata: Vec<(String, IcrcMetadataValue)> =
        query_ledger(agent, ledger_canister, "icrc1_metadata").await?;

    Ok(IcrcLedgerTokenMetadata {
        token_name,
        token_symbol,
        decimals,
        transfer_fee: transfer_fee.to_string(),
        total_supply: total_supply.to_string(),
        minting_account_owner: minting_account
            .as_ref()
            .map(|account| account.owner.to_text()),
        minting_account_subaccount_hex: minting_account
            .as_ref()
            .and_then(|account| account.subaccount.as_deref())
            .map(hex_bytes),
        supported_standards,
        metadata: metadata
            .into_iter()
            .map(|(key, value)| metadata_row(key, value))
            .collect(),
    })
}

pub async fn fetch_icrc_supported_standards<E>(
    agent: &Agent,
    ledger_canister: &Principal,
) -> Result<Vec<IcrcLedgerStandardRow>, E>
where
    E: IcrcLedgerError,
{
    let supported_standards: Vec<IcrcSupportedStandard> =
        query_ledger(agent, ledger_canister, "icrc1_supported_standards").await?;
    Ok(supported_standards
        .into_iter()
        .map(|standard| IcrcLedgerStandardRow {
            name: standard.name,
            url: standard.url,
        })
        .collect())
}

pub async fn query_ledger<T, E>(
    agent: &Agent,
    ledger_canister: &Principal,
    method: &'static str,
) -> Result<T, E>
where
    E: IcrcLedgerError,
    T: for<'de> Deserialize<'de> + CandidType,
{
    let arg = Encode!().map_err(|err| E::candid_encode(method, err.to_string()))?;
    query_encoded(agent, ledger_canister, method, arg).await
}

pub async fn query_ledger_arg<Arg, Response, E>(
    agent: &Agent,
    ledger_canister: &Principal,
    method: &'static str,
    arg: &Arg,
) -> Result<Response, E>
where
    Arg: CandidType + Sync,
    E: IcrcLedgerError,
    Response: for<'de> Deserialize<'de> + CandidType,
{
    let arg = candid::encode_one(arg).map_err(|err| E::candid_encode(method, err.to_string()))?;
    query_encoded(agent, ledger_canister, method, arg).await
}

pub fn metadata_row(key: String, value: IcrcMetadataValue) -> IcrcLedgerMetadataRow {
    if key == ICRC_LOGO_METADATA_KEY {
        return IcrcLedgerMetadataRow {
            key,
            value_type: "bool".to_string(),
            value: JsonValue::Bool(metadata_value_is_present(&value)),
        };
    }

    let (value_type, value) = match value {
        IcrcMetadataValue::Nat(value) => ("nat", value.to_string()),
        IcrcMetadataValue::Int(value) => ("int", value.to_string()),
        IcrcMetadataValue::Text(value) => ("text", value),
        IcrcMetadataValue::Blob(value) => ("blob", hex_bytes(&value)),
    };
    IcrcLedgerMetadataRow {
        key,
        value_type: value_type.to_string(),
        value: JsonValue::String(value),
    }
}

#[must_use]
pub fn index_principal_error_text(error: GetIndexPrincipalError) -> String {
    match error {
        GetIndexPrincipalError::IndexPrincipalNotSet => "index principal not set".to_string(),
        GetIndexPrincipalError::GenericError {
            error_code,
            description,
        } => format!("generic error {error_code}: {description}"),
    }
}

async fn query_encoded<T, E>(
    agent: &Agent,
    ledger_canister: &Principal,
    method: &'static str,
    arg: Vec<u8>,
) -> Result<T, E>
where
    E: IcrcLedgerError,
    T: for<'de> Deserialize<'de> + CandidType,
{
    let bytes = agent
        .query(ledger_canister, method)
        .with_arg(arg)
        .call()
        .await
        .map_err(|err| E::agent_call(method, err.to_string()))?;
    candid::decode_one(&bytes).map_err(|err| E::candid_decode(method, err.to_string()))
}

fn metadata_value_is_present(value: &IcrcMetadataValue) -> bool {
    match value {
        IcrcMetadataValue::Text(value) => !value.trim().is_empty(),
        IcrcMetadataValue::Blob(value) => !value.is_empty(),
        IcrcMetadataValue::Nat(_) | IcrcMetadataValue::Int(_) => true,
    }
}