diff --git a/e2e/routes-demo.test.ts b/e2e/routes-demo.test.ts index 4e8ac9533..8cee6f510 100644 --- a/e2e/routes-demo.test.ts +++ b/e2e/routes-demo.test.ts @@ -597,6 +597,8 @@ async function chooseRoute(page: Page, from: [string, string], to: [string, stri await pick(toSelect(page, 'Asset'), to[1]) } const lifecycle = (page: Page) => page.locator('.routes-test-lifecycle') +/** The quote summary: what is sent, what arrives, and any fee. */ +const quoteSummary = (page: Page) => lifecycle(page).locator('dl').first() const button = (page: Page, name: string) => page.getByRole('button', { name, exact: true }) /** A funding method in the Transfer / Deposit address segmented control. */ const method = (page: Page, name: string) => page.getByRole('radio', { name, exact: true }) @@ -675,10 +677,11 @@ test.describe('Routes demo', () => { await openDemo(page) await quoteBaseTransfer(page) - // Transfer fees are charged on top of the routed amount, here in ETH. + // Without 1:1 delivery, the fee is the whole gap between what is sent and what arrives. await expect(lifecycle(page)).toContainText( - 'You send1 USDCRecipient gets0.9991 USDC.eFee0.0001006 ETH', + 'You send1 USDCRecipient gets0.9991 USDC.eFee0.0009 USDC', ) + await expect(quoteSummary(page).getByText('Fee', { exact: true })).toHaveCount(1) const [quote] = api.to('GET', '/v1/routes/transfers/quote') expect(Object.fromEntries(quote.query)).toMatchObject({ amount: '1000000', @@ -782,6 +785,23 @@ test.describe('Routes demo', () => { expect(sent).toEqual({ Rabby: 0, MetaMask: 2 }) }) + test('shows a subsidized transfer quote at 1:1 with no fee line', async ({ page }) => { + await mockRoutesApi(page, { + 'GET /v1/routes': [directory], + 'GET /v1/routes/transfers/quote': [ + // A subsidized transfer quote keeps the provider's amount and fee, and guarantees 1:1. + { body: { ...transferQuote, subsidize: true, destinationAmountRequired: usd('1') } }, + ], + }) + await openDemo(page) + await chooseRoute(page, ['Base', 'USDC'], ['Tempo', 'USDC.e']) + await page.getByLabel('Amount (USDC)').fill('1') + await page.getByLabel('Sender on Base').fill(sender) + await page.getByLabel('Recipient on Tempo').fill(tempoRecipient) + await button(page, 'Get quote').click() + await expect(quoteSummary(page)).toHaveText('You send1 USDCRecipient gets1 USDC.e') + }) + test('quotes subsidized 1:1 delivery and watches a deposit through delivery', async ({ page, }) => { @@ -811,11 +831,10 @@ test.describe('Routes demo', () => { await page.getByLabel('Refund address on Base').fill(sender) await button(page, 'Get quote').click() - // Tempo covers the gap between the routed amount (0.9591) and 1:1 delivery. - await expect(lifecycle(page)).toContainText( - 'Recipient gets1 USDC.eCovered by Tempo0.0409 USDC.eFeesNone', - ) - await expect(lifecycle(page)).not.toContainText('1:1 delivery preview') + // 1:1 delivery: the recipient gets the amount sent, with no fee line. + await expect(lifecycle(page)).toContainText('You send1 USDCRecipient gets1 USDC.e') + await expect(lifecycle(page)).not.toContainText('Covered by Tempo') + await expect(quoteSummary(page)).not.toContainText('Fee') const quoteQuery = Object.fromEntries( api.to('GET', '/v1/routes/deposit-addresses/quote')[0].query, ) @@ -1379,10 +1398,8 @@ test.describe('Routes demo without a key', () => { // Only an approved organization can quote 1:1 delivery, so the docs key prices the preview. await expect(lifecycle(page)).toContainText('Recipient gets1 USDC.e') - await expect(lifecycle(page)).toContainText('Covered by Tempo0.0409 USDC.e') - await expect(lifecycle(page)).toContainText( - '1:1 delivery preview from the docs demo organization. Creating a 1:1 route needs subsidy approval for your organization.', - ) + await expect(lifecycle(page)).not.toContainText('Covered by Tempo') + await expect(lifecycle(page)).not.toContainText('1:1 delivery preview') await expect(lifecycle(page)).toContainText( 'Add your Tempo API key here to create routes with configured pricing. Get yours in the Tempo API console.', ) @@ -1401,8 +1418,8 @@ test.describe('Routes demo without a key', () => { await expect(page.getByLabel('Project API key')).toBeFocused() await page.getByLabel('Project API key').fill(key) await button(page, 'Use key').click() - await expect(lifecycle(page)).toContainText('Covered by Tempo0.0009 USDC.e') - await expect(lifecycle(page)).not.toContainText('1:1 delivery preview') + await expect(lifecycle(page)).toContainText('Recipient gets1 USDC.e') + await expect(lifecycle(page)).not.toContainText('Covered by Tempo') const keyed = api.to('GET', '/v1/routes/deposit-addresses/quote').at(-1) expect(keyed?.headers['tempo-api-key']).toBe(key) expect(keyed?.query.get('subsidize')).toBe('true') @@ -1425,14 +1442,15 @@ test.describe('Routes demo without a key', () => { await page.getByLabel('Recipient on Tempo').fill(tempoRecipient) await page.getByLabel('Refund address on Base').fill(sender) await button(page, 'Get quote').click() - await expect(lifecycle(page)).toContainText('1:1 delivery preview') + await expect(quoteSummary(page)).toHaveText('You send1 USDCRecipient gets1 USDC.e') await addKey(page, key) await expect(lifecycle(page)).toContainText('Recipient gets0.9591 USDC.e') await expect(lifecycle(page)).toContainText( 'Quoted without 1:1 delivery. This organization is not approved for 1:1 delivery on this route. (routes_subsidy_not_allowed · request req_sub)', ) - await expect(lifecycle(page)).not.toContainText('1:1 delivery preview') + // Without the subsidy, the one fee line returns. + await expect(quoteSummary(page)).toContainText('Recipient gets0.9591 USDC.eFee0.0409 USDC') expect( api.to('GET', '/v1/routes/deposit-addresses/quote').map((q) => q.query.get('subsidize')), ).toEqual(['true', 'false']) diff --git a/src/components/RoutesTester.tsx b/src/components/RoutesTester.tsx index df8f6791b..1dd956a98 100644 --- a/src/components/RoutesTester.tsx +++ b/src/components/RoutesTester.tsx @@ -56,6 +56,7 @@ import { demoMethods, linkedRoute, quickRoutes, + quoteFee, type RoutePick, routeChoices, routeQuoteRequest, @@ -417,8 +418,6 @@ function RouteLifecycle({ // Why the open quote lacks 1:1 delivery, when the API refused it. const [subsidyNotice, setSubsidyNotice] = useState('') const [quote, setQuote] = useState() - // Without a key, a 1:1 quote is the docs demo organization's preview, not the reader's terms. - const [quoteKeyed, setQuoteKeyed] = useState(false) const [created, setCreated] = useState() const [hashes, setHashes] = useState([]) const [confirmedCalls, setConfirmedCalls] = useState(0) @@ -745,7 +744,6 @@ function RouteLifecycle({ result = await unsubsidizedQuote() } setQuote(result) - setQuoteKeyed(!!apiKey.trim()) quoteReady.current = true }) // Adding or removing a key changes the price list, so an open quote is priced again. @@ -1422,12 +1420,6 @@ function RouteLifecycle({ {subsidyNotice}

)} - {!quoteKeyed && subsidizedTerms && ( -

- 1:1 delivery preview from the docs demo organization. Creating a 1:1 route needs - subsidy approval for your organization. -

- )} ) : (
@@ -1835,10 +1827,7 @@ function usePolling( }, [enabled, intervalMs, maxRuns]) } -type Fee = { amount?: { formatted?: string }; token?: { symbol?: string } } -const feeDigits = new Intl.NumberFormat('en-US', { maximumSignificantDigits: 4 }) - -/** The quote as a receipt: what is sent, what arrives, and the fees the API lists. */ +/** The quote as a receipt: what is sent, what arrives, and any fee when it isn't 1:1. */ function QuoteSummary({ data, route }: { data: Record; route: TestRoute }) { const subsidized = data.subsidize === true const { decimals, symbol } = route.destinationToken @@ -1846,7 +1835,7 @@ function QuoteSummary({ data, route }: { data: Record; route: T const received = delivery ? formatUnits(delivery.guaranteed, decimals) : quantity(data.destinationAmount) - const fees = Array.isArray(data.fees) ? (data.fees as Fee[]) : [] + const fee = quoteFee(data, route.sourceToken.symbol) return (
@@ -1855,21 +1844,7 @@ function QuoteSummary({ data, route }: { data: Record; route: T {received} {symbol} - {delivery && delivery.covered > 0n && ( - - {formatUnits(delivery.covered, decimals)} {symbol} - - )} - {fees.length === 0 ? ( - None - ) : ( - fees.map((fee, index) => ( - - {fee.amount?.formatted ? feeDigits.format(Number(fee.amount.formatted)) : '—'}{' '} - {fee.token?.symbol} - - )) - )} + {fee && {fee}}
) } diff --git a/src/lib/routes-test.test.ts b/src/lib/routes-test.test.ts index ca6b69b2f..cea60a111 100644 --- a/src/lib/routes-test.test.ts +++ b/src/lib/routes-test.test.ts @@ -5,6 +5,7 @@ import { directorySchema, linkedRoute, quickRoutes, + quoteFee, routeChoices, routeDemoHref, routeQuoteRequest, @@ -190,6 +191,35 @@ describe('route test requests', () => { covered: 0n, }) }) + it('shows no fee for a 1:1 quote and the whole gap otherwise', () => { + const usd = (baseUnits: string, decimals = 6) => ({ baseUnits, decimals, currency: 'USD' }) + const listed = [{ amount: { formatted: '2.810008' }, token: { symbol: 'USDT' } }] + // Live Tron USDT to OUSD: 10000 sent, 9985.605531 arrives, and the API lists only 2.81. + const tron = { + sourceAmount: usd('10000000000'), + destinationAmount: usd('9985605531'), + fees: listed, + } + expect(quoteFee({ ...tron, subsidize: true }, 'USDT')).toBeUndefined() + expect(quoteFee({ ...tron, subsidize: false }, 'USDT')).toBe('14.394469 USDT') + // Amounts in different decimals compare at the finer one. + expect( + quoteFee( + { sourceAmount: usd('1000000000000000000', 18), destinationAmount: usd('999000') }, + 'USDC', + ), + ).toBe('0.001 USDC') + expect(quoteFee({ sourceAmount: usd('1000000'), destinationAmount: usd('1000000') })).toBe( + 'None', + ) + // Between currencies the gap is a rate, so the listed fees show instead. + const eur = { ...usd('920000'), currency: 'EUR' } + expect(quoteFee({ sourceAmount: usd('1000000'), destinationAmount: eur, fees: listed })).toBe( + '2.81 USDT', + ) + expect(quoteFee({ fees: [] })).toBe('None') + expect(quoteFee({})).toBe('None') + }) it('offers wallet transfers for EVM, Tron, and Stellar sources, and deposits everywhere', () => { expect(demoMethods(route)).toEqual(['transfer', 'depositAddress']) const tron = { id: 'tron:0x2b6653dc', name: 'Tron', addressFormat: 'base58check' } diff --git a/src/lib/routes-test.ts b/src/lib/routes-test.ts index 21a4d7751..9a0c623de 100644 --- a/src/lib/routes-test.ts +++ b/src/lib/routes-test.ts @@ -106,6 +106,73 @@ export function subsidizedDelivery(data: Record, decimals: numb } } +type QuoteFee = { + amount?: { baseUnits?: string; decimals?: number; formatted?: string } + token?: { symbol?: string } +} +const feeDigits = new Intl.NumberFormat('en-US', { maximumSignificantDigits: 4 }) +const feeValue = ({ baseUnits, decimals, formatted }: NonNullable) => + formatted !== undefined + ? Number(formatted) + : baseUnits !== undefined && decimals !== undefined + ? Number(baseUnits) / 10 ** decimals + : undefined + +type Amount = { baseUnits?: string; decimals?: number; currency?: string } +const exact = (units: bigint, decimals: number) => { + const digits = units.toString().padStart(decimals + 1, '0') + const fraction = digits.slice(digits.length - decimals).replace(/0+$/, '') + return fraction + ? `${digits.slice(0, digits.length - decimals)}.${fraction}` + : digits.slice(0, -decimals || undefined) +} + +/** + * The quote's one fee line. A subsidized quote delivers 1:1, so it shows none. Otherwise the fee is + * the whole gap between what is sent and what arrives, so the lines add up: the API's `fees` list + * leaves out deductions already taken from `destinationAmount`, such as conversion. Routes between + * currencies have no such gap, so they show the listed fees instead. + */ +export function quoteFee(data: Record, sourceSymbol?: string) { + if (data.subsidize === true) return undefined + const sent = (data.sourceAmount ?? {}) as Amount + const received = (data.destinationAmount ?? {}) as Amount + if ( + sent.baseUnits && + received.baseUnits && + sent.decimals !== undefined && + received.decimals !== undefined && + sent.currency && + sent.currency === received.currency + ) { + const decimals = Math.max(sent.decimals, received.decimals) + const scale = (amount: Amount) => + BigInt(amount.baseUnits as string) * 10n ** BigInt(decimals - (amount.decimals as number)) + const gap = scale(sent) - scale(received) + if (gap <= 0n) return 'None' + return [exact(gap, decimals), sourceSymbol].filter(Boolean).join(' ') + } + return listedFees(data) +} + +/** The fees the API lists, added up per token, such as `0.0001006 ETH`. */ +function listedFees(data: Record) { + const fees = Array.isArray(data.fees) ? (data.fees as QuoteFee[]) : [] + const totals = new Map() + for (const fee of fees) { + const symbol = fee.token?.symbol ?? '' + const value = fee.amount ? feeValue(fee.amount) : undefined + const total = totals.has(symbol) ? totals.get(symbol) : 0 + totals.set(symbol, total === undefined || value === undefined ? undefined : total + value) + } + if (totals.size === 0) return 'None' + return [...totals] + .map(([symbol, total]) => + [total === undefined ? '—' : feeDigits.format(total), symbol].filter(Boolean).join(' '), + ) + .join(' + ') +} + export function toBaseUnits(amount: string, decimals: number): string { if (!/^\d+(\.\d+)?$/.test(amount)) throw new Error('Enter a positive decimal amount.') const [whole, fraction = ''] = amount.split('.')