Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FOLLOW-244: Add notifyTopUpIfNeeded to canisters service #5857

Merged
merged 2 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 83 additions & 1 deletion frontend/src/lib/services/canisters.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,21 @@ import {
createCanister as createCanisterApi,
detachCanister as detachCanisterApi,
getIcpToCyclesExchangeRate as getIcpToCyclesExchangeRateApi,
notifyTopUpCanister,
queryCanisterDetails as queryCanisterDetailsApi,
queryCanisters,
renameCanister as renameCanisterApi,
topUpCanister as topUpCanisterApi,
updateSettings as updateSettingsApi,
} from "$lib/api/canisters.api";
import { getTransactions } from "$lib/api/icp-index.api";
import type {
CanisterDetails,
CanisterSettings,
} from "$lib/canisters/ic-management/ic-management.canister.types";
import type { CanisterDetails as CanisterInfo } from "$lib/canisters/nns-dapp/nns-dapp.types";
import { TOP_UP_CANISTER_MEMO } from "$lib/constants/api.constants";
import { CYCLES_MINTING_CANISTER_ID } from "$lib/constants/canister-ids.constants";
import { FORCE_CALL_STRATEGY } from "$lib/constants/mockable.constants";
import { mainTransactionFeeE8sStore } from "$lib/derived/main-transaction-fee.derived";
import { canistersStore } from "$lib/stores/canisters.store";
Expand All @@ -27,8 +31,19 @@ import {
mapCanisterErrorToToastMessage,
toToastError,
} from "$lib/utils/error.utils";
import { AnonymousIdentity } from "@dfinity/agent";
import {
AccountIdentifier,
SubAccount,
type TransactionWithId,
} from "@dfinity/ledger-icp";
import type { Principal } from "@dfinity/principal";
import { ICPToken, TokenAmountV2 } from "@dfinity/utils";
import {
ICPToken,
TokenAmountV2,
isNullish,
principalToSubAccount,
} from "@dfinity/utils";
import { get } from "svelte/store";
import { getAuthenticatedIdentity } from "./auth.services";
import { getAccountIdentity, loadBalance } from "./icp-accounts.services";
Expand Down Expand Up @@ -166,6 +181,73 @@ export const topUpCanister = async ({
}
};

// Returns the blockheight of the transaction, if it was a canister topup, or
dskloetd marked this conversation as resolved.
Show resolved Hide resolved
// undefined otherwise.
const getBlockHeightFromCanisterTopup = ({
dskloetd marked this conversation as resolved.
Show resolved Hide resolved
id: blockHeight,
transaction: { memo, operation },
}: TransactionWithId): bigint | undefined => {
if (memo !== TOP_UP_CANISTER_MEMO || !("Transfer" in operation)) {
return undefined;
}
return blockHeight;
};

// Returns true if notify_top_up was called (whether successful or not).
export const notifyTopUpIfNeeded = async ({
canisterId,
}: {
canisterId: Principal;
}): Promise<boolean> => {
const subAccount = principalToSubAccount(canisterId);
const cmcAccountIdentifier = AccountIdentifier.fromPrincipal({
principal: CYCLES_MINTING_CANISTER_ID,
subAccount: SubAccount.fromBytes(subAccount) as SubAccount,
});
const cmcAccountIdentifierHex = cmcAccountIdentifier.toHex();

const {
balance,
transactions: [transaction],
} = await getTransactions({
identity: new AnonymousIdentity(),
dskloetd marked this conversation as resolved.
Show resolved Hide resolved
maxResults: 1n,
accountIdentifier: cmcAccountIdentifierHex,
});

if (balance === 0n || isNullish(transaction)) {
return false;
}

const blockHeight = getBlockHeightFromCanisterTopup(transaction);

if (isNullish(blockHeight)) {
// This should be very rare but it might be useful to know if it happens.
console.warn(
"CMC subaccount has non-zero balance but the most recent transaction is not a top-up",
{
canisterId: canisterId.toText(),
cmcAccountIdentifierHex,
balance,
transaction,
}
);
return false;
}

try {
await notifyTopUpCanister({
identity: new AnonymousIdentity(),
blockHeight,
canisterId,
});
} catch (error: unknown) {
console.error(error);
// Ignore. This is just a background fallback.
}
return true;
};

