canic-core 0.91.5

Canic — a canister orchestration and management toolkit for the Internet Computer
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
//! Module: workflow::ic::icp_refill::execution
//!
//! Responsibility: execute ICP ledger transfers and CMC top-up notifications.
//! Does not own: endpoint authorization, stable record schemas, or pure policy.
//! Boundary: orchestrates ops/storage/replay after request preflight.

use crate::{
    InternalError,
    cdk::{candid::Nat, types::Principal},
    domain::{
        icp_refill::{IcpRefillErrorCode, IcpRefillStatus},
        policy::pure::icp_refill::IcpRefillPolicyViolation,
    },
    dto::icp_refill::{IcpRefillRequest, IcpRefillResponse},
    ids::CanisterRole,
    infra::ic::icp_refill::{NotifyTopUpArg, NotifyTopUpError, TransferError},
    ops::{
        cost_guard::CostGuardPermit,
        ic::{IcOps, icp_refill::IcpRefillOps},
        replay::receipt::{ReplayReceiptToken, abort_reserved_receipt},
        runtime::cycles_funding::CyclesFundingLedgerOps,
        storage::{
            children::CanisterChildrenOps,
            icp_refill::{
                IcpRefillOperationCreateInput, IcpRefillRecordOpsError, IcpRefillStoreOps,
            },
        },
    },
    view::icp_refill::IcpRefillOperation,
    workflow::ic::icp_refill::{
        MAX_NOTIFY_ATTEMPTS, RateQueryMode, TX_WINDOW_NANOS,
        cost_guard::{
            recover_icp_refill_cost_guard, require_icp_refill_cost_permit,
            reserve_icp_refill_cost_guard_if_needed,
        },
        policy_denied, prepare_context,
        replay::{
            finish_icp_refill_replay, mark_icp_refill_notify_effect,
            mark_icp_refill_recovery_required, mark_icp_refill_transfer_effect,
        },
    },
};

pub(super) async fn execute_fresh_manual_refill(
    request: IcpRefillRequest,
    operation_id: [u8; 32],
    token: &ReplayReceiptToken,
) -> Result<IcpRefillResponse, InternalError> {
    let mut cost_permit = None;
    let operation =
        match execute_manual_refill_operation(request, operation_id, token, &mut cost_permit).await
        {
            Ok(operation) => operation,
            Err(err) => {
                recover_icp_refill_cost_guard(cost_permit.as_ref());
                abort_reserved_receipt(token);
                return Err(err);
            }
        };
    let response = IcpRefillStoreOps::to_response(&operation);

    if let Err(err) = finish_icp_refill_replay(token, &operation, &response, cost_permit.as_ref()) {
        abort_reserved_receipt(token);
        return Err(err);
    }

    Ok(response)
}

async fn execute_manual_refill_operation(
    request: IcpRefillRequest,
    operation_id: [u8; 32],
    token: &ReplayReceiptToken,
    cost_permit: &mut Option<CostGuardPermit>,
) -> Result<IcpRefillOperation, InternalError> {
    if let Some(operation) = IcpRefillStoreOps::find_by_operation_id(operation_id) {
        IcpRefillStoreOps::validate_retry_request_matches_operation(&request, &operation)?;
        return advance_operation(operation, token, cost_permit).await;
    }

    let context = prepare_context(&request, RateQueryMode::WhenGateConfigured).await?;
    let cmc_account =
        IcpRefillOps::cmc_topup_account(context.cmc_canister_id, request.target_canister)?;
    let operation = create_or_get_operation(IcpRefillOperationCreateInput {
        operation_id,
        source_canister: request.source_canister,
        source_subaccount: request.source_subaccount,
        target_canister: request.target_canister,
        ledger_canister_id: context.ledger_canister_id,
        cmc_canister_id: context.cmc_canister_id,
        cmc_to_account_owner: cmc_account.owner,
        cmc_to_account_subaccount: cmc_account.subaccount,
        amount_e8s: request.amount_e8s,
        fee_e8s: context.fee_e8s,
        memo: IcpRefillOps::topup_memo(),
        created_at_time_ns: context.created_at_time_ns,
        now_ns: IcOps::now_nanos(),
    })?;

    advance_operation(operation, token, cost_permit).await
}

fn create_or_get_operation(
    input: IcpRefillOperationCreateInput,
) -> Result<IcpRefillOperation, InternalError> {
    match IcpRefillStoreOps::create_or_get(input) {
        Ok(operation) => Ok(operation),
        Err(IcpRefillRecordOpsError::ConcurrentOperation { .. }) => {
            Err(policy_denied(IcpRefillPolicyViolation::ConcurrentRefill))
        }
        Err(err) => Err(err.into()),
    }
}

