ic-platform 0.7.6

Controlled Candid and IC runtime dependency boundary
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
//! Required external IC protocol codecs, independent of transport and recovery.
//!
//! Encode before submission and retain those exact bytes for intent journals.
//! Callers select the destination, wait, attachment, budgets and reply arity.
//! Returned protocol errors are decoded values, separate from transport failures.
//! Decoding authenticates nothing and never permits resubmission. The parent
//! module admits at most 16 constructed wire levels before upstream decoding.

use super::{DecodeError, DecodeLimits, with_decoder};
use candid::utils::ArgumentDecoder;

/// Caller-selected handling of the declared top-level reply arity.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReplyArity {
    /// Retain upstream optional omission and skipping within caller work quotas.
    Compatible,
    /// Require the declared value, even if optional, and refuse extra values
    /// before attempting to skip them. Zero-result operations require zero values.
    Exact,
}

fn reply<'a, T: ArgumentDecoder<'a>>(
    bytes: &'a [u8],
    limits: DecodeLimits,
    arity: ReplyArity,
    requires_value: bool,
) -> Result<T, DecodeError> {
    with_decoder(bytes, limits, |decoder| {
        if arity == ReplyArity::Exact && requires_value && decoder.is_done() {
            return Err(DecodeError::Candid(candid::Error::msg(
                "missing external protocol reply value",
            )));
        }
        let value = T::decode(decoder).map_err(DecodeError::Candid)?;
        if arity == ReplyArity::Exact && !decoder.is_done() {
            return Err(DecodeError::Candid(candid::Error::msg(
                "unexpected additional external protocol reply values",
            )));
        }
        Ok(value)
    })
}

#[cfg(any(
    feature = "management-canister-types",
    feature = "cmc-types",
    feature = "icp-ledger-types",
    feature = "icrc-ledger-types",
    feature = "nns-registry-types",
    feature = "cycles-ledger-types",
    all(feature = "certified-assets-types", not(target_family = "wasm"))
))]
macro_rules! single {
    ($module:ident, $method:literal, $request:ty, $response:ty) => {
        #[doc = concat!("External `", $method, "`: one request value and one result value.")]
        pub mod $module {
            /// Exact external method name; destination and transport remain caller-owned.
            pub const METHOD: &str = $method;
            /// Encode one argument without submitting, normalizing or mutating it.
            ///
            /// # Errors
            /// Returns the existing Candid encoding error.
            pub fn encode(request: &$request) -> Result<Vec<u8>, candid::Error> {
                candid::encode_one(request)
            }
            /// Decode one result, preserving the typed external success/error value.
            ///
            /// # Errors
            /// Refuses malformed, over-budget or arity-incompatible replies.
            pub fn decode(
                bytes: &[u8],
                limits: super::super::DecodeLimits,
                arity: super::super::ReplyArity,
            ) -> Result<$response, super::super::DecodeError> {
                super::super::reply::<($response,)>(bytes, limits, arity, true)
                    .map(|(value,)| value)
            }
        }
    };
}
macro_rules! empty_request {
    ($module:ident, $method:literal, $response:ty) => {
        #[doc = concat!("External `", $method, "`: zero request values and one result value.")]
        pub mod $module {
            /// Exact external method name.
            pub const METHOD: &str = $method;
            /// Encode the explicit zero-argument envelope, without submitting it.
            ///
            /// # Errors
            /// Returns the existing Candid encoding error.
            pub fn encode() -> Result<Vec<u8>, candid::Error> {
                candid::encode_args(())
            }
            /// Decode one result with caller-selected limits and arity.
            ///
            /// # Errors
            /// Refuses malformed, over-budget or arity-incompatible replies.
            pub fn decode(
                bytes: &[u8],
                limits: super::super::DecodeLimits,
                arity: super::super::ReplyArity,
            ) -> Result<$response, super::super::DecodeError> {
                super::super::reply::<($response,)>(bytes, limits, arity, true)
                    .map(|(value,)| value)
            }
        }
    };
}

