diff --git a/CHANGELOG.md b/CHANGELOG.md index 644d4e0d609..27fda44edea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ ## Unreleased (develop) - added: Swap success events name the swap mode, including Swap & Send from the send scene +- fixed: Android crash when opening DFX and other web pages on some Android 12+ phones, where the blurred header and tab bar redrew the page +- fixed: DFX shows an error instead of opening when it blocks the country of the user's internet connection, for Bitcoin and EVM wallets, which Edge logs in to DFX +- fixed: DFX sells entered in fiat open DFX with the crypto amount filled in +- fixed: The header back button in Buy and Sell plugin scenes acting on the other tab's plugin - fixed: Exchange info, gift card info, Houdini chain, and Zcash migration status refreshes running twice per interval ## 4.53.0 (staging) diff --git a/src/__tests__/components/BlurBackground.test.tsx b/src/__tests__/components/BlurBackground.test.tsx new file mode 100644 index 00000000000..37a398bab36 --- /dev/null +++ b/src/__tests__/components/BlurBackground.test.tsx @@ -0,0 +1,93 @@ +import { describe, expect, it, jest } from '@jest/globals' +import type * as TestingLibrary from '@testing-library/react-native' +import type * as ReactModule from 'react' +import type * as ReactNative from 'react-native' + +import type * as BlurBackgroundModule from '../../components/common/BlurBackground' + +// BlurBackground picks its platform when it loads, so load a copy of it, +// with its own React and React Native, on an Android 12+ device. The JSX in +// this file renders with that copy of React: +let React: typeof ReactModule +let rtl: typeof TestingLibrary +let blur: typeof BlurBackgroundModule +jest.isolateModules(() => { + const { Platform } = jest.requireActual('react-native') + Platform.OS = 'android' + Object.defineProperty(Platform, 'Version', { get: () => 34 }) + React = jest.requireActual('react') + rtl = jest.requireActual( + '@testing-library/react-native' + ) + blur = jest.requireActual( + '../../components/common/BlurBackground' + ) +}) + +interface FocusedSceneProps { + hasWebView: boolean +} + +/** A focused scene, publishing itself the way SceneWrapper does. */ +const FocusedScene: ReactModule.FC = props => { + blur.useSceneBlurTarget(true, props.hasWebView) + return null +} + +/** The host component type `surface` renders over a focused scene. */ +const renderedType = ( + surface: ReactModule.ReactElement, + scene?: { hasWebView: boolean } +): string => { + const { toJSON, unmount } = rtl.render( + <> + {scene == null ? null : } + {surface} + + ) + const json = toJSON() + unmount() + if (json == null || Array.isArray(json)) throw new Error('no single surface') + return json.type +} + +describe('blur surfaces over a focused WebView scene on Android', () => { + it('blurs modals over other scenes', () => { + expect( + renderedType(, { hasWebView: false }) + ).toBe('ExpoBlurView') + expect(renderedType()).toBe('ExpoBlurView') + }) + + it('tints modals over a WebView scene', () => { + expect( + renderedType(, { hasWebView: true }) + ).toBe('View') + expect( + renderedType(, { hasWebView: true }) + ).toBe('View') + }) + + it('tints the chrome over a WebView scene', () => { + expect( + renderedType(, { hasWebView: false }) + ).toBe('ExpoBlurView') + expect( + renderedType(, { hasWebView: true }) + ).toBe('View') + }) + + it('blurs modals again once the WebView scene loses focus', () => { + const { toJSON, rerender, unmount } = rtl.render( + <> + + + + ) + expect(toJSON()).toMatchObject({ type: 'View' }) + + rerender() + expect(toJSON()).toMatchObject({ type: 'ExpoBlurView' }) + unmount() + }) +}) diff --git a/src/__tests__/components/GuiPluginBackButton.test.tsx b/src/__tests__/components/GuiPluginBackButton.test.tsx new file mode 100644 index 00000000000..71a1f8dbbf9 --- /dev/null +++ b/src/__tests__/components/GuiPluginBackButton.test.tsx @@ -0,0 +1,94 @@ +import { afterEach, describe, expect, it, jest } from '@jest/globals' +import { fireEvent, render } from '@testing-library/react-native' +import * as React from 'react' +import type * as ReactNative from 'react-native' + +import { + PluginBackButton, + setPluginScene +} from '../../components/navigation/GuiPluginBackButton' + +jest.mock('../../components/navigation/BackButton', () => { + const { TouchableOpacity } = + jest.requireActual('react-native') + return { + BackButton: (props: { onPress: () => void }) => ( + + ) + } +}) + +const makeScene = (): { goBack: jest.Mock<() => boolean> } => ({ + goBack: jest.fn(() => true) +}) + +const pressBack = (): void => { + const { getByTestId, unmount } = render() + fireEvent.press(getByTestId('backButton')) + unmount() +} + +// The button's owner is module state, so each test releases what it took: +let releases: Array<() => void> = [] +const register = (scene: ReturnType): (() => void) => { + const release = setPluginScene(scene) + releases.push(release) + return release +} + +afterEach(() => { + releases.forEach(release => { + release() + }) + releases = [] +}) + +describe('PluginBackButton', () => { + it('acts on the scene that registered last', () => { + const buyScene = makeScene() + const sellScene = makeScene() + register(buyScene) + register(sellScene) + + pressBack() + + expect(sellScene.goBack).toHaveBeenCalledTimes(1) + expect(buyScene.goBack).not.toHaveBeenCalled() + }) + + it('keeps the newly focused scene when the old one blurs after it', () => { + // React Navigation can focus the new tab's scene before it blurs the old: + const buyScene = makeScene() + const sellScene = makeScene() + const releaseBuy = register(buyScene) + register(sellScene) + releaseBuy() + + pressBack() + + expect(sellScene.goBack).toHaveBeenCalledTimes(1) + expect(buyScene.goBack).not.toHaveBeenCalled() + }) + + it('hands the button to the scene focused after a release', () => { + const buyScene = makeScene() + const sellScene = makeScene() + const releaseBuy = register(buyScene) + releaseBuy() + register(sellScene) + + pressBack() + + expect(sellScene.goBack).toHaveBeenCalledTimes(1) + expect(buyScene.goBack).not.toHaveBeenCalled() + }) + + it('does nothing once the scene holding it releases it', () => { + const buyScene = makeScene() + const releaseBuy = register(buyScene) + releaseBuy() + + expect(pressBack).not.toThrow() + expect(buyScene.goBack).not.toHaveBeenCalled() + }) +}) diff --git a/src/__tests__/components/pluginBackHistory.test.ts b/src/__tests__/components/pluginBackHistory.test.ts new file mode 100644 index 00000000000..6b973433cfc --- /dev/null +++ b/src/__tests__/components/pluginBackHistory.test.ts @@ -0,0 +1,154 @@ +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest +} from '@jest/globals' + +import { + BACK_SETTLE_MS, + makePluginBackHistory +} from '../../components/navigation/pluginBackHistory' + +const DEEP_LINK = 'https://app.dfx.swiss/buy?blockchain=Monero&amount-in=500' +const LOGIN = 'https://app.dfx.swiss/login' +const EMAIL = 'https://app.dfx.swiss/login/mail' + +beforeEach(() => { + jest.useFakeTimers() +}) + +afterEach(() => { + jest.useRealTimers() +}) + +describe('makePluginBackHistory', () => { + it('leaves the scene when the webview has no history', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation(LOGIN, false) + + expect(history.pressBack()).toBe(false) + }) + + it('leaves the scene when going back bounces off a redirect', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + // DFX redirects its deep link to its login page: + history.onNavigation(DEEP_LINK, false) + history.onNavigation(LOGIN, true) + + expect(history.pressBack()).toBe(true) + history.onNavigation(DEEP_LINK, false) + history.onNavigation(LOGIN, true) + jest.advanceTimersByTime(BACK_SETTLE_MS) + + expect(leave).toHaveBeenCalledTimes(1) + }) + + it('leaves the scene when going back changes nothing', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation(LOGIN, true) + + expect(history.pressBack()).toBe(true) + jest.advanceTimersByTime(BACK_SETTLE_MS) + + expect(leave).toHaveBeenCalledTimes(1) + }) + + it('stays when going back reaches an earlier page', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation(LOGIN, true) + history.onNavigation(EMAIL, true) + + expect(history.pressBack()).toBe(true) + history.onNavigation(LOGIN, true) + jest.advanceTimersByTime(BACK_SETTLE_MS) + + expect(leave).not.toHaveBeenCalled() + }) + + it('treats a page that differs only in its query as the same page', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation(`${LOGIN}?redirect=buy`, true) + + history.pressBack() + history.onNavigation(`${LOGIN}?redirect=buy&t=1`, true) + jest.advanceTimersByTime(BACK_SETTLE_MS) + + expect(leave).toHaveBeenCalledTimes(1) + }) + + it('tells hash-routed pages apart', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation('https://plugin.example/#/amount', true) + + history.pressBack() + history.onNavigation('https://plugin.example/#/start', true) + jest.advanceTimersByTime(BACK_SETTLE_MS) + + expect(leave).not.toHaveBeenCalled() + }) + + it('does not leave once cancelled, as when the scene blurs', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation(LOGIN, true) + + history.pressBack() + history.cancel() + jest.advanceTimersByTime(BACK_SETTLE_MS) + + expect(leave).not.toHaveBeenCalled() + }) + + it('leaves on a second press that finds the page unchanged', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation(LOGIN, true) + + expect(history.pressBack()).toBe(true) + // The caller leaves the scene itself when this returns false: + expect(history.pressBack()).toBe(false) + jest.advanceTimersByTime(BACK_SETTLE_MS) + + // The dropped check must not leave a second time: + expect(leave).not.toHaveBeenCalled() + }) + + it('leaves on a second press during a redirect bounce', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation(DEEP_LINK, false) + history.onNavigation(LOGIN, true) + + expect(history.pressBack()).toBe(true) + history.onNavigation(DEEP_LINK, false) + history.onNavigation(LOGIN, true) + + expect(history.pressBack()).toBe(false) + jest.advanceTimersByTime(BACK_SETTLE_MS) + expect(leave).not.toHaveBeenCalled() + }) + + it('goes back again when the first press reached an earlier page', () => { + const leave = jest.fn() + const history = makePluginBackHistory(leave) + history.onNavigation(LOGIN, true) + history.onNavigation(EMAIL, true) + + expect(history.pressBack()).toBe(true) + history.onNavigation(LOGIN, true) + + // A fresh check starts from the earlier page: + expect(history.pressBack()).toBe(true) + jest.advanceTimersByTime(BACK_SETTLE_MS) + expect(leave).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/__tests__/plugins/ramps/dfxQuote.test.ts b/src/__tests__/plugins/ramps/dfxQuote.test.ts new file mode 100644 index 00000000000..49ce196579a --- /dev/null +++ b/src/__tests__/plugins/ramps/dfxQuote.test.ts @@ -0,0 +1,126 @@ +import { + afterEach, + beforeEach, + describe, + expect, + it, + jest +} from '@jest/globals' + +import { fetchDfxSellCryptoAmount } from '../../../plugins/ramps/dfx/dfxQuote' +import { + installFakeFetch, + makeTextResponse +} from '../../../util/fake/fakeFetch' + +let fakeFetch: ReturnType +let assetStatus = 200 +let quoteStatus = 200 +let quoteAmount = 0.003502 +const realWarn = console.warn + +const params = { + blockchain: 'Bitcoin', + asset: 'BTC', + fiat: 'EUR', + fiatAmount: '200' +} + +beforeEach(() => { + assetStatus = 200 + quoteStatus = 200 + quoteAmount = 0.003502 + console.warn = jest.fn() + fakeFetch = installFakeFetch(({ url }) => { + if (url.includes('/asset?')) { + return makeTextResponse(assetStatus, [ + { id: 7, name: 'WBTC', blockchain: 'Bitcoin' }, + { id: 113, name: 'BTC', blockchain: 'Bitcoin' } + ]) + } + if (url.endsWith('/fiat')) { + return makeTextResponse(200, [ + { id: 1, name: 'CHF' }, + { id: 2, name: 'EUR' } + ]) + } + return makeTextResponse(quoteStatus, { amount: quoteAmount }) + }) +}) + +afterEach(() => { + fakeFetch.restore() + console.warn = realWarn +}) + +describe('fetchDfxSellCryptoAmount', () => { + it('quotes the fiat amount with the DFX asset and fiat ids', async () => { + expect(await fetchDfxSellCryptoAmount(params)).toBe('0.003502') + + expect(fakeFetch.calls).toContainEqual({ + url: 'https://api.dfx.swiss/v1/asset?blockchains=Bitcoin' + }) + expect(fakeFetch.calls).toContainEqual({ + url: 'https://api.dfx.swiss/v1/sell/quote', + method: 'PUT', + body: { asset: { id: 113 }, currency: { id: 2 }, targetAmount: 200 } + }) + }) + + it('writes small amounts as plain decimals', async () => { + quoteAmount = 1e-7 + + expect(await fetchDfxSellCryptoAmount(params)).toBe('0.0000001') + }) + + it('gives up when DFX does not trade the asset', async () => { + expect( + await fetchDfxSellCryptoAmount({ ...params, asset: 'ETH' }) + ).toBeUndefined() + expect(console.warn).toHaveBeenCalled() + }) + + it('gives up when DFX does not trade the fiat', async () => { + expect( + await fetchDfxSellCryptoAmount({ ...params, fiat: 'USD' }) + ).toBeUndefined() + expect(console.warn).toHaveBeenCalled() + }) + + it('gives up when the asset list fails', async () => { + assetStatus = 500 + + expect(await fetchDfxSellCryptoAmount(params)).toBeUndefined() + expect(console.warn).toHaveBeenCalled() + }) + + it('gives up when the quote fails', async () => { + quoteStatus = 400 + + expect(await fetchDfxSellCryptoAmount(params)).toBeUndefined() + }) + + it('gives up on an empty quote', async () => { + quoteAmount = 0 + + expect(await fetchDfxSellCryptoAmount(params)).toBeUndefined() + }) + + it('gives up when DFX does not answer in time', async () => { + jest.useFakeTimers() + try { + fakeFetch.restore() + fakeFetch = installFakeFetch( + async () => await new Promise(() => {}) + ) + + const pending = fetchDfxSellCryptoAmount(params) + await jest.advanceTimersByTimeAsync(10000) + + expect(await pending).toBeUndefined() + expect(console.warn).toHaveBeenCalled() + } finally { + jest.useRealTimers() + } + }) +}) diff --git a/src/__tests__/plugins/ramps/dfxRampPlugin.test.ts b/src/__tests__/plugins/ramps/dfxRampPlugin.test.ts index 176691a4221..5f36779dd2d 100644 --- a/src/__tests__/plugins/ramps/dfxRampPlugin.test.ts +++ b/src/__tests__/plugins/ramps/dfxRampPlugin.test.ts @@ -3,6 +3,7 @@ import type { EdgeCurrencyWallet } from 'edge-core-js' import type { PluginViewParams } from '../../../components/scenes/GuiPluginViewScene' import { locale } from '../../../locales/intl' +import { fetchDfxSellCryptoAmount } from '../../../plugins/ramps/dfx/dfxQuote' import { dfxRampPlugin, makeDfxRequestQuery @@ -12,18 +13,24 @@ import type { RampPluginConfig, RampQuoteRequest } from '../../../plugins/ramps/rampPluginTypes' +import { RampIpCountryError } from '../../../types/RampIpCountryError' jest.mock('../../../components/services/AirshipInstance', () => ({ showToastSpinner: async (message: string, promise: Promise) => await promise })) +jest.mock('../../../plugins/ramps/dfx/dfxQuote', () => ({ + fetchDfxSellCryptoAmount: jest.fn() +})) + jest.mock('../../../plugins/ramps/dfx/dfxSession', () => ({ ...jest.requireActual('../../../plugins/ramps/dfx/dfxSession'), fetchDfxSessionQuery: jest.fn() })) const mockFetchSessionQuery = jest.mocked(fetchDfxSessionQuery) +const mockFetchSellCryptoAmount = jest.mocked(fetchDfxSellCryptoAmount) const realLocaleId = locale.localeIdentifier const makeRequest = ( @@ -43,6 +50,7 @@ const makeRequest = ( afterEach(() => { locale.localeIdentifier = realLocaleId + jest.clearAllMocks() }) describe('makeDfxRequestQuery', () => { @@ -93,14 +101,25 @@ describe('makeDfxRequestQuery', () => { }) }) - it('leaves the amount out of a fiat-entered sell and a max quote', () => { + it('passes a fiat amount on a sell as the amount to receive', () => { const fiatSell = makeRequest('ethereum', { direction: 'sell' }) + + expect(makeDfxRequestQuery(fiatSell, 'Edge')).toEqual({ + wallet: 'Edge', + lang: 'en', + blockchain: 'Ethereum', + 'asset-in': 'ETH', + 'asset-out': 'CHF', + 'amount-out': '500' + }) + }) + + it('leaves the amount out of a max quote', () => { const maxBuy = makeRequest('ethereum', { amountQuery: { max: true } }) + const query = makeDfxRequestQuery(maxBuy, 'Edge') - expect(makeDfxRequestQuery(fiatSell, 'Edge')).not.toHaveProperty( - 'amount-in' - ) - expect(makeDfxRequestQuery(maxBuy, 'Edge')).not.toHaveProperty('amount-in') + expect(query).not.toHaveProperty('amount-in') + expect(query).not.toHaveProperty('amount-out') }) it('falls back to English for languages DFX does not offer', () => { @@ -153,4 +172,100 @@ describe('dfxRampPlugin approveQuote', () => { session: 'jwt' }) }) + + it('does not quote a crypto-entered buy', async () => { + mockFetchSessionQuery.mockResolvedValueOnce(undefined) + const cryptoBuy = makeRequest('bitcoin', { + amountQuery: { exchangeAmount: '0.01' }, + amountType: 'crypto' + }) + + expect(await approveDeepQuery(cryptoBuy)).toEqual({ + wallet: 'Edge', + lang: 'en', + blockchain: 'Bitcoin', + 'asset-in': 'CHF', + 'asset-out': 'BTC', + 'amount-out': '0.01' + }) + expect(mockFetchSellCryptoAmount).not.toHaveBeenCalled() + }) + + it('does not quote a crypto-entered sell', async () => { + mockFetchSessionQuery.mockResolvedValueOnce(undefined) + const cryptoSell = makeRequest('bitcoin', { + amountQuery: { exchangeAmount: '0.01' }, + amountType: 'crypto', + direction: 'sell' + }) + + expect(await approveDeepQuery(cryptoSell)).toEqual({ + wallet: 'Edge', + lang: 'en', + blockchain: 'Bitcoin', + 'asset-in': 'BTC', + 'asset-out': 'CHF', + 'amount-in': '0.01' + }) + expect(mockFetchSellCryptoAmount).not.toHaveBeenCalled() + }) + + describe('a fiat-entered sell', () => { + const fiatSell = makeRequest('bitcoin', { + direction: 'sell', + amountQuery: { exchangeAmount: '200' }, + fiatCurrencyCode: 'iso:EUR' + }) + const sellQuery = { + wallet: 'Edge', + lang: 'en', + blockchain: 'Bitcoin', + 'asset-in': 'BTC', + 'asset-out': 'EUR' + } + + it('opens with the crypto amount DFX quotes for the fiat', async () => { + mockFetchSessionQuery.mockResolvedValueOnce({ session: 'jwt' }) + mockFetchSellCryptoAmount.mockResolvedValueOnce('0.003502') + + expect(await approveDeepQuery(fiatSell)).toEqual({ + ...sellQuery, + 'amount-in': '0.003502', + session: 'jwt' + }) + expect(mockFetchSellCryptoAmount).toHaveBeenCalledWith({ + blockchain: 'Bitcoin', + asset: 'BTC', + fiat: 'EUR', + fiatAmount: '200' + }) + }) + + it('keeps the fiat amount when DFX cannot quote it', async () => { + mockFetchSessionQuery.mockResolvedValueOnce(undefined) + mockFetchSellCryptoAmount.mockResolvedValueOnce(undefined) + + expect(await approveDeepQuery(fiatSell)).toEqual({ + ...sellQuery, + 'amount-out': '200' + }) + }) + }) + + it('does not open DFX when it blocks the country', async () => { + mockFetchSessionQuery.mockRejectedValueOnce( + new RampIpCountryError('DFX', 'Forbidden') + ) + const navigate = jest.fn() + const plugin = dfxRampPlugin({ + initOptions: {}, + navigation: { navigate } + } as unknown as RampPluginConfig) + + const [quote] = await plugin.fetchQuotes(request) + await expect( + quote.approveQuote({ coreWallet: request.wallet }) + ).rejects.toBeInstanceOf(RampIpCountryError) + expect(navigate).not.toHaveBeenCalled() + }) }) diff --git a/src/__tests__/plugins/ramps/dfxSession.test.ts b/src/__tests__/plugins/ramps/dfxSession.test.ts index e3ac5aa2ae7..6f9401d2948 100644 --- a/src/__tests__/plugins/ramps/dfxSession.test.ts +++ b/src/__tests__/plugins/ramps/dfxSession.test.ts @@ -9,29 +9,30 @@ import { import type { EdgeCurrencyWallet } from 'edge-core-js' import { fetchDfxSessionQuery } from '../../../plugins/ramps/dfx/dfxSession' +import { RampIpCountryError } from '../../../types/RampIpCountryError' +import { + installFakeFetch, + makeTextResponse +} from '../../../util/fake/fakeFetch' +import { translateError } from '../../../util/translateError' const MESSAGE_PREFIX = 'By_signing_this_message,_you_confirm_that_you_are_the_sole_owner_of_the_provided_Blockchain_address._Your_ID:_' -interface FetchCall { - url: string - body?: unknown +// DFX's answer to a login from a blocked country, as its NestJS API sends it: +const IP_COUNTRY_BODY = { + statusCode: 403, + message: 'The country of IP address is not allowed', + error: 'Forbidden' } -let fetchCalls: FetchCall[] = [] +let fakeFetch: ReturnType let authStatus = 201 +let authBody: unknown = {} let signBlockchains: string[] = [] let signMessageText: ((address: string) => string) | undefined -const realFetch = global.fetch const realWarn = console.warn -const textResponse = (status: number, body: unknown): Response => - ({ - ok: status >= 200 && status < 300, - status, - text: async () => JSON.stringify(body) - } as unknown as Response) - const makeWallet = ( pluginId: string, addresses: Array<{ addressType: string; publicAddress: string }> @@ -58,32 +59,26 @@ const makeWallet = ( } beforeEach(() => { - fetchCalls = [] authStatus = 201 + authBody = { statusCode: 403, message: 'Forbidden', error: 'Forbidden' } signBlockchains = ['Bitcoin'] signMessageText = undefined console.warn = jest.fn() - global.fetch = (async (input: unknown, init?: RequestInit) => { - const url = String(input) - const body = - init?.body == null ? undefined : JSON.parse(init.body as string) - fetchCalls.push({ url, body }) + fakeFetch = installFakeFetch(({ url }) => { if (url.includes('/auth/signMessage')) { const address = decodeURIComponent(url.split('address=')[1]) - return textResponse(200, { + return makeTextResponse(200, { message: signMessageText?.(address) ?? MESSAGE_PREFIX + address, blockchains: signBlockchains }) } - if (authStatus !== 201) { - return textResponse(authStatus, { message: 'Forbidden' }) - } - return textResponse(201, { accessToken: 'jwt-token' }) - }) as typeof fetch + if (authStatus !== 201) return makeTextResponse(authStatus, authBody) + return makeTextResponse(201, { accessToken: 'jwt-token' }) + }) }) afterEach(() => { - global.fetch = realFetch + fakeFetch.restore() console.warn = realWarn }) @@ -99,14 +94,15 @@ describe('fetchDfxSessionQuery', () => { expect(query).toEqual({ session: 'jwt-token' }) expect(getAddresses).toHaveBeenCalledWith({ tokenId: null, forceIndex: 0 }) - expect(fetchCalls[0].url).toBe( + expect(fakeFetch.calls[0].url).toBe( 'https://api.dfx.swiss/v1/auth/signMessage?address=bc1segwit' ) expect(signMessage).toHaveBeenCalledWith(message, { otherParams: { publicAddress: 'bc1segwit' } }) - expect(fetchCalls[1]).toEqual({ + expect(fakeFetch.calls[1]).toEqual({ url: 'https://api.dfx.swiss/v1/auth', + method: 'POST', body: { address: 'bc1segwit', signature: 'sig-' + message, @@ -129,7 +125,7 @@ describe('fetchDfxSessionQuery', () => { expect(Buffer.from(signBytes.mock.calls[0][0]).toString('utf8')).toBe( message ) - expect(fetchCalls[1].body).toEqual({ + expect(fakeFetch.calls[1].body).toEqual({ address: '0xabc', signature: '0xsig-' + message, wallet: 'Edge' @@ -144,7 +140,7 @@ describe('fetchDfxSessionQuery', () => { const query = await fetchDfxSessionQuery({ wallet, walletName: 'Edge' }) expect(query).toBeUndefined() - expect(fetchCalls).toHaveLength(0) + expect(fakeFetch.calls).toHaveLength(0) expect(signMessage).not.toHaveBeenCalled() }) @@ -160,6 +156,45 @@ describe('fetchDfxSessionQuery', () => { expect(console.warn).toHaveBeenCalled() }) + it('stops the launch when DFX blocks the country of the IP address', async () => { + authStatus = 403 + authBody = IP_COUNTRY_BODY + const { wallet } = makeWallet('bitcoin', [ + { addressType: 'segwitAddress', publicAddress: 'bc1segwit' } + ]) + + const error = await fetchDfxSessionQuery({ + wallet, + walletName: 'Edge' + }).catch((error: unknown) => error) + + expect(error).toBeInstanceOf(RampIpCountryError) + expect(error).toMatchObject({ + providerName: 'DFX', + serverMessage: JSON.stringify(IP_COUNTRY_BODY) + }) + expect(translateError(error)).toBe( + "DFX doesn't accept connections from the country you're in. It checks where your internet connection is, not the region you chose in Edge." + ) + }) + + it('falls back on other country refusals', async () => { + authStatus = 403 + authBody = { + statusCode: 403, + message: 'Your country of residence is not supported', + error: 'Forbidden' + } + const { wallet } = makeWallet('bitcoin', [ + { addressType: 'segwitAddress', publicAddress: 'bc1segwit' } + ]) + + const query = await fetchDfxSessionQuery({ wallet, walletName: 'Edge' }) + + expect(query).toBeUndefined() + expect(console.warn).toHaveBeenCalled() + }) + it('refuses to sign any text but the DFX message for the address', async () => { signMessageText = () => 'Sign in to another service' const { wallet, signMessage } = makeWallet('bitcoin', [ @@ -170,7 +205,7 @@ describe('fetchDfxSessionQuery', () => { expect(query).toBeUndefined() expect(signMessage).not.toHaveBeenCalled() - expect(fetchCalls).toHaveLength(1) + expect(fakeFetch.calls).toHaveLength(1) }) it('refuses the DFX message when it names another address', async () => { diff --git a/src/components/common/BlurBackground.tsx b/src/components/common/BlurBackground.tsx index 7d6d1b7727d..96f3a37b092 100644 --- a/src/components/common/BlurBackground.tsx +++ b/src/components/common/BlurBackground.tsx @@ -74,11 +74,18 @@ export const useBlurTarget = (): React.RefObject | undefined => // must never sample a tree containing itself. Each SceneWrapper publishes its // content view here while focused; chrome subscribes to the current one. // +// A focused WebView scene publishes no target, and counts itself in +// `webViewScenes` instead. On Android a blur redraws what it samples into an +// offscreen layer, and drawing a WebView there crashes Chromium on some +// devices (Vulkan rendering), so while one is focused the modal blurs, which +// sample the app-level target holding that scene, fall back to their tint. +// const sceneBlurRegistry: { ref: React.RefObject | null + webViewScenes: number listeners: Set<() => void> -} = { ref: null, listeners: new Set() } +} = { ref: null, webViewScenes: 0, listeners: new Set() } const emitSceneBlur = (): void => { sceneBlurRegistry.listeners.forEach(listener => { @@ -91,17 +98,30 @@ const subscribeSceneBlur = (listener: () => void): (() => void) => { } const getFocusedSceneBlurTarget = (): React.RefObject | null => sceneBlurRegistry.ref +const getIsWebViewSceneFocused = (): boolean => + sceneBlurRegistry.webViewScenes > 0 /** * For SceneWrapper: returns a ref to attach to the scene's BlurTargetView, - * published as the focused scene's blur target while `active`. + * published as the focused scene's blur target while `focused`. A WebView + * scene publishes no target, and keeps the modal blurs off it on Android + * while focused. */ export function useSceneBlurTarget( - active: boolean + focused: boolean, + hasWebView: boolean = false ): React.RefObject { const ref = React.useRef(null) React.useEffect(() => { - if (!active) return + if (!focused) return + if (hasWebView) { + sceneBlurRegistry.webViewScenes += 1 + emitSceneBlur() + return () => { + sceneBlurRegistry.webViewScenes -= 1 + emitSceneBlur() + } + } sceneBlurRegistry.ref = ref emitSceneBlur() return () => { @@ -110,10 +130,14 @@ export function useSceneBlurTarget( emitSceneBlur() } } - }, [active]) + }, [focused, hasWebView]) return ref } +/** True while a focused WebView scene keeps the modal blurs off it. */ +const useIsWebViewSceneFocused = (): boolean => + React.useSyncExternalStore(subscribeSceneBlur, getIsWebViewSceneFocused) + interface AndroidBlurProps { rounded?: boolean /** iOS-style blur tint. Defaults to the theme's mode. */ @@ -209,13 +233,20 @@ export const ChromeBlurBackground: React.FC<{ rounded?: boolean }> = props => { } /** The blur behind modal sheets. Modals mount in the Airship layer, outside - * the BlurTarget, so on Android 12+ they can sample it for real blur. */ + * the BlurTarget, so on Android 12+ they can sample it for real blur, except + * over a focused WebView scene, where they use the tint. */ export const ModalBlurBackground: React.FC = () => { const theme = useTheme() const stylesLocal = getStyles(theme) + const isWebViewSceneFocused = useIsWebViewSceneFocused() if (isBlurDisabled) return null - if (isAndroid) return + if (isAndroid) { + if (isWebViewSceneFocused) { + return + } + return + } return ( { } /** Full-screen blur with the tint flipped against the theme, for standing out - * over content rather than blending in (the QR modal's underlay). */ + * over content rather than blending in (the QR modal's underlay). Over a + * focused WebView scene, Android uses the flipped tint alone. */ export const BlurUnderlayReversed: React.FC = () => { const theme = useTheme() + const stylesLocal = getStyles(theme) + const isWebViewSceneFocused = useIsWebViewSceneFocused() if (isBlurDisabled) return null - if (isAndroid) return + if (isAndroid) { + if (isWebViewSceneFocused) { + return + } + return + } return ( ({ : '#ffffff55' : undefined }, + // The blurView tint flipped against the theme: + blurViewReversed: { + ...StyleSheet.absoluteFill, + backgroundColor: isAndroid + ? theme.isDark + ? '#ffffff55' + : '#161616aa' + : undefined + }, clip: { overflow: 'hidden' }, diff --git a/src/components/common/SceneWrapper.tsx b/src/components/common/SceneWrapper.tsx index 1f59a5e7db1..928a6abb952 100644 --- a/src/components/common/SceneWrapper.tsx +++ b/src/components/common/SceneWrapper.tsx @@ -110,6 +110,14 @@ interface SceneWrapperProps { // True if this scene has a bottom tab bar: hasTabs?: boolean + // True if the scene shows a WebView. On Android 12+ the chrome over the + // scene (header, footer, tab bar and notification cards) and the modals + // shown over it then use their plain tint instead of blurring the scene: + // that blur redraws the scene into an offscreen layer, and drawing a + // WebView there crashes Chromium on some devices (Vulkan rendering). iOS + // blurs natively and keeps its blur. + hasWebView?: boolean + // Settings for when using ScrollView keyboardShouldPersistTaps?: 'always' | 'never' | 'handled' @@ -162,6 +170,7 @@ function SceneWrapperComponent(props: SceneWrapperProps): React.ReactElement { footerHeight = 0, hasHeader = true, hasTabs = false, + hasWebView = false, padding = 0, renderFooter, scroll = false, @@ -177,9 +186,10 @@ function SceneWrapperComponent(props: SceneWrapperProps): React.ReactElement { const isIos = Platform.OS === 'ios' // Publish this scene's content as the blur target chrome samples while the - // scene is focused (see BlurBackground): + // scene is focused, or for a WebView scene, that no blur may sample it + // (see BlurBackground): const isSceneFocused = useIsFocused() - const sceneBlurTargetRef = useSceneBlurTarget(isSceneFocused) + const sceneBlurTargetRef = useSceneBlurTarget(isSceneFocused, hasWebView) // Track dock height for content padding when dockProps is used const [dockHeight, setDockHeight] = useState(0) diff --git a/src/components/navigation/GuiPluginBackButton.tsx b/src/components/navigation/GuiPluginBackButton.tsx index 91ff03e0d9c..bdb61576b40 100644 --- a/src/components/navigation/GuiPluginBackButton.tsx +++ b/src/components/navigation/GuiPluginBackButton.tsx @@ -9,8 +9,17 @@ interface PluginScene { } let currentPlugin: PluginScene | undefined -export function setPluginScene(plugin: PluginScene | undefined): void { +/** + * Hands the header back button to the focused plugin scene. The Buy and + * Sell tabs each keep a plugin scene mounted, so the button must follow + * focus rather than whichever webview mounted last. + * Returns a cleanup that releases the button if this scene still holds it. + */ +export function setPluginScene(plugin: PluginScene): () => void { currentPlugin = plugin + return () => { + if (currentPlugin === plugin) currentPlugin = undefined + } } export const PluginBackButton: React.FC = () => { diff --git a/src/components/navigation/pluginBackHistory.ts b/src/components/navigation/pluginBackHistory.ts new file mode 100644 index 00000000000..bf13e81db84 --- /dev/null +++ b/src/components/navigation/pluginBackHistory.ts @@ -0,0 +1,70 @@ +/** + * How long a webview has to settle after going back before landing on the + * page it left counts as a redirect bouncing it there. + */ +export const BACK_SETTLE_MS = 1500 + +export interface PluginBackHistory { + /** Records each page the webview reports, with its `canGoBack`. */ + onNavigation: (url: string, canGoBack: boolean) => void + /** + * True when the webview should go back. False when the button should + * leave the scene instead: the webview has no history, or an earlier + * press has not moved it yet. + */ + pressBack: () => boolean + /** Drops a pending check, as when the scene loses focus. */ + cancel: () => void +} + +/** + * Decides what the plugin back button does with a webview's history. A web + * app that redirects its entry URL keeps that URL in the history: DFX sends + * a visitor who is not logged in from its deep link to its login page, so + * the webview reports it can go back, and going back only lands on the + * login page again. When a back press ends on the page it started from, the + * history held nothing to go back to, so this calls `leave`. + */ +export function makePluginBackHistory(leave: () => void): PluginBackHistory { + let canGoBack = false + let page = '' + let pending: ReturnType | undefined + let pendingFrom = '' + + const cancel = (): void => { + if (pending != null) clearTimeout(pending) + pending = undefined + } + + return { + onNavigation(url, webViewCanGoBack) { + canGoBack = webViewCanGoBack + page = pageOf(url) + }, + + pressBack() { + if (!canGoBack) return false + // Another press before the last one settled, with the webview still + // where that press started: going back has done nothing the user can + // see, so leave now rather than make them wait out the check again: + if (pending != null && page === pendingFrom) { + cancel() + return false + } + cancel() + pendingFrom = page + pending = setTimeout(() => { + pending = undefined + if (page === pendingFrom) leave() + }, BACK_SETTLE_MS) + return true + }, + + cancel + } +} + +/** The URL without its query, which a redirect can change: */ +function pageOf(url: string): string { + return url.replace(/\?[^#]*/, '') +} diff --git a/src/components/scenes/ExtraTabScene.tsx b/src/components/scenes/ExtraTabScene.tsx index 92f649a9e02..0adbb5b720d 100644 --- a/src/components/scenes/ExtraTabScene.tsx +++ b/src/components/scenes/ExtraTabScene.tsx @@ -24,7 +24,7 @@ export const ExtraTabScene: React.FC = props => { } return ( - + = props => { } return ( - + + = props => { const { uri } = props.route.params return ( - + ) diff --git a/src/components/themed/EdgeProviderComponent.tsx b/src/components/themed/EdgeProviderComponent.tsx index 62d62343cc1..2d55c5144d1 100644 --- a/src/components/themed/EdgeProviderComponent.tsx +++ b/src/components/themed/EdgeProviderComponent.tsx @@ -1,3 +1,4 @@ +import { useFocusEffect } from '@react-navigation/native' import { uncleaner } from 'cleaners' import type { EdgeCurrencyWallet } from 'edge-core-js' import * as React from 'react' @@ -21,6 +22,7 @@ import type { UriQueryMap } from '../../types/WebTypes' import { makePluginUri } from '../../util/GuiPluginTools' import { bestOfPlugins } from '../../util/ReferralHelpers' import { setPluginScene } from '../navigation/GuiPluginBackButton' +import { makePluginBackHistory } from '../navigation/pluginBackHistory' import { showToast } from '../services/AirshipInstance' import { requestPermissionOnSettings } from '../services/PermissionsManager' @@ -117,32 +119,47 @@ export function EdgeProviderComponent(props: Props): React.ReactElement { // Sign up for back-button events: const webView = React.useRef(null) - const canGoBack = React.useRef(false) - React.useEffect(() => { - setPluginScene({ - goBack() { - if (webView.current == null || !canGoBack.current) { - navigation.goBack() - return false + const backHistory = React.useMemo( + () => + makePluginBackHistory(() => { + navigation.goBack() + }), + [navigation] + ) + useFocusEffect( + React.useCallback(() => { + const release = setPluginScene({ + goBack() { + if (webView.current == null || !backHistory.pressBack()) { + navigation.goBack() + return false + } + webView.current.goBack() + return true } - webView.current.goBack() - return true + }) + return () => { + backHistory.cancel() + release() } - }) - }, [navigation]) + }, [backHistory, navigation]) + ) const handleLoadProgress = useHandler( (event: NativeSyntheticEvent) => { // The query can carry a login token (DFX `session`): console.log('Plugin navigation: ', event.nativeEvent.url.split('?')[0]) - canGoBack.current = event.nativeEvent.canGoBack + backHistory.onNavigation( + event.nativeEvent.url, + event.nativeEvent.canGoBack + ) } ) const handleNavigationStateChange = useHandler((event: WebViewEvent) => { // The query can carry a login token (DFX `session`): console.log('Plugin navigation: ', event.url.split('?')[0]) - canGoBack.current = event.canGoBack + backHistory.onNavigation(event.url, event.canGoBack) }) const handleError = useHandler( diff --git a/src/locales/en_US.ts b/src/locales/en_US.ts index 80ee15b1754..d7ed9ae1161 100644 --- a/src/locales/en_US.ts +++ b/src/locales/en_US.ts @@ -1342,6 +1342,8 @@ const strings = { tap_to_change_provider: 'Tap to Change Provider', tap_to_view_quote_amount_and_rate: 'Select to view quote', failed_to_calculate_quote_rate: 'Failed to calculate quote rate', + ramp_provider_ip_country_blocked_1s: + "%1$s doesn't accept connections from the country you're in. It checks where your internet connection is, not the region you chose in Edge.", send_from_wallet: 'Send from %s', send_to_wallet: 'Receive to %s', exchange_slow: 'Locating a swap is taking longer than usual.\nPlease wait...', diff --git a/src/locales/strings/enUS.json b/src/locales/strings/enUS.json index 20301247959..58499c83796 100644 --- a/src/locales/strings/enUS.json +++ b/src/locales/strings/enUS.json @@ -1051,6 +1051,7 @@ "tap_to_change_provider": "Tap to Change Provider", "tap_to_view_quote_amount_and_rate": "Select to view quote", "failed_to_calculate_quote_rate": "Failed to calculate quote rate", + "ramp_provider_ip_country_blocked_1s": "%1$s doesn't accept connections from the country you're in. It checks where your internet connection is, not the region you chose in Edge.", "send_from_wallet": "Send from %s", "send_to_wallet": "Receive to %s", "exchange_slow": "Locating a swap is taking longer than usual.\nPlease wait...", diff --git a/src/plugins/gui/scenes/FiatPluginWebView.tsx b/src/plugins/gui/scenes/FiatPluginWebView.tsx index 6d511e58feb..d560412bbf6 100644 --- a/src/plugins/gui/scenes/FiatPluginWebView.tsx +++ b/src/plugins/gui/scenes/FiatPluginWebView.tsx @@ -83,7 +83,7 @@ export const FiatPluginWebViewComponent: React.FC = props => { ) return ( - + { + const response = await fetch(`${DFX_API_URL}${path}`, init) + const text = await response.text() + if (!response.ok) { + if (response.status === 403 && isIpCountryBlock(text)) { + throw new RampIpCountryError('DFX', text) + } + throw new Error( + `${path.split('?')[0]} returned ${response.status}: ${text}` + ) + } + return text +} + +function isIpCountryBlock(text: string): boolean { + const body = asMaybe(asDfxErrorResponse)(text) + if (body == null) return false + const messages = + typeof body.message === 'string' ? [body.message] : body.message + return messages.some(message => IP_COUNTRY_MESSAGE.test(message)) +} diff --git a/src/plugins/ramps/dfx/dfxQuote.ts b/src/plugins/ramps/dfx/dfxQuote.ts new file mode 100644 index 00000000000..d1362cb34f5 --- /dev/null +++ b/src/plugins/ramps/dfx/dfxQuote.ts @@ -0,0 +1,81 @@ +import { raceTimeout, TIMED_OUT } from '../../../util/raceTimeout' +import { fetchDfx } from './dfxApi' +import { + asDfxAssets, + asDfxFiats, + asDfxSellQuoteResponse, + wasDfxSellQuoteRequest +} from './dfxRampTypes' + +// Runs beside the login under the same quote-approval spinner: +const DFX_QUOTE_TIMEOUT_MS = 10000 + +export interface DfxSellAmountParams { + /** DFX blockchain name, such as 'Bitcoin' */ + readonly blockchain: string + /** DFX asset name, such as 'BTC' */ + readonly asset: string + /** Fiat currency code without the 'iso:' prefix, such as 'EUR' */ + readonly fiat: string + /** The fiat the user wants to receive */ + readonly fiatAmount: string +} + +/** + * Asks DFX how much crypto to sell for the fiat amount the user entered. + * DFX's sell screen only fills its crypto field from a fiat amount once the + * user has picked a bank account, so the crypto amount is what opens the + * screen with both sides filled. + * Returns undefined when DFX cannot quote the amount in time. + */ +export async function fetchDfxSellCryptoAmount( + params: DfxSellAmountParams +): Promise { + try { + const amount = await raceTimeout( + quoteSellAmount(params), + DFX_QUOTE_TIMEOUT_MS + ) + if (amount === TIMED_OUT) { + throw new Error(`quote timed out after ${DFX_QUOTE_TIMEOUT_MS}ms`) + } + return amount + } catch (error: unknown) { + console.warn(`DFX sell quote failed: ${String(error)}`) + return undefined + } +} + +async function quoteSellAmount(params: DfxSellAmountParams): Promise { + const { blockchain, asset, fiat, fiatAmount } = params + + const [assets, fiats] = await Promise.all([ + fetchDfx(`/asset?blockchains=${encodeURIComponent(blockchain)}`).then( + asDfxAssets + ), + fetchDfx('/fiat').then(asDfxFiats) + ]) + const dfxAsset = assets.find( + item => item.blockchain === blockchain && item.name === asset + ) + if (dfxAsset == null) throw new Error(`no DFX asset ${blockchain}/${asset}`) + const dfxFiat = fiats.find(item => item.name === fiat) + if (dfxFiat == null) throw new Error(`no DFX fiat ${fiat}`) + + const quote = asDfxSellQuoteResponse( + await fetchDfx('/sell/quote', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: wasDfxSellQuoteRequest({ + asset: { id: dfxAsset.id }, + currency: { id: dfxFiat.id }, + targetAmount: Number(fiatAmount) + }) + }) + ) + if (!(quote.amount > 0)) throw new Error(`quote amount ${quote.amount}`) + + // DFX rounds its amounts well within 8 decimals. toFixed keeps the + // string a plain decimal, never exponent notation such as 1e-7: + return quote.amount.toFixed(8).replace(/\.?0+$/, '') +} diff --git a/src/plugins/ramps/dfx/dfxRampPlugin.ts b/src/plugins/ramps/dfx/dfxRampPlugin.ts index d13bdd84976..d29b1dcf5ce 100644 --- a/src/plugins/ramps/dfx/dfxRampPlugin.ts +++ b/src/plugins/ramps/dfx/dfxRampPlugin.ts @@ -9,6 +9,7 @@ import { createExternalRampPlugin, type DirectionSupportData } from '../utils/createExternalRampPlugin' +import { fetchDfxSellCryptoAmount } from './dfxQuote' import { asInitOptions } from './dfxRampTypes' import { DFX_SESSION_CHAINS, fetchDfxSessionQuery } from './dfxSession' @@ -78,8 +79,9 @@ const DFX_CRYPTO_ASSETS = Object.keys(DFX_CHAINS).map(pluginId => ({ * Carries the user's quote choices into DFX's app (its query parameters, * github.com/DFXswiss/app#query-parameters): the language, the fiat, the * crypto asset and its blockchain, and the amount the user entered. - * DFX has no amount for the fiat side of a sell, so a fiat-entered sell - * opens without one. + * A fiat-entered sell carries the fiat as `amount-out`, which DFX only turns + * into a crypto amount once the user picks a bank account, so + * `resolveDeepQuery` swaps in the crypto amount when DFX can quote it. */ export function makeDfxRequestQuery( request: RampQuoteRequest, @@ -105,13 +107,45 @@ export function makeDfxRequestQuery( if ('exchangeAmount' in amountQuery) { // The input side is the fiat on a buy and the crypto on a sell: const isInputAmount = isBuy === (amountType === 'fiat') - if (isInputAmount) query['amount-in'] = amountQuery.exchangeAmount - else if (isBuy) query['amount-out'] = amountQuery.exchangeAmount + query[isInputAmount ? 'amount-in' : 'amount-out'] = + amountQuery.exchangeAmount } return query } +/** + * The crypto amount for a fiat-entered sell, from DFX's quote for the + * fiat in `amount-out`. On a sell, the request query names the crypto as + * `asset-in` and the fiat as `asset-out`. Undefined for other requests or + * without a quote. + */ +async function fetchFiatSellCryptoAmount( + request: RampQuoteRequest, + query: Record +): Promise { + const { + blockchain, + 'asset-in': asset, + 'asset-out': fiat, + 'amount-out': fiatAmount + } = query + if ( + request.direction !== 'sell' || + blockchain == null || + asset == null || + fiatAmount == null + ) { + return undefined + } + return await fetchDfxSellCryptoAmount({ + blockchain, + asset, + fiat, + fiatAmount + }) +} + export const dfxRampPlugin: RampPluginFactory = config => { const initOptions = asInitOptions(config.initOptions) const support: Omit = { @@ -125,18 +159,26 @@ export const dfxRampPlugin: RampPluginFactory = config => { // Opens DFX with the user's quote choices, logged in with the selected // wallet's address where the chain supports a signature login. The choices - // stay when the login is unavailable or fails. + // stay when the login is unavailable or fails, but DFX does not open when + // it blocks the country of the user's IP address (RampIpCountryError). A + // fiat-entered sell opens with the crypto amount DFX quotes for the fiat, + // when it can quote one. const resolveDeepQuery = async ( request: RampQuoteRequest ): Promise> => { - const sessionQuery = await fetchDfxSessionQuery({ - wallet: request.wallet, - walletName: initOptions.wallet - }) - return { - ...makeDfxRequestQuery(request, initOptions.wallet), - ...sessionQuery + const query = makeDfxRequestQuery(request, initOptions.wallet) + const [sessionQuery, sellCryptoAmount] = await Promise.all([ + fetchDfxSessionQuery({ + wallet: request.wallet, + walletName: initOptions.wallet + }), + fetchFiatSellCryptoAmount(request, query) + ]) + if (sellCryptoAmount != null) { + delete query['amount-out'] + query['amount-in'] = sellCryptoAmount } + return { ...query, ...sessionQuery } } return createExternalRampPlugin( diff --git a/src/plugins/ramps/dfx/dfxRampTypes.ts b/src/plugins/ramps/dfx/dfxRampTypes.ts index 48442ec1ed9..7ac09229f9f 100644 --- a/src/plugins/ramps/dfx/dfxRampTypes.ts +++ b/src/plugins/ramps/dfx/dfxRampTypes.ts @@ -1,4 +1,13 @@ -import { asArray, asJSON, asObject, asOptional, asString } from 'cleaners' +import { + asArray, + asEither, + asJSON, + asNumber, + asObject, + asOptional, + asString, + uncleaner +} from 'cleaners' export interface InitOptions { readonly partnerIcon: string @@ -12,6 +21,16 @@ export const asInitOptions = asObject({ wallet: asOptional(asString, 'Edge') }).withRest +/** + * A failed request's body. DFX answers errors the way NestJS does, + * `{ statusCode, message, error }`, where `message` may be a list. + */ +export const asDfxErrorResponse = asJSON( + asObject({ + message: asEither(asString, asArray(asString)) + }) +) + /** GET /v1/auth/signMessage: the ownership message to sign. */ export const asDfxSignMessageResponse = asJSON( asObject({ @@ -26,3 +45,40 @@ export const asDfxAuthResponse = asJSON( accessToken: asString }) ) + +/** GET /v1/asset: the assets DFX trades, with the ids its quotes take. */ +export const asDfxAssets = asJSON( + asArray( + asObject({ + id: asNumber, + name: asString, + blockchain: asString + }) + ) +) + +/** GET /v1/fiat: the fiat currencies, with the ids its quotes take. */ +export const asDfxFiats = asJSON( + asArray( + asObject({ + id: asNumber, + name: asString + }) + ) +) + +/** PUT /v1/sell/quote: the fiat to receive, by DFX's asset and fiat ids. */ +export const asDfxSellQuoteRequest = asObject({ + asset: asObject({ id: asNumber }), + currency: asObject({ id: asNumber }), + targetAmount: asNumber +}) + +export const wasDfxSellQuoteRequest = uncleaner(asJSON(asDfxSellQuoteRequest)) + +/** PUT /v1/sell/quote: `amount` is the crypto to send for `targetAmount`. */ +export const asDfxSellQuoteResponse = asJSON( + asObject({ + amount: asNumber + }) +) diff --git a/src/plugins/ramps/dfx/dfxSession.ts b/src/plugins/ramps/dfx/dfxSession.ts index 853bfab560e..b7503040896 100644 --- a/src/plugins/ramps/dfx/dfxSession.ts +++ b/src/plugins/ramps/dfx/dfxSession.ts @@ -1,11 +1,11 @@ import type { EdgeCurrencyWallet } from 'edge-core-js' +import { RampIpCountryError } from '../../../types/RampIpCountryError' import { utf8 } from '../../../util/encoding' import { raceTimeout, TIMED_OUT } from '../../../util/raceTimeout' +import { fetchDfx } from './dfxApi' import { asDfxAuthResponse, asDfxSignMessageResponse } from './dfxRampTypes' -const DFX_API_URL = 'https://api.dfx.swiss/v1' - // The quote approval waits for the login, so a slow DFX API must not hold // the user on the quote list. const DFX_LOGIN_TIMEOUT_MS = 10000 @@ -53,7 +53,9 @@ export interface DfxSessionParams { * Signs DFX's ownership message with the wallet and returns the `session` * query parameter that opens DFX logged in with the wallet's address. * Returns undefined when the chain has no session login or any step fails, - * so the caller opens the link without a login. + * so the caller opens the link without a login. Throws RampIpCountryError + * when DFX blocks the country of the user's IP address, since DFX's own + * login would fail the same way. */ export async function fetchDfxSessionQuery( params: DfxSessionParams @@ -71,6 +73,7 @@ export async function fetchDfxSessionQuery( } return query } catch (error: unknown) { + if (error instanceof RampIpCountryError) throw error console.warn( `DFX session login failed, opening plain link: ${String(error)}` ) @@ -85,14 +88,8 @@ async function loginToDfx( const { wallet, walletName } = params const address = await getDfxAddress(wallet) - const signResponse = await fetch( - `${DFX_API_URL}/auth/signMessage?address=${encodeURIComponent(address)}` - ) - if (!signResponse.ok) { - throw new Error(`signMessage returned ${signResponse.status}`) - } const { message, blockchains } = asDfxSignMessageResponse( - await signResponse.text() + await fetchDfx(`/auth/signMessage?address=${encodeURIComponent(address)}`) ) if (!blockchains.includes(chain.blockchain)) { throw new Error(`address not accepted on ${chain.blockchain}`) @@ -110,17 +107,13 @@ async function loginToDfx( otherParams: { publicAddress: address } }) - const authResponse = await fetch(`${DFX_API_URL}/auth`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ address, signature, wallet: walletName }) - }) - if (!authResponse.ok) { - throw new Error( - `auth returned ${authResponse.status}: ${await authResponse.text()}` - ) - } - const { accessToken } = asDfxAuthResponse(await authResponse.text()) + const { accessToken } = asDfxAuthResponse( + await fetchDfx('/auth', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ address, signature, wallet: walletName }) + }) + ) return { session: accessToken } } diff --git a/src/types/RampIpCountryError.ts b/src/types/RampIpCountryError.ts new file mode 100644 index 00000000000..e7ad5d1e1eb --- /dev/null +++ b/src/types/RampIpCountryError.ts @@ -0,0 +1,31 @@ +import { sprintf } from 'sprintf-js' + +import { lstrings } from '../locales/strings' + +/** + * A ramp provider refused the user because of the country of their IP + * address, whatever region they chose in Edge. Opening the provider anyway + * only lands the user on its own login, which fails the same way. + */ +export class RampIpCountryError extends Error { + /** The provider's display name, such as 'DFX' */ + readonly providerName: string + /** The provider's response, for logs */ + readonly serverMessage: string + + constructor(providerName: string, serverMessage: string) { + super( + `${providerName} blocks the country of the IP address: ${serverMessage}` + ) + this.name = 'RampIpCountryError' + this.providerName = providerName + this.serverMessage = serverMessage + } +} + +export function translateRampIpCountryError(error: RampIpCountryError): string { + return sprintf( + lstrings.ramp_provider_ip_country_blocked_1s, + error.providerName + ) +} diff --git a/src/util/fake/fakeFetch.ts b/src/util/fake/fakeFetch.ts new file mode 100644 index 00000000000..3435ea8c9dc --- /dev/null +++ b/src/util/fake/fakeFetch.ts @@ -0,0 +1,40 @@ +/** One request a fake fetch received, with its JSON body parsed. */ +export interface FakeFetchCall { + url: string + method?: string + body?: unknown +} + +/** A fetch Response with the parts API helpers read: ok, status and text. */ +export const makeTextResponse = (status: number, body: unknown): Response => + ({ + ok: status >= 200 && status < 300, + status, + text: async () => JSON.stringify(body) + } as unknown as Response) + +/** + * Replaces the global fetch with `respond`, recording each request in + * `calls`. `restore` puts the real fetch back. + */ +export function installFakeFetch( + respond: (call: FakeFetchCall) => Response | Promise +): { calls: FakeFetchCall[]; restore: () => void } { + const realFetch = global.fetch + const calls: FakeFetchCall[] = [] + global.fetch = (async (input: unknown, init?: RequestInit) => { + const call: FakeFetchCall = { + url: String(input), + method: init?.method, + body: init?.body == null ? undefined : JSON.parse(init.body as string) + } + calls.push(call) + return await respond(call) + }) as typeof fetch + return { + calls, + restore: () => { + global.fetch = realFetch + } + } +} diff --git a/src/util/translateError.ts b/src/util/translateError.ts index 31bc964fd43..d858f719c06 100644 --- a/src/util/translateError.ts +++ b/src/util/translateError.ts @@ -5,6 +5,10 @@ import { PaymentProtoError, translatePaymentProtoError } from '../types/PaymentProtoError' +import { + RampIpCountryError, + translateRampIpCountryError +} from '../types/RampIpCountryError' import { ResolutionError, translateResolutionError @@ -51,6 +55,9 @@ export function translateError(error: unknown): string { if (error instanceof PaymentProtoError) return translatePaymentProtoError(error) if (error instanceof ResolutionError) return translateResolutionError(error) + if (error instanceof RampIpCountryError) { + return translateRampIpCountryError(error) + } return asErrorMessage(error) }