export const addController = async ({
controller,
canisterDetails,
Expand Down
139 changes: 139 additions & 0 deletions frontend/src/tests/lib/services/canisters.services.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as api from "$lib/api/canisters.api";
import * as icpIndexApi from "$lib/api/icp-index.api";
import * as ledgerApi from "$lib/api/icp-ledger.api";
import { UserNotTheControllerError } from "$lib/canisters/ic-management/ic-management.errors";
import * as authServices from "$lib/services/auth.services";
Expand All @@ -10,6 +11,7 @@ import {
getCanisterDetails,
getIcpToCyclesExchangeRate,
listCanisters,
notifyTopUpIfNeeded,
removeController,
renameCanister,
topUpCanister,
Expand All @@ -31,8 +33,11 @@ import {
} from "$tests/mocks/canisters.mock";
import en from "$tests/mocks/i18n.mock";
import { mockMainAccount } from "$tests/mocks/icp-accounts.store.mock";
import { createTransactionWithId } from "$tests/mocks/icp-transactions.mock";
import { blockAllCallsTo } from "$tests/utils/module.test-utils";
import { AnonymousIdentity } from "@dfinity/agent";
import { toastsStore } from "@dfinity/gix-components";
import { Principal } from "@dfinity/principal";
import { waitFor } from "@testing-library/svelte";
import { get } from "svelte/store";
import type { MockInstance } from "vitest";
Expand All @@ -54,6 +59,7 @@ describe("canisters-services", () => {
let spyUpdateSettings: MockInstance;
let spyCreateCanister: MockInstance;
let spyTopUpCanister: MockInstance;
let spyNotifyTopUpCanister: MockInstance;
let spyQueryCanisterDetails: MockInstance;
let spyGetExchangeRate: MockInstance;

Expand Down Expand Up @@ -92,6 +98,10 @@ describe("canisters-services", () => {
.spyOn(api, "topUpCanister")
.mockImplementation(() => Promise.resolve(undefined));

spyNotifyTopUpCanister = vi
.spyOn(api, "notifyTopUpCanister")
.mockImplementation(() => Promise.resolve(undefined));

spyQueryCanisterDetails = vi
.spyOn(api, "queryCanisterDetails")
.mockImplementation(() => Promise.resolve(mockCanisterDetails));
Expand Down Expand Up @@ -600,4 +610,133 @@ describe("canisters-services", () => {
resetIdentity();
});
});

describe("notifyTopUpIfNeeded", () => {
const canisterId = Principal.fromText("mkam6-f4aaa-aaaaa-qablq-cai");
// Can be reconstructed with:
// CMC_ID=rkp4c-7iaaa-aaaaa-aaaca-cai
// CANISTER_ID=mkam6-f4aaa-aaaaa-qablq-cai
// scripts/convert-id --input text --subaccount_format text --output account_identifier $CMC_ID $CANISTER_ID
const cmcAccountIdentifierHex =
"addb464aaaa06f2e7dabf929fb5f729519848fdce636894806797859d23724eb";

it("should notify if there is a non-zero balance from an unburned top-up", async () => {
const blockHeight = 34n;
const memo = 0x50555054n; // TPUP
const topupTransaction = createTransactionWithId({
id: blockHeight,
memo,
});

const spyGetTransactions = vi.spyOn(icpIndexApi, "getTransactions");
spyGetTransactions.mockResolvedValue({
balance: 100_000_000n,
transactions: [topupTransaction],
});

const result = await notifyTopUpIfNeeded({
canisterId,
});

expect(result).toBe(true);

expect(spyNotifyTopUpCanister).toBeCalledTimes(1);
expect(spyNotifyTopUpCanister).toBeCalledWith({
canisterId,
blockHeight,
identity: new AnonymousIdentity(),
});

expect(spyGetTransactions).toBeCalledTimes(1);
expect(spyGetTransactions).toBeCalledWith({
accountIdentifier: cmcAccountIdentifierHex,
identity: new AnonymousIdentity(),
maxResults: 1n,
});
});

it("should not notify if there is a zero balance in the cmc account", async () => {
const balance = 0n;

const spyGetTransactions = vi.spyOn(icpIndexApi, "getTransactions");
spyGetTransactions.mockResolvedValue({
balance,
transactions: [],
});

const result = await notifyTopUpIfNeeded({
canisterId,
});

expect(result).toBe(false);

expect(spyNotifyTopUpCanister).toBeCalledTimes(0);
});

it("should not notify if there is a non-zero balance from a non-topup transaction", async () => {
dskloetd marked this conversation as resolved.
Show resolved Hide resolved
const blockHeight = 34n;
const memo = 0n;
const nonTopupTransaction = createTransactionWithId({
id: blockHeight,
memo,
});
const balance = 100_000_000n;

const spyConsoleWarn = vi.spyOn(console, "warn").mockReturnValue();

const spyGetTransactions = vi.spyOn(icpIndexApi, "getTransactions");
spyGetTransactions.mockResolvedValue({
balance,
transactions: [nonTopupTransaction],
});

const result = await notifyTopUpIfNeeded({
canisterId,
});

expect(result).toBe(false);

expect(spyNotifyTopUpCanister).toBeCalledTimes(0);

expect(spyConsoleWarn).toBeCalledTimes(1);
expect(spyConsoleWarn).toBeCalledWith(
"CMC subaccount has non-zero balance but the most recent transaction is not a top-up",
{
balance,
canisterId: canisterId.toText(),
cmcAccountIdentifierHex,
transaction: nonTopupTransaction,
}
);
});

it("should ignore errors on notifying", async () => {
const blockHeight = 34n;
const memo = 0x50555054n; // TPUP
const topupTransaction = createTransactionWithId({
id: blockHeight,
memo,
});

const spyConsoleError = vi.spyOn(console, "error").mockReturnValue();

const spyGetTransactions = vi.spyOn(icpIndexApi, "getTransactions");
spyGetTransactions.mockResolvedValue({
balance: 100_000_000n,
transactions: [topupTransaction],
});

const error = new Error("Notify in progress");
spyNotifyTopUpCanister.mockRejectedValue(error);

const result = await notifyTopUpIfNeeded({
canisterId,
});

expect(result).toBe(true);

expect(spyConsoleError).toBeCalledTimes(1);
expect(spyConsoleError).toBeCalledWith(error);
});
});
});