#[cfg(feature = "management-canister-types")]
macro_rules! empty_reply {
    ($module:ident, $method:literal, $request:ty) => {
        #[doc = concat!("External `", $method, "`: one request value and zero reply values.")]
        pub mod $module {
            /// Exact external method name; no destination or spending authority.
            pub const METHOD: &str = $method;
            /// Encode the complete request before any caller-owned submission.
            ///
            /// # Errors
            /// Preserves the existing Candid encoding error.
            pub fn encode(request: &$request) -> Result<Vec<u8>, candid::Error> {
                candid::encode_one(request)
            }
            /// Decode zero results with explicit caller arity and resource policy.
            ///
            /// # Errors
            /// Refuses malformed, over-budget or arity-incompatible replies.
            pub fn decode(
                bytes: &[u8],
                limits: super::super::DecodeLimits,
                arity: super::super::ReplyArity,
            ) -> Result<(), super::super::DecodeError> {
                super::super::reply(bytes, limits, arity, false)
            }
        }
    };
}

/// Management protocol operations; no controller, settings or allocation policy.
pub mod management {
    empty_request!(raw_rand, "raw_rand", Vec<u8>);
    #[cfg(feature = "management-canister-types")]
    single!(
        canister_status,
        "canister_status",
        crate::management_canister_types::CanisterIdRecord,
        crate::management_canister_types::CanisterStatusResult
    );
    #[cfg(feature = "management-canister-types")]
    single!(
        canister_info,
        "canister_info",
        crate::management_canister_types::CanisterInfoArgs,
        crate::management_canister_types::CanisterInfoResult
    );
    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        update_settings,
        "update_settings",
        crate::management_canister_types::UpdateSettingsArgs
    );
    #[cfg(feature = "management-canister-types")]
    single!(
        upload_chunk,
        "upload_chunk",
        crate::management_canister_types::UploadChunkArgs,
        crate::management_canister_types::ChunkHash
    );

    #[cfg(feature = "management-canister-types")]
    single!(
        stored_chunks,
        "stored_chunks",
        crate::management_canister_types::CanisterIdRecord,
        Vec<crate::management_canister_types::ChunkHash>
    );

    #[cfg(feature = "management-canister-types")]
    single!(
        list_canister_snapshots,
        "list_canister_snapshots",
        crate::management_canister_types::CanisterIdRecord,
        Vec<crate::management_canister_types::Snapshot>
    );

    #[cfg(feature = "management-canister-types")]
    single!(
        ecdsa_public_key,
        "ecdsa_public_key",
        crate::management_canister_types::EcdsaPublicKeyArgs,
        crate::management_canister_types::EcdsaPublicKeyResult
    );

    #[cfg(feature = "management-canister-types")]
    single!(
        sign_with_ecdsa,
        "sign_with_ecdsa",
        crate::management_canister_types::SignWithEcdsaArgs,
        crate::management_canister_types::SignWithEcdsaResult
    );

    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        clear_chunk_store,
        "clear_chunk_store",
        crate::management_canister_types::CanisterIdRecord
    );

    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        install_chunked_code,
        "install_chunked_code",
        crate::management_canister_types::InstallChunkedCodeArgs
    );

    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        uninstall_code,
        "uninstall_code",
        crate::management_canister_types::UninstallCodeArgs
    );

    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        start_canister,
        "start_canister",
        crate::management_canister_types::CanisterIdRecord
    );

    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        stop_canister,
        "stop_canister",
        crate::management_canister_types::CanisterIdRecord
    );

    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        delete_canister,
        "delete_canister",
        crate::management_canister_types::CanisterIdRecord
    );

    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        deposit_cycles,
        "deposit_cycles",
        crate::management_canister_types::CanisterIdRecord
    );

    #[cfg(feature = "management-canister-types")]
    empty_reply!(
        delete_canister_snapshot,
        "delete_canister_snapshot",
        crate::management_canister_types::DeleteCanisterSnapshotArgs
    );
}

/// Direct CMC operations; distinct from Cycles Ledger creation and withdrawals.
#[cfg(feature = "cmc-types")]
pub mod cmc {
    empty_request!(
        get_icp_xdr_conversion_rate,
        "get_icp_xdr_conversion_rate",
        crate::cmc_types::IcpXdrConversionRateResponse
    );
    single!(
        notify_top_up,
        "notify_top_up",
        crate::cmc_types::NotifyTopUpArg,
        crate::cmc_types::NotifyTopUpResult
    );
    single!(
        notify_mint_cycles,
        "notify_mint_cycles",
        crate::cmc_types::NotifyMintCyclesArg,
        crate::cmc_types::NotifyMintCyclesResult
    );
}

