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
48 changes: 33 additions & 15 deletions e2e/routes-demo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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,
}) => {
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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.',
)
Expand All @@ -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')
Expand All @@ -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'])
Expand Down
33 changes: 4 additions & 29 deletions src/components/RoutesTester.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
demoMethods,
linkedRoute,
quickRoutes,
quoteFee,
type RoutePick,
routeChoices,
routeQuoteRequest,
Expand Down Expand Up @@ -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<ApiResult>()
// 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<ApiResult>()
const [hashes, setHashes] = useState<string[]>([])
const [confirmedCalls, setConfirmedCalls] = useState(0)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -1422,12 +1420,6 @@ function RouteLifecycle({
{subsidyNotice}
</p>
)}
{!quoteKeyed && subsidizedTerms && (
<p {...cx(stepBody(), noteStyle())}>
1:1 delivery preview from the docs demo organization. Creating a 1:1 route needs
subsidy approval for your organization.
</p>
)}
</>
) : (
<div {...stepForm()}>
Expand Down Expand Up @@ -1835,18 +1827,15 @@ 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<string, unknown>; route: TestRoute }) {
const subsidized = data.subsidize === true
const { decimals, symbol } = route.destinationToken
const delivery = subsidized ? subsidizedDelivery(data, decimals) : undefined
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 (
<dl {...quoteSummary()}>
<Row label="You send">
Expand All @@ -1855,21 +1844,7 @@ function QuoteSummary({ data, route }: { data: Record<string, unknown>; route: T
<Row label="Recipient gets">
{received} {symbol}
</Row>
{delivery && delivery.covered > 0n && (
<Row label="Covered by Tempo">
{formatUnits(delivery.covered, decimals)} {symbol}
</Row>
)}
{fees.length === 0 ? (
<Row label="Fees">None</Row>
) : (
fees.map((fee, index) => (
<Row key={`${fee.token?.symbol}-${index}`} label="Fee">
{fee.amount?.formatted ? feeDigits.format(Number(fee.amount.formatted)) : '—'}{' '}
{fee.token?.symbol}
</Row>
))
)}
{fee && <Row label="Fee">{fee}</Row>}
</dl>
)
}
Expand Down
30 changes: 30 additions & 0 deletions src/lib/routes-test.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
directorySchema,
linkedRoute,
quickRoutes,
quoteFee,
routeChoices,
routeDemoHref,
routeQuoteRequest,
Expand Down Expand Up @@ -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' }
Expand Down
67 changes: 67 additions & 0 deletions src/lib/routes-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,73 @@ export function subsidizedDelivery(data: Record<string, unknown>, 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<QuoteFee['amount']>) =>
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<string, unknown>, sourceSymbol?: string) {
if (data.subsidize === true) return undefined

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Senders of a subsidized transfer quote no longer see fees they still pay, such as source-network gas in ETH, so the quote understates their cost. quoteFee returns undefined whenever subsidize === true, which drops every listed fee. A 1:1 subsidy only guarantees the recipient amount. Fix: on subsidized quotes, hide only fees the subsidy covers and keep separately charged fees, such as those with side: 'source'. Or show the fee line whenever fees is non-empty and drop only the 'None' row.

Why this was flagged

A keyed or keyless transfer quote returns subsidize: true with a non-empty fees array. The e2e fixture transferQuote (e2e/routes-demo.test.ts:104-111) shows such a fee: 0.0001006 ETH with side: 'source', commented "Transfers can charge source-network gas in the native asset". quoteFee returns undefined at src/lib/routes-test.ts:126, so QuoteSummary (src/components/RoutesTester.tsx:1847) shows only "You send 1 USDC / Recipient gets 1 USDC.e". On the base branch every listed fee got its own 'Fee' row. src/pages/docs/routes/quotes.mdx:40 says the fees array "lists only separately charged fees", and quotes.mdx:38 tells integrators to show fees. quotes.mdx:46 says the subsidy guarantees delivery: "the recipient receives the amount sent". It says nothing about covering source-side charges. The new e2e test 'shows a subsidized transfer quote at 1:1 with no fee line' locks this in.

Verification: The trigger is a subsidized transfer quote that comes back with a non-empty fees array, such as a source-side ETH network fee. src/lib/routes-test.ts:126 returns early with if (data.subsidize === true) return undefined, before any fee is read. On the base branch, fees.map(...) rendered a "Fee" row for every listed fee, whatever subsidize was.

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<string, unknown>) {
const fees = Array.isArray(data.fees) ? (data.fees as QuoteFee[]) : []
const totals = new Map<string, number | undefined>()
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('.')
Expand Down
Loading