async fn transfer_operation(
    operation: IcpRefillOperation,
    token: &ReplayReceiptToken,
    cost_permit: &mut Option<CostGuardPermit>,
) -> Result<IcpRefillOperation, InternalError> {
    let to = IcpRefillOps::cmc_topup_account(operation.cmc_canister_id, operation.target_canister)?;
    let transfer_arg = IcpRefillOps::transfer_arg(
        operation.source_subaccount,
        to,
        operation.amount_e8s,
        operation.fee_e8s,
        operation.memo.clone(),
        operation.created_at_time_ns,
    );

    reserve_icp_refill_cost_guard_if_needed(token, &operation, cost_permit)?;
    let cost_permit = require_icp_refill_cost_permit(cost_permit.as_ref())?;
    mark_icp_refill_transfer_effect(token, &operation);

    match IcpRefillOps::icrc1_transfer(cost_permit, operation.ledger_canister_id, transfer_arg)
        .await
    {
        Err(err) => {
            mark_icp_refill_recovery_required(token, &operation, "ledger_transfer", &err);
            Err(err)
        }
        Ok(Ok(block_index)) => {
            let block_index = match IcpRefillOps::checked_block_index(block_index) {
                Ok(block_index) => block_index,
                Err(err) => {
                    return IcpRefillStoreOps::mark_transfer_failed(
                        operation.id,
                        IcpRefillErrorCode::InvalidLedgerBlockIndex,
                        err.to_string(),
                        IcOps::now_nanos(),
                    );
                }
            };
            IcpRefillStoreOps::mark_transferred(operation.id, block_index, IcOps::now_nanos())
        }
        Ok(Err(err)) => apply_transfer_error(operation.id, err),
    }
}

async fn advance_operation(
    operation: IcpRefillOperation,
    token: &ReplayReceiptToken,
    cost_permit: &mut Option<CostGuardPermit>,
) -> Result<IcpRefillOperation, InternalError> {
    let operation = match operation.status {
        IcpRefillStatus::Requested => {
            transfer_unless_window_stale(operation, token, cost_permit).await?
        }
        IcpRefillStatus::Transferred | IcpRefillStatus::NotifyProcessing => operation,
        IcpRefillStatus::Failed if IcpRefillStoreOps::can_retry_notify(&operation) => operation,
        IcpRefillStatus::Failed if IcpRefillStoreOps::can_retry_bad_fee(&operation) => {
            transfer_unless_window_stale(operation, token, cost_permit).await?
        }
        IcpRefillStatus::Completed
        | IcpRefillStatus::Failed
        | IcpRefillStatus::InvalidTransaction
        | IcpRefillStatus::Refunded
        | IcpRefillStatus::TransactionTooOld => return Ok(operation),
    };

    if IcpRefillStoreOps::should_notify(&operation) {
        notify_operation(operation, token, cost_permit).await
    } else {
        Ok(operation)
    }
}

async fn transfer_unless_window_stale(
    operation: IcpRefillOperation,
    token: &ReplayReceiptToken,
    cost_permit: &mut Option<CostGuardPermit>,
) -> Result<IcpRefillOperation, InternalError> {
    let now_ns = IcOps::now_nanos();
    if IcpRefillStoreOps::transfer_window_stale(&operation, now_ns, TX_WINDOW_NANOS) {
        IcpRefillStoreOps::mark_transfer_window_stale(operation.id, now_ns)
    } else {
        transfer_operation(operation, token, cost_permit).await
    }
}

async fn notify_operation(
    operation: IcpRefillOperation,
    token: &ReplayReceiptToken,
    cost_permit: &mut Option<CostGuardPermit>,
) -> Result<IcpRefillOperation, InternalError> {
    let Some(block_index) = operation.ledger_block_index else {
        return IcpRefillStoreOps::mark_notify_failed(
            operation.id,
            "notify_top_up cannot run before ledger block is recorded".to_string(),
            IcOps::now_nanos(),
        );
    };

    let operation =
        IcpRefillStoreOps::mark_notify_attempt_started(operation.id, IcOps::now_nanos())?;
    let args = NotifyTopUpArg {
        block_index,
        canister_id: operation.target_canister,
    };

    reserve_icp_refill_cost_guard_if_needed(token, &operation, cost_permit)?;
    let cost_permit = require_icp_refill_cost_permit(cost_permit.as_ref())?;
    mark_icp_refill_notify_effect(token, &operation);

    match IcpRefillOps::notify_top_up(cost_permit, operation.cmc_canister_id, args).await {
        Ok(Ok(cycles_sent)) => {
            let operation =
                IcpRefillStoreOps::mark_completed(operation.id, cycles_sent, IcOps::now_nanos())?;
            record_direct_child_refill_grant(&operation, IcOps::now_secs());
            Ok(operation)
        }
        Ok(Err(err)) => apply_notify_error(operation.id, operation.notify_attempts, err),
        Err(err) => {
            mark_icp_refill_recovery_required(token, &operation, "cmc_notify_top_up", &err);
            Err(err)
        }
    }
}

