Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
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
21 changes: 21 additions & 0 deletions src/frontend/src/lib/components/loaders/LoaderOisyTrade.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<script lang="ts">
import { OISY_TRADE_ENABLED } from '$env/oisy-trade';
import { authIdentity } from '$lib/derived/auth.derived';
import { loadOisyTrade } from '$lib/services/oisy-trade.services';

// Loads the DEX pairs, supported tokens, balances and orders app-wide (e.g. the
// hero net worth, which counts deposited balances) without visiting the Trading
// tab or the OISY Trade page first. Reactive on the identity.
//
// Gated on the provider flag rather than the `anyTradingProviderEnabled`
// aggregate: this only ever talks to the OISY Trade canister, so it must stay
// off when that provider is, even with the Trading surface kept reachable by
// another one — the same split `TradingList` and `OisyTradeProvider` make.
$effect(() => {
if (!OISY_TRADE_ENABLED) {
return;
}

loadOisyTrade({ identity: $authIdentity });
Comment thread
sbpublic marked this conversation as resolved.
Outdated
Comment thread
sbpublic marked this conversation as resolved.
Outdated
});
</script>
3 changes: 3 additions & 0 deletions src/frontend/src/lib/components/loaders/Loaders.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import LoaderHarvest from '$lib/components/loaders/LoaderHarvest.svelte';
import LoaderLiquidium from '$lib/components/loaders/LoaderLiquidium.svelte';
import LoaderMetamask from '$lib/components/loaders/LoaderMetamask.svelte';
import LoaderOisyTrade from '$lib/components/loaders/LoaderOisyTrade.svelte';
import LoaderSwapTokens from '$lib/components/loaders/LoaderSwapTokens.svelte';
import LoaderTokens from '$lib/components/loaders/LoaderTokens.svelte';
import LoaderUserProfile from '$lib/components/loaders/LoaderUserProfile.svelte';
Expand Down Expand Up @@ -62,6 +63,8 @@

<LoaderLiquidium />

<LoaderOisyTrade />

<LoaderSwapTokens />

{@render children()}
Expand Down
13 changes: 13 additions & 0 deletions src/frontend/src/lib/services/oisy-trade.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
OISY_TRADE_MAX_ORDER_PAGES,
OISY_TRADE_ORDERS_PAGE_SIZE
} from '$lib/constants/oisy-trade.constants';
import { authIdentity } from '$lib/derived/auth.derived';
import { ProgressStepsTradingWithdraw } from '$lib/enums/progress-steps';
import { i18n } from '$lib/stores/i18n.store';
import { oisyTradeStore } from '$lib/stores/oisy-trade.store';
Expand Down Expand Up @@ -76,6 +77,14 @@ const loadMyOrders = async ({
return orders;
};

// The load is fire-and-forget and app-wide (`LoaderOisyTrade`), so a request
// started for one identity can resolve after a sign-out has already reset the
// store — or after a newer load has written. Re-reading `authIdentity` at the
// commit point and dropping a result whose principal is no longer the current
// one keeps the store from being repopulated with the previous account's data.
const isCurrentIdentity = (identity: NonNullable<NullishIdentity>): boolean =>
get(authIdentity)?.getPrincipal().toText() === identity.getPrincipal().toText();

// Best-effort load of trading pairs, supported tokens and the caller's DEX
// balances into `oisyTradeStore`; errors are logged so a transient canister
// failure never breaks the Trading tab. Read-only.
Expand All @@ -97,6 +106,10 @@ export const loadOisyTrade = async ({ identity }: { identity: NullishIdentity })
loadMyOrders({ identity, nullishIdentityErrorMessage })
]);

if (!isCurrentIdentity(identity)) {
return;
Comment thread
sbpublic marked this conversation as resolved.
Outdated
}

