diff --git a/app/(protected)/(tabs)/card/collateral-order.tsx b/app/(protected)/(tabs)/card/collateral-order.tsx index 6efc394f2..56592be34 100644 --- a/app/(protected)/(tabs)/card/collateral-order.tsx +++ b/app/(protected)/(tabs)/card/collateral-order.tsx @@ -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, @@ -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={} - onReset={() => setDraft([...DEFAULT_COLLATERAL_ORDER])} + onReset={() => setDraft([...saved.defaultOrder])} canReset={isReady} onSave={handleSave} canSave={canSave} diff --git a/components/Card/CollateralOrder/__tests__/collateralOrder.test.ts b/components/Card/CollateralOrder/__tests__/collateralOrder.test.ts index c8bb3741a..10e26d814 100644 --- a/components/Card/CollateralOrder/__tests__/collateralOrder.test.ts +++ b/components/Card/CollateralOrder/__tests__/collateralOrder.test.ts @@ -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 => ({ @@ -90,6 +95,9 @@ describe('collateral order keys', () => { expect(DEFAULT_COLLATERAL_ORDER).toEqual([ 'USD_YIELD', 'EUR_YIELD', + 'USDC', + 'USDT', + 'EURC', 'BTC', 'BTC_YIELD', 'WBTC', @@ -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'], @@ -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(); }); }); @@ -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', () => { @@ -206,6 +308,9 @@ describe('the listed order', () => { expect(next).toEqual([ 'SOL', 'EUR_YIELD', + 'USDC', + 'USDT', + 'EURC', 'USD_YIELD', 'BTC_YIELD', 'WBTC', @@ -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', () => { diff --git a/components/Card/CollateralOrder/collateralOrderRows.ts b/components/Card/CollateralOrder/collateralOrderRows.ts index 4316162e9..3e54c1ed5 100644 --- a/components/Card/CollateralOrder/collateralOrderRows.ts +++ b/components/Card/CollateralOrder/collateralOrderRows.ts @@ -70,7 +70,7 @@ export const buildCollateralOrderRows = ( ].filter(asset => asset.listedAsCollateral); const byKey = new Map(); 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]); } diff --git a/components/Card/Credit/AdditionalCollateral.tsx b/components/Card/Credit/AdditionalCollateral.tsx index 0a6197d0d..e18199612 100644 --- a/components/Card/Credit/AdditionalCollateral.tsx +++ b/components/Card/Credit/AdditionalCollateral.tsx @@ -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 = [ diff --git a/components/Card/Credit/CreditSheetViews.tsx b/components/Card/Credit/CreditSheetViews.tsx index 154a926aa..a79b004c0 100644 --- a/components/Card/Credit/CreditSheetViews.tsx +++ b/components/Card/Credit/CreditSheetViews.tsx @@ -30,6 +30,7 @@ import { type LoanModel, type LoanRisk, quoteUnlock, + steadyAssetsLabel, unitsCeil, type UnlockQuote, WAD, @@ -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 ( <> @@ -223,8 +226,7 @@ export const BreakdownView = ({ {together === null ? ( - 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.`} ) : together !== undefined ? ( @@ -232,9 +234,7 @@ export const BreakdownView = ({ {'Your crypto can fall '} {formatFraction(together)} - { - ' 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.`} ) : null} diff --git a/components/Card/Credit/LoanCard.tsx b/components/Card/Credit/LoanCard.tsx index c47ddf629..c6ca0e1fa 100644 --- a/components/Card/Credit/LoanCard.tsx +++ b/components/Card/Credit/LoanCard.tsx @@ -24,6 +24,7 @@ import { type LoanAsset, type LoanModel, type LoanSale, + steadyAssetsLabel, valueOf, } from '@/lib/creditRisk'; @@ -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 [ diff --git a/components/Card/Credit/collateralDiscovery.ts b/components/Card/Credit/collateralDiscovery.ts index 09221bfca..24a9441c5 100644 --- a/components/Card/Credit/collateralDiscovery.ts +++ b/components/Card/Credit/collateralDiscovery.ts @@ -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 = ( diff --git a/components/Card/Credit/useCreditDetails.ts b/components/Card/Credit/useCreditDetails.ts index 6e2925d5e..e094ad1c4 100644 --- a/components/Card/Credit/useCreditDetails.ts +++ b/components/Card/Credit/useCreditDetails.ts @@ -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'; @@ -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 = ( @@ -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', }; }; @@ -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. diff --git a/components/Card/NewCardDetails/SpendMode/RepaySheetContent.tsx b/components/Card/NewCardDetails/SpendMode/RepaySheetContent.tsx index b6f281514..a8479f4d6 100644 --- a/components/Card/NewCardDetails/SpendMode/RepaySheetContent.tsx +++ b/components/Card/NewCardDetails/SpendMode/RepaySheetContent.tsx @@ -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 diff --git a/components/Card/NewCardDetails/SpendMode/SpendModePanels.tsx b/components/Card/NewCardDetails/SpendMode/SpendModePanels.tsx index 9e665e8be..a8c66a61a 100644 --- a/components/Card/NewCardDetails/SpendMode/SpendModePanels.tsx +++ b/components/Card/NewCardDetails/SpendMode/SpendModePanels.tsx @@ -239,6 +239,17 @@ export const CollateralLogo = ({ icon }: { icon: CollateralRowFigures['icon'] }) if (icon === 'eth') { return ; } + // The Base stablecoins: their token logos, drawn as the Cash panel draws them. + if (icon === 'usdc' || icon === 'eurc') { + return ; + } + if (icon === 'usdt') { + return ( + + + + ); + } if (icon === 'usd' || icon === 'eur' || icon === 'cbbtc') { return ( diff --git a/components/Card/NewCardDetails/SpendMode/useCreditModeFigures.ts b/components/Card/NewCardDetails/SpendMode/useCreditModeFigures.ts index 2f6e1fc38..c217f7544 100644 --- a/components/Card/NewCardDetails/SpendMode/useCreditModeFigures.ts +++ b/components/Card/NewCardDetails/SpendMode/useCreditModeFigures.ts @@ -33,11 +33,14 @@ import type { BorrowedSummaryFigures } from '@/components/Card/NewCardDetails/Sp /** * A collateral row's mark: the yield glyphs for Solid's own shares, the token's logo for the - * crypto Base takes as collateral. + * stablecoins and the crypto Base takes as collateral. */ export type CollateralIcon = | 'usd' | 'eur' + | 'usdc' + | 'usdt' + | 'eurc' | 'eth' | 'cbbtc' | 'sobtc' @@ -99,12 +102,16 @@ export interface CreditModeFigures extends BorrowedSummaryFigures { } /** - * What each collateral token is, as the app names it: the savings product for Solid's shares, - * the asset's own name for the crypto Base takes. + * What each collateral token is, as the app names it: the savings product for Solid's shares, the + * ticker for the Base stablecoins (as the spend order names them), the asset's own name for the + * crypto Base takes. Fuse's USDC.e and USDT are never collateral, so never reach these rows. */ export const COLLATERAL_LABEL: Readonly> = { soUSD: { label: 'USD Yield', icon: 'usd' }, soEUR: { label: 'EUR Yield', icon: 'eur' }, + USDC: { label: 'USDC', icon: 'usdc' }, + USDT: { label: 'USDT', icon: 'usdt' }, + EURC: { label: 'EURC', icon: 'eurc' }, soETH: { label: 'ETH Yield', icon: 'eth' }, cbBTC: { label: 'Bitcoin', icon: 'cbbtc' }, soBTC: { label: 'BTC Yield', icon: 'sobtc' }, @@ -264,7 +271,7 @@ export const combineCreditFigures = ( ...(positions?.fuse?.collateral ?? []), ...(positions?.base?.collateral ?? []), ].filter(asset => asset.listedAsCollateral); - const keyOf = (asset: CreditCollateralAsset) => collateralAssetKeyOf(asset.symbol); + const keyOf = (asset: CreditCollateralAsset) => collateralAssetKeyOf(asset.symbol, asset.chainId); const lockable = new Set( accepted.map(keyOf).filter((key): key is CollateralAssetKey => key !== undefined), ); diff --git a/components/Card/NewCardDetails/__tests__/combineCreditFigures.test.ts b/components/Card/NewCardDetails/__tests__/combineCreditFigures.test.ts index bf51b358e..35e2e19aa 100644 --- a/components/Card/NewCardDetails/__tests__/combineCreditFigures.test.ts +++ b/components/Card/NewCardDetails/__tests__/combineCreditFigures.test.ts @@ -423,6 +423,108 @@ describe('combineCreditFigures', () => { ]); }); }); + describe('Base stablecoin collateral rows', () => { + const BASE_USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; + const BASE_USDT = '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2'; + const BASE_EURC = '0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42'; + const FUSE_USDC_E = '0xc6Bc407706B7140EE8Eef2f86F9504651b63e7f9'; + const FUSE_USDT = '0x68c9736781E9316ebf5c3d49FE0C1f45D2D104Cd'; + const stable = ( + token: string, + symbol: string, + overrides: Partial = {}, + ) => asset({ chainId: 8453, token: token as `0x${string}`, symbol, decimals: 6, ...overrides }); + + it('lists USDC, USDT and EURC when held, by ticker and logo, EURC in euros', () => { + const figures = combineCreditFigures(noFuseDebt, RATE, { + fuse: null, + base: baseLoan({ + collateral: [ + stable(BASE_EURC, 'EURC', { + amount: 70_000_000n, + valueUsd: 81_600_000n, + valueEur: 70_000_000n, + }), + stable(BASE_USDT, 'USDT', { amount: 5_000_000n, valueUsd: 5_000_000n }), + stable(BASE_USDC, 'USDC', { amount: 20_000_000n, valueUsd: 20_000_000n }), + ], + }), + }); + + // In the default lock order: USDC, USDT, then EURC. + expect( + figures.collateral.map(row => [row.label, row.icon, row.value, row.usdEquivalent, row.ltv]), + ).toEqual([ + ['USDC', 'usdc', '$20.00', undefined, 'LTV 90%'], + ['USDT', 'usdt', '$5.00', undefined, 'LTV 90%'], + ['EURC', 'eurc', '€70.00', '≈ $81.60', 'LTV 90%'], + ]); + expect(figures.collateralKeys).toEqual(['USDC', 'USDT', 'EURC']); + }); + + it('offers the stables to order when unheld, without a $0.00 row for each', () => { + const figures = combineCreditFigures(noFuseDebt, RATE, { + fuse: null, + base: baseLoan({ + collateral: [ + asset({ chainId: 8453, token: SOEUR, symbol: 'soEUR' }), + stable(BASE_USDC, 'USDC'), + stable(BASE_EURC, 'EURC'), + ], + }), + }); + + expect(figures.collateral.map(row => row.label)).toEqual(['EUR Yield']); + expect(figures.collateralKeys).toEqual(['EUR_YIELD', 'USDC', 'EURC']); + }); + + it('never lists Fuse USDC.e or USDT as collateral', () => { + const figures = combineCreditFigures(fusePosition, RATE, { + fuse: instance({ + collateral: [ + asset({}), + asset({ + token: FUSE_USDC_E, + symbol: 'USDC.e', + decimals: 6, + amount: 1n, + valueUsd: 1n, + listedAsCollateral: false, + countsTowardPower: false, + }), + asset({ + token: FUSE_USDT, + symbol: 'USDT', + decimals: 6, + amount: 1n, + valueUsd: 1n, + listedAsCollateral: false, + countsTowardPower: false, + }), + ], + }), + base: null, + }); + + expect(figures.collateral.map(row => row.label)).toEqual(['USD Yield']); + expect(figures.collateralKeys).toEqual(['USD_YIELD']); + }); + + it('names the stables in what a loan is backed by', () => { + const figures = combineCreditFigures(noFuseDebt, RATE, { + fuse: null, + base: baseLoan({ + debtUsd: 10_000_000n, + collateral: [ + stable(BASE_USDC, 'USDC', { amount: 30_000_000n, valueUsd: 30_000_000n }), + stable(BASE_EURC, 'EURC', { amount: 10_000_000n, valueUsd: 11_000_000n }), + ], + }), + }); + + expect(figures.positions.map(loan => loan.backedBy)).toEqual(['USDC and EURC']); + }); + }); describe('the collateral order', () => { const BASE_SOBTC = '0x49d88bd2b250d57fc2c14a16a3420fb149078d00'; const BASE_WBTC = '0x0555e30da8f98308edb960aa94c0db47230d2b9c'; diff --git a/hooks/useCardCreditPositions.ts b/hooks/useCardCreditPositions.ts index 641e3b37f..bb9dc1266 100644 --- a/hooks/useCardCreditPositions.ts +++ b/hooks/useCardCreditPositions.ts @@ -40,8 +40,8 @@ const LENS_MODULE_ABI = [ }, ] as const; -/** Collateral denominated in euros, shown in euros first. */ -const EURO_COLLATERAL_SYMBOLS: readonly string[] = ['soEUR']; +/** Collateral denominated in euros, shown in euros first: soEUR, and EURC on Base. */ +const EURO_COLLATERAL_SYMBOLS: readonly string[] = ['soEUR', 'EURC']; /** What a euro collateral is converted through: the same instance's own EURC price. */ const EURC_SYMBOL = 'EURC'; diff --git a/hooks/useCollateralOrder.ts b/hooks/useCollateralOrder.ts index e20fe9453..d1557f6e9 100644 --- a/hooks/useCollateralOrder.ts +++ b/hooks/useCollateralOrder.ts @@ -46,7 +46,20 @@ export const useCollateralOrder = () => { const order = useMemo( () => query.data?.collateralOrder - ? normalizeCollateralOrder(query.data.collateralOrder) + ? // Only keys this backend accepts: it rejects a saved list naming one it does not know. + normalizeCollateralOrder(query.data.collateralOrder, query.data.defaultCollateralOrder) + : [...DEFAULT_COLLATERAL_ORDER], + [query.data], + ); + + /** The backend's default order, cut to keys it accepts: what Reset puts on screen. */ + const defaultOrder = useMemo( + () => + query.data?.defaultCollateralOrder + ? normalizeCollateralOrder( + query.data.defaultCollateralOrder, + query.data.defaultCollateralOrder, + ) : [...DEFAULT_COLLATERAL_ORDER], [query.data], ); @@ -75,6 +88,7 @@ export const useCollateralOrder = () => { return { order, + defaultOrder, customized: query.data?.collateralOrderCustomized ?? false, /** * Whether to offer "Edit order": the backend's internal-team cohort decides. Fails closed — @@ -112,6 +126,10 @@ export const COLLATERAL_ORDER_PREVIEW_PURCHASE = SPEND_ORDER_PREVIEW_PURCHASE; * contract's lock math — so the preview never shows a lock the card would not make. Debounced, so * dragging a row does not send a request per swap, and the last answer stays on screen while the * next one loads. + * + * Waits for the saved order, and sends only keys it names: until then the draft is this build's own + * default, and a backend older than a key (the stables) rejects a list naming it with a 400. The + * debounced draft can still be that default for a moment after the read answers, hence the filter. */ export const useCollateralOrderPreview = ( draft: readonly CollateralAssetKey[], @@ -119,14 +137,18 @@ export const useCollateralOrderPreview = ( ) => { const { user } = useUser(); const { provider } = useCardProvider(); + const saved = useCollateralOrder(); const debounced = useDebounce(draft, 300); + const order = useMemo( + () => debounced.filter(key => saved.order.includes(key)), + [debounced, saved.order], + ); const purchase = COLLATERAL_ORDER_PREVIEW_PURCHASE[shop]; return useQuery({ - queryKey: [CARD_COLLATERAL_ORDER_PREVIEW_QUERY_KEY, user?.userId, shop, debounced.join(',')], - queryFn: () => - withRefreshToken(() => getCardCollateralOrderPreview({ ...purchase, order: [...debounced] })), - enabled: !!user?.userId && provider === CardProvider.WIREX, + queryKey: [CARD_COLLATERAL_ORDER_PREVIEW_QUERY_KEY, user?.userId, shop, order.join(',')], + queryFn: () => withRefreshToken(() => getCardCollateralOrderPreview({ ...purchase, order })), + enabled: !!user?.userId && provider === CardProvider.WIREX && saved.hasLoaded, placeholderData: keepPreviousData, staleTime: 30_000, retry: 1, diff --git a/hooks/useEuroSpendEnablement.ts b/hooks/useEuroSpendEnablement.ts index 476cbaf8f..2d522b498 100644 --- a/hooks/useEuroSpendEnablement.ts +++ b/hooks/useEuroSpendEnablement.ts @@ -191,9 +191,10 @@ export const useCardSpendDeployments = () => { * * ## Note on the name * - * The Base instance is **dollar-denominated**; EURC is a spendable asset within it and is - * not collateral, so nothing here lends against euros — and lending is not planned. The copy this - * powers says "euro spending", which is exactly what the user gets: spending a euro balance. + * The Base instance is **dollar-denominated**: debt is in dollars. EURC (and soEUR) are spendable + * there and, in Credit mode, also collateral the card can borrow against — but enabling Base is + * what this flow does, and what the cardholder gets from it first is spending a euro balance. So + * the copy this powers says "euro spending" (or "Base spending"), never "lending". */ export const useEuroSpendEnablement = (): EuroSpendEnablement => { const { user, safeAA } = useUser(); diff --git a/lib/__tests__/creditRisk.test.ts b/lib/__tests__/creditRisk.test.ts index f3e74c93f..0f04bde16 100644 --- a/lib/__tests__/creditRisk.test.ts +++ b/lib/__tests__/creditRisk.test.ts @@ -9,6 +9,7 @@ import { quoteUnlock, roundUpToStep, statusOf, + steadyAssetsLabel, UNLOCK_INTEREST_HEADROOM_SECONDS, WAD, } from '@/lib/creditRisk'; @@ -260,6 +261,77 @@ describe('buildLoan — several volatile assets', () => { }); }); +describe('buildLoan — Base stablecoins as collateral', () => { + // USDC, USDT and EURC on Base: LTV 90%, threshold 95%, 5% bonus — soUSD's and soEUR's tier. + const usdcOnly = (debt: number, overrides: Partial = {}) => + position(debt, [asset('USDC', 1_000, 0.9, 0.95)], overrides); + + it('prices a USDC-only loan from cover over debt, and never gives it a sell price', () => { + const loan = buildLoan(usdcOnly(800), NOW); + // cover 950 over 800 owed + expect(loan.coverUsd).toBe(usd(950)); + expect(loan.powerUsd).toBe(usd(900)); + expect(loan.healthFactor).toBeCloseTo(1.1875, 4); + expect(loan.status).toBe('healthy'); + expect(loan.risk).toEqual({ kind: 'steady' }); + expect(loan.assets[0].steady).toBe(true); + expect(loan.assets[0].aloneDrop).toBeNull(); + expect(loan.assets[0].aloneSellPriceUsd).toBeNull(); + expect(loan.penaltyBps).toEqual({ min: 500, max: 500 }); + expect(loanSafetyStatus(loan)).toBe('healthy'); + }); + + it('still warns a USDC-only loan that interest has pushed close to the line', () => { + // 950 / 930 ≈ 1.02: Getting close by health alone, with no price to quote. + const loan = buildLoan(usdcOnly(930), NOW); + expect(loan.status).toBe('caution'); + expect(loan.risk.kind).toBe('steady'); + expect(loan.sale).toBeNull(); + // 950 / 960 < 1.0 + expect(buildLoan(usdcOnly(960), NOW).sale).toEqual({ kind: 'unrecorded' }); + }); + + it('unlocks USDC up to the spare power at its 90% LTV', () => { + const loan = buildLoan(usdcOnly(800), NOW); + // (900 − 800) / 0.9 + expect(freeToUnlock(loan, loan.assets[0])).toEqual({ + amount: 111_111_111n, + valueUsd: 111_111_111n, + }); + }); + + it('holds USDT and EURC steady too, beside soUSD and soEUR', () => { + const loan = buildLoan( + position(500, [ + asset('USDT', 200, 0.9, 0.95), + asset('EURC', 200, 0.9, 0.95), + asset('soUSD', 200, 0.9, 0.95), + ]), + NOW, + ); + expect(loan.assets.every(a => a.steady)).toBe(true); + expect(loan.risk).toEqual({ kind: 'steady' }); + }); + + it('counts a stablecoin as steady cover when one crypto asset can move', () => { + // The design loan with its EUR Yield swapped for the same $81 of USDC: the same sell price. + const loan = buildLoan(position(600, [asset('USDC', 81, 0.9, 0.95), bitcoin(930.23)]), NOW); + expect(loan.risk.kind).toBe('single'); + if (loan.risk.kind !== 'single') return; + expect(loan.risk.asset.symbol).toBe('cbBTC'); + expect(Number(loan.risk.sellPriceUsd) / 1e6).toBeCloseTo(80_325.76, 0); + }); + + it('names what is held steady: Yield assets, stablecoins, or both', () => { + expect(steadyAssetsLabel([])).toBe('Yield assets'); + expect(steadyAssetsLabel([{ symbol: 'soEUR' }])).toBe('Yield assets'); + expect(steadyAssetsLabel([{ symbol: 'USDC' }, { symbol: 'EURC' }])).toBe('stablecoins'); + expect(steadyAssetsLabel([{ symbol: 'soUSD' }, { symbol: 'USDT' }])).toBe( + 'stablecoins and Yield assets', + ); + }); +}); + describe('buildLoan — when a sale can happen', () => { // $723.50 of Bitcoin left: cover 583.40, health ≈ 0.972 const atRisk = (overrides: Partial = {}) => diff --git a/lib/creditRisk.ts b/lib/creditRisk.ts index 0375987c4..35f708a4c 100644 --- a/lib/creditRisk.ts +++ b/lib/creditRisk.ts @@ -52,11 +52,36 @@ export const UNLOCK_REPAY_STEP_USD = 5n * USD; /** Health the module reports for a position with no debt. */ const NO_DEBT_HF = 2n ** 255n; +/** Solid's dollar and euro yield shares: steady, and they keep earning while locked. */ +export const YIELD_SYMBOLS: readonly string[] = ['soUSD', 'soEUR']; + +/** + * The stablecoins Base takes as collateral. USDC and USDT are dollar pegs; EURC moves with the + * euro the way soEUR does, which the module prices and the loan model treats as holding its value. + */ +export const STABLECOIN_COLLATERAL_SYMBOLS: readonly string[] = ['USDC', 'USDT', 'EURC']; + /** - * Yield shares that hold their value: only interest moves a loan backed by these alone. Everything - * else — Bitcoin, ETH, ETH Yield (priced in ETH), the other crypto — can fall. + * Assets that hold their value: only interest moves a loan backed by these alone, so they never + * get a "sold if it falls by N%" price. Everything else — Bitcoin, ETH, ETH Yield (priced in ETH), + * the other crypto — can fall. */ -export const STEADY_SYMBOLS: readonly string[] = ['soUSD', 'soEUR']; +export const STEADY_SYMBOLS: readonly string[] = [ + ...YIELD_SYMBOLS, + ...STABLECOIN_COLLATERAL_SYMBOLS, +]; + +/** + * What a loan's steady assets are called in copy that sets them against the crypto: "Yield + * assets", "stablecoins", or both. Falls back to "Yield assets" when none is locked. + */ +export const steadyAssetsLabel = (assets: readonly Pick[]): string => { + const hasYield = assets.some(asset => YIELD_SYMBOLS.includes(asset.symbol)); + const hasStable = assets.some(asset => STABLECOIN_COLLATERAL_SYMBOLS.includes(asset.symbol)); + if (hasStable && hasYield) return 'stablecoins and Yield assets'; + if (hasStable) return 'stablecoins'; + return 'Yield assets'; +}; export type LoanStatus = 'healthy' | 'caution' | 'at-risk'; diff --git a/lib/utils/collateralOrder.ts b/lib/utils/collateralOrder.ts index 764a742d1..05e2219f0 100644 --- a/lib/utils/collateralOrder.ts +++ b/lib/utils/collateralOrder.ts @@ -1,3 +1,5 @@ +import { base } from 'viem/chains'; + import type { SpendAssetKey } from '@/lib/utils/spendOrder'; /** @@ -9,11 +11,17 @@ import type { SpendAssetKey } from '@/lib/utils/spendOrder'; * * It governs new locks only — the shortfall after what is already escrowed — and the shop's own * yield share still comes first: EUR Yield at a euro shop, USD Yield at a dollar shop. + * + * USDC, USDT and EURC are collateral on Base only (Fuse locks soUSD alone), at soUSD's and soEUR's + * tier: LTV 90%, threshold 95%. */ export type CollateralAssetKey = Extract< SpendAssetKey, | 'USD_YIELD' | 'EUR_YIELD' + | 'USDC' + | 'USDT' + | 'EURC' | 'BTC' | 'BTC_YIELD' | 'WBTC' @@ -31,6 +39,9 @@ export type CollateralAssetKey = Extract< export const DEFAULT_COLLATERAL_ORDER: readonly CollateralAssetKey[] = [ 'USD_YIELD', 'EUR_YIELD', + 'USDC', + 'USDT', + 'EURC', 'BTC', 'BTC_YIELD', 'WBTC', @@ -44,6 +55,10 @@ export const DEFAULT_COLLATERAL_ORDER: readonly CollateralAssetKey[] = [ const KEY_BY_SYMBOL: Readonly> = { soUSD: 'USD_YIELD', soEUR: 'EUR_YIELD', + // Base's native USDC. Fuse's bridged USDC is "USDC.e", which is not collateral and maps to none. + USDC: 'USDC', + USDT: 'USDT', + EURC: 'EURC', cbBTC: 'BTC', soBTC: 'BTC_YIELD', WBTC: 'WBTC', @@ -54,9 +69,26 @@ const KEY_BY_SYMBOL: Readonly> = { cbZEC: 'ZEC', }; -/** The collateral key for a token's symbol ("cbBTC" → `BTC`), or undefined for any other. */ -export const collateralAssetKeyOf = (symbol: string | undefined): CollateralAssetKey | undefined => - symbol ? KEY_BY_SYMBOL[symbol] : undefined; +/** + * The stables, which only the Base instance takes as collateral. Fuse's USDT shares the ticker, so + * a token on any other chain never maps to these. + */ +const BASE_ONLY_KEYS: ReadonlySet = new Set(['USDC', 'USDT', 'EURC']); + +/** + * The collateral key for a token's symbol ("cbBTC" → `BTC`), or undefined for any other. With a + * chain, the stables map on Base only: Fuse USDC.e and USDT are spendable there, never collateral. + */ +export const collateralAssetKeyOf = ( + symbol: string | undefined, + chainId?: number, +): CollateralAssetKey | undefined => { + const key = symbol ? KEY_BY_SYMBOL[symbol] : undefined; + if (key && chainId !== undefined && chainId !== base.id && BASE_ONLY_KEYS.has(key)) { + return undefined; + } + return key; +}; export const isCollateralAssetKey = (value: string): value is CollateralAssetKey => (DEFAULT_COLLATERAL_ORDER as readonly string[]).includes(value); @@ -65,16 +97,27 @@ export const isCollateralAssetKey = (value: string): value is CollateralAssetKey * Every collateral key once, in the given order, with any key it leaves out at its default * position. The backend sends the full list; this keeps the app right against a partial one, and * drops a key this build does not know rather than guessing where it goes. + * + * With `known` (the backend's own `defaultCollateralOrder`), only keys the backend also names are + * kept or added. The order is sent back on Save and in the preview, and a backend older than a key + * rejects the whole list with a 400: the stables reached this build before the backend that + * accepts them. */ export const normalizeCollateralOrder = ( order: readonly string[] | undefined, + known?: readonly string[], ): CollateralAssetKey[] => { - const ranked = [...new Set((order ?? []).filter(isCollateralAssetKey))]; - for (const [index, key] of DEFAULT_COLLATERAL_ORDER.entries()) { + const defaults = known + ? DEFAULT_COLLATERAL_ORDER.filter(key => known.includes(key)) + : DEFAULT_COLLATERAL_ORDER; + const ranked = [ + ...new Set((order ?? []).filter(isCollateralAssetKey).filter(key => defaults.includes(key))), + ]; + for (const [index, key] of defaults.entries()) { if (ranked.includes(key)) continue; // In front of the first ranked key that follows it by default, so a key a newer build added // lands where today's order would put it rather than at the bottom. - const after = DEFAULT_COLLATERAL_ORDER.slice(index + 1).find(next => ranked.includes(next)); + const after = defaults.slice(index + 1).find(next => ranked.includes(next)); ranked.splice(after ? ranked.indexOf(after) : ranked.length, 0, key); } return ranked;