pub(super) fn apply_transfer_error(
    record_id: u64,
    err: TransferError,
) -> Result<IcpRefillOperation, InternalError> {
    match err {
        TransferError::BadFee { expected_fee } => {
            let expected_fee_e8s = match crate::workflow::ic::icp_refill::checked_nat_u64(
                "bad_fee.expected_fee",
                expected_fee,
            ) {
                Ok(expected_fee_e8s) => expected_fee_e8s,
                Err(err) => {
                    return IcpRefillStoreOps::mark_transfer_failed(
                        record_id,
                        IcpRefillErrorCode::BadFee,
                        err.to_string(),
                        IcOps::now_nanos(),
                    );
                }
            };
            IcpRefillStoreOps::mark_bad_fee(
                record_id,
                expected_fee_e8s,
                format!("bad fee; expected {expected_fee_e8s}"),
                IcOps::now_nanos(),
            )
        }
        TransferError::Duplicate { duplicate_of } => {
            let duplicate_of = match IcpRefillOps::checked_block_index(duplicate_of) {
                Ok(block_index) => block_index,
                Err(err) => {
                    return IcpRefillStoreOps::mark_transfer_failed(
                        record_id,
                        IcpRefillErrorCode::InvalidLedgerBlockIndex,
                        err.to_string(),
                        IcOps::now_nanos(),
                    );
                }
            };
            IcpRefillStoreOps::mark_duplicate_transferred(
                record_id,
                duplicate_of,
                IcOps::now_nanos(),
            )
        }
        TransferError::TooOld => {
            IcpRefillStoreOps::mark_transfer_window_stale(record_id, IcOps::now_nanos())
        }
        other => IcpRefillStoreOps::mark_transfer_failed(
            record_id,
            IcpRefillErrorCode::LedgerTransferFailed,
            other.to_string(),
            IcOps::now_nanos(),
        ),
    }
}

pub(super) fn apply_notify_error(
    record_id: u64,
    notify_attempts: u32,
    err: NotifyTopUpError,
) -> Result<IcpRefillOperation, InternalError> {
    match err {
        NotifyTopUpError::Refunded {
            block_index,
            reason,
        } => IcpRefillStoreOps::mark_refunded(record_id, block_index, reason, IcOps::now_nanos()),
        NotifyTopUpError::InvalidTransaction(reason) => {
            IcpRefillStoreOps::mark_invalid_transaction(record_id, reason, IcOps::now_nanos())
        }
        NotifyTopUpError::Processing => mark_notify_processing(record_id, notify_attempts),
        NotifyTopUpError::TransactionTooOld(min_block_index) => {
            IcpRefillStoreOps::mark_transaction_too_old(
                record_id,
                Some(min_block_index),
                IcOps::now_nanos(),
            )
        }
        NotifyTopUpError::Other {
            error_code,
            error_message,
        } => mark_retryable_notify_failure(
            record_id,
            notify_attempts,
            format!("notify_top_up error {error_code}: {error_message}"),
        ),
    }
}

pub(super) fn mark_notify_processing(
    record_id: u64,
    notify_attempts: u32,
) -> Result<IcpRefillOperation, InternalError> {
    if notify_attempts >= MAX_NOTIFY_ATTEMPTS {
        IcpRefillStoreOps::mark_notify_max_attempts(
            record_id,
            "notify_top_up returned Processing after max attempts".to_string(),
            IcOps::now_nanos(),
        )
    } else {
        IcpRefillStoreOps::mark_notify_processing(record_id, IcOps::now_nanos())
    }
}

pub(super) fn mark_retryable_notify_failure(
    record_id: u64,
    notify_attempts: u32,
    error_message: String,
) -> Result<IcpRefillOperation, InternalError> {
    if notify_attempts >= MAX_NOTIFY_ATTEMPTS {
        IcpRefillStoreOps::mark_notify_max_attempts(record_id, error_message, IcOps::now_nanos())
    } else {
        IcpRefillStoreOps::mark_notify_failed(record_id, error_message, IcOps::now_nanos())
    }
}

fn record_direct_child_refill_grant(operation: &IcpRefillOperation, now_secs: u64) {
    let Some(cycles_sent) = operation.cycles_sent.as_ref() else {
        return;
    };
    let Some((_child_role, parent_pid)) =
        CanisterChildrenOps::role_parent(operation.target_canister)
    else {
        return;
    };
    let Some((child, cycles)) = direct_child_refill_grant(operation, cycles_sent, parent_pid)
    else {
        return;
    };

    CyclesFundingLedgerOps::record_child_grant(child, cycles, now_secs);
}

pub(super) fn direct_child_refill_grant(
    operation: &IcpRefillOperation,
    cycles_sent: &Nat,
    parent_pid: Option<Principal>,
) -> Option<(Principal, u128)> {
    if !direct_child_refill_parent_matches(parent_pid, operation.source_canister) {
        return None;
    }

    Some((
        operation.target_canister,
        IcpRefillStoreOps::nat_to_u128_saturating(cycles_sent),
    ))
}

pub(super) fn direct_child_refill_role(
    target_canister: Principal,
    source_canister: Principal,
) -> Option<CanisterRole> {
    let (role, parent_pid) = CanisterChildrenOps::role_parent(target_canister)?;
    if direct_child_refill_parent_matches(parent_pid, source_canister) {
        Some(role)
    } else {
        None
    }
}

fn direct_child_refill_parent_matches(
    parent_pid: Option<Principal>,
    source_canister: Principal,
) -> bool {
    parent_pid == Some(source_canister)
}