oisyTradeStore.set({ pairs, supportedTokens, balances, orders });
} catch (err: unknown) {
consoleError(err);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import LoaderOisyTrade from '$lib/components/loaders/LoaderOisyTrade.svelte';
import { mockAuthStore } from '$tests/mocks/auth.mock';
import { mockIdentity } from '$tests/mocks/identity.mock';
import { render, waitFor } from '@testing-library/svelte';

const { mockTradingEnabled, mockProviderEnabled, mockLoadOisyTrade } = vi.hoisted(() => ({
mockTradingEnabled: { value: true },
mockProviderEnabled: { value: true },
mockLoadOisyTrade: vi.fn(() => Promise.resolve(undefined))
}));

// The two flags are mocked independently, as `OisyTradeProvider.svelte.spec.ts`
// does: the codebase models the Trading surface staying reachable through
// another provider while OISY TRADE itself is off, and this loader must follow
// the provider flag, not the aggregate.
vi.mock('$env/trading', () => ({
get anyTradingProviderEnabled() {
return mockTradingEnabled.value;
}
}));

vi.mock('$env/oisy-trade', () => ({
get OISY_TRADE_ENABLED() {
return mockProviderEnabled.value;
}
}));

vi.mock('$lib/services/oisy-trade.services', () => ({
loadOisyTrade: mockLoadOisyTrade
}));

describe('LoaderOisyTrade', () => {
beforeEach(() => {
vi.clearAllMocks();

mockTradingEnabled.value = true;
mockProviderEnabled.value = true;
});

it('should load the OISY Trade data when an identity is available', async () => {
mockAuthStore();

render(LoaderOisyTrade);

await waitFor(() => {
expect(mockLoadOisyTrade).toHaveBeenCalledExactlyOnceWith({ identity: mockIdentity });
});
});

// Signed out, `loadOisyTrade` resets the store, so the loader must still call it.
it('should call the loader with a nullish identity when signed out', async () => {
mockAuthStore(null);

render(LoaderOisyTrade);

await waitFor(() => {
expect(mockLoadOisyTrade).toHaveBeenCalledExactlyOnceWith({ identity: null });
});
});

it('should not load anything when the OISY Trade provider is disabled', () => {
mockProviderEnabled.value = false;
mockAuthStore();

render(LoaderOisyTrade);

expect(mockLoadOisyTrade).not.toHaveBeenCalled();
});

it('should not load anything when OISY Trade is off but another provider keeps the surface on', () => {
mockTradingEnabled.value = true;
mockProviderEnabled.value = false;
mockAuthStore();

render(LoaderOisyTrade);

expect(mockLoadOisyTrade).not.toHaveBeenCalled();
});
});
79 changes: 66 additions & 13 deletions src/frontend/src/tests/lib/services/oisy-trade.services.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import {
withdrawFromOisyTrade
} from '$lib/services/oisy-trade.services';
import { oisyTradeStore } from '$lib/stores/oisy-trade.store';
import { mockIdentity } from '$tests/mocks/identity.mock';
import { mockAuthStore } from '$tests/mocks/auth.mock';
import { mockIdentity, mockPrincipal2 } from '$tests/mocks/identity.mock';
import type { Identity } from '@icp-sdk/core/agent';
import { Principal } from '@icp-sdk/core/principal';
import { get } from 'svelte/store';

Expand All @@ -37,9 +39,22 @@ describe('oisy-trade.services', () => {
const balances = [{ balance: { free: 1n, reserved: ZERO } }] as unknown as UserTokenBalance[];
const orders = [{ id: 'order-1' }] as unknown as UserOrder[];

const resetStoreValue = {
pairs: undefined,
supportedTokens: undefined,
balances: undefined,
orders: undefined
};

// A second signed-in account, to drive the identity-transition guard.
const otherIdentity = { getPrincipal: () => mockPrincipal2 } as unknown as Identity;

beforeEach(() => {
vi.clearAllMocks();
oisyTradeStore.reset();
// The store commit is guarded on the identity still being the current one,
// so the loading identity has to be the signed-in one for a write to land.
mockAuthStore();
vi.mocked(oisyTradeApi.getTradingPairs).mockResolvedValue(pairs);
vi.mocked(oisyTradeApi.listSupportedTokens).mockResolvedValue(supportedTokens);
vi.mocked(oisyTradeApi.getBalances).mockResolvedValue(balances);
Expand All @@ -53,12 +68,7 @@ describe('oisy-trade.services', () => {

await loadOisyTrade({ identity: null });

expect(get(oisyTradeStore)).toEqual({
pairs: undefined,
supportedTokens: undefined,
balances: undefined,
orders: undefined
});
expect(get(oisyTradeStore)).toEqual(resetStoreValue);
expect(oisyTradeApi.getTradingPairs).not.toHaveBeenCalled();
});

Expand Down Expand Up @@ -135,12 +145,55 @@ describe('oisy-trade.services', () => {

await expect(loadOisyTrade({ identity: mockIdentity })).resolves.toBeUndefined();

expect(get(oisyTradeStore)).toEqual({
pairs: undefined,
supportedTokens: undefined,
balances: undefined,
orders: undefined
});
expect(get(oisyTradeStore)).toEqual(resetStoreValue);
});

it('does not repopulate the store when the load resolves after a sign-out', async () => {
let resolveBalances: (value: UserTokenBalance[]) => void = () => undefined;
vi.mocked(oisyTradeApi.getBalances).mockReturnValue(
new Promise<UserTokenBalance[]>((resolve) => {
resolveBalances = resolve;
})
);

// The signed-in load is still in flight when the user signs out.
const pending = loadOisyTrade({ identity: mockIdentity });

mockAuthStore(null);
await loadOisyTrade({ identity: null });

expect(get(oisyTradeStore)).toEqual(resetStoreValue);

// The older request resolves last — it must not undo the reset.
resolveBalances(balances);
await pending;

expect(get(oisyTradeStore)).toEqual(resetStoreValue);
});

it('does not overwrite a newer account when the older load resolves last', async () => {
const otherBalances = [
{ balance: { free: 2n, reserved: ZERO } }
] as unknown as UserTokenBalance[];

let resolveBalances: (value: UserTokenBalance[]) => void = () => undefined;
vi.mocked(oisyTradeApi.getBalances).mockReturnValueOnce(
new Promise<UserTokenBalance[]>((resolve) => {
resolveBalances = resolve;
})
);

const pending = loadOisyTrade({ identity: mockIdentity });

// The second account signs in and its load completes first.
mockAuthStore(otherIdentity);
vi.mocked(oisyTradeApi.getBalances).mockResolvedValue(otherBalances);
await loadOisyTrade({ identity: otherIdentity });

resolveBalances(balances);
await pending;

expect(get(oisyTradeStore).balances).toEqual(otherBalances);
});
});

Expand Down
Loading