Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 1 addition & 2 deletions app/(protected)/(tabs)/card/collateral-order.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { type CollateralOrderPreviewShop, useCollateralOrder } from '@/hooks/use
import { showErrorToast } from '@/lib/errors';
import {
type CollateralAssetKey,
DEFAULT_COLLATERAL_ORDER,
sameCollateralOrder,
visibleCollateralOrder,
withVisibleCollateralOrder,
Expand Down Expand Up @@ -97,7 +96,7 @@ export default function CollateralOrderScreen() {
note="Euro shops lock your EUR Yield first and dollar shops your USD Yield. For any other currency, your card follows this order. Collateral that’s already locked stays locked."
list={list}
preview={<CollateralOrderPreview draft={current} shop={shop} onShopChange={setShop} />}
onReset={() => setDraft([...DEFAULT_COLLATERAL_ORDER])}
onReset={() => setDraft([...saved.defaultOrder])}
canReset={isReady}
onSave={handleSave}
canSave={canSave}
Expand Down
173 changes: 166 additions & 7 deletions components/Card/CollateralOrder/__tests__/collateralOrder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ const CBBTC = '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf' as Address;
const SOBTC = '0x49d88bd2b250d57fc2c14a16a3420fb149078d00' as Address;
const WBTC = '0x0555e30da8f98308edb960aa94c0db47230d2b9c' as Address;
const AAVE = '0x63706e401c06ac8513145b7687A14804d17f814b' as Address;
const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' as Address;
const BASE_USDT = '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2' as Address;
const BASE_EURC = '0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42' as Address;
const FUSE_USDC_E = '0xc6Bc407706B7140EE8Eef2f86F9504651b63e7f9' as Address;
const FUSE_USDT = '0x68c9736781E9316ebf5c3d49FE0C1f45D2D104Cd' as Address;
const LTV_90 = 900_000_000_000_000_000n;

const asset = (overrides: Partial<CreditCollateralAsset>): CreditCollateralAsset => ({
Expand Down Expand Up @@ -90,6 +95,9 @@ describe('collateral order keys', () => {
expect(DEFAULT_COLLATERAL_ORDER).toEqual([
'USD_YIELD',
'EUR_YIELD',
'USDC',
'USDT',
'EURC',
'BTC',
'BTC_YIELD',
'WBTC',
Expand All @@ -105,6 +113,9 @@ describe('collateral order keys', () => {
it.each([
['soUSD', 'USD_YIELD'],
['soEUR', 'EUR_YIELD'],
['USDC', 'USDC'],
['USDT', 'USDT'],
['EURC', 'EURC'],
['cbBTC', 'BTC'],
['soBTC', 'BTC_YIELD'],
['WBTC', 'WBTC'],
Expand All @@ -117,9 +128,24 @@ describe('collateral order keys', () => {
expect(collateralAssetKeyOf(symbol)).toBe(key);
});

it('keys the stables on Base', () => {
expect(collateralAssetKeyOf('USDC', 8453)).toBe('USDC');
expect(collateralAssetKeyOf('USDT', 8453)).toBe('USDT');
expect(collateralAssetKeyOf('EURC', 8453)).toBe('EURC');
});

it('never keys a Fuse stable: USDC.e and USDT are spendable there, not collateral', () => {
expect(collateralAssetKeyOf('USDC.e')).toBeUndefined();
expect(collateralAssetKeyOf('USDC.e', 122)).toBeUndefined();
expect(collateralAssetKeyOf('USDT', 122)).toBeUndefined();
expect(collateralAssetKeyOf('USDC', 122)).toBeUndefined();
// soUSD is collateral on both, so the chain does not change its key.
expect(collateralAssetKeyOf('soUSD', 122)).toBe('USD_YIELD');
expect(collateralAssetKeyOf('soUSD', 8453)).toBe('USD_YIELD');
});

it('has no key for a token the card cannot lock', () => {
expect(collateralAssetKeyOf('USDC')).toBeUndefined();
expect(collateralAssetKeyOf('EURC')).toBeUndefined();
expect(collateralAssetKeyOf('FUSE')).toBeUndefined();
expect(collateralAssetKeyOf(undefined)).toBeUndefined();
});
});
Expand All @@ -135,22 +161,98 @@ describe('normalizeCollateralOrder', () => {
});

it('collapses duplicates and drops keys that are not collateral or not known', () => {
const order = normalizeCollateralOrder(['BTC', 'BTC', 'USDC', 'NOPE', 'USD_YIELD']);
const order = normalizeCollateralOrder(['BTC', 'BTC', 'FUSE', 'NOPE', 'USD_YIELD']);

expect(order.indexOf('BTC')).toBeLessThan(order.indexOf('USD_YIELD'));
expect(order).toHaveLength(DEFAULT_COLLATERAL_ORDER.length);
expect(new Set(order).size).toBe(DEFAULT_COLLATERAL_ORDER.length);
expect(order).not.toContain('USDC');
expect(order).not.toContain('FUSE');
});

it('slots the stables into an order saved before they were collateral, after EUR Yield', () => {
// The default before USDC, USDT and EURC were collateral.
const saved = [
'USD_YIELD',
'EUR_YIELD',
'BTC',
'BTC_YIELD',
'WBTC',
'ETH',
'ETH_YIELD',
'SOL',
'AAVE',
'ZEC',
];

expect(normalizeCollateralOrder(saved)).toEqual([...DEFAULT_COLLATERAL_ORDER]);
});

it('keeps a customised older order and slots the stables in front of the key after them', () => {
const order = normalizeCollateralOrder([
'EUR_YIELD',
'USD_YIELD',
'SOL',
'BTC',
'BTC_YIELD',
'WBTC',
'ETH',
'ETH_YIELD',
'AAVE',
'ZEC',
]);

expect(order).toEqual([
'EUR_YIELD',
'USD_YIELD',
'SOL',
'USDC',
'USDT',
'EURC',
'BTC',
'BTC_YIELD',
'WBTC',
'ETH',
'ETH_YIELD',
'AAVE',
'ZEC',
]);
});

it('puts a key a partial order leaves out at its default place', () => {
// EUR_YIELD comes before BTC by default, so it lands in front of it.
// EUR_YIELD and the stables come before BTC by default, so they land in front of it, in
// default order.
const order = normalizeCollateralOrder(['SOL', 'BTC', 'USD_YIELD']);
const btc = order.indexOf('BTC');

expect(order.indexOf('EUR_YIELD')).toBe(order.indexOf('BTC') - 1);
expect(order.slice(btc - 4, btc)).toEqual(['EUR_YIELD', 'USDC', 'USDT', 'EURC']);
expect(order.indexOf('SOL')).toBeLessThan(order.indexOf('BTC'));
expect(order.indexOf('BTC')).toBeLessThan(order.indexOf('USD_YIELD'));
});

it('never adds or keeps a key the backend does not name', () => {
// A backend from before the stables: its default has none of them, and it rejects a saved
// list that names one with a 400.
const known = DEFAULT_COLLATERAL_ORDER.filter(
key => key !== 'USDC' && key !== 'USDT' && key !== 'EURC',
);

const order = normalizeCollateralOrder(['SOL', 'USDT', 'BTC', 'USD_YIELD'], known);

expect(order).toHaveLength(known.length);
expect(order).not.toContain('USDC');
expect(order).not.toContain('USDT');
expect(order).not.toContain('EURC');
// With no stables to place, EUR_YIELD lands right in front of BTC again.
expect(order.indexOf('EUR_YIELD')).toBe(order.indexOf('BTC') - 1);
});

it('adds the stables once the backend names them', () => {
const order = normalizeCollateralOrder(['SOL', 'BTC'], [...DEFAULT_COLLATERAL_ORDER]);

expect([...order].sort()).toEqual([...DEFAULT_COLLATERAL_ORDER].sort());
const btc = order.indexOf('BTC');
expect(order.slice(btc - 3, btc)).toEqual(['USDC', 'USDT', 'EURC']);
});
});

describe('sameCollateralOrder', () => {
Expand Down Expand Up @@ -206,6 +308,9 @@ describe('the listed order', () => {
expect(next).toEqual([
'SOL',
'EUR_YIELD',
'USDC',
'USDT',
'EURC',
'USD_YIELD',
'BTC_YIELD',
'WBTC',
Expand Down Expand Up @@ -337,11 +442,65 @@ describe('buildCollateralOrderRows', () => {
it('lists nothing before the credit reads answer, and skips tokens with no key', () => {
expect(buildCollateralOrderRows(undefined).size).toBe(0);
const rows = buildCollateralOrderRows({
fuse: instance(122, [asset({ symbol: 'USDC' })]),
fuse: instance(122, [asset({ symbol: 'FUSE' })]),
base: null,
});
expect(rows.size).toBe(0);
});

it('lists the Base stables as collateral: USDC and USDT in dollars, EURC in euros', () => {
const rows = buildCollateralOrderRows({
fuse: null,
base: instance(8453, [
asset({ chainId: 8453, token: BASE_USDC, symbol: 'USDC', decimals: 6 }),
asset({
chainId: 8453,
token: BASE_USDT,
symbol: 'USDT',
decimals: 6,
amount: 12_000_000n,
valueUsd: 12_000_000n,
}),
asset({
chainId: 8453,
token: BASE_EURC,
symbol: 'EURC',
decimals: 6,
amount: 70_000_000n,
valueUsd: 81_600_000n,
valueEur: 70_000_000n,
}),
]),
});

expect([...rows.keys()].sort()).toEqual(['EURC', 'USDC', 'USDT']);
expect(rows.get('USDC')).toMatchObject({
name: 'USDC',
icon: 'usdc',
value: '$0.00',
subtitle: 'LTV 90%',
});
expect(rows.get('USDT')).toMatchObject({ name: 'USDT', icon: 'usdt', value: '$12.00' });
expect(rows.get('EURC')).toMatchObject({
name: 'EURC',
icon: 'eurc',
value: '€70.00',
detail: '≈ $81.60',
});
});

it('never lists Fuse USDC.e or USDT, even if Fuse listed them', () => {
const rows = buildCollateralOrderRows({
fuse: instance(122, [
asset({}),
asset({ token: FUSE_USDC_E, symbol: 'USDC.e', decimals: 6 }),
asset({ token: FUSE_USDT, symbol: 'USDT', decimals: 6 }),
]),
base: null,
});

expect([...rows.keys()]).toEqual(['USD_YIELD']);
});
});

describe('the collateral preview', () => {
Expand Down
2 changes: 1 addition & 1 deletion components/Card/CollateralOrder/collateralOrderRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const buildCollateralOrderRows = (
].filter(asset => asset.listedAsCollateral);
const byKey = new Map<CollateralAssetKey, CreditCollateralAsset[]>();
for (const asset of accepted) {
const key = collateralAssetKeyOf(asset.symbol);
const key = collateralAssetKeyOf(asset.symbol, asset.chainId);
if (!key) continue;
byKey.set(key, [...(byKey.get(key) ?? []), asset]);
}
Expand Down
2 changes: 1 addition & 1 deletion components/Card/Credit/AdditionalCollateral.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export const AdditionalCollateral = ({
knownKeys.add(key);
return true;
}),
asset => collateralAssetKeyOf(asset.symbol),
asset => collateralAssetKeyOf(asset.symbol, asset.chainId),
DEFAULT_COLLATERAL_ORDER,
);
const rows = [
Expand Down
10 changes: 5 additions & 5 deletions components/Card/Credit/CreditSheetViews.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
type LoanModel,
type LoanRisk,
quoteUnlock,
steadyAssetsLabel,
unitsCeil,
type UnlockQuote,
WAD,
Expand Down Expand Up @@ -214,6 +215,8 @@ export const BreakdownView = ({
}) => {
const together = loan.risk.kind === 'multi' ? loan.risk.togetherDrop : undefined;
const payDown = loan.payDown;
// "Yield assets", "stablecoins" or both: what is held steady against the crypto.
const steady = steadyAssetsLabel(loan.assets.filter(asset => asset.steady));

return (
<>
Expand All @@ -223,18 +226,15 @@ export const BreakdownView = ({
{together === null ? (
<Note>
<Text className="text-[14px] leading-[20px] text-white/80">
Your Yield assets cover this loan on their own, so a fall in your crypto can’t put it at
risk.
{`Your ${steady} cover this loan on their own, so a fall in your crypto can’t put it at risk.`}
</Text>
</Note>
) : together !== undefined ? (
<Note>
<Text className="text-[14px] leading-[20px] text-white/80">
{'Your crypto can fall '}
<Text className="font-semibold text-white">{formatFraction(together)}</Text>
{
' together before part of this loan can be sold. Yield assets are held steady in this figure.'
}
{` together before part of this loan can be sold. ${steady.charAt(0).toUpperCase()}${steady.slice(1)} are held steady in this figure.`}
</Text>
</Note>
) : null}
Expand Down
4 changes: 3 additions & 1 deletion components/Card/Credit/LoanCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
type LoanAsset,
type LoanModel,
type LoanSale,
steadyAssetsLabel,
valueOf,
} from '@/lib/creditRisk';

Expand Down Expand Up @@ -109,8 +110,9 @@ const riskSentence = (
}
if (risk.kind === 'multi') {
if (risk.togetherDrop === null) {
const steady = steadyAssetsLabel(loan.assets.filter(asset => asset.steady));
return [
'Your Yield assets cover this loan on their own, so a fall in your crypto can’t put it at risk.',
`Your ${steady} cover this loan on their own, so a fall in your crypto can’t put it at risk.`,
];
}
return [
Expand Down
3 changes: 2 additions & 1 deletion components/Card/Credit/collateralDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { collateralAssetKeyOf } from '@/lib/utils/collateralOrder';
import type { CollateralCatalogAsset, CreditCollateralAsset } from '@/hooks/useCardCreditPositions';

export const collateralDiscoveryKey = (asset: CollateralCatalogAsset): string =>
collateralAssetKeyOf(asset.symbol) ?? `${asset.chainId}:${asset.token.toLowerCase()}`;
collateralAssetKeyOf(asset.symbol, asset.chainId) ??
`${asset.chainId}:${asset.token.toLowerCase()}`;

/** One recommendation per asset, using the first eligible instance in the given order. */
export const findAdditionalCollateral = (
Expand Down
13 changes: 8 additions & 5 deletions components/Card/Credit/useCreditDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import {
buildLoan,
type LoanModel,
type LoanStatus,
STEADY_SYMBOLS,
WAD,
worstStatus,
YIELD_SYMBOLS,
} from '@/lib/creditRisk';
import { collateralAssetKeyOf, sortByCollateralOrder } from '@/lib/utils/collateralOrder';

Expand Down Expand Up @@ -100,11 +100,14 @@ const formatEuro = (amount: bigint) =>
maximumFractionDigits: 2,
});

/** Held balances and the default Yield rows. Discovery takes eligible zero-balance rows below. */
/**
* Held balances and the default Yield rows. Discovery takes eligible zero-balance rows below —
* the Base stablecoins among them, which are listed here only when held.
*/
const listsAsset = (asset: CreditCollateralAsset): boolean =>
asset.amount > 0n ||
// soUSD on Base only when held: otherwise a second "$0.00" USD Yield row beside Fuse's.
(STEADY_SYMBOLS.includes(asset.symbol) &&
(YIELD_SYMBOLS.includes(asset.symbol) &&
!(asset.symbol === 'soUSD' && asset.chainId !== fuseChain.id));

const collateralEntry = (
Expand All @@ -130,7 +133,7 @@ const collateralEntry = (
: `${lockedValue} locked`,
terms:
asset.ltvWad > 0n && asset.countsTowardPower
? `LTV ${percentOf(asset.ltvWad)}${STEADY_SYMBOLS.includes(asset.symbol) ? ' · keeps earning' : ''}`
? `LTV ${percentOf(asset.ltvWad)}${YIELD_SYMBOLS.includes(asset.symbol) ? ' · keeps earning' : ''}`
: 'Not used for borrowing',
};
};
Expand Down Expand Up @@ -206,7 +209,7 @@ export const useCreditDetails = (): CreditDetails => {
);
const collateral = sortByCollateralOrder(
instances.flatMap(position => position.collateral),
asset => collateralAssetKeyOf(asset.symbol),
asset => collateralAssetKeyOf(asset.symbol, asset.chainId),
figures.collateralKeys,
);
// A failed or unanswered position read can hide a holding on the other instance.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,9 @@ interface RepaySheetContentProps {
*
* The source list mixes the two ways the module can be paid. Wallet rows are tender tokens the
* Safe holds loose; collateral rows spend what is already escrowed against the loan — soUSD on
* Fuse; soUSD, soETH, soEUR, cbBTC, WETH, SOL, AAVE or cbZEC on Base — which is how someone with nothing loose
* closes a position. The escrow itself is listed under "Collateral locked". The same token can appear twice, so
* Fuse; soUSD, soEUR, USDC, USDT, EURC, soETH, cbBTC, WETH, SOL, AAVE or cbZEC on Base — which is
* how someone with nothing loose closes a position. USDT on Base is collateral but not tender, so
* it is only ever a collateral row. The escrow itself is listed under "Collateral locked". The same token can appear twice, so
* every row and the balance line say which of the two it is.
*
* Nothing here decides what a repayment does — `quoteRepay` does, and the hook runs it again
Expand Down
Loading
Loading