/// Legacy ICP ledger operations; callers retain transfer and archive authority.
#[cfg(feature = "icp-ledger-types")]
pub mod icp_ledger {
    single!(
        transfer,
        "transfer",
        crate::icp_ledger_types::TransferArgs,
        crate::icp_ledger_types::TransferResult
    );
    single!(
        query_encoded_blocks,
        "query_encoded_blocks",
        crate::icp_ledger_types::GetBlocksArgs,
        crate::icp_ledger_types::QueryEncodedBlocksResponse
    );
}

/// ICRC operations retain the exact upstream DTO identities, including Accounts.
/// The standard get_blocks projection omits legacy Nat64; use the separate
/// cycles_ledger::get_blocks codec for that provider's wider value schema.
#[cfg(feature = "icrc-ledger-types")]
pub mod icrc {
    empty_request!(fee, "icrc1_fee", candid::Nat);
    single!(
        balance_of,
        "icrc1_balance_of",
        crate::icrc_ledger_types::Account,
        candid::Nat
    );
    single!(transfer, "icrc1_transfer", crate::icrc_ledger_types::TransferArg, Result<candid::Nat, crate::icrc_ledger_types::TransferError>);
    empty_request!(
        get_tip_certificate,
        "icrc3_get_tip_certificate",
        Option<crate::icrc_ledger_types::ICRC3DataCertificate>
    );
    single!(
        get_blocks,
        "icrc3_get_blocks",
        Vec<crate::icrc_ledger_types::GetBlocksRequest>,
        crate::icrc_ledger_types::GetBlocksResult
    );
}

/// NNS Registry operations; subnet interpretation remains consumer-owned.
#[cfg(feature = "nns-registry-types")]
pub mod nns_registry {
    single!(
        get_subnet_for_canister,
        "get_subnet_for_canister",
        crate::nns_registry_types::GetSubnetForCanisterRequest,
        crate::nns_registry_types::GetSubnetForCanisterResponse
    );
}

/// Cycles Ledger requests preserve debit, duplicate and topology fields unchanged.
#[cfg(feature = "cycles-ledger-types")]
pub mod cycles_ledger {
    #[cfg(feature = "icrc-ledger-types")]
    single!(
        get_blocks,
        "icrc3_get_blocks",
        Vec<crate::icrc_ledger_types::GetBlocksRequest>,
        crate::cycles_ledger_types::GetBlocksResult
    );
    single!(
        create_canister,
        "create_canister",
        crate::cycles_ledger_types::CreateCanisterArgs,
        crate::cycles_ledger_types::CreateCanisterResult
    );
    single!(
        withdraw,
        "withdraw",
        crate::cycles_ledger_types::WithdrawArgs,
        crate::cycles_ledger_types::WithdrawResult
    );
}

/// Native certified-asset acquisition; decoding does not authenticate content.
#[cfg(all(feature = "certified-assets-types", not(target_family = "wasm")))]
pub mod certified_assets {
    single!(
        get,
        "get",
        crate::certified_assets_types::GetArgs,
        crate::certified_assets_types::GetResult
    );
    single!(
        get_chunk,
        "get_chunk",
        crate::certified_assets_types::GetChunkArgs,
        crate::certified_assets_types::GetChunkResult
    );
}

/// Legacy archive callback signature. Consumers validate the callback's source
/// and method themselves; no guessed method or automatic archive follow is added.
#[cfg(feature = "icp-ledger-types")]
pub mod archive_encoded_blocks {
    /// Encode the admitted callback range, independently of its destination/method.
    ///
    /// # Errors
    /// Preserves the existing Candid encoding error.
    pub fn encode(
        request: &crate::icp_ledger_types::GetBlocksArgs,
    ) -> Result<Vec<u8>, candid::Error> {
        candid::encode_one(request)
    }
    /// Decode the callback's typed success/error without validating its authority.
    ///
    /// # Errors
    /// Refuses malformed, over-budget or arity-incompatible replies.
    pub fn decode(
        bytes: &[u8],
        limits: super::DecodeLimits,
        arity: super::ReplyArity,
    ) -> Result<crate::icp_ledger_types::QueryEncodedBlocksResult, super::DecodeError> {
        super::reply::<(crate::icp_ledger_types::QueryEncodedBlocksResult,)>(
            bytes, limits, arity, true,
        )
        .map(|(value,)| value